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
adde88/Nerdpack-Zylla
rotations/paladin/protection.lua
1
8873
local _, Zylla = ... local unpack = _G.unpack local NeP = _G.NeP local Mythic_Plus = _G.Zylla.Mythic_Plus local GUI = { unpack(Zylla.Logo_GUI), -- Header {type = 'header', size = 16, text = 'Keybinds', align = 'center'}, {type = 'checkbox', text = 'Left Shift: '..Zylla.ClassColor..'Pause|r', align = 'left', key = 'lshift', default = true}, {type = 'checkbox', text = 'Left Ctrl: '..Zylla.ClassColor..'|r', align = 'left', key = 'lcontrol', default = true}, {type = 'checkbox', text = 'Left Alt: '..Zylla.ClassColor..'|r', align = 'left', key = 'lalt', default = true}, {type = 'checkbox', text = 'Right Alt: '..Zylla.ClassColor..'|r', align = 'left', key = 'ralt', default = true}, {type = 'spacer'}, {type = 'checkbox', text = 'Enable Chatoverlay', key = 'chat', width = 55, default = true, desc = Zylla.ClassColor..'This will enable some messages as an overlay!|r'}, unpack(Zylla.PayPal_GUI), {type = 'spacer'}, unpack(Zylla.PayPal_IMG), {type = 'spacer'}, {type = 'ruler'}, {type = 'spacer'}, --TODO: Targetting: Use, or NOT use?! We'll see.... {type = 'header', size = 16, text = 'Targetting:', align = 'center'}, {type = 'combo', default = 'target', key = 'target', list = Zylla.faketarget, width = 75}, {type = 'spacer'}, {type = 'text', text = Zylla.ClassColor..'Only one can be enabled.\nChose between normal targetting, or hitting the highest/lowest enemy.|r'}, {type = 'spacer'}, {type = 'ruler'}, {type = 'spacer'}, -- Settings {type = 'header', size = 16, text = 'Class Settings', align = 'center'}, {type = 'spinner', size = 11, text = 'Interrupt at percentage:', key = 'intat', default = 60, step = 5, shiftStep = 10, max = 100, min = 1}, {type = 'checkbox', text = 'Enable DBM Integration', key = 'kDBM', default = true}, {type = 'checkbox', text = 'Enable \'pre-potting\', flasks and Legion-rune', key = 'prepot', default = false}, {type = 'combo', default = '3', key = 'list', list = Zylla.prepots, width = 175}, {type = 'spacer'}, {type = 'spacer'}, {type = 'checkspin',text = 'Light\'s Judgment - Units', key = 'LJ', spin = 4, step = 1, max = 20, min = 1, check = true, desc = Zylla.ClassColor..'World Spell usable on Argus.|r'}, {type = 'checkbox', text = 'Use Trinket #1', key = 'trinket1', default = false}, {type = 'checkbox', text = 'Use Trinket #2', key = 'trinket2', default = false, desc = Zylla.ClassColor..'Trinkets will be used whenever possible!|r'}, {type = 'spacer'}, {type = 'checkspin',text = 'Kil\'Jaeden\'s Burning Wish - Units', key = 'kj', align = 'left', width = 55, step = 1, shiftStep = 2, spin = 4, max = 20, min = 1, check = true, desc = Zylla.ClassColor..'Legendary will be used only on selected amount of units!|r'}, {type = 'ruler'}, {type = 'spacer'}, -- Survival {type='spacer'}, {type='rule'}, {type = 'header', size = 16, text = 'Survival', align = 'center'}, {type = 'checkspin',text = 'Flash of Light', key = 'fol', align = 'left', width = 55, step = 5, shiftStep = 10, spin = 75, max = 100, min = 1, check = true}, {type = 'checkspin',text = 'Light of the Protector', key = 'lotp', align = 'left', width = 55, step = 5, shiftStep = 10, spin = 75, max = 100, min = 1, check = true}, unpack(Zylla.Mythic_GUI), } local exeOnLoad = function() Zylla.ExeOnLoad() Zylla.AFKCheck() print('|cffADFF2F ----------------------------------------------------------------------|r') print('|cffADFF2F --- |rPALADIN |cffADFF2FProtection |r') print('|cffADFF2F --- |rRecommended Talents: 1/2 - 2/2 - 3/3 - 4/1 - 5/2 - 6/2 - 7/3') print('|cffADFF2F ----------------------------------------------------------------------|r') NeP.Interface:AddToggle({ key = 'AutoTaunt', name = 'Auto Taunt', text = 'Automatically taunt nearby enemies.', icon = 'Interface\\Icons\\spell_nature_shamanrage.png', }) NeP.Interface:AddToggle({ key = 'xIntRandom', name = 'Interrupt Anyone', text = 'Interrupt all nearby enemies, without targeting them.', icon = 'Interface\\Icons\\inv_ammo_arrow_04', }) end local PreCombat ={ -- Pots {'#127844', 'UI(list)==1&item(127844).usable&item(127844).count>0&UI(kDBM)&UI(prepot)&!buff(Potion of the Old War)&dbm(pull in)<3'}, --XXX: Potion of the Old War {'#127843', 'UI(list)==2&item(127843).usable&item(127843).count>0&UI(kDBM)&UI(prepot)&!buff(Potion of Deadly Grace)&dbm(pull in)<3'}, --XXX: Potion of Deadly Grace {'#142117', 'UI(list)==3&item(142117).usable&item(142117).count>0&UI(kDBM)&UI(prepot)&!buff(Potion of Prolonged Power)&dbm(pull in)<3'}, --XXX: Potion of Prolonged Power -- Flasks {'#127850', 'item(127850).usable&item(127850).count>0&UI(prepot)&!buff(Flask of Ten Thousand Scars)'}, --XXX: Flask of Ten Thousand Scars {'#153023', 'item(153023).usable&item(153023).count>0&UI(prepot)&!buff(Defiled Augmentation)'}, --XXX: Lightforged Augment Rune } local Keybinds = { {'%pause', 'keybind(lshift)&UI(lshift)'}, {'Divine Steed', 'keybind(lcontrol)&UI(lcontrol)', 'player'} } local Interrupts = { {'!Rebuke'}, {'!Hammer of Justice', 'cooldown(Rebuke).remains>=gcd'}, {'!Arcane Torrent', 'inMelee&spell(Rebuke).cooldown>=gcd&!player.lastgcd(Rebuke)'}, } local Survival ={ {'Flash of Light', 'health<=UI(fol_check)&lastmoved>0&UI(fol_spin)'}, {'Light of the Protector', 'UI(lotp_check)&health<UI(lotp_spin)&buff(Consecration)'}, } local EyeofTyr = { {'Divine Steed', 'talent(5,2)'}, {'Eye of Tyr'}, {'Aegis of Light', 'talent(6,1)'}, {'Guardian of Ancient Kings'}, {'Divine Shield'}, {'Ardent Defender'}, } local Cooldowns = { {'Seraphim', 'spell(Shield of the Righteous).charges>1', 'player'}, {'Shield of the Righteous', 'inMelee&inFront&{!talent(7,2)||spell(Shield of the Righteous).charges>=3}&!{player.buff(Eye of Tyr)&player.buff(Aegis of Light)&player.buff(Ardent Defender)&player.buff(Guardian of Ancient Kings)&player.buff(Divine Shield)}', 'target'}, {'Bastion of Light', 'talent(2,2)&spell(Shield of the Righteous).charges<1', 'player'}, {'Light of the Protector', 'health<40', 'player'}, {'Hand of the Protector', 'talent(5,1)&health<40', 'player'}, {'Light of the Protector', '{incdmg(10)>health.max*1.25}&health<55&talent(7,1)', 'player'}, {'Light of the Protector', '{incdmg(13)>health.max*1.6}&health<55', 'player'}, {'Hand of the Protector', 'talent(5,1)&{incdmg(6)>health.max*0.7}&health<55&talent(7,1)', 'player'}, {'Hand of the Protector', 'talent(5,1)&{incdmg(9)>health.max*1.2}&health<55', 'player'}, {EyeofTyr, 'player.incdmg(2.5)>player.health.max*0.40&!{player.buff(Eye of Tyr)||player.buff(Aegis of Light)||player.buff(Ardent Defender)||player.buff(Guardian of Ancient Kings)||player.buff(Divine Shield)}'}, {'Lay on Hands', 'health<15', 'player'}, {'Avenging Wrath', '!talent(7,2)||talent(7,2)&buff(Seraphim)', 'player'}, {'#trinket1', 'UI(trinket1)'}, {'#trinket2', 'UI(trinket2)'}, {'Light\'s Judgment', 'advanced&UI(LJ_check)&range<61&area(15).enemies>=UI(LJ_spin)', 'enemies.ground'}, {'&#144259', 'UI(kj_check)&range<=40&area(10).enemies>=UI(kj_spin)&equipped(144259)'}, --XXX: Kil'jaeden's Burning Wish (Legendary) } local AoE = { {'Avenger\'s Shield'}, {'Blessed Hammer'}, {'Judgment'}, {'Consecration'}, {'Hammer of the Righteous', '!talent(1,2)'}, } local ST = { {'Judgment'}, {'Blessed Hammer'}, {'Avenger\'s Shield'}, {'Consecration'}, {'Blinding Light'}, {'Hammer of the Righteous', '!talent(1,2)'}, } local xCombat = { {Interrupts, 'toggle(interrupts)&@Zylla.InterruptAt(intat)'}, {Interrupts, 'toggle(interrupts)&toggle(xIntRandom)&@Zylla.InterruptAt(intat)', 'enemies'}, {Cooldowns, 'toggle(Cooldowns)'}, {AoE, 'toggle(AoE)&player.area(8).enemies>=3'}, {ST, 'inFront&inMelee'} } local inCombat = { {Keybinds}, {Survival, nil, 'player'}, {'%taunt(Hand of Reckoning)', 'toggle(aoe)'}, {'Shield of the Righteous', '!player.buff&{player.health<60||spell.count>1}', 'target'}, {xCombat, 'combat&alive&inMelee&inFront', (function() return NeP.DSL:Get("UI")(nil, 'target') end)}, --TODO: TEST! ALOT MORE TESTING! {Mythic_Plus, 'inMelee'}, } local outCombat = { {Keybinds}, {PreCombat, nil, 'player'} } NeP.CR:Add(66, { name = '[|cff'..Zylla.addonColor..'Zylla\'s|r] Paladin - Protection', ic = inCombat, ooc = outCombat, gui = GUI, gui_st = Zylla.GuiSettings, ids = Zylla.SpellIDs[Zylla.Class], wow_ver = Zylla.wow_ver, nep_ver = Zylla.nep_ver, load = exeOnLoad })
mit
Lleafll/sws-lleaf
libs/AceConfig-3.0/AceConfigDialog-3.0/AceConfigDialog-3.0.lua
15
56930
--- AceConfigDialog-3.0 generates AceGUI-3.0 based windows based on option tables. -- @class file -- @name AceConfigDialog-3.0 -- @release $Id: AceConfigDialog-3.0.lua 1126 2014-11-10 06:38:01Z nevcairiel $ local LibStub = LibStub local MAJOR, MINOR = "AceConfigDialog-3.0", 60 local AceConfigDialog, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceConfigDialog then return end AceConfigDialog.OpenFrames = AceConfigDialog.OpenFrames or {} AceConfigDialog.Status = AceConfigDialog.Status or {} AceConfigDialog.frame = AceConfigDialog.frame or CreateFrame("Frame") AceConfigDialog.frame.apps = AceConfigDialog.frame.apps or {} AceConfigDialog.frame.closing = AceConfigDialog.frame.closing or {} AceConfigDialog.frame.closeAllOverride = AceConfigDialog.frame.closeAllOverride or {} local gui = LibStub("AceGUI-3.0") local reg = LibStub("AceConfigRegistry-3.0") -- Lua APIs local tconcat, tinsert, tsort, tremove, tsort = table.concat, table.insert, table.sort, table.remove, table.sort local strmatch, format = string.match, string.format local assert, loadstring, error = assert, loadstring, error local pairs, next, select, type, unpack, wipe, ipairs = pairs, next, select, type, unpack, wipe, ipairs local rawset, tostring, tonumber = rawset, tostring, tonumber local math_min, math_max, math_floor = math.min, math.max, math.floor -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: NORMAL_FONT_COLOR, GameTooltip, StaticPopupDialogs, ACCEPT, CANCEL, StaticPopup_Show -- GLOBALS: PlaySound, GameFontHighlight, GameFontHighlightSmall, GameFontHighlightLarge -- GLOBALS: CloseSpecialWindows, InterfaceOptions_AddCategory, geterrorhandler local emptyTbl = {} --[[ xpcall safecall implementation ]] local xpcall = xpcall local function errorhandler(err) return geterrorhandler()(err) end 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, errorhandler) 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, errorhandler) end local function safecall(func, ...) return Dispatchers[select("#", ...)](func, ...) end local width_multiplier = 170 --[[ Group Types Tree - All Descendant Groups will all become nodes on the tree, direct child options will appear above the tree - Descendant Groups with inline=true and thier children will not become nodes Tab - Direct Child Groups will become tabs, direct child options will appear above the tab control - Grandchild groups will default to inline unless specified otherwise Select- Same as Tab but with entries in a dropdown rather than tabs Inline Groups - Will not become nodes of a select group, they will be effectivly part of thier parent group seperated by a border - If declared on a direct child of a root node of a select group, they will appear above the group container control - When a group is displayed inline, all descendants will also be inline members of the group ]] -- Recycling functions local new, del, copy --newcount, delcount,createdcount,cached = 0,0,0 do local pool = setmetatable({},{__mode="k"}) function new() --newcount = newcount + 1 local t = next(pool) if t then pool[t] = nil return t else --createdcount = createdcount + 1 return {} end end function copy(t) local c = new() for k, v in pairs(t) do c[k] = v end return c end function del(t) --delcount = delcount + 1 wipe(t) pool[t] = true end -- function cached() -- local n = 0 -- for k in pairs(pool) do -- n = n + 1 -- end -- return n -- end end -- picks the first non-nil value and returns it local function pickfirstset(...) for i=1,select("#",...) do if select(i,...)~=nil then return select(i,...) end end end --gets an option from a given group, checking plugins local function GetSubOption(group, key) if group.plugins then for plugin, t in pairs(group.plugins) do if t[key] then return t[key] end end end return group.args[key] end --Option member type definitions, used to decide how to access it --Is the member Inherited from parent options local isInherited = { set = true, get = true, func = true, confirm = true, validate = true, disabled = true, hidden = true } --Does a string type mean a literal value, instead of the default of a method of the handler local stringIsLiteral = { name = true, desc = true, icon = true, usage = true, width = true, image = true, fontSize = true, } --Is Never a function or method local allIsLiteral = { type = true, descStyle = true, imageWidth = true, imageHeight = true, } --gets the value for a member that could be a function --function refs are called with an info arg --every other type is returned local function GetOptionsMemberValue(membername, option, options, path, appName, ...) --get definition for the member local inherits = isInherited[membername] --get the member of the option, traversing the tree if it can be inherited local member if inherits then local group = options if group[membername] ~= nil then member = group[membername] end for i = 1, #path do group = GetSubOption(group, path[i]) if group[membername] ~= nil then member = group[membername] end end else member = option[membername] end --check if we need to call a functon, or if we have a literal value if ( not allIsLiteral[membername] ) and ( type(member) == "function" or ((not stringIsLiteral[membername]) and type(member) == "string") ) then --We have a function to call local info = new() --traverse the options table, picking up the handler and filling the info with the path local handler local group = options handler = group.handler or handler for i = 1, #path do group = GetSubOption(group, path[i]) info[i] = path[i] handler = group.handler or handler end info.options = options info.appName = appName info[0] = appName info.arg = option.arg info.handler = handler info.option = option info.type = option.type info.uiType = "dialog" info.uiName = MAJOR local a, b, c ,d --using 4 returns for the get of a color type, increase if a type needs more if type(member) == "function" then --Call the function a,b,c,d = member(info, ...) else --Call the method if handler and handler[member] then a,b,c,d = handler[member](handler, info, ...) else error(format("Method %s doesn't exist in handler for type %s", member, membername)) end end del(info) return a,b,c,d else --The value isnt a function to call, return it return member end end --[[calls an options function that could be inherited, method name or function ref local function CallOptionsFunction(funcname ,option, options, path, appName, ...) local info = new() local func local group = options local handler --build the info table containing the path -- pick up functions while traversing the tree if group[funcname] ~= nil then func = group[funcname] end handler = group.handler or handler for i, v in ipairs(path) do group = GetSubOption(group, v) info[i] = v if group[funcname] ~= nil then func = group[funcname] end handler = group.handler or handler end info.options = options info[0] = appName info.arg = option.arg local a, b, c ,d if type(func) == "string" then if handler and handler[func] then a,b,c,d = handler[func](handler, info, ...) else error(string.format("Method %s doesn't exist in handler for type func", func)) end elseif type(func) == "function" then a,b,c,d = func(info, ...) end del(info) return a,b,c,d end --]] --tables to hold orders and names for options being sorted, will be created with new() --prevents needing to call functions repeatedly while sorting local tempOrders local tempNames local function compareOptions(a,b) if not a then return true end if not b then return false end local OrderA, OrderB = tempOrders[a] or 100, tempOrders[b] or 100 if OrderA == OrderB then local NameA = (type(tempNames[a]) == "string") and tempNames[a] or "" local NameB = (type(tempNames[b]) == "string") and tempNames[b] or "" return NameA:upper() < NameB:upper() end if OrderA < 0 then if OrderB > 0 then return false end else if OrderB < 0 then return true end end return OrderA < OrderB end --builds 2 tables out of an options group -- keySort, sorted keys -- opts, combined options from .plugins and args local function BuildSortedOptionsTable(group, keySort, opts, options, path, appName) tempOrders = new() tempNames = new() if group.plugins then for plugin, t in pairs(group.plugins) do for k, v in pairs(t) do if not opts[k] then tinsert(keySort, k) opts[k] = v path[#path+1] = k tempOrders[k] = GetOptionsMemberValue("order", v, options, path, appName) tempNames[k] = GetOptionsMemberValue("name", v, options, path, appName) path[#path] = nil end end end end for k, v in pairs(group.args) do if not opts[k] then tinsert(keySort, k) opts[k] = v path[#path+1] = k tempOrders[k] = GetOptionsMemberValue("order", v, options, path, appName) tempNames[k] = GetOptionsMemberValue("name", v, options, path, appName) path[#path] = nil end end tsort(keySort, compareOptions) del(tempOrders) del(tempNames) end local function DelTree(tree) if tree.children then local childs = tree.children for i = 1, #childs do DelTree(childs[i]) del(childs[i]) end del(childs) end end local function CleanUserData(widget, event) local user = widget:GetUserDataTable() if user.path then del(user.path) end if widget.type == "TreeGroup" then local tree = user.tree widget:SetTree(nil) if tree then for i = 1, #tree do DelTree(tree[i]) del(tree[i]) end del(tree) end end if widget.type == "TabGroup" then widget:SetTabs(nil) if user.tablist then del(user.tablist) end end if widget.type == "DropdownGroup" then widget:SetGroupList(nil) if user.grouplist then del(user.grouplist) end if user.orderlist then del(user.orderlist) end end end -- - Gets a status table for the given appname and options path. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param path The path to the options (a table with all group keys) -- @return function AceConfigDialog:GetStatusTable(appName, path) local status = self.Status if not status[appName] then status[appName] = {} status[appName].status = {} status[appName].children = {} end status = status[appName] if path then for i = 1, #path do local v = path[i] if not status.children[v] then status.children[v] = {} status.children[v].status = {} status.children[v].children = {} end status = status.children[v] end end return status.status end --- Selects the specified path in the options window. -- The path specified has to match the keys of the groups in the table. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param ... The path to the key that should be selected function AceConfigDialog:SelectGroup(appName, ...) local path = new() local app = reg:GetOptionsTable(appName) if not app then error(("%s isn't registed with AceConfigRegistry, unable to open config"):format(appName), 2) end local options = app("dialog", MAJOR) local group = options local status = self:GetStatusTable(appName, path) if not status.groups then status.groups = {} end status = status.groups local treevalue local treestatus for n = 1, select("#",...) do local key = select(n, ...) if group.childGroups == "tab" or group.childGroups == "select" then --if this is a tab or select group, select the group status.selected = key --children of this group are no longer extra levels of a tree treevalue = nil else --tree group by default if treevalue then --this is an extra level of a tree group, build a uniquevalue for it treevalue = treevalue.."\001"..key else --this is the top level of a tree group, the uniquevalue is the same as the key treevalue = key if not status.groups then status.groups = {} end --save this trees status table for any extra levels or groups treestatus = status end --make sure that the tree entry is open, and select it. --the selected group will be overwritten if a child is the final target but still needs to be open treestatus.selected = treevalue treestatus.groups[treevalue] = true end --move to the next group in the path group = GetSubOption(group, key) if not group then break end tinsert(path, key) status = self:GetStatusTable(appName, path) if not status.groups then status.groups = {} end status = status.groups end del(path) reg:NotifyChange(appName) end local function OptionOnMouseOver(widget, event) --show a tooltip/set the status bar to the desc text local user = widget:GetUserDataTable() local opt = user.option local options = user.options local path = user.path local appName = user.appName GameTooltip:SetOwner(widget.frame, "ANCHOR_TOPRIGHT") local name = GetOptionsMemberValue("name", opt, options, path, appName) local desc = GetOptionsMemberValue("desc", opt, options, path, appName) local usage = GetOptionsMemberValue("usage", opt, options, path, appName) local descStyle = opt.descStyle if descStyle and descStyle ~= "tooltip" then return end GameTooltip:SetText(name, 1, .82, 0, true) if opt.type == "multiselect" then GameTooltip:AddLine(user.text, 0.5, 0.5, 0.8, true) end if type(desc) == "string" then GameTooltip:AddLine(desc, 1, 1, 1, true) end if type(usage) == "string" then GameTooltip:AddLine("Usage: "..usage, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, true) end GameTooltip:Show() end local function OptionOnMouseLeave(widget, event) GameTooltip:Hide() end local function GetFuncName(option) local type = option.type if type == "execute" then return "func" else return "set" end end local function confirmPopup(appName, rootframe, basepath, info, message, func, ...) if not StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] then StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] = {} end local t = StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] for k in pairs(t) do t[k] = nil end t.text = message t.button1 = ACCEPT t.button2 = CANCEL t.preferredIndex = STATICPOPUP_NUMDIALOGS local dialog, oldstrata t.OnAccept = function() safecall(func, unpack(t)) if dialog and oldstrata then dialog:SetFrameStrata(oldstrata) end AceConfigDialog:Open(appName, rootframe, unpack(basepath or emptyTbl)) del(info) end t.OnCancel = function() if dialog and oldstrata then dialog:SetFrameStrata(oldstrata) end AceConfigDialog:Open(appName, rootframe, unpack(basepath or emptyTbl)) del(info) end for i = 1, select("#", ...) do t[i] = select(i, ...) or false end t.timeout = 0 t.whileDead = 1 t.hideOnEscape = 1 dialog = StaticPopup_Show("ACECONFIGDIALOG30_CONFIRM_DIALOG") if dialog then oldstrata = dialog:GetFrameStrata() dialog:SetFrameStrata("TOOLTIP") end end local function ActivateControl(widget, event, ...) --This function will call the set / execute handler for the widget --widget:GetUserDataTable() contains the needed info local user = widget:GetUserDataTable() local option = user.option local options = user.options local path = user.path local info = new() local func local group = options local funcname = GetFuncName(option) local handler local confirm local validate --build the info table containing the path -- pick up functions while traversing the tree if group[funcname] ~= nil then func = group[funcname] end handler = group.handler or handler confirm = group.confirm validate = group.validate for i = 1, #path do local v = path[i] group = GetSubOption(group, v) info[i] = v if group[funcname] ~= nil then func = group[funcname] end handler = group.handler or handler if group.confirm ~= nil then confirm = group.confirm end if group.validate ~= nil then validate = group.validate end end info.options = options info.appName = user.appName info.arg = option.arg info.handler = handler info.option = option info.type = option.type info.uiType = "dialog" info.uiName = MAJOR local name if type(option.name) == "function" then name = option.name(info) elseif type(option.name) == "string" then name = option.name else name = "" end local usage = option.usage local pattern = option.pattern local validated = true if option.type == "input" then if type(pattern)=="string" then if not strmatch(..., pattern) then validated = false end end end local success if validated and option.type ~= "execute" then if type(validate) == "string" then if handler and handler[validate] then success, validated = safecall(handler[validate], handler, info, ...) if not success then validated = false end else error(format("Method %s doesn't exist in handler for type execute", validate)) end elseif type(validate) == "function" then success, validated = safecall(validate, info, ...) if not success then validated = false end end end local rootframe = user.rootframe if type(validated) == "string" then --validate function returned a message to display if rootframe.SetStatusText then rootframe:SetStatusText(validated) else -- TODO: do something else. end PlaySound("igPlayerInviteDecline") del(info) return true elseif not validated then --validate returned false if rootframe.SetStatusText then if usage then rootframe:SetStatusText(name..": "..usage) else if pattern then rootframe:SetStatusText(name..": Expected "..pattern) else rootframe:SetStatusText(name..": Invalid Value") end end else -- TODO: do something else end PlaySound("igPlayerInviteDecline") del(info) return true else local confirmText = option.confirmText --call confirm func/method if type(confirm) == "string" then if handler and handler[confirm] then success, confirm = safecall(handler[confirm], handler, info, ...) if success and type(confirm) == "string" then confirmText = confirm confirm = true elseif not success then confirm = false end else error(format("Method %s doesn't exist in handler for type confirm", confirm)) end elseif type(confirm) == "function" then success, confirm = safecall(confirm, info, ...) if success and type(confirm) == "string" then confirmText = confirm confirm = true elseif not success then confirm = false end end --confirm if needed if type(confirm) == "boolean" then if confirm then if not confirmText then local name, desc = option.name, option.desc if type(name) == "function" then name = name(info) end if type(desc) == "function" then desc = desc(info) end confirmText = name if desc then confirmText = confirmText.." - "..desc end end local iscustom = user.rootframe:GetUserData("iscustom") local rootframe if iscustom then rootframe = user.rootframe end local basepath = user.rootframe:GetUserData("basepath") if type(func) == "string" then if handler and handler[func] then confirmPopup(user.appName, rootframe, basepath, info, confirmText, handler[func], handler, info, ...) else error(format("Method %s doesn't exist in handler for type func", func)) end elseif type(func) == "function" then confirmPopup(user.appName, rootframe, basepath, info, confirmText, func, info, ...) end --func will be called and info deleted when the confirm dialog is responded to return end end --call the function if type(func) == "string" then if handler and handler[func] then safecall(handler[func],handler, info, ...) else error(format("Method %s doesn't exist in handler for type func", func)) end elseif type(func) == "function" then safecall(func,info, ...) end local iscustom = user.rootframe:GetUserData("iscustom") local basepath = user.rootframe:GetUserData("basepath") or emptyTbl --full refresh of the frame, some controls dont cause this on all events if option.type == "color" then if event == "OnValueConfirmed" then if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end elseif option.type == "range" then if event == "OnMouseUp" then if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end --multiselects don't cause a refresh on 'OnValueChanged' only 'OnClosed' elseif option.type == "multiselect" then user.valuechanged = true else if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end end del(info) end local function ActivateSlider(widget, event, value) local option = widget:GetUserData("option") local min, max, step = option.min or (not option.softMin and 0 or nil), option.max or (not option.softMax and 100 or nil), option.step if min then if step then value = math_floor((value - min) / step + 0.5) * step + min end value = math_max(value, min) end if max then value = math_min(value, max) end ActivateControl(widget,event,value) end --called from a checkbox that is part of an internally created multiselect group --this type is safe to refresh on activation of one control local function ActivateMultiControl(widget, event, ...) ActivateControl(widget, event, widget:GetUserData("value"), ...) local user = widget:GetUserDataTable() local iscustom = user.rootframe:GetUserData("iscustom") local basepath = user.rootframe:GetUserData("basepath") or emptyTbl if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end local function MultiControlOnClosed(widget, event, ...) local user = widget:GetUserDataTable() if user.valuechanged then local iscustom = user.rootframe:GetUserData("iscustom") local basepath = user.rootframe:GetUserData("basepath") or emptyTbl if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end end local function FrameOnClose(widget, event) local appName = widget:GetUserData("appName") AceConfigDialog.OpenFrames[appName] = nil gui:Release(widget) end local function CheckOptionHidden(option, options, path, appName) --check for a specific boolean option local hidden = pickfirstset(option.dialogHidden,option.guiHidden) if hidden ~= nil then return hidden end return GetOptionsMemberValue("hidden", option, options, path, appName) end local function CheckOptionDisabled(option, options, path, appName) --check for a specific boolean option local disabled = pickfirstset(option.dialogDisabled,option.guiDisabled) if disabled ~= nil then return disabled end return GetOptionsMemberValue("disabled", option, options, path, appName) end --[[ local function BuildTabs(group, options, path, appName) local tabs = new() local text = new() local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] if v.type == "group" then path[#path+1] = k local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) local hidden = CheckOptionHidden(v, options, path, appName) if not inline and not hidden then tinsert(tabs, k) text[k] = GetOptionsMemberValue("name", v, options, path, appName) end path[#path] = nil end end del(keySort) del(opts) return tabs, text end ]] local function BuildSelect(group, options, path, appName) local groups = new() local order = new() local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] if v.type == "group" then path[#path+1] = k local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) local hidden = CheckOptionHidden(v, options, path, appName) if not inline and not hidden then groups[k] = GetOptionsMemberValue("name", v, options, path, appName) tinsert(order, k) end path[#path] = nil end end del(opts) del(keySort) return groups, order end local function BuildSubGroups(group, tree, options, path, appName) local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] if v.type == "group" then path[#path+1] = k local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) local hidden = CheckOptionHidden(v, options, path, appName) if not inline and not hidden then local entry = new() entry.value = k entry.text = GetOptionsMemberValue("name", v, options, path, appName) entry.icon = GetOptionsMemberValue("icon", v, options, path, appName) entry.iconCoords = GetOptionsMemberValue("iconCoords", v, options, path, appName) entry.disabled = CheckOptionDisabled(v, options, path, appName) if not tree.children then tree.children = new() end tinsert(tree.children,entry) if (v.childGroups or "tree") == "tree" then BuildSubGroups(v,entry, options, path, appName) end end path[#path] = nil end end del(keySort) del(opts) end local function BuildGroups(group, options, path, appName, recurse) local tree = new() local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] if v.type == "group" then path[#path+1] = k local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) local hidden = CheckOptionHidden(v, options, path, appName) if not inline and not hidden then local entry = new() entry.value = k entry.text = GetOptionsMemberValue("name", v, options, path, appName) entry.icon = GetOptionsMemberValue("icon", v, options, path, appName) entry.disabled = CheckOptionDisabled(v, options, path, appName) tinsert(tree,entry) if recurse and (v.childGroups or "tree") == "tree" then BuildSubGroups(v,entry, options, path, appName) end end path[#path] = nil end end del(keySort) del(opts) return tree end local function InjectInfo(control, options, option, path, rootframe, appName) local user = control:GetUserDataTable() for i = 1, #path do user[i] = path[i] end user.rootframe = rootframe user.option = option user.options = options user.path = copy(path) user.appName = appName control:SetCallback("OnRelease", CleanUserData) control:SetCallback("OnLeave", OptionOnMouseLeave) control:SetCallback("OnEnter", OptionOnMouseOver) end --[[ options - root of the options table being fed container - widget that controls will be placed in rootframe - Frame object the options are in path - table with the keys to get to the group being fed --]] local function FeedOptions(appName, options,container,rootframe,path,group,inline) local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] tinsert(path, k) local hidden = CheckOptionHidden(v, options, path, appName) local name = GetOptionsMemberValue("name", v, options, path, appName) if not hidden then if v.type == "group" then if inline or pickfirstset(v.dialogInline,v.guiInline,v.inline, false) then --Inline group local GroupContainer if name and name ~= "" then GroupContainer = gui:Create("InlineGroup") GroupContainer:SetTitle(name or "") else GroupContainer = gui:Create("SimpleGroup") end GroupContainer.width = "fill" GroupContainer:SetLayout("flow") container:AddChild(GroupContainer) FeedOptions(appName,options,GroupContainer,rootframe,path,v,true) end else --Control to feed local control local name = GetOptionsMemberValue("name", v, options, path, appName) if v.type == "execute" then local imageCoords = GetOptionsMemberValue("imageCoords",v, options, path, appName) local image, width, height = GetOptionsMemberValue("image",v, options, path, appName) if type(image) == "string" then control = gui:Create("Icon") if not width then width = GetOptionsMemberValue("imageWidth",v, options, path, appName) end if not height then height = GetOptionsMemberValue("imageHeight",v, options, path, appName) end if type(imageCoords) == "table" then control:SetImage(image, unpack(imageCoords)) else control:SetImage(image) end if type(width) ~= "number" then width = 32 end if type(height) ~= "number" then height = 32 end control:SetImageSize(width, height) control:SetLabel(name) else control = gui:Create("Button") control:SetText(name) end control:SetCallback("OnClick",ActivateControl) elseif v.type == "input" then local controlType = v.dialogControl or v.control or (v.multiline and "MultiLineEditBox") or "EditBox" control = gui:Create(controlType) if not control then geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType))) control = gui:Create(v.multiline and "MultiLineEditBox" or "EditBox") end if v.multiline and control.SetNumLines then control:SetNumLines(tonumber(v.multiline) or 4) end control:SetLabel(name) control:SetCallback("OnEnterPressed",ActivateControl) local text = GetOptionsMemberValue("get",v, options, path, appName) if type(text) ~= "string" then text = "" end control:SetText(text) elseif v.type == "toggle" then control = gui:Create("CheckBox") control:SetLabel(name) control:SetTriState(v.tristate) local value = GetOptionsMemberValue("get",v, options, path, appName) control:SetValue(value) control:SetCallback("OnValueChanged",ActivateControl) if v.descStyle == "inline" then local desc = GetOptionsMemberValue("desc", v, options, path, appName) control:SetDescription(desc) end local image = GetOptionsMemberValue("image", v, options, path, appName) local imageCoords = GetOptionsMemberValue("imageCoords", v, options, path, appName) if type(image) == "string" then if type(imageCoords) == "table" then control:SetImage(image, unpack(imageCoords)) else control:SetImage(image) end end elseif v.type == "range" then control = gui:Create("Slider") control:SetLabel(name) control:SetSliderValues(v.softMin or v.min or 0, v.softMax or v.max or 100, v.bigStep or v.step or 0) control:SetIsPercent(v.isPercent) local value = GetOptionsMemberValue("get",v, options, path, appName) if type(value) ~= "number" then value = 0 end control:SetValue(value) control:SetCallback("OnValueChanged",ActivateSlider) control:SetCallback("OnMouseUp",ActivateSlider) elseif v.type == "select" then local values = GetOptionsMemberValue("values", v, options, path, appName) if v.style == "radio" then local disabled = CheckOptionDisabled(v, options, path, appName) local width = GetOptionsMemberValue("width",v,options,path,appName) control = gui:Create("InlineGroup") control:SetLayout("Flow") control:SetTitle(name) control.width = "fill" control:PauseLayout() local optionValue = GetOptionsMemberValue("get",v, options, path, appName) local t = {} for value, text in pairs(values) do t[#t+1]=value end tsort(t) for k, value in ipairs(t) do local text = values[value] local radio = gui:Create("CheckBox") radio:SetLabel(text) radio:SetUserData("value", value) radio:SetUserData("text", text) radio:SetDisabled(disabled) radio:SetType("radio") radio:SetValue(optionValue == value) radio:SetCallback("OnValueChanged", ActivateMultiControl) InjectInfo(radio, options, v, path, rootframe, appName) control:AddChild(radio) if width == "double" then radio:SetWidth(width_multiplier * 2) elseif width == "half" then radio:SetWidth(width_multiplier / 2) elseif width == "full" then radio.width = "fill" else radio:SetWidth(width_multiplier) end end control:ResumeLayout() control:DoLayout() else local controlType = v.dialogControl or v.control or "Dropdown" control = gui:Create(controlType) if not control then geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType))) control = gui:Create("Dropdown") end local itemType = v.itemControl if itemType and not gui:GetWidgetVersion(itemType) then geterrorhandler()(("Invalid Custom Item Type - %s"):format(tostring(itemType))) itemType = nil end control:SetLabel(name) control:SetList(values, nil, itemType) local value = GetOptionsMemberValue("get",v, options, path, appName) if not values[value] then value = nil end control:SetValue(value) control:SetCallback("OnValueChanged", ActivateControl) end elseif v.type == "multiselect" then local values = GetOptionsMemberValue("values", v, options, path, appName) local disabled = CheckOptionDisabled(v, options, path, appName) local controlType = v.dialogControl or v.control local valuesort = new() if values then for value, text in pairs(values) do tinsert(valuesort, value) end end tsort(valuesort) if controlType then control = gui:Create(controlType) if not control then geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType))) end end if control then control:SetMultiselect(true) control:SetLabel(name) control:SetList(values) control:SetDisabled(disabled) control:SetCallback("OnValueChanged",ActivateControl) control:SetCallback("OnClosed", MultiControlOnClosed) local width = GetOptionsMemberValue("width",v,options,path,appName) if width == "double" then control:SetWidth(width_multiplier * 2) elseif width == "half" then control:SetWidth(width_multiplier / 2) elseif width == "full" then control.width = "fill" else control:SetWidth(width_multiplier) end --check:SetTriState(v.tristate) for i = 1, #valuesort do local key = valuesort[i] local value = GetOptionsMemberValue("get",v, options, path, appName, key) control:SetItemValue(key,value) end else control = gui:Create("InlineGroup") control:SetLayout("Flow") control:SetTitle(name) control.width = "fill" control:PauseLayout() local width = GetOptionsMemberValue("width",v,options,path,appName) for i = 1, #valuesort do local value = valuesort[i] local text = values[value] local check = gui:Create("CheckBox") check:SetLabel(text) check:SetUserData("value", value) check:SetUserData("text", text) check:SetDisabled(disabled) check:SetTriState(v.tristate) check:SetValue(GetOptionsMemberValue("get",v, options, path, appName, value)) check:SetCallback("OnValueChanged",ActivateMultiControl) InjectInfo(check, options, v, path, rootframe, appName) control:AddChild(check) if width == "double" then check:SetWidth(width_multiplier * 2) elseif width == "half" then check:SetWidth(width_multiplier / 2) elseif width == "full" then check.width = "fill" else check:SetWidth(width_multiplier) end end control:ResumeLayout() control:DoLayout() end del(valuesort) elseif v.type == "color" then control = gui:Create("ColorPicker") control:SetLabel(name) control:SetHasAlpha(GetOptionsMemberValue("hasAlpha",v, options, path, appName)) control:SetColor(GetOptionsMemberValue("get",v, options, path, appName)) control:SetCallback("OnValueChanged",ActivateControl) control:SetCallback("OnValueConfirmed",ActivateControl) elseif v.type == "keybinding" then control = gui:Create("Keybinding") control:SetLabel(name) control:SetKey(GetOptionsMemberValue("get",v, options, path, appName)) control:SetCallback("OnKeyChanged",ActivateControl) elseif v.type == "header" then control = gui:Create("Heading") control:SetText(name) control.width = "fill" elseif v.type == "description" then control = gui:Create("Label") control:SetText(name) local fontSize = GetOptionsMemberValue("fontSize",v, options, path, appName) if fontSize == "medium" then control:SetFontObject(GameFontHighlight) elseif fontSize == "large" then control:SetFontObject(GameFontHighlightLarge) else -- small or invalid control:SetFontObject(GameFontHighlightSmall) end local imageCoords = GetOptionsMemberValue("imageCoords",v, options, path, appName) local image, width, height = GetOptionsMemberValue("image",v, options, path, appName) if type(image) == "string" then if not width then width = GetOptionsMemberValue("imageWidth",v, options, path, appName) end if not height then height = GetOptionsMemberValue("imageHeight",v, options, path, appName) end if type(imageCoords) == "table" then control:SetImage(image, unpack(imageCoords)) else control:SetImage(image) end if type(width) ~= "number" then width = 32 end if type(height) ~= "number" then height = 32 end control:SetImageSize(width, height) end local width = GetOptionsMemberValue("width",v,options,path,appName) control.width = not width and "fill" end --Common Init if control then if control.width ~= "fill" then local width = GetOptionsMemberValue("width",v,options,path,appName) if width == "double" then control:SetWidth(width_multiplier * 2) elseif width == "half" then control:SetWidth(width_multiplier / 2) elseif width == "full" then control.width = "fill" else control:SetWidth(width_multiplier) end end if control.SetDisabled then local disabled = CheckOptionDisabled(v, options, path, appName) control:SetDisabled(disabled) end InjectInfo(control, options, v, path, rootframe, appName) container:AddChild(control) end end end tremove(path) end container:ResumeLayout() container:DoLayout() del(keySort) del(opts) end local function BuildPath(path, ...) for i = 1, select("#",...) do tinsert(path, (select(i,...))) end end local function TreeOnButtonEnter(widget, event, uniquevalue, button) local user = widget:GetUserDataTable() if not user then return end local options = user.options local option = user.option local path = user.path local appName = user.appName local feedpath = new() for i = 1, #path do feedpath[i] = path[i] end BuildPath(feedpath, ("\001"):split(uniquevalue)) local group = options for i = 1, #feedpath do if not group then return end group = GetSubOption(group, feedpath[i]) end local name = GetOptionsMemberValue("name", group, options, feedpath, appName) local desc = GetOptionsMemberValue("desc", group, options, feedpath, appName) GameTooltip:SetOwner(button, "ANCHOR_NONE") if widget.type == "TabGroup" then GameTooltip:SetPoint("BOTTOM",button,"TOP") else GameTooltip:SetPoint("LEFT",button,"RIGHT") end GameTooltip:SetText(name, 1, .82, 0, true) if type(desc) == "string" then GameTooltip:AddLine(desc, 1, 1, 1, true) end GameTooltip:Show() end local function TreeOnButtonLeave(widget, event, value, button) GameTooltip:Hide() end local function GroupExists(appName, options, path, uniquevalue) if not uniquevalue then return false end local feedpath = new() local temppath = new() for i = 1, #path do feedpath[i] = path[i] end BuildPath(feedpath, ("\001"):split(uniquevalue)) local group = options for i = 1, #feedpath do local v = feedpath[i] temppath[i] = v group = GetSubOption(group, v) if not group or group.type ~= "group" or CheckOptionHidden(group, options, temppath, appName) then del(feedpath) del(temppath) return false end end del(feedpath) del(temppath) return true end local function GroupSelected(widget, event, uniquevalue) local user = widget:GetUserDataTable() local options = user.options local option = user.option local path = user.path local rootframe = user.rootframe local feedpath = new() for i = 1, #path do feedpath[i] = path[i] end BuildPath(feedpath, ("\001"):split(uniquevalue)) local group = options for i = 1, #feedpath do group = GetSubOption(group, feedpath[i]) end widget:ReleaseChildren() AceConfigDialog:FeedGroup(user.appName,options,widget,rootframe,feedpath) del(feedpath) end --[[ -- INTERNAL -- This function will feed one group, and any inline child groups into the given container Select Groups will only have the selection control (tree, tabs, dropdown) fed in and have a group selected, this event will trigger the feeding of child groups Rules: If the group is Inline, FeedOptions If the group has no child groups, FeedOptions If the group is a tab or select group, FeedOptions then add the Group Control If the group is a tree group FeedOptions then its parent isnt a tree group: then add the tree control containing this and all child tree groups if its parent is a tree group, its already a node on a tree --]] function AceConfigDialog:FeedGroup(appName,options,container,rootframe,path, isRoot) local group = options --follow the path to get to the curent group local inline local grouptype, parenttype = options.childGroups, "none" for i = 1, #path do local v = path[i] group = GetSubOption(group, v) inline = inline or pickfirstset(v.dialogInline,v.guiInline,v.inline, false) parenttype = grouptype grouptype = group.childGroups end if not parenttype then parenttype = "tree" end --check if the group has child groups local hasChildGroups for k, v in pairs(group.args) do if v.type == "group" and not pickfirstset(v.dialogInline,v.guiInline,v.inline, false) and not CheckOptionHidden(v, options, path, appName) then hasChildGroups = true end end if group.plugins then for plugin, t in pairs(group.plugins) do for k, v in pairs(t) do if v.type == "group" and not pickfirstset(v.dialogInline,v.guiInline,v.inline, false) and not CheckOptionHidden(v, options, path, appName) then hasChildGroups = true end end end end container:SetLayout("flow") local scroll --Add a scrollframe if we are not going to add a group control, this is the inverse of the conditions for that later on if (not (hasChildGroups and not inline)) or (grouptype ~= "tab" and grouptype ~= "select" and (parenttype == "tree" and not isRoot)) then if container.type ~= "InlineGroup" and container.type ~= "SimpleGroup" then scroll = gui:Create("ScrollFrame") scroll:SetLayout("flow") scroll.width = "fill" scroll.height = "fill" container:SetLayout("fill") container:AddChild(scroll) container = scroll end end FeedOptions(appName,options,container,rootframe,path,group,nil) if scroll then container:PerformLayout() local status = self:GetStatusTable(appName, path) if not status.scroll then status.scroll = {} end scroll:SetStatusTable(status.scroll) end if hasChildGroups and not inline then local name = GetOptionsMemberValue("name", group, options, path, appName) if grouptype == "tab" then local tab = gui:Create("TabGroup") InjectInfo(tab, options, group, path, rootframe, appName) tab:SetCallback("OnGroupSelected", GroupSelected) tab:SetCallback("OnTabEnter", TreeOnButtonEnter) tab:SetCallback("OnTabLeave", TreeOnButtonLeave) local status = AceConfigDialog:GetStatusTable(appName, path) if not status.groups then status.groups = {} end tab:SetStatusTable(status.groups) tab.width = "fill" tab.height = "fill" local tabs = BuildGroups(group, options, path, appName) tab:SetTabs(tabs) tab:SetUserData("tablist", tabs) for i = 1, #tabs do local entry = tabs[i] if not entry.disabled then tab:SelectTab((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or entry.value) break end end container:AddChild(tab) elseif grouptype == "select" then local select = gui:Create("DropdownGroup") select:SetTitle(name) InjectInfo(select, options, group, path, rootframe, appName) select:SetCallback("OnGroupSelected", GroupSelected) local status = AceConfigDialog:GetStatusTable(appName, path) if not status.groups then status.groups = {} end select:SetStatusTable(status.groups) local grouplist, orderlist = BuildSelect(group, options, path, appName) select:SetGroupList(grouplist, orderlist) select:SetUserData("grouplist", grouplist) select:SetUserData("orderlist", orderlist) local firstgroup = orderlist[1] if firstgroup then select:SetGroup((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or firstgroup) end select.width = "fill" select.height = "fill" container:AddChild(select) --assume tree group by default --if parenttype is tree then this group is already a node on that tree elseif (parenttype ~= "tree") or isRoot then local tree = gui:Create("TreeGroup") InjectInfo(tree, options, group, path, rootframe, appName) tree:EnableButtonTooltips(false) tree.width = "fill" tree.height = "fill" tree:SetCallback("OnGroupSelected", GroupSelected) tree:SetCallback("OnButtonEnter", TreeOnButtonEnter) tree:SetCallback("OnButtonLeave", TreeOnButtonLeave) local status = AceConfigDialog:GetStatusTable(appName, path) if not status.groups then status.groups = {} end local treedefinition = BuildGroups(group, options, path, appName, true) tree:SetStatusTable(status.groups) tree:SetTree(treedefinition) tree:SetUserData("tree",treedefinition) for i = 1, #treedefinition do local entry = treedefinition[i] if not entry.disabled then tree:SelectByValue((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or entry.value) break end end container:AddChild(tree) end end end local old_CloseSpecialWindows local function RefreshOnUpdate(this) for appName in pairs(this.closing) do if AceConfigDialog.OpenFrames[appName] then AceConfigDialog.OpenFrames[appName]:Hide() end if AceConfigDialog.BlizOptions and AceConfigDialog.BlizOptions[appName] then for key, widget in pairs(AceConfigDialog.BlizOptions[appName]) do if not widget:IsVisible() then widget:ReleaseChildren() end end end this.closing[appName] = nil end if this.closeAll then for k, v in pairs(AceConfigDialog.OpenFrames) do if not this.closeAllOverride[k] then v:Hide() end end this.closeAll = nil wipe(this.closeAllOverride) end for appName in pairs(this.apps) do if AceConfigDialog.OpenFrames[appName] then local user = AceConfigDialog.OpenFrames[appName]:GetUserDataTable() AceConfigDialog:Open(appName, unpack(user.basepath or emptyTbl)) end if AceConfigDialog.BlizOptions and AceConfigDialog.BlizOptions[appName] then for key, widget in pairs(AceConfigDialog.BlizOptions[appName]) do local user = widget:GetUserDataTable() if widget:IsVisible() then AceConfigDialog:Open(widget:GetUserData("appName"), widget, unpack(user.basepath or emptyTbl)) end end end this.apps[appName] = nil end this:SetScript("OnUpdate", nil) end -- Upgrade the OnUpdate script as well, if needed. if AceConfigDialog.frame:GetScript("OnUpdate") then AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) end --- Close all open options windows function AceConfigDialog:CloseAll() AceConfigDialog.frame.closeAll = true AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) if next(self.OpenFrames) then return true end end --- Close a specific options window. -- @param appName The application name as given to `:RegisterOptionsTable()` function AceConfigDialog:Close(appName) if self.OpenFrames[appName] then AceConfigDialog.frame.closing[appName] = true AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) return true end end -- Internal -- Called by AceConfigRegistry function AceConfigDialog:ConfigTableChanged(event, appName) AceConfigDialog.frame.apps[appName] = true AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) end reg.RegisterCallback(AceConfigDialog, "ConfigTableChange", "ConfigTableChanged") --- Sets the default size of the options window for a specific application. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param width The default width -- @param height The default height function AceConfigDialog:SetDefaultSize(appName, width, height) local status = AceConfigDialog:GetStatusTable(appName) if type(width) == "number" and type(height) == "number" then status.width = width status.height = height end end --- Open an option window at the specified path (if any). -- This function can optionally feed the group into a pre-created container -- instead of creating a new container frame. -- @paramsig appName [, container][, ...] -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param container An optional container frame to feed the options into -- @param ... The path to open after creating the options window (see `:SelectGroup` for details) function AceConfigDialog:Open(appName, container, ...) if not old_CloseSpecialWindows then old_CloseSpecialWindows = CloseSpecialWindows CloseSpecialWindows = function() local found = old_CloseSpecialWindows() return self:CloseAll() or found end end local app = reg:GetOptionsTable(appName) if not app then error(("%s isn't registed with AceConfigRegistry, unable to open config"):format(appName), 2) end local options = app("dialog", MAJOR) local f local path = new() local name = GetOptionsMemberValue("name", options, options, path, appName) --If an optional path is specified add it to the path table before feeding the options --as container is optional as well it may contain the first element of the path if type(container) == "string" then tinsert(path, container) container = nil end for n = 1, select("#",...) do tinsert(path, (select(n, ...))) end local option = options if type(container) == "table" and container.type == "BlizOptionsGroup" and #path > 0 then for i = 1, #path do option = options.args[path[i]] end name = format("%s - %s", name, GetOptionsMemberValue("name", option, options, path, appName)) end --if a container is given feed into that if container then f = container f:ReleaseChildren() f:SetUserData("appName", appName) f:SetUserData("iscustom", true) if #path > 0 then f:SetUserData("basepath", copy(path)) end local status = AceConfigDialog:GetStatusTable(appName) if not status.width then status.width = 700 end if not status.height then status.height = 500 end if f.SetStatusTable then f:SetStatusTable(status) end if f.SetTitle then f:SetTitle(name or "") end else if not self.OpenFrames[appName] then f = gui:Create("Frame") self.OpenFrames[appName] = f else f = self.OpenFrames[appName] end f:ReleaseChildren() f:SetCallback("OnClose", FrameOnClose) f:SetUserData("appName", appName) if #path > 0 then f:SetUserData("basepath", copy(path)) end f:SetTitle(name or "") local status = AceConfigDialog:GetStatusTable(appName) f:SetStatusTable(status) end self:FeedGroup(appName,options,f,f,path,true) if f.Show then f:Show() end del(path) if AceConfigDialog.frame.closeAll then -- close all is set, but thats not good, since we're just opening here, so force it AceConfigDialog.frame.closeAllOverride[appName] = true end end -- convert pre-39 BlizOptions structure to the new format if oldminor and oldminor < 39 and AceConfigDialog.BlizOptions then local old = AceConfigDialog.BlizOptions local new = {} for key, widget in pairs(old) do local appName = widget:GetUserData("appName") if not new[appName] then new[appName] = {} end new[appName][key] = widget end AceConfigDialog.BlizOptions = new else AceConfigDialog.BlizOptions = AceConfigDialog.BlizOptions or {} end local function FeedToBlizPanel(widget, event) local path = widget:GetUserData("path") AceConfigDialog:Open(widget:GetUserData("appName"), widget, unpack(path or emptyTbl)) end local function ClearBlizPanel(widget, event) local appName = widget:GetUserData("appName") AceConfigDialog.frame.closing[appName] = true AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) end --- Add an option table into the Blizzard Interface Options panel. -- You can optionally supply a descriptive name to use and a parent frame to use, -- as well as a path in the options table.\\ -- If no name is specified, the appName will be used instead. -- -- If you specify a proper `parent` (by name), the interface options will generate a -- tree layout. Note that only one level of children is supported, so the parent always -- has to be a head-level note. -- -- This function returns a reference to the container frame registered with the Interface -- Options. You can use this reference to open the options with the API function -- `InterfaceOptionsFrame_OpenToCategory`. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param name A descriptive name to display in the options tree (defaults to appName) -- @param parent The parent to use in the interface options tree. -- @param ... The path in the options table to feed into the interface options panel. -- @return The reference to the frame registered into the Interface Options. function AceConfigDialog:AddToBlizOptions(appName, name, parent, ...) local BlizOptions = AceConfigDialog.BlizOptions local key = appName for n = 1, select("#", ...) do key = key.."\001"..select(n, ...) end if not BlizOptions[appName] then BlizOptions[appName] = {} end if not BlizOptions[appName][key] then local group = gui:Create("BlizOptionsGroup") BlizOptions[appName][key] = group group:SetName(name or appName, parent) group:SetTitle(name or appName) group:SetUserData("appName", appName) if select("#", ...) > 0 then local path = {} for n = 1, select("#",...) do tinsert(path, (select(n, ...))) end group:SetUserData("path", path) end group:SetCallback("OnShow", FeedToBlizPanel) group:SetCallback("OnHide", ClearBlizPanel) InterfaceOptions_AddCategory(group.frame) return group.frame else error(("%s has already been added to the Blizzard Options Window with the given path"):format(appName), 2) end end
mit
Joshalexjacobs/fantastic-guacamole
bullets.lua
1
6902
-- bullets.lua -- --local hit = love.audio.newSource("sound/bullet sound/hit.wav", static) --hit:setVolume(0.1) --love.audio.play(hit) local pbullet = { type = "invincible", owner = "player", hitSound = nil, hit = false, x = nil, y = nil, w = 4, -- 8 h = 4, -- 8 dx = 0, dy = 0, speed = 400, dir = nil, actualDir = nil, isShot = false, isDead = false, color = {255, 255, 255, 255}, filter = function(item, other) if other.type == "enemy" or other.type == "boss" or other.type == "bubble" then return 'touch' -- used to be cross elseif other.type == "block" or other.type == "ground" then return 'touch' -- used to be cross end end, reaction = function(entity, cols, len) for j = 1, len do if cols[j].other.type == "enemy" or cols[j].other.type == "boss" or cols[j].other.type == "bubble" then entity.hit = true entity.isDead = true -- destroy bullet cols[j].other.hp = cols[j].other.hp - 1 -- decrement other.hp elseif cols[j].other.type == "block" or cols[j].other.type == "ground" then entity.hit = true entity.isDead = true end end end, curAnim = 1, spriteSheet = nil, spriteGrid = nil, animations = {}, timers = {} } pProneFilter = function(item, other) if other.type == "enemy" or other.type == "boss" then return 'touch' elseif other.type == "block" then return 'touch' end end local ebullet = { type = "invincible", owner = "enemy", x = nil, y = nil, w = 8, h = 8, dx = 0, dy = 0, speed = 150, dir = nil, actualDir = nil, isShot = false, isDead = false, color = {255, 255, 255, 255}, filter = function(item, other) if other.type == "player" then return 'touch' -- used to be cross elseif other.type == "block" or other.type == "ground" then return 'touch' -- used to be cross end end, reaction = function(entity, cols, len) for j = 1, len do if cols[j].other.type == "player" then entity.isDead = true -- destroy bullet cols[j].other.killPlayer(world) break elseif cols[j].other.type == "block" or cols[j].other.type == "ground" then entity.isDead = true break end end end, curAnim = 1, spriteSheet = nil, spriteGrid = nil, animations = {}, timers = {} } local pBulletsCount = 0 -- max is 4 local eBullets = {} -- enemy bullets local pBullets = {} -- player bullets function loadBullet() -- load player bullets pbullet.spriteSheet = love.graphics.newImage("img/other/newBullet.png") pbullet.spriteGrid = anim8.newGrid(16, 8, 48, 32, 0, 0, 0) pbullet.animations = { anim8.newAnimation(pbullet.spriteGrid('1-2', 1), 0.005, 'pauseAtEnd'), -- 1 muzzle flash anim8.newAnimation(pbullet.spriteGrid(3, 1, '1-3', 2), 0.08), -- 2 shot anim8.newAnimation(pbullet.spriteGrid('1-3', '3-4'), 0.02, 'pauseAtEnd'), -- 3 dead } pbullet.hitSound = love.audio.newSource("sound/bullet sound/hit.wav", static) pbullet.hitSound:setVolume(0.00) -- load enemy bullets ebullet.spriteSheet = love.graphics.newImage("img/other/enemy bullet.png") ebullet.spriteGrid = anim8.newGrid(16, 8, 48, 32, 0, 0, 0) ebullet.animations = { anim8.newAnimation(ebullet.spriteGrid('1-2', 1), 0.005, 'pauseAtEnd'), -- 1 muzzle flash anim8.newAnimation(ebullet.spriteGrid(3, 1, 1, 2), 0.25), -- 2 shot anim8.newAnimation(ebullet.spriteGrid('1-3', '3-4'), 0.02, 'pauseAtEnd'), -- 3 dead } end function addBullet(danger, xPos, yPos, direction, world, newDir, isProne) -- add world as parameter isProne = isProne or false if pBulletsCount >= player.bulletsMax and danger == false then -- 4 return false elseif danger == false then newBullet = copy(pbullet, newBullet) newBullet.x, newBullet.y, newBullet.dir, newBullet.actualDir = xPos, yPos, direction, newDir pBulletsCount = pBulletsCount + 1 if isProne then newBullet.filter = pProneFilter end elseif danger == true then newBullet = copy(ebullet, newBullet) newBullet.x, newBullet.y, newBullet.dir, newBullet.actualDir = xPos, yPos, direction, newDir end addTimer(0.01, "flash", newBullet.timers) world:add(newBullet, newBullet.x, newBullet.y, newBullet.w, newBullet.h) -- add all bullets to world... if danger then table.insert(eBullets, newBullet) else table.insert(pBullets, newBullet) end return true end local function handleBullets(dt, left, viewportWidth, world, bullets) for i, newBullet in ipairs(bullets) do newBullet.animations[newBullet.curAnim]:update(dt) -- update animations if updateTimer(dt, "flash", newBullet.timers) and newBullet.isDead == false and newBullet.isShot == false then newBullet.curAnim = 2 newBullet.isShot = true newBullet.type = "bullet" end newBullet.dx = math.cos(newBullet.actualDir) * newBullet.speed * dt newBullet.dy = math.sin(newBullet.actualDir) * newBullet.speed * dt if newBullet.isDead == false then newBullet.x, newBullet.y, cols, len = world:move(newBullet, newBullet.x + newBullet.dx, newBullet.y + newBullet.dy, newBullet.filter) -- update world end newBullet.reaction(newBullet, cols, len) if (newBullet.x > left + viewportWidth + newBullet.w) or (newBullet.x < left - newBullet.w) or (newBullet.y < -16) then newBullet.isDead = true end if newBullet.isDead == true then -- if a newBullet leaves the play area... if checkTimer("dead", newBullet.timers) == false then if world:hasItem(newBullet) then world:remove(newBullet) -- remove from world... end newBullet.curAnim = 3 addTimer(0.1, "dead", newBullet.timers) if newBullet.hit == true then love.audio.play(newBullet.hitSound) end end if updateTimer(dt, "dead", newBullet.timers) then table.remove(bullets, i) -- ...and the bullets table if newBullet.owner == "player" then pBulletsCount = pBulletsCount - 1 end end end end end function updateBullets(dt, left, viewportWidth, world) -- add world as a parameter handleBullets(dt, left, viewportWidth, world, pBullets) handleBullets(dt, left, viewportWidth, world, eBullets) end function drawBullets() for _, newBullet in ipairs(pBullets) do newBullet.animations[newBullet.curAnim]:draw(newBullet.spriteSheet, newBullet.x, newBullet.y, newBullet.actualDir, 1, 1, 10, newBullet.actualDir + 3) --love.graphics.rectangle("line", newBullet.x, newBullet.y, newBullet.w, newBullet.h) end for _, newBullet in ipairs(eBullets) do newBullet.animations[newBullet.curAnim]:draw(newBullet.spriteSheet, newBullet.x, newBullet.y, newBullet.actualDir, 1, 1, newBullet.actualDir + 14, newBullet.actualDir + 5) --love.graphics.rectangle("line", newBullet.x, newBullet.y, newBullet.w, newBullet.h) end end
mit
Laterus/Darkstar-Linux-Fork
scripts/zones/RuLude_Gardens/npcs/Radeivepart.lua
1
2766
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Radeivepart -- Starts and Finishes Quest: Northward -- Involved in Quests: Save the Clock Tower -- @zone 243 -- @pos 5 9 -39 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); package.loaded["scripts/globals/quests"] = nil; require("scripts/globals/quests"); package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(555,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then a = player:getVar("saveTheClockTowerNPCz1"); -- NPC Zone1 if(a == 0 or (a ~= 1 and a ~= 3 and a ~= 5 and a ~= 9 and a ~= 17 and a ~= 7 and a ~= 25 and a ~= 11 and a ~= 13 and a ~= 19 and a ~= 21 and a ~= 15 and a ~= 23 and a ~= 27 and a ~= 29 and a ~= 31)) then player:startEvent(0x00a0,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end elseif(player:getQuestStatus(JEUNO,NORTHWARD) == QUEST_ACCEPTED) then if(trade:hasItemQty(16522,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x003d); -- Finish quest "Northward" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getFameLevel(JEUNO) >= 4 and player:getQuestStatus(JEUNO,NORTHWARD) == QUEST_AVAILABLE) then player:startEvent(000); -- Start quest "Northward" CS NOT FOUND else player:startEvent(0x009f); -- Standard dialog end end; --0x009f 0x003d 0x00a0 ----------------------------------- -- 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 == 0x00a0) then player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1); player:setVar("saveTheClockTowerNPCz1",player:getVar("saveTheClockTowerNPCz1") + 1); elseif(csid == 000 and option == 0) then player:addQuest(JEUNO,NORTHWARD); elseif(csid == 0x003d) then player:completeQuest(JEUNO,NORTHWARD); player:setTitle(ENVOY_TO_THE_NORTH); player:addKeyItem(MAP_OF_CASTLE_ZVAHL); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_CASTLE_ZVAHL); player:addFame(JEUNO,30); player:tradeComplete(); end end;
gpl-3.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Network/Packets/PacketEntityTeleport.lua
1
1883
--[[ Title: PacketEntityTeleport Author(s): LiXizhi Date: 2014/7/4 Desc: use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Packets/PacketEntityTeleport.lua"); local Packets = commonlib.gettable("MyCompany.Aries.Game.Network.Packets"); local packet = Packets.PacketEntityTeleport:new():Init(); ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Packets/Packet.lua"); local PacketEntityTeleport = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Network.Packets.Packet"), commonlib.gettable("MyCompany.Aries.Game.Network.Packets.PacketEntityTeleport")); function PacketEntityTeleport:ctor() end function PacketEntityTeleport:Init(entityOrId, scaledX, scaledY, scaledZ, facing, pitch) if(type(entityOrId) == "table") then return self:Init1(entityOrId); else return self:Init2(entityOrId, scaledX, scaledY, scaledZ, facing, pitch); end end function PacketEntityTeleport:Init1(entity) self.entityId = entity.entityId; self.x = math.floor(entity.x * 32); self.y = math.floor(entity.y * 32); self.z = math.floor(entity.z * 32); self.facing = math.floor(entity.facing * 32); self.pitch = math.floor(entity.rotationPitch * 32); return self; end function PacketEntityTeleport:Init2(entityId, scaledX, scaledY, scaledZ, facing, pitch) self.entityId = entityId; self.x = scaledX; self.y = scaledY; self.z = scaledZ; self.facing = facing; self.pitch = pitch; return self; end -- Passes this Packet on to the NetHandler for processing. function PacketEntityTeleport:ProcessPacket(net_handler) if(net_handler.handleEntityTeleport) then net_handler:handleEntityTeleport(self); end end function PacketEntityTeleport:ContainsSameEntityIDAs(packet) return packet.entityId == self.entityId; end
gpl-2.0
monkoose/neovim-setup
lua/statusline.lua
1
4991
local diagn = vim.diagnostic local M = {} local augroup = vim.api.nvim_create_augroup("StatusLine", {}) local autocmd = vim.api.nvim_create_autocmd local colors = { green = 1, yellow = 2, blue = 3, magenta = 4, red = 5, bold_red = 6, } -- UTILS ------------------------------ local function colorize(str, color) return "%" .. color .. "*" .. str .. "%*" end local function set_window_statusline(str) vim.wo.statusline = str end local function set_spell() vim.b.status_spell = vim.o.spell and " SPELL " or "" end autocmd("BufWinEnter", { group = augroup, callback = set_spell, }) autocmd("OptionSet", { pattern = "spell", group = augroup, callback = set_spell, }) local function set_iminsert() vim.b.status_iminsert = vim.o.iminsert == 1 and " RU " or "" end autocmd("BufWinEnter", { group = augroup, callback = function() set_iminsert() end, }) autocmd("OptionSet", { pattern = "iminsert", group = augroup, callback = function() set_iminsert() end, }) local function set_readonly() vim.b.status_readonly = vim.bo.readonly and " " or "" end autocmd("BufWinEnter", { group = augroup, callback = function() set_readonly() end, }) autocmd("OptionSet", { pattern = "readonly", group = augroup, callback = function() set_readonly() end, }) local function set_fname() local fname = vim.api.nvim_buf_get_name(0) if fname == '' then vim.b.status_filename = "[No Name]" elseif vim.bo.filetype == "help" then vim.b.status_filename = vim.fn.fnamemodify(fname, ":t") else vim.b.status_filename = vim.fn.fnamemodify(fname, ':~:.') end end autocmd({"BufEnter", "BufFilePost", "BufNew", "BufWinEnter"}, { group = augroup, callback = function() set_fname() end, }) local function set_diagnostics() local errs = #diagn.get(0, { severity = diagn.severity.ERROR }) local warns = #diagn.get(0, { severity = diagn.severity.WARN }) local err_str = errs ~= 0 and " E:" .. errs or "" local warn_str = warns ~= 0 and " W:" .. warns or "" vim.b.status_diagnostics = err_str .. warn_str .. " " end autocmd("DiagnosticChanged", { group = augroup, callback = set_diagnostics, }) -- PARTS ------------------------------ local spell = colorize("%{get(b:, 'status_spell', '')}", colors.magenta) local right = " %=" local tail = " %{&filetype} " .. colorize("%P ", colors.blue) local tail_nc = " %{&filetype} %P " local fname_block = "%{get(b:, 'status_filename', '')}" local fname = " %w " .. colorize(fname_block, colors.yellow) .. colorize(" %m ", colors.bold_red) local fname_nc = " %w " .. fname_block .. " %m " local ro = colorize("%{get(b:, 'status_readonly', '')}", colors.red) local iminsert = colorize("%{get(b:, 'status_iminsert', '')}", colors.red) local diagnostics = colorize("%{get(b:, 'status_diagnostics', '')}", colors.bold_red) local githead = " %{get(b:, 'gitsigns_head', ' ')}" local gitsigns = " %{get(b:, 'gitsigns_status', '')}" local git = colorize(githead, colors.green) .. gitsigns local git_nc = githead local function default_status(active) if active then return iminsert .. fname .. ro .. git .. spell .. right .. diagnostics .. tail else return fname_nc .. git_nc .. right .. tail_nc end end -- WINDOWS ------------------------------ -- fugitive blame local function blame_status(active) local name = " BLAME " if active then name = colorize(name, colors.yellow) end local b_tail = " %=%(%l/%L%) %P " return name .. b_tail end local function fugitive_status(active) local bufname = vim.api.nvim_buf_get_name(0) if string.find(bufname, "%.git//$") then local name = " FUGITIVE STATUS" if active then name = colorize(name, colors.yellow) end return name else return default_status(active) end end -- quickfix and locationlist local function qf_status(active) local qf_title = "%{get(w:, 'quickfix_title', '')}" local qf_head = " %q " local qf_lines = " %L " if active then qf_head = colorize(qf_head, colors.yellow) qf_lines = colorize(qf_lines, colors.blue) end return qf_head .. qf_lines .. qf_title end -- terminal local function term_status(active) local term_name = " TERM " local term_title = " %{get(b:, 'term_title', '')} " if active then term_name = colorize(term_name, colors.yellow) term_title = colorize(term_title, colors.blue) return term_name .. term_title .. right .. tail end return term_name .. term_title .. right .. tail_nc end -- STATUSLINE ------------------------------ function M.setstatusline(active) local ft = vim.api.nvim_buf_get_option(0, "filetype") if ft == "fugitiveblame" then set_window_statusline(blame_status(active)) elseif ft == "qf" then set_window_statusline(qf_status(active)) elseif ft == "myterm" then set_window_statusline(term_status(active)) elseif ft == "fugitive" then set_window_statusline(fugitive_status(active)) else set_window_statusline(default_status(active)) end end return M
mit
Laterus/Darkstar-Linux-Fork
scripts/zones/Bastok_Mines/npcs/Leonie.lua
5
1046
----------------------------------- -- Area: Bastok Mines -- NPC: Leonie -- Type: Room Renters -- @zone: 234 -- @pos: 118.871 -0.004 -83.916 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0238); 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
koenwtje/dotfiles
config/awesome/battery.lua
1
3149
-- This function returns a formatted string with the current battery status. It -- can be used to populate a text widget in the awesome window manager. Based -- on the "Gigamo Battery Widget" found in the wiki at awesome.naquadah.org local naughty = require("naughty") local beautiful = require("beautiful") function readFile(path) file = io.open(path, "r") if file then local str = file:read() file:close() return str end end -- Given the name of a power device (e.g. BAT0) and a list of metrics -- corresponding to files in `/sys/class/power_supply/*/`, return the value of -- the given metric. function getBatteryMetric(adapter, ...) local basepath = "/sys/class/power_supply/"..adapter.."/" for i, name in pairs({...}) do result = readFile(basepath .. name) if result then return result end end end function getPowerUsage(adapter) local uwatts = readFile("/sys/class/power_supply/" .. adapter .. "/power_now") if uwatts then return uwatts end end function batteryInfo(adapter) local fh = io.open("/sys/class/power_supply/"..adapter.."/present", "r") if fh == nil then battery = "A/C" icon = "" percent = "" else local energy_now = getBatteryMetric(adapter, "charge_now", "energy_now") local energy_full = getBatteryMetric(adapter, "charge_full", "energy_full") local status = getBatteryMetric(adapter, "status") uwatts = getPowerUsage(adapter) power_usage = "" if uwatts then power_usage = uwatts * 10^-6 else power_usage = "?" end battery_percent = math.floor(energy_now / energy_full * 100) if status:match("Charging") then icon = "🔌" percent = "%" if tonumber(battery_percent) == 80 then naughty.notify({ title = "Battery charged to 80%, unplug charger?" , text = "" , timeout = 5 , position = "top_right" , fg = beautiful.fg_focus , bg = beautiful.bg_focus }) end elseif status:match("Discharging") then icon = "🔋" percent = "%" if tonumber(battery_percent) < 15 then naughty.notify({ title = "Battery Warning" , text = "Battery low!".." "..battery_percent..percent.." ".."left!" , timeout = 5 , position = "top_right" , fg = beautiful.fg_focus , bg = beautiful.bg_focus }) end if tonumber(battery_percent) == 40 then naughty.notify({ title = "Battery down to 40%, plug charger?" , text = "" , timeout = 5 , position = "top_right" , fg = beautiful.fg_focus , bg = beautiful.bg_focus }) end else -- If we are neither charging nor discharging, assume that we are on A/C battery = "A/C" icon = "" percent = "" end -- fix 'too many open files' bug on awesome 4.0 fh:close() end return " " .. icon .. battery_percent .. percent .. " " .. power_usage .. " W⚡" end
mit
TerminalShell/zombiesurvival
entities/entities/prop_aegisboard/cl_init.lua
1
1568
include("shared.lua") ENT.RenderGroup = RENDERGROUP_TRANSLUCENT function ENT:SetBoardHealth(health) self:SetDTFloat(0, health) end //local matOutlineWhite = Material("white_outline") //local ScaleNormal = 1 //local ScaleOutline = 1.09 function ENT:Draw() if MySelf:IsValid() and MySelf:Team() == TEAM_HUMAN then //render.SuppressEngineLighting(true) //render.SetAmbientLight(1, 1, 1) //local percentage = self:GetBoardHealth() / self:GetMaxBoardHealth() //render.SetColorModulation(1 - percentage, percentage, 0) //self:SetModelScale(ScaleOutline, 0) //render.ModelMaterialOverride(matOutlineWhite) //self:DrawModel() //render.ModelMaterialOverride() //self:SetModelScale(ScaleNormal, 0) //render.SuppressEngineLighting(false) //render.SetColorModulation(1, 1, 1) self:DrawModel() local owner = self:GetObjectOwner() if owner:IsValid() and owner:IsPlayer() and owner:Team() ~= TEAM_UNDEAD then local name = owner:Name() local ang = self:GetAngles() ang:RotateAroundAxis(ang:Up(), 270) ang:RotateAroundAxis(ang:Right(), 270) ang:RotateAroundAxis(ang:Forward(), 270) local vPos = self:GetPos() local vOffset = self:GetForward() * self:OBBMaxs().x cam.Start3D2D(vPos + vOffset, ang, 0.1) draw.SimpleText(name, "ZS3D2DFont", 0, 0, COLOR_WHITE, TEXT_ALIGN_CENTER) cam.End3D2D() ang:RotateAroundAxis(ang:Right(), 180) cam.Start3D2D(vPos - vOffset, ang, 0.1) draw.SimpleText(name, "ZS3D2DFont", 0, 0, COLOR_WHITE, TEXT_ALIGN_CENTER) cam.End3D2D() end else self:DrawModel() end end
gpl-3.0
madpilot78/ntopng
attic/scripts/plugins/alerts/network/threshold_cross/user_scripts/interface/throughput.lua
2
1434
-- -- (C) 2019-21 - ntop.org -- local alerts_api = require("alerts_api") local alert_consts = require("alert_consts") local user_scripts = require("user_scripts") local alert_severities = require "alert_severities" local script = { -- Script category category = user_scripts.script_categories.network, default_enabled = false, -- This script is only for alerts generation is_alert = true, default_value = { severity = alert_severities.error, }, -- See below hooks = {}, gui = { i18n_title = "alerts_thresholds_config.throughput", i18n_description = "alerts_thresholds_config.alert_throughput_description", i18n_field_unit = user_scripts.field_units.mbits, input_builder = "threshold_cross", } } -- ################################################################# function script.hooks.all(params) local interface_bytes = params.entity_info["stats"]["bytes"] -- Delta local value = alerts_api.interface_delta_val(script.key, params.granularity, interface_bytes) -- Granularity value = value / alert_consts.granularity2sec(params.granularity) -- Bytes to Mbit value = (value * 8) / 1000000 -- Check if the configured threshold is crossed by the value and possibly trigger an alert alerts_api.checkThresholdAlert(params, alert_consts.alert_types.alert_threshold_cross, value) end -- ################################################################# return script
gpl-3.0
TerminalShell/zombiesurvival
entities/entities/gmod_player_start/init.lua
1
1561
-- This makes old gmod9 ZS maps playable ENT.Type = "point" function ENT:Initialize() if self.RedTeam or self.GreenTeam or self.YellowTeam or self.BlueTeam then self.BlueTeam = self.BlueTeam or false self.GreenTeam = self.GreenTeam or false self.YellowTeam = self.YellowTeam or false self.RedTeam = self.RedTeam or false else self.BlueTeam = true self.GreenTeam = true self.YellowTeam = true self.RedTeam = true end self.Entity:GetTable().BlueTeam = self.BlueTeam self.Entity:GetTable().GreenTeam = self.GreenTeam self.Entity:GetTable().RedTeam = self.RedTeam self.Entity:GetTable().YellowTeam = self.YellowTeam end function ENT:KeyValue(key, value) if key == "spawnflags" then local sf = tonumber(Value) for i=15, 0, -1 do local bit = math.pow(2, i) if sf - bit >= 0 then if bit == 8 then self.RedTeam = true self.Entity:GetTable().RedTeam = true elseif bit == 4 then self.GreenTeam = true self.Entity:GetTable().GreenTeam = true elseif bit == 2 then self.YellowTeam = true self.Entity:GetTable().YellowTeam = true elseif bit == 1 then self.BlueTeam = true self.Entity:GetTable().BlueTeam = true end sf = sf - bit else if bit == 8 then self.RedTeam = false self.Entity:GetTable().RedTeam = false elseif bit == 4 then self.GreenTeam = false self.Entity:GetTable().GreenTeam = false elseif bit == 2 then self.YellowTeam = false self.Entity:GetTable().YellowTeam = false elseif bit == 1 then self.BlueTeam = false self.Entity:GetTable().BlueTeam = false end end end end end
gpl-3.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Common/Files.lua
1
26984
--[[ Title: World Files Author(s): LiXizhi Date: 2014/5/7 Desc: use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/Common/Files.lua"); local Files = commonlib.gettable("MyCompany.Aries.Game.Common.Files"); -- search and cache the relative path local filepath = Files.GetFilePath("readme.md"); local filepath = Files.FindFile("readme.md"); Files:ClearFindFileCache(); local filename = Files.GetWorldFilePath("preview.jpg"); Files:GetFileFromCache(filename) echo(Files.GetRelativePath(GameLogic.GetWorldDirectory().."1.png")); echo(Files.GetRelativePath(GameLogic.GetWorldDirectory().."1.png")); echo(Files:FindWorldFiles({}, "blocktemplates/", nMaxFileLevels, nMaxFilesNum, filterFunc)) ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Packets/PacketGetFile.lua"); NPL.load("(gl)script/ide/math/StringUtil.lua"); NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/OpenFileDialog.lua"); local OpenFileDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.OpenFileDialog"); local Packets = commonlib.gettable("MyCompany.Aries.Game.Network.Packets"); local SlashCommand = commonlib.gettable("MyCompany.Aries.SlashCommand.SlashCommand"); local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine") local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types") local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic") local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager"); local Files = commonlib.gettable("MyCompany.Aries.Game.Common.Files"); -- additional world search path Files.worldSearchPath = nil; -- how many assets to unload during each step. Files.garbageCollectStep = 20; -- add default always-in-memory files here, keep this to minimum, these file will survive UnloadAllUnusedAssets when a new world is loaded. local alwaysInMemoryFiles = { -- system ["Texture/whitedot.png"] = true, ["Texture/dxutcontrols.dds"] = true, ["Texture/kidui/main/cursor.tga"] = true, ["Texture/Aries/Common/AssetLoader_32bits.png"] = true, ["Texture/Aries/Creator/keepwork/worldshare_32bits.png"] = true, -- world share main UI ["Texture/Aries/Creator/Theme/GameCommonIcon_32bits.png"] = true, -- paracraft main UI ["Texture/Aries/Creator/Theme/scroll_track_32bits.png"] = true, ["Texture/3DMapSystem/common/ThemeLightBlue/container_bg.png"] = true, ["Texture/3DMapSystem/common/ThemeLightBlue/slider_button_16.png"] = true, ["Texture/Aries/Common/ThemeKid/editbox_32bits.png"] = true, -- Loading screen ["Texture/Aries/Login/Login/teen/loading_green_32bits.png"] = true, ["Texture/Aries/Login/Login/teen/loading_gray_32bits.png"] = true, ["Texture/Aries/Login/Login/teen/progressbar_green_tile.png"] = true, ["Texture/Aries/Creator/Mobile/blocks_Background.png"] = true, -- camera and actors ["character/CC/02human/actor/actor.x"] = true, ["character/CC/02human/CustomGeoset/actor.x"] = true, ["character/CC/05effect/Birthplace/Birthplace.x"] = true, -- make sure the camera model is preloaded, otherwise the first movie block's camera height will be wrong ["character/CC/02human/Camera/Camera.x"] = true, [""] = true, } -- currently only one addtional world search path can be added. function Files.AddWorldSearchPath(worldPath) Files.worldSearchPath = worldPath; end function Files.GetAdditionalWorldSearchPath() return Files.worldSearchPath; end -- this is a temporary folder that is cleared on world load. function Files.CreateGetAdditionalWorldSearchPath() if(not Files.worldSearchPath) then Files.worldSearchPath = ParaIO.GetWritablePath().."temp/paraworld/temp/"; end return Files.worldSearchPath; end function Files.GetTempPath() if(not Files.projectTempPath) then Files.projectTempPath = ParaIO.GetWritablePath().."temp/"; end return Files.projectTempPath; end -- this is called when world exits function Files.ClearWorldSearchPaths() Files.worldSearchPath = nil; end -- @param filename: the filename maybe relative to the current world or the SDK root. -- in case it is relative to the world, we will return a path relative to SDK root. -- @param search_folder: if nil, it is current world directory, otherwise, one can specify an additional search folder in addition to current world directory. -- such as "Texture/blocks/human/" -- @return return file relative to SDK root. or nil, if no file is found. function Files.GetWorldFilePath(any_filename, search_folder, bCache) if(any_filename) then -- this fix a error that some user frequently appending / to file name. if(any_filename:match("^/\\")) then any_filename = any_filename:gsub("^/\\+", ""); end search_folder = search_folder or Files.worldSearchPath if(not ParaIO.DoesAssetFileExist(any_filename, true)) then local filename = GameLogic.GetWorldDirectory()..any_filename; if(ParaIO.DoesAssetFileExist(filename, true)) then any_filename = filename; elseif(search_folder) then local filename = search_folder..any_filename; if(ParaIO.DoesAssetFileExist(filename, true)) then any_filename = filename; else any_filename = nil; end else if(GameLogic.isRemote) then -- if it is the remote world, we will create an empty file locally, and send a get file request to the server world. local filepath = Files:GetFileFromCache(any_filename); if(filepath) then any_filename = filepath; elseif(filepath == false) then any_filename = nil; else local ext = commonlib.Files.GetFileExtension(any_filename); if(ext == "bmax" or ext == "x" or ext == "fbx" or ext == "png" or ext == "jpg") then Files:AddFileToCache(any_filename, filename); ParaIO.CreateDirectory(filename); local file = ParaIO.open(filename, "w"); if(file:IsValid()) then file:close(); Files.GetRemoteWorldFile(any_filename); end any_filename = filename; else Files:AddFileToCache(any_filename, false); any_filename = nil; end end else -- LOG.std(nil, "debug", "Files", "can not file world file %s", filename) any_filename = nil; end end end return any_filename; end end -- one can check the result after 1 second -- @param any_filename: relative to world path. function Files.GetRemoteWorldFile(any_filename) GameLogic.GetPlayer():AddToSendQueue(Packets.PacketGetFile:new():Init(any_filename)); LOG.std(nil, "info", "Files", "fetching remote file: %s", any_filename) end -- check if file exists. -- @param filename: can be relative to current world or sdk root. function Files.FileExists(filename) return Files.GetWorldFilePath(filename) ~= nil; end -- this function is mostly used to locate a local file resource. -- @param filename: must be relative to world. -- @param bCheckExist: if true, we will only return non-nil filename if the file exist on disk. function Files.WorldPathToFullPath(filename, bCheckExist) if(filename) then if(not bCheckExist) then return GameLogic.GetWorldDirectory()..filename; else filename = GameLogic.GetWorldDirectory()..filename; if(ParaIO.DoesFileExist(filename, true)) then return filename; end end end end -- map from short path to long path Files.cache = {}; -- map from long path to the shortest path Files.reverse_cache = {}; Files.loadedAssetFiles = {}; -- call this function when world is loaded. function Files:ClearFindFileCache() self.reverse_cache = {}; self.cache = {}; self.loadedAssetFiles = {}; Files.ClearWorldSearchPaths() end -- this is usually used when user entered or left a complex closed room full of assets. -- one may expect 2 or 3 seconds stall on graphics function Files:SafeUnloadAllAssets() Files:UnloadAllUnusedAssets(10000) end local s_managers = {}; -- @param name: "ParaXManager" or "TextureManager" function Files:GetAssetManager(name) if(s_managers[name]) then return s_managers[name]; else local assetManager = ParaEngine.GetAttributeObject():GetChild("AssetManager"); s_managers[name] = assetManager:GetChild(name) return s_managers[name]; end end -- @param MaxRefCount: release all assets whose reference count it smaller than or equal to this value. default to 1. function Files:UnloadAllUnusedAssets(MaxRefCount) MaxRefCount = MaxRefCount or 1; local paraXManager = self:GetAssetManager("ParaXManager") for i=1, paraXManager:GetChildCount(0) do local attr = paraXManager:GetChildAt(i) if(attr:GetField("IsInitialized", false) and attr:GetField("RefCount", 1) <= MaxRefCount) then local filename = attr:GetField("name", ""); if(filename ~= "" and not self:IsFileAlwaysInMemory(filename)) then local ext = filename:match("%.(%w+)$"); if(ext) then ext = string.lower(ext) if(ext == "bmax" or ext == "x" or ext == "fbx") then ParaAsset.LoadParaX("", filename):UnloadAsset(); LOG.std(nil, "info", "Files", "unload unused asset file: %s", filename); end end end end end local textureManager = self:GetAssetManager("TextureManager") for i=1, textureManager:GetChildCount(0) do local attr = textureManager:GetChildAt(i) -- remove following line, for debugging texture reference count -- LOG.std(nil, "debug", "Files", "texture file: %s, Inited: %s, Ref:%d", attr:GetField("name", ""), tostring(attr:GetField("IsInitialized", false)), attr:GetField("RefCount", 1)); if(attr:GetField("IsInitialized", false) and attr:GetField("RefCount", 1) <= MaxRefCount) then local filename = attr:GetField("name", ""); if(filename ~= "" and not self:IsFileAlwaysInMemory(filename)) then local ext = filename:match("%.(%w+)$"); -- also release http textures if(not ext and filename:match("^https?://")) then ext = "http"; end if(ext) then ext = string.lower(ext) if(ext == "jpg" or ext == "png" or ext == "dds" or ext == "http") then ParaAsset.LoadTexture("", filename, 1):UnloadAsset(); LOG.std(nil, "info", "Files", "unload unused asset file: %s", filename); end end end end end end function Files:AddAlwaysInMemoryFile(filename) alwaysInMemoryFiles[filename] = true; end function Files:IsFileAlwaysInMemory(filename) return alwaysInMemoryFiles[filename or ""]; end -- for debugging only function Files:PrintAllAssets() local managers = {"TextureManager", "ParaXManager"} local initedList = {}; local uninitedList = {}; for _, managerName in ipairs(managers) do local manager = self:GetAssetManager(managerName) for i=1, manager:GetChildCount(0) do local attr = manager:GetChildAt(i) local item = {managerName, attr:GetField("name", ""), attr:GetField("IsInitialized", false), attr:GetField("RefCount", 1)} if(item[3]) then initedList[#initedList + 1] = item else uninitedList[#uninitedList + 1] = item end end end LOG.std(nil, "info", "Files", "%d files are initied", #initedList); for _, item in ipairs(initedList) do LOG.std(nil, "info", "Files", "%s file: %s, Inited, Ref:%d", item[1], item[2], item[4]); end LOG.std(nil, "info", "Files", "%d files are UnInited", #uninitedList); for _, item in ipairs(uninitedList) do LOG.std(nil, "info", "Files", "%s file: %s, UnInited, Ref:%d", item[1], item[2], item[4]); end end function Files:IsAssetFileLoaded(filename) if(self.loadedAssetFiles[filename]) then return true; else if(ParaAsset.LoadParaX("", filename):GetAttributeObject():GetField("IsLoaded", false)) then self.loadedAssetFiles[filename] = true; return true; else return false; end end end -- this is usually used when user entered or left a complex closed room full of assets. -- one may expect 1 or 2 seconds stall on graphics function Files:SafeUnloadAllWorldAssets() Files:UnloadAllWorldAssets(10000) end -- this function is called before a new world is loaded. It will try to unload assets used in previous world. -- unload all assets in all world directory, where IsInitialized is true and RefCount is 1. -- @param MaxRefCount: release all assets whose reference count it smaller than or equal to this value. default to 1. function Files:UnloadAllWorldAssets(MaxRefCount) MaxRefCount = MaxRefCount or 1; local paraXManager = self:GetAssetManager("ParaXManager") for i=1, paraXManager:GetChildCount(0) do local attr = paraXManager:GetChildAt(i) if(attr:GetField("IsInitialized", false) and attr:GetField("RefCount", 1) <= MaxRefCount) then local filename = attr:GetField("name", ""); if(filename ~= "") then local ext = filename:match("worlds/DesignHouse/.*%.(%w+)$") or filename:match("temp/.*%.(%w+)$"); if(ext) then ext = string.lower(ext) if(ext == "bmax" or ext == "x" or ext == "fbx") then ParaAsset.LoadParaX("", filename):UnloadAsset(); LOG.std(nil, "info", "Files", "unload world asset file: %s", filename); end end end end end local textureManager = self:GetAssetManager("TextureManager") for i=1, textureManager:GetChildCount(0) do local attr = textureManager:GetChildAt(i) if(attr:GetField("IsInitialized", false) and attr:GetField("RefCount", 1) <= MaxRefCount) then local filename = attr:GetField("name", ""); if(filename ~= "") then local ext = filename:match("worlds/DesignHouse/.*%.(%w+)$") or filename:match("temp/.*%.(%w+)$"); -- also release http textures if(not ext and filename:match("^https?://")) then ext = "http"; end if(ext) then ext = string.lower(ext) if(ext == "jpg" or ext == "png" or ext == "dds" or ext == "http") then ParaAsset.LoadTexture("", filename, 1):UnloadAsset(); LOG.std(nil, "info", "Files", "unload world asset file: %s", filename); end end end end end end -- how many assets to unload during each step. -- @param nStep: default to 20. function Files:SetGarbageColectStep(nStep) Files.garbageCollectStep = nStep or 20; end function Files:GetGarbageColectStep() return Files.garbageCollectStep; end local nXfileGCIndex = 0; local nTexfileGCIndex = 0; -- call this function regularly to release unreferenced assets -- @param bModel: if not false, we will garbage collect model files -- @param bTexture: if not false, we will garbage collect texture files -- @see also: SetGarbageColectStep() function Files:GarbageCollect(bModel, bTexture) local nStep = self:GetGarbageColectStep() if(bModel~=false) then local count = 0; local paraXManager = self:GetAssetManager("ParaXManager") local nTotalCount = paraXManager:GetChildCount(0) for i=1, math.min(nStep*10, nTotalCount) do nXfileGCIndex = nXfileGCIndex + 1; local attr = paraXManager:GetChildAt(((i+nXfileGCIndex)%nTotalCount)+1) if(attr:GetField("IsInitialized", false) and attr:GetField("RefCount", 1) <= 1) then local filename = attr:GetField("name", ""); if(filename ~= "" and not self:IsFileAlwaysInMemory(filename)) then local ext = filename:match("%.(%w+)$"); if(ext) then ext = string.lower(ext) if(ext == "bmax" or ext == "x" or ext == "fbx") then ParaAsset.LoadParaX("", filename):UnloadAsset(); count = count + 1; LOG.std(nil, "debug", "Files", "GarbageCollect unused asset file: %s", filename); if(count >= nStep) then break; end end end end end end if(count > 0) then LOG.std(nil, "debug", "Files", "GarbageCollect %d/%d x files in this step", count, nTotalCount); end end if(bTexture~=false) then local count = 0; local textureManager = self:GetAssetManager("TextureManager") local nTotalCount = textureManager:GetChildCount(0) for i=1, math.min(nStep*10, nTotalCount) do nXfileGCIndex = nXfileGCIndex + 1; local attr = textureManager:GetChildAt(((i+nXfileGCIndex)%nTotalCount)+1) if(attr:GetField("IsInitialized", false) and attr:GetField("RefCount", 1) <= 1) then local filename = attr:GetField("name", ""); if(filename ~= "" and not self:IsFileAlwaysInMemory(filename)) then local ext = filename:match("%.(%w+)$"); -- also release http textures if(not ext and filename:match("^https?://")) then ext = "http"; end if(ext) then ext = string.lower(ext) if(ext == "jpg" or ext == "png" or ext == "dds" or ext == "http") then ParaAsset.LoadTexture("", filename, 1):UnloadAsset(); count = count + 1; LOG.std(nil, "debug", "Files", "GarbageCollect unused asset file: %s", filename); if(count >= nStep) then break; end end end end end end if(count > 0) then LOG.std(nil, "debug", "Files", "GarbageCollect %d/%d texture files in this step", count, nTotalCount); end end end function Files:GetFileCache() return self.cache; end -- cache all existing filename function Files:AddFileToCache(filename, filepath) self.cache[filename] = filepath; if(filepath) then local old_shortname = self.reverse_cache[filepath]; if(not old_shortname or #old_shortname > #filename) then self.reverse_cache[filepath] = filename; end end end -- get the full filename from cache of existing files. function Files:GetFileFromCache(filename) return self.cache[filename]; end -- get short filename from cache of existing files to their long file path. function Files:GetShortFileFromLongFile(filename) return self.reverse_cache[filename]; end -- get file path that is relative to current world directory. if not, it will return as it is. -- in most cases, we will store filenames using relative file path. But we have to pass to game engine the real path. function Files.GetRelativePath(filename) local world_dir = GameLogic.GetWorldDirectory() local file_dir = filename:sub(1, #world_dir); if(world_dir == file_dir) then return filename:sub(#world_dir+1) or ""; else return filename; end end -- we will try to find a file in world directory or global directory at all cost and save the result to cache -- so that the next time the same file is requried, we will return fast for both exist or non-exist ones. -- see also Files.FindFile() it differs with it for non-exist files, this function will also cache non-exist files. -- Files.FindFile does not cache non-exist files. -- @return it will return the file path or false if not found function Files.GetFilePath(filename) if(not filename) then return; end local filepath = Files:GetFileFromCache(filename); if(filepath or filepath == false) then return filepath; else return Files.FindFile(filename); end end -- find a given file by its file path. -- see also: Files.GetCachedFilePath() -- it will search filename, [worldpath]/filename, replace [worlds/DesignHouse/last] with current one. -- internally it will use a cache which only last for the current world, to accelerate for repeated calls. -- @param searchpaths: nil or additional search path seperated by ";". such as such as "Texture/blocks/human/" -- @return the real file or nil if not exist function Files.FindFile(filename, searchpaths) if(not filename) then return; end local filepath = Files:GetFileFromCache(filename); if(not filepath) then filepath = Files.GetWorldFilePath(filename, searchpaths); if(filepath) then Files:AddFileToCache(filename, filepath); else local old_worldpath, relative_path = filename:match("^(worlds/DesignHouse/[^/]+/)(.*)$"); if(relative_path and old_worldpath ~= GameLogic.GetWorldDirectory()) then local new_filename = GameLogic.GetWorldDirectory()..relative_path; filepath = Files.GetWorldFilePath(new_filename); if(filepath) then Files:AddFileToCache(filename, filepath); end end end end if(filepath) then return filepath; else -- cache non-exist Files:AddFileToCache(filename, false); end end -- resolve filename and return some information. -- @param filename: any file path such as an absolute path during a drag & drop event. -- @return { -- isExternalFile, -- boolean: if file is external to SDK -- isInWorldDirectory, -- boolean: if file is inside the current world directory. -- relativeToWorldPath, -- relativeToRootPath, -- only valid if isExternalFile is nil. -- isAbsoluteFilepath, -- boolean relativeToRootPath, -- filename, -- no directory -- } function Files.ResolveFilePath(filename) if(not filename) then return; end local info = {}; if(filename:match("^/") or filename:match(":")) then info.isAbsoluteFilepath = true; end -- check external file and compute relativeToRootPath filename = filename:gsub("\\", "/"); if(info.isAbsoluteFilepath) then local sdk_root = ParaIO.GetCurDirectory(0); if(filename:sub(1, #sdk_root) == sdk_root) then info.relativeToRootPath = filename:sub(#sdk_root+1, -1); else info.isExternalFile = true; end else info.relativeToRootPath = filename; end local world_root = GameLogic.GetWorldDirectory(); if(info.isAbsoluteFilepath and commonlib.Files.IsAbsolutePath(world_root)) then if(filename:sub(1, #world_root) == world_root) then info.relativeToWorldPath = filename:sub(#world_root+1, -1); info.isInWorldDirectory = true; end elseif(info.relativeToRootPath and info.relativeToRootPath:sub(1, #world_root) == world_root) then info.relativeToWorldPath = info.relativeToRootPath:sub(#world_root+1, -1); info.isInWorldDirectory = true; end info.filename = filename:match("([^/]+)$"); return info; end -- @param filename: must be relative to Root directory instead of world directory function Files.NotifyNetworkFileChange(filename) if(GameLogic.isRemote) then -- uploading file local relativeFilename = Files.GetRelativePath(filename); if(relativeFilename ~= filename) then local file = ParaIO.open(filename, "r") if(file:IsValid()) then local data = file:GetText(0, -1); file:close(); GameLogic.GetPlayer():AddToSendQueue(Packets.PacketPutFile:new():Init(relativeFilename, data)); LOG.std(nil, "info", "Files", "upload file: %s", relativeFilename) end end elseif(GameLogic.isServer) then local relativeFilename = Files.GetRelativePath(filename); if(relativeFilename ~= filename) then local servermanager = GameLogic.GetWorld():GetServerManager(); if(servermanager) then LOG.std(nil, "info", "Files", "notify all clients about changed file: %s", relativeFilename) servermanager:SendPacketToAllPlayers(Packets.PacketPutFile:new():Init(relativeFilename)); end end end end function Files:UnloadFoldAssets(foldpath) local assetManager = ParaEngine.GetAttributeObject():GetChild("AssetManager"); local textureManager = assetManager:GetChild("TextureManager") for i=1, textureManager:GetChildCount(0) do local attr = textureManager:GetChildAt(i) if(attr:GetField("IsInitialized", false) and attr:GetField("RefCount", 1) <= 1) then local filename = attr:GetField("name", ""); if filename ~= "" and string.find(filename, foldpath) then local ext = filename:match("%.(%w+)$"); -- also release http textures if(not ext and filename:match("^https?://")) then local localFilename = attr:GetField("LocalFileName", "") ext = localFilename:match("^temp/webcache/.*%.(%w+)$"); end if(ext) then ext = string.lower(ext) if(ext == "jpg" or ext == "png" or ext == "dds") then ParaAsset.LoadTexture("", filename, 1):UnloadAsset(); LOG.std(nil, "info", "Files", "unload unused asset file: %s", filename); end end end end end end -- find all files in the given world directory. -- @param output: output files, default to a new empty table -- @param folder: relative to world folder. default to "", which is root of world. values like "blocktemplates/" -- @param nMaxFileLevels: default to 2 -- @param nMaxFilesNum: default to 500 -- @param filter: a function({filename, filesize, writedate}) return true or false end. if nil, all files are returned. -- it can also be string like, "model", "bmax", "audio", "texture", "xml", "script" -- @return output: a table array containing relative to folder file name, such as below: -- {{filename,filesize,createdate,fileattr,accessdate,writedate,},} function Files:FindWorldFiles(output, folder, nMaxFileLevels, nMaxFilesNum, filterFunc) local rootPath = GameLogic.GetWorldDirectory() folder = folder or "" rootPath = rootPath..folder; local searchLevel = nMaxFileLevels or 2 local nMaxFilesNum = nMaxFilesNum or 500 local files = output or {}; local duplicates filterFunc = OpenFileDialog.GetFilterFunction(filterFunc) or filterFunc; local result = commonlib.Files.Find(files, rootPath, searchLevel, nMaxFilesNum, filterFunc or "*"); if(System.World.worldzipfile) then local filemap = {}; for i = 1, #result do filemap[result[i].filename] = true; end local zip_archive = ParaEngine.GetAttributeObject():GetChild("AssetManager"):GetChild("CFileManager"):GetChild(System.World.worldzipfile); local zipParentDir = zip_archive:GetField("RootDirectory", ""); if(zipParentDir~="") then if(rootPath:sub(1, #zipParentDir) == zipParentDir) then rootPath = rootPath:sub(#zipParentDir+1, -1) local result = commonlib.Files.Find({}, rootPath, searchLevel, nMaxFilesNum, ":.", System.World.worldzipfile); for i = 1, #result do -- skip duplicated names if(not filemap[result[i].filename]) then if(filterFunc and filterFunc(result[i])) then files[#files+1] = result[i]; end end end end end end return files; end -- find all files in folder relative to the root directory. both disk and zip files are searched. -- @param output: output files, default to a new empty table -- @param folder: relative to world folder. default to "", which is root of world. values like "blocktemplates/" -- @param nMaxFileLevels: default to 2 -- @param nMaxFilesNum: default to 500 -- @param filter: a function({filename, filesize, writedate}) return true or false end. if nil, all files are returned. -- it can also be string like, "model", "bmax", "audio", "texture", "xml", "script" -- @return output: a table array containing relative to folder file name, such as below: -- {{filename,filesize,createdate,fileattr,accessdate,writedate,},} function Files:FindSystemFiles(output, folder, nMaxFileLevels, nMaxFilesNum, filterFunc) local rootPath = folder or "" local searchLevel = nMaxFileLevels or 2 local nMaxFilesNum = nMaxFilesNum or 500 local files = output or {}; local duplicates filterFunc = OpenFileDialog.GetFilterFunction(filterFunc) or filterFunc; local result = commonlib.Files.Find(files, rootPath, searchLevel, nMaxFilesNum, filterFunc or "*"); local filemap = {}; for i = 1, #result do filemap[result[i].filename] = true; end local result = commonlib.Files.Find({}, rootPath, searchLevel, nMaxFilesNum, ":.", "*.zip"); for i = 1, #result do -- skip duplicated names if(not filemap[result[i].filename]) then if(filterFunc and filterFunc(result[i])) then files[#files+1] = result[i]; end end end return files; end
gpl-2.0
pakoito/ToME---t-engine4
game/modules/tome/data/maps/vaults/32-chambers.lua
3
1763
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org --32 chambers startx = 0 starty = 1 setStatusAll{no_teleport=true} rotates = {"default", "90", "180", "270", "flipx", "flipy"} defineTile('%', "WALL") defineTile('.', "FLOOR") defineTile('#', "HARDWALL") defineTile('X', "DOOR_VAULT") defineTile('*', "FLOOR", {random_filter={type="gem"}}) defineTile('L', "FLOOR", {random_filter={add_levels=15, tome_mod="gvault"}}) defineTile('D', "FLOOR", nil, {random_filter={name="greater multi-hued wyrm", add_levels=30}}) defineTile('c', "FLOOR", {random_filter={add_levels=15, tome_mod="vault"}}, {random_filter={add_levels=20}}) return { [[#########################]], [[X.c#..%..%..%..#L*#..#*L#]], [[#..#.c#.c#.c#.c#*D%.c%D*#]], [[##%##%#######%######%####]], [[#..#..#..%..%..#..%..#..#]], [[#.c%.c#.c#.c#.c#.c#.c%.c#]], [[########%########%#####%#]], [[#..%..#..#LL#..%..#..#..#]], [[#.c#.c%.c#DD#.c#.c#.c%.c#]], [[##%########%##%##########]], [[#..%..%..%..#..%..%..#..#]], [[#.c#.c#.c#.c#.c#.c#.c%.cX]], [[#########################]], }
gpl-3.0
derkling/dotfiles
awesome/lain/util/init.lua
7
6701
--[[ Lain Layouts, widgets and utilities for Awesome WM Utilities section Licensed under GNU General Public License v2 * (c) 2013, Luke Bonham * (c) 2010-2012, Peter Hofmann --]] local awful = require("awful") local beautiful = require("beautiful") local math = { sqrt = math.sqrt } local mouse = mouse local pairs = pairs local string = { gsub = string.gsub } local client = client local screen = screen local tonumber = tonumber local wrequire = require("lain.helpers").wrequire local setmetatable = setmetatable -- Lain utilities submodule -- lain.util local util = { _NAME = "lain.util" } -- Like awful.menu.clients, but only show clients of currently selected -- tags. function util.menu_clients_current_tags(menu, args) -- List of currently selected tags. local cls_tags = awful.tag.selectedlist(mouse.screen) -- Final list of menu items. local cls_t = {} if cls_tags == nil then return nil end -- For each selected tag get all clients of that tag and add them to -- the menu. A click on a menu item will raise that client. for i = 1,#cls_tags do local t = cls_tags[i] local cls = t:clients() for k, c in pairs(cls) do cls_t[#cls_t + 1] = { awful.util.escape(c.name) or "", function () c.minimized = false client.focus = c c:raise() end, c.icon } end end -- No clients? Then quit. if #cls_t <= 0 then return nil end -- menu may contain some predefined values, otherwise start with a -- fresh menu. if not menu then menu = {} end -- Set the list of items and show the menu. menu.items = cls_t local m = awful.menu.new(menu) m:show(args) return m end -- Magnify a client: Set it to "float" and resize it. function util.magnify_client(c) if not awful.client.floating.get(c) then awful.client.floating.set(c, true) local mg = screen[mouse.screen].geometry local tag = awful.tag.selected(mouse.screen) local mwfact = awful.tag.getmwfact(tag) local g = {} g.width = math.sqrt(mwfact) * mg.width g.height = math.sqrt(mwfact) * mg.height g.x = mg.x + (mg.width - g.width) / 2 g.y = mg.y + (mg.height - g.height) / 2 c:geometry(g) else awful.client.floating.set(c, false) end end -- Read the nice value of pid from /proc. local function get_nice_value(pid) local n = first_line('/proc/' .. pid .. '/stat') if n == nil then -- This should not happen. But I don't want to crash, either. return 0 end -- Remove pid and tcomm. This is necessary because tcomm may contain -- nasty stuff such as whitespace or additional parentheses... n = string.gsub(n, '.*%) ', '') -- Field number 17 now is the nice value. fields = split(n, ' ') return tonumber(fields[17]) end -- To be used as a signal handler for "focus" -- This requires beautiful.border_focus{,_highprio,_lowprio}. function util.niceborder_focus(c) local n = get_nice_value(c.pid) if n == 0 then c.border_color = beautiful.border_focus elseif n < 0 then c.border_color = beautiful.border_focus_highprio else c.border_color = beautiful.border_focus_lowprio end end -- To be used as a signal handler for "unfocus" -- This requires beautiful.border_normal{,_highprio,_lowprio}. function util.niceborder_unfocus(c) local n = get_nice_value(c.pid) if n == 0 then c.border_color = beautiful.border_normal elseif n < 0 then c.border_color = beautiful.border_normal_highprio else c.border_color = beautiful.border_normal_lowprio end end -- Non-empty tag browsing -- direction in {-1, 1} <-> {previous, next} non-empty tag function util.tag_view_nonempty(direction, sc) local s = sc or mouse.screen or 1 local scr = screen[s] for i = 1, #awful.tag.gettags(s) do awful.tag.viewidx(direction,s) if #awful.client.visible(s) > 0 then return end end end -- {{{ Dynamic tagging -- -- Add a new tag function util.add_tag(mypromptbox) awful.prompt.run({prompt="New tag name: "}, mypromptbox[mouse.screen].widget, function(text) if text:len() > 0 then props = { selected = true } tag = awful.tag.add(new_name, props) tag.name = text tag:emit_signal("property::name") end end) end -- Rename current tag -- @author: minism function util.rename_tag(mypromptbox) local tag = awful.tag.selected(mouse.screen) awful.prompt.run({prompt="Rename tag: "}, mypromptbox[mouse.screen].widget, function(text) if text:len() > 0 then tag.name = text tag:emit_signal("property::name") end end) end -- Move current tag -- pos in {-1, 1} <-> {previous, next} tag position function util.move_tag(pos) local tag = awful.tag.selected(mouse.screen) local idx = awful.tag.getidx(tag) if tonumber(pos) <= -1 then awful.tag.move(idx - 1, tag) else awful.tag.move(idx + 1, tag) end end -- Remove current tag (if empty) -- Any rule set on the tag shall be broken function util.remove_tag() local tag = awful.tag.selected(mouse.screen) local prevtag = awful.tag.gettags(mouse.screen)[awful.tag.getidx(tag) - 1] awful.tag.delete(tag, prevtag) end -- -- }}} -- On the fly useless gaps change function util.useless_gaps_resize(thatmuch) beautiful.useless_gap_width = tonumber(beautiful.useless_gap_width) + thatmuch awful.layout.arrange(mouse.screen) end -- On the fly global border change function util.global_border_resize(thatmuch) beautiful.global_border_width = tonumber(beautiful.global_border_width) + thatmuch awful.layout.arrange(mouse.screen) end -- Check if an element exist on a table function util.element_in_table(element, tbl) for _, i in pairs(tbl) do if i == element then return true end end return false end return setmetatable(util, { __index = wrequire })
mit
Laterus/Darkstar-Linux-Fork
scripts/zones/Silver_Sea_route_to_Nashmau/Zone.lua
1
1162
----------------------------------- -- -- Zone: Silver_Sea_route_to_Nashmau -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"] = nil; require("scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,menuchoice) --print("CSID: ",csid); --print("RESULT: ",menuchoice); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,menuchoice) --print("CSID: ",csid); --print("RESULT: ",menuchoice); end;
gpl-3.0
abasshacker/abbas00
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
M4J1D/Tabchi_robotsazTeam
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-3.0
NPLPackages/paracraft
script/kids/3DMapSystemUI/MsgProc_profile.lua
1
2043
--[[ Title: user profile message processor Author(s): LiXizhi Date: 2007/10/19 use the lib: ------------------------------------------------------------ NPL.load("(gl)script/kids/3DMapSystemUI/MsgProc_obj.lua"); Map3DSystem.SendMessage_profile({type = Map3DSystem.msg.USER_AddPoint, value=10}) ------------------------------------------------------------ ]] --[[ ------------------------------------------------- USER REWARD AND BONUS POINT SYSTEM Draft by LiXizhi ------------------------------------------------- For each user action, we will award the user some points. points can be converted to credits which may be used to purchase things on the server. The server will keep track of the user points, yet point is a client based system, users can easily fake them. Therefore, points is only relavent to the subscription business model. It has nothing to do with virtual currency,which is a different business model. Sometimes, we can use points to track user behaviors and award the user free things or unlock free levels, etc. Because of its client based nature, points can not be mixed with virtual currency. ]] -- scene:object window handler function Map3DSystem.OnProfileMessage(window, msg) if(msg.type == Map3DSystem.msg.USER_AddPoint) then ----------------------------------------------- -- user just earned some points. ----------------------------------------------- if(msg.value~=nil) then -- play sound ParaAudio.PlayUISound("Btn1"); -- TODO: some UI animation to inform user that he or she earns some points -- TODO: award the user randomly based on the points gain before. Such as every 50 points, a big sound, every 100 points, a silver medal, every 300 points, ... -- TODO: write to local database -- TODO: if total points is larger than a certain value, update to the remove server. end elseif(msg.type == Map3DSystem.msg.USER_GetProfile) then ----------------------------------------------- -- get profile ----------------------------------------------- --TODO: end end
gpl-2.0
DashingStrike/Automato-ATITD
scripts/fishing.lua
1
41069
-- Pin up your Lures menu 'Self Click, Skills, Fishing, Use Lure' (no other pinned up windows can exist) -- In Interface Options ensure 'Interface is Small' -- Should have (Chat-Related): 'Chat and Inventory can be minimized' AND 'Minimized chat-channels are still visible' AND 'Console Messages are Indented' -- You must have Main Chat tab showing at all times and window is long/wide enough so no lines don't wrap. -- Yes, this macro reads your MAIN chat screen, so make sure you read the above statement for it to work correctly. -- Each line of text must not scroll/wrap to the next line. If it does, then drag your chat window wider so it doesn't wrap. -- You want to make your chat very wide. Note: It is possible to see a LONG message like "Though you lost your lure, you did catch a 15 deben Orange Spongefish" -- Another long message is "You didn't catch anything. You also lost your lure. Try different lures and locations" -- At 1280x1024 your chat screen should reach at least to the mid point of your screen to avoid having a chat line wrap to next line, for a long message, like above. -- Higher resolutions may not have to reach quite to the mid point. -- You should ensure that your chat has timestamps -- ********** This macro writes to a log file (Fishlog.txt) for most actions, so you can review later! ****** -- ********** This also macro writes to a log file (Fishstats.txt) showing stats of your last fishing session, so you can review later! ****** --You can delete any of the log files if you wish. It will automatically create new ones if they dont exist. --The fishlog.txt file gets APPENDED everytime you fish, so the file can grow quite long over time. --The fishstats.txt file gets OVERWRITTEN everytime your gui program window updates, so it doesn't 'grow' over time. -- Almost all issues can be corrected by slightly adjusting the main chat window size and restarting. -- And also verify the lines aren't wrapping to the next line (if so, adjust chat screen to be wider until it is no longer wrapping down to next line). -- Note: These are currently refered to as Common Fish in the below 'SkipCommon' type of fishes (True or False), checkbox. --Abdju --Chromis --Catfish --Carp --Perch --Phagrus --Tilapia dofile("common.inc"); dofile("Fishing_Func.inc"); dofile("settings.inc"); SNum = 0; Sfish = ""; muteSoundEffects = false; TotalCasts = 5; -- Additional reporting in the log file -- Choose true or false. -- Note 'LogStrangeUnusual' and 'LogOdd' (below) overrides LogFails setting. ie if LogStrange true, then it would still log even if LogFails = False --If LogFails = false and LogStrangeUnusual or LogOdd = true, then failed catches those would still be included in the log file. SkipCommon = false; --Skips to next lure if fish caught is a common (Choose True or False). LogFails = false; -- Do you want to add Failed Catches to log file? 'Failed to catch anything' or 'No fish bit'. Note the log will still add an entry if you lost lure. LogStrangeUnusual = false; -- Do you want to add Strange and Unusual fish to the log file? Note the log will still add an entry if you lost lure. LogOdd = false; -- Do you want to add Odd fish to the log file? Note the log will still add an entry if you lost lure. AutoFillet = true; -- Do you want to auto-fillet fish if menu is pinned? function setOptions() local is_done = false; local count = 1; while not is_done do lsDoFrame(); checkBreak(); local y = 10; lsPrint(5, y, 0, 0.7, 0.7, 0xffffffff, "Casts per Lure?"); TotalCasts = readSetting("TotalCasts",TotalCasts); is_done, TotalCasts = lsEditBox("totalcasts", 120, y, 0, 40, 0, 0.8, 0.8, 0x000000ff, TotalCasts); TotalCasts = tonumber(TotalCasts); if not TotalCasts then is_done = false; lsPrint(190, y+2, 10, 0.7, 0.7, 0xFF2020ff, "<- MUST BE A NUMBER"); TotalCasts = 5; end writeSetting("TotalCasts",TotalCasts); y = y + 25; lsPrint(5, y, 0, 0.6, 0.6, 0xffffffff, "Casts per Lure? # Casts before switching lures."); y = y + 25; lsPrint(5, y, 0, 0.6, 0.6, 0xffffffff, " Self Click, Options, Chat-Related:"); y = y + 16; lsPrint(5, y, 0, 0.6, 0.6, 0xffff80ff, "Minimized chat-channels are still visible: CHECKED"); y = y + 16; lsPrint(5, y, 0, 0.6, 0.6, 0xffffffff, " Self Click, Options, Interface Options:"); y = y + 16; lsPrint(5, y, 0, 0.6, 0.6, 0xffff80ff, "Display fishing lures in sub-menus: CHECKED"); y = y + 16; lsPrint(5, y, 0, 0.6, 0.6, 0xc0c0ffff, "Main chat MUST be wide enough so no lines wrap!"); y = y + 25; AutoFillet = readSetting("AutoFillet",AutoFillet); AutoFillet = CheckBox(10, y, 10, 0xFFFFFFff, " Automatically Fillet Fish", AutoFillet, 0.7, 0.7); writeSetting("AutoFillet",AutoFillet); y = y + 20; muteSoundEffects = readSetting("muteSoundEffects",muteSoundEffects); muteSoundEffects = CheckBox(10, y, 10, 0xFFFFFFff, " Mute Sound Effects", muteSoundEffects, 0.7, 0.7); writeSetting("muteSoundEffects",muteSoundEffects); y = y + 20; SkipCommon = readSetting("SkipCommon",SkipCommon); SkipCommon = CheckBox(10, y, 10, 0xFFFFFFff, " Skip Common Fish", SkipCommon, 0.7, 0.7); writeSetting("SkipCommon",SkipCommon); y = y + 20; lsPrintWrapped(10, y, 0, lsScreenX, 0.6, 0.6, 0xffff80ff, "If Common Fish caught, then switch to next lure:"); y = y + 18 lsPrintWrapped(10, y, 0, lsScreenX, 0.6, 0.6, 0xffffffff, "(Abdju, Chromis, Catfish, Carp, Perch, Phagrus, Tilapia)"); y = y + 20; lsPrintWrapped(10, y, 0, lsScreenX, 0.6, 0.6, 0x80ff80ff, "Log entries are recorded to FishLog.txt in Automato/games/ATITD folder."); y = y + 35; LogFails = readSetting("LogFails",LogFails); LogFails = CheckBox(10, y, 10, 0xFFFFFFff, " Log Failed Catches (Log Everything)", LogFails, 0.7, 0.7); writeSetting("LogFails",LogFails); if LogFails then LogStrangeUnusual = false; LogOdd = false; else y = y + 20; LogStrangeUnusual = readSetting("LogStrangeUnusual",LogStrangeUnusual); LogStrangeUnusual = CheckBox(10, y, 10, 0xFFFFFFff, " Log Strange & Unusual Fish Seen ...", LogStrangeUnusual, 0.7, 0.7); writeSetting("LogStrangeUnusual",LogStrangeUnusual); y = y + 20; LogOdd = readSetting("LogOdd",LogOdd); LogOdd = CheckBox(10, y, 10, 0xFFFFFFff, " Log Odd Fish Seen ...", LogOdd, 0.7, 0.7); writeSetting("LogOdd",LogOdd); end if setResume then buttonName = "Set/Resume"; else buttonName = "Start"; end if lsButtonText(10, lsScreenY - 30, 0, 130, 0xFFFFFFff, buttonName) then is_done = 1; setResume = false; end if lsButtonText(lsScreenX - 110, lsScreenY - 30, 0, 100, 0xFFFFFFff, "End script") then error(quitMessage); end lsSleep(10); end return count; end function SetupLureGroup() TLures = {}; FirstLure=""; LastLure = ""; lsDoFrame(); statusScreen("Indexing Lures ...",nil, 0.7, 0.7); checkBreak() srReadScreen(); FindPin = srFindImage("UnPin.png"); if FindPin then --Click the pinup to refresh the lures window (in case a lure was lost earlier, it would still be showing on menu). --srClickMouseNoMove(FindPin[0]-8,FindPin[1]); -- clickAllImages(image_name, offsetX, offsetY, rightClick, tol) clickAllImages("UnPin.png",-8,0); lsSleep(100); srReadScreen(); -- Push Up arrow, just in case its current at bottom of list --DownPin = srFindImageInRange("Fishing/Menu_DownArrow.png",FindPin[0]-10,FindPin[1],50,500); DownPin = srFindImage("Fishing/Menu_DownArrow.png"); if DownPin then --UpArrow = srFindImageInRange("Fishing/Menu_UpArrow.png",FindPin[0]-10,FindPin[1],50,50); UpArrow = srFindImage("Fishing/Menu_UpArrow.png"); if UpArrow then srClickMouseNoMove(UpArrow[0]+5,UpArrow[1]+5); lsSleep(200); srReadScreen(); FirstLure = FindLureNameFirst(); LastLure=FindLureNameLast(); end else --No Arrows on lure menu? FirstLure = FindLureNameFirst(); LastLure=nil; end if not muteSoundEffects then lsPlaySound("moneycounter.wav"); end else error("Didn\'t find Lures pinned window - Self Click->Skills, Fishing -> Use Lure, PIN THIS WINDOW!"); end if LastLure ~= nil then --We have last lure, and arrows showing ChangeLureMenu = LastLure; FirstLurLoc = findText(FirstLure); LastLurLoc = findText(LastLure); lureCounter = 0; for i = 1, #Lures,1 do test = findText(Lures[i]); if test then --Add Lure lureCounter = lureCounter + 1; statusScreen("Indexing Lures [" .. lureCounter .. "]\n" .. Lures[i],nil, 0.7, 0.7); lsSleep(50); table.insert(TLures,Lures[i]); if Lures[i] == LastLure then --End of Menu, Use Down Arrow arrow=srFindImageInRange("Fishing/menu_downarrow.png",test[0],test[1]-5,175,50); if arrow then DownArrowLocs = arrow; srClickMouseNoMove(arrow[0]+5,arrow[1]+5); lsSleep(200); srReadScreen(); --else --error("no arrow found"); end end LastLureMenu = Lures[i]; end end --Reset Lure Menu --UpArrow = srFindImageInRange("Fishing/Menu_UpArrow.png",FindPin[0]-10,FindPin[1],50,50); UpArrow = srFindImage("Fishing/Menu_UpArrow.png"); if UpArrow then srClickMouseNoMove(UpArrow[0]+5,UpArrow[1]+5); lsSleep(200); end else --No arrows, just get lures lureCounter = 0; for i = 1, #Lures, 1 do test = findText(Lures[i]); if test then lureCounter = lureCounter + 1; statusScreen("Indexing Lures [" .. lureCounter .. "]\n" .. Lures[i],nil, 0.7, 0.7); lsSleep(50); table.insert(TLures,Lures[i]); end end end lsSleep(100); return TLures; end function FindLureNameFirst() for i = 1, #Lures, 1 do -- start from first line Lure = findText(Lures[i]); if Lure then return Lures[i] end end end function FindLureNameLast() for i = #Lures, 1, -1 do -- start from last line Lure = findText(Lures[i]); if Lure then return Lures[i] end end end function UseLure() checkBreak(); if #TLures == 0 then if not muteSoundEffects then lsPlaySound("fail.wav"); end error 'Can\'t find any lures on the pinned window. Did you run out of lures?' end CurrentLure = PlayersLures[CurrentLureIndex]; if #TLures == 1 then QCurrentLure = CurrentLure; QCurrentLureIndex = CurrentLureIndex; elseif LostLure == 1 and not lastCast then --Do Nothing, continue... else QCurrentLure = PlayersLures[QCurrentLureIndex]; end -- Uses lure according to CurrentLureIndex, which is used in PlayersLures which contains each lure the player has. lsDoFrame(); -- Blank the screen so next statusScreen messages isn't mixed/obscured with previous gui_refresh info on screen lsSleep(10); if LostLure == 1 and not lastCast then statusScreen("Lost Lure! | " .. lastLostLure .. "\nUsing same lure again!", nil, 0.7, 0.7); table.insert(lostlure_log, Time .. " | " .. lastLostLure .. " (" .. lastLostLureType .. ")"); lsSleep(1000); elseif LostLure == 1 then statusScreen("Lost Lure! | " .. lastLostLure .. "\nSwitching Lures | " .. QCurrentLure, nil, 0.7, 0.7); table.insert(lostlure_log, Time .. " | " .. lastLostLure .. " (" .. lastLostLureType .. ")"); lsSleep(1000); else statusScreen("Switching Lures | " .. QCurrentLure, nil, 0.7, 0.7); lsSleep(750); end srReadScreen(); --Only the first 30 lures will show in window, 31+ needs the down arrow clicked to be viewed, else click the up arrow (if more than 30 lures). if QCurrentLureIndex > 30 then down = srFindImage("Fishing/Menu_DownArrow.png"); srClickMouseNoMove(down[0]+5,down[1]+5); lsSleep(200); elseif #PlayersLures > 30 then up = srFindImage("Fishing/Menu_UpArrow.png"); srClickMouseNoMove(up[0]+5,up[1]+5); lsSleep(200); end srReadScreen(); if LostLure == 1 and not lastCast then lure = findText(PlayersLures[CurrentLureIndex]); else lure = findText(PlayersLures[QCurrentLureIndex]); end LostLure = 0; if lure then srClickMouseNoMove(lure[0]+12,lure[1]+5); lsSleep(200); srReadScreen(); -- Find Lure Type for i = 1, #Lure_Types, 1 do test = findText(Lure_Types[i]); if test then LureType = Lure_Types[i]; if not muteSoundEffects then lsPlaySound("high_rise.wav"); end --Click it! srClickMouseNoMove(test[0]+12,test[1]+5); break; end end end end function checkIfMain(chatText) for j = 1, #chatText do if string.find(chatText[j][2], "^%*%*", 0) then return true; end for k, v in pairs(Chat_Types) do if string.find(chatText[j][2], k, 0, true) then return true; end end end return false; end function ChatReadFish(value) --Find the last line of chat local chatText = getChatText(); if value then numCaught, fishType = string.match(lastLine2, "(%d+) deben ([^.]+)%."); -- Read next to last line of main chat else numCaught, fishType = string.match(lastLine, "(%d+) deben ([^.]+)%."); -- Read last line of main chat end if fishType then GrandTotalCaught = GrandTotalCaught + 1 Sfish = string.gsub(fishType, "%W", ""); SNum = numCaught GrandTotaldb = GrandTotaldb + SNum end return("[" .. CurrentLure .. " (" .. LureType .. ")] " .. Sfish .. " (" .. SNum .. "db)"); end function findchat() --Find the last line of chat checkBreak(); srReadScreen(); chatText = getChatText(); local onMain = checkIfMain(chatText); if not onMain then if not muteSoundEffects then lsPlaySound("timer.wav"); end end -- Wait for Main chat screen and alert user if its not showing while not onMain do checkBreak(); srReadScreen(); chatText = getChatText(); onMain = checkIfMain(chatText); sleepWithStatus(500, "Looking for Main chat screen...\n\nMake sure main chat tab is showing and that the window is sized, wide enough, so that no lines wrap to next line.\n\nAlso if you main chat tab is minimized, you need to check Options, Interface Option, Minimized chat-channels are still visible.", nil, 0.7, 0.7); end while #chatText < 2 do checkBreak(); srReadScreen(); chatText = getChatText(); sleepWithStatus(500, "Error: We must be able to read at least the last 2 lines of chat!\n\nCurrently we only see " .. #chatText .. " lines ...\n\nYou can also type something in main chat or manually fish, once or twice, to bypass this error!", nil, 0.7, 0.7); end --Read last line in chat lastLine = chatText[#chatText][2]; lastLineParse = string.sub(lastLine,string.find(lastLine,"m]")+3,string.len(lastLine)); --Read next to last line in chat lastLine2 = chatText[#chatText-1][2]; lastLineParse2 = string.sub(lastLine2,string.find(lastLine2,"m]")+3,string.len(lastLine2)); gui_refresh(); end function findClockInfo() srReadScreen(); clockWin = findText("Year", nil, REGION, NOPIN); if clockWin then lines = findAllText(nil, clockWin, nil, NOPIN); for i=1,#lines do lsPrintln("LINE " .. i .. " : " .. table.concat(lines[i], ",")); theDateTime = table.concat(lines[1], ",") -- Line 1 on the clock theDateTime = string.sub(theDateTime,string.find(theDateTime,",") + 1); regionCoords = table.concat(lines[2], ",") -- Line 2 on the clock regionCoords = string.sub(regionCoords,string.find(regionCoords,",") + 1); Coordinates = string.sub(regionCoords,string.find(regionCoords,":") + 2); stripYear = string.sub(theDateTime,string.find(theDateTime,",") + 2); Time = string.sub(stripYear,string.find(stripYear,",") + 2); stripYear = "," .. stripYear Date = string.sub(stripYear,string.find(stripYear,",") + 1, string.len(stripYear) - string.len(Time) - 2); --lsPrintln(theDateTime .. "\nCoords: " .. Coordinates .. " (" .. string.len(Coordinates) .. ")\nTime: " .. Time .. " (" .. string.len(Time) .. ")\nDate: " .. Date .. " (" .. string.len(Date) .. ")"); end end end function gui_refresh() checkBreak(); if GrandTotalCasts == 0 or GrandTotalCasts == 1 then DateBegin = Date; TimeBegin = Time; end if GrandTotalCaught < 10 then last10 = GrandTotalCaught .. "/10"; elseif GrandTotalCaught > 10 then last10 = "10/" .. GrandTotalCaught else last10 = 10; end --Stats (On Screen Display) --CurrentLureIndex out of PlayersLures winsize = lsGetWindowSize(); if #PlayersLures == 0 then if not muteSoundEffects then lsPlaySound("fail.wav"); end error 'Can\'t find any lures on the pinned window. Did you run out of lures?'; elseif #PlayersLures == 1 then CurrentLureIndex = 1; QCurrentLureIndex = 1; elseif CurrentLureIndex > #PlayersLures then CurrentLureIndex = #PlayersLures; QCurrentLureIndex = 1; end local y = 2; CurrentLure = PlayersLures[CurrentLureIndex]; QCurrentLure = PlayersLures[QCurrentLureIndex]; lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.5, 0.5, 0xc0c0ffff, Date .. " | " .. Time .. " | " .. Coordinates); nextLureChange = TotalCasts + 1 - castcount nextLureChangeMessageColor = 0xc0ffffff; if nextLureChange-1 <= 0 and LockLure then nextLureChangeMessageColor = 0xffff40ff; nextLureChangeMessage = "< LURE LOCKED! > Unlock when ready to change Lure!"; elseif nextLureChange-1 <= 0 and not LockLure then nextLureChangeMessageColor = 0xffff40ff; nextLureChangeMessage = "0 casts remaining ... Lure will change after this cast!"; elseif LockLure then nextLureChangeMessageColor = 0xffff40ff; nextLureChangeMessage = "< LURE LOCKED! > " .. nextLureChange-1 .. " casts remaining ..."; else nextLureChangeMessage = nextLureChange-1 .. " casts remaining until Next Lure change!"; end y = y + 12; lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.5, 0.5, 0xc0ffc0ff, "Current Lure: " .. CurrentLureIndex .. " of " .. #PlayersLures .. " " .. CurrentLure .. " (" .. LureType .. ")"); y = y + 12; lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.5, 0.5, nextLureChangeMessageColor, nextLureChangeMessage); y = y + 14; lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.5, 0.5, 0xfcad86ff, "Cast Timer: " .. round(castWait/1000, 1) .. " s"); y = y + 12; lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.5, 0.5, 0xfbc3abff, "Last Timer: " .. round(lastCastWait/1000, 1) .. " s"); lsSetCamera(0,0,lsScreenX*1.6,lsScreenY*1.6); if lsButtonText(160, y+20, 0, 20, 0xffffffff, "-" ) then QCurrentLureIndex = QCurrentLureIndex - 1; if QCurrentLureIndex < 1 then QCurrentLureIndex = #PlayersLures; end end if lsButtonText(187, y+20, 0, 20, 0xffffffff, "+" ) then QCurrentLureIndex = QCurrentLureIndex + 1 if QCurrentLureIndex > #PlayersLures then QCurrentLureIndex = 1; end end lsSetCamera(0,0,lsScreenX*1.0,lsScreenY*1.0); lsPrintWrapped(137, y-5, 0, lsScreenX - 20, 0.5, 0.5, 0xfFFFFFff, "Next Lure (" .. QCurrentLureIndex .. "):"); if skipLure or ((TotalCasts + 1 - castcount) <= 1 and not LockLure) then lsPrintWrapped(209, y-5, 0, lsScreenX - 20, 0.5, 0.5, 0xffffc0ff, QCurrentLure); else lsPrintWrapped(209, y-5, 0, lsScreenX - 20, 0.5, 0.5, 0xc0ffffff, QCurrentLure); end y = y + 13; lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.5, 0.5, 0xffffc0ff, "Last " .. last10 .. " Fish Caught:\n"); --Reset this string before showing last10 or allcaught fish below. Else the entries will multiply exponetially with entries from previous loops/call to this function last10caught = ""; allcaught = ""; lostlures = ""; if #gui_log_fish > 10 then table.remove(gui_log_fish,11); end for i = 1, #gui_log_fish,1 do lsPrintWrapped(10, y + (14*i), 0, lsScreenX - 18, 0.5, 0.5, 0xffffdfff, gui_log_fish[i]); end for i = 1, #gui_log_fish2,1 do allcaught = allcaught .. gui_log_fish2[i] .. "\n"; end for i = 1, #lostlure_log,1 do lostlures = lostlures .. lostlure_log[i] .. "\n"; end lsPrintWrapped(10, winsize[1]-130, 0, lsScreenX - 20, 0.5, 0.5, 0xffffffff, "Odd Fish Seen: " .. GrandTotalOdd); lsPrintWrapped(10, winsize[1]-118, 0, lsScreenX - 20, 0.5, 0.5, 0xffffffff, "Unusual Fish Seen: " .. GrandTotalUnusual); lsPrintWrapped(10, winsize[1]-106, 0, lsScreenX - 20, 0.5, 0.5, 0xffffffff, "Strange Fish Seen: " .. GrandTotalStrange); lsPrintWrapped(10, winsize[1]-94, 0, lsScreenX - 20, 0.5, 0.5, 0xFFFFFFff, "-----------------------------"); lsPrintWrapped(10, winsize[1]-82, 0, lsScreenX - 20, 0.5, 0.5, 0xc0ffc0ff, "Lures Switched: " .. GrandTotalLuresUsed-1); if lastLostLure ~= "" then lsPrintWrapped(10, winsize[1]-70, 0, lsScreenX - 20, 0.5, 0.5, 0xff8080ff, "Lures Lost: " .. GrandTotalLostLures .. " - Last: " .. lastLostLure .. " (" .. lastLostLureType .. ")"); else lsPrintWrapped(10, winsize[1]-70, 0, lsScreenX - 20, 0.5, 0.5, 0xff8080ff, "Lures Lost: " .. GrandTotalLostLures); end lsPrintWrapped(10, winsize[1]-58, 0, lsScreenX - 20, 0.5, 0.5, 0xFFFFFFff, "-----------------------------"); lsPrintWrapped(10, winsize[1]-46, 0, lsScreenX - 20, 0.5, 0.5, 0xc0ffffff, "Completed Casts: " .. GrandTotalCasts); lsPrintWrapped(10, winsize[1]-34, 0, lsScreenX - 20, 0.5, 0.5, 0xff8080ff, "Failed Catches: " .. GrandTotalFailed); lsPrintWrapped(10, winsize[1]-22, 0, lsScreenX - 20, 0.5, 0.5, 0xffffc0ff, "Fish Caught: " .. GrandTotalCaught .. " (" .. math.floor(GrandTotaldb) .. "db)"); lsSetCamera(0,0,lsScreenX*1.6,lsScreenY*1.6); if lsButtonText(lsScreenX + 40, lsScreenY + 20, 0, 130, 0xFFFFFFff, "Options") then lsDoFrame(); setResume = true; setOptions(); end if lsButtonText(lsScreenX + 40, lsScreenY + 50, 0, 130, 0xFFFFFFff, "End Script") then error(quitMessage); end if skipLure or ((TotalCasts + 1 - castcount) <= 1 and not LockLure) then skipLureText = "Next Lure"; skipLureTextColor = 0xffff40ff; else lastCast = false; skipLureText = "Next Lure"; skipLureTextColor = 0xFFFFFFff; end if skipLure or ((TotalCasts + 1 - castcount) <= 0 and not LockLure) then lastCast = true; else lastCast = false; end if not finishUp then if lsButtonText(lsScreenX + 40, lsScreenY + 120, 0, 130, 0xFFFFFFff, "Finish Up") then finishUp = true; end else if lsButtonText(lsScreenX + 40, lsScreenY + 120, 0, 130, 0xff8080ff, "Cancel ...") then finishUp = false; end end if lsButtonText(lsScreenX + 40, lsScreenY + 150, 0, 130, skipLureTextColor, skipLureText ) then if skipLure then skipLure = false; else skipLure = true; LockLure = false; end end if LockLure then LockLureColor = 0xffff40ff; LockLureText = "Cancel Lock!"; else LockLureColor = 0xFFFFFFff; LockLureText = "Lock Lure"; end if lsButtonText(lsScreenX + 40, lsScreenY + 180, 0, 130, LockLureColor, LockLureText ) then if LockLure then LockLure = false; else LockLure = true; skipLure = false; end end if #lostlure_log == 0 then lostlures = "*** No lures lost! ***"; end if #gui_log_fish2 == 0 then allcaught = "*** No fish caught! ***"; end WriteFishStats("Note this report is overwritten every time the macro runs. The stats are for last fishing session only!\nYou can safely delete this file, but it will be created the next time macro runs!\n\n\nStart Time: " .. DateBegin .. " @ " .. TimeBegin .. "\nEnd Time: " .. Date .. " @ " .. Time .. "\nLast Coordinates: " .. Coordinates .. "\n----------------------------------\nOdd Fish Seen: " .. GrandTotalOdd .. "\nUnusual Fish Seen: " .. GrandTotalUnusual .. "\nStrange Fish Seen: " .. GrandTotalStrange .. "\n----------------------------------\nLures Clicked: " .. GrandTotalLuresUsed .. "\nLures Lost: " .. GrandTotalLostLures .. " \n----------------------------------\nCasts: " .. GrandTotalCasts .. "\nFailed Catches: " .. GrandTotalFailed .. "\nFish Caught: " .. GrandTotalCaught .. " (" .. math.floor(GrandTotaldb) .. "db)\n----------------------------------\n\nAll lures lost this Session:\n\n" .. lostlures .. "\n\n\nAll fish caught this Session:\n\n".. allcaught); lsDoFrame(); lsSleep(10); end function doit() askForWindow("Fishing v2.0.7 (by Tutmault, revised by KasumiGhia, Cegaiel, and Skyfeather)\n\nMAIN chat tab MUST be showing and wide enough so that each line doesn't wrap.\n\nRequired: Pin Lures Menu (Self, Skills, Fishing, Use Lures). History will be recorded in FishLog.txt and stats in FishStats.txt.\n\nOptional: Pin Fillet Menu (Self, Skills, Fishing, Fillet). 'All Fish' will be clicked after each caught fish (empty windows are refreshed).\n\nSelf, Options, Interface Options (Menu:) \"Display available fishing lures in submenus\" MUST BE CHECKED! Egypt Clock /clockloc must be showing and unobstructed. Move clock window slightly if any problems.\n\nMost problems can be fixed by adjusting main chat window! Ensure that your chat displays timestamps"); ---------------------------------------- --Variables Used By Program -- Don't Edit Unless you know what you're doing! CurrentLure = ""; --Don't Edit gui_log_fish = {}; --Don't Edit, holds log display gui_log_fish2 = {}; --Don't Edit, holds log display log_fish = {}; --Don't Edit, holds log display lostlure_log = {}; --Don't Edit, holds log display CurrentLureIndex = 1; -- 1 = First Lure Player Owns in alphabetical order QCurrentLureIndex = 1; ChangeLureMenu=""; LastLureMenu=""; DownArrowLocs=nil; PlayersLures={}; --Don't Edit, Holds Current Player Lures castcount = 0; GrandTotalCaught = 0; GrandTotalCasts = 0; GrandTotaldb = 0; GrandTotalStrange = 0; GrandTotalOdd = 0; GrandTotalUnusual = 0; GrandTotalLuresUsed = 0; GrandTotalLostLures = 0; GrandTotalFailed = 0; lastLostLure = ""; LostLure = 0; LureType = ""; lastLostLureType = ""; lockLure = false; skipLure = false; lastCastWait = 0; castWait = 0; ---------------------------------------- setOptions(); PlayersLures = SetupLureGroup(); -- Fetch the list of lures from pinned lures window lsSleep(1000); -- Just a delay to let the sound effect finishing playing, not needed... findClockInfo(); while not Time do checkBreak(); findClockInfo(); sleepWithStatus(1000, "Can not find Clock!\n\nMove your clock slightly.\n\nMacro will resume once found ...\n\nIf you do not see a clock, type /clockloc in chat bar."); end while 1 do checkBreak(); srReadScreen(); cast = srFindImage("fishicon.png"); OK = srFindImage("OK.png"); if ignoreOK then OK = nil; -- We got a popup box while examining isis ship pieces recently, prevent potential reindexing lures (No lure found, refreshing.. Below) end lsSleep(100) if not cast then if not muteSoundEffects then lsPlaySound("timer.wav"); end end while not cast do checkBreak(); srReadScreen(); cast = srFindImage("fishicon.png"); sleepWithStatus(500, "Can\'t find Fishing icon ..."); end if castcount == 0 or OK or skipLure then castcount = 1; skipLure = false; if #PlayersLures > 1 then LockLure = false; else LockLure = true; end if #PlayersLures > 1 and not OK then UseLure(); --Switch Lures GrandTotalLuresUsed = GrandTotalLuresUsed + 1; end if OK then srClickMouseNoMove(OK[0]+5,OK[1]+3); -- Close the popup OK button sleepWithStatus(1500,"No " .. QCurrentLure .. " lure found!\nRefreshing lure list ...", nil, 0.7, 0.7) PlayersLures = SetupLureGroup(); if QCurrentLureIndex > #PlayersLures or QCurrentLureIndex == 1 then QCurrentLureIndex = 2; CurrentLureIndex = 1; end UseLure(); --Switch Lures else CurrentLureIndex = QCurrentLureIndex; QCurrentLureIndex = QCurrentLureIndex + 1; end if QCurrentLureIndex > #PlayersLures and not OK then --Last Lure, Prepare to go to first lure in list ... QCurrentLureIndex = 1; CurrentLureIndex = #PlayersLures; end --update log gui_refresh(); elseif LostLure == 1 then UseLure(); -- Equip Same Lure again elseif castcount > TotalCasts and not LockLure then --Reset castcount=0; else --Cast checkBreak(); castWait = 0; findchat(); lastLineFound = lastLineParse; -- Record last line before casting lastLineFound2 = lastLineParse2; -- Record next to last line before casting srClickMouseNoMove(cast[0]+3,cast[1]+3); startTime = lsGetTimer(); ignoreOK = nil; while 1 do findchat(); OK = srFindImage("OK.png"); writeLastTwoLines = nil; noWriteLog = nil; overweight = nil; skipOkOnce = nil; -- Helps prevent premature break, from OK box while checking Isis ship debris lsSleep(100); checkBreak(); castWait = (lsGetTimer() - startTime); gui_refresh(); if not muteSoundEffects and castWait/1000 > 2.5 and castWait/1000 < 2.7 then lsPlaySound("fishingreel.wav"); end for k, v in pairs(Isis_List) do if string.find(lastLine, k, 0, true) then -- If we get a message in chat from examining test of isis ship pieces, then ignore message and ignore popup box -- This causes a short OK popup "Examining Relic", but then closes by itself. We don't want to confuse this for a popup from missing lure; ignore lastLineFound = lastLineParse; -- Re-Record last line (with new message) lastLineFound2 = lastLineParse2; -- Re-Record next to last line (with new message) ignoreOK = 1; noWriteLog = 1; end end if OK then skipOkOnce = 1; -- Prevents a premature break below from OK box while Examining Isis ship pieces, until next loop. Give a chance for ignoreOK to get recognized end for k, v in pairs(Ignore_List) do if string.find(lastLine, k, 0, true) or not string.find(lastLine, "^%*%*", 0) then -- If we get a message defined in Ignore_List (already fishing, item is from a forge, or no ** (player is speaking in main chat), then ignore lastLineFound = lastLineParse; -- Re-Record last line (with new message) lastLineFound2 = lastLineParse2; -- Re-Record next to last line (with new message) noWriteLog = 1; end end if (lastLineFound2 ~= lastLineParse2 or lastLineFound ~= lastLineParse) or (OK and not ignoreOK and not skipOkOnce) or ( (lsGetTimer() - startTime) > 20000 ) then lastCastWait = castWait; break; end end -- end while 1 do castcount = castcount + 1; GrandTotalCasts = GrandTotalCasts + 1; findClockInfo(); --Parse Chat CurrentLure = PlayersLures[CurrentLureIndex]; caughtFish = false; oddFound = false; strangeUnusualFound = false; for k, v in pairs(Chat_Types) do if string.find(lastLine, k, 0, true) then if v == "overweight" then if string.match(lastLine2, "(%d+) deben ([^.]+)%.") then caughtFish = true; -- This will force it to parse the next to last line, instead of last line for any caught fish end end if v == "achievement" then -- If last message was 'You have achieved: Caught a blah blah', then caughtFish = true, parse the next to last line for fish caught -- Also set bool to record both lines in log writeLastTwoLines = 1; caughtFish = true; -- This will force it to parse the next to last line, instead of last line for any caught fish end if v == "alreadyfishing" or (OK and not ignoreOK) then castcount = castcount - 1; GrandTotalCasts = GrandTotalCasts - 1; end if v == "lostlure" then if not muteSoundEffects then lsPlaySound("boing.wav"); end lastLostLure = CurrentLure; lastLostLureType = LureType; GrandTotalLostLures = GrandTotalLostLures + 1; LostLure = 1; --Reset, skip to next lure --castcount=0; end if v == "odd" then GrandTotalOdd = GrandTotalOdd + 1; if LogOdd then oddFound = true; end end if v == "strange" then GrandTotalStrange = GrandTotalStrange + 1; if LogStrangeUnusual then strangeUnusualFound = true; end end if v == "unusual" then GrandTotalUnusual = GrandTotalUnusual + 1; if LogStrangeUnusual then strangeUnusualFound = true; end end if v == "caught" or caughtFish then if v == "caught" then caughtFish = true; Fish = ChatReadFish(); -- Parse last line of main chat else Fish = ChatReadFish(1); -- Parse next to last line of main chat if not fishType then caughtFish = nil; else overweight=1; end end if caughtFish then --Last 10 fish caught that displays on GUI addlog = Time .. " | " .. Sfish .. " (" .. SNum .. "db) | " .. CurrentLure table.insert(gui_log_fish, 1, addlog); -- All fish caught that displays in fishstats.txt table.insert(gui_log_fish2, addlog); FishType = Sfish; if SkipCommon == true and LockLure == false then --FishType = string.sub(Fish,string.find(Fish,",") + 1); if FishType == "Abdju" or FishType == "Chromis" or FishType == "Catfish" or FishType == "Carp" or FishType == "Perch" or FishType == "Phagrus" or FishType == "Tilapia" then --Skip it castcount=0; end end --if not muteSoundEffects then --if FishType == "Abdju" or FishType == "Chromis" or FishType == "Catfish" or FishType == "Carp" or FishType == "Perch" or FishType == "Phagrus" or FishType == "Tilapia" then --lsPlaySound("cheer.wav"); --else --lsPlaySound("applause.wav"); --end --end filletFish(); -- Search for "All Fish" pinned up. If so, fillet. end end --Add more if v == "something" then statements here if needed end gui_refresh(); end if not caughtFish then GrandTotalFailed = GrandTotalFailed + 1; end if v == "lure" or v == "alreadyfishing" or noWriteLog or not string.find(lastLine, "^%*%*", 0) then -- Do nothing elseif overweight then WriteFishLog("[" .. Date .. ", " .. Time .. "] [" .. Coordinates .. "] [" .. CurrentLure .. " (" .. LureType .. ")] " .. lastLineParse2 .. "\n"); elseif writeLastTwoLines then WriteFishLog("[" .. Date .. ", " .. Time .. "] [" .. Coordinates .. "] [" .. CurrentLure .. " (" .. LureType .. ")] " .. lastLineParse2 .. "\n"); WriteFishLog("[" .. Date .. ", " .. Time .. "] [" .. Coordinates .. "] [" .. CurrentLure .. " (" .. LureType .. ")] " .. lastLineParse .. "\n"); elseif LogFails or caughtFish or oddFound or strangeUnusualFound then WriteFishLog("[" .. Date .. ", " .. Time .. "] [" .. Coordinates .. "] [" .. CurrentLure .. " (" .. LureType .. ")] " .. lastLineParse .. "\n"); end gui_refresh(); end if finishUp then lsPlaySound("Complete.wav"); error("Finished up, per your request!"); end gui_refresh(); end end function round(num, numDecimalPlaces) local mult = 10^(numDecimalPlaces or 0) return math.floor(num * mult + 0.5) / mult end function filletFish() if AutoFillet then -- Pin your Skills, Fishing, Fillet menu, and we will fillet fish every catch (so they don't go rotten). You need to have at least 1 whole fish in inventory for this menu to appear! srReadScreen(); emptyWindow = srFindImage("WindowEmpty.png"); fillet = findText("All Fish"); if emptyWindow then --refresh any empty windows; just in case a previous fillet All Fish caused window to become empty clickAllImages("WindowEmpty.png", 5, 5, nil, nil); lsSleep(150); end if fillet then clickAllText("All Fish"); end end end
mit
jsj2008/ValyriaTear
dat/maps/layna_forest/layna_forest_cave2_map.lua
4
94807
map_data = {} -- The number of rows, and columns that compose the map map_data.num_tile_cols = 64 map_data.num_tile_rows = 48 -- The tilesets definition files used. map_data.tileset_filenames = {} map_data.tileset_filenames[1] = "dat/tilesets/desert_cave_ground.lua" map_data.tileset_filenames[2] = "dat/tilesets/desert_cave_walls2.lua" map_data.tileset_filenames[3] = "dat/tilesets/desert_cave_walls.lua" -- The map grid to indicate walkability. 0 is walkable, 1 is not. map_data.map_grid = {} map_data.map_grid[0] = { 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[1] = { 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[2] = { 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,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, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[95] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } -- The tile layers. The numbers are indeces to the tile_mappings table. map_data.layers = {} map_data.layers[0] = {} map_data.layers[0].type = "ground" map_data.layers[0].name = "Background" map_data.layers[0][0] = { 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 1, 1, 1, 2, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][1] = { 1, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 2, 116, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 1, 2, 2, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][2] = { 0, 1, 2, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 17, 18, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 1, 2, 0, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][3] = { 1, 1, 0, 1, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, 2, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 2, 1, 1, 2, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 0, 1, 1, -1, -1 } map_data.layers[0][4] = { -1, 0, 1, 0, 2, 0, 0, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 2, 17, 18, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, 1, 0, 1, -1, -1 } map_data.layers[0][5] = { -1, -1, -1, -1, 2, 2, 0, 0, -1, -1, -1, -1, -1, 2, 0, 2, 2, -1, -1, -1, -1, -1, -1, -1, 1, 2, -1, -1, -1, -1, -1, -1, 2, 0, 1, 0, 0, 0, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 2, 2, 1, -1, -1 } map_data.layers[0][6] = { -1, -1, -1, -1, -1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 2, 0, 1, -1, -1, -1, -1, -1, -1, 0, 1, 0, 1, -1, -1, -1, -1, -1, -1, 0, 0, 2, 0, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 0, -1, -1 } map_data.layers[0][7] = { -1, -1, -1, -1, -1, 2, 2, 1, 2, 2, 0, 2, 1, 0, 2, 2, -1, -1, -1, -1, -1, -1, 0, 0, 2, 17, 18, 0, -1, -1, -1, -1, -1, -1, 0, 1, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 2, 1, -1, -1 } map_data.layers[0][8] = { -1, -1, -1, -1, -1, 2, 1, 16, 1, 1, 0, 1, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, 1, 1, 0, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 1, 2, 1, -1, -1 } map_data.layers[0][9] = { -1, -1, -1, -1, -1, 0, 1, 32, 2, 1, 1, 2, 2, 0, -1, -1, -1, -1, -1, -1, -1, 2, 1, 2, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 2, 0, 0, 1, -1, -1 } map_data.layers[0][10] = { -1, -1, -1, -1, -1, 0, 2, 2, 2, 2, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 0, 1, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, 2, 2, 1, 0, -1, -1 } map_data.layers[0][11] = { -1, -1, -1, -1, -1, 1, 0, 1, 0, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 0, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 0, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, 0, 0, 0, 16, 0, 2, -1, -1, -1 } map_data.layers[0][12] = { -1, -1, -1, -1, -1, 2, 2, 2, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 16, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 1, 0, 1, 2, 16, -1, -1, -1, -1, -1, -1, -1, 2, 1, 2, 1, 0, 1, 0, 0, 2, 2, 0, 32, 2, -1, -1, -1, -1 } map_data.layers[0][13] = { -1, -1, -1, -1, -1, 2, 1, 2, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 0, 32, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 0, 1, 1, 2, 1, 2, 0, 1, -1, -1, -1, -1 } map_data.layers[0][14] = { -1, -1, -1, -1, -1, -1, 0, 2, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 0, 2, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 0, 1, 1, 1, 2, 1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 1, 2, 1, 1, 2, 0, 1, 0, 0, -1, -1, -1, -1, -1 } map_data.layers[0][15] = { -1, -1, -1, -1, 2, 2, 2, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 2, 2, 0, 0, 0, 2, 119, -1, -1, -1, -1, -1, -1, -1, -1, 2, 0, 0, 2, 1, 0, 2, 1, 2, -1, -1, -1, -1, -1, -1 } map_data.layers[0][16] = { -1, -1, -1, -1, 0, 0, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 0, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 0, 0, 2, 2, 1, 0, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 1, 0, 0, 0, 1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][17] = { -1, -1, -1, -1, -1, 1, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 0, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 1, 0, 1, 0, 2, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][18] = { -1, -1, -1, -1, 1, 0, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 0, 0, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 1, 2, 2, 1, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][19] = { -1, -1, -1, 2, 0, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 2, 2, 0, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][20] = { -1, -1, -1, 2, 1, 1, 2, 1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 2, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 1, 2, 0, 0, 0, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][21] = { -1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 0, 0, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 1, 1, 2, 1, 0, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 2, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 0, 2, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 0, 1, 2, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, 2, 1, 1, 0, 0, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 1, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 17, 18, 1, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 1, 2, 1, 0, 1, 16, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][24] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 1, 0, 0, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 2, 1, 0, 2, 2, 32, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][25] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, 0, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 1, 0, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][26] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 2, 0, 1, 1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 0, 0, 1, 1, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][27] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 2, 0, 2, 1, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][28] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 1, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][29] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 2, 2, 0, 2, -1, -1, -1, -1, -1, -1, -1, 0, 2, 0, 16, 1, 0, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, 1, 2, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][30] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 32, 2, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][31] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 1, 1, 0, -1, -1, -1, -1, -1, -1, 1, 0, 1, 2, 0, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][32] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 2, 1, -1, -1, -1, -1, 1, 2, 2, 1, 1, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 150, -1, -1, -1, -1, -1, -1, 0, 2, 2, 2, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][33] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 16, 1, 0, -1, -1, -1, -1, 1, 2, 2, 2, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 113, 150, 0, 2, 0, 2, 2, 2, 2, 0, 1, 0, 0, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][34] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 32, 2, 1, -1, -1, -1, -1, -1, 1, 2, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 113, 1, 1, 1, 2, 0, 2, 1, 0, 0, 1, 1, 1, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][35] = { -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 0, -1, -1, -1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 2, 17, 18, 1, 0, 1, 0, -1, -1, 2, 2, 1, 16, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][36] = { 1, 0, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 1, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 1, 2, 1, 1, 0, 2, 0, -1, -1, -1, 2, 2, 32, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][37] = { 0, 2, 2, 1, 2, 2, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 2, 2, 2, 2, 0, -1, -1, -1, -1, -1, 2, 2, 2, 1, 1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][38] = { -1, 0, 2, 0, 0, 1, 1, 0, 0, 1, 1, 0, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 2, 1, 2, 1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][39] = { -1, -1, 2, 2, 2, 1, 2, 1, 0, 1, 2, 0, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 0, 2, 0, 0, -1, -1, -1, -1, -1 } map_data.layers[0][40] = { -1, -1, -1, -1, 0, 2, 2, 2, 0, 1, 1, 1, 0, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 0, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 2, 2, 0, 2, 0, -1, -1, -1 } map_data.layers[0][41] = { -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 0, 2, 2, 0, -1, -1, -1, -1, -1, 2, 0, 1, -1, -1, -1, -1, -1, -1, -1, 2, 0, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 0, 1, 1, 0, 1, -1, -1, -1 } map_data.layers[0][42] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 0, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, 2, 1, 0, 2, 0, 2, 2, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 0, 1, 1, -1, -1, -1, -1 } map_data.layers[0][43] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 0, 0, 2, 0, 0, 2, 2, 2, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 0, 0, 0, 2, -1, -1, -1 } map_data.layers[0][44] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 2, 1, 1, 16, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 0, 2, 2, 1, -1, -1 } map_data.layers[0][45] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 32, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, 0, 2, 1, 1, -1, -1 } map_data.layers[0][46] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 1, 1, 0, -1, -1, -1 } map_data.layers[0][47] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 0, 1, -1, -1, -1, -1 } map_data.layers[1] = {} map_data.layers[1].type = "ground" map_data.layers[1].name = "Background 2" map_data.layers[1][0] = { -1, 166, 119, 100, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 120, 116, 165, 101, 177, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, 104, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][1] = { 192, 182, 135, 116, 119, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 136, -1, 181, 117, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 119, 149, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 149, -1, -1, -1, -1 } map_data.layers[1][2] = { 192, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1, -1, -1, -1, 97, 113, -1, -1, -1, -1, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 165, 177, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176, 113, 165, 103, -1, -1, -1 } map_data.layers[1][3] = { 192, -1, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1, -1, 97, 113, 136, -1, -1, -1, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, 181, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 136, 181, 119, 177, -1, -1 } map_data.layers[1][4] = { -1, -1, -1, -1, -1, -1, 135, 119, 103, -1, -1, -1, 97, 113, 136, -1, -1, -1, 209, -1, -1, -1, -1, -1, 98, 99, 149, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, 135, 193, -1, -1 } map_data.layers[1][5] = { -1, -1, -1, 208, -1, -1, -1, 135, 119, 99, 100, 101, 113, 136, -1, -1, -1, 209, -1, -1, -1, -1, -1, 98, 120, 116, 165, 103, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, 193, -1, -1 } map_data.layers[1][6] = { -1, -1, -1, -1, 208, -1, -1, -1, 135, 115, 116, 117, 136, -1, -1, -1, 193, -1, -1, -1, -1, 524, 98, 113, 136, -1, 181, 119, 129, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, -1, -1, -1, 193, -1, -1 } map_data.layers[1][7] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 209, -1, -1, -1, -1, -1, 113, 136, -1, -1, -1, 135, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, -1, -1, -1, 193, -1, -1 } map_data.layers[1][8] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, 209, -1, -1, -1, -1, -1, 98, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176, 113, 136, -1, -1, -1, 193, -1, -1 } map_data.layers[1][9] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, 209, -1, -1, -1, -1, -1, 98, 113, -1, -1, -1, -1, 145, -1, -1, -1, -1, -1, -1, -1, -1, 133, 133, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 150, 103, -1, -1, -1, -1, -1, 96, 136, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[1][10] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, 209, -1, -1, -1, -1, -1, -1, 128, 113, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 99, 100, 101, 149, -1, -1, -1, -1, -1, -1, -1, -1, 176, 166, 119, 103, 133, 133, 133, 97, 113, -1, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[1][11] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, 209, -1, -1, -1, -1, -1, -1, -1, 160, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176, 113, 115, 116, 117, 165, -1, -1, -1, -1, -1, -1, -1, -1, 192, 182, 135, 119, 100, 100, 100, 113, 136, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][12] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, 98, -1, -1, -1, -1, 145, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, 181, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, 135, 116, 116, 116, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][13] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, 98, 113, -1, -1, -1, -1, 145, -1, -1, -1, -1, -1, -1, -1, -1, 96, -1, -1, -1, -1, -1, 104, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1 } map_data.layers[1][14] = { -1, -1, -1, -1, -1, 96, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, 524, 113, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, -1, -1, -1, -1, -1, 119, 193, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 209, -1, -1, -1, -1 } map_data.layers[1][15] = { -1, -1, -1, -1, 176, 112, -1, -1, -1, 209, -1, -1, -1, -1, -1, 524, -1, 96, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, 136, -1, -1, -1, -1, -1, 135, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][16] = { -1, -1, -1, -1, 144, 136, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, 113, -1, -1, -1, -1, 145, -1, -1, -1, -1, -1, -1, -1, 176, 113, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][17] = { -1, -1, -1, -1, 96, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, 98, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][18] = { -1, -1, -1, 128, 166, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, 97, 113, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 96, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][19] = { -1, -1, -1, 192, 182, -1, -1, -1, 209, -1, -1, -1, -1, -1, 150, 113, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 99, 113, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 133, 133, 133, 133, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][20] = { -1, -1, -1, 192, -1, -1, -1, 193, -1, -1, -1, -1, -1, 98, 166, 136, -1, -1, -1, 145, -1, -1, -1, -1, -1, -1, -1, 176, 113, 115, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 150, 100, 100, 100, 100, 100, 100, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][21] = { -1, -1, -1, 208, -1, -1, -1, 209, -1, -1, -1, -1, 128, 112, 182, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176, 166, 116, 116, 116, 116, 116, 116, 119, 177, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, 136, -1, -1, -1, -1, 145, -1, -1, -1, -1, -1, -1, -1, 176, 113, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 182, -1, -1, -1, -1, -1, -1, 135, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 144, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][24] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][25] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, -1, -1, 134, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][26] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 99, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176, 113, 136, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][27] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 128, 166, 115, 119, 103, -1, -1, -1, -1, -1, -1, -1, -1, 96, 136, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][28] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 182, -1, 135, 119, 103, -1, -1, -1, -1, -1, -1, 176, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][29] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, 136, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][30] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, -1, -1, -1, -1, 135, 119, 129, -1, -1, -1, -1, -1, 96, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][31] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 103, -1, -1, -1, -1, 176, 166, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 133, 133, 133, 133, 97, 113, 136, -1, -1, -1, 104, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][32] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 119, -1, -1, -1, -1, 192, 182, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 99, 100, 101, 100, 100, 113, 136, -1, -1, -1, -1, 119, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][33] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 149, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176, 166, 115, 116, 117, 116, 116, 136, -1, -1, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][34] = { -1, 150, 99, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 165, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 182, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][35] = { 176, 166, 115, 119, 101, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 181, 119, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][36] = { 192, 182, -1, 135, 117, 119, 100, 100, 103, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, 135, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][37] = { 192, -1, -1, -1, -1, 135, 116, 116, 119, 100, 101, 100, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1, -1, -1 } map_data.layers[1][38] = { -1, -1, -1, -1, -1, -1, -1, -1, 135, 116, 117, 116, 119, 149, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, 165, 129, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1, -1 } map_data.layers[1][39] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 165, -1, -1, -1, -1, -1, -1, -1, 98, 103, -1, -1, -1, -1, -1, -1, -1, 97, 113, 136, 181, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 119, 103, -1, -1, -1, -1 } map_data.layers[1][40] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 181, 193, -1, -1, -1, -1, -1, 128, 166, 119, 102, -1, -1, -1, -1, -1, 98, 113, 136, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 119, 193, -1, -1, -1 } map_data.layers[1][41] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, 192, 182, 135, 119, 100, 101, 99, 102, 98, 113, 136, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, 135, 193, -1, -1, -1 } map_data.layers[1][42] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, 135, 116, 117, 115, 116, 114, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 104, -1, -1, -1 } map_data.layers[1][43] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, 165, 177, -1, -1 } map_data.layers[1][44] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 181, 193, -1, -1 } map_data.layers[1][45] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[1][46] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 104, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][47] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 113, -1, -1, 119, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2] = {} map_data.layers[2].type = "ground" map_data.layers[2].name = "Background 3" map_data.layers[2][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 227, -1, 226, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 145, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 227, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 128, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 145, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 227, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][24] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][25] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][26] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][27] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][28] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][29] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][30] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 194, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][31] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 226, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][32] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 194, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][33] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 226, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][34] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][35] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][36] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][37] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][38] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][39] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][40] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][41] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][42] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 232, 233, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][43] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 248, 249, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][44] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][45] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][46] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][47] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3] = {} map_data.layers[3].type = "sky" map_data.layers[3].name = "Sky" map_data.layers[3][0] = { 176, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 210, 211, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][1] = { 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 226, 227, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][2] = { 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 179, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][3] = { 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1 } map_data.layers[3][4] = { 208, 179, 179, 180, -1, -1, -1, -1, -1, 133, 133, 133, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, 193, -1, -1 } map_data.layers[3][5] = { -1, -1, -1, -1, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, 193, -1, -1 } map_data.layers[3][6] = { -1, -1, -1, -1, -1, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[3][7] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, 208, 179, 179, 179, 179, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[3][8] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[3][9] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[3][10] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[3][11] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, 195, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 177, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1 } map_data.layers[3][12] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 227, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1 } map_data.layers[3][13] = { -1, -1, -1, -1, -1, 192, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1 } map_data.layers[3][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 226, 177, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1 } map_data.layers[3][15] = { -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1 } map_data.layers[3][16] = { -1, -1, -1, -1, 192, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, 208, 179, 179, 179, 179, 179, 179, 179, 209, -1, -1, -1, -1, -1, -1 } map_data.layers[3][17] = { -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][18] = { -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][19] = { -1, -1, -1, 192, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][20] = { -1, -1, -1, 192, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][21] = { -1, -1, -1, -1, 179, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 180, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][24] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 180, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][25] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, 179, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][26] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 179, 179, 180, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][27] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][28] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][29] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][30] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][31] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][32] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, 180, -1, -1, -1, -1, 129, -1, -1, -1, 192, -1, -1, -1, -1, 178, 179, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][33] = { -1, -1, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, 180, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][34] = { -1, -1, -1, -1, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, 180, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][35] = { -1, -1, -1, -1, -1, -1, 133, 133, -1, -1, -1, -1, -1, -1, -1, 160, 180, -1, -1, -1, 129, -1, -1, 208, 179, 179, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, 208, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][36] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 133, 133, -1, -1, -1, -1, 144, -1, -1, -1, 145, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][37] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, 180, -1, 178, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 179, 179, 179, 179, 179, 179, 179, 209, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][38] = { 208, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 160, 179, 161, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][39] = { -1, 208, 179, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 177, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][40] = { -1, -1, -1, 208, 179, 180, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 133, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, 177, -1, -1, -1 } map_data.layers[3][41] = { -1, -1, -1, -1, -1, 208, 179, 179, 179, 179, 179, 180, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, 193, -1, -1, -1 } map_data.layers[3][42] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 179, 179, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 226, 227, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][43] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 179, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][44] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 179, 179, 179, 180, -1, -1, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[3][45] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 180, -1, -1, 178, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, 193, -1, -1 } map_data.layers[3][46] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, 178, 209, -1, -1 } map_data.layers[3][47] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 179, 179, 179, 209, -1, -1, -1 }
gpl-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/NplMod/NplModConfig.lua
1
1512
--[[ Title: NplModConfig Author(s): leio Date: 2021/1/7 Desc: define nplm config use the lib: ------------------------------------------------------------ local NplModConfig = NPL.load("(gl)script/apps/Aries/Creator/Game/NplMod/NplModConfig.lua"); ------------------------------------------------------------ --]] NPL.load("(gl)script/ide/System/Core/ToolBase.lua"); local NplModConfig = commonlib.inherit(commonlib.gettable("System.Core.ToolBase"), NPL.export()); function NplModConfig:ctor() self.name = nil; -- global name for all modules self.version = nil; self.description = nil; self.dependencies = {}; end function NplModConfig:parse(object) if(not object)then return end self.name = object.name; self.version = object.version; self.description = object.description; -- clear dependencies self.dependencies = {}; if(object.dependencies)then for k,v in ipairs(object.dependencies) do self.dependencies[k] = commonlib.copy(v); end end end function NplModConfig:getDepByIndex(index) return self.dependencies[index]; end function NplModConfig:getDepLen() return #self.dependencies; end function NplModConfig:toJson() local object = {}; object.name = self.name; object.version = self.version; object.description = self.description; object.dependencies = {}; for k,v in ipairs(self.dependencies) do object.dependencies[k] = commonlib.copy(v); end return object; end
gpl-2.0
fegimanam/best
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
fmassa/nn
SpatialUpSamplingNearest.lua
36
1914
local SpatialUpSamplingNearest, parent = torch.class('nn.SpatialUpSamplingNearest', 'nn.Module') --[[ Applies a 2D up-sampling over an input image composed of several input planes. The upsampling is done using the simple nearest neighbor technique. The Y and X dimensions are assumed to be the last 2 tensor dimensions. For instance, if the tensor is 4D, then dim 3 is the y dimension and dim 4 is the x. owidth = width*scale_factor oheight = height*scale_factor --]] function SpatialUpSamplingNearest:__init(scale) parent.__init(self) self.scale_factor = scale if self.scale_factor < 1 then error('scale_factor must be greater than 1') end if math.floor(self.scale_factor) ~= self.scale_factor then error('scale_factor must be integer') end self.inputSize = torch.LongStorage(4) self.outputSize = torch.LongStorage(4) self.usage = nil end function SpatialUpSamplingNearest:updateOutput(input) if input:dim() ~= 4 and input:dim() ~= 3 then error('SpatialUpSamplingNearest only support 3D or 4D tensors') end -- Copy the input size local xdim = input:dim() local ydim = input:dim() - 1 for i = 1, input:dim() do self.inputSize[i] = input:size(i) self.outputSize[i] = input:size(i) end self.outputSize[ydim] = self.outputSize[ydim] * self.scale_factor self.outputSize[xdim] = self.outputSize[xdim] * self.scale_factor -- Resize the output if needed if input:dim() == 3 then self.output:resize(self.outputSize[1], self.outputSize[2], self.outputSize[3]) else self.output:resize(self.outputSize) end input.nn.SpatialUpSamplingNearest_updateOutput(self, input) return self.output end function SpatialUpSamplingNearest:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input) input.nn.SpatialUpSamplingNearest_updateGradInput(self, input, gradOutput) return self.gradInput end
bsd-3-clause
pakoito/ToME---t-engine4
game/modules/tome/data/general/npcs/xorn.lua
3
7595
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Talents = require("engine.interface.ActorTalents") newEntity{ define_as = "BASE_NPC_XORN", type = "elemental", subtype = "xorn", display = "X", color=colors.UMBER, blood_color = colors.UMBER, combat = { dam=resolvers.levelup(resolvers.mbonus(46, 15), 1, 0.8), atk=15, apr=15, dammod={str=0.8} }, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 }, resolvers.drops{chance=100, nb=1, {type="money"} }, resolvers.drops{chance=60, nb=1, {type="money"} }, resolvers.drops{chance=40, nb=1, {type="money"} }, can_pass = {pass_wall=20}, infravision = 10, life_rating = 12, max_stamina = 90, rank = 2, size_category = 4, autolevel = "warrior", ai = "dumb_talented_simple", ai_state = { ai_target="target_player_radius", ai_move="move_complex", sense_radius=6, talent_in=3, }, dont_pass_target = true, stats = { str=20, dex=8, mag=6, con=16 }, resists = { [DamageType.PHYSICAL] = 20, [DamageType.FIRE] = 50, }, no_breath = 1, confusion_immune = 1, poison_immune = 1, cut_immune = 1, stone_immune = 1, ingredient_on_death = "XORN_FRAGMENT", not_power_source = {arcane=true}, } newEntity{ base = "BASE_NPC_XORN", name = "umber hulk", color=colors.LIGHT_UMBER, desc = [[This bizarre creature has glaring eyes and large mandibles capable of slicing through rock.]], level_range = {10, nil}, exp_worth = 1, rarity = 1, max_life = resolvers.rngavg(100,120), combat_armor = 12, combat_def = 0, move_project = {[DamageType.DIG]=1}, resolvers.talents{ [Talents.T_MIND_DISRUPTION]={base=2, every=5, max=6}, }, } newEntity{ base = "BASE_NPC_XORN", name = "xorn", color=colors.UMBER, desc = [[A huge creature of the element Earth. Able to merge with its element, it has four huge arms protruding from its enormous torso.]], level_range = {15, nil}, exp_worth = 1, rarity = 1, max_life = resolvers.rngavg(130,140), combat_armor = 15, combat_def = 10, combat = { damtype=DamageType.ACID }, resolvers.talents{ [Talents.T_CONSTRICT]={base=4, every=7, max=8}, }, } newEntity{ base = "BASE_NPC_XORN", name = "xaren", color=colors.SLATE, desc = [[It is a tougher relative of the Xorn. Its hide glitters with metal ores.]], level_range = {15, nil}, exp_worth = 1, rarity = 3, max_life = resolvers.rngavg(130,140), combat_armor = 15, combat_def = 10, combat = { damtype=DamageType.ACID }, resolvers.talents{ [Talents.T_CONSTRICT]={base=4, every=7, max=8}, [Talents.T_RUSH]=2, }, } newEntity{ base = "BASE_NPC_XORN", name = "The Fragmented Essence of Harkor'Zun", color=colors.VIOLET, unique=true, resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/elemental_xorn_fragmented_harkor_zun.png", display_h=2, display_y=-1}}}, desc = [[Fragmented essence... maybe it'd be best if it stayed fragmented.]], level_range = {17, nil}, exp_worth = 0, rank = 3.5, size_category = 4, rarity = 50, max_life = 230, life_rating = 12, combat_armor = 15, combat_def = 10, combat = { damtype=DamageType.ACID }, timetravel_immune = 1, ai = "tactical", ai_tactic = resolvers.tactic"melee", stun_immune = 1, can_pass = {pass_wall=0}, -- We restore it after generation, to make sure it does not birth in walls -- Come in 5! on_added_to_level = function(self) self.add_max_life = self.max_life * 0.2 local all = {self} for i = 1, 4 do local x, y = util.findFreeGrid(self.x, self.y, 15, true, {[engine.Map.ACTOR]=true}) if x and y then local m = self:clone() m:removeAllMOs() m.on_added_to_level = nil m.x, m.y = nil, nil game.zone:addEntity(game.level, m, "actor", x, y) all[#all+1] = m end end for _, m in ipairs(all) do m.all_fragments = all m.can_pass = {pass_wall=20} -- Restore passwall end end, on_die = function(self, who) local nb_alive = 0 -- Buff others for _, m in ipairs(self.all_fragments) do if not m.dead then nb_alive = nb_alive + 1 game.logSeen(self, "#AQUAMARINE#%s absorbs the energy of the destroyed fragment!", self.name) m.max_life = m.max_life + m.add_max_life m:heal(m.add_max_life) m.inc_damage.all = (m.inc_damage.all or 0) + 20 end end -- Only one left? if nb_alive == 1 then local x, y for _, m in ipairs(self.all_fragments) do if not m.dead then x, y = m.x, m.y; m:die(who) end end local m = game.zone:makeEntityByName(game.level, "actor", "FULL_HARKOR_ZUN") if m then game.zone:addEntity(game.level, m, "actor", x, y) game.level.map:particleEmitter(x, y, 1, "teleport") game.logSeen(self, "#AQUAMARINE#%s is infused with all the energies of the fragments. The real Harkor'Zun is reconstituted!", m.name) end end end, resolvers.talents{ [Talents.T_CONSTRICT]=4, [Talents.T_RUSH]=2, }, } -- Does not appear randomly, it is summoned by killing the fragments newEntity{ base = "BASE_NPC_XORN", define_as = "FULL_HARKOR_ZUN", name = "Harkor'Zun", color=colors.VIOLET, unique=true, resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/elemental_xorn_harkor_zun.png", display_h=2, display_y=-1}}}, desc = [[A gigantic demon composed of elemental Earth, resembling a twisted Xaren but much, much larger. It doesn't seem pleased with your presence.]], level_range = {23, nil}, exp_worth = 2, rank = 3.5, size_category = 5, autolevel = "warriormage", stats = { str=20, dex=8, mag=25, con=16 }, max_life = 460, life_rating=24, mana_regen = 100, combat_armor = 20, combat_def = 10, combat = { dam=resolvers.mbonus(46, 30), atk=35, apr=18, dammod={str=1}, damtype=DamageType.ACID }, resists = { [DamageType.PHYSICAL] = 50, [DamageType.ACID] = 50, }, no_auto_resists = true, silence_immune = 1, stun_immune = 1, demon = 1, resolvers.drops{chance=100, nb=1, {unique=true} }, resolvers.drops{chance=100, nb=3, {ego_chance=100} }, ai = "tactical", ai_tactic = resolvers.tactic"melee", resolvers.talents{ [Talents.T_CONSTRICT]={base=4, every=7, max=8}, [Talents.T_RUSH]=4, [Talents.T_STONE_SKIN]={base=4, every=7, max=8}, [Talents.T_STRIKE]={base=4, every=7, max=8}, [Talents.T_EARTHQUAKE]={base=5, every=7, max=9}, [Talents.T_EARTHEN_MISSILES]={base=4, every=7, max=8}, [Talents.T_CRYSTALLINE_FOCUS]={base=4, every=7, max=8}, [Talents.T_VOLCANO]={base=2, every=7, max=4}, }, resolvers.inscriptions(1, {"shielding rune"}), resolvers.sustains_at_birth(), on_die = function(self) if profile.mod.allow_build.mage then game:setAllowedBuild("mage_geomancer", true) world:gainAchievement("GEOMANCER", game.player) local p = game.party:findMember{main=true} if p.descriptor.subclass == "Archmage" or p.descriptor.subclass == "Arcane Blade" then if p:knowTalentType("spell/stone") == nil then p:learnTalentType("spell/stone", false) p:setTalentTypeMastery("spell/stone", p.descriptor.subclass == "Archmage" and 1.3 or 1.1) end end end end, }
gpl-3.0
Joshalexjacobs/fantastic-guacamole
humpCamera.lua
1
6430
--[[ Copyright (c) 2010-2015 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local _PATH = (...):match('^(.*[%./])[^%.%/]+$') or '' local cos, sin = math.cos, math.sin local camera = {} camera.__index = camera -- Movement interpolators (for camera locking/windowing) camera.smooth = {} function camera.smooth.none() return function(dx,dy) return dx,dy end end function camera.smooth.linear(speed) assert(type(speed) == "number", "Invalid parameter: speed = "..tostring(speed)) return function(dx,dy, s) -- normalize direction local d = math.sqrt(dx*dx+dy*dy) local dts = math.min((s or speed) * love.timer.getDelta(), d) -- prevent overshooting the goal if d > 0 then dx,dy = dx/d, dy/d end return dx*dts, dy*dts end end function camera.smooth.damped(stiffness) assert(type(stiffness) == "number", "Invalid parameter: stiffness = "..tostring(stiffness)) return function(dx,dy, s) local dts = love.timer.getDelta() * (s or stiffness) return dx*dts, dy*dts end end -- damped smoothing that only moves forward (right) function camera.smooth.forwardDamped(stiffness) assert(type(stiffness) == "number", "Invalid parameter: stiffness = "..tostring(stiffness)) return function(dx,dy, s) local dts = love.timer.getDelta() * (s or stiffness) if dx <= 0 then return dx*0, dy*dts else return dx*dts, dy*dts end end end local function new(x,y, zoom, rot, smoother) x,y = x or love.graphics.getWidth()/2, y or love.graphics.getHeight()/2 zoom = zoom or 1 rot = rot or 0 smoother = smoother or camera.smooth.none() -- for locking, see below return setmetatable({x = x, y = y, scale = zoom, rot = rot, smoother = smoother}, camera) end function camera:lookAt(x,y) self.x, self.y = x, y return self end function camera:move(dx,dy) self.x, self.y = self.x + dx, self.y + dy return self end function camera:position() return self.x, self.y end function camera:rotate(phi) self.rot = self.rot + phi return self end function camera:rotateTo(phi) self.rot = phi return self end function camera:zoom(mul) self.scale = self.scale * mul return self end function camera:zoomTo(zoom) self.scale = zoom return self end function camera:attach(x,y,w,h, noclip) x,y = x or 0, y or 0 w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight() self._sx,self._sy,self._sw,self._sh = love.graphics.getScissor() if not noclip then love.graphics.setScissor(x,y,w,h) end local cx,cy = x+w/2, y+h/2 love.graphics.push() love.graphics.translate(cx, cy) love.graphics.scale(self.scale) love.graphics.rotate(self.rot) love.graphics.translate(-self.x, -self.y) end function camera:detach() love.graphics.pop() love.graphics.setScissor(self._sx,self._sy,self._sw,self._sh) end function camera:draw(...) local x,y,w,h,noclip,func local nargs = select("#", ...) if nargs == 1 then func = ... elseif nargs == 5 then x,y,w,h,func = ... elseif nargs == 6 then x,y,w,h,noclip,func = ... else error("Invalid arguments to camera:draw()") end self:attach(x,y,w,h,noclip) func() self:detach() end -- world coordinates to camera coordinates function camera:cameraCoords(x,y, ox,oy,w,h) ox, oy = ox or 0, oy or 0 w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight() -- x,y = ((x,y) - (self.x, self.y)):rotated(self.rot) * self.scale + center local c,s = cos(self.rot), sin(self.rot) x,y = x - self.x, y - self.y x,y = c*x - s*y, s*x + c*y return x*self.scale + w/2 + ox, y*self.scale + h/2 + oy end -- camera coordinates to world coordinates function camera:worldCoords(x,y, ox,oy,w,h) ox, oy = ox or 0, oy or 0 w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight() -- x,y = (((x,y) - center) / self.scale):rotated(-self.rot) + (self.x,self.y) local c,s = cos(-self.rot), sin(-self.rot) x,y = (x - w/2 - ox) / self.scale, (y - h/2 - oy) / self.scale x,y = c*x - s*y, s*x + c*y return x+self.x, y+self.y end function camera:mousePosition(ox,oy,w,h) local mx,my = love.mouse.getPosition() return self:worldCoords(mx,my, ox,oy,w,h) end -- camera scrolling utilities function camera:lockX(x, smoother, ...) local dx, dy = (smoother or self.smoother)(x - self.x, self.y, ...) self.x = self.x + dx return self end function camera:lockY(y, smoother, ...) local dx, dy = (smoother or self.smoother)(self.x, y - self.y, ...) self.y = self.y + dy return self end function camera:lockPosition(x,y, smoother, ...) return self:move((smoother or self.smoother)(x - self.x, y - self.y, ...)) end function camera:lockWindow(x, y, x_min, x_max, y_min, y_max, smoother, ...) -- figure out displacement in camera coordinates x,y = self:cameraCoords(x,y) local dx, dy = 0,0 if x < x_min then dx = x - x_min elseif x > x_max then dx = x - x_max end if y < y_min then dy = y - y_min elseif y > y_max then dy = y - y_max end -- transform displacement to movement in world coordinates local c,s = cos(-self.rot), sin(-self.rot) dx,dy = (c*dx - s*dy) / self.scale, (s*dx + c*dy) / self.scale -- move self:move((smoother or self.smoother)(dx,dy,...)) end -- the module return setmetatable({new = new, smooth = camera.smooth}, {__call = function(_, ...) return new(...) end})
mit
osamaalbsraoy/osama_albsraoy1989
plugins/robot.lua
1
1957
--[[ # For More Information ....! # Developer : osama < @os_Aa23 > #Dev # our channel: @os_Aa23 ]] 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 '😊 اَلـبـِوتَ بأَلتأكيَدَ تمَ تشَغيِلهَ ب أَلمجموعـهِ ✔️👍🏻' end _config.disabled_channels[receiver] = false save_config() return "تَمِ ✔️ تشغـيَل البوَتَ في المَجمَوعـهَ 👍" end local function disable_channel( receiver ) if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[receiver] = true save_config() return "تَمِ ✔️ أطـفأءَ الـبوَتَ فـي أَلمجـموَعـهَ 👍🏻❌" end local function pre_process(msg) local receiver = get_receiver(msg) -- If sender is moderator then re-enable the channel --if is_sudo(msg) then if is_momod(msg) then if msg.text == "start bot" then enable_channel(receiver) end end if is_channel_disabled(receiver) then msg.text = "" end return msg end local function run(msg, matches) local receiver = get_receiver(msg) -- Enable a channel if matches[1] == 'start bot' then return enable_channel(receiver) end -- Disable a channel if matches[1] == 'stop bot' then return disable_channel(receiver) end end return { description = "Plugin to manage Bot.", usage = { "Bot on: enable BOT In a Group", "Bot off: disable Bot In a Group" }, patterns = { "^(start bot)", "^(stop bot)" }, run = run, privileged = true, --moderated = true, pre_process = pre_process }
gpl-2.0
pakoito/ToME---t-engine4
game/modules/tome/data/gfx/particles/stone_shards.lua
3
1495
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org base_size = 32 local starts = {} for i = 1, 4 do starts[#starts+1] = { a = math.rad(rng.range(0, 360)), r = rng.range(6, 20) } end -- Populate the beam based on the forks return { generator = function() local rad = rng.range(-3,3) local s = rng.table(starts) local ra = s.a local r = s.r return { life = 4, size = rng.range(4, 6), sizev = -0.1, sizea = 0, x = 2 * math.cos(ra), xv = 0, xa = 0, y = 2 * math.sin(ra), yv = 0, ya = 0, dir = 0, dirv = 0, dira = 0, vel = 0, velv = 0, vela = 0, r = 0xD7/255, rv = 0, ra = 0, g = 0x8E/255, gv = 0, ga = 0, b = 0x45/255, bv = 0, ba = 0, a = rng.range(100, 220)/255, av = 0.05, aa = 0, } end, }, function(self) self.ps:emit(30 * 4) end, 4*30*4
gpl-3.0
pakoito/ToME---t-engine4
game/modules/tome/data/zones/unremarkable-cave/npcs.lua
3
5035
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org load("/data/general/npcs/rodent.lua", rarity(0)) load("/data/general/npcs/vermin.lua", rarity(0)) load("/data/general/npcs/molds.lua", rarity(0)) load("/data/general/npcs/skeleton.lua", rarity(0)) load("/data/general/npcs/snake.lua", rarity(0)) load("/data/general/npcs/all.lua", rarity(0, 10)) local Talents = require("engine.interface.ActorTalents") newEntity{ define_as = "FILLAREL", type = "humanoid", subtype = "elf", unique = true, name = "Fillarel Aldaren", faction = "neutral", display = "@", color=colors.GOLD, resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/humanoid_elf_fillarel_aldaren.png", display_h=2, display_y=-1}}}, desc = [[An Elven woman. She wears a tight robe decorated with symbols of the Sun and the Moon and wields a staff.]], level_range = {25, nil}, exp_worth = 2, female = 1, max_life = 120, life_rating = 15, fixed_rating = true, positive_regen = 10, negative_regen = 10, rank = 4, size_category = 3, infravision = 10, stats = { str=10, dex=22, cun=25, mag=20, con=12 }, instakill_immune = 1, teleport_immune = 1, move_others=true, never_anger=true, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 }, equipment = resolvers.equip{ {type="weapon", subtype="staff", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true}, {type="armor", subtype="cloth", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true}, }, resolvers.drops{chance=100, nb=3, {tome_drops="boss"} }, resolvers.talents{ [Talents.T_MOONLIGHT_RAY]=4, [Talents.T_STARFALL]=5, [Talents.T_SHADOW_BLAST]=3, [Talents.T_SEARING_LIGHT]=4, [Talents.T_FIREBEAM]=4, [Talents.T_SUNBURST]=3, [Talents.T_HYMN_OF_SHADOWS]=2, [Talents.T_CHANT_OF_FORTITUDE]=2, }, resolvers.sustains_at_birth(), autolevel = "caster", ai = "dumb_talented_simple", ai_state = { talent_in=1, ai_move="move_astar" }, on_added = function(self) self.energy.value = game.energy_to_act self:useTalent(self.T_HYMN_OF_SHADOWS) self.energy.value = game.energy_to_act self:useTalent(self.T_CHANT_OF_FORTITUDE) end, on_die = function(self, who) game.player:hasQuest("strange-new-world"):fillarel_dies(self) end, seen_by = function(self, who) if not self.has_been_seen and who.player then self.seen_by = nil local Chat = require("engine.Chat") local chat = Chat.new("unremarkable-cave-bosses", self, who) chat:invoke() self.has_been_seen = true end end, can_talk = "unremarkable-cave-fillarel", can_talk_only_once = true, } newEntity{ define_as = "CORRUPTOR", type = "humanoid", subtype = "orc", unique = true, name = "Krogar", faction = "neutral", display = "@", color=colors.GREEN, resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/humanoid_orc_krogar.png", display_h=2, display_y=-1}}}, desc = [[An orc clad in mail armour, he wields a staff and looks menacing.]], level_range = {25, nil}, exp_worth = 2, max_life = 120, life_rating = 15, fixed_rating = true, positive_regen = 10, negative_regen = 10, rank = 4, size_category = 3, stats = { str=10, dex=22, cun=25, mag=20, con=12 }, instakill_immune = 1, teleport_immune = 1, move_others=true, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 }, equipment = resolvers.equip{ {type="weapon", subtype="staff", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true}, {type="armor", subtype="heavy", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true}, }, resolvers.drops{chance=100, nb=3, {tome_drops="boss"} }, resolvers.drops{chance=100, nb=1, {type="jewelry", subtype="orb", defined="ORB_MANY_WAYS"} }, resolvers.talents{ [Talents.T_ARMOUR_TRAINING]=2, [Talents.T_MOONLIGHT_RAY]=4, [Talents.T_STARFALL]=5, [Talents.T_SHADOW_BLAST]=3, [Talents.T_SEARING_LIGHT]=4, [Talents.T_FIREBEAM]=4, [Talents.T_SUNBURST]=3, [Talents.T_HYMN_OF_SHADOWS]=2, [Talents.T_CHANT_OF_FORTITUDE]=2, }, resolvers.sustains_at_birth(), autolevel = "caster", ai = "dumb_talented_simple", ai_state = { talent_in=1, ai_move="move_astar" }, on_die = function(self, who) game.player:hasQuest("strange-new-world"):krogar_dies(self) end, can_talk = "unremarkable-cave-krogar", }
gpl-3.0
eXhausted/Ovale
scripts/ovale_priest_spells.lua
1
15325
local OVALE, Ovale = ... local OvaleScripts = Ovale.OvaleScripts do local name = "ovale_priest_spells" local desc = "[7.0] Ovale: Priest spells" local code = [[ # Priest spells and functions. # Learned spells Define(borrowed_time 52798) SpellInfo(borrowed_time learn=1 level=10 specialization=discipline) Define(rapture 47536) SpellInfo(rapture learn=1 level=10 specialization=discipline) Define(surge_of_light 109186) SpellInfo(surge_of_light learn=1 level=45 specialization=discipline) SpellInfo(surge_of_light learn=1 level=45 specialization=holy) # Dummy spells Define(mindbender_tier18_2pc 999123040) SpellInfo(mindbender_tier18_2pc dummy_replace=123040 replace=mindbender) SpellInfo(mindbender_tier18_2pc cd=20) Define(shadowfiend_tier18_2pc 999034433) SpellInfo(shadowfiend_tier18_2pc dummy_replace=34433 replace=shadowfiend) SpellInfo(shadowfiend_tier18_2pc cd=20) Define(archangel 81700) SpellInfo(archangel cd=30 gcd=0 offgcd=1) SpellRequire(archangel unusable 1=buff,!evangelism_buff) SpellAddBuff(archangel archangel_buff=1) SpellAddBuff(archangel clear_thoughts_buff=1 itemset=T17 itemcount=4 specialization=discipline) SpellAddBuff(archangel evangelism_buff=0 if_spell=evangelism) Define(archangel_buff 81700) SpellInfo(archangel_buff duration=18) Define(auspicious_spirits_talent 21) Define(binding_heal 32546) SpellAddBuff(binding_heal serendipity_buff=1 if_spell=serendipity) Define(body_and_soul_talent 4) Define(borrowed_time_buff 59889) SpellInfo(borrowed_time_buff duration=6) Define(cascade_caster 121135) SpellInfo(cascade_caster cd=25 travel_time=1) Define(cascade_heal 121135) SpellInfo(cascade_heal cd=25 travel_time=1) Define(cascade_talent 16) Define(chakra_chastise 81209) SpellInfo(chakra_chastise cd=30 sharedcd=chakra) SpellInfo(chakra_chastise addcd=-20 if_spell=enhanced_chakras) SpellInfo(chakra_chastise unusable=1) SpellAddBuff(chakra_chastise chakra_chastise_buff=1) Define(chakra_chastise_buff 81209) Define(chakra_sanctuary 81206) SpellInfo(chakra_sanctuary cd=30 sharedcd=chakra) SpellInfo(chakra_sanctuary addcd=-20 if_spell=enhanced_chakras) SpellInfo(chakra_sanctuary unusable=1) SpellAddBuff(chakra_sanctuary chakra_sanctuary_buff=1) Define(chakra_sanctuary_buff 81206) Define(chakra_serenity 81208) SpellInfo(chakra_serenity cd=30 sharedcd=chakra) SpellInfo(chakra_serenity addcd=-20 if_spell=enhanced_chakras) SpellInfo(chakra_serenity unusable=1) SpellAddBuff(chakra_serenity chakra_serenity_buff=1) Define(chakra_serenity_buff 81208) Define(circle_of_healing 34861) SpellInfo(circle_of_healing cd=12) SpellInfo(circle_of_healing addcd=-4 itemset=T14_heal itemcount=4) Define(clarity_of_power 155246) Define(clarity_of_power_talent 19) Define(clarity_of_purpose 155245) SpellAddBuff(clarity_of_purpose serendipity_buff=0 if_spell=serendipity) Define(clarity_of_purpose_talent 19) Define(clarity_of_will 152118) SpellAddTargetBuff(clarity_of_will clarity_of_will_buff=1) Define(clarity_of_will_buff 152118) SpellInfo(clarity_of_will_buff duration=20) Define(clarity_of_will_talent 19) Define(clear_thoughts_buff 167695) SpellInfo(clear_thoughts_buff duration=6) Define(devouring_plague 2944) SpellInfo(devouring_plague shadoworbs=finisher min_shadoworbs=3) SpellAddTargetDebuff(devouring_plague devouring_plague_debuff=1) SpellAddTargetDebuff(devouring_plague void_entropy_debuff=refresh if_spell=void_entropy) Define(devouring_plague_debuff 158831) SpellInfo(devouring_plague_debuff duration=6 haste=spell tick=1) Define(devouring_plague_dot_debuff 158831) Define(dispersion 47585) SpellInfo(dispersion cd=120) SpellInfo(dispersion addcd=-15 glyph=glyph_of_dispersion) Define(divine_hymn 64843) SpellInfo(divine_hymn cd=180 channel=4 haste=spell) Define(divine_insight 109175) Define(divine_insight_buff 123267) SpellInfo(divine_insight_buff duration=10) Define(divine_star_caster 110744) SpellInfo(divine_star_caster cd=15 travel_time=1) Define(divine_star_heal 110744) SpellInfo(divine_star_heal cd=15 travel_time=1) Define(divine_star_talent 17) Define(empowered_archangel 157197) Define(empowered_archangel_buff 172359) SpellInfo(empowered_archangel_buff duration=30) Define(enhanced_chakras 157206) Define(enhanced_mind_flay 157223) Define(enhanced_power_word_shield 157129) Define(enhanced_renew 157207) Define(enhanced_shadow_word_death 157218) Define(evangelism 81662) Define(evangelism_buff 81661) SpellInfo(evangelism_buff duration=20 max_stacks=5) Define(flash_heal 2061) SpellAddBuff(flash_heal empowered_archangel_buff=0 if_spell=empowered_archangel) SpellAddBuff(flash_heal serendipity_buff=1 if_spell=serendipity) SpellAddBuff(flash_heal surge_of_light_buff=0 if_spell=surge_of_light) SpellAddTargetBuff(flash_heal renew_buff=refresh if_spell=chakra_serenity) Define(fortress_of_the_mind_talent 2) Define(halo_caster 120644) SpellInfo(halo_caster cd=40 travel_time=2) Define(halo_heal 120517) SpellInfo(halo_heal cd=40 travel_time=2) Define(halo_talent 18) Define(heal 2060) SpellAddBuff(heal serendipity_buff=0 if_spell=serendipity) SpellAddTargetBuff(heal renew_buff=refresh if_spell=chakra_serenity) Define(holy_fire 14914) SpellInfo(holy_fire cd=10) SpellInfo(holy_fire replace=power_word_solace talent=power_word_solace_talent) SpellAddBuff(holy_fire evangelism_buff=1 if_spell=evangelism) SpellAddTargetDebuff(holy_fire holy_fire_debuff=1) Define(holy_fire_debuff 14914) SpellInfo(holy_fire_debuff duration=9 haste=spell tick=1) Define(holy_word 88625) Define(holy_word_chastise 88625) SpellInfo(holy_word_chastise cd=30) SpellInfo(holy_word_chastise replace=holy_word_sanctuary if_spell=chakra_sanctuary) SpellInfo(holy_word_chastise replace=holy_word_serenity if_spell=chakra_serenity) Define(holy_word_sanctuary 88685) SpellInfo(holy_word_sanctuary cd=40) Define(holy_word_serenity 88684) SpellInfo(holy_word_serenity cd=10) SpellAddTargetBuff(holy_word_serenity holy_word_serenity_buff=1) SpellAddTargetBuff(holy_word_serenity renew_buff=refresh,buff,chakra_serenity_buff if_spell=chakra_serenity) Define(holy_word_serenity_buff 88684) SpellInfo(holy_word_serenity_buff duration=6) Define(insanity_drain_stacks_buff 194249) Define(legacy_of_the_void_talent 19) Define(lightwell 126135) SpellInfo(lightwell cd=180) Define(mental_fatigue_debuff 185104) SpellInfo(mental_fatigue_debuff duration=10 max_stacks=5) Define(mental_instinct_buff 167254) SpellInfo(mental_instinct_buff duration=4 max_stacks=12) Define(mind_blast 8092) SpellInfo(mind_blast cd=9 cd_haste=spell shadoworbs=-1) SpellInfo(mind_blast addcd=-3 if_spell=clarity_of_power) SpellInfo(mind_blast addcd=6 glyph=glyph_of_mind_harvest) SpellRequire(mind_blast shadoworbs -3=target_debuff,glyph_of_mind_harvest_debuff glyph=glyph_of_mind_harvest) SpellAddBuff(mind_blast shadowy_insight_buff=0 if_spell=shadowy_insight) SpellAddTargetDebuff(mind_blast glyph_of_mind_harvest_debuff=1 glyph=glyph_of_mind_harvest) Define(mind_flay 15407) SpellInfo(mind_flay channel=3 haste=spell) SpellInfo(mind_flay channel=2 if_spell=enhanced_mind_flay) Define(mind_sear 48045) SpellInfo(mind_sear channel=5 haste=spell) Define(mind_spike 73510) SpellAddBuff(mind_spike surge_of_darkness_buff=-1 if_spell=surge_of_darkness) SpellAddTargetDebuff(mind_spike devouring_plague_debuff=0,buff,!surge_of_darkness_buff) SpellAddTargetDebuff(mind_spike shadow_word_pain_debuff=0,buff,!surge_of_darkness_buff) SpellAddTargetDebuff(mind_spike vampiric_touch_debuff=0,buff,!surge_of_darkness_buff) SpellAddTargetDebuff(mind_spike void_entropy_debuff=0,buff,!surge_of_darkness_buff if_spell=void_entropy) Define(mind_spike_talent 20) Define(mindbender 123040) SpellInfo(mindbender cd=60) SpellInfo(mindbender addcd=-40 itemset=T18 itemcount=2 specialization=shadow) Define(mindbender_talent 8) Define(penance 47540) SpellInfo(penance cd=9) SpellInfo(penance addcd=-3 itemset=T14_heal itemcount=4) SpellAddBuff(penance evangelism_buff=1 if_spell=evangelism itemset=T17 itemset=2 specialization=discipline) SpellAddBuff(penance reparation_buff=1 itemset=T18 itemcount=2 specialization=discipline) Define(penance_heal 47540) SpellAddBuff(penance_heal reparation_buff=1 itemset=T18 itemcount=2 specialization=discipline) Define(power_infusion 10060) SpellInfo(power_infusion cd=120 gcd=0) SpellAddBuff(power_infusion power_infusion_buff=1) Define(power_infusion_buff 10060) SpellInfo(power_infusion_buff duration=20) Define(power_infusion_talent 14) Define(power_word_fortitude 21562) SpellAddBuff(power_word_fortitude power_word_fortitude_buff=1) Define(power_word_fortitude_buff 21562) SpellInfo(power_word_fortitude_buff duration=3600) Define(power_word_shield 17) SpellInfo(power_word_shield cd=6) SpellInfo(power_word_shield cd=0 if_spell=rapture) SpellRequire(power_word_shield unusable 1=target_debuff,weakened_soul_debuff) SpellAddBuff(power_word_shield borrowed_time_buff=1 if_spell=borrowed_time) SpellAddDebuff(power_word_shield weakened_soul_debuff=1) Define(power_word_solace 129250) SpellInfo(power_word_solace cd=10) SpellAddBuff(power_word_solace evangelism_buff=1 if_spell=evangelism) SpellAddTargetDebuff(power_word_solace power_word_solace_debuff=1) Define(power_word_solace_debuff 129250) SpellInfo(power_word_solace_debuff duration=9 haste=spell tick=1) Define(power_word_solace_talent 9) Define(prayer_of_healing 596) SpellInfo(prayer_of_healing replace=clarity_of_purpose talent=clarity_of_purpose_talent specialization=holy) SpellAddBuff(prayer_of_healing empowered_archangel_buff=0 if_spell=empowered_archangel) SpellAddBuff(prayer_of_healing serendipity_buff=0 if_spell=serendipity) Define(prayer_of_mending 33076) SpellInfo(prayer_of_mending cd=10) SpellRequire(prayer_of_mending replace prayer_of_mending_divine_insight=buff,divine_insight_buff if_spell=divine_insight) SpellAddTargetBuff(prayer_of_mending prayer_of_mending_buff=4 glyph=glyph_of_prayer_of_mending) SpellAddTargetBuff(prayer_of_mending prayer_of_mending_buff=8 glyph=glyph_of_prayer_of_mending itemset=T17 itemcount=2 specialization=holy) SpellAddTargetBuff(prayer_of_mending prayer_of_mending_buff=5 glyph=!glyph_of_prayer_of_mending) SpellAddTargetBuff(prayer_of_mending prayer_of_mending_buff=9 glyph=!glyph_of_prayer_of_mending itemset=T17 itemcount=2 specialization=holy) Define(prayer_of_mending_buff 41635) SpellInfo(prayer_of_mending_buff duration=30) SpellInfo(prayer_of_mending_buff max_stacks=4 glyph=glyph_of_prayer_of_mending) SpellInfo(prayer_of_mending_buff max_stacks=5 glyph=!glyph_of_prayer_of_mending) Define(prayer_of_mending_divine_insight 123259) SpellAddBuff(prayer_of_mending_divine_insight divine_insight_buff=0) Define(prayers_reprise_buff 186367) SpellInfo(prayers_reprise_buff duration=15 max_stacks=3) Define(premonition_buff 188779) SpellInfo(premonition_buff duration=15) Define(psychic_scream 8122) SpellInfo(psychic_scream cd=30) Define(psychic_scream_talent 11) Define(reaper_of_souls_talent 11) Define(reparation_buff 186478) SpellInfo(reparation_buff duration=15 max_stacks=6) Define(renew 139) Define(renew_buff 139) SpellInfo(renew_buff duration=12 haste=spell tick=3) SpellInfo(renew_buff addduration=-3 glyph=glyph_of_renew) SpellInfo(renew_buff addduration=3 if_spell=enhanced_renew) Define(serendipity 63733) Define(serendipity_buff 63735) SpellInfo(serendipity_buff duration=20 max_stacks=2) Define(shadow_crash 205385) SpellInfo(shadow_crash cd=30 insanity=-15) Define(shadow_crash_talent 17) Define(shadow_word_void 205351) SpellInfo(shadow_word_void cd=30 charges=3 insanity=-25) Define(shadow_word_death 32379) SpellInfo(shadow_word_death cd=8 shadoworbs=-1 target_health_pct=20) SpellRequire(shadow_word_death shadoworbs 0=buff,shadow_word_death_reset_cooldown_buff if_spell=!enhanced_shadow_word_death) Define(shadow_word_death_glyphed 129176) SpellInfo(shadow_word_death_glyphed cd=8 shadoworbs=-1) SpellRequire(shadow_word_death_glyphed shadoworbs 0=buff,shadow_word_death_reset_cooldown_buff if_spell=!enhanced_shadow_word_death) Define(shadow_word_death_reset_cooldown_buff 125927) # OvaleShadowWordDeath SpellInfo(shadow_word_death_reset_cooldown_buff duration=9) Define(shadow_word_pain 589) SpellAddTargetDebuff(shadow_word_pain shadow_word_pain_debuff=1) Define(shadow_word_pain_debuff 589) SpellInfo(shadow_word_pain_debuff duration=18 haste=spell tick=3) SpellInfo(shadow_word_pain_debuff addduration=3 itemset=T14_caster itemcount=4) Define(shadowfiend 34433) SpellInfo(shadowfiend cd=180) SpellInfo(shadowfiend addcd=-160 itemset=T18 itemcount=2 specialization=shadow) SpellInfo(shadowfiend replace=mindbender if_spell=mindbender) Define(shadowform_buff 15473) Define(shadowy_insight 162452) Define(shadowy_insight_buff 124430) SpellInfo(shadowy_insight_buff duration=12) Define(silence 15487) SpellInfo(silence cd=45 gcd=0 interrupt=1) SpellInfo(silence addcd=-25 glyph=glyph_of_silence) Define(smite 585) SpellAddBuff(smite evangelism_buff=1 if_spell=evangelism) Define(surge_of_darkness 87160) Define(surge_of_darkness_buff 87160) SpellInfo(surge_of_darkness_buff duration=10 max_stacks=3) Define(surge_of_darkness_talent 7) Define(surge_of_light_buff 114255) SpellInfo(surge_of_light_buff duration=20) Define(surrender_to_madness 193223) SpellInfo(surrender_to_madness cd=600) SpellAddBuff(surrender_to_madness surrender_to_madness_buff=1) Define(surrender_to_madness_buff 193223) SpellInfo(surrender_to_madness_buff duration=180) Define(surrender_to_madness_talent 21) Define(t18_class_trinket 124519) Define(vampiric_touch 34914) SpellAddTargetDebuff(vampiric_touch vampiric_touch_debuff=1) Define(vampiric_touch_debuff 34914) SpellInfo(vampiric_touch_debuff duration=15 haste=spell tick=3) SpellInfo(vampiric_touch_debuff addduration=3 itemset=T14_caster itemcount=4) Define(void_bolt 205448) SpellInfo(void_bolt cd=4.5 insanity=-16) SpellAddTargetDebuff(void_bolt shadow_word_pain_debuff=refresh) SpellAddTargetDebuff(void_bolt vampiric_touch_debuff=refresh) Define(void_entropy 155361) SpellInfo(void_entropy shadoworbs=finisher min_shadoworbs=3) SpellAddTargetDebuff(void_entropy void_entropy_debuff=1) Define(void_entropy_debuff 155361) SpellInfo(void_entropy_debuff duration=60 haste=spell tick=3) Define(void_entropy_talent 20) Define(void_eruption 228260) SpellInfo(void_eruption cd=180 insanity=100) SpellAddBuff(void_eruption voidform_buff=1) SpellRequire(void_eruption unusable 1=buff,voidform_buff) SpellRequire(void_eruption replace void_bolt=buff,voidform_buff) Define(void_torrent 205065) SpellInfo(void_torrent cd=60) SpellRequire(void_torrent unusable 1=buff,voidform_buff) Define(void_torrent_buff 205065) # TODO Insanity does not drain during this buff Define(voidform_buff 194249) Define(weakened_soul_debuff 6788) SpellInfo(weakened_soul_debuff duration=15) SpellInfo(weakened_soul_debuff addduration=-2 glyph=glyph_of_weakened_soul) SpellInfo(weakened_soul_debuff addduration=-3 if_spell=enhanced_power_word_shield) # Non-default tags for OvaleSimulationCraft. SpellInfo(cascade_caster tag=shortcd) SpellInfo(divine_star_caster tag=shortcd) AddFunction CurrentInsanityDrain { if BuffPresent(void_torrent_buff) 0 if BuffPresent(voidform_buff) BuffStacks(voidform_buff)/2 + 9 0 } ]] OvaleScripts:RegisterScript("PRIEST", nil, name, desc, code, "include") end
mit
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Movie/QRCodeWnd.lua
1
1056
--[[ Title: minimap UI window Author(s): Date: Desc: use the lib: ------------------------------------------------------------ NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/QRCodeWnd.lua"); local QRCodeWnd = commonlib.gettable("MyCompany.Aries.Game.Movie.QRCodeWnd"); QRCodeWnd:Show(); ------------------------------------------------------- ]] NPL.load("(gl)script/ide/System/Windows/Window.lua"); local Window = commonlib.gettable("System.Windows.Window"); local QRCodeWnd = commonlib.inherit(nil, commonlib.gettable("MyCompany.Aries.Game.Movie.QRCodeWnd")); function QRCodeWnd:Show() local width = 192; local height = 192; if(not self.window) then local window = Window:new(); window:EnableSelfPaint(true); window:SetAutoClearBackground(false); self.window = window; end self.window:Show({ name="QRCodeWnd", url="script/apps/Aries/Creator/Game/Movie/QRCodeWnd.html", alignment="_ct", left=-width/2, top=-height/2-16, width = width, height = height, zorder = 1, }); end function QRCodeWnd:Hide() self.window:hide(); end
gpl-2.0
jsj2008/ValyriaTear
dat/tilesets/building_interior_objects_01.lua
4
12426
tileset = {} tileset.image = "img/tilesets/building_interior_objects_01.png" tileset.num_tile_cols = 16 tileset.num_tile_rows = 16 -- The general walkability of the tiles in the tileset. Zero indicates walkable. One tile has four walkable quadrants listed as: NW corner, NE corner, SW corner, SE corner. tileset.walkability = {} tileset.walkability[0] = {} tileset.walkability[0][0] = { 0, 0, 0, 0 } tileset.walkability[0][1] = { 0, 0, 0, 0 } tileset.walkability[0][2] = { 0, 0, 0, 0 } tileset.walkability[0][3] = { 0, 0, 0, 0 } tileset.walkability[0][4] = { 0, 0, 0, 0 } tileset.walkability[0][5] = { 0, 0, 0, 0 } tileset.walkability[0][6] = { 0, 0, 1, 1 } tileset.walkability[0][7] = { 0, 0, 1, 1 } tileset.walkability[0][8] = { 0, 0, 1, 1 } tileset.walkability[0][9] = { 1, 1, 1, 1 } tileset.walkability[0][10] = { 1, 1, 1, 1 } tileset.walkability[0][11] = { 0, 0, 0, 0 } tileset.walkability[0][12] = { 0, 0, 0, 0 } tileset.walkability[0][13] = { 0, 0, 1, 1 } tileset.walkability[0][14] = { 0, 0, 1, 1 } tileset.walkability[0][15] = { 0, 0, 1, 1 } tileset.walkability[1] = {} tileset.walkability[1][0] = { 0, 0, 1, 1 } tileset.walkability[1][1] = { 0, 0, 1, 1 } tileset.walkability[1][2] = { 0, 0, 0, 0 } tileset.walkability[1][3] = { 0, 0, 0, 0 } tileset.walkability[1][4] = { 0, 0, 0, 0 } tileset.walkability[1][5] = { 0, 0, 0, 0 } tileset.walkability[1][6] = { 1, 1, 1, 1 } tileset.walkability[1][7] = { 1, 1, 1, 1 } tileset.walkability[1][8] = { 1, 1, 1, 1 } tileset.walkability[1][9] = { 1, 1, 1, 1 } tileset.walkability[1][10] = { 1, 1, 1, 1 } tileset.walkability[1][11] = { 1, 1, 1, 1 } tileset.walkability[1][12] = { 0, 0, 1, 1 } tileset.walkability[1][13] = { 0, 0, 1, 1 } tileset.walkability[1][14] = { 0, 0, 1, 1 } tileset.walkability[1][15] = { 0, 0, 1, 1 } tileset.walkability[2] = {} tileset.walkability[2][0] = { 1, 1, 1, 1 } tileset.walkability[2][1] = { 1, 1, 1, 1 } tileset.walkability[2][2] = { 0, 0, 0, 0 } tileset.walkability[2][3] = { 0, 0, 0, 0 } tileset.walkability[2][4] = { 0, 0, 0, 0 } tileset.walkability[2][5] = { 0, 0, 0, 0 } tileset.walkability[2][6] = { 1, 1, 1, 0 } tileset.walkability[2][7] = { 1, 1, 0, 0 } tileset.walkability[2][8] = { 1, 1, 0, 1 } tileset.walkability[2][9] = { 1, 1, 1, 1 } tileset.walkability[2][10] = { 1, 1, 1, 1 } tileset.walkability[2][11] = { 0, 0, 0, 0 } tileset.walkability[2][12] = { 0, 0, 0, 0 } tileset.walkability[2][13] = { 0, 0, 0, 0 } tileset.walkability[2][14] = { 0, 0, 0, 0 } tileset.walkability[2][15] = { 0, 0, 0, 0 } tileset.walkability[3] = {} tileset.walkability[3][0] = { 0, 0, 0, 0 } tileset.walkability[3][1] = { 0, 0, 0, 0 } tileset.walkability[3][2] = { 0, 0, 0, 0 } tileset.walkability[3][3] = { 0, 0, 0, 0 } tileset.walkability[3][4] = { 0, 0, 0, 0 } tileset.walkability[3][5] = { 0, 0, 0, 0 } tileset.walkability[3][6] = { 0, 0, 0, 0 } tileset.walkability[3][7] = { 0, 0, 0, 0 } tileset.walkability[3][8] = { 0, 0, 0, 0 } tileset.walkability[3][9] = { 0, 0, 0, 0 } tileset.walkability[3][10] = { 0, 0, 0, 0 } tileset.walkability[3][11] = { 0, 0, 0, 0 } tileset.walkability[3][12] = { 1, 1, 1, 1 } tileset.walkability[3][13] = { 0, 0, 0, 0 } tileset.walkability[3][14] = { 0, 0, 0, 0 } tileset.walkability[3][15] = { 0, 0, 0, 0 } tileset.walkability[4] = {} tileset.walkability[4][0] = { 0, 0, 0, 0 } tileset.walkability[4][1] = { 0, 0, 0, 0 } tileset.walkability[4][2] = { 0, 0, 0, 0 } tileset.walkability[4][3] = { 0, 0, 0, 0 } tileset.walkability[4][4] = { 0, 0, 0, 0 } tileset.walkability[4][5] = { 0, 0, 0, 0 } tileset.walkability[4][6] = { 0, 0, 0, 0 } tileset.walkability[4][7] = { 0, 0, 0, 0 } tileset.walkability[4][8] = { 0, 0, 0, 0 } tileset.walkability[4][9] = { 0, 0, 0, 0 } tileset.walkability[4][10] = { 0, 0, 0, 0 } tileset.walkability[4][11] = { 0, 0, 0, 0 } tileset.walkability[4][12] = { 0, 0, 0, 0 } tileset.walkability[4][13] = { 0, 0, 0, 0 } tileset.walkability[4][14] = { 1, 1, 1, 1 } tileset.walkability[4][15] = { 0, 0, 0, 0 } tileset.walkability[5] = {} tileset.walkability[5][0] = { 0, 0, 1, 1 } tileset.walkability[5][1] = { 0, 0, 1, 1 } tileset.walkability[5][2] = { 0, 0, 0, 0 } tileset.walkability[5][3] = { 0, 0, 0, 0 } tileset.walkability[5][4] = { 0, 0, 0, 0 } tileset.walkability[5][5] = { 0, 0, 0, 0 } tileset.walkability[5][6] = { 0, 0, 0, 0 } tileset.walkability[5][7] = { 0, 0, 0, 0 } tileset.walkability[5][8] = { 0, 0, 0, 0 } tileset.walkability[5][9] = { 0, 0, 0, 0 } tileset.walkability[5][10] = { 0, 0, 0, 0 } tileset.walkability[5][11] = { 0, 0, 1, 1 } tileset.walkability[5][12] = { 0, 0, 1, 1 } tileset.walkability[5][13] = { 0, 0, 0, 0 } tileset.walkability[5][14] = { 1, 1, 1, 1 } tileset.walkability[5][15] = { 0, 0, 0, 0 } tileset.walkability[6] = {} tileset.walkability[6][0] = { 0, 0, 0, 0 } tileset.walkability[6][1] = { 0, 0, 0, 0 } tileset.walkability[6][2] = { 0, 0, 0, 0 } tileset.walkability[6][3] = { 0, 0, 0, 0 } tileset.walkability[6][4] = { 1, 1, 1, 1 } tileset.walkability[6][5] = { 1, 1, 1, 1 } tileset.walkability[6][6] = { 1, 1, 1, 1 } tileset.walkability[6][7] = { 1, 1, 1, 1 } tileset.walkability[6][8] = { 1, 1, 1, 1 } tileset.walkability[6][9] = { 0, 0, 0, 0 } tileset.walkability[6][10] = { 0, 0, 0, 0 } tileset.walkability[6][11] = { 0, 0, 0, 0 } tileset.walkability[6][12] = { 0, 0, 0, 0 } tileset.walkability[6][13] = { 0, 0, 0, 0 } tileset.walkability[6][14] = { 0, 0, 0, 0 } tileset.walkability[6][15] = { 1, 1, 1, 1 } tileset.walkability[7] = {} tileset.walkability[7][0] = { 0, 0, 0, 0 } tileset.walkability[7][1] = { 0, 0, 0, 0 } tileset.walkability[7][2] = { 0, 0, 0, 0 } tileset.walkability[7][3] = { 0, 0, 0, 0 } tileset.walkability[7][4] = { 0, 0, 0, 0 } tileset.walkability[7][5] = { 0, 0, 0, 0 } tileset.walkability[7][6] = { 1, 1, 1, 1 } tileset.walkability[7][7] = { 1, 1, 1, 1 } tileset.walkability[7][8] = { 1, 1, 1, 1 } tileset.walkability[7][9] = { 1, 1, 1, 1 } tileset.walkability[7][10] = { 1, 1, 1, 1 } tileset.walkability[7][11] = { 1, 1, 1, 1 } tileset.walkability[7][12] = { 1, 1, 1, 1 } tileset.walkability[7][13] = { 1, 1, 1, 1 } tileset.walkability[7][14] = { 1, 1, 1, 1 } tileset.walkability[7][15] = { 1, 1, 1, 1 } tileset.walkability[8] = {} tileset.walkability[8][0] = { 0, 0, 0, 0 } tileset.walkability[8][1] = { 0, 0, 0, 0 } tileset.walkability[8][2] = { 0, 0, 0, 0 } tileset.walkability[8][3] = { 0, 0, 0, 0 } tileset.walkability[8][4] = { 0, 0, 0, 0 } tileset.walkability[8][5] = { 0, 0, 0, 0 } tileset.walkability[8][6] = { 1, 1, 1, 1 } tileset.walkability[8][7] = { 1, 1, 1, 1 } tileset.walkability[8][8] = { 1, 1, 1, 1 } tileset.walkability[8][9] = { 1, 1, 1, 1 } tileset.walkability[8][10] = { 1, 1, 1, 1 } tileset.walkability[8][11] = { 1, 1, 1, 1 } tileset.walkability[8][12] = { 1, 1, 1, 1 } tileset.walkability[8][13] = { 1, 1, 1, 1 } tileset.walkability[8][14] = { 1, 1, 1, 1 } tileset.walkability[8][15] = { 1, 1, 1, 1 } tileset.walkability[9] = {} tileset.walkability[9][0] = { 0, 0, 0, 0 } tileset.walkability[9][1] = { 0, 0, 0, 0 } tileset.walkability[9][2] = { 0, 0, 0, 0 } tileset.walkability[9][3] = { 0, 0, 0, 0 } tileset.walkability[9][4] = { 0, 0, 0, 0 } tileset.walkability[9][5] = { 0, 0, 0, 0 } tileset.walkability[9][6] = { 0, 0, 0, 0 } tileset.walkability[9][7] = { 0, 0, 0, 0 } tileset.walkability[9][8] = { 0, 0, 0, 0 } tileset.walkability[9][9] = { 0, 0, 0, 0 } tileset.walkability[9][10] = { 1, 1, 1, 1 } tileset.walkability[9][11] = { 1, 1, 1, 1 } tileset.walkability[9][12] = { 1, 1, 1, 1 } tileset.walkability[9][13] = { 1, 1, 1, 1 } tileset.walkability[9][14] = { 1, 1, 1, 1 } tileset.walkability[9][15] = { 1, 1, 1, 1 } tileset.walkability[10] = {} tileset.walkability[10][0] = { 0, 0, 0, 0 } tileset.walkability[10][1] = { 0, 0, 0, 0 } tileset.walkability[10][2] = { 0, 0, 0, 0 } tileset.walkability[10][3] = { 0, 0, 0, 0 } tileset.walkability[10][4] = { 0, 0, 0, 0 } tileset.walkability[10][5] = { 0, 0, 0, 0 } tileset.walkability[10][6] = { 0, 0, 0, 0 } tileset.walkability[10][7] = { 0, 0, 0, 0 } tileset.walkability[10][8] = { 0, 0, 0, 0 } tileset.walkability[10][9] = { 0, 0, 0, 0 } tileset.walkability[10][10] = { 1, 1, 1, 1 } tileset.walkability[10][11] = { 1, 1, 1, 1 } tileset.walkability[10][12] = { 1, 1, 1, 1 } tileset.walkability[10][13] = { 1, 1, 1, 1 } tileset.walkability[10][14] = { 0, 0, 0, 0 } tileset.walkability[10][15] = { 0, 0, 0, 0 } tileset.walkability[11] = {} tileset.walkability[11][0] = { 0, 0, 0, 0 } tileset.walkability[11][1] = { 0, 0, 0, 0 } tileset.walkability[11][2] = { 0, 0, 0, 0 } tileset.walkability[11][3] = { 0, 0, 0, 0 } tileset.walkability[11][4] = { 0, 0, 0, 0 } tileset.walkability[11][5] = { 0, 0, 0, 0 } tileset.walkability[11][6] = { 0, 0, 0, 0 } tileset.walkability[11][7] = { 0, 0, 0, 0 } tileset.walkability[11][8] = { 0, 0, 0, 0 } tileset.walkability[11][9] = { 0, 0, 0, 0 } tileset.walkability[11][10] = { 0, 0, 0, 0 } tileset.walkability[11][11] = { 0, 0, 0, 0 } tileset.walkability[11][12] = { 0, 0, 0, 0 } tileset.walkability[11][13] = { 0, 0, 0, 0 } tileset.walkability[11][14] = { 0, 0, 0, 0 } tileset.walkability[11][15] = { 0, 0, 0, 0 } tileset.walkability[12] = {} tileset.walkability[12][0] = { 1, 1, 1, 1 } tileset.walkability[12][1] = { 1, 1, 1, 1 } tileset.walkability[12][2] = { 1, 1, 1, 1 } tileset.walkability[12][3] = { 1, 1, 1, 1 } tileset.walkability[12][4] = { 1, 1, 1, 1 } tileset.walkability[12][5] = { 1, 1, 1, 1 } tileset.walkability[12][6] = { 1, 1, 1, 1 } tileset.walkability[12][7] = { 0, 0, 0, 0 } tileset.walkability[12][8] = { 0, 0, 0, 0 } tileset.walkability[12][9] = { 0, 0, 0, 0 } tileset.walkability[12][10] = { 1, 1, 1, 1 } tileset.walkability[12][11] = { 1, 1, 1, 1 } tileset.walkability[12][12] = { 1, 1, 1, 1 } tileset.walkability[12][13] = { 1, 1, 1, 1 } tileset.walkability[12][14] = { 1, 1, 1, 1 } tileset.walkability[12][15] = { 1, 1, 1, 1 } tileset.walkability[13] = {} tileset.walkability[13][0] = { 1, 1, 1, 1 } tileset.walkability[13][1] = { 1, 1, 1, 1 } tileset.walkability[13][2] = { 1, 1, 1, 1 } tileset.walkability[13][3] = { 1, 1, 1, 1 } tileset.walkability[13][4] = { 1, 1, 1, 1 } tileset.walkability[13][5] = { 1, 1, 1, 1 } tileset.walkability[13][6] = { 0, 0, 0, 0 } tileset.walkability[13][7] = { 0, 0, 0, 0 } tileset.walkability[13][8] = { 0, 0, 0, 0 } tileset.walkability[13][9] = { 0, 0, 0, 0 } tileset.walkability[13][10] = { 0, 0, 0, 0 } tileset.walkability[13][11] = { 0, 0, 0, 0 } tileset.walkability[13][12] = { 0, 0, 0, 0 } tileset.walkability[13][13] = { 0, 0, 0, 0 } tileset.walkability[13][14] = { 0, 0, 0, 0 } tileset.walkability[13][15] = { 0, 0, 0, 0 } tileset.walkability[14] = {} tileset.walkability[14][0] = { 1, 1, 1, 1 } tileset.walkability[14][1] = { 1, 1, 1, 1 } tileset.walkability[14][2] = { 1, 1, 1, 1 } tileset.walkability[14][3] = { 1, 1, 1, 1 } tileset.walkability[14][4] = { 0, 0, 1, 1 } tileset.walkability[14][5] = { 0, 0, 1, 1 } tileset.walkability[14][6] = { 0, 0, 1, 1 } tileset.walkability[14][7] = { 0, 0, 1, 1 } tileset.walkability[14][8] = { 0, 0, 1, 1 } tileset.walkability[14][9] = { 0, 0, 1, 1 } tileset.walkability[14][10] = { 0, 0, 1, 1 } tileset.walkability[14][11] = { 0, 0, 1, 1 } tileset.walkability[14][12] = { 0, 0, 0, 0 } tileset.walkability[14][13] = { 0, 0, 0, 0 } tileset.walkability[14][14] = { 0, 0, 0, 0 } tileset.walkability[14][15] = { 0, 0, 0, 0 } tileset.walkability[15] = {} tileset.walkability[15][0] = { 0, 0, 0, 0 } tileset.walkability[15][1] = { 0, 0, 0, 0 } tileset.walkability[15][2] = { 0, 0, 0, 0 } tileset.walkability[15][3] = { 0, 0, 0, 0 } tileset.walkability[15][4] = { 0, 0, 0, 0 } tileset.walkability[15][5] = { 0, 0, 0, 0 } tileset.walkability[15][6] = { 0, 0, 0, 0 } tileset.walkability[15][7] = { 0, 0, 0, 0 } tileset.walkability[15][8] = { 0, 0, 1, 1 } tileset.walkability[15][9] = { 0, 0, 1, 1 } tileset.walkability[15][10] = { 0, 0, 1, 1 } tileset.walkability[15][11] = { 0, 0, 1, 1 } tileset.walkability[15][12] = { 0, 0, 1, 1 } tileset.walkability[15][13] = { 0, 0, 0, 0 } tileset.walkability[15][14] = { 0, 0, 0, 0 } tileset.walkability[15][15] = { 0, 0, 0, 0 } -- The animated tiles table has one row per animated tile, with each entry in a row indicating which tile in the tileset is the next part of the animation, followed by the time in ms that the tile will be displayed for. tileset.animated_tiles = {} tileset.animated_tiles[1] = { 239, 200, 240, 200, 241, 200, 242, 200, 243, 200, 244, 200, 245, 200, 246, 200 } tileset.animated_tiles[2] = { 247, 150, 248, 150, 249, 150, 250, 150, 252, 150 }
gpl-2.0
pakoito/ToME---t-engine4
game/modules/tome/data/general/objects/lore/sunwall.lua
3
1077
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org for i = 1, 4 do newEntity{ base = "BASE_LORE_RANDOM", define_as = "SUNWALL_LORE_NOTE"..i, name = "Loremaster Verutir's note", lore="sunwall-note-"..i, unique="Loremaster Verutir's note "..i, desc = [[A paper scrap containing some lore.]], level_range = {1, 50}, rarity = 50, encumber = 0, } end
gpl-3.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Code/NplCad/NplCadDef/NplCadDef_Animation.lua
1
7183
--[[ Title: NplCadDef_Animation Author(s): leio Date: 2019/8/2 Desc: a set of commands to animate joints use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/Code/NplCad/NplCadDef/NplCadDef_Animation.lua"); local NplCadDef_Animation = commonlib.gettable("MyCompany.Aries.Game.Code.NplCad.NplCadDef_Animation"); ------------------------------------------------------- ]] local NplCadDef_Animation = commonlib.gettable("MyCompany.Aries.Game.Code.NplCad.NplCadDef_Animation"); local cmds = { { type = "createAnimation", message0 = L"骨骼动画 %1 %2", arg0 = { { name = "name", type = "input_value", shadow = { type = "text", value = "anim",}, text = "", }, { name = "is_enabled", type = "field_dropdown", options = { { L"有效", "true" }, { L"无效", "false" }, }, }, }, category = "Animation", helpUrl = "", canRun = false, previousStatement = true, nextStatement = true, funcName = "createAnimation", func_description = 'createAnimation(%s,%s)', func_description_js = 'createAnimation(%s,%s)', ToNPL = function(self) return string.format('createAnimation("%s",%s)\n', self:getFieldValue('name'), self:getFieldValue('is_enabled')) end, examples = {{desc = "", canRun = true, code = [[ createAnimation("anim") ]]}}, }, { type = "addChannel", message0 = L"动画通道 %1 %2", message1 = L"%1", arg0 = { { name = "name", type = "input_value", shadow = { type = "text", value = "",}, text = "", }, { name = "type", type = "field_dropdown", options = { { L"线性", "'linear'" }, { L"步", "'step'" }, }, }, }, arg1 = { { name = "input", type = "input_statement", }, }, category = "Animation", helpUrl = "", canRun = false, previousStatement = true, nextStatement = true, funcName = "addChannel", func_description = 'addChannel(%s,%s)\\n%sendChannel()', func_description_js = 'addChannel(%s,%s)\\n%sendChannel()', ToNPL = function(self) return "" end, examples = {{desc = "", canRun = true, code = [[ ]]}}, }, { type = "setAnimationTimeValue_Translate", message0 = L"时间 %1 移动 %2 %3 %4", arg0 = { { name = "time", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "x", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "y", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "z", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, }, category = "Animation", helpUrl = "", canRun = false, previousStatement = true, nextStatement = true, funcName = "setAnimationTimeValue_Translate", func_description = 'setAnimationTimeValue_Translate(%s,%s,%s,%s)', func_description_js = 'setAnimationTimeValue_Translate(%s,%s,%s,%s)', ToNPL = function(self) return ""; end, examples = {{desc = "", canRun = true, code = [[ ]]}}, }, { type = "setAnimationTimeValue_Scale", message0 = L"时间 %1 缩放 %2 %3 %4", arg0 = { { name = "time", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "x", type = "input_value", shadow = { type = "math_number", value = 1,}, text = 1, }, { name = "y", type = "input_value", shadow = { type = "math_number", value = 1,}, text = 1, }, { name = "z", type = "input_value", shadow = { type = "math_number", value = 1,}, text = 1, }, }, category = "Animation", helpUrl = "", canRun = false, previousStatement = true, nextStatement = true, funcName = "setAnimationTimeValue_Scale", func_description = 'setAnimationTimeValue_Scale(%s,%s,%s,%s)', func_description_js = 'setAnimationTimeValue_Scale(%s,%s,%s,%s)', ToNPL = function(self) return ""; end, examples = {{desc = "", canRun = true, code = [[ ]]}}, }, { type = "setAnimationTimeValue_Rotate", message0 = L"时间 %1 旋转 %2 %3 度", arg0 = { { name = "time", type = "input_value", shadow = { type = "math_number", value = "0",}, text = "0", }, { name = "axis", type = "field_dropdown", options = { { L"x轴", "'x'" }, { L"y轴", "'y'" }, { L"z轴", "'z'" }, }, }, { name = "angle", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, }, category = "Animation", helpUrl = "", canRun = false, previousStatement = true, nextStatement = true, funcName = "setAnimationTimeValue_Rotate", func_description = 'setAnimationTimeValue_Rotate(%s,%s,%s)', func_description_js = 'setAnimationTimeValue_Rotate(%s,%s,%s)', ToNPL = function(self) return ""; end, examples = {{desc = "", canRun = true, code = [[ ]]}}, }, { type = "setAnimationTimeValue_rotateFromPivot", message0 = L"时间 %1 旋转 %2 %3 度 中心点 %4 %5 %6", arg0 = { { name = "time", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "axis", type = "field_dropdown", options = { { L"x轴", "'x'" }, { L"y轴", "'y'" }, { L"z轴", "'z'" }, }, }, { name = "angle", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "tx", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "ty", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "tz", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, }, hide_in_toolbox = true, category = "Animation", helpUrl = "", canRun = false, previousStatement = true, nextStatement = true, funcName = "setAnimationTimeValue_rotateFromPivot", func_description = 'setAnimationTimeValue_rotateFromPivot(%s,%s,%s,%s,%s,%s)', func_description_js = 'setAnimationTimeValue_rotateFromPivot(%s,%s,%s,%s,%s,%s)', ToNPL = function(self) return ""; end, examples = {{desc = "", canRun = true, code = [[ ]]}}, }, { type = "animationiNames", message0 = L"%1", arg0 = { { name = "name", type = "field_dropdown", options = { { L"待机", "'ParaAnimation_0'" }, { L"倒下", "'ParaAnimation_1'" }, { L"走路", "'ParaAnimation_4'" }, { L"跑步", "'ParaAnimation_5'" }, }, }, }, category = "Animation", helpUrl = "", canRun = false, output = {type = "null",}, func_description = '%s', func_description_js = '%s', ToNPL = function(self) return string.format('%s', self:getFieldAsString('name') ); end, examples = {{desc = "", canRun = true, code = [[ ]]}}, }, }; function NplCadDef_Animation.GetCmds() return cmds; end
gpl-2.0
vince06fr/prosody-modules
mod_auth_dovecot/auth_dovecot/mod_auth_dovecot.lua
32
2974
-- Dovecot authentication backend for Prosody -- -- Copyright (C) 2010-2011 Waqas Hussain -- Copyright (C) 2011 Kim Alvefur -- local name = "Dovecot SASL"; local log = require "util.logger".init("auth_dovecot"); local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); local socket_host = module:get_option_string("dovecot_auth_host", "127.0.0.1"); local socket_port = module:get_option_string("dovecot_auth_port"); local service_realm = module:get_option("realm"); local service_name = module:get_option("service_name"); local append_host = module:get_option_boolean("auth_append_host"); --assert(not append_host, "auth_append_host does not work"); local validate_domain = module:get_option_boolean("validate_append_host"); local handle_appended = module:get_option_string("handle_appended"); local util_sasl_new = require "util.sasl".new; local new_dovecot_sasl = module:require "sasl_dovecot".new; local new_sasl = function(realm) return new_dovecot_sasl( service_realm or realm, service_name or "xmpp", socket_port and { socket_host, socket_port } or socket_path, { --config handle_domain = handle_appended or (append_host and "split" or "escape"), validate_domain = validate_domain, } ); end do local s, err = new_sasl(module.host) if not s then log("error", "%s", tostring(err)); end assert(s, "Could not create a new SASL object"); assert(s.mechanisms, "SASL object has no mechanims method"); local m, _m = {}, s:mechanisms(); assert(not append_host or _m.PLAIN, "auth_append_host requires PLAIN, but it is unavailable"); for k in pairs(_m) do table.insert(m, k); end log("debug", "Mechanims found: %s", table.concat(m, ", ")); end provider = {}; function provider.test_password(username, password) return new_sasl(module.host):plain_test(username, password); end function provider.get_password(username) return nil, "Passwords unavailable for "..name; end function provider.set_password(username, password) return nil, "Passwords unavailable for "..name; end function provider.user_exists(username) return true -- FIXME --[[ This, sadly, doesn't work. local user_test = new_sasl(module.host); user_test:select("PLAIN"); user_test:process(("\0%s\0"):format(username)); return user_test.username == username; --]] end function provider.create_user(username, password) return nil, "Account creation/modification not available with "..name; end function provider.get_sasl_handler() return new_sasl(module.host); end if append_host then function provider.test_password(username, password) return new_sasl(module.host):plain_test(username .. "@".. (service_realm or module.host), password) == "success"; end function provider.get_sasl_handler() return util_sasl_new(module.host, { plain_test = function(sasl, username, password, realm) return provider.test_password(username, password), true end; }); end end module:provides("auth", provider);
mit
RyMarq/Zero-K
effects/gundam_missile_explosion.lua
26
2926
-- missile_explosion return { ["missile_explosion"] = { dirt = { count = 4, ground = true, properties = { alphafalloff = 2, alwaysvisible = true, color = [[0.2, 0.1, 0.05]], pos = [[r-10 r10, 0, r-10 r10]], size = 20, speed = [[r1.5 r-1.5, 2, r1.5 r-1.5]], }, }, groundflash = { air = true, alwaysvisible = true, circlealpha = 0.6, circlegrowth = 6, flashalpha = 0.9, flashsize = 120, ground = true, ttl = 13, water = true, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, poof01 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[1.0 1.0 1.0 0.04 0.9 0.5 0.2 0.01 0.8 0.1 0.1 0.01]], directional = true, emitrot = 45, emitrotspread = 32, emitvector = [[0, 1, 0]], gravity = [[0, -0.05, 0]], numparticles = 8, particlelife = 10, particlelifespread = 5, particlesize = 20, particlesizespread = 0, particlespeed = 5, particlespeedspread = 5, pos = [[0, 2, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[flashside1]], useairlos = false, }, }, pop1 = { air = true, class = [[heatcloud]], count = 2, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1.1, maxheat = 15, pos = [[r-2 r2, 5, r-2 r2]], size = 1, sizegrowth = 15, speed = [[0, 1 0, 0]], texture = [[uglynovaexplo]], }, }, pop2 = { air = true, class = [[heatcloud]], count = 1, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1.3, maxheat = 15, pos = [[r-2 r2, 5, r-2 r2]], size = 3, sizegrowth = 25, speed = [[0, 1 0, 0]], texture = [[flare]], }, }, }, }
gpl-2.0
p00ria/Grandex
plugins/Google_Image.lua
2
3167
do local mime = require("mime") local google_config = load_from_file('data/google.lua') local cache = {} --[[ local function send_request(url) local t = {} local options = { url = url, sink = ltn12.sink.table(t), method = "GET" } local a, code, headers, status = http.request(options) return table.concat(t), code, headers, status end]]-- local function get_google_data(text) local url = "http://ajax.googleapis.com/ajax/services/search/images?" url = url.."v=1.0&rsz=5" url = url.."&q="..URL.escape(text) url = url.."&imgsz=small|medium|large" if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local res, code = http.request(url) if code ~= 200 then print("HTTP Error code:", code) return nil end local google = json:decode(res) return google end -- Returns only the useful google data to save on cache local function simple_google_table(google) local new_table = {} new_table.responseData = {} new_table.responseDetails = google.responseDetails new_table.responseStatus = google.responseStatus new_table.responseData.results = {} local results = google.responseData.results for k,result in pairs(results) do new_table.responseData.results[k] = {} new_table.responseData.results[k].unescapedUrl = result.unescapedUrl new_table.responseData.results[k].url = result.url end return new_table end local function save_to_cache(query, data) -- Saves result on cache if string.len(query) <= 7 then local text_b64 = mime.b64(query) if not cache[text_b64] then local simple_google = simple_google_table(data) cache[text_b64] = simple_google end end end local function process_google_data(google, receiver, query) if google.responseStatus == 403 then local text = 'ERROR: Reached maximum searches per day' send_msg(receiver, text, ok_cb, false) elseif google.responseStatus == 200 then local data = google.responseData if not data or not data.results or #data.results == 0 then local text = 'Image not found.' send_msg(receiver, text, ok_cb, false) return false end -- Random image from table local i = math.random(#data.results) local url = data.results[i].unescapedUrl or data.results[i].url local old_timeout = http.TIMEOUT or 10 http.TIMEOUT = 5 send_photo_from_url(receiver, url) http.TIMEOUT = old_timeout save_to_cache(query, google) else local text = 'ERROR!' send_msg(receiver, text, ok_cb, false) end end function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local text_b64 = mime.b64(text) local cached = cache[text_b64] if cached then process_google_data(cached, receiver, text) else local data = get_google_data(text) process_google_data(data, receiver, text) end end return { description = "Search Image With Google", usage = "/img (item) : search image in google", patterns = { "^[!/#]img (.*)$" }, run = run } end
gpl-2.0
RyMarq/Zero-K
LuaRules/Gadgets/unit_spherical_los.lua
2
3109
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Spherical LOS", desc = "Approximates sphereical (actually a double cone) LOS by reducing LOS for very high ground units.", author = "Google Frog", date = "31 August 2012", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local UPDATE_FREQUENCY = 15 local ELONGATION = 1.5 local ON_GROUND_THRESHOLD = 10 local units = {count = 0, data = {}} local unitsByID = {} local frame = Spring.GetGameFrame() local function AddSphericalLOSCheck(unitID, unitDefID) if unitsByID[unitID] then local index = unitsByID[unitID] units.data[index].removeAfter = frame + 40 else local ud = UnitDefs[unitDefID] units.count = units.count + 1 --GG.UnitEcho(unitID, "added") units.data[units.count] = { unitID = unitID, los = ud.losRadius, airLos = ud.airLosRadius, removeAfter = frame + 40, } unitsByID[unitID] = units.count end end GG.AddSphereicalLOSCheck = AddSphericalLOSCheck -- deprecated typo'd version, left in for any reverse compatibility that might be needed GG.AddSphericalLOSCheck = AddSphericalLOSCheck local function CheckUnit(unitID, los, airLos) if not Spring.ValidUnitID(unitID) then return false end local x,y,z = Spring.GetUnitPosition(unitID) local ground = Spring.GetGroundHeight(x,z) if ground and y then local diff = y - math.max(0, ground) if diff < ON_GROUND_THRESHOLD then Spring.SetUnitSensorRadius(unitID, "los", los) Spring.SetUnitSensorRadius(unitID, "airLos", airLos) return true, false end diff = diff/ELONGATION if diff >= los then Spring.SetUnitSensorRadius(unitID, "los", 0) Spring.SetUnitSensorRadius(unitID, "airLos", 0) return true, true end local angle = math.asin(diff / los) local scaleFactor = math.cos(angle) Spring.SetUnitSensorRadius(unitID, "los", scaleFactor * los) Spring.SetUnitSensorRadius(unitID, "airLos", scaleFactor * airLos) end return true, true end function gadget:GameFrame(f) if f%UPDATE_FREQUENCY == 3 then frame = f local i = 1 while i <= units.count do local data = units.data[i] local unitID = data.unitID local valid, flying = CheckUnit(unitID, data.los, data.airLos) if valid and (flying or f < data.removeAfter) then i = i + 1 else --GG.UnitEcho(unitID, "removed") unitsByID[unitID] = nil unitsByID[units.data[units.count].unitID] = i units.data[i] = units.data[units.count] units.count = units.count - 1 end end end end
gpl-2.0
vince06fr/prosody-modules
mod_admin_web/admin_web/mod_admin_web.lua
31
9425
-- Copyright (C) 2010 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- -- <session xmlns="http://prosody.im/streams/c2s" jid="alice@example.com/brussels"> -- <encrypted/> -- <compressed/> -- </session> -- <session xmlns="http://prosody.im/streams/s2s" jid="example.com"> -- <encrypted> -- <valid/> / <invalid/> -- </encrypted> -- <compressed/> -- <in/> / <out/> -- </session> local st = require "util.stanza"; local uuid_generate = require "util.uuid".generate; local is_admin = require "core.usermanager".is_admin; local pubsub = require "util.pubsub"; local jid_bare = require "util.jid".bare; local hosts = prosody.hosts; local incoming_s2s = prosody.incoming_s2s; module:set_global(); local service = {}; local xmlns_adminsub = "http://prosody.im/adminsub"; local xmlns_c2s_session = "http://prosody.im/streams/c2s"; local xmlns_s2s_session = "http://prosody.im/streams/s2s"; local idmap = {}; local function add_client(session, host) local name = session.full_jid; local id = idmap[name]; if not id then id = uuid_generate(); idmap[name] = id; end local item = st.stanza("item", { id = id }):tag("session", {xmlns = xmlns_c2s_session, jid = name}):up(); if session.secure then local encrypted = item:tag("encrypted"); local sock = session.conn and session.conn.socket and session.conn:socket() local info = sock and sock.info and sock:info(); for k, v in pairs(info or {}) do encrypted:tag("info", { name = k }):text(tostring(v)):up(); end end if session.compressed then item:tag("compressed"):up(); end service[host]:publish(xmlns_c2s_session, host, id, item); module:log("debug", "Added client " .. name); end local function del_client(session, host) local name = session.full_jid; local id = idmap[name]; if id then local notifier = st.stanza("retract", { id = id }); service[host]:retract(xmlns_c2s_session, host, id, notifier); end end local function add_host(session, type, host) local name = (type == "out" and session.to_host) or (type == "in" and session.from_host); local id = idmap[name.."_"..type]; if not id then id = uuid_generate(); idmap[name.."_"..type] = id; end local item = st.stanza("item", { id = id }):tag("session", {xmlns = xmlns_s2s_session, jid = name}) :tag(type):up(); if session.secure then local encrypted = item:tag("encrypted"); local sock = session.conn and session.conn.socket and session.conn:socket() local info = sock and sock.info and sock:info(); for k, v in pairs(info or {}) do encrypted:tag("info", { name = k }):text(tostring(v)):up(); end if session.cert_identity_status == "valid" then encrypted:tag("valid"); else encrypted:tag("invalid"); end end if session.compressed then item:tag("compressed"):up(); end service[host]:publish(xmlns_s2s_session, host, id, item); module:log("debug", "Added host " .. name .. " s2s" .. type); end local function del_host(session, type, host) local name = (type == "out" and session.to_host) or (type == "in" and session.from_host); local id = idmap[name.."_"..type]; if id then local notifier = st.stanza("retract", { id = id }); service[host]:retract(xmlns_s2s_session, host, id, notifier); end end local function get_affiliation(jid, host) local bare_jid = jid_bare(jid); if is_admin(bare_jid, host) then return "member"; else return "none"; end end function module.add_host(module) -- Dependencies module:depends("bosh"); module:depends("admin_adhoc"); module:depends("http"); local serve_file = module:depends("http_files").serve { path = module:get_directory() .. "/www_files"; }; -- Setup HTTP server module:provides("http", { name = "admin"; route = { ["GET"] = function(event) event.response.headers.location = event.request.path .. "/"; return 301; end; ["GET /*"] = serve_file; } }); -- Setup adminsub service local function simple_broadcast(kind, node, jids, item) if item then item = st.clone(item); item.attr.xmlns = nil; -- Clear the pubsub namespace end local message = st.message({ from = module.host, type = "headline" }) :tag("event", { xmlns = xmlns_adminsub .. "#event" }) :tag(kind, { node = node }) :add_child(item); for jid in pairs(jids) do module:log("debug", "Sending notification to %s", jid); message.attr.to = jid; module:send(message); end end service[module.host] = pubsub.new({ broadcaster = simple_broadcast; normalize_jid = jid_bare; get_affiliation = function(jid) return get_affiliation(jid, module.host) end; capabilities = { member = { create = false; publish = false; retract = false; get_nodes = true; subscribe = true; unsubscribe = true; get_subscription = true; get_subscriptions = true; get_items = true; subscribe_other = false; unsubscribe_other = false; get_subscription_other = false; get_subscriptions_other = false; be_subscribed = true; be_unsubscribed = true; set_affiliation = false; }; owner = { create = true; publish = true; retract = true; get_nodes = true; subscribe = true; unsubscribe = true; get_subscription = true; get_subscriptions = true; get_items = true; subscribe_other = true; unsubscribe_other = true; get_subscription_other = true; get_subscriptions_other = true; be_subscribed = true; be_unsubscribed = true; set_affiliation = true; }; }; }); -- Create node for s2s sessions local ok, err = service[module.host]:create(xmlns_s2s_session, true); if not ok then module:log("warn", "Could not create node " .. xmlns_s2s_session .. ": " .. tostring(err)); else service[module.host]:set_affiliation(xmlns_s2s_session, true, module.host, "owner") end -- Add outgoing s2s sessions for _, session in pairs(hosts[module.host].s2sout) do if session.type ~= "s2sout_unauthed" then add_host(session, "out", module.host); end end -- Add incomming s2s sessions for session in pairs(incoming_s2s) do if session.to_host == module.host then add_host(session, "in", module.host); end end -- Create node for c2s sessions ok, err = service[module.host]:create(xmlns_c2s_session, true); if not ok then module:log("warn", "Could not create node " .. xmlns_c2s_session .. ": " .. tostring(err)); else service[module.host]:set_affiliation(xmlns_c2s_session, true, module.host, "owner") end -- Add c2s sessions for _, user in pairs(hosts[module.host].sessions or {}) do for _, session in pairs(user.sessions or {}) do add_client(session, module.host); end end -- Register adminsub handler module:hook("iq/host/http://prosody.im/adminsub:adminsub", function(event) local origin, stanza = event.origin, event.stanza; local adminsub = stanza.tags[1]; local action = adminsub.tags[1]; local reply; if action.name == "subscribe" then local ok, ret = service[module.host]:add_subscription(action.attr.node, stanza.attr.from, stanza.attr.from); if ok then reply = st.reply(stanza) :tag("adminsub", { xmlns = xmlns_adminsub }); else reply = st.error_reply(stanza, "cancel", ret); end elseif action.name == "unsubscribe" then local ok, ret = service[module.host]:remove_subscription(action.attr.node, stanza.attr.from, stanza.attr.from); if ok then reply = st.reply(stanza) :tag("adminsub", { xmlns = xmlns_adminsub }); else reply = st.error_reply(stanza, "cancel", ret); end elseif action.name == "items" then local node = action.attr.node; local ok, ret = service[module.host]:get_items(node, stanza.attr.from); if not ok then return origin.send(st.error_reply(stanza, "cancel", ret)); end local data = st.stanza("items", { node = node }); for _, entry in pairs(ret) do data:add_child(entry); end if data then reply = st.reply(stanza) :tag("adminsub", { xmlns = xmlns_adminsub }) :add_child(data); else reply = st.error_reply(stanza, "cancel", "item-not-found"); end elseif action.name == "adminfor" then local data = st.stanza("adminfor"); for host_name in pairs(hosts) do if is_admin(stanza.attr.from, host_name) then data:tag("item"):text(host_name):up(); end end reply = st.reply(stanza) :tag("adminsub", { xmlns = xmlns_adminsub }) :add_child(data); else reply = st.error_reply(stanza, "feature-not-implemented"); end return origin.send(reply); end); -- Add/remove c2s sessions module:hook("resource-bind", function(event) add_client(event.session, module.host); end); module:hook("resource-unbind", function(event) del_client(event.session, module.host); service[module.host]:remove_subscription(xmlns_c2s_session, module.host, event.session.full_jid); service[module.host]:remove_subscription(xmlns_s2s_session, module.host, event.session.full_jid); end); -- Add/remove s2s sessions module:hook("s2sout-established", function(event) add_host(event.session, "out", module.host); end); module:hook("s2sin-established", function(event) add_host(event.session, "in", module.host); end); module:hook("s2sout-destroyed", function(event) del_host(event.session, "out", module.host); end); module:hook("s2sin-destroyed", function(event) del_host(event.session, "in", module.host); end); end
mit
madpilot78/ntopng
scripts/lua/inc/users.lua
1
1781
local page_utils = require("page_utils") local get_users_url = ntop.getHttpPrefix().."/lua/admin/get_users.lua" local users_type = {ntopng=ternary(ntop.isnEdge(), i18n("nedge.system_users"), i18n("login.web_users"))} local title = users_type["ntopng"] page_utils.print_page_title(title) print [[ <div id="table-users"></div> <script> $("#table-users").datatable({ url: "]] print (get_users_url) print [[", showPagination: true, title: "", buttons: [ "<a href='#add_user_dialog' role='button' class='add-on btn' data-bs-toggle='modal'><i class='fas fa-plus fa-sm'></i></a>" ], tableCallback: function() { // if there is `user` get param then open the user's modal let user = "]] print(_GET["user"]) print [["; if (user !== "nil" && isAdministrator) { reset_pwd_dialog(user); // set the preference tab $(`#change-password-dialog`).removeClass('active'); $(`a[href='#change-password-dialog']`).removeClass('active'); $(`#li_change_prefs > a`).addClass('active'); $(`#change-prefs-dialog`).tab('show'); // show the modal $(`#password_dialog`).modal('show'); } }, columns: [ { title: "]] print(i18n("login.username")) print[[", field: "column_username", sortable: true, css: { textAlign: 'left' } }, { title: "]] print(i18n("users.full_name")) print[[", field: "column_full_name", sortable: true, css: { textAlign: 'left' } }, { title: "]] print(i18n("manage_users.group")) print[[", field: "column_group", sortable: true, css: { textAlign: 'center' } }, { title: "]] print(i18n("users.edit")) print[[", field: "column_edit", css: { textAlign: 'center' } }, ] }); </script> ]]
gpl-3.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/blocks/BlockLiquidFlow.lua
1
12038
--[[ Title: Flowing Water Block Author(s): LiXizhi Date: 2013/12/1 Desc: To keep track of which blocks are actively flowing, Water and Lava each have a pair of block IDs. For water, there is Water (75) and Still Water (76). Still Water will stay in place until it receives a block update. Water updates periodically and will change itself to Still Water when it cannot spread any further. Updating a block next to Still Water will turn it back to Water so it can spread some more. If you edit either type of liquid block, they will spread when placed, since placing a block causes updates. use the lib: ------------------------------------------------------------ NPL.load("(gl)script/apps/Aries/Creator/Game/blocks/BlockLiquidFlow.lua"); local block = commonlib.gettable("MyCompany.Aries.Game.blocks.BlockLiquidFlow") ------------------------------------------------------- ]] local ItemClient = commonlib.gettable("MyCompany.Aries.Game.Items.ItemClient"); local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine") local TaskManager = commonlib.gettable("MyCompany.Aries.Game.TaskManager") local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types") local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic") local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager"); local Materials = commonlib.gettable("MyCompany.Aries.Game.Materials"); local block = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.block"), commonlib.gettable("MyCompany.Aries.Game.blocks.BlockLiquidFlow")); -- register block_types.RegisterBlockClass("BlockLiquidFlow", block); -- Number of horizontally adjacent liquid source blocks. Diagonal doesn't count. Only source blocks of the same -- liquid as the block using the field are counted. local numAdjacentSources = 0; -- Indicates whether the flow direction is optimal. Each array index corresponds to one of the four cardinal directions. local isOptimalFlowDirection = {false, false, false, false}; -- The estimated cost to flow in a given direction from the current point. Each array index corresponds to one of -- the four cardinal directions. local flowCost = {0,0,0,0}; function block:ctor() self.isAutoUserData = true; end function block:Init() end function block:tickRate() return 5; end function block:OnToggle(bx, by, bz) end function block:OnBlockAdded(x, y, z) --block._super.OnBlockAdded(self, x, y, z); if(not GameLogic.isRemote) then if (ParaTerrain.GetBlockTemplateByIdx(x,y,z) == self.id) then GameLogic.GetSim():ScheduleBlockUpdate(x, y, z, self.id, self:tickRate()); end end end -- Returns the amount of fluid decay at the coordinates, or -1 if the block at the coordinates is not the same material as the fluid. -- Source blocks have a decay of 0, and the maximum decay depends on liquid type. water is 7, lava is 3. -- The "decay" value increases as the water is further from the source. A high value means that the water is actually physically downhill. function block:getFlowDecay(x, y, z) if(BlockEngine:GetBlockMaterial(x, y, z) == self.material) then return ParaTerrain.GetBlockUserDataByIdx(x,y,z); else return -1; end end -- getSmallestFlowDecay(World world, intx, int y, int z, int currentSmallestFlowDecay) - Looks up the flow decay at -- the coordinates given and returns the smaller of this value or the provided currentSmallestFlowDecay. If one -- value is valid and the other isn't, the valid value will be returned. Valid values are >= 0. Flow decay is the -- amount that a liquid has dissipated. 0 indicates a source block. function block:getSmallestFlowDecay(x, y, z, last_value) local my_value = self:getFlowDecay(x, y, z); if (my_value < 0) then return last_value; else if (my_value == 0) then numAdjacentSources = numAdjacentSources + 1; end if (my_value >= 8) then my_value = 0; end if(last_value >= 0 and my_value >= last_value) then return last_value; else return my_value; end end end function block:OnNeighborChanged(x,y,z,neighbor_block_id) end -- Updates the flow for the BlockFlowing object. -- making the block still again. function block:updateFlowToStill(x, y, z) -- update block flow local data = ParaTerrain.GetBlockUserDataByIdx(x,y,z); BlockEngine:SetBlock(x, y, z, self.id + 1, data); end -- Returns true if the block at the coordinates can be displaced by the liquid. function block:liquidCanDisplaceBlock(x, y, z) local material = BlockEngine:GetBlockMaterial(x, y, z); if( material == self.material) then return false; else if(material == Materials.lava) then return false; else return not self:blockBlocksFlow(x,y,z); end end end local block_flow_ids; local function block_flow(block_id) if(not block_flow_ids) then block_flow_ids = { [block_types.names.Ladder] = true, --[block_types.names.doorIron] = true, --[block_types.names.signPost] = true, --[block_types.names.reed] = true, }; end return block_flow_ids[block_id]; end -- Returns true if block at coords blocks fluids function block:blockBlocksFlow(x, y, z) local block_id = ParaTerrain.GetBlockTemplateByIdx(x, y, z); if (not block_flow(block_id)) then if (block_id == 0) then return false; else local block = block_types.get(block_id); if(block and block.material:blocksMovement()) then return true; else return false; end end else return true; end end -- determine the path of least resistance, this method returns the lowest possible flow cost for the direction of -- flow indicated. Each necessary horizontal flow adds to the flow cost. function block:calculateFlowCost(x,y,z, accumulatedCost, previousDirectionOfFlow) local final_cost = 1000; for dir = 0, 3 do if ((dir ~= 0 or previousDirectionOfFlow ~= 1) and (dir ~= 1 or previousDirectionOfFlow ~= 0) and (dir ~= 2 or previousDirectionOfFlow ~= 3) and (dir ~= 3 or previousDirectionOfFlow ~= 2)) then local x_ = x; local z_ = z; if (dir == 0) then x_ = x - 1; end if (dir == 1) then x_ = x_ + 1; end if (dir == 2) then z_ = z - 1; end if (dir == 3) then z_ = z_ + 1; end if (not self:blockBlocksFlow(x_, y, z_) and (BlockEngine:GetBlockMaterial(x_, y, z_) ~= self.material or ParaTerrain.GetBlockUserDataByIdx(x_, y, z_) ~= 0)) then if (not self:blockBlocksFlow(x_, y - 1, z_)) then return accumulatedCost; end if (accumulatedCost < 4) then local tmp_cost = self:calculateFlowCost(x_, y, z_, accumulatedCost + 1, dir); if (tmp_cost < final_cost) then final_cost = tmp_cost; end end end end end return final_cost; end -- Returns a boolean array indicating which flow directions are optimal based on each direction's calculated flow -- cost. Each array index corresponds to one of the four cardinal directions. A value of true indicates the -- direction is optimal. function block:getOptimalFlowDirections(x,y,z) for dir = 0, 3 do flowCost[dir] = 1000; local x_ = x; local z_ = z; if (dir == 0) then x_ = x - 1; end if (dir == 1) then x_ = x_ + 1; end if (dir == 2) then z_ = z - 1; end if (dir == 3) then z_ = z_ + 1; end if (not self:blockBlocksFlow(x_, y, z_) and (BlockEngine:GetBlockMaterial(x_, y, z_) ~= self.material or ParaTerrain.GetBlockUserDataByIdx(x_, y, z_) ~= 0)) then if (self:blockBlocksFlow(x_, y - 1, z_)) then flowCost[dir] = self:calculateFlowCost(x_, y, z_, 1, dir); else flowCost[dir] = 0; end end end local dir = flowCost[0]; for i = 1, 3 do if (flowCost[i] < dir) then dir = flowCost[i]; end end for i = 0, 3 do isOptimalFlowDirection[i] = flowCost[i] == dir; end return isOptimalFlowDirection; end -- flowIntoBlock(World world, int x, int y, int z, int newFlowDecay) - Flows into the block at the coordinates and -- changes the block type to the liquid. function block:flowIntoBlock(x,y,z, newFlowDecay) if (self:liquidCanDisplaceBlock(x,y,z) and y>=0) then local block_id = ParaTerrain.GetBlockTemplateByIdx(x,y,z); if (block_id > 0) then if (self.material == Materials.lava) then -- self:triggerLavaMixEffects(x,y,z); else -- Block.blocksList[block_id].DropBlockAsItem(x,y,z); end end BlockEngine:SetBlock(x,y,z, self.id, newFlowDecay, 3); end end -- framemove function block:updateTick(x,y,z) if(GameLogic.isRemote) then return end local cur_decay = self:getFlowDecay(x,y,z); local decay_step = 1; local final_decay; if (cur_decay > 0) then local smallest_decay = -100; numAdjacentSources = 0; smallest_decay = self:getSmallestFlowDecay(x - 1, y, z, smallest_decay); smallest_decay = self:getSmallestFlowDecay(x + 1, y, z, smallest_decay); smallest_decay = self:getSmallestFlowDecay(x, y, z - 1, smallest_decay); smallest_decay = self:getSmallestFlowDecay(x, y, z + 1, smallest_decay); final_decay = smallest_decay + decay_step; if (final_decay >= 8 or smallest_decay < 0) then final_decay = -1; end if (self:getFlowDecay(x, y + 1, z) >= 0) then local decay_top = self:getFlowDecay(x, y + 1, z); if (decay_top >= 8) then final_decay = decay_top; else final_decay = decay_top + 8; end end if (numAdjacentSources >= 2 and self.material == Materials.water) then if (BlockEngine:GetBlockMaterial(x, y - 1, z):isSolid()) then final_decay = 0; elseif (BlockEngine:GetBlockMaterial(x, y - 1, z) == self.material and ParaTerrain.GetBlockUserDataByIdx(x, y - 1, z) == 0) then final_decay = 0; end end if (final_decay == cur_decay) then self:updateFlowToStill(x, y, z); else cur_decay = final_decay; if (final_decay < 0) then BlockEngine:SetBlockToAir(x, y, z, 3); else BlockEngine:SetBlockData(x, y, z, final_decay); GameLogic.GetSim():ScheduleBlockUpdate(x, y, z, self.id, self:tickRate()); BlockEngine:NotifyNeighborBlocksChange(x, y, z, self.id); end end else self:updateFlowToStill(x,y,z); end if (self:liquidCanDisplaceBlock(x, y - 1, z)) then if (cur_decay >= 8) then self:flowIntoBlock(x, y - 1, z, cur_decay); else self:flowIntoBlock(x, y - 1, z, cur_decay + 8); end elseif (cur_decay >= 0 and (cur_decay == 0 or self:blockBlocksFlow(x, y - 1, z))) then local optimal_directions = self:getOptimalFlowDirections( x, y, z); final_decay = cur_decay + decay_step; if (cur_decay >= 8) then final_decay = 1; end if (final_decay >= 8) then return; end if (optimal_directions[0]) then self:flowIntoBlock(x - 1, y, z, final_decay); end if (optimal_directions[1]) then self:flowIntoBlock(x + 1, y, z, final_decay); end if (optimal_directions[2]) then self:flowIntoBlock(x, y, z - 1, final_decay); end if (optimal_directions[3]) then self:flowIntoBlock(x, y, z + 1, final_decay); end end end
gpl-2.0
eXhausted/Ovale
Queue.lua
1
2943
--[[-------------------------------------------------------------------- Copyright (C) 2013, 2014 Johnny C. Lam. See the file LICENSE.txt for copying permission. --]]-------------------------------------------------------------------- -- Double-ended queue. local OVALE, Ovale = ... local OvaleQueue = {} Ovale.OvaleQueue = OvaleQueue --<private-static-properties> local setmetatable = setmetatable --</private-static-properties> --<public-static-properties> OvaleQueue.name = "OvaleQueue" OvaleQueue.first = 1 OvaleQueue.last = 0 OvaleQueue.__index = OvaleQueue --</public-static-properties> --<private-static-methods> local function BackToFrontIterator(invariant, control) control = control - 1 local element = invariant[control] if element then return control, element end end local function FrontToBackIterator(invariant, control) control = control + 1 local element = invariant[control] if element then return control, element end end --</private-static-methods> --<public-static-methods> function OvaleQueue:NewDeque(name) return setmetatable({ name = name, first = 0, last = -1 }, OvaleQueue) end function OvaleQueue:InsertFront(element) local first = self.first - 1 self.first = first self[first] = element end function OvaleQueue:InsertBack(element) local last = self.last + 1 self.last = last self[last] = element end function OvaleQueue:RemoveFront() local first = self.first local element = self[first] if element then self[first] = nil self.first = first + 1 end return element end function OvaleQueue:RemoveBack() local last = self.last local element = self[last] if element then self[last] = nil self.last = last - 1 end return element end function OvaleQueue:At(index) if index > self:Size() then return end return self[self.first + index - 1] end function OvaleQueue:Front() return self[self.first] end function OvaleQueue:Back() return self[self.last] end function OvaleQueue:BackToFrontIterator() return BackToFrontIterator, self, self.last + 1 end function OvaleQueue:FrontToBackIterator() return FrontToBackIterator, self, self.first - 1 end function OvaleQueue:Reset() for i in self:BackToFrontIterator() do self[i] = nil end self.first = 0 self.last = -1 end function OvaleQueue:Size() return self.last - self.first + 1 end function OvaleQueue:DebuggingInfo() Ovale:Print("Queue %s has %d item(s), first=%d, last=%d.", self.name, self:Size(), self.first, self.last) end --</public-static-methods> --<public-static-properties> -- Queue (FIFO) methods OvaleQueue.NewQueue = OvaleQueue.NewDeque OvaleQueue.Insert = OvaleQueue.InsertBack OvaleQueue.Remove = OvaleQueue.RemoveFront OvaleQueue.Iterator = OvaleQueue.FrontToBackIterator -- Stack (LIFO) methods OvaleQueue.NewStack = OvaleQueue.NewDeque OvaleQueue.Push = OvaleQueue.InsertBack OvaleQueue.Pop = OvaleQueue.RemoveBack OvaleQueue.Top = OvaleQueue.Back --</public-static-properties>
mit
p00ria/Grandex
plugins/ClashOfClans.lua
1
3002
local apikey = '' local function run(msg, matches) if matches[1]:lower() == 'clan' or matches[1]:lower() == 'clash' or matches[1]:lower() == 'clantag' or matches[1]:lower() == 'tag' then local clantag = matches[2] if string.match(matches[2], '^#.+$') then clantag = string.gsub(matches[2], '#', '') end clantag = string.upper(clantag) local curl = 'curl -X GET --header "Accept: application/json" --header "authorization: Bearer '..apikey..'" "https://api.clashofclans.com/v1/clans/%23'..clantag..'"' cmd = io.popen(curl) local result = cmd:read('*all') local jdat = json:decode(result) if jdat.reason then if jdat.reason == 'accessDenied' then return 'برای ثبت API Key خود به سایت زیر بروید\ndeveloper.clashofclans.com' end return '#Error\n'..jdat.reason end local text = 'Clan Tag: '.. jdat.tag text = text..'\nClan Name: '.. jdat.name text = text..'\nDescription: '.. jdat.description text = text..'\nType: '.. jdat.type text = text..'\nWar Frequency: '.. jdat.warFrequency text = text..'\nClan Level: '.. jdat.clanLevel text = text..'\nWar Wins: '.. jdat.warWins text = text..'\nClan Points: '.. jdat.clanPoints text = text..'\nRequired Trophies: '.. jdat.requiredTrophies text = text..'\nMembers: '.. jdat.members text = text..'\n\nGrandex Bot' cmd:close() return text end if matches[1]:lower() == 'members' or matches[1]:lower() == 'clashmembers' or matches[1]:lower() == 'clanmembers' then local members = matches[2] if string.match(matches[2], '^#.+$') then members = string.gsub(matches[2], '#', '') end members = string.upper(members) local curl = 'curl -X GET --header "Accept: application/json" --header "authorization: Bearer '..apikey..'" "https://api.clashofclans.com/v1/clans/%23'..members..'/members"' cmd = io.popen(curl) local result = cmd:read('*all') local jdat = json:decode(result) if jdat.reason then if jdat.reason == 'accessDenied' then return 'برای ثبت API Key خود به سایت زیر بروید\ndeveloper.clashofclans.com' end return '#Error\n'..jdat.reason end local leader = "" local coleader = "" local items = jdat.items leader = 'Clan Moderators: \n' for i = 1, #items do if items[i].role == "leader" then leader = leader.."\nLeader: "..items[i].name.."\nLevel: "..items[i].expLevel end if items[i].role == "coLeader" then coleader = coleader.."\nCo-Leader: "..items[i].name.."\nLevel: "..items[i].expLevel end end text = leader.."\n"..coleader.."\n\nClan Members:" for i = 1, #items do text = text..'\n'..i..'- '..items[i].name..'\nlevel: '..items[i].expLevel.."\n" end text = text.."\n\nGrandex Bot" cmd:close() return text end end return { patterns = { "^[/!#](clash) (.*)$", "^[/!#](clan) (.*)$", "^[/!#](clantag) (.*)$", "^[/!#](tag) (.*)$", "^[/!#](clashmembers) (.*)$", "^[/!#](clanmembers) (.*)$", "^[/!#](members) (.*)$", }, run = run }
gpl-2.0
salehvw0011/stfbot
libs/XMLElement.lua
569
4025
-- Copyright 2009 Leo Ponomarev. Distributed under the BSD Licence. -- updated for module-free world of lua 5.3 on April 2 2015 -- Not documented at all, but not interesting enough to warrant documentation anyway. local setmetatable, pairs, ipairs, type, getmetatable, tostring, error = setmetatable, pairs, ipairs, type, getmetatable, tostring, error local table, string = table, string local XMLElement={} local mt XMLElement.new = function(lom) return setmetatable({lom=lom or {}}, mt) end local function filter(filtery_thing, lom) filtery_thing=filtery_thing or '*' for i, thing in ipairs(type(filtery_thing)=='table' and filtery_thing or {filtery_thing}) do if thing == "text()" then if type(lom)=='string' then return true end elseif thing == '*' then if type(lom)=='table' then return true end else if type(lom)=='table' and string.lower(lom.tag)==string.lower(thing) then return true end end end return nil end mt ={ __index = { getAttr = function(self, attribute) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end return self.lom.attr[attribute] end, setAttr = function(self, attribute, value) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if value == nil then return self:removeAttr(attribute) end self.lom.attr[attribute]=tostring(value) return self end, removeAttr = function(self, attribute) local lom = self.lom if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if not lom.attr[attribute] then return self end for i,v in ipairs(lom.attr) do if v == attribute then table.remove(lom.attr, i) break end end lom.attr[attribute]=nil end, removeAllAttributes = function(self) local attr = self.lom.attr for i, v in pairs(self.lom.attr) do attr[i]=nil end return self end, getAttributes = function(self) local attr = {} for i, v in ipairs(self.lom.attr) do table.insert(attr,v) end return attr end, getXML = function(self) local function getXML(lom) local attr, inner = {}, {} for i, attribute in ipairs(lom.attr) do table.insert(attr, string.format('%s=%q', attribute, lom.attr[attribute])) end for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getXML(v)) else error("oh shit") end end local tagcontents = table.concat(inner) local attrstring = #attr>0 and (" " .. table.concat(attr, " ")) or "" if #tagcontents>0 then return string.format("<%s%s>%s</%s>", lom.tag, attrstring, tagcontents, lom.tag) else return string.format("<%s%s />", lom.tag, attrstring) end end return getXML(self.lom) end, getText = function(self) local function getText(lom) local inner = {} for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getText(v)) end end return table.concat(inner) end return getText(self.lom) end, getChildren = function(self, filter_thing) local res = {} for i, node in ipairs(self.lom) do if filter(filter_thing, node) then table.insert(res, type(node)=='table' and XMLElement.new(node) or node) end end return res end, getDescendants = function(self, filter_thing) local res = {} local function descendants(lom) for i, child in ipairs(lom) do if filter(filter_thing, child) then table.insert(res, type(child)=='table' and XMLElement.new(child) or child) if type(child)=='table' then descendants(child) end end end end descendants(self.lom) return res end, getChild = function(self, filter_thing) for i, node in ipairs(self.lom) do if filter(filter_thing, node) then return type(node)=='table' and XMLElement.new(node) or node end end end, getTag = function(self) return self.lom.tag end }} return XMLElement
gpl-2.0
pakoito/ToME---t-engine4
game/modules/tome/data/gfx/particles/slime.lua
3
1217
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org base_size = 32 return { base = 1000, angle = { 0, 360 }, anglev = { 2000, 4000 }, anglea = { 20, 60 }, life = { 5, 10 }, size = { 4, 7 }, sizev = {0, 0}, sizea = {0, 0}, r = {0, 0}, rv = {0, 0}, ra = {0, 0}, g = {80, 200}, gv = {0, 10}, ga = {0, 0}, b = {0, 0}, bv = {0, 0}, ba = {0, 0}, a = {155, 255}, av = {0, 0}, aa = {0, 0}, }, function(self) self.nb = (self.nb or 0) + 1 if self.nb < 6 then self.ps:emit(100) end end
gpl-3.0
Laterus/Darkstar-Linux-Fork
scripts/zones/La_Theine_Plateau/Zone.lua
1
2039
----------------------------------- -- -- Zone: La_Theine_Plateau -- ----------------------------------- package.loaded["scripts/globals/quests"] = nil; require("scripts/globals/quests"); require("scripts/globals/settings"); package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; if (player:getQuestStatus(WINDURST, I_CAN_HEAR_A_RAINBOW) == 1 and player:hasItem(1125)) then colors = player:getVar("ICanHearARainbow"); g = (tonumber(colors) % 16 >= 8); b = (tonumber(colors) % 32 >= 16); cs = 0x007b; if (g == false) then player:setVar("ICanHearARainbow_Weather",10); player:setVar("ICanHearARainbow",colors+8); elseif (b == false) then player:setVar("ICanHearARainbow_Weather",6); player:setVar("ICanHearARainbow",colors+16); else cs = -1; end end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,menuchoice) --print("CSID: ",csid); --print("RESULT: ",menuchoice); if (csid == 0x007b) then weather = player:getVar("ICanHearARainbow_Weather"); if (player:getVar("ICanHearARainbow") < 127) then player:updateEvent(0,0,weather); else player:updateEvent(0,0,weather,6); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,menuchoice) --print("CSID: ",csid); --print("RESULT: ",menuchoice); if (csid == 0x007b) then player:setVar("ICanHearARainbow_Weather",0); end end;
gpl-3.0
RyMarq/Zero-K
units/vehcapture.lua
1
4212
return { vehcapture = { unitname = [[vehcapture]], name = [[Dominatrix]], description = [[Capture Rover]], acceleration = 0.222, brakeRate = 0.385, buildCostMetal = 420, builder = false, buildPic = [[vehcapture.png]], canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[26 26 50]], collisionVolumeType = [[cylZ]], selectionVolumeOffsets = [[0 0 0]], selectionVolumeScales = [[40 40 50]], selectionVolumeType = [[cylZ]], corpse = [[DEAD]], customParams = { modelradius = [[13]], turnatfullspeed = [[1]], cus_noflashlight = 1, }, explodeAs = [[BIG_UNITEX]], footprintX = 3, footprintZ = 3, iconType = [[vehiclespecial]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 820, maxSlope = 18, maxVelocity = 1.95, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[TANK3]], noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP]], objectName = [[corvrad_big.s3o]], script = [[vehcapture.lua]], selfDestructAs = [[BIG_UNITEX]], sightDistance = 550, trackOffset = -7, trackStrength = 5, trackStretch = 1, trackType = [[StdTank]], trackWidth = 28, turninplace = 0, turnRate = 420, workerTime = 0, weapons = { { def = [[CAPTURERAY]], badTargetCategory = [[UNARMED FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { CAPTURERAY = { name = [[Capture Ray]], beamdecay = 0.9, beamTime = 1/30, beamttl = 3, coreThickness = 0, craterBoost = 0, craterMult = 0, customparams = { capture_scaling = 1, is_capture = 1, post_capture_reload = 360, stats_hide_damage = 1, -- continuous laser stats_hide_reload = 1, light_radius = 120, light_color = [[0 0.6 0.15]], }, damage = { default = 11.1, }, explosionGenerator = [[custom:NONE]], fireStarter = 30, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 0, largeBeamLaser = true, laserFlareSize = 0, minIntensity = 1, range = 450, reloadtime = 1/30, rgbColor = [[0 0.8 0.2]], scrollSpeed = 2, soundStart = [[weapon/laser/pulse_laser2]], soundStartVolume = 0.5, soundTrigger = true, sweepfire = false, texture1 = [[dosray]], texture2 = [[flare]], texture3 = [[flare]], texture4 = [[smallflare]], thickness = 4.2, tolerance = 5000, turret = true, waterweapon = true, weaponType = [[BeamLaser]], weaponVelocity = 500, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[26 26 50]], collisionVolumeType = [[cylZ]], object = [[corvrad_big_dead.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2c.s3o]], }, }, } }
gpl-2.0
TeamHypersomnia/Hypersomnia
hypersomnia/content/gfx/resistance_torso_pistol_shot_2.meta.lua
2
2749
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.40000000596046448, amplification = 100, light_colors = { "223 113 38 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = -1, y = 15 }, rotation = -87.207298278808594 }, head = { pos = { x = -2, y = 1 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 69, y = 6 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 19, y = -5 }, rotation = 92 }, shoulder = { pos = { x = -21, y = -6 }, rotation = 87 }, strafe_facing_offset = -90 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
RyMarq/Zero-K
LuaRules/Gadgets/factory_anti_slacker.lua
1
1779
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Factory Anti Slacker", desc = "Inhibits factory blocking.", author = "Licho, edited by KingRaptor", date = "10.4.2009", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end local spGetUnitDefID = Spring.GetUnitDefID local spGetGameFrame = Spring.GetGameFrame local spSetUnitBlocking = Spring.SetUnitBlocking local spGetUnitIsDead = Spring.GetUnitIsDead local noEject = { [UnitDefNames["staticmissilesilo"].id] = true, [UnitDefNames["factoryship"].id] = true, [UnitDefNames["factoryplane"].id] = true, [UnitDefNames["factorygunship"].id] = true, } local ghostFrames = 30 --how long the unit will be ethereal local setBlocking = {} --indexed by gameframe, contains a subtable of unitIDs function gadget:GameFrame(n) if setBlocking[n] then --restore blocking for unitID, _ in pairs(setBlocking[n]) do if not spGetUnitIsDead(unitID) then spSetUnitBlocking(unitID, true) end end setBlocking[n] = nil end end function gadget:UnitFromFactory(unitID, unitDefID, teamID, builderID, builderDefID) if not noEject[builderDefID] then --Spring.Echo("Ejecting unit") local frame = spGetGameFrame() + ghostFrames if not setBlocking[frame] then setBlocking[frame] = {} end setBlocking[frame][unitID] = true spSetUnitBlocking(unitID, false) end end
gpl-2.0
RyMarq/Zero-K
effects/beamlaser.lua
25
2996
-- beamlaser_violet_hit_200 -- beamlaser_blue_hit_200 return { ["beamlaser_violet_hit_200"] = { usedefaultexplosions = false, pikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.02, color = [[0.75,0.5,1]], dir = [[-4 r4 r4, 1 r4, -4 r4 r4]], length = 1, lengthgrowth = 1, width = 4, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.75 0 0.01 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 4, particlelife = 20, particlelifespread = 5, particlesize = 4, particlesizespread = 2, particlespeed = 4, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["beamlaser_blue_hit_200"] = { usedefaultexplosions = false, pikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.02, color = [[0.75,0.75,1]], dir = [[-4 r4 r4, 1 r4, -4 r4 r4]], length = 1, lengthgrowth = 1, width = 4, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.75 0 0.01 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 4, particlelife = 20, particlelifespread = 5, particlesize = 4, particlesizespread = 2, particlespeed = 4, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, }
gpl-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Commands/CommandDetect.lua
1
2742
--[[ Title: detect Author(s): LiXizhi Date: 2016/1/13 Desc: detect command use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandDetect.lua"); ------------------------------------------------------- ]] NPL.load("(gl)script/ide/System/Core/ObjectPath.lua"); local ObjectPath = commonlib.gettable("System.Core.ObjectPath") local CmdParser = commonlib.gettable("MyCompany.Aries.Game.CmdParser"); local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine") local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types") local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic") local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager"); local Commands = commonlib.gettable("MyCompany.Aries.Game.Commands"); local CommandManager = commonlib.gettable("MyCompany.Aries.Game.CommandManager"); Commands["detect"] = { name="detect", quick_ref="/detect [entity_name] [-p x y z (dx dy dz)] [-r radius]", desc=[[detect if given entity_name entered the given region @param entity_name: name of the entity, if not specified it means the players @param -p x y z (dx dy dz): specify a aabb region to detect. please note, if dx dy dz is not specified, it will detect a single point or a sphere region if -r is specified. @param -r radius: specify the radius if -p is a point. @return true if entity exist or false if not. Examples: /detect * /tip $(property get -all WindowText) /property set -all WindowText helloworld /property WindowText helloworld short cut /property AsyncChunkMode false ]], handler = function(cmd_name, cmd_text, cmd_params) local set_get, objPath, name, value; bAsyncMode, cmd_text = CmdParser.ParseBool(cmd_text); name, cmd_text = CmdParser.ParseString(cmd_text); if(name == "set" or name == "get") then set_get = name; name, cmd_text = CmdParser.ParseString(cmd_text); else -- default to set set_get = "set"; end if(name:match("^[/%-]")) then objPath = name; name, cmd_text = CmdParser.ParseString(cmd_text); end if(name) then if(not objPath) then objPath = name_to_objpath[name] or "-scene-1_1"; end objPath = objPath:gsub("-", "/"); local root_name = objPath:match("^/(%w+)") if(allowed_root_names[root_name or ""]) then local path = ObjectPath:new():init(objPath); if(path) then if(set_get == "get") then value = path:GetFieldStr(name); return value; else path:SetFieldStr(name, cmd_text); end else GameLogic.AddBBS(nil, format(L"root path %s is not found", objPath)); end else GameLogic.AddBBS(nil, L"root object path is not allowed"); end end end, };
gpl-2.0
eriche2016/nn
Padding.lua
17
2404
local Padding, parent = torch.class('nn.Padding', 'nn.Module') -- pad puts in [pad] amount of [value] over dimension [dim], starting at index [index] in that dimension. If pad<0, index counts from the left. If pad>0 index counts from the right -- index = 1 pads before index 1. index = 2 pads starting before index 2 and after index 1 in dimension [dim] function Padding:__init(dim, pad, nInputDim, value, index) self.value = value or 0 self.index = index or 1 self.dim = dim self.pad = pad self.nInputDim = nInputDim self.outputSize = torch.LongStorage() parent.__init(self) end function Padding:updateOutput(input) self.outputSize:resize(input:dim()) self.outputSize:copy(input:size()) local dim = self.dim if self.nInputDim and input:dim() ~= self.nInputDim then dim = dim + 1 end self.outputSize[dim] = self.outputSize[dim] + math.abs(self.pad) self.output:resize(self.outputSize) self.output:fill(self.value) local index = self.index local pad = self.pad if pad > 0 then index = input:size(dim) - index + 2 else pad = -pad end if index == 1 then self.output:narrow(dim, 1 + pad, input:size(dim)):copy(input) elseif index == input:size(dim) + 1 then self.output:narrow(dim, 1, input:size(dim)):copy(input) else self.output:narrow(dim, 1, index - 1):copy(input:narrow(dim, 1, index - 1)) self.output:narrow(dim, index + pad, input:size(dim) - (index - 1)):copy(input:narrow(dim, index, input:size(dim) - (index - 1))) end return self.output end function Padding:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input) local dim = self.dim if self.nInputDim and input:dim() ~= self.nInputDim then dim = dim + 1 end local index = self.index local pad = self.pad if pad > 0 then index = input:size(dim) - index + 2 else pad = -pad end if index == 1 then self.gradInput:copy(gradOutput:narrow(dim, 1 + pad, input:size(dim))) elseif index == input:size(dim) + 1 then self.gradInput:copy(gradOutput:narrow(dim, 1, input:size(dim))) else self.gradInput:narrow(dim, 1, index - 1):copy(gradOutput:narrow(dim, 1, index - 1)) self.gradInput:narrow(dim, index, input:size(dim) - (index - 1)):copy(gradOutput:narrow(dim, index + pad, input:size(dim) - (index - 1))) end return self.gradInput end
bsd-3-clause
soheil22222222/mm
plugins/lock_fosh.lua
2
1126
local function run(msg, matches) if is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['fosh'] then lock_fosh = data[tostring(msg.to.id)]['settings']['fosh'] end end end local chat = get_receiver(msg) local user = "user#id"..msg.from.id if lock_fosh == "yes" then delete_msg(msg.id, ok_cb, true) end end return { patterns = { "(ک*س)$", "کیر", "کص", "کونی", "مادر جنده", "کیری مقام", "ننت گاییدم", "مادر عمومی", "یتیم", "کــــــــــیر", "کــــــــــــــــــــــــــــــیر", "کـیـــــــــــــــــــــــــــــــــــــــــــــــــــر", "ک×یر", "ک÷یر", "ک*ص", "کــــــــــیرر", "kir", "([Kk][Oo][Ss] (.*)", "گوساله", "gosale", "gusale", }, run = run }
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/The_Eldieme_Necropolis/npcs/Sarcophagus.lua
1
2121
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Sarcophagus -- Involved in Quest: The Requiem (BARD AF2) -- @zone 195 -- @pos -420 8 500 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(4154,1) == true and trade:getItemCount() == 1) then YumKilled = player:getVar("TheRequiemYumKilled"); if(player:getVar("TheRequiemCS") == 3 and YumKilled == 0) then player:messageSpecial(SENSE_OF_FOREBODING); SpawnMob(17576265):updateEnmity(player); -- Spawn Yum Kimil NM @pos -414 8 499 SpawnMob(17576267):updateEnmity(player); -- Spawn Owl Guardian NM @pos -414 8 501 SpawnMob(17576266):updateEnmity(player); -- Spawn Dog Guardian NM @pos -414 8 497 elseif(player:getVar("TheRequiemCS") == 3 and YumKilled == 1) then player:startEvent(0x002e); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(SARCOPHAGUS_CANNOT_BE_OPENED); -- Standard dialog 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 == 0x002e) then player:setVar("TheRequiemCS",0); player:setVar("TheRequiemYumKilled",0); player:addKeyItem(STAR_RING1); player:messageSpecial(KEYITEM_OBTAINED,STAR_RING1); -- Star Ring (Key Item). player:tradeComplete(); end end;
gpl-3.0
TerminalShell/zombiesurvival
entities/entities/prop_messagebeacon/init.lua
1
2352
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") ENT.m_Health = 100 function ENT:Initialize() self:SetModel("models/props_combine/combine_mine01.mdl") --self:PhysicsInit(SOLID_VPHYSICS) self:PhysicsInitBox(Vector(-8.29, -8.29, 0), Vector(8.29, 8.29, 10.13)) self:SetCollisionBounds(Vector(-8.29, -8.29, 0), Vector(8.29, 8.29, 10.13)) self:SetCollisionGroup(COLLISION_GROUP_WORLD) self:SetUseType(SIMPLE_USE) self:SetModelScale(0.333, 0) local phys = self:GetPhysicsObject() if phys:IsValid() then phys:SetMaterial("metal") phys:EnableMotion(false) //phys:EnableCollisions(false) phys:Wake() end local worldhint = ents.Create("point_worldhint") if worldhint:IsValid() then self.WorldHint = worldhint worldhint:SetPos(self:GetPos()) worldhint:SetParent(self) worldhint:Spawn() worldhint:SetViewable(TEAM_HUMAN) worldhint:SetRange(7680) worldhint:SetHint(self:GetMessage()) end end function ENT:KeyValue(key, value) key = string.lower(key) if key == "messageid" then value = tonumber(value) if not value then return end self:SetMessageID(value) end end function ENT:OnTakeDamage(dmginfo) self:TakePhysicsDamage(dmginfo) if not self.Destroyed then local attacker = dmginfo:GetAttacker() if not (attacker:IsValid() and attacker:IsPlayer() and attacker:Team() == TEAM_HUMAN) then if attacker.LifeBarricadeDamage ~= nil and self:HumanNearby() then attacker.LifeBarricadeDamage = attacker.LifeBarricadeDamage + dmginfo:GetDamage() end self.m_Health = self.m_Health - dmginfo:GetDamage() if self.m_Health <= 0 then self.Destroyed = true local effectdata = EffectData() effectdata:SetOrigin(self:LocalToWorld(self:OBBCenter())) util.Effect("Explosion", effectdata, true, true) end end end end function ENT:SetMessageID(id) self:SetDTInt(0, id) self.WorldHint:SetHint(self:GetMessage()) end function ENT:AltUse(activator, tr) self:PackUp(activator) end function ENT:OnPackedUp(pl) pl:GiveEmptyWeapon("weapon_zs_beacon") pl:GiveAmmo(1, "striderminigun") pl.m_PackedMessageBeacons = pl.m_PackedMessageBeacons or {} table.insert(pl.m_PackedMessageBeacons, 1, self.m_Health) self:Remove() end function ENT:Think() if self.Destroyed then self:Remove() end end function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end
gpl-3.0
NPLPackages/paracraft
script/apps/Aries/mcml/pe_aries_lobbyservice.lua
1
10019
--[[ Title: Author(s): Leio Date: 2011/08/16 Desc: use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/mcml/pe_aries_lobbyservice.lua"); ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Service/CommonClientService.lua"); local CommonClientService = commonlib.gettable("MyCompany.Aries.Service.CommonClientService"); local pe_aries_lobbyservice_template = commonlib.gettable("MyCompany.Aries.mcml_controls.pe_aries_lobbyservice_template"); local pe_aries_lobbyservice_template_item = commonlib.gettable("MyCompany.Aries.mcml_controls.pe_aries_lobbyservice_template_item"); NPL.load("(gl)script/apps/Aries/Quest/NPCList.lua"); local NPCList = commonlib.gettable("MyCompany.Aries.Quest.NPCList"); NPL.load("(gl)script/apps/Aries/Scene/WorldManager.lua"); local WorldManager = commonlib.gettable("MyCompany.Aries.WorldManager"); function pe_aries_lobbyservice_template.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) local childnode; for childnode in mcmlNode:next() do Map3DSystem.mcml_controls.create(rootName, childnode, bindingContext, _parent, left, top, width, height, style, parentLayout); end end function pe_aries_lobbyservice_template_item.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) NPL.load("(gl)script/apps/Aries/CombatRoom/LobbyClientServicePage.lua"); local LobbyClientServicePage = commonlib.gettable("MyCompany.Aries.CombatRoom.LobbyClientServicePage"); local parentNode = mcmlNode:GetParent("aries:lobbyservice_template"); local keyname; local search_worldname; if(parentNode)then keyname = parentNode:GetAttributeWithCode("keyname",nil,true); search_worldname = parentNode:GetAttributeWithCode("worldname",nil,true); end local property = mcmlNode:GetAttributeWithCode("property"); local tempaltes = LobbyClientServicePage.GetGameTemplates(); local template; --先找worldname if(search_worldname)then local k,v; for k,v in pairs(tempaltes) do if(v and v.worldname == search_worldname)then template = v; break; end end elseif(keyname)then template = tempaltes[keyname]; end if(not template)then return end if(property == "loots_menu")then NPL.load("(gl)script/kids/3DMapSystemApp/mcml/pe_togglebuttons.lua"); local pe_togglebuttons = commonlib.gettable("Map3DSystem.mcml_controls.pe_togglebuttons"); local mode = template.mode_list or "1,2,3"; local selected_mode = parentNode:GetAttributeWithCode("selected_mode",nil,true) or 1; local onclick = mcmlNode:GetAttributeWithCode("onclick",nil,true); local OnlyShowSelectedMode = mcmlNode:GetBool("OnlyShowSelectedMode"); local mode_list = LobbyClientServicePage.LoadModeList(keyname) local result = {}; local k,v; for k,v in ipairs(mode_list) do local label = v.lable_1 or ""; label = label.."难度掉落"; local node = { label = label, mode = v.mode, }; if(selected_mode == v.mode)then node.selected = true; end if(OnlyShowSelectedMode)then if(node.selected)then table.insert(result,node); end else table.insert(result,node); end end mcmlNode:SetAttribute("DataSource",result); mcmlNode:SetAttribute("onclick",onclick); pe_togglebuttons.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) elseif(property == "pic")then local worldname = template.worldname; local pic = template.pic; local usesmaller = mcmlNode:GetBool("usesmaller"); if(not pic)then if(CommonClientService.IsKidsVersion())then pic = string.format("Texture/Aries/LobbyService/WorldPic/%s.png",worldname); else if(usesmaller)then pic = string.format("Texture/Aries/LobbyService/WorldPic/Teen/%s_64.png",worldname); else pic = string.format("Texture/Aries/LobbyService/WorldPic/Teen/%s.png",worldname); end end end mcmlNode:SetAttribute("src", pic); Map3DSystem.mcml_controls.pe_img.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout); elseif(property == "worldname" or property == "world_label" or property == "world_description" )then local value; if(property == "worldname")then value = template.worldname; elseif(property == "world_label")then value = template.name; elseif(property == "world_description")then value = template.desc; end mcmlNode:SetInnerText(value); Map3DSystem.mcml_controls.pe_simple_styles.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout); end end local pe_aries_lobbyservice = commonlib.gettable("MyCompany.Aries.mcml_controls.pe_aries_lobbyservice"); local pe_aries_lobbyservice_item = commonlib.gettable("MyCompany.Aries.mcml_controls.pe_aries_lobbyservice_item"); function pe_aries_lobbyservice.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) local childnode; for childnode in mcmlNode:next() do Map3DSystem.mcml_controls.create(rootName, childnode, bindingContext, _parent, left, top, width, height, style, parentLayout); end end function pe_aries_lobbyservice_item.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) NPL.load("(gl)script/apps/Aries/CombatRoom/LobbyClientServicePage.lua"); local LobbyClientServicePage = commonlib.gettable("MyCompany.Aries.CombatRoom.LobbyClientServicePage"); local parentNode = mcmlNode:GetParent("aries:lobbyservice"); local gameinfo; if(parentNode)then gameinfo = parentNode:GetAttributeWithCode("gameinfo",nil,true); end if(not gameinfo)then return end local property = mcmlNode:GetAttributeWithCode("property"); local label = mcmlNode:GetAttributeWithCode("label"); local tempaltes = LobbyClientServicePage.GetGameTemplates(); local keyname = gameinfo.keyname; local template = tempaltes[keyname]; if(not template)then return end if(property == "pic")then local worldname = template.worldname; local pic = template.pic; if(not pic)then pic = string.format("Texture/Aries/LobbyService/WorldPic/%s.png",worldname); end mcmlNode:SetAttribute("src", pic); Map3DSystem.mcml_controls.pe_img.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout); elseif(property == "worldname" or property == "world_label" or property == "world_label_and_level_range" or property == "world_description" )then local value; if(property == "worldname")then value = template.worldname; elseif(property == "world_label_and_level_range")then local name = template.name; local min_level = template.min_level or 0; local max_level = template.max_level or 100; --value = string.format("%s(%d-%d)",name,min_level,max_level); value = string.format("%s(%d)",name,min_level); elseif(property == "world_label")then value = template.name; elseif(property == "world_description")then value = template.desc; end value = tostring(value) ; if(not value or value == "" or value == "nil")then value = "无"; end if(not label or label == "" or label == "nil")then value = string.format("%s",value); else value = string.format("%s:%s",label or "",value); end mcmlNode:SetInnerText(value); Map3DSystem.mcml_controls.pe_simple_styles.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout); elseif(property == "id" or property == "name" or property == "leader_text" or property == "min_level" or property == "max_level" or property == "status" or property == "player_count" or property == "requirement_tag" or property == "max_players" or property == "password" or property == "owner_nid" or property == "magic_star_level" or property == "attack" or property == "hit" or property == "hp" or property == "mode" or property == "cure" or property == "guard_map" )then local value = gameinfo[property]; if(property == "mode")then value = value or 1; if(value == 1)then value = "简单"; elseif(value == 2)then value = "普通"; elseif(value == 3)then value = "精英"; end elseif(property == "requirement_tag")then if(value)then value = string.gsub(value,"storm","风暴系") value = string.gsub(value,"fire","烈火系") value = string.gsub(value,"life","生命系") value = string.gsub(value,"death","死亡系") value = string.gsub(value,"ice","寒冰系") end elseif(property == "guard_map")then local function get_value(guard_map,key,label) if(guard_map)then local v = guard_map[key]; v = tostring(v); if(v and v ~= "" and v ~= "nil")then v = string.format("%s %s%%",label,v); return v; end end end local function link_str(v1,v2) if(v1 and v2 and v1~="" and v2~="")then local v = string.format("%s,%s",v1,v2); return v; end end local s = ""; local v = get_value(value,"storm","风暴"); if(v)then s = v; end v = get_value(value,"fire","烈火"); if(v)then s = s..","..v; end v = get_value(value,"life","生命"); if(v)then s = s..","..v; end v = get_value(value,"death","死亡"); if(v)then s = s..","..v; end v = get_value(value,"ice","寒冰"); if(v)then s = s..","..v; end value = s; else value = tostring(value) ; end if(not value or value == "" or value == "nil")then value = "无"; end if(not label or label == "" or label == "nil")then value = string.format("%s",value); else if(value == "无")then value = ""; else value = string.format("%s:%s",label or "",value); end end mcmlNode:SetInnerText(value); Map3DSystem.mcml_controls.pe_simple_styles.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout); end end
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Tavnazian_Safehold/npcs/Melleupaux.lua
37
1310
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Melleupaux -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MELLEUPAUX_SHOP_DIALOG); stock = {0x4042,1867, --Dagger 0x40b6,8478, --Longsword 0x43B7,8, --Rusty Bolt 0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet) 0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet) showShop(player, STATIC, 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
RyMarq/Zero-K
scripts/shieldassault.lua
8
6613
-- original bos animation by Chris Mackey -- converted to lua by psimyn include 'constants.lua' local base = piece 'base' local shield = piece 'shield' local head = piece 'head' local l_gun = piece 'l_gun' local r_gun = piece 'r_gun' local firept1 = piece 'firept1' local r_barrel = piece 'r_barrel' local firept2 = piece 'firept2' local l_barrel = piece 'l_barrel' local l_leg, lf_lever, lb_lever, l_foot, l_heel, l_heeltoe = piece('l_leg', 'lf_lever', 'lb_lever', 'l_foot', 'l_heel', 'l_heeltoe') local r_leg, rf_lever, rb_lever, r_foot, r_heel, r_heeltoe = piece('r_leg', 'rf_lever', 'rb_lever', 'r_foot', 'r_heel', 'r_heeltoe') local leftLeg = { leg=piece'l_leg', flever=piece'lf_lever', blever=piece'lb_lever', foot=piece'l_foot', heel=piece'l_heel', heeltoe=piece'l_heeltoe'} local rightLeg = { leg=piece'r_leg', flever=piece'rf_lever', blever=piece'rb_lever', foot=piece'r_foot', heel=piece'r_heel', heeltoe=piece'r_heeltoe' } -- constants local smokePiece = { head, l_gun, r_gun } local PACE = 2 -- signals local SIG_WALK = 1 local SIG_AIM = 2 local SIG_RESTORE = 4 -- variables local gun_1 local function Step(front, back) Move(base, y_axis, 0, 2) -- move and turn front leg Move(front.leg, z_axis, 1, 3 * PACE) Turn(front.blever, x_axis, math.rad(-50), math.rad(95) * PACE) Turn(front.foot, x_axis, math.rad(45), math.rad(80) * PACE) Turn(front.flever, x_axis, math.rad(-45), math.rad(65) * PACE) Turn(front.heeltoe, x_axis, math.rad(10), math.rad(20) * PACE) -- move and turn back leg Move(back.leg, z_axis, -2, 3 * PACE) Turn(back.blever, x_axis, math.rad(45), math.rad(95) * PACE) Turn(back.foot, x_axis, math.rad(-35), math.rad(80) * PACE) Turn(back.flever, x_axis, math.rad(20), math.rad(65) * PACE) Turn(back.heeltoe, x_axis, math.rad(-10), math.rad(20) * PACE) Move(base, y_axis, -1, 2) WaitForTurn(front.foot, x_axis) WaitForTurn(back.foot, x_axis) -- sleep for 1 gameframe; stops animation breaking in the Walk loop Sleep(0) end local function Walk() Signal(SIG_WALK) SetSignalMask(SIG_WALK) while true do Step(leftLeg, rightLeg) Step(rightLeg, leftLeg) end end function script.Create() gun_1 = true StartThread(GG.Script.SmokeUnit, unitID, smokePiece) Move(base, x_axis, -2) end local function Stopping() Signal(SIG_WALK) SetSignalMask(SIG_WALK) Move(leftLeg.leg, z_axis, 0, 2) Move(rightLeg.leg, z_axis, 0, 2) Turn(leftLeg.blever, x_axis, 0, math.rad(45)) Turn(leftLeg.foot, x_axis, 0, math.rad(45)) Turn(leftLeg.flever, x_axis, 0, math.rad(45)) Turn(leftLeg.heeltoe, x_axis, 0, math.rad(45)) Turn(rightLeg.blever, x_axis, 0, math.rad(45)) Turn(rightLeg.foot, x_axis, 0, math.rad(45)) Turn(rightLeg.flever, x_axis, 0, math.rad(45)) Turn(rightLeg.heeltoe, x_axis, 0, math.rad(45)) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(Stopping) end local function RestoreAfterDelay() Signal(SIG_RESTORE) SetSignalMask(SIG_RESTORE) Sleep(3000) --move all the pieces to their original spots Turn(head, y_axis, 0, math.rad(100)) Turn(l_gun, x_axis, 0, math.rad(100)) Turn(r_gun, x_axis, 0, math.rad(100)) end function script.AimFromWeapon() return head end function script.AimWeapon(num, heading, pitch) Signal(SIG_AIM) SetSignalMask(SIG_AIM) Turn(head, y_axis, heading, math.rad(100)) Turn(l_gun, x_axis, -pitch, math.rad(100)) Turn(r_gun, x_axis, -pitch, math.rad(100)) WaitForTurn(head, y_axis) StartThread(RestoreAfterDelay) return 1 -- allows fire weapon after WaitForTurn end function script.FireWeapon() if gun_1 then EmitSfx(firept1, GG.Script.UNIT_SFX1) EmitSfx(firept1, GG.Script.UNIT_SFX2) Move(r_barrel, z_axis, -4, 0) Move(r_gun, z_axis, -2, 0) Move(r_barrel, z_axis, 0, 2.5) Move(r_gun, z_axis, 0, 1.25) else EmitSfx(firept2, GG.Script.UNIT_SFX1) EmitSfx(firept2, GG.Script.UNIT_SFX2) Move(l_barrel, z_axis, -4, 0) Move(l_gun, z_axis, -2, 0) Move(l_barrel, z_axis, 0, 2.5) Move(l_gun, z_axis, 0, 1.25) end end function script.QueryWeapon(num) if num == 1 then -- Gun if gun_1 then return firept1 else return firept2 end else -- Shield return shield end end function script.EndBurst() gun_1 = not gun_1 end function script.BlockShot(num, targetID) if Spring.ValidUnitID(targetID) then local distMult = (Spring.GetUnitSeparation(unitID, targetID) or 0)/280 return GG.OverkillPrevention_CheckBlock(unitID, targetID, 170.1, 35 * distMult, false, false, true) end return false end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= 0.25 then Explode(head, SFX.NONE) Explode(l_gun, SFX.NONE) Explode(r_gun, SFX.NONE) Explode(leftLeg.leg, SFX.NONE) Explode(leftLeg.flever, SFX.NONE) Explode(leftLeg.blever, SFX.NONE) Explode(leftLeg.foot, SFX.NONE) Explode(leftLeg.heel, SFX.NONE) Explode(leftLeg.heeltoe, SFX.NONE) Explode(rightLeg.leg, SFX.NONE) Explode(rightLeg.flever, SFX.NONE) Explode(rightLeg.blever, SFX.NONE) Explode(rightLeg.foot, SFX.NONE) Explode(rightLeg.heel, SFX.NONE) Explode(rightLeg.heeltoe, SFX.NONE) return 1 elseif severity <= 0.5 then Explode(head, SFX.NONE) Explode(l_gun, SFX.NONE) Explode(r_gun, SFX.FALL + SFX.EXPLODE_ON_HIT) Explode(leftLeg.leg, SFX.FALL + SFX.EXPLODE_ON_HIT) Explode(rightLeg.leg, SFX.NONE) Explode(leftLeg.foot, SFX.NONE) Explode(rightLeg.foot, SFX.NONE) Explode(leftLeg.blever, SFX.NONE) Explode(rightLeg.blever, SFX.NONE) Explode(leftLeg.flever, SFX.NONE) Explode(rightLeg.flever, SFX.NONE) Explode(leftLeg.heel, SFX.NONE) Explode(rightLeg.heel, SFX.NONE) Explode(leftLeg.heeltoe, SFX.NONE) Explode(rightLeg.heeltoe, SFX.NONE) return 1 else Explode(head, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT) Explode(l_gun, SFX.NONE) Explode(r_gun, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT) Explode(leftLeg.leg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT) Explode(rightLeg.leg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT) Explode(leftLeg.foot, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT) Explode(rightLeg.foot, SFX.NONE) Explode(leftLeg.blever, SFX.NONE) Explode(rightLeg.blever, SFX.NONE) Explode(leftLeg.flever, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT) Explode(rightLeg.flever, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT) Explode(leftLeg.heel, SFX.NONE) Explode(rightLeg.heel, SFX.NONE) Explode(leftLeg.heeltoe, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT) Explode(rightLeg.heeltoe, SFX.NONE) return 2 end end
gpl-2.0
vince06fr/prosody-modules
mod_rawdebug/mod_rawdebug.lua
32
1337
module:set_global(); local tostring = tostring; local filters = require "util.filters"; local def_env = module:shared("admin_telnet/env"); local rawdebug_enabled = module:shared("sessions"); local full_sessions = prosody.full_sessions; local log = module._log; local rawdebug = {}; def_env.rawdebug = rawdebug; local function new_logger(log, prefix) local msg = prefix .. ": %s"; return function (data) log("debug", msg, tostring(data)) return data; end end function rawdebug:enable(sessionid) local session = full_sessions[sessionid]; if not session then return nil, "No such session"; end local f = { ["stanzas/in"] = new_logger(session.log or log, "RECV"); ["stanzas/out"] = new_logger(session.log or log, "SEND"); }; for type, callback in pairs(f) do filters.add_filter(session, type, callback) end rawdebug_enabled[session] = f; end function rawdebug:disable(sessionid) local session = full_sessions[sessionid]; if not session then return nil, "No such session"; end local f = rawdebug_enabled[session]; for type, callback in pairs(f) do filters.remove_filter(session, type, callback) end end function module.unload() def_env.rawdebug = nil; for session, f in pairs(rawdebug_enabled) do for type, callback in pairs(f) do filters.remove_filter(session, type, callback) end end end
mit
Laterus/Darkstar-Linux-Fork
scripts/zones/Fort_Karugo-Narugo_[S]/Zone.lua
1
1147
----------------------------------- -- -- Zone: Fort_Karugo-Narugo_[S] -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Fort_Karugo-Narugo_[S]/TextIDs"] = nil; require("scripts/zones/Fort_Karugo-Narugo_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,menuchoice) --print("CSID: ",csid); --print("RESULT: ",menuchoice); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,menuchoice) --print("CSID: ",csid); --print("RESULT: ",menuchoice); end;
gpl-3.0
NPLPackages/paracraft
script/kids/3DMapSystemUI/CCS/DefaultAppearance.lua
1
1458
--[[ Title: Character Customization System default appearance Author(s): WangTian Date: 2008/3/12 use the lib: ------------------------------------------------------------ NPL.load("(gl)script/kids/3DMapSystemUI/CCS/DefaultAppearance.lua"); ------------------------------------------------------- Desc: mount a nude CCS character with default appearance ]] local DefaultAppearance = commonlib.gettable("Map3DSystem.UI.CCS.DefaultAppearance") local CCS = commonlib.gettable("Map3DSystem.UI.CCS") local DB = commonlib.gettable("Map3DSystem.DB") local LOG = LOG; -- mount a nude CCS character with default appearance -- @param obj: ParaObject object function Map3DSystem.UI.CCS.DefaultAppearance.MountDefaultAppearance(obj) if(obj == nil or obj:IsValid() == false or obj:IsCharacter() == false) then LOG.std("", "debug", "CCS", "character obj expected got non-character or nil in CCS.DefaultAppearance.MountDefaultAppearance() function call"); return; end -- get the default appearance information local filename = obj:GetPrimaryAsset():GetKeyName(); local item = DB.GetItemByModelFilePath(filename, "Normal Character"); if(not item or not item.Reserved5) then LOG.std("", "debug", "CCS", "no default appearance info for character: "..filename); return; end local sInfo = item.Reserved5; -- TODO: provide CCS infomation setting through non obj_params param -- apply character CCS information CCS.ApplyCCSInfoString(obj, sInfo); end
gpl-2.0
RyMarq/Zero-K
gamedata/modularcomms/weapons/lightninggun.lua
6
1282
local name = "commweapon_lightninggun" local weaponDef = { name = [[Lightning Gun]], areaOfEffect = 8, beamTTL = 12, craterBoost = 0, craterMult = 0, customParams = { is_unit_weapon = 1, extra_damage_mult = 2.5, slot = [[5]], muzzleEffectFire = [[custom:zeus_fire_fx]], light_camera_height = 1600, light_color = [[0.85 0.85 1.2]], light_radius = 200, reaim_time = 1, }, cylinderTargeting = 0, damage = { default = 220, }, explosionGenerator = [[custom:LIGHTNINGPLOSION]], fireStarter = 110, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, intensity = 12, interceptedByShieldType = 1, paralyzeTime = 1, range = 300, reloadtime = 1 + 25/30, rgbColor = [[0.5 0.5 1]], soundStart = [[weapon/more_lightning_fast]], soundTrigger = true, sprayAngle = 500, texture1 = [[lightning]], thickness = 10, turret = true, weaponType = [[LightningCannon]], weaponVelocity = 400, } return name, weaponDef
gpl-2.0
TerminalShell/zombiesurvival
gamemode/zombieclasses/fast_headcrab.lua
1
2546
CLASS.Name = "Fast Headcrab" CLASS.Description = "The male headcrab is considerably faster but less beefy than the female.\nEither way, it's equally as annoying and deadly in groups." CLASS.Help = "> PRIMARY: Lunge attack" CLASS.Model = Model("models/headcrab.mdl") CLASS.Wave = 1 / 4 CLASS.SWEP = "weapon_zs_fastheadcrab" CLASS.Health = 40 CLASS.Speed = 190 CLASS.JumpPower = 100 CLASS.NoFallDamage = true CLASS.NoFallSlowdown = true CLASS.Points = 1 CLASS.Hull = {Vector(-12, -12, 0), Vector(12, 12, 18.1)} CLASS.HullDuck = {Vector(-12, -12, 0), Vector(12, 12, 18.1)} CLASS.ViewOffset = Vector(0, 0, 10) CLASS.ViewOffsetDucked = Vector(0, 0, 10) CLASS.StepSize = 18 // Was 8 CLASS.CrouchedWalkSpeed = 1 CLASS.Mass = 16 CLASS.CantDuck = true CLASS.IsHeadcrab = true CLASS.PainSounds = {"NPC_FastHeadcrab.Pain"} CLASS.DeathSounds = {"NPC_FastHeadcrab.Die"} function CLASS:Move(pl, mv) local wep = pl:GetActiveWeapon() if wep.Move and wep:Move(mv) then return true end end function CLASS:PlayerFootstep(pl, vFootPos, iFoot, strSoundName, fVolume, pFilter) return true end function CLASS:ScalePlayerDamage(pl, hitgroup, dmginfo) return true end function CLASS:CalcMainActivity(pl, velocity) if pl:OnGround() then if velocity:Length2D() > 0.5 then pl.CalcIdeal = ACT_RUN else pl.CalcSeqOverride = 1 end elseif pl:WaterLevel() >= 3 then pl.CalcSeqOverride = 6 else pl.CalcSeqOverride = 3 end return true end function CLASS:UpdateAnimation(pl, velocity, maxseqgroundspeed) pl:FixModelAngles(velocity) local seq = pl:GetSequence() if seq == 3 then if not pl.m_PrevFrameCycle then pl.m_PrevFrameCycle = true pl:SetCycle(0) end pl:SetPlaybackRate(1) return true elseif pl.m_PrevFrameCycle then pl.m_PrevFrameCycle = nil end end if not CLIENT then return end CLASS.HealthBar = surface.GetTextureID("zombiesurvival/healthbar_fastheadcrab") CLASS.Icon = "zombiesurvival/killicons/fastheadcrab" function CLASS:CreateMove(pl, cmd) local wep = pl:GetActiveWeapon() if wep:IsValid() and wep.m_ViewAngles and wep.IsPouncing and wep:IsPouncing() then local maxdiff = FrameTime() * 15 local mindiff = -maxdiff local originalangles = wep.m_ViewAngles local viewangles = cmd:GetViewAngles() local diff = math.AngleDifference(viewangles.yaw, originalangles.yaw) if diff > maxdiff or diff < mindiff then viewangles.yaw = math.NormalizeAngle(originalangles.yaw + math.Clamp(diff, mindiff, maxdiff)) end wep.m_ViewAngles = viewangles cmd:SetViewAngles(viewangles) end end
gpl-3.0
pakoito/ToME---t-engine4
game/engines/default/engine/ui/ListColumns.lua
2
25128
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local Base = require "engine.ui.Base" local Focusable = require "engine.ui.Focusable" local Slider = require "engine.ui.Slider" --- A generic UI multi columns list module(..., package.seeall, class.inherit(Base, Focusable)) function _M:init(t) self.list = assert(t.list, "no list entires") self.columns = assert(t.columns, "no list columns") self.w = assert(t.width, "no list width") assert(t.height or t.nb_items, "no list height/nb_items") self.nb_rows = t.nb_items self.font = t.font or self.font self.row_height = t.item_height or (self.font_h + 6) self.h = t.height or self.row_height * ( (self.nb_rows or 0) + (self.hide_columns and 0 or 1) ) self.sortable = t.sortable self.scrollbar = t.scrollbar self.fct = t.fct self.on_select = t.select --self.on_focus_change = t.on_focus_change self.on_drag = t.on_drag self.on_drag_end = t.on_drag_end self.all_clicks = t.all_clicks self.floating_headers = t.floating_headers or true self.hide_columns = t.hide_columns or false self.dest_area = t.dest_area and t.dest_area or { w = self.w, h = self.h } self.text_shadow = t.text_shadow or self.text_shadow self.click_select = t.click_select or false self.only_display = t.only_display or false if t.select_delay then self:setSelectDelay(t.select_delay) end self.max_h = 0 self.max_h_columns = 0 self.prevrow = 0 self.prev_sel = 0 self.prevclick = 0 self.last_input_was_keyboard = false self.scroll_inertia = 0 self.mouse_pos = { x = 0, y = 0 } if self.scrollbar then self.scrollbar = Slider.new{size=self.h, max=1} end self:setColumns(t.columns) Base.init(self, t) end function _M:generate() -- Create the scrollbar if self.scrollbar then self.scrollbar.h = self.h - (self.hide_columns and 0 or self.max_h_columns) end self.sel = 1 self:selectColumn(1, true) -- Init rows for i=1, #self.list do local row = self.list[i] self:generateRow(row) self.max_h = self.max_h + row.h end if self.scrollbar then self.scrollbar.max = self.max_h - self.h self.scrollbar.pos = 0 end self:setupInput() self:onSelect() end function _M:setupInput() self.prev_sel = 0 self.mouse_pos = { x = 0, y = 0 } self.mouse:reset() self.key:reset() local colx = 0 for i=1, #self.columns do local col = self.columns[i] local on_left = function(button, x, y, xrel, yrel, bx, by, event) if button == "left" and event == "button" then self:selectColumn(i) end end self.mouse:registerZone(colx, 0, col.width, self.row_height, on_left, nil, ("column header%d"):format(i)) colx = colx + col.width end local on_mouse = function(button, x, y, xrel, yrel, bx, by, event) self.last_input_was_keyboard = false if button == "wheelup" and event == "button" then self.last_input_was_keyboard = false if self.scrollbar then self.scroll_inertia = math.min(self.scroll_inertia, 0) - 5 end elseif button == "wheeldown" and event == "button" then self.last_input_was_keyboard = false if self.scrollbar then self.scroll_inertia = math.max(self.scroll_inertia, 0) + 5 end end if button == "middle" and self.scrollbar then if not self.scroll_drag then self.scroll_drag = true self.scroll_drag_x_start = x self.scroll_drag_y_start = y else self.scrollbar.pos = util.minBound(self.scrollbar.pos + y - self.scroll_drag_y_start, 0, self.scrollbar.max) self.scroll_drag_x_start = x self.scroll_drag_y_start = y end else self.scroll_drag = false end if (self.all_clicks or button == "left") and event == "button" then if self.click_select then if self.prevclick == self.sel then self:onUse(button, event) end self:onSelect() self.prevclick = self.sel else self:onUse(button, event) end end if event == "motion" and button == "left" and self.on_drag then self.on_drag(self.list[self.sel], self.sel) end if button == "drag-end" and self.on_drag_end then self.on_drag_end(self.list[self.sel], self.sel) end self.mouse_pos = { x = bx, y = by } end self.mouse:registerZone(0, self.row_height, self.w, self.h, on_mouse, nil, "list area") self.key:addBinds{ ACCEPT = function() self.last_input_was_keyboard = true self:onUse("left", "key") end, MOVE_UP = function() local prev = self.sel self.last_input_was_keyboard = true self.sel = util.minBound(self.sel - 1, 1, #self.list) self.prev_sel = self.sel ~= prev and prev or self.prev_sel end, MOVE_DOWN = function() local prev = self.sel self.last_input_was_keyboard = true self.sel = util.minBound(self.sel + 1, 1, #self.list) self.prev_sel = self.sel ~= prev and prev or self.prev_sel end, } self.key:addCommands{ [{"_UP","ctrl"}] = function() self.last_input_was_keyboard = false if self.scrollbar then self.scroll_inertia = math.min(self.scroll_inertia, 0) - 5 end end, [{"_DOWN","ctrl"}] = function() self.last_input_was_keyboard = false if self.scrollbar then self.scroll_inertia = math.max(self.scroll_inertia, 0) + 5 end end, _HOME = function() self.last_input_was_keyboard = true self.sel = 1 self.scrollbar.pos = 0 self:onSelect() end, _END = function() self.last_input_was_keyboard = true self.sel = self.list and #self.list or 1 self.scrollbar.pos = self.scrollbar.max self:onSelect() end, _PAGEUP = function() self.last_input_was_keyboard = false if self.scrollbar then local scrollby = self.h - (self.only_display and 0 or (self.hide_columns and 0 or (self.floating_headers and self.max_h_columns or 0))) self.scrollbar.pos = util.minBound(self.scrollbar.pos - scrollby, 0, self.scrollbar.max) end end, _PAGEDOWN = function() self.last_input_was_keyboard = false if self.scrollbar then local scrollby = self.h - (self.only_display and 0 or (self.hide_columns and 0 or (self.floating_headers and self.max_h_columns or 0))) self.scrollbar.pos = util.minBound(self.scrollbar.pos + scrollby, 0, self.scrollbar.max) end end, } end function _M:generateRow(row, force) local max_h = 0 row.cells = {} local text for j=1, #self.columns do local col = self.columns[j] row.cells[j] = {} -- if color for each column is different if row.color and type(row.color[1]) == "table" then color = row.color[j] row.cells[j].color = color else row.color = row.color or {255,255,255} end if col.direct_draw then row.cells[j].w, row.cells[j].h = col.direct_draw(row, 0, 0, col.width, self.row_height, 0, 0, 0, 0, self.dest_area) or self.row_height, self.row_height else if type(col.display_prop) == "function" then text = tostring(col.display_prop(row)) else text = tostring(row[col.display_prop or col.sort]) end gen = self.font:draw(text, text:toTString():maxWidth(self.font), 255, 255, 255) row.cells[j]._tex, row.cells[j]._tex_w, row.cells[j]._tex_h, row.cells[j].w, row.cells[j].h = gen[1]._tex, gen[1]._tex_w, gen[1]._tex_h, gen[1].w, gen[1].h if row.cells[j].w > col.width - 2 * col.frame_sel.b4.w then row.cells[j].display_offset = { x = 0, x_dir = 0 } end end if row.cells[j].h > max_h then max_h = row.cells[j].h end end row.h = self.row_height or max_h end function _M:drawRow(row, row_i, nb_keyframes, x, y, total_w, total_h, loffset_x, loffset_y, dest_area) nb_keyframes = (nb_keyframes or 0) * 0.5 dest_area = dest_area or self.dest_area local column_w_offset = x local clip_y_start = 0 local clip_y_end = 0 local clip_x_start = 0 local clip_x_end = 0 local clip_maxy_start = 0 local clip_maxy_end = 0 local clip_maxx_start = 0 local clip_maxx_end = 0 local frame_clip_y = 0 local one_by_white = 1/255 local tmp_total_h = total_h for j = 1, #self.columns do total_h = tmp_total_h col = self.columns[j] clip_y_start = 0 clip_y_end = 0 -- if we only want to display content without being able to select etc. if not self.only_display then if self.sel == row_i then if self.focused then self:drawFrame(col.frame_sel, column_w_offset, y, nil, nil, nil, nil, nil, nil, 0, total_h, 0, loffset_y, dest_area) else self:drawFrame(col.frame_usel, column_w_offset, y, nil, nil, nil, nil, nil, nil, 0, total_h, 0, loffset_y, dest_area) end else if row.focus_decay then if self.focused then self:drawFrame(col.frame_sel, column_w_offset, y, 1, 1, 1, row.focus_decay * self.one_by_focus_decay, nil, nil, 0, total_h, 0, loffset_y, dest_area) else self:drawFrame(col.frame_usel, column_w_offset, y, 1, 1, 1, row.focus_decay * self.one_by_focus_decay, nil, nil, 0, total_h, 0, loffset_y, dest_area) end else self:drawFrame(col.frame, column_w_offset, y, nil, nil, nil, nil, nil, nil, 0, total_h, 0, loffset_y, dest_area) end end if row.special_bg then local c = row.special_bg if type(c) == "function" then c = c(row) end if c then self:drawFrame(col.frame_special, column_w_offset, y, c.r, c.g, c.b, c.a or 1, nil, nil, 0, total_h, 0, loffset_y, dest_area) end end if total_h < loffset_y then frame_clip_y = loffset_y - total_h end end if clip_y_start > clip_maxy_start then clip_maxy_start = clip_y_start end if col.direct_draw then _, _, clip_x_start, clip_x_end, clip_y_start, clip_y_end = col.direct_draw(row, column_w_offset, y, col.width, self.row_height, total_w, total_h, loffset_x, loffset_y, dest_area) or 0, 0, 0, 0, 0, 0 frame_clip_y = 0 elseif row.cells[j]._tex then local center_h = ( (self.row_height and self.row_height or row.cells[j].h) - row.cells[j].h) * 0.5 -- if it started before visible area then compute its top clip, take centering into account if total_h + center_h < loffset_y then clip_y_start = loffset_y - total_h - center_h frame_clip_y = center_h end -- if it ended after visible area then compute its bottom clip if total_h + row.cells[j].h + center_h > loffset_y + dest_area.h then clip_y_end = total_h + row.cells[j].h + center_h - loffset_y - dest_area.h end -- clip clipping to avoid texture display errors if clip_y_start > row.cells[j].h then clip_y_start = row.cells[j].h end local one_by_tex_h = 1 / row.cells[j]._tex_h -- precalculate for using it to multiply instead of division local one_by_tex_w = 1 / row.cells[j]._tex_w if row.cells[j].display_offset and not self.only_display then if self.sel == row_i then -- if we are going right if row.cells[j].display_offset.x_dir == 0 then row.cells[j].display_offset.x = row.cells[j].display_offset.x + nb_keyframes -- if we are going left else row.cells[j].display_offset.x = row.cells[j].display_offset.x - nb_keyframes end -- if we would see too much to right then clip it and change dir if row.cells[j].display_offset.x >= row.cells[j].w - col.width + 2 * col.frame_sel.b4.w then row.cells[j].display_offset.x_dir = 1 row.cells[j].display_offset.x = row.cells[j].w - col.width + 2 * col.frame_sel.b4.w -- if we would see too much to left then clip it and change dir elseif row.cells[j].display_offset.x <= 0 then row.cells[j].display_offset.x_dir = 0 row.cells[j].display_offset.x = 0 end else row.cells[j].display_offset.x = 0 end _, _, frame_clip_y, _ = util.clipOffset(0, center_h, total_w, total_h, loffset_x, loffset_y, dest_area) total_h = tmp_total_h + center_h if self.text_shadow then util.clipTexture(row.cells[j], column_w_offset + 1 + col.frame_sel.b4.w, y + 1 + center_h - frame_clip_y, row.cells[j].w, row.cells[j].h, 0, total_h, row.cells[j].display_offset.x, loffset_y, { w = col.width - 2 * col.frame_sel.b4.w, h = dest_area.h}, 0, 0, 0, self.text_shadow) end util.clipTexture(row.cells[j], column_w_offset + col.frame_sel.b4.w, y + center_h - frame_clip_y, row.cells[j].w, row.cells[j].h, 0, total_h, row.cells[j].display_offset.x, loffset_y, { w = col.width - 2 * col.frame_sel.b4.w, h = dest_area.h }, row.color[1] * one_by_white, row.color[2] * one_by_white, row.color[3] * one_by_white, 1.0) else _, _, frame_clip_y, _ = util.clipOffset(0, center_h, total_w, total_h, loffset_x, loffset_y, dest_area) total_h = tmp_total_h + center_h if self.text_shadow then util.clipTexture(row.cells[j], column_w_offset + 1 + col.frame_sel.b4.w, y + 1 + center_h - frame_clip_y, row.cells[j].w, row.cells[j].h, 0, total_h, 0, loffset_y, dest_area, 0, 0, 0, self.text_shadow) end util.clipTexture(row.cells[j], column_w_offset + col.frame_sel.b4.w, y + center_h - frame_clip_y, row.cells[j].w, row.cells[j].h, 0, total_h, 0, loffset_y, dest_area, row.color[1] * one_by_white, row.color[2] * one_by_white, row.color[3] * one_by_white, 1.0) end end clip_y_start = clip_y_start + frame_clip_y column_w_offset = column_w_offset + col.width if clip_x_start > clip_maxx_start then clip_maxx_start = clip_x_start end if clip_x_end > clip_maxx_end then clip_maxx_end = clip_x_end end if clip_y_start > clip_maxy_start then clip_maxy_start = clip_y_start end if clip_y_end > clip_maxy_end then clip_maxy_end = clip_y_end end end return 0, 0, clip_maxy_start, clip_maxy_end end function _M:setColumns(columns, force) local w = self.w local col_size = #columns local max_h = 0 if self.scrollbar then w = w - self.scrollbar.w end for i=1, col_size do local col = columns[i] if type(col.width) == "table" then if col.width[2] == "fixed" then w = w - col.width[1] end end end local colx = 0 for i=1, col_size do local col = columns[i] if type(col.width) == "table" then if col.width[2] == "fixed" then col.width = col.width[1] end else col.width = w * col.width * 0.01 end col.frame = self:makeFrame(nil, col.width, self.row_height) col.frame_special = self:makeFrame("ui/selector", col.width, self.row_height) col.frame_sel = self:makeFrame("ui/selector-sel", col.width, self.row_height) col.frame_usel = self:makeFrame("ui/selector", col.width, self.row_height) col.frame_col = self:makeFrame("ui/heading", col.width, self.row_height) col.frame_col_sel = self:makeFrame("ui/heading-sel", col.width, self.row_height) self.font:setStyle("bold") local gen = self.font:draw(col.name:toString(), col.width, 255, 255, 255) self.font:setStyle("normal") col._tex, col._tex_w, col._tex_h, col.w, col.h = gen[1]._tex, gen[1]._tex_w, gen[1]._tex_h, gen[1].w, gen[1].h colx = colx + col.width if col.h > max_h then max_h = col.h end end self.columns = columns self.max_h_columns = self.hide_columns and 0 or (self.row_height or max_h) self.max_h = self.max_h_columns self.sel = 1 self:selectColumn(1, true) end function _M:setList(list, force) if list and #list > 0 and (self.list ~= list or force) then self.list = list self.sel = util.minBound(self.sel, 1, #self.list) local oldcol = self.cur_col self:selectColumn(oldcol or 1, (not oldcol) and true or false, self.sort_reverse) self.max_h = self.max_h_columns for i=1, #self.list do local row = self.list[i] if self.focus_decay_max then row.focus_decay = 0 end self:generateRow(row) self.max_h = self.max_h + row.h end else self.list = {} self.sel = 1 self.max_h = self.max_h_columns end if self.scrollbar then self.scrollbar.pos = 0 self.scrollbar.max = self.max_h - self.h end self.prevrow = 0 self.prev_sel = 0 end function _M:changeAll(columns, list) self:setColumns(columns) self:setList(list) self:setupInput() end function _M:onSelect(force) if self.only_display then return end local row = self.list[self.sel] -- if not found fall back if not row then return end -- self.scroll_inertia = 0 if self.on_select then self.on_select(row, self.sel) end end function _M:removeRow(row_i) table.remove(self.list, row_i) end function _M:appendList(row) self.list[#self.list + 1] = row if (not self.sortable or self.only_display) and not force then return end local col = self.columns[self.cur_col] if self.sortable and not force then local fct = col.sort if type(fct) == "string" then fct = function(a, b) return a[col.sort] < b[col.sort] end end if self.sort_reverse and fct then local old=fct fct = function(a, b) return old(b, a) end end pcall(table.sort, self.list, fct) end end function _M:onUse(...) if #self.list == 0 or self.only_display then return end local row = self.list[self.sel] if not row then return end self:sound("button") if row.fct then row:fct(row, self.sel, ...) else self.fct(row, self.sel, ...) end end function _M:selectColumn(i, force, reverse) if (not self.sortable or self.only_display) and not force then return end local col = self.columns[i] if not col then return end if self.cur_col ~= i then self.cur_col = i self.sort_reverse = false else self.sort_reverse = not self.sort_reverse end self.sort_reverse = reverse if self.sortable and not force then local fct = col.sort if type(fct) == "string" then fct = function(a, b) return a[col.sort] < b[col.sort] end end if self.sort_reverse and fct then local old=fct fct = function(a, b) return old(b, a) end end pcall(table.sort, self.list, fct) end end function _M:setSelectDelay(delay) self.delay = delay self.delay_start = os.clock() end function _M:display(x, y, nb_keyframes, screen_x, screen_y, offset_x, offset_y, local_x, local_y) self.last_display_x = screen_x self.last_display_y = screen_y nb_keyframes = nb_keyframes or 0 offset_x = offset_x and offset_x or 0 local row = 0 if self.scrollbar then self.scrollbar.pos = util.minBound(self.scrollbar.pos + self.scroll_inertia, 0, self.scrollbar.max) if self.scroll_inertia > 0 then self.scroll_inertia = math.max(self.scroll_inertia - 1, 0) elseif self.scroll_inertia < 0 then self.scroll_inertia = math.min(self.scroll_inertia + 1, 0) end if self.scrollbar.pos == 0 or self.scrollbar.pos == self.scrollbar.max then self.scroll_inertia = 0 end end -- if we used keyboard then match display to input if self.scrollbar and self.last_input_was_keyboard then local columns_h = self.hide_columns and 0 or self.max_h_columns local mul = self.floating_headers and 2 or 1 -- if we have floating headers we have to take them into account while scrolling local pos = self.hide_columns and 0 or self.max_h_columns for i = 1, #self.list do row = self.list[i] pos = pos + row.h -- we've reached selected row if self.sel == i then -- check if it was visible if not go scroll over there if pos - mul * columns_h < self.scrollbar.pos then self.scrollbar.pos = util.minBound(pos - mul * columns_h, 0, self.scrollbar.max) elseif pos + columns_h > self.scrollbar.pos + self.h then self.scrollbar.pos = util.minBound(pos - self.h, 0, self.scrollbar.max) end break end end end offset_y = offset_y and offset_y or (self.scrollbar and self.scrollbar.pos or 0) local_x = local_x and local_x or 0 local_y = local_y and local_y or 0 local loffset_y = offset_y - local_y local current_y = 0 local current_x = 0 local total_h = 0 local clip_x_start = 0 local clip_x_end = 0 local clip_y_start = 0 local clip_y_end = 0 local frame_clip_y = 0 local dest_area = table.clone(self.dest_area) local frame_clip_y_start, frame_clip_y_end local max_h = 0 if not self.hide_columns then for j = 1, #self.columns do clip_y_end = 0 local col = self.columns[j] local center_h = ( (self.row_height and self.row_height or col.h) - col.h) * 0.5 if self.floating_headers then if self.cur_col == j then self:drawFrame(col.frame_col, x + current_x, y + current_y) else self:drawFrame(col.frame_col_sel, x + current_x, y + current_y) end local one_by_tex_h = 1 / col._tex_h col._tex:toScreenPrecise(x + current_x + col.frame_sel.b4.w, y + current_y + center_h, col.w, col.h - (clip_y_start + clip_y_end), 0, col.w / col._tex_w, clip_y_start * one_by_tex_h, (col.h - clip_y_end) * one_by_tex_h ) elseif total_h + self.max_h_columns > loffset_y and total_h < loffset_y + dest_area.h then if self.cur_col == j then _, _, frame_clip_y_start, frame_clip_y_end = self:drawFrame(col.frame_col, x + current_x, y + current_y, nil, nil, nil, nil, nil, nil, 0, total_h, 0, loffset_y, dest_area) else _, _, frame_clip_y_start, frame_clip_y_end = self:drawFrame(col.frame_col_sel, x + current_x, y + current_y, nil, nil, nil, nil, nil, nil, 0, total_h, 0, loffset_y, dest_area) end self.mouse:updateZone(("column header%d"):format(j), current_x, current_y, col.width, self.row_height - frame_clip_y_start - frame_clip_y_end) if self.only_display then frame_clip_y = center_h else frame_clip_y = loffset_y - total_h end -- if its visible then compute how much of it needs to be clipped, take centering into account if total_h + center_h < loffset_y then clip_y_start = loffset_y - total_h - center_h frame_clip_y = center_h end -- if it ended after visible area then compute its bottom clip if total_h + col.h + center_h > loffset_y + dest_area.h then clip_y_end = total_h + col.h + center_h - loffset_y - dest_area.h end local one_by_tex_h = 1 / col._tex_h if total_h + col.h > loffset_y and total_h < loffset_y + dest_area.h then col._tex:toScreenPrecise(x + current_x + col.frame_sel.b4.w, y + current_y + center_h - frame_clip_y, col.w, col.h - (clip_y_start + clip_y_end), 0, col.w / col._tex_w, clip_y_start * one_by_tex_h, (col.h - clip_y_end) * one_by_tex_h ) end end if col.h > max_h then max_h = col.h end current_x = current_x + col.width end max_h = self.row_height or max_h if self.floating_headers then dest_area.h = dest_area.h - max_h current_y = current_y + max_h loffset_y = loffset_y + max_h elseif total_h + max_h > loffset_y and total_h < loffset_y + dest_area.h then current_y = current_y + max_h if not self.only_display then current_y = current_y + total_h - loffset_y end end total_h = total_h + max_h end local list_start_y = current_y self.mouse:updateZone("list area", 0, current_y, self.w, self.h - current_y) -- if list is empty then display only column headers and fall back if #self.list == 0 then return end -- refresh focus decay if any if self.focus_decay_max then self.list[self.sel].focus_decay = self.focus_decay_max end -- if we are too deep then end this if total_h > loffset_y + dest_area.h then return end for i = 1, #self.list do row = self.list[i] -- if its visible then draw it if total_h + row.h > loffset_y and total_h < loffset_y + dest_area.h then _, _, clip_y_start, clip_y_end = self:drawRow(row, i, nb_keyframes, x, y + current_y, 0, total_h, 0, loffset_y, dest_area) row.last_display_x = screen_x row.last_display_y = screen_y + current_y -- use display loop to determine which row is selected if not self.last_input_was_keyboard and self.mouse_pos.y + list_start_y> current_y and self.mouse_pos.y + list_start_y< current_y + row.h - clip_y_start then self.sel = i end current_y = current_y + row.h - clip_y_start end -- decay focus if any if row.focus_decay then row.focus_decay = row.focus_decay - nb_keyframes if row.focus_decay <= 0 then row.focus_decay = nil end end -- add full size of row total_h = total_h + row.h -- if we are too deep then end this if total_h > loffset_y + dest_area.h then break end end -- show scrollbar only if there is one, total size of UI element is greater than visible one and only_display switch is not set if self.focused and self.scrollbar and self.max_h > self.h and not self.only_display then if self.hide_columns then self.scrollbar:display(x + self.w - self.scrollbar.w, y) else self.scrollbar:display(x + self.w - self.scrollbar.w, y + max_h) end end -- if there is delay set and its still focused if self.delay and self.focused == true then -- previously displayed selection is still the same if self.prevrow == self.sel then if os.clock() > self.delay + self.delay_start then if self.prev_sel ~= self.sel then self.prev_sel = self.sel if not self.click_select then self:onSelect() end end self.delay_start = os.clock() end else -- selection was changed self.delay_start = os.clock() end self.prevrow = self.sel -- if the rows changed elseif not self.delay and self.prev_sel ~= self.sel then self.prev_sel = self.sel if not self.click_select then self:onSelect() end end end
gpl-3.0
pakoito/ToME---t-engine4
game/engines/default/modules/boot/ai/player.lua
3
1873
-- ToME - Tales of Middle-Earth -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Astar = require "engine.Astar" -- AI for the escort quest -- the NPC will run toward the portal, if hostiles are in sight he attacks them newAI("player_demo", function(self) if self:runAI("target_simple") then -- One in "talent_in" chance of using a talent if rng.chance(self.ai_state.talent_in or 6) and self:reactionToward(self.ai_target.actor) < 0 then self:runAI("dumb_talented") end if not self.energy.used then self:runAI("move_simple") end return true else self:runAI("move_player") end end) newAI("move_player", function(self) if self.player_waypoint then local path = self.player_waypoint if not path[1] then self.player_waypoint = nil return self:runAI("move_simple") else local ret = self:move(path[1].x, path[1].y) table.remove(path, 1) return ret end else local e = rng.table(game.level.e_array) while e == self do e = rng.table(game.level.e_array) end print("Selecting waypoint", e.x, e.y, "::", e.name) local a = Astar.new(game.level.map, self) self.player_waypoint = a:calc(self.x, self.y, e.x, e.y) end end)
gpl-3.0
madpilot78/ntopng
scripts/lua/modules/file_utils.lua
1
2763
-- -- (C) 2019-21 - ntop.org -- local file_utils = {} local os_utils = require("os_utils") -- ############################################## function file_utils.copy_file(fname, src_path, dst_path) local src local dst if(fname == nil) then src = os_utils.fixPath(src_path) dst = os_utils.fixPath(dst_path) else src = os_utils.fixPath(src_path .. "/" .. fname) dst = os_utils.fixPath(dst_path .. "/" .. fname) end local infile, err = io.open(src, "rb") -- NOTE: Do not forget the 'b' flag [https://www.lua.org/pil/21.2.2.html] -- as this is compulsory on windows traceError(TRACE_INFO, TRACE_CONSOLE, string.format("Copying file %s -> %s", src, dst)) if(do_trace) then io.write(string.format("\tLoad [%s]\n", fname)) end if(ntop.exists(dst)) then -- NOTE: overwriting is not allowed as it means that a file was already provided by -- another plugin -- io.write(debug.traceback()) traceError(TRACE_ERROR, TRACE_CONSOLE, string.format("Trying to overwrite existing file %s", dst)) return(false) end if(infile == nil) then traceError(TRACE_ERROR, TRACE_CONSOLE, string.format("Could not open file %s for read: %s", src, err or "")) return(false) end local instr = infile:read("*all") infile:close() local outfile, err = io.open(dst, "wb") if(outfile == nil) then traceError(TRACE_ERROR, TRACE_CONSOLE, string.format("Could not open file %s for write", dst, err or "")) return(false) end if (instr == nil) then traceError(TRACE_ERROR, TRACE_CONSOLE, string.format("Could not write the string into file %s", dst)) return (false) end outfile:write(instr) outfile:close() ntop.setDefaultFilePermissions(dst) return(true) end -- ######################################################### function file_utils.recursive_copy(src_path, dst_path, path_map, required_extension) for fname in pairs(ntop.readdir(src_path)) do local do_copy = true if((required_extension ~= nil) and not(ends(fname, ".lua"))) then -- Don't copy do_copy = false traceError(TRACE_INFO, TRACE_CONSOLE, "SKIP file_utils.recursive_copy("..fname.." ["..src_path.." -> "..dst_path.."])\n") end if(do_copy) then traceError(TRACE_INFO, TRACE_CONSOLE, "COPY file_utils.recursive_copy("..fname.." ["..src_path.." -> "..dst_path.."])\n") if not file_utils.copy_file(fname, src_path, dst_path) then return(false) end if path_map then path_map[os_utils.fixPath(dst_path .. "/" .. fname)] = os_utils.fixPath(src_path .. "/" .. fname) end end end return(true) end -- ######################################################### return(file_utils)
gpl-3.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/mcml/pe_mc_player.lua
1
6607
--[[ Title: player avatar display Author(s): LiXizhi Company: ParaEngine Date: 2013.10.14 Desc: use the lib: ------------------------------------------------------------ NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/pe_mc_player.lua"); ------------------------------------------------------------ ]] NPL.load("(gl)script/apps/Aries/Creator/Game/Entity/EntityManager.lua"); local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager"); NPL.load("(gl)script/apps/Aries/Creator/Game/Entity/PlayerAssetFile.lua"); local PlayerAssetFile = commonlib.gettable("MyCompany.Aries.Game.EntityManager.PlayerAssetFile") NPL.load("(gl)script/apps/Aries/Creator/Game/Entity/CustomCharItems.lua"); local CustomCharItems = commonlib.gettable("MyCompany.Aries.Game.EntityManager.CustomCharItems") -- create class local pe_mc_player = commonlib.gettable("MyCompany.Aries.Game.mcml.pe_mc_player"); function pe_mc_player.render_callback(mcmlNode, rootName, bindingContext, _parent, left, top, right, bottom, myLayout, css) -- get user nid local nid = mcmlNode:GetAttributeWithCode("nid",nil,true); nid = tonumber(nid) or 0; local IsActiveRendering = mcmlNode:GetBool("IsActiveRendering") if(IsActiveRendering == nil) then IsActiveRendering = true end local IsInteractive = mcmlNode:GetBool("IsInteractive") if(IsInteractive == nil) then IsInteractive = true; end local autoRotateSpeed = mcmlNode:GetNumber("autoRotateSpeed") if(autoRotateSpeed == nil) then autoRotateSpeed = 0; end local callback = function(ctl) pe_mc_player.OnFrameMove(ctl, mcmlNode); end; if (mcmlNode:GetBool("NoFrameMove")) then callback = nil; end local name = mcmlNode:GetAttributeWithCode("name") or mcmlNode:GetInstanceName(rootName); local miniSceneName = mcmlNode:GetAttributeWithCode("miniscenegraphname") or "pe:player"..ParaGlobal.GenerateUniqueID(); local renderSize = mcmlNode:GetNumber("RenderTargetSize") or 256 local instName = name NPL.load("(gl)script/ide/Canvas3D.lua"); local ctl = CommonCtrl.Canvas3D:new{ name = instName.."_mcplayer", alignment = "_lt", left = left, top = top, width = right - left, height = bottom - top, background = mcmlNode:GetString("background") or css.background, parent = _parent, IsActiveRendering = IsActiveRendering, miniscenegraphname = miniSceneName, DefaultRotY = mcmlNode:GetNumber("DefaultRotY") or 0, RenderTargetSize = renderSize, IsInteractive = IsInteractive, autoRotateSpeed = autoRotateSpeed, DefaultCameraObjectDist = mcmlNode:GetNumber("DefaultCameraObjectDist") or 7, DefaultLiftupAngle = mcmlNode:GetNumber("DefaultLiftupAngle") or 0.25, LookAtHeight = mcmlNode:GetNumber("LookAtHeight") or 1.5, FrameMoveCallback = callback, }; mcmlNode.Canvas3D_ctl = ctl; mcmlNode.control = ctl; ctl:Show(true); local entityPlayer = EntityManager.GetPlayer(); local playerObj = entityPlayer and entityPlayer:GetInnerObject() or ParaScene.GetPlayer(); local obj_params = ObjEditor.GetObjectParams(playerObj); NPL.load("(gl)script/apps/Aries/Creator/Game/PlayerController.lua"); if(not obj_params.AssetFile or obj_params.AssetFile == "") then obj_params = { IsCharacter = true, AssetFile = MyCompany.Aries.Game.PlayerController:GetMainAssetPath(), x = 0, y=0, z=0, facing=0, Attribute = 128, }; end obj_params.name = "mc_player"; pe_mc_player.AutoSetObjectSkin(obj_params) if(obj_params.ReplaceableTextures[2]) then local player = entityPlayer; if(player and player.GetSkin) then obj_params.ReplaceableTextures[2] = player:GetSkin() or obj_params.ReplaceableTextures[2]; end end obj_params.facing = 1.57; -- MESH_USE_LIGHT = 0x1<<7: use block ambient and diffuse lighting for this model. obj_params.Attribute = 128; obj_params.CustomGeosets = CustomCharItems:RemovePetIdFromSkinIds(obj_params.CustomGeosets or PlayerAssetFile.Store.skin) if(string.find(obj_params.AssetFile, "character/CC/ObjectComponents/Ride/")) then obj_params.AssetFile = "character/CC/02human/CustomGeoset/actor.x" end mcmlNode.obj_params = obj_params; ctl:ShowModel(obj_params); pe_mc_player.OnFrameMove(ctl, mcmlNode); end function pe_mc_player.AutoSetObjectSkin(obj_params) NPL.load("(gl)script/apps/Aries/Creator/Game/Entity/PlayerSkins.lua"); local PlayerSkins = commonlib.gettable("MyCompany.Aries.Game.EntityManager.PlayerSkins") obj_params.ReplaceableTextures = obj_params.ReplaceableTextures or {}; if(not PlayerSkins:CheckModelHasSkin(obj_params.AssetFile)) then obj_params.ReplaceableTextures[2] = nil; PlayerAssetFile:Init(); if(PlayerAssetFile:HasCustomGeosets(obj_params.AssetFile)) then obj_params.CustomGeosets = MyCompany.Aries.Game.PlayerController:GetSkinTexture(); end else obj_params.ReplaceableTextures[2] = MyCompany.Aries.Game.PlayerController:GetSkinTexture(); end end function pe_mc_player.SetAssetFile(mcmlNode, pageInst, filename) if(mcmlNode.Canvas3D_ctl and filename and filename~="") then PlayerAssetFile:Init(); mcmlNode.obj_params.AssetFile = PlayerAssetFile:GetValidAssetByString(filename) pe_mc_player.AutoSetObjectSkin(mcmlNode.obj_params); mcmlNode.Canvas3D_ctl:ShowModel(mcmlNode.obj_params); end end function pe_mc_player.SetCustomGeosets(mcmlNode, pageInst, customGeosets) if(mcmlNode.Canvas3D_ctl and customGeosets and customGeosets~="") then mcmlNode.obj_params.CustomGeosets = customGeosets; mcmlNode.Canvas3D_ctl:ShowModel(mcmlNode.obj_params); end end -- on frame move: facing the mouse cursor function pe_mc_player.OnFrameMove(ctl, mcmlNode) local mouse_x, mouse_y = ParaUI.GetMousePosition(); local _parent = ctl:GetContainer(); if(_parent and _parent:IsValid()) then local x, y, width, height = _parent:GetAbsPosition(); local dx = mouse_x - (x + width/2); local dy = mouse_y - (y + height/2); local player = ctl:GetObject(); if(player) then local HeadUpdownAngle = 0; local HeadTurningAngle = 0; local facing = 1.57; -- max pixel local len = dx^2 + dy^2; if(len > 0) then len = math.sqrt(len); HeadUpdownAngle = -dy/len*0.7; HeadTurningAngle = -dx/len; end player:SetFacing(facing); player:SetField("HeadUpdownAngle", HeadUpdownAngle); player:SetField("HeadTurningAngle", HeadTurningAngle); end end end -- this is just a temparory tag for offline mode function pe_mc_player.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) return mcmlNode:DrawDisplayBlock(rootName, bindingContext, _parent, left, top, width, height, parentLayout, style, pe_mc_player.render_callback); end
gpl-2.0
HellBoooy021/HellBot
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
pakoito/ToME---t-engine4
game/modules/tome/data/zones/vor-pride/objects.lua
3
3553
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org load("/data/general/objects/objects-far-east.lua") load("/data/general/objects/lore/sunwall.lua") load("/data/general/objects/lore/orc-prides.lua") local Stats = require"engine.interface.ActorStats" -- Artifact, randomly dropped in Vor Pride, and only there newEntity{ base = "BASE_SCROLL", subtype="tome", power_source = {arcane=true}, name = "Tome of Wildfire", unided_name = "burning book", unique=true, no_unique_lore=true, image = "object/artifact/tome_of_wildfire.png", desc = "This huge book is covered in searing flames. Yet they do not harm you.", color = colors.VIOLET, level_range = {35, 45}, rarity = 200, cost = 100, use_simple = { name="learn the ancient secrets", use = function(self, who) if not who:knowTalent(who.T_FLAME) then who:learnTalent(who.T_FLAME, true, 3, {no_unlearn=true}) game.logPlayer(who, "#00FFFF#You read the tome and learn about ancient forgotten fire magic!") else who.talents_types_mastery["spell/fire"] = (who.talents_types_mastery["spell/fire"] or 1) + 0.1 who.talents_types_mastery["spell/wildfire"] = (who.talents_types_mastery["spell/wildfire"] or 1) + 0.1 game.logPlayer(who, "#00FFFF#You read the tome and perfect your mastery of fire magic!") end return {used=true, id=true, destroy=true} end} } -- Artifact, randomly dropped in Vor Pride, and only there newEntity{ base = "BASE_SCROLL", subtype="tome", power_source = {arcane=true}, name = "Tome of Uttercold", unided_name = "frozen book", unique=true, no_unique_lore=true, image = "object/artifact/tome_of_uttercold.png", desc = "This huge book is covered in slowly shifting patterns of ice. Yet they do not harm you.", color = colors.VIOLET, level_range = {35, 45}, rarity = 200, cost = 100, use_simple = { name="learn the ancient secrets", use = function(self, who) if not who:knowTalent(who.T_ICE_STORM) then who:learnTalent(who.T_ICE_STORM, true, 3, {no_unlearn=true}) game.logPlayer(who, "#00FFFF#You read the tome and learn about ancient forgotten ice magic!") else who.talents_types_mastery["spell/water"] = (who.talents_types_mastery["spell/water"] or 1) + 0.1 who.talents_types_mastery["spell/ice"] = (who.talents_types_mastery["spell/ice"] or 1) + 0.1 game.logPlayer(who, "#00FFFF#You read the tome and perfect your mastery of ice magic!") end return {used=true, id=true, destroy=true} end} } newEntity{ base = "BASE_LORE", define_as = "NOTE_LORE", name = "draft note", lore="vor-pride-note", desc = [[A note.]], rarity = false, } for i = 1, 5 do newEntity{ base = "BASE_LORE", define_as = "ORC_HISTORY"..i, name = "Records of Lorekeeper Hadak", lore="orc-history-"..i, unique="Records of Lorekeeper Hadak "..i, desc = [[Part of the long history of the Orc race.]], rarity = false, } end
gpl-3.0
Ferk/Dungeontest
mods/dungeon_artefacts/dmaking/tome.lua
1
9468
statuses.register_status("dmaking:maker",{ description = "DungeonMaking", hidden = true, survive_player_death = true, groups = {dmaking=1} }) local pool_selection_array = {"0","1","2","3","4","down","up"} -- Teleport the given player to the X entrance of the room, which is always -- open in unrotated schematics. This way he won't get inside a wall on load function dmaking.teleport_player_safe(player) local room = dungeon_rooms.room_at(player:get_pos()) local pos = { x = room.maxp.x - 1, y = room.maxp.y - dungeon_rooms.room_area.y/2, z = room.maxp.z - dungeon_rooms.room_area.z/2, } player:setpos(pos) end function dmaking.show_formspec(player, context) local name = player:get_player_name() or "singleplayer" local pos = player:get_pos() local room = dungeon_rooms.room_at(pos) local details = dungeon_rooms.get_room_details(room) context.room = context.room or room if pos.y > dungeon_rooms.origin.y then minetest.chat_send_player(name, "You open the tome but it's empty! it seems to have no power outside the Dungeon") return false end local formspec = "size[10,7]" .."background[-1,-1;12,9;dmaking_tome_bg.png]" .."label[0.5,0;Tome of DungeonMaking]" .."label[0,1;Level " .. room.level .." of the Dungeon.]" .."label[0,1.5;" .. details.leveldata.name .."]" .."button[0,1.5;4,3.5;show_map;Show Level map]" .."label[0,2;Current Room: (" .. room.x ..","..room.z .. ")]" .."button[0,3;4,3.5;reset;RESET room to default state]" .."label[0,5;Default state layout: " .. details.layout .. " (rotation:" .. details.rotation .. ")]" .."label[0,5.5;Title: " .. details.data.name .."]" .."label[0,6;Door direction: " .. details.door .."]" if context.roomdata and context.room.x == room.x and context.room.z == room.z and context.room.level == room.level then local roomdata = context.roomdata formspec = formspec .."field[5.75,0.5;4,1;roomdata_name;Room Name;" .. minetest.formspec_escape(roomdata.name) .."]" .."field[5.75,1.6;1,1;roomdata_rarity;Rarity;" .. roomdata.rarity .."]" .."field[6.75,1.6;1.5,1;roomdata_minlevel;Min Level;" .. (roomdata.minlevel or "") .."]" .."field[8.25,1.6;1.5,1;roomdata_maxlevel;Max Level;" .. (roomdata.maxlevel or "") .."]" .."field[5.75,3;4,1;roomdata_groups;Groups (comma separated);" .. table.concat(roomdata.groups,",") .."]" .."button[5.75,3.5;4,3.5;save;Save this room]" .."button[5.75,4.5;4,3.5;select;Load another room]" -- If there's at least a pool index, show the selection elseif context.pooli then local poolid = pool_selection_array[context.pooli] or error("Invalid pool index " .. context.pooli) local pool = dungeon_rooms.rooms[poolid] or error("No rooms loaded for pool " .. poolid) local roomlist = "" for i=1, #pool do local room = minetest.formspec_escape(pool[i].name) roomlist = roomlist=="" and room or roomlist..","..room end formspec = formspec .."label[5.75,0;Room Layout:]" .."dropdown[7.75,-0.1;2,1;select;".. table.concat(pool_selection_array,",") ..";" .. context.pooli .. "]" .."label[5.75,0.75;Double click the room to load it]" .."textlist[5.75,1.5;3,4;selected_roomdata;"..roomlist..";1;true]" else formspec = formspec .."label[5.75,0;No Room Data selected.]" .."label[5.75,1.0;If you had a room selected before]" .."label[5.75,1.5;the room might have been reset]" .."label[5.75,2.0;or you walked into a different room]" .."button[5.75,2.75;4,3.5;select;SELECT room data to load]" .."button[5.75,3.5;4,4.75;new;Create NEW room data]" end minetest.show_formspec(name, "dmaking:tome", formspec) end -- Turn a comma-separated string into a table of groups -- or an empty table in any other case local function togroups(str) return string.split(str,",") or {} end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "dmaking:tome" then local name = player:get_player_name() local context = statuses.get_player_status(name)["dmaking:maker"] if fields.reset then minetest.show_formspec(name, "dmaking:tome", "size[4,2.5]" .."label[0,0;Are you sure you want to reset it?]" .."label[0,0.5;Current room changes will be lost]" .."button_exit[0,1.5;2,1;reset_for_sure;Reset!]" .."button_exit[2,1.5;2,1;cancel;Cancel]", context) elseif fields.reset_for_sure then local pos = player:get_pos() dungeon_rooms.clear_room_meta(pos) local room = dungeon_rooms.room_at(pos) local center = { x = room.maxp.x - math.floor(dungeon_rooms.room_area.x/2), y = room.maxp.y - math.floor(dungeon_rooms.room_area.y/2), z = room.maxp.z - math.floor(dungeon_rooms.room_area.z/2), } local details = dungeon_rooms.spawn_room(center) -- reset the context as well context.pooli = nil context.roomdata = nil --dmaking.teleport_player_safe(player) minetest.chat_send_player(name, "room regenerated: " .. details.data.name) -- Room data selection elseif fields.select then -- Room data was clicked! if fields.selected_roomdata then local event = minetest.explode_textlist_event(fields.selected_roomdata) if event.type == "DCL" then local pool = dungeon_rooms.rooms[fields.select] context.roomdata = pool and pool[event.index] if context.roomdata then context.room = nil dmaking.show_formspec(player, context) local pos = player:get_pos() dungeon_rooms.clear_room_meta(pos) if dungeon_rooms.place_roomdata(pos, context.roomdata) then minetest.chat_send_player(name, "room loaded: " .. context.roomdata.name) dmaking.teleport_player_safe(player) else minetest.chat_send_player(name, "room couldn't be loaded") end end end else -- Refresh formspec with appropiate value for the selection context.roomdata = nil context.pooli = context.pooli or 1 for i=1, #pool_selection_array do if fields.select == pool_selection_array[i] then context.pooli = i break end end dmaking.show_formspec(player, context) end elseif fields.save then local filesplit = string.split(context.roomdata.path, "/",true,-1,true) context.filename = filesplit[#filesplit] context.save = { name = fields.roomdata_name, rarity = tonumber(fields.roomdata_rarity), minlevel = tonumber(fields.roomdata_minlevel), maxlevel = tonumber(fields.roomdata_maxlevel), groups = fields.roomdata_groups, } if context.save.rarity == 0 then context.save.rarity = nil end minetest.show_formspec(name, "dmaking:tome", "size[5,3]" .."label[0,0;A different filename will create a new room]" .."field[0.5,1.5;4,1;filename;Room filename;" .. context.filename .."]" .."button_exit[0.5,2.5;2,1;save_for_sure;Save!]" .."button_exit[2.5,2.5;2,1;cancel;Cancel]", context) elseif fields.save_for_sure then -- Sanitize filenames local filename = string.gsub(string.gsub(fields.filename, "/", "_"), "%.", "_") local dir = pool_selection_array[context.pooli] context.roomdata.path = dungeon_rooms.roomdata_directory .. "/" .. dir .. "/" .. filename context.roomdata.name = context.save.name context.roomdata.rarity = context.save.rarity context.roomdata.minlevel = context.save.minlevel context.roomdata.maxlevel = context.save.maxlevel context.roomdata.groups = togroups(context.save.groups) local roomconf = Settings(context.roomdata.path .. ".conf") roomconf:set("name", context.save.name) if context.save.rarity then roomconf:set("rarity", context.save.rarity) else roomconf:remove("rarity") end if context.save.minlevel then roomconf:set("minlevel", context.save.minlevel) else roomconf:remove("minlevel") end if context.save.maxlevel then roomconf:set("maxlevel", context.save.maxlevel) else roomconf:remove("maxlevel") end if context.save.groups then roomconf:set("groups", context.save.groups) else roomconf:remove("groups") end if roomconf:write() and dungeon_rooms.save_roomdata(player:get_pos(), context.roomdata) then minetest.chat_send_player(name, "room saved: " .. (context.save.name or filename)) else minetest.chat_send_player(name, "room couldn't be saved") end if filename ~= context.filename then -- if the filename is new (different file) add it to the pool! table.insert(dungeon_rooms.rooms[dir], context.roomdata) end context.filename = nil context.save = nil elseif fields.new then minetest.show_formspec(name, "dmaking:tome", "size[4,3]" .."label[0,0.0;To create a new room, first load a]" .."label[0,0.5;room for the desired layout and]" .."label[0,1.0;then save it under a different name]" .."button[0,2;4,1;select;SELECT room data to load]", context) elseif fields.show_map then dmaking.show_map(player) end return true end return false end) minetest.register_tool("dmaking:tome", { description = "Tome of DungeonMaking", inventory_image = "dmaking_tome.png", groups = {dmaking=1}, liquids_pointable = true, stack_max = 1, on_use = function(itemstack, player, pointed_thing) local name = player:get_player_name() local context = statuses.get_player_status(name)["dmaking:maker"] if not context then local i i, context = statuses.apply_player_status(player, {name="dmaking:maker"}) end if context then dmaking.show_formspec(player, context) end return itemstack end, })
gpl-3.0
RyMarq/Zero-K
effects/rome.lua
25
7463
-- rome return { ["rome"] = { air = true, count = 10, ground = true, water = true, debris1 = { air = true, class = [[CSimpleParticleSystem]], count = 20, ground = true, water = true, properties = { airdrag = 0.98, alwaysvisible = true, colormap = [[0.22 0.18 0.15 1 0.22 0.18 0.15 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 90, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 5, particlelife = [[50 i-0.5]], particlelifespread = 0, particlesize = [[10 r10]], particlesizespread = 0, particlespeed = 3, particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = [[-0.1 i0.015]], sizemod = 1.0, texture = [[debris2]], }, }, debris2 = { air = true, class = [[CSimpleParticleSystem]], count = 20, ground = true, water = true, properties = { airdrag = 0.98, alwaysvisible = true, colormap = [[0.22 0.18 0.15 1 0.22 0.18 0.15 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 20, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 5, particlelife = 150, particlelifespread = 0, particlesize = [[1 r10]], particlesizespread = 0, particlespeed = 5, particlespeedspread = 8, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[debris2]], }, }, dirt1 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[1 0.6 0 0.1 1 0.4 0 0.1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 30, particlelife = 18.5, particlelifespread = 5, particlesize = 1.5, particlesizespread = 3, particlespeed = 0, particlespeedspread = 19, pos = [[0, 2, 0]], sizegrowth = 3, sizemod = 1.0, texture = [[dirtplosion2]], }, }, dirt2 = { air = true, class = [[CSimpleParticleSystem]], count = 0, ground = true, water = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[1 0.6 0 0.1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 30, particlelife = 8.5, particlelifespread = 5, particlesize = 1.5, particlesizespread = 3, particlespeed = 0, particlespeedspread = 19, pos = [[0, 2, 0]], sizegrowth = 3, sizemod = 1.0, texture = [[dirtplosion2]], }, }, dirt3 = { air = true, class = [[CSimpleParticleSystem]], count = 10, ground = true, water = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[0 0 0 0.01 0.4 0.4 0.4 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 25, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 1, particlelife = 80, particlelifespread = 5, particlesize = 1.5, particlesizespread = 3, particlespeed = 5, particlespeedspread = 24, pos = [[0, 2, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[kfoam]], }, }, fanny = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 30, explosiongenerator = [[custom:FANNY]], pos = [[0, 0, 0]], }, }, glow = { air = true, class = [[CSimpleParticleSystem]], count = 10, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 0.8 0.9 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[-0, 1, 0]], gravity = [[0, 0.00, 0]], numparticles = 1, particlelife = 5, particlelifespread = 0, particlesize = 60, particlesizespread = 10, particlespeed = 1, particlespeedspread = 0, pos = [[0, 2, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[diamondstar]], }, }, groundflash = { circlealpha = 0.5, circlegrowth = 0, flashalpha = 1, flashsize = 50, ttl = 250, color = { [1] = 1, [2] = 0.40000000596046, [3] = 0.10000000149012, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 0, ground = true, water = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[1 1 0 0.01 1 0.7 0.5 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 40, particlelife = 30, particlelifespread = 0, particlesize = 2, particlesizespread = 7, particlespeed = 2, particlespeedspread = 16, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, }
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Port_San_dOria/Zone.lua
1
2062
----------------------------------- -- -- Zone: Port_San_dOria -- ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/server"); require("scripts/globals/settings"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; -- FIRST LOGIN (START CS) if (prevZone == 0) then if (OPENING_CUTSCENE_ENABLE == 1) then cs = 0x01F4; end CharCreate(player); player:setPos(-104, -8, -128, 227); player:setHomePoint(); end if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then if (prevZone == 223) then cs = 0x02BE; player:setPos(-1.000, 0.000, 44.000, 0); else player:setPos(80,-16,-135,165); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 0x7534; end player:setVar("PlayerMainJob",0); end end return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x02BC); 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 == 0x01F4) then player:messageSpecial(ITEM_OBTAINED,536); elseif (csid == 0x02BC) then player:setPos(0,0,0,0,223); elseif (csid == 0x7534 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); end end;
gpl-3.0
pakoito/ToME---t-engine4
game/modules/tome/data/maps/zones/reknor-last.lua
3
3437
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org defineTile('<', "UP") defineTile(' ', "FLOOR") defineTile('+', "DOOR") defineTile('#', "WALL") defineTile('$', "FLOOR", "MONEY_SMALL") defineTile('*', "FLOOR", "MONEY_BIG") defineTile('&', "FAR_EAST_PORTAL") defineTile('!', "CFAR_EAST_PORTAL") defineTile('O', "FLOOR", nil, "GOLBUG") defineTile('a', "FLOOR", nil, "ORC_ARCHER") defineTile('o', "FLOOR", nil, "ORC") defineTile('f', "FLOOR", nil, "ORC_FIRE_WYRMIC") defineTile('i', "FLOOR", nil, "ORC_ICE_WYRMIC") startx = 0 starty = 13 return [[ ####################################################################### ####################################################################### ####################################################################### ####################################################################### ####################################################################### ####################################################################### ##### ########################################################## #### a################################################### ##### ############a a######################## ###### ### ########### ######################## #### ###f ########## ########a ############# ### ### # ########## ###### ########### ### ### ########## f##### &&& ########## < o ###o +++++ O+++++ &!& ########## ### ## ########## i##### &&& ########## #### ### ########## ###### ########### #### ###i ########## ########a ############# ##### ### ########### ######################## ###### a############a a######################## ######## #################################################### ########## ######################################################### ####################################################################### ####################################################################### ####################################################################### ####################################################################### ####################################################################### ####################################################################### ####################################################################### ####################################################################### #######################################################################]]
gpl-3.0
gleachkr/luakit
config/rc.lua
1
6216
------------------------------------------------------------------------------ -- luakit configuration file, more information at https://luakit.github.io/ -- ------------------------------------------------------------------------------ require "lfs" -- Check for lua configuration files that will never be loaded because they are -- shadowed by builtin modules. table.insert(package.loaders, 2, function (modname) if not package.searchpath then return end local f = package.searchpath(modname, package.path) if not f or f:find(luakit.install_paths.install_dir .. "/", 0, true) ~= 1 then return end local lf = luakit.config_dir .. "/" .. modname:gsub("%.","/") .. ".lua" if f == lf then msg.warn("Loading local version of '" .. modname .. "' module: " .. lf) elseif lfs.attributes(lf) then msg.warn("Found local version " .. lf .. " for core module '" .. modname .. "', but it won't be used, unless you update 'package.path' accordingly.") end end) require "unique_instance" -- Set the number of web processes to use. A value of 0 means 'no limit'. luakit.process_limit = 4 -- Set the cookie storage location soup.cookies_storage = luakit.data_dir .. "/cookies.db" -- Load library of useful functions for luakit local lousy = require "lousy" -- Load users theme -- ("$XDG_CONFIG_HOME/luakit/theme.lua" or "/etc/xdg/luakit/theme.lua") lousy.theme.init(lousy.util.find_config("theme.lua")) assert(lousy.theme.get(), "failed to load theme") -- Load users window class -- ("$XDG_CONFIG_HOME/luakit/window.lua" or "/etc/xdg/luakit/window.lua") local window = require "window" -- Load users webview class -- ("$XDG_CONFIG_HOME/luakit/webview.lua" or "/etc/xdg/luakit/webview.lua") local webview = require "webview" -- Add luakit;//log/ chrome page local log_chrome = require "log_chrome" window.add_signal("build", function (w) local widgets, l, r = require "lousy.widget", w.sbar.l, w.sbar.r -- Left-aligned status bar widgets l.layout:pack(widgets.uri()) l.layout:pack(widgets.hist()) l.layout:pack(widgets.progress()) -- Right-aligned status bar widgets r.layout:pack(widgets.buf()) r.layout:pack(log_chrome.widget()) r.layout:pack(widgets.ssl()) r.layout:pack(widgets.tabi()) r.layout:pack(widgets.scroll()) end) -- Load luakit binds and modes local modes = require "modes" local binds = require "binds" local settings = require "settings" require "settings_chrome" ---------------------------------- -- Optional user script loading -- ---------------------------------- -- Add adblock local adblock = require "adblock" local adblock_chrome = require "adblock_chrome" local webinspector = require "webinspector" -- Add uzbl-like form filling local formfiller = require "formfiller" -- Add proxy support & manager local proxy = require "proxy" -- Add quickmarks support & manager local quickmarks = require "quickmarks" -- Add session saving/loading support local session = require "session" -- Add command to list closed tabs & bind to open closed tabs local undoclose = require "undoclose" -- Add command to list tab history items local tabhistory = require "tabhistory" -- Add greasemonkey-like javascript userscript support local userscripts = require "userscripts" -- Add bookmarks support local bookmarks = require "bookmarks" local bookmarks_chrome = require "bookmarks_chrome" -- Add download support local downloads = require "downloads" local downloads_chrome = require "downloads_chrome" -- Add automatic PDF downloading and opening local viewpdf = require "viewpdf" -- Example using xdg-open for opening downloads / showing download folders downloads.add_signal("open-file", function (file) luakit.spawn(string.format("xdg-open %q", file)) return true end) -- Add vimperator-like link hinting & following local follow = require "follow" -- Add command history local cmdhist = require "cmdhist" -- Add search mode & binds local search = require "search" -- Add ordering of new tabs local taborder = require "taborder" -- Save web history local history = require "history" local history_chrome = require "history_chrome" local help_chrome = require "help_chrome" local binds_chrome = require "binds_chrome" -- Add command completion local completion = require "completion" -- Press Control-E while in insert mode to edit the contents of the currently -- focused <textarea> or <input> element, using `xdg-open` local open_editor = require "open_editor" -- NoScript plugin, toggle scripts and or plugins on a per-domain basis. -- `,ts` to toggle scripts, `,tp` to toggle plugins, `,tr` to reset. -- If you use this module, don't use any site-specific `enable_scripts` or -- `enable_plugins` settings, as these will conflict. --require "noscript" local follow_selected = require "follow_selected" local go_input = require "go_input" local go_next_prev = require "go_next_prev" local go_up = require "go_up" -- Filter Referer HTTP header if page domain does not match Referer domain require_web_module("referer_control_wm") local error_page = require "error_page" -- Add userstyles loader local styles = require "styles" -- Hide scrollbars on all pages local hide_scrollbars = require "hide_scrollbars" -- Add a stylesheet when showing images local image_css = require "image_css" -- Add a new tab page local newtab_chrome = require "newtab_chrome" -- Add tab favicons mod local tab_favicons = require "tab_favicons" -- Add :view-source command local view_source = require "view_source" -- Put "userconf.lua" in your Luakit config dir with your own tweaks; if this is -- permanent, no need to copy/paste/modify the default rc.lua whenever you -- update Luakit. if pcall(function () lousy.util.find_config("userconf.lua") end) then require "userconf" end ----------------------------- -- End user script loading -- ----------------------------- -- Restore last saved session local w = (not luakit.nounique) and (session and session.restore()) if w then for i, uri in ipairs(uris) do w:new_tab(uri, { switch = i == 1 }) end else -- Or open new window window.new(uris) end -- vim: et:sw=4:ts=8:sts=4:tw=80
gpl-3.0
pakoito/ToME---t-engine4
game/modules/tome/data/talents/misc/misc.lua
2
16163
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org -- race & classes newTalentType{ type="base/class", name = "class", hide = true, description = "The basic talents defining a class." } newTalentType{ type="base/race", name = "race", hide = true, description = "The various racial bonuses a character can have." } newTalentType{ is_nature = true, type="inscriptions/infusions", name = "infusions", hide = true, description = "Infusions are not class abilities, you must find them or learn them from other people." } newTalentType{ is_spell=true, no_silence=true, type="inscriptions/runes", name = "runes", hide = true, description = "Runes are not class abilities, you must find them or learn them from other people." } newTalentType{ is_spell=true, no_silence=true, type="inscriptions/taints", name = "taints", hide = true, description = "Taints are not class abilities, you must find them or learn them from other people." } -- Load other misc things load("/data/talents/misc/objects.lua") load("/data/talents/misc/inscriptions.lua") load("/data/talents/misc/npcs.lua") load("/data/talents/misc/horrors.lua") load("/data/talents/misc/races.lua") load("/data/talents/misc/tutorial.lua") -- Default melee attack newTalent{ name = "Attack", type = {"base/class", 1}, no_energy = "fake", hide = "always", innate = true, points = 1, range = 1, message = false, no_break_stealth = true, -- stealth is broken in attackTarget requires_target = true, target = {type="hit", range=1}, tactical = { ATTACK = { PHYSICAL = 1 } }, no_unlearn_last = true, ignored_by_hotkeyautotalents = true, speed = 'weapon', action = function(self, t) local tg = self:getTalentTarget(t) local x, y = self:getTarget(tg) if not x then return end local _ _, x, y = self:canProject(tg, x, y) if not x then return end local target = game.level.map(x, y, engine.Map.ACTOR) if not target then return end local double_strike = false if self:knowTalent(self.T_DOUBLE_STRIKE) and self:isTalentActive(self.T_STRIKING_STANCE) then local t = self:getTalentFromId(self.T_DOUBLE_STRIKE) if not self:isTalentCoolingDown(t) then double_strike = true end end -- if double strike isn't on cooldown, throw a double strike; quality of life hack if double_strike then self:forceUseTalent(self.T_DOUBLE_STRIKE, {force_target=target}) -- uses energy because attack is 'fake' else self:attackTarget(target) end if config.settings.tome.smooth_move > 0 and config.settings.tome.twitch_move then self:setMoveAnim(self.x, self.y, config.settings.tome.smooth_move, blur, util.getDir(x, y, self.x, self.y), 0.2) end return true end, info = function(self, t) return ([[Hack and slash, baby!]]) end, } --mindslayer resource newTalent{ name = "Psi Pool", type = {"base/class", 1}, info = "Allows you to have an energy pool. Energy is used to perform psionic manipulations.", mode = "passive", hide = "always", no_unlearn_last = true, } newTalent{ name = "Feedback Pool", type = {"base/class", 1}, info = "Allows you to have a Feedback pool. Feedback is used to power feedback and discharge talents.", mode = "passive", hide = "always", -- Adjust feedback ratio with character level to reflect the degree of "pain" received -- Called in function _M:onTakeHit in mod.class.Actor.lua getFeedbackRatio = function(self, t, raw) local ratio = self:combatLimit(self.level, 0, 0.5, 1, 0.2, 50) -- Limit >0% damage taken, 50% @ level 1, 20% @ level 50 local mult = 1 + (not raw and self:callTalent(self.T_AMPLIFICATION, "getFeedbackGain") or 0) return ratio*mult end, no_unlearn_last = true, on_learn = function(self, t) if self:getMaxFeedback() <= 0 then -- self:incMaxFeedback(100) self:incMaxFeedback(100 - self:getMaxFeedback()) end return true end, } newTalent{ name = "Mana Pool", type = {"base/class", 1}, info = "Allows you to have a mana pool. Mana is used to cast all spells.", mode = "passive", hide = "always", no_unlearn_last = true, } newTalent{ name = "Soul Pool", type = {"base/class", 1}, info = "Allows you to have a mana soul. Souls are used to cast necrotic spells.", mode = "passive", hide = "always", no_unlearn_last = true, } newTalent{ name = "Vim Pool", type = {"base/class", 1}, info = "Allows you to have a vim pool. Vim is used by corruptions.", mode = "passive", hide = "always", no_unlearn_last = true, } newTalent{ name = "Stamina Pool", type = {"base/class", 1}, info = "Allows you to have a stamina pool. Stamina is used to activate special combat attacks.", mode = "passive", hide = "always", no_unlearn_last = true, } newTalent{ name = "Equilibrium Pool", type = {"base/class", 1}, info = "Allows you to have an equilibrium pool. Equilibrium is used to measure your balance with nature and the use of wild gifts.", mode = "passive", hide = "always", no_unlearn_last = true, } newTalent{ name = "Positive Pool", type = {"base/class", 1}, info = "Allows you to have a positive energy pool.", mode = "passive", hide = "always", no_unlearn_last = true, } newTalent{ name = "Negative Pool", type = {"base/class", 1}, info = "Allows you to have a negative energy pool.", mode = "passive", hide = "always", no_unlearn_last = true, } newTalent{ name = "Hate Pool", type = {"base/class", 1}, info = "Allows you to have a hate pool.", mode = "passive", hide = "always", no_unlearn_last = true, updateRegen = function(self, t) -- hate loss speeds up as hate increases local hate = self:getHate() local hateChange if hate < self.baseline_hate then hateChange = 0 else hateChange = -0.7 * math.pow(hate / 100, 1.5) end if hateChange < 0 then hateChange = math.min(0, math.max(hateChange, self.baseline_hate - hate)) end self.hate_regen = self.hate_regen - (self.hate_decay or 0) + hateChange self.hate_decay = hateChange end, updateBaseline = function(self, t) self.baseline_hate = math.max(10, self:getHate() * 0.5) end, on_kill = function(self, t, target) local hateGain = self.hate_per_kill local hateMessage if target.level - 2 > self.level then -- level bonus hateGain = hateGain + math.ceil(self:combatTalentScale(target.level - 2 - self.level, 2, 10, "log", 0, 1)) hateMessage = "#F53CBE#You have taken the life of an experienced foe!" end if target.rank >= 4 then -- boss bonus hateGain = hateGain * 4 hateMessage = "#F53CBE#Your hate has conquered a great adversary!" elseif target.rank >= 3 then -- elite bonus hateGain = hateGain * 2 hateMessage = "#F53CBE#An elite foe has fallen to your hate!" end hateGain = math.min(hateGain, 100) self.hate = math.min(self.max_hate, self.hate + hateGain) if hateMessage then game.logPlayer(self, hateMessage.." (+%d hate)", hateGain - self.hate_per_kill) end end, } newTalent{ name = "Paradox Pool", type = {"base/class", 1}, info = "Allows you to have a paradox pool.", mode = "passive", hide = "always", no_unlearn_last = true, } -- Madness difficulty newTalent{ name = "Hunted!", short_name = "HUNTED_PLAYER", type = {"base/class", 1}, mode = "passive", no_unlearn_last = true, callbackOnActBase = function(self, t) if not rng.percent(1 + self.level / 7) then return end local rad = math.ceil(10 + self.level / 5) for i = self.x - rad, self.x + rad do for j = self.y - rad, self.y + rad do if game.level.map:isBound(i, j) then local actor = game.level.map(i, j, game.level.map.ACTOR) if actor and self:reactionToward(actor) < 0 and not actor:attr("hunted_difficulty_immune") then actor:setEffect(actor.EFF_HUNTER_PLAYER, 30, {src=self}) end end end end end, info = function(self, t) return ([[You are hunted!. There is a %d%% chance each turn that all foes in a %d radius get a glimpse of your position for 30 turns.]]): format(1 + self.level / 7, 10 + self.level / 5) end, } -- Mages class talent, teleport to angolwen newTalent{ short_name = "TELEPORT_ANGOLWEN", name = "Teleport: Angolwen", type = {"base/class", 1}, cooldown = 400, no_npc_use = true, no_unlearn_last = true, no_silence=true, is_spell=true, action = function(self, t) if not self:canBe("worldport") or self:attr("never_move") then game.logPlayer(self, "The spell fizzles...") return end local seen = false -- Check for visible monsters, only see LOS actors, so telepathy wont prevent it core.fov.calc_circle(self.x, self.y, game.level.map.w, game.level.map.h, 20, function(_, x, y) return game.level.map:opaque(x, y) end, function(_, x, y) local actor = game.level.map(x, y, game.level.map.ACTOR) if actor and actor ~= self then seen = true end end, nil) if seen then game.log("There are creatures that could be watching you; you cannot take the risk.") return end self:setEffect(self.EFF_TELEPORT_ANGOLWEN, 40, {}) return true end, info = [[Allows a mage to teleport to the secret town of Angolwen. You have studied the magic arts there and have been granted a special portal spell to teleport there. Nobody must learn about this spell and so it should never be used while seen by any creatures. The spell will take time to activate. You must be out of sight of any creature when you cast it and when the teleportation takes effect.]] } -- Chronomancer class talent, teleport to Point Zero newTalent{ short_name = "TELEPORT_POINT_ZERO", name = "Timeport: Point Zero", type = {"base/class", 1}, cooldown = 400, no_npc_use = true, no_unlearn_last = true, no_silence=true, is_spell=true, action = function(self, t) if not self:canBe("worldport") or self:attr("never_move") then game.logPlayer(self, "The spell fizzles...") return end local seen = false -- Check for visible monsters, only see LOS actors, so telepathy wont prevent it core.fov.calc_circle(self.x, self.y, game.level.map.w, game.level.map.h, 20, function(_, x, y) return game.level.map:opaque(x, y) end, function(_, x, y) local actor = game.level.map(x, y, game.level.map.ACTOR) if actor and actor ~= self then if actor.summoner and actor.summoner == self then seen = false else seen = true end end end, nil) if seen then game.log("There are creatures that could be watching you; you cannot take the risk.") return end self:setEffect(self.EFF_TELEPORT_POINT_ZERO, 40, {}) self:attr("temporal_touched", 1) self:attr("time_travel_times", 1) return true end, info = [[Allows a chronomancer to timeport to Point Zero. You have studied the chronomancy there and have been granted a special portal spell to teleport there. Nobody must learn about this spell and so it should never be used while seen by any creatures. The spell will take time to activate. You must be out of sight of any creature when you cast it and when the timeportation takes effect.]] } newTalent{ name = "Relentless Pursuit", type = {"base/class", 1}, points = 5, no_energy = true, cooldown = function(self, t) return 55 - self:getTalentLevel(t) * 5 end, tactical = { CURE = function(self, t, target) local nb = 0 for eff_id, p in pairs(self.tmp) do local e = self.tempeffect_def[eff_id] if e.status == "detrimental" then nb = nb + 1 end end return nb end}, action = function(self, t) local target = self local todel = {} local save_for_effects = { magical = "combatSpellResist", mental = "combatMentalResist", physical = "combatPhysicalResist", } for eff_id, p in pairs(target.tmp) do local e = target.tempeffect_def[eff_id] if e.status == "detrimental" and save_for_effects[e.type] then local save = self[save_for_effects[e.type]](self, true) local decrease = math.floor(save/5) print("About to reduce duration of... %s. Will use %s. Reducing duration by %d", e.desc, save_for_effects[e.type]) p.dur = p.dur - decrease if p.dur <= 0 then todel[#todel+1] = eff_id end end end while #todel > 0 do target:removeEffect(table.remove(todel)) end game:playSoundNear(self, "talents/spell_generic") return true end, info = function(self, t) local physical_reduction = math.floor(self:combatPhysicalResist(true)/5) local spell_reduction = math.floor(self:combatSpellResist(true)/5) local mental_reduction = math.floor(self:combatMentalResist(true)/5) return ([[Not the Master himself, nor all the orcs in fallen Reknor, nor even the terrifying unknown beyond Reknor's portal could slow your pursuit of the Staff of Absorption. Children will hear of your relentlessness in song for years to come. When activated, this ability reduces the duration of all active detrimental effects by the appropriate saving throw duration reduction. Physical effect durations reduced by %d turns Magical effect durations reduced by %d turns Mental effect durations reduced by %d turns]]): format(physical_reduction, spell_reduction, mental_reduction) end, } newTalent{ short_name = "SHERTUL_FORTRESS_GETOUT", name = "Teleport to the ground", type = {"base/race", 1}, no_npc_use = true, no_unlearn_last = true, on_pre_use = function(self, t) return not game.zone.stellar_map end, action = function(self, t) if game.level.map:checkAllEntities(self.x, self.y, "block_move") then game.log("You cannot teleport there.") return true end game:onTickEnd(function() game.party:removeMember(self, true) game.party:findSuitablePlayer() game.player.dont_act = nil game.player:move(self.x, self.y, true) end) return true end, info = [[Use the onboard short-range teleport of the Fortress to beam down to the surface. Requires being in flight above the ground of a planet.]] } newTalent{ short_name = "SHERTUL_FORTRESS_BEAM", name = "Fire a blast of energy", type = {"base/race", 1}, fortress_energy = 10, no_npc_use = true, no_unlearn_last = true, on_pre_use = function(self, t) return not game.zone.stellar_map end, action = function(self, t) for i = 1, 5 do local rad = rng.float(0.5, 1) local bx = rng.range(-12, 12) local by = rng.range(-12, 12) if core.shader.active(4) then game.level.map:particleEmitter(self.x, self.y, 1, "shader_ring", {radius=rad * 2, life=12, x=bx, y=by}, {type="sparks", zoom=1, time_factor=400, hide_center=0, color1={0.6, 0.3, 0.8, 1}, color2={0.8, 0, 0.8, 1}}) else game.level.map:particleEmitter(self.x, self.y, 1, "generic_ball", {rm=150, rM=180, gm=20, gM=60, bm=180, bM=200, am=80, aM=150, radius=rad, x=bx, y=by}) end end local target = game.level.map(self.x, self.y, Map.ACTOR) if target and target.takePowerHit then target:takePowerHit(20, self) end game:playSoundNear(self, "talents/arcane") return true end, info = [[Use 10 Fortress energy to send a powerful blast to the ground, directly below the Fortress, heavily damaging any creatures caught inside. Requires being in flight above the ground of a planet.]] } newTalent{ short_name = "SHERTUL_FORTRESS_ORBIT", name = "High Planetary Orbit", type = {"base/race", 1}, fortress_energy = 100, no_npc_use = true, no_unlearn_last = true, no_energy = true, on_pre_use = function(self, t) return not game.zone.stellar_map end, action = function(self, t) game:changeLevelReal(1, "stellar-system-shandral", {}) game:playSoundNear(self, "talents/arcane") return true end, info = [[Activate the powerful flight engines of the Fortress, propelling it fast into high planetary orbit. Requires being in flight above the ground of a planet.]] }
gpl-3.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Bastok_Mines/npcs/Faustin.lua
1
1415
----------------------------------- -- Area: Bastok_Mines -- NPC: Faustin -- Only sells when Bastok controlls Ronfaure Region ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = getRegionOwner(RONFAURE); if (RegionOwner ~= BASTOK) then player:showText(npc,FAUSTIN_CLOSED_DIALOG); else player:showText(npc,FAUSTIN_OPEN_DIALOG); stock = {0x1125,29, -- San d'Orian Carrot 0x114f,69, -- San d'Orian Grape 0x027f,110, -- Chestnut 0x0262,55} -- San d'Orian Flour showShop(player,BASTOK,stock); 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
Max-pbot/Maxbot3
plugins/admin.lua
1
7212
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('User['..user_id..']File download shod dar:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, '['..user_id..']ax avaz shod!!', ok_cb, false) redis:del("bot:photo") else print('Khataye download: '..msg.id) send_large_msg(receiver, 'User['..user_id..']Khata lotfan dobare emtehan konid!!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'User['..user_id..']Sabr konid!' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'User['..user_id..']Lotfan axe morede nazaretoon ra ersal konid!' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > Roshan" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > Khamoosh" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg Send shod" end if matches[1] == "block" then if is_admin2(matches[2]) then return "User["..user_id.."]Shoma nemitavanid adminha ra kick konid!" end block_user("user#id"..matches[2],ok_cb,false) return "User["..user_id.."]User block shod" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User["..user_id.."]User Unblock shod" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end if matches[1] == "sync_gbans" then if not is_sudo(msg) then-- Sudo only return end local url = "http://seedteam.ir/Teleseed/Global_bans.json" local SEED_gbans = http.request(url) local jdat = json:decode(SEED_gbans) for k,v in pairs(jdat) do if not tonumber(v) == tonumber(our_id) and not is_admin2(v) then-- Ignore bot and admins :) redis:hset('user:'..v, 'print_name', k) redis:sadd('gbanned', v) print(k, v.." User["..user_id.."]Global ban shod") end end end return end return { patterns = { "^[!/](pm) (%d+) (.*)$", "^[!/](import) (.*)$", "^[!/](unblock) (%d+)$", "^[!/](block) (%d+)$", "^[!/](markread) (on)$", "^[!/](markread) (off)$", "^[!/](setbotphoto)$", "%[(photo)%]", "^[!/](contactlist)$", "^[!/](dialoglist)$", "^[!/](delcontact) (%d+)$", "^[!/](whois) (%d+)$", "^/(sync_gbans)$"--sync your global bans with seed }, run = run, } --By @imandaneshi :) --https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
gpl-2.0
pakoito/ToME---t-engine4
game/modules/tome/data/zones/temporal-rift/npcs.lua
2
8089
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org load("/data/general/npcs/telugoroth.lua", rarity(0)) load("/data/general/npcs/horror_temporal.lua", rarity(0)) local Talents = require("engine.interface.ActorTalents") newEntity{ define_as = "BEN_CRUTHDAR_ABOMINATION", type = "humanoid", subtype = "temporal", unique = true, name = "Ben Cruthdar, the Abomination", image = "npc/humanoid_human_ben_cruthdar__the_cursed.png", display = "p", color=colors.VIOLET, desc = [[This crazed madman seems twisted and corrupted by temporal energy, his body shifting and phasing in and out of reality.]], level_range = {15, nil}, exp_worth = 2, max_life = 270, life_rating = 17, fixed_rating = true, max_stamina = 85, stats = { str=20, dex=15, wil=18, con=20 }, rank = 3.5, size_category = 3, infravision = 10, instakill_immune = 1, move_others=true, resists = { [DamageType.COLD] = 25, [DamageType.TEMPORAL] = 25}, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 }, resolvers.equip{ {type="weapon", subtype="battleaxe", force_drop=true, tome_drops="boss", autoreq=true}, }, resolvers.drops{chance=100, nb=1, {tome_drops="boss"} }, resolvers.talents{ [Talents.T_GLOOM]=3, [Talents.T_WEAKNESS]=3, [Talents.T_DISMAY]=3, [Talents.T_UNNATURAL_BODY]=4, [Talents.T_DOMINATE]=1, [Talents.T_BLINDSIDE]=3, [Talents.T_SLASH]=3, [Talents.T_RECKLESS_CHARGE]=1, [Talents.T_DAMAGE_SMEARING]=5, [Talents.T_WEAPON_FOLDING]=3, [Talents.T_DISPLACE_DAMAGE]=3, [Talents.T_TEMPORAL_WAKE]=3, }, resolvers.sustains_at_birth(), autolevel = "warriorwill", ai = "tactical", ai_state = { talent_in=1, ai_move="move_astar", }, ai_tactic = resolvers.tactic"melee", resolvers.inscriptions(1, "healing infusion"), -- On die needs to make stairs back to the Rift on_die = function(self, who) game.level.data.portal_next(self) end, } newEntity{ define_as = "ABOMINATION_RANTHA", type = "dragon", subtype = "temporal", unique = true, name = "Rantha the Abomination", display = "D", color=colors.VIOLET, resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/dragon_temporal_rantha_the_abomination.png", display_h=2, display_y=-1}}}, desc = [[Claws and teeth. Ice and death. Dragons are not all extinct it seems... and this one seems to have been corrupted by the time rift.]], level_range = {15, nil}, exp_worth = 2, max_life = 220, life_rating = 15, fixed_rating = true, max_stamina = 85, max_mana = 200, stats = { str=25, dex=10, cun=8, mag=20, wil=20, con=20 }, rank = 3.5, size_category = 5, combat_armor = 17, combat_def = 14, infravision = 10, instakill_immune = 1, move_others=true, resists = { [DamageType.FIRE] = -20, [DamageType.COLD] = 100, [DamageType.TEMPORAL] = 25, }, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 }, -- Frost Treads drop should be changed. resolvers.drops{chance=100, nb=5, {type="gem"} }, resolvers.drops{chance=100, nb=10, {type="money"} }, resolvers.talents{ [Talents.T_KNOCKBACK]=3, [Talents.T_ICE_STORM]=2, [Talents.T_FREEZE]=3, [Talents.T_ICE_CLAW]=4, [Talents.T_ICY_SKIN]=3, [Talents.T_ICE_BREATH]=4, [Talents.T_CELERITY]=4, [Talents.T_SLOW]=4, [Talents.T_STOP]=4, [Talents.T_HASTE]=4, }, resolvers.sustains_at_birth(), autolevel = "warriormage", ai = "tactical", ai_state = { talent_in=1, ai_move="move_astar", }, resolvers.inscriptions(1, "infusion"), -- On die needs to make stairs back to the Rift on_die = function(self, who) game.level.data.portal_next(self) end, } local twin_take_hit = function(self, value, src) value = mod.class.Actor.onTakeHit(self, value, src) value = value / 2 if value > 0 and self.brother then local o = self.brother.onTakeHit self.brother.onTakeHit = nil self.brother:takeHit(value, src) if self.brother then self.brother.onTakeHit = o end end return value end newEntity{ base="BASE_NPC_HORROR_TEMPORAL", define_as = "CHRONOLITH_TWIN", name = "Chronolith Twin", color=colors.VIOLET, unique = true, subtype = "temporal", resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/horror_temporal_cronolith_twin.png", display_h=2, display_y=-1}}}, desc = [[A six-armed creature, dressed in robes, with black insectile eyes.]], level_range = {20, nil}, exp_worth = 1, max_life = 150, life_rating = 15, fixed_rating = true, rank = 4, size_category = 3, stats = { str=10, dex=12, cun=14, mag=25, wil=25, con=16 }, instakill_immune = 1, blind_immune = 0.5, silence_immune = 0.5, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 }, equipment = resolvers.equip{ {type="weapon", subtype="staff", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true}, {type="armor", subtype="cloth", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true}, }, resolvers.drops{chance=100, nb=2, {tome_drops="boss"} }, resolvers.drops{chance=100, nb=1, {unique=true} }, resists = { [DamageType.TEMPORAL] = 50, }, resolvers.talents{ [Talents.T_DUST_TO_DUST]=3, [Talents.T_REPULSION_BLAST]=3, [Talents.T_DESTABILIZE]=3, [Talents.T_ECHOES_FROM_THE_PAST]=3, [Talents.T_HASTE]=3, [Talents.T_DISENTANGLE]=5, [Talents.T_ENERGY_ABSORPTION]=5, [Talents.T_REPULSION_FIELD]=5, }, autolevel = "warriormage", ai = "tactical", ai_state = { talent_in=1, ai_move="move_astar", }, ai_tactic = resolvers.tactic "ranged", resolvers.inscriptions(1, {"shielding rune"}), onTakeHit = twin_take_hit, on_die = function(self, who) self.brother = nil game.player:resolveSource():setQuestStatus("temporal-rift", engine.Quest.COMPLETED, "twin") end, } newEntity{ base="BASE_NPC_HORROR_TEMPORAL", define_as = "CHRONOLITH_CLONE", name = "Chronolith Clone", color=colors.VIOLET, unique = true, subtype = "temporal", resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/horror_temporal_cronolith_clone.png", display_h=2, display_y=-1}}}, desc = [[A six-armed creature, dressed in robes, with black insectile eyes.]], level_range = {20, nil}, exp_worth = 1, max_life = 150, life_rating = 15, fixed_rating = true, rank = 4, size_category = 3, stats = { str=10, dex=12, cun=14, mag=25, wil=25, con=16 }, instakill_immune = 1, blind_immune = 0.5, silence_immune = 0.5, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 }, equipment = resolvers.equip{ {type="weapon", subtype="staff", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true}, {type="armor", subtype="cloth", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true}, }, resolvers.drops{chance=100, nb=2, {tome_drops="boss"} }, resolvers.drops{chance=100, nb=1, {unique=true} }, resists = { [DamageType.TEMPORAL] = 50, }, resolvers.talents{ [Talents.T_RETHREAD]=3, [Talents.T_FADE_FROM_TIME]=3, [Talents.T_TEMPORAL_FUGUE]=3, [Talents.T_TURN_BACK_THE_CLOCK]=3, [Talents.T_HASTE]=3, [Talents.T_BANISH]=5, [Talents.T_DISENTANGLE]=5, [Talents.T_ENTROPIC_FIELD]=5, }, autolevel = "warriormage", ai = "tactical", ai_state = { talent_in=1, ai_move="move_astar", }, ai_tactic = resolvers.tactic "ranged", resolvers.inscriptions(1, {"invisibility rune"}), onTakeHit = twin_take_hit, on_die = function(self, who) self.brother = nil game.player:resolveSource():setQuestStatus("temporal-rift", engine.Quest.COMPLETED, "clone") end, }
gpl-3.0
pakoito/ToME---t-engine4
game/modules/tome/data/chats/mage-apprentice-quest.lua
3
5765
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local p = game.party:findMember{main=true} if p:attr("forbid_arcane") then newChat{ id="welcome", text = [[#LIGHT_GREEN#*Before you stands a young man, a novice mage by his looks*#WHITE# Good day to yo...#LIGHT_GREEN#*He stares at you and starts to run away fast!*#WHITE# Do not kill me please!]], answers = { {"...", action = function(npc, player) npc:die() end, }, } } return "welcome" end newChat{ id="welcome", text = [[#LIGHT_GREEN#*Before you stands a young man, a novice mage by his looks*#WHITE# Good day to you, fellow traveler!]], answers = { {"What brings an apprentice mage out into the wilds?", jump="quest", cond=function(npc, player) return not player:hasQuest("mage-apprentice") end}, {"I found this artefact; it looks powerful and arcane infused. Maybe it would be enough?", jump="unique", cond=function(npc, player) return player:hasQuest("mage-apprentice") and player:hasQuest("mage-apprentice"):can_offer_unique(player) end, action=function(npc, player, dialog) player:hasQuest("mage-apprentice"):collect_staff_unique(npc, player, dialog) end }, -- Reward for non-mages: access to Angolwen {"So you have enough magical items now?", jump="thanks", cond=function(npc, player) return player:hasQuest("mage-apprentice") and player:hasQuest("mage-apprentice"):isCompleted() and not player:knowTalent(player.T_TELEPORT_ANGOLWEN) end, }, -- Reward for mages: upgrade a talent mastery {"So you have enough magical items now?", jump="thanks_mage", cond=function(npc, player) return player:hasQuest("mage-apprentice") and player:hasQuest("mage-apprentice"):isCompleted() and player:knowTalent(player.T_TELEPORT_ANGOLWEN) end, }, -- {"Do you have any items to sell?", jump="store"}, {"Sorry I have to go!"}, } } newChat{ id="quest", text = [[Ahh, my story is a sad one... I should not trouble you with it, my friend.]], answers = { {"It is no trouble at all! Please tell me!", jump="quest2"}, {"Ok, bye then!"}, } } newChat{ id="quest2", text = [[Well, if you insist... I am a novice mage, as you might have noticed, and my goal is to be accepted by the people of Angolwen and be taught the secrets of the arcane.]], answers = { {"Who are the people of Angolwen?", jump="quest3", cond=function(npc, player) return player.faction ~= "angolwen" end,}, {"Ah yes, Angolwen, I have called it home for many years...", jump="quest3_mage", cond=function(npc, player) return player.faction == "angolwen" end,}, {"Well, good luck, bye!"}, } } newChat{ id="quest3", text = [[The keepers of ar... err, I do not think I am supposed to talk about them... sorry, my friend... In any case, I must collect many items. I have some already but I am still looking for an arcane-infused artefact. You do not happen to have one, I imagine... Well, if you do, tell me please!]], answers = { {"I will keep that in mind!", action=function(npc, player) player:grantQuest("mage-apprentice") end}, {"No way, bye!"}, } } newChat{ id="quest3_mage", text = [[I hope I will too... In any case, I must collect many items. I have some already but I am still looking for an arcane-infused artefact. You do not happen to have one, I imagine... Well, if you do, tell me please!]], answers = { {"I will keep that in mind!", action=function(npc, player) player:grantQuest("mage-apprentice") end}, {"No way, bye!"}, } } newChat{ id="unique", text = [[Let me examine it. Oh yes, my friend, this is indeed a powerful artefact! I think that it should suffice to complete my quest! Many thanks!]], answers = { {"Well, I cannot use it anyway.", jump="welcome"}, } } newChat{ id="thanks", text = [[Ah yes! I am so glad! I will be able to go back to Angolw...err... Oh well, I guess I can tell you; you deserve it for helping me. During the dark years of the Spellhunt, many thousands of years ago, Linaniil, the great mage of the Kor'Krul, worried that magic might disappear with her generation and be lost to mortals should they need it again. So she set a secret plan into action and built a secret place where magic would be kept alive. Her plan worked and the group built a town called Angolwen in the western mountains. #LIGHT_GREEN#*He marks it on your map, along with a portal to access it*#WHITE# Not many people are accepted there but I will arrange for you to be allowed inside.]], answers = { {"Oh! How could such a place be kept secret for so long... This is interesting indeed. Thank you for your trust!", action = function(npc, player) player:hasQuest("mage-apprentice"):access_angolwen(player) npc:die() end, }, } } newChat{ id="thanks_mage", text = [[Ah yes! I am so glad! I will be able to go back to Angolwen now, and perhaps we will meet there. Please take this ring; it has served me well.]], answers = { {"Thanks, and best luck in your studies!", action = function(npc, player) player:hasQuest("mage-apprentice"):ring_gift(player) npc:die() end, }, } } return "welcome"
gpl-3.0
sagarwaghmare69/dpnn
ArgMax.lua
3
2014
------------------------------------------------------------------------ --[[ ArgMax ]]-- -- Returns the index of the maxima for dimension dim. -- Cannot backpropagate through this module. -- Created for use with ReinforceCategorical. ------------------------------------------------------------------------ local ArgMax, parent = torch.class("nn.ArgMax", "nn.Module") function ArgMax:__init(dim, nInputDim, asLong) parent.__init(self) self.dim = dim or 1 self.nInputDim = nInputDim or 9999 self.asLong = (asLong == nil) and true or asLong if self.asLong then self.output = torch.LongTensor() end end function ArgMax:updateOutput(input) self._value = self._value or input.new() self._indices = self._indices or (torch.type(input) == 'torch.CudaTensor' and (torch.CudaLongTensor and torch.CudaLongTensor() or torch.CudaTensor()) or torch.LongTensor()) local dim = (input:dim() > self.nInputDim) and (self.dim + 1) or self.dim torch.max(self._value, self._indices, input, dim) if input:dim() > 1 then local idx = self._indices:select(dim, 1) self.output:resize(idx:size()):copy(idx) else self.output:resize(self._indices:size()):copy(self._indices) end return self.output end function ArgMax:updateGradInput(input, gradOutput) -- cannot backprop from an index so just return a dummy zero tensor self.gradInput:resizeAs(input):zero() return self.gradInput end function ArgMax:type(type) -- torch.max expects a LongTensor as indices, whereas cutorch.max expects a CudaTensor. if type == 'torch.CudaTensor' then parent.type(self, type) else -- self._indices must be a LongTensor. Setting it to nil temporarily avoids -- unnecessary memory allocations. local indices indices, self._indices = self._indices, nil parent.type(self, type) self._indices = indices and indices:long() or nil end if self.asLong then self.output = torch.LongTensor() end return self end
bsd-3-clause
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Common/QuadTree.lua
1
11628
--[[ Title: QuadTree Author(s): wxa, refined and ported lxz Date: 2020/6/10 Desc: it will split as new objects are added to the tree. And it will only split vertically or horizontally if the number of objects on the parent node is larger than splitThreshold (default to 20). The minimum node size is defined by minWidth and minHeight, which all defaults to 16 use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/Common/QuadTree.lua"); local QuadTree = commonlib.gettable("MyCompany.Aries.Game.Common.QuadTree") local quadtree = QuadTree:new():Init({minWidth = 16, minHeight = 16, left = 0, top = 0, right = 100, bottom = 100, splitThreshold = 20}); -- object, left, top, right, bottom: where object can be any data type, except nil. quadtree:AddObject("1", 10, 10, 10, 10); quadtree:AddObject("2", 60, 10, 60, 10); quadtree:AddObject("3", 10, 60, 10, 60); quadtree:AddObject("4", 60, 60, 60, 60); echo(quadtree:GetObjects(10, 10, 10, 60)); -- {"3", "1"} quadtree:RemoveObject("1"); echo(quadtree:GetObjects(10, 10, 10, 60)); -- {"3"} echo(quadtree:GetObjectsByPoint(60, 10)); -- {"2"} ------------------------------------------------------- ]] local QuadTree = commonlib.inherit(commonlib.gettable("System.Core.ToolBase"), commonlib.gettable("MyCompany.Aries.Game.Common.QuadTree")); local QuadTreeNode = commonlib.inherit(commonlib.gettable("System.Core.ToolBase"), {}); -- when a quad object has less than this number of objects, we will not split. QuadTree.splitThreshold = 20; -- The minimum node size QuadTree.minWidth = 16; QuadTree.minHeight = 16; local QuadTreeNodeNid = 0; -- use the object itself as unique key local function GetObjectKey(object) return object; end function QuadTreeNode:ctor() self.childNodes = nil; self.objects = {}; -- 区间对象集 self.objectCount = 0; -- 对象数 end function QuadTreeNode:Init(left, top, right, bottom) self.left, self.top, self.right, self.bottom = left, top, right, bottom; return self; end function QuadTreeNode:IsSubArea(left, top, right, bottom) return not (left < self.left or right > self.right or top < self.top or bottom > self.bottom) end function QuadTreeNode:IsPointInSubArea(x, y) return not (x < self.left or x > self.right or y < self.top or y > self.bottom) end function QuadTreeNode:GetSubArea(left, top, right, bottom) left = left < self.left and self.left or left; top = top < self.top and self.top or top; right = right > self.right and self.right or right; bottom = bottom > self.bottom and self.bottom or bottom; return left, top, right, bottom, right >= left and bottom >= top; end function QuadTreeNode:Split(isSplitWidth, isSplitHeight) if (self.childNodes) then return end local left, top, right, bottom = self.left, self.top, self.right, self.bottom; local width, height = right - left, bottom - top; local centerX = left + math.floor(width / 2); local centerY = top + math.floor(height / 2); self.childNodes = {}; if (isSplitWidth and isSplitHeight) then table.insert(self.childNodes, QuadTreeNode:new():Init(left, top, centerX, centerY)); -- 左上角 table.insert(self.childNodes, QuadTreeNode:new():Init(centerX, top, right, centerY)); -- 右上角 table.insert(self.childNodes, QuadTreeNode:new():Init(left, centerY, centerX, bottom)); -- 左下角 table.insert(self.childNodes, QuadTreeNode:new():Init(centerX, centerY, right, bottom)); -- 右下角 elseif (isSplitWidth and not isSplitHeight) then table.insert(self.childNodes, QuadTreeNode:new():Init(left, top, centerX, bottom)); -- 左区 table.insert(self.childNodes, QuadTreeNode:new():Init(centerX, top, right, bottom)); -- 右区 elseif (not isSplitWidth and isSplitHeight) then table.insert(self.childNodes, QuadTreeNode:new():Init(left, top, right, centerY)); -- 上区 table.insert(self.childNodes, QuadTreeNode:new():Init(left, centerY, right, bottom)); -- 下区 end end function QuadTreeNode:GetChildNodes() return self.childNodes; end function QuadTreeNode:GetObjects() return self.objects; end function QuadTreeNode:IsSplit() return self.childNodes and true or false; end function QuadTreeNode:AddObject(object) local key = GetObjectKey(object); if (self.objects[key] ~= nil) then return end self.objectCount = self.objectCount + 1; self.objects[key] = object; end function QuadTreeNode:RemoveObject(object) local key = GetObjectKey(object); if (not self.objects[key]) then return end self.objectCount = self.objectCount - 1; self.objects[key] = nil; end function QuadTreeNode:GetObjectCount() return self.objectCount; end function QuadTreeNode:GetWidthHeight() return self.right - self.left, self.bottom - self.top; end function QuadTree:ctor() end function QuadTree:Init(opts) self.objects = {}; self.objectCount = 0; self.minWidth = opts.minWidth or self.minWidth; self.minHeight = opts.minHeight or self.minHeight; self.splitThreshold = opts.splitThreshold or self.splitThreshold; self.root = QuadTreeNode:new():Init(opts.left, opts.top, opts.right, opts.bottom); return self; end -- add object to quadtree according to its size and position. -- @param object: can be everything but nil. -- @param fromHeight, toHeight: optional third dimension. so that we can also filter objects as 3D AABB box. function QuadTree:AddObject(object, left, top, right, bottom, fromHeight, toHeight) local minWidth, minHeight, splitThreshold = self.minWidth, self.minHeight, self.splitThreshold; -- 添加前先移除旧对象 self:RemoveObject(object); -- 添加新对象 local function AddObjectToNode(node, object, left, top, right, bottom) local key = GetObjectKey(object); self.objects[key] = {node = node, left = left, right = right, top = top, bottom = bottom, fromHeight = fromHeight, toHeight = toHeight}; self.objectCount = self.objectCount + 1; node:AddObject(object); -- echo({"------------------AddObjectToNode", object, node.left, node.top, node.right, node.bottom, node:GetObjects()}); return node; end local function AddObject(node, object, left, top, right, bottom) -- echo({"------------------IsSubArea", object, node.left, node.top, node.right, node.bottom, node:IsSubArea(left, top, right, bottom), left, top, right, bottom}); local width, height = right - left, bottom - top; local nodeWidth, nodeHeight = node:GetWidthHeight(); local childNodeWidth, childNodeHeight = math.floor(nodeWidth / 2), math.floor(nodeHeight / 2); local splitThreshold, objectCount = self.splitThreshold, node:GetObjectCount(); -- 不在当前节点区域内 直接返回 if (not node:IsSubArea(left, top, right, bottom)) then return end -- 添加区域大于子区域, 子区域小于最小区域 if ((childNodeWidth <= width and childNodeHeight <= height) or (childNodeWidth <= minWidth and childNodeHeight <= minHeight)) then return AddObjectToNode(node, object, left, top, right, bottom); end if (not node:IsSplit()) then -- 未分割,且节点对象小于阈值直接添加 if (objectCount < splitThreshold) then return AddObjectToNode(node, object, left, top, right, bottom); end -- 已超过分割阈值 进行分割 node:Split(childNodeWidth > minWidth, childNodeHeight > minHeight); -- 子节点宽高大于最小宽高时才执行分割 -- 分割完, 节点对象需进行重新分配 local objects = node:GetObjects(); for key, val in pairs(objects) do local ov = self.objects[key]; node:RemoveObject(val); AddObject(node, val, ov.left, ov.top, ov.right, ov.bottom); end end -- 是否分割 local childNodes = node:GetChildNodes(); for i = 1, #childNodes do local childNode = childNodes[i]; if (childNode:IsSubArea(left, top, right, bottom)) then return AddObject(childNode, object, left, top, right, bottom); end end -- 没有添加到子区域则添加到当前区域 AddObjectToNode(node, object, left, top, right, bottom); end return AddObject(self.root, object, left, top, right, bottom); end function QuadTree:RemoveObject(object) local key = GetObjectKey(object); local value = self.objects[key]; if (not value) then return end value.node:RemoveObject(object); self.objects[key] = nil; self.objectCount = self.objectCount - 1; end function QuadTree:GetObjectCount() return self.objectCount; end -- return nil or array of objects inside the given region function QuadTree:GetObjects(left, top, right, bottom) local list local objects = self.objects; local function GetObjects(node, left, top, right, bottom) left, top, right, bottom, isValidArea = node:GetSubArea(left, top, right, bottom); -- 交集区域无效 直接返回 if (not isValidArea) then return end; local nodeObjects = node:GetObjects(); -- 当前节点存的在对象都不在子区域内, 对象占多个子区域, 所以需加入遍历列表 for key, val in pairs(nodeObjects) do local o = objects[key]; if (o and o.left >= left and o.right <= right and o.top >= top and o.bottom <= bottom) then list = list or {}; list[#list + 1] = val; end end if (not node:IsSplit()) then return end -- 已分割查找子区域 local childNodes = node:GetChildNodes(); for i = 1, #childNodes do GetObjects(childNodes[i], left, top, right, bottom); end end GetObjects(self.root, left, top, right, bottom); return list; end -- return nil or array of objects containing the given point function QuadTree:GetObjectsByPoint(x, y) local list local objects = self.objects; local function GetObjectsByPoint(node) if(not node:IsPointInSubArea(x, y)) then return end local nodeObjects = node:GetObjects(); for key, val in pairs(nodeObjects) do local o = objects[key]; if (o and o.left <= x and o.right >= x and o.top <= y and o.bottom >= y) then list = list or {}; list[#list + 1] = val; end end if (node:IsSplit()) then local childNodes = node:GetChildNodes(); for i = 1, #childNodes do GetObjectsByPoint(childNodes[i]); end end end GetObjectsByPoint(self.root); return list; end -- return nil or array of objects containing the given point function QuadTree:GetObjectsBy3DPoint(x, y, z) local list local objects = self.objects; local function GetObjectsBy3DPoint(node) if(not node:IsPointInSubArea(x, z)) then return end local nodeObjects = node:GetObjects(); for key, val in pairs(nodeObjects) do local o = objects[key]; if (o and o.left <= x and o.right >= x and o.top <= z and o.bottom >= z and (not o.fromHeight or (o.fromHeight <= y and y <= o.toHeight))) then list = list or {}; list[#list + 1] = val; end end if (node:IsSplit()) then local childNodes = node:GetChildNodes(); for i = 1, #childNodes do GetObjectsBy3DPoint(childNodes[i]); end end end GetObjectsBy3DPoint(self.root); return list; end
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Metalworks/npcs/Manilam.lua
5
1034
----------------------------------- -- Area: Metalworks -- NPC: Manilam -- Type: Quest NPC -- @zone: 237 -- @pos: -57.300 -11 22.332 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0191); 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
hfjgjfg/eli25
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
hfjgjfg/PERSIANGUARD10
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
Har1eyquinn/Watch_Dog
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
terinux/ahhhh
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
llX8Xll/DEVKEEPER1
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Code/NplMicroRobot/NplMicroRobotDef/NplMicroRobotDef_Servo.lua
1
1704
--[[ Title: NplMicroRobotDef_Servo Author(s): leio Date: 2020/12/15 Desc: use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/Code/NplMicroRobot/NplMicroRobotDef/NplMicroRobotDef_Servo.lua"); ------------------------------------------------------- ]] NPL.export({ { type = "ServoPulse", message0 = L"设置舵机 %1 脉宽 %2", arg0 = { { name = "channel", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "value", type = "input_value", shadow = { type = "math_number", value = 1500,}, text = 1500, }, }, previousStatement = true, nextStatement = true, category = "NplMicroRobot.Servo", helpUrl = "", canRun = false, funcName = "NplMicroRobot.ServoPulse", func_description = 'NplMicroRobot.ServoPulse(%s,%s)', ToNPL = function(self) return ""; end, examples = {{desc = "", canRun = true, code = [[ ]]}}, }, { type = "Servo", message0 = L"设置舵机 %1 角度 %2", arg0 = { { name = "channel", type = "input_value", shadow = { type = "math_number", value = 0,}, text = 0, }, { name = "value", type = "input_value", shadow = { type = "math_number", value = 90,}, text = 90, }, }, previousStatement = true, nextStatement = true, category = "NplMicroRobot.Servo", helpUrl = "", canRun = false, funcName = "NplMicroRobot.Servo", func_description = 'NplMicroRobot.Servo(%s,%s)', ToNPL = function(self) return ""; end, examples = {{desc = "", canRun = true, code = [[ ]]}}, }, })
gpl-2.0
CerNerCompany/Anti-Spam
bot/utf8.lua
9
26232
-- $Id: utf8.lua 179 2009-04-03 18:10:03Z pasta $ -- -- Provides UTF-8 aware string functions implemented in pure lua: -- * utf8len(s) -- * utf8sub(s, i, j) -- * utf8reverse(s) -- * utf8char(unicode) -- * utf8unicode(s, i, j) -- * utf8gensub(s, sub_len) -- * utf8find(str, regex, init, plain) -- * utf8match(str, regex, init) -- * utf8gmatch(str, regex, all) -- * utf8gsub(str, regex, repl, limit) -- -- If utf8data.lua (containing the lower<->upper case mappings) is loaded, these -- additional functions are available: -- * utf8upper(s) -- * utf8lower(s) -- -- All functions behave as their non UTF-8 aware counterparts with the exception -- that UTF-8 characters are used instead of bytes for all units. --[[ Copyright (c) 2006-2007, Kyle Smith All rights reserved. Contributors: Alimov Stepan Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --]] -- ABNF from RFC 3629 -- -- UTF8-octets = *( UTF8-char ) -- UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4 -- UTF8-1 = %x00-7F -- UTF8-2 = %xC2-DF UTF8-tail -- UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / -- %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) -- UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / -- %xF4 %x80-8F 2( UTF8-tail ) -- UTF8-tail = %x80-BF -- local byte = string.byte local char = string.char local dump = string.dump local find = string.find local format = string.format local len = string.len local lower = string.lower local rep = string.rep local sub = string.sub local upper = string.upper -- returns the number of bytes used by the UTF-8 character at byte i in s -- also doubles as a UTF-8 character validator local function utf8charbytes (s, i) -- argument defaults i = i or 1 -- argument checking if type(s) ~= "string" then error("bad argument #1 to 'utf8charbytes' (string expected, got ".. type(s).. ")") end if type(i) ~= "number" then error("bad argument #2 to 'utf8charbytes' (number expected, got ".. type(i).. ")") end local c = byte(s, i) -- determine bytes needed for character, based on RFC 3629 -- validate byte 1 if c > 0 and c <= 127 then -- UTF8-1 return 1 elseif c >= 194 and c <= 223 then -- UTF8-2 local c2 = byte(s, i + 1) if not c2 then error("UTF-8 string terminated early") end -- validate byte 2 if c2 < 128 or c2 > 191 then error("Invalid UTF-8 character") end return 2 elseif c >= 224 and c <= 239 then -- UTF8-3 local c2 = byte(s, i + 1) local c3 = byte(s, i + 2) if not c2 or not c3 then error("UTF-8 string terminated early") end -- validate byte 2 if c == 224 and (c2 < 160 or c2 > 191) then error("Invalid UTF-8 character") elseif c == 237 and (c2 < 128 or c2 > 159) then error("Invalid UTF-8 character") elseif c2 < 128 or c2 > 191 then error("Invalid UTF-8 character") end -- validate byte 3 if c3 < 128 or c3 > 191 then error("Invalid UTF-8 character") end return 3 elseif c >= 240 and c <= 244 then -- UTF8-4 local c2 = byte(s, i + 1) local c3 = byte(s, i + 2) local c4 = byte(s, i + 3) if not c2 or not c3 or not c4 then error("UTF-8 string terminated early") end -- validate byte 2 if c == 240 and (c2 < 144 or c2 > 191) then error("Invalid UTF-8 character") elseif c == 244 and (c2 < 128 or c2 > 143) then error("Invalid UTF-8 character") elseif c2 < 128 or c2 > 191 then error("Invalid UTF-8 character") end -- validate byte 3 if c3 < 128 or c3 > 191 then error("Invalid UTF-8 character") end -- validate byte 4 if c4 < 128 or c4 > 191 then error("Invalid UTF-8 character") end return 4 else error("Invalid UTF-8 character") end end -- returns the number of characters in a UTF-8 string local function utf8len (s) -- argument checking if type(s) ~= "string" then for k,v in pairs(s) do print('"',tostring(k),'"',tostring(v),'"') end error("bad argument #1 to 'utf8len' (string expected, got ".. type(s).. ")") end local pos = 1 local bytes = len(s) local length = 0 while pos <= bytes do length = length + 1 pos = pos + utf8charbytes(s, pos) end return length end -- functions identically to string.sub except that i and j are UTF-8 characters -- instead of bytes local function utf8sub (s, i, j) -- argument defaults j = j or -1 local pos = 1 local bytes = len(s) local length = 0 -- only set l if i or j is negative local l = (i >= 0 and j >= 0) or utf8len(s) local startChar = (i >= 0) and i or l + i + 1 local endChar = (j >= 0) and j or l + j + 1 -- can't have start before end! if startChar > endChar then return "" end -- byte offsets to pass to string.sub local startByte,endByte = 1,bytes while pos <= bytes do length = length + 1 if length == startChar then startByte = pos end pos = pos + utf8charbytes(s, pos) if length == endChar then endByte = pos - 1 break end end if startChar > length then startByte = bytes+1 end if endChar < 1 then endByte = 0 end return sub(s, startByte, endByte) end --[[ -- replace UTF-8 characters based on a mapping table local function utf8replace (s, mapping) -- argument checking if type(s) ~= "string" then error("bad argument #1 to 'utf8replace' (string expected, got ".. type(s).. ")") end if type(mapping) ~= "table" then error("bad argument #2 to 'utf8replace' (table expected, got ".. type(mapping).. ")") end local pos = 1 local bytes = len(s) local charbytes local newstr = "" while pos <= bytes do charbytes = utf8charbytes(s, pos) local c = sub(s, pos, pos + charbytes - 1) newstr = newstr .. (mapping[c] or c) pos = pos + charbytes end return newstr end -- identical to string.upper except it knows about unicode simple case conversions local function utf8upper (s) return utf8replace(s, utf8_lc_uc) end -- identical to string.lower except it knows about unicode simple case conversions local function utf8lower (s) return utf8replace(s, utf8_uc_lc) end ]] -- identical to string.reverse except that it supports UTF-8 local function utf8reverse (s) -- argument checking if type(s) ~= "string" then error("bad argument #1 to 'utf8reverse' (string expected, got ".. type(s).. ")") end local bytes = len(s) local pos = bytes local charbytes local newstr = "" while pos > 0 do local c = byte(s, pos) while c >= 128 and c <= 191 do pos = pos - 1 c = byte(s, pos) end charbytes = utf8charbytes(s, pos) newstr = newstr .. sub(s, pos, pos + charbytes - 1) pos = pos - 1 end return newstr end -- http://en.wikipedia.org/wiki/Utf8 -- http://developer.coronalabs.com/code/utf-8-conversion-utility local function utf8char(unicode) if unicode <= 0x7F then return char(unicode) end if (unicode <= 0x7FF) then local Byte0 = 0xC0 + math.floor(unicode / 0x40); local Byte1 = 0x80 + (unicode % 0x40); return char(Byte0, Byte1); end; if (unicode <= 0xFFFF) then local Byte0 = 0xE0 + math.floor(unicode / 0x1000); local Byte1 = 0x80 + (math.floor(unicode / 0x40) % 0x40); local Byte2 = 0x80 + (unicode % 0x40); return char(Byte0, Byte1, Byte2); end; if (unicode <= 0x10FFFF) then local code = unicode local Byte3= 0x80 + (code % 0x40); code = math.floor(code / 0x40) local Byte2= 0x80 + (code % 0x40); code = math.floor(code / 0x40) local Byte1= 0x80 + (code % 0x40); code = math.floor(code / 0x40) local Byte0= 0xF0 + code; return char(Byte0, Byte1, Byte2, Byte3); end; error 'Unicode cannot be greater than U+10FFFF!' end local shift_6 = 2^6 local shift_12 = 2^12 local shift_18 = 2^18 local utf8unicode utf8unicode = function(str, i, j, byte_pos) i = i or 1 j = j or i if i > j then return end local ch,bytes if byte_pos then bytes = utf8charbytes(str,byte_pos) ch = sub(str,byte_pos,byte_pos-1+bytes) else ch,byte_pos = utf8sub(str,i,i), 0 bytes = #ch end local unicode if bytes == 1 then unicode = byte(ch) end if bytes == 2 then local byte0,byte1 = byte(ch,1,2) local code0,code1 = byte0-0xC0,byte1-0x80 unicode = code0*shift_6 + code1 end if bytes == 3 then local byte0,byte1,byte2 = byte(ch,1,3) local code0,code1,code2 = byte0-0xE0,byte1-0x80,byte2-0x80 unicode = code0*shift_12 + code1*shift_6 + code2 end if bytes == 4 then local byte0,byte1,byte2,byte3 = byte(ch,1,4) local code0,code1,code2,code3 = byte0-0xF0,byte1-0x80,byte2-0x80,byte3-0x80 unicode = code0*shift_18 + code1*shift_12 + code2*shift_6 + code3 end return unicode,utf8unicode(str, i+1, j, byte_pos+bytes) end -- Returns an iterator which returns the next substring and its byte interval local function utf8gensub(str, sub_len) sub_len = sub_len or 1 local byte_pos = 1 local length = #str return function(skip) if skip then byte_pos = byte_pos + skip end local char_count = 0 local start = byte_pos repeat if byte_pos > length then return end char_count = char_count + 1 local bytes = utf8charbytes(str,byte_pos) byte_pos = byte_pos+bytes until char_count == sub_len local last = byte_pos-1 local slice = sub(str,start,last) return slice, start, last end end local function binsearch(sortedTable, item, comp) local head, tail = 1, #sortedTable local mid = math.floor((head + tail)/2) if not comp then while (tail - head) > 1 do if sortedTable[tonumber(mid)] > item then tail = mid else head = mid end mid = math.floor((head + tail)/2) end end if sortedTable[tonumber(head)] == item then return true, tonumber(head) elseif sortedTable[tonumber(tail)] == item then return true, tonumber(tail) else return false end end local function classMatchGenerator(class, plain) local codes = {} local ranges = {} local ignore = false local range = false local firstletter = true local unmatch = false local it = utf8gensub(class) local skip for c, _, be in it do skip = be if not ignore and not plain then if c == "%" then ignore = true elseif c == "-" then table.insert(codes, utf8unicode(c)) range = true elseif c == "^" then if not firstletter then error('!!!') else unmatch = true end elseif c == ']' then break else if not range then table.insert(codes, utf8unicode(c)) else table.remove(codes) -- removing '-' table.insert(ranges, {table.remove(codes), utf8unicode(c)}) range = false end end elseif ignore and not plain then if c == 'a' then -- %a: represents all letters. (ONLY ASCII) table.insert(ranges, {65, 90}) -- A - Z table.insert(ranges, {97, 122}) -- a - z elseif c == 'c' then -- %c: represents all control characters. table.insert(ranges, {0, 31}) table.insert(codes, 127) elseif c == 'd' then -- %d: represents all digits. table.insert(ranges, {48, 57}) -- 0 - 9 elseif c == 'g' then -- %g: represents all printable characters except space. table.insert(ranges, {1, 8}) table.insert(ranges, {14, 31}) table.insert(ranges, {33, 132}) table.insert(ranges, {134, 159}) table.insert(ranges, {161, 5759}) table.insert(ranges, {5761, 8191}) table.insert(ranges, {8203, 8231}) table.insert(ranges, {8234, 8238}) table.insert(ranges, {8240, 8286}) table.insert(ranges, {8288, 12287}) elseif c == 'l' then -- %l: represents all lowercase letters. (ONLY ASCII) table.insert(ranges, {97, 122}) -- a - z elseif c == 'p' then -- %p: represents all punctuation characters. (ONLY ASCII) table.insert(ranges, {33, 47}) table.insert(ranges, {58, 64}) table.insert(ranges, {91, 96}) table.insert(ranges, {123, 126}) elseif c == 's' then -- %s: represents all space characters. table.insert(ranges, {9, 13}) table.insert(codes, 32) table.insert(codes, 133) table.insert(codes, 160) table.insert(codes, 5760) table.insert(ranges, {8192, 8202}) table.insert(codes, 8232) table.insert(codes, 8233) table.insert(codes, 8239) table.insert(codes, 8287) table.insert(codes, 12288) elseif c == 'u' then -- %u: represents all uppercase letters. (ONLY ASCII) table.insert(ranges, {65, 90}) -- A - Z elseif c == 'w' then -- %w: represents all alphanumeric characters. (ONLY ASCII) table.insert(ranges, {48, 57}) -- 0 - 9 table.insert(ranges, {65, 90}) -- A - Z table.insert(ranges, {97, 122}) -- a - z elseif c == 'x' then -- %x: represents all hexadecimal digits. table.insert(ranges, {48, 57}) -- 0 - 9 table.insert(ranges, {65, 70}) -- A - F table.insert(ranges, {97, 102}) -- a - f else if not range then table.insert(codes, utf8unicode(c)) else table.remove(codes) -- removing '-' table.insert(ranges, {table.remove(codes), utf8unicode(c)}) range = false end end ignore = false else if not range then table.insert(codes, utf8unicode(c)) else table.remove(codes) -- removing '-' table.insert(ranges, {table.remove(codes), utf8unicode(c)}) range = false end ignore = false end firstletter = false end table.sort(codes) local function inRanges(charCode) for _,r in ipairs(ranges) do if r[1] <= charCode and charCode <= r[2] then return true end end return false end if not unmatch then return function(charCode) return binsearch(codes, charCode) or inRanges(charCode) end, skip else return function(charCode) return charCode ~= -1 and not (binsearch(codes, charCode) or inRanges(charCode)) end, skip end end --[[ -- utf8sub with extra argument, and extra result value local function utf8subWithBytes (s, i, j, sb) -- argument defaults j = j or -1 local pos = sb or 1 local bytes = len(s) local length = 0 -- only set l if i or j is negative local l = (i >= 0 and j >= 0) or utf8len(s) local startChar = (i >= 0) and i or l + i + 1 local endChar = (j >= 0) and j or l + j + 1 -- can't have start before end! if startChar > endChar then return "" end -- byte offsets to pass to string.sub local startByte,endByte = 1,bytes while pos <= bytes do length = length + 1 if length == startChar then startByte = pos end pos = pos + utf8charbytes(s, pos) if length == endChar then endByte = pos - 1 break end end if startChar > length then startByte = bytes+1 end if endChar < 1 then endByte = 0 end return sub(s, startByte, endByte), endByte + 1 end ]] local cache = setmetatable({},{ __mode = 'kv' }) local cachePlain = setmetatable({},{ __mode = 'kv' }) local function matcherGenerator(regex, plain) local matcher = { functions = {}, captures = {} } if not plain then cache[regex] = matcher else cachePlain[regex] = matcher end local function simple(func) return function(cC) if func(cC) then matcher:nextFunc() matcher:nextStr() else matcher:reset() end end end local function star(func) return function(cC) if func(cC) then matcher:fullResetOnNextFunc() matcher:nextStr() else matcher:nextFunc() end end end local function minus(func) return function(cC) if func(cC) then matcher:fullResetOnNextStr() end matcher:nextFunc() end end local function question(func) return function(cC) if func(cC) then matcher:fullResetOnNextFunc() matcher:nextStr() end matcher:nextFunc() end end local function capture(id) return function(_) local l = matcher.captures[id][2] - matcher.captures[id][1] local captured = utf8sub(matcher.string, matcher.captures[id][1], matcher.captures[id][2]) local check = utf8sub(matcher.string, matcher.str, matcher.str + l) if captured == check then for _ = 0, l do matcher:nextStr() end matcher:nextFunc() else matcher:reset() end end end local function captureStart(id) return function(_) matcher.captures[id][1] = matcher.str matcher:nextFunc() end end local function captureStop(id) return function(_) matcher.captures[id][2] = matcher.str - 1 matcher:nextFunc() end end local function balancer(str) local sum = 0 local bc, ec = utf8sub(str, 1, 1), utf8sub(str, 2, 2) local skip = len(bc) + len(ec) bc, ec = utf8unicode(bc), utf8unicode(ec) return function(cC) if cC == ec and sum > 0 then sum = sum - 1 if sum == 0 then matcher:nextFunc() end matcher:nextStr() elseif cC == bc then sum = sum + 1 matcher:nextStr() else if sum == 0 or cC == -1 then sum = 0 matcher:reset() else matcher:nextStr() end end end, skip end matcher.functions[1] = function(_) matcher:fullResetOnNextStr() matcher.seqStart = matcher.str matcher:nextFunc() if (matcher.str > matcher.startStr and matcher.fromStart) or matcher.str >= matcher.stringLen then matcher.stop = true matcher.seqStart = nil end end local lastFunc local ignore = false local skip = nil local it = (function() local gen = utf8gensub(regex) return function() return gen(skip) end end)() local cs = {} for c, bs, be in it do skip = nil if plain then table.insert(matcher.functions, simple(classMatchGenerator(c, plain))) else if ignore then if find('123456789', c, 1, true) then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) lastFunc = nil end table.insert(matcher.functions, capture(tonumber(c))) elseif c == 'b' then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) lastFunc = nil end local b b, skip = balancer(sub(regex, be + 1, be + 9)) table.insert(matcher.functions, b) else lastFunc = classMatchGenerator('%' .. c) end ignore = false else if c == '*' then if lastFunc then table.insert(matcher.functions, star(lastFunc)) lastFunc = nil else error('invalid regex after ' .. sub(regex, 1, bs)) end elseif c == '+' then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) table.insert(matcher.functions, star(lastFunc)) lastFunc = nil else error('invalid regex after ' .. sub(regex, 1, bs)) end elseif c == '-' then if lastFunc then table.insert(matcher.functions, minus(lastFunc)) lastFunc = nil else error('invalid regex after ' .. sub(regex, 1, bs)) end elseif c == '?' then if lastFunc then table.insert(matcher.functions, question(lastFunc)) lastFunc = nil else error('invalid regex after ' .. sub(regex, 1, bs)) end elseif c == '^' then if bs == 1 then matcher.fromStart = true else error('invalid regex after ' .. sub(regex, 1, bs)) end elseif c == '$' then if be == len(regex) then matcher.toEnd = true else error('invalid regex after ' .. sub(regex, 1, bs)) end elseif c == '[' then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) end lastFunc, skip = classMatchGenerator(sub(regex, be + 1)) elseif c == '(' then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) lastFunc = nil end table.insert(matcher.captures, {}) table.insert(cs, #matcher.captures) table.insert(matcher.functions, captureStart(cs[#cs])) if sub(regex, be + 1, be + 1) == ')' then matcher.captures[#matcher.captures].empty = true end elseif c == ')' then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) lastFunc = nil end local cap = table.remove(cs) if not cap then error('invalid capture: "(" missing') end table.insert(matcher.functions, captureStop(cap)) elseif c == '.' then if lastFunc then table.insert(matcher.functions, simple(lastFunc)) end lastFunc = function(cC) return cC ~= -1 end elseif c == '%' then ignore = true else if lastFunc then table.insert(matcher.functions, simple(lastFunc)) end lastFunc = classMatchGenerator(c) end end end end if #cs > 0 then error('invalid capture: ")" missing') end if lastFunc then table.insert(matcher.functions, simple(lastFunc)) end table.insert(matcher.functions, function() if matcher.toEnd and matcher.str ~= matcher.stringLen then matcher:reset() else matcher.stop = true end end) matcher.nextFunc = function(self) self.func = self.func + 1 end matcher.nextStr = function(self) self.str = self.str + 1 end matcher.strReset = function(self) local oldReset = self.reset local str = self.str self.reset = function(s) s.str = str s.reset = oldReset end end matcher.fullResetOnNextFunc = function(self) local oldReset = self.reset local func = self.func +1 local str = self.str self.reset = function(s) s.func = func s.str = str s.reset = oldReset end end matcher.fullResetOnNextStr = function(self) local oldReset = self.reset local str = self.str + 1 local func = self.func self.reset = function(s) s.func = func s.str = str s.reset = oldReset end end matcher.process = function(self, str, start) self.func = 1 start = start or 1 self.startStr = (start >= 0) and start or utf8len(str) + start + 1 self.seqStart = self.startStr self.str = self.startStr self.stringLen = utf8len(str) + 1 self.string = str self.stop = false self.reset = function(s) s.func = 1 end -- local lastPos = self.str -- local lastByte local ch while not self.stop do if self.str < self.stringLen then --[[ if lastPos < self.str then print('last byte', lastByte) ch, lastByte = utf8subWithBytes(str, 1, self.str - lastPos - 1, lastByte) ch, lastByte = utf8subWithBytes(str, 1, 1, lastByte) lastByte = lastByte - 1 else ch, lastByte = utf8subWithBytes(str, self.str, self.str) end lastPos = self.str ]] ch = utf8sub(str, self.str,self.str) --print('char', ch, utf8unicode(ch)) self.functions[self.func](utf8unicode(ch)) else self.functions[self.func](-1) end end if self.seqStart then local captures = {} for _,pair in pairs(self.captures) do if pair.empty then table.insert(captures, pair[1]) else table.insert(captures, utf8sub(str, pair[1], pair[2])) end end return self.seqStart, self.str - 1, unpack(captures) end end return matcher end -- string.find local function utf8find(str, regex, init, plain) local matcher = cache[regex] or matcherGenerator(regex, plain) return matcher:process(str, init) end -- string.match local function utf8match(str, regex, init) init = init or 1 local found = {utf8find(str, regex, init)} if found[1] then if found[3] then return unpack(found, 3) end return utf8sub(str, found[1], found[2]) end end -- string.gmatch local function utf8gmatch(str, regex, all) regex = (utf8sub(regex,1,1) ~= '^') and regex or '%' .. regex local lastChar = 1 return function() local found = {utf8find(str, regex, lastChar)} if found[1] then lastChar = found[2] + 1 if found[all and 1 or 3] then return unpack(found, all and 1 or 3) end return utf8sub(str, found[1], found[2]) end end end local function replace(repl, args) local ret = '' if type(repl) == 'string' then local ignore = false local num for c in utf8gensub(repl) do if not ignore then if c == '%' then ignore = true else ret = ret .. c end else num = tonumber(c) if num then ret = ret .. args[num] else ret = ret .. c end ignore = false end end elseif type(repl) == 'table' then ret = repl[args[1] or args[0]] or '' elseif type(repl) == 'function' then if #args > 0 then ret = repl(unpack(args, 1)) or '' else ret = repl(args[0]) or '' end end return ret end -- string.gsub local function utf8gsub(str, regex, repl, limit) limit = limit or -1 local ret = '' local prevEnd = 1 local it = utf8gmatch(str, regex, true) local found = {it()} local n = 0 while #found > 0 and limit ~= n do local args = {[0] = utf8sub(str, found[1], found[2]), unpack(found, 3)} ret = ret .. utf8sub(str, prevEnd, found[1] - 1) .. replace(repl, args) prevEnd = found[2] + 1 n = n + 1 found = {it()} end return ret .. utf8sub(str, prevEnd), n end local utf8 = {} utf8.len = utf8len utf8.sub = utf8sub utf8.reverse = utf8reverse utf8.char = utf8char utf8.unicode = utf8unicode utf8.gensub = utf8gensub utf8.byte = utf8unicode utf8.find = utf8find utf8.match = utf8match utf8.gmatch = utf8gmatch utf8.gsub = utf8gsub utf8.dump = dump utf8.format = format utf8.lower = lower utf8.upper = upper utf8.rep = rep return utf8
lgpl-2.1
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Tasks/ParaWorld/ParaWorldSchools.lua
1
3568
--[[ Title: paraworld list Author(s): chenjinxian Date: 2020/9/8 Desc: use the lib: ------------------------------------------------------------ local ParaWorldSchools = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/ParaWorld/ParaWorldSchools.lua"); ParaWorldSchools.ShowPage(); ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/keepwork.rawfile.lua"); local ParaWorldSchools = NPL.export(); ParaWorldSchools.Templates = {}; ParaWorldSchools.CurrentIndex = 1; local result = nil; local page; function ParaWorldSchools.OnInit() page = document:GetPageCtrl(); end function ParaWorldSchools.ShowPage(onClose, delay) commonlib.TimerManager.SetTimeout(function() result = nil; local params = { url = "script/apps/Aries/Creator/Game/Tasks/ParaWorld/ParaWorldSchools.html", name = "ParaWorldSchools.ShowPage", isShowTitleBar = false, DestroyOnClose = true, style = CommonCtrl.WindowFrame.ContainerStyle, allowDrag = true, enable_esc_key = true, app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key, directPosition = true, align = "_ct", x = -720 / 2, y = -420 / 2, width = 720, height = 420, }; System.App.Commands.Call("File.MCMLWindowFrame", params); params._page.OnClose = function() if (onClose) then onClose(result); end end -- https://keepwork.com/official/paracraft/config/paraworldTemplate keepwork.rawfile.get({ cache_policy = "access plus 0", router_params = { repoPath = "official%%2Fparacraft", filePath = "official%%2Fparacraft%%2Fconfig%%2FparaworldTemplate.md", } }, function(err, msg, data) local templates = commonlib.LoadTableFromString(data); if (templates) then ParaWorldSchools.Templates = templates; ParaWorldSchools.CurrentIndex = 1; page:Refresh(0); end end); end, delay or 2000); end function ParaWorldSchools.OnClose() page:CloseWindow(); end function ParaWorldSchools.OnOK() if (#ParaWorldSchools.Templates >= ParaWorldSchools.CurrentIndex) then local template = ParaWorldSchools.Templates[ParaWorldSchools.CurrentIndex]; local info = string.format(L"即将使用【%s】替换当前世界", template.name); _guihelper.MessageBox(info, function(res) if(res and res == _guihelper.DialogResult.OK) then result = template.projectId; page:CloseWindow(); end end, _guihelper.MessageBoxButtons.OKCancel); end end function ParaWorldSchools.GetCurrentImage() if (#ParaWorldSchools.Templates >= ParaWorldSchools.CurrentIndex) then return ParaWorldSchools.Templates[ParaWorldSchools.CurrentIndex].img; else return "Texture/Aries/Creator/keepwork/ParaWorld/zuopkuang_266X134_32bits.png#0 0 32 32:8 8 8 8"; end end function ParaWorldSchools.GetCurrentName() if (#ParaWorldSchools.Templates >= ParaWorldSchools.CurrentIndex) then local name = ParaWorldSchools.Templates[ParaWorldSchools.CurrentIndex].name; return string.format("%s(%d/%d)", name, ParaWorldSchools.CurrentIndex, #ParaWorldSchools.Templates); end end function ParaWorldSchools.ShowPrevious() if (ParaWorldSchools.CurrentIndex > 1) then ParaWorldSchools.CurrentIndex = ParaWorldSchools.CurrentIndex - 1; else ParaWorldSchools.CurrentIndex = #ParaWorldSchools.Templates; end page:Refresh(0); end function ParaWorldSchools.ShowNext() if (ParaWorldSchools.CurrentIndex < #ParaWorldSchools.Templates) then ParaWorldSchools.CurrentIndex = ParaWorldSchools.CurrentIndex + 1; else ParaWorldSchools.CurrentIndex = 1; end page:Refresh(0); end
gpl-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Items/ItemSign.lua
1
2243
--[[ Title: ItemSign Author(s): LiXizhi Date: 2015/6/18 Desc: use the lib: ------------------------------------------------------------ NPL.load("(gl)script/apps/Aries/Creator/Game/Items/ItemSign.lua"); local ItemSign = commonlib.gettable("MyCompany.Aries.Game.Items.ItemSign"); local item = ItemSign:new({icon,}); ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Creator/Game/Common/Files.lua"); local Files = commonlib.gettable("MyCompany.Aries.Game.Common.Files"); local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager"); local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine") local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types") local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic") local ItemStack = commonlib.gettable("MyCompany.Aries.Game.Items.ItemStack"); local ItemSign = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Items.Item"), commonlib.gettable("MyCompany.Aries.Game.Items.ItemSign")); block_types.RegisterItemClass("ItemSign", ItemSign); function ItemSign:PickItemFromPosition(x,y,z) local entity = self:GetBlock():GetBlockEntity(x,y,z); if(entity) then if(entity.cmd and entity.cmd~="") then local itemStack = ItemStack:new():Init(self.id, 1); -- transfer filename from entity to item stack. itemStack:SetTooltip(entity.cmd); return itemStack; end end return ItemSign._super.PickItemFromPosition(self, x,y,z); end -- return true if items are the same. -- @param left, right: type of ItemStack or nil. function ItemSign:CompareItems(left, right) if(ItemSign._super.CompareItems(self, left, right)) then if(left and right and left:GetTooltip() == right:GetTooltip()) then return true; end end end function ItemSign:TryCreate(itemStack, entityPlayer, x,y,z, side, data, side_region) local text = itemStack:GetDataField("tooltip"); local res = ItemSign._super.TryCreate(self, itemStack, entityPlayer, x,y,z, side, data, side_region); if(res and text and text~="") then local entity = self:GetBlock():GetBlockEntity(x,y,z); if(entity and entity:GetBlockId() == self.id) then entity.cmd = text; entity:Refresh(); end end return res; end
gpl-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Movie/ActorLight.lua
1
18950
--[[ Title: Actor Light Author(s): LiXizhi Date: 2020/5/11 Desc: actor light object use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/ActorLight.lua"); local ActorLight = commonlib.gettable("MyCompany.Aries.Game.Movie.ActorLight"); ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/Actor.lua"); NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CmdParser.lua"); NPL.load("(gl)script/apps/Aries/Creator/Game/Items/ItemStack.lua"); NPL.load("(gl)script/apps/Aries/Creator/Game/Common/Files.lua"); NPL.load("(gl)script/apps/Aries/Creator/Game/Entity/EntityLightChar.lua"); local EntityLightChar = commonlib.gettable("MyCompany.Aries.Game.EntityManager.EntityLightChar") local Color = commonlib.gettable("System.Core.Color"); local Files = commonlib.gettable("MyCompany.Aries.Game.Common.Files"); local ItemStack = commonlib.gettable("MyCompany.Aries.Game.Items.ItemStack"); local CmdParser = commonlib.gettable("MyCompany.Aries.Game.CmdParser"); local MultiAnimBlock = commonlib.gettable("MyCompany.Aries.Game.Common.MultiAnimBlock"); local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine") local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types") local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic") local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager"); local Actor = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Movie.Actor"), commonlib.gettable("MyCompany.Aries.Game.Movie.ActorLight")); Actor.class_name = "ActorLight"; Actor:Property({"enablePicking", true, "IsPickingEnabled", "EnablePicking", auto=true}) -- keyframes that can be edited from UI keyframe. local selectable_var_list = { "pos", -- multiple of x,y,z "rot", -- multiple of "roll", "pitch", "facing" "---", -- separator "LightType", "Diffuse", "Specular", "Ambient", "Range", "Falloff", "Attenuation0", "Attenuation1", "Attenuation2", "Theta", "Phi", "---", -- separator "parent", }; function Actor:ctor() end function Actor:DeleteThisActor() self:OnRemove(); self:Destroy(); end function Actor:GetMultiVariable() local var = self:GetCustomVariable("multi_variable"); if(var) then return var; else var = MultiAnimBlock:new(); var:AddVariable(self:GetVariable("x")); var:AddVariable(self:GetVariable("y")); var:AddVariable(self:GetVariable("z")); var:AddVariable(self:GetVariable("facing")); -- facing is yaw, actually var:AddVariable(self:GetVariable("pitch")); var:AddVariable(self:GetVariable("roll")); var:AddVariable(self:GetVariable("Range")); self:SetCustomVariable("multi_variable", var); return var; end end -- get position multi variable function Actor:GetPosVariable() local var = self:GetCustomVariable("pos_variable"); if(var) then return var; else var = MultiAnimBlock:new({name="pos"}); var:AddVariable(self:GetVariable("x")); var:AddVariable(self:GetVariable("y")); var:AddVariable(self:GetVariable("z")); self:SetCustomVariable("pos_variable", var); return var; end end -- get rotate multi variable function Actor:GetRotateVariable() local var = self:GetCustomVariable("rot_variable"); if(var) then return var; else var = MultiAnimBlock:new({name="rot"}); var:AddVariable(self:GetVariable("roll")); var:AddVariable(self:GetVariable("pitch")); var:AddVariable(self:GetVariable("facing")); self:SetCustomVariable("rot_variable", var); return var; end end function Actor:Init(itemStack, movieclipEntity) -- base class must be called last, so that child actors have created their own variables on itemStack. if(not Actor._super.Init(self, itemStack, movieclipEntity)) then return; end local timeseries = self.TimeSeries; timeseries:CreateVariableIfNotExist("x", "Linear"); timeseries:CreateVariableIfNotExist("y", "Linear"); timeseries:CreateVariableIfNotExist("z", "Linear"); timeseries:CreateVariableIfNotExist("facing", "LinearAngle"); timeseries:CreateVariableIfNotExist("pitch", "LinearAngle"); timeseries:CreateVariableIfNotExist("roll", "LinearAngle"); timeseries:CreateVariableIfNotExist("LightType", "Discrete"); timeseries:CreateVariableIfNotExist("Diffuse", "LinearTable"); timeseries:CreateVariableIfNotExist("Specular", "LinearTable"); timeseries:CreateVariableIfNotExist("Ambient", "LinearTable"); timeseries:CreateVariableIfNotExist("Range", "Linear"); timeseries:CreateVariableIfNotExist("Falloff", "Linear"); timeseries:CreateVariableIfNotExist("Attenuation0", "Linear"); timeseries:CreateVariableIfNotExist("Attenuation1", "Linear"); timeseries:CreateVariableIfNotExist("Attenuation2", "Linear"); timeseries:CreateVariableIfNotExist("Theta", "Linear"); timeseries:CreateVariableIfNotExist("Phi", "Linear"); timeseries:CreateVariableIfNotExist("parent", "LinearTable"); self:AddValue("position", self.GetPosVariable); -- get initial position from itemStack, if not exist, we will use movie clip entity's block position. local movieClip = self:GetMovieClip(); if(movieClip) then local x = self:GetValue("x", 0); local y = self:GetValue("y", 0); local z = self:GetValue("z", 0); if(not x or not y or not z) then x, y, z = movieClip:GetOrigin(); y = y + BlockEngine.blocksize; self:AddKey("x", 0, x); self:AddKey("y", 0, y); self:AddKey("z", 0, z); end self.entity = EntityLightChar:Create({x=x,y=y,z=z,}); if(self.entity) then self.entity:SetActor(self); self.entity:SetPersistent(false); self.entity:Attach(); end return self; end end -- return the parent link and parent actor if found. -- @return parent, curTime, parentActor, keypath: where parent contains local transform relative to target: -- in the form {target="fullname", pos={}, rot={}, use_rot=true} function Actor:GetParentLink(curTime) curTime = curTime or self:GetTime(); local parent = self:GetValue("parent", curTime); if(parent and type(parent) == "table" and parent.target and parent.target ~="")then -- animate linking to another actor's bone animation. local actorname, keypath = parent.target:match("^([^:]+):*(.*)"); if(actorname) then local parentActor = self:FindActor(actorname); if(parentActor and parentActor~=self) then return parent, curTime, parentActor, keypath; end end end end -- force adding current values to all transform variables, these include position and rotation. function Actor:KeyTransform() local curTime = self:GetTime(); local entity = self.entity; if(not entity or not curTime) then return end entity:UpdatePosition(); local x,y,z = entity:GetPosition(); self:BeginUpdate(); self:AutoAddKey("x", curTime, x); self:AutoAddKey("y", curTime, y); self:AutoAddKey("z", curTime, z); local obj = entity:GetInnerObject(); if(obj) then local yaw = obj:GetField("yaw", 0); self:AutoAddKey("facing", curTime, yaw); local roll = obj:GetField("roll", 0); self:AutoAddKey("roll", curTime, roll); local pitch = obj:GetField("pitch", 0); self:AutoAddKey("pitch", curTime, pitch); end self:EndUpdate(); end -- @return nil or a table of variable list. function Actor:GetEditableVariableList() return selectable_var_list; end -- @param selected_index: if nil, default to current index -- @return var function Actor:GetEditableVariable(selected_index) selected_index = selected_index or self:GetCurrentEditVariableIndex(); local name = selectable_var_list[selected_index]; local var; if(name == "pos") then var = self:GetPosVariable(); elseif(name == "rot") then var = self:GetRotateVariable(); else var = self.TimeSeries:GetVariable(name); end return var; end function Actor:CreateKeyFromUI(keyname, callbackFunc) local curTime = self:GetTime(); local h,m,s = commonlib.timehelp.SecondsToHMS(curTime/1000); local strTime = string.format("%.2d:%.2d", m,math.floor(s)); local old_value = self:GetValue(keyname, curTime); if(keyname == "Range") then old_value = old_value or self.entity:GetField(keyname) local title = format(L"起始时间%s, 请输入光源范围", strTime); -- TODO: use a dedicated UI NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/EnterTextDialog.lua"); local EnterTextDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.EnterTextDialog"); EnterTextDialog.ShowPage(title, function(result) result = tonumber(result); if(result) then self:AddKeyFrameByName(keyname, nil, result); self:FrameMovePlaying(0); if(callbackFunc) then callbackFunc(true); end end end,old_value) elseif(keyname == "Falloff") then old_value = old_value or self.entity:GetField(keyname) local title = format(L"起始时间%s, 请输入衰减值", strTime); -- TODO: use a dedicated UI NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/EnterTextDialog.lua"); local EnterTextDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.EnterTextDialog"); EnterTextDialog.ShowPage(title, function(result) result = tonumber(result); if(result) then self:AddKeyFrameByName(keyname, nil, result); self:FrameMovePlaying(0); if(callbackFunc) then callbackFunc(true); end end end,old_value) elseif(keyname == "Theta" or keyname == "Phi") then old_value = old_value or self.entity:GetField(keyname) local title = format(L"起始时间%s, 请输入%s角度", strTime, keyname); -- TODO: use a dedicated UI NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/EnterTextDialog.lua"); local EnterTextDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.EnterTextDialog"); EnterTextDialog.ShowPage(title, function(result) result = tonumber(result); if(result) then self:AddKeyFrameByName(keyname, nil, result); self:FrameMovePlaying(0); if(callbackFunc) then callbackFunc(true); end end end,old_value) elseif(keyname == "Attenuation0" or keyname == "Attenuation1" or keyname == "Attenuation2") then old_value = old_value or self.entity:GetField(keyname) local title = format(L"起始时间%s, 请输入 %s角度", strTime, keyname); -- TODO: use a dedicated UI NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/EnterTextDialog.lua"); local EnterTextDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.EnterTextDialog"); EnterTextDialog.ShowPage(title, function(result) result = tonumber(result); if(result) then self:AddKeyFrameByName(keyname, nil, result); self:FrameMovePlaying(0); if(callbackFunc) then callbackFunc(true); end end end,old_value) elseif(keyname == "LightType") then old_value = old_value or self.entity:GetField(keyname) local title = format(L"起始时间%s, 光源类型:", strTime); local options = { {value = 1, text= L"点光源"}, {value = 2, text= L"聚光灯"}, {value = 3, text= L"平行光"}, } NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/EnterTextDialog.lua"); local EnterTextDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.EnterTextDialog"); EnterTextDialog.ShowPage(title, function(result) if(result and result ~= "") then if( type(result) == "number") then local result = tonumber(result); if(result >= 1 and result <=3) then self:AddKeyFrameByName(keyname, nil, result); self:FrameMovePlaying(0); if(callbackFunc) then callbackFunc(true); end end end end end, old_value or 1, "select", options); elseif(keyname == "Diffuse" or keyname == "Specular" or keyname == "Ambient") then local title = format(L"起始时间%s, 请输入颜色RGB. 例如:#ffffff", strTime); old_value = old_value or self.entity:GetField(keyname) old_value = old_value and Color.RGBAfloat_TO_ColorStr(old_value[1],old_value[2],old_value[3]) NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/EnterTextDialog.lua"); local EnterTextDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.EnterTextDialog"); EnterTextDialog.ShowPage(title, function(result) if(result and result~="" and result:match("^#[%d%w]+$")) then local r, g, b = Color.ColorStr_TO_RGBAfloat(result); self:AddKeyFrameByName(keyname, nil, {r,g,b}); self:FrameMovePlaying(0); if(callbackFunc) then callbackFunc(true); end end end,old_value) elseif(keyname == "rot") then local title = format(L"起始时间%s, 请输入roll, pitch, yaw [-180, 180]<br/>", strTime); old_value = string.format("%f, %f, %f", (self:GetValue("roll", curTime) or 0) / math.pi * 180, (self:GetValue("pitch", curTime) or 0) / math.pi * 180, (self:GetValue("facing", curTime) or 0) / math.pi * 180); -- TODO: use a dedicated UI NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/EnterTextDialog.lua"); local EnterTextDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.EnterTextDialog"); EnterTextDialog.ShowPage(title, function(result) if(result and result~="") then local vars = CmdParser.ParseNumberList(result, nil, "|,%s"); if(result and vars[1] and vars[2] and vars[3]) then self:BeginUpdate(); self:AddKeyFrameByName("roll", nil, vars[1] / 180 * math.pi); self:AddKeyFrameByName("pitch", nil, vars[2] / 180 * math.pi); self:AddKeyFrameByName("facing", nil, vars[3] / 180 * math.pi); self:EndUpdate(); self:FrameMovePlaying(0); if(callbackFunc) then callbackFunc(true); end end end end,old_value) elseif(keyname == "pos") then local title = format(L"起始时间%s, 请输入位置x,y,z:", strTime); local bx, by, bz = self:GetValue("x", curTime),self:GetValue("y", curTime), self:GetValue("z", curTime); if(not bx or not by or not bz) then local entity = self:GetEntity() or EntityManager.GetPlayer(); bx, by, bz = entity:GetPosition(); end bx, by, bz = BlockEngine:block_float(bx, by, bz) bx = bx - 0.5; bz = bz - 0.5; old_value = string.format("%f, %f, %f", bx, by, bz); -- TODO: use a dedicated UI NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/EnterTextDialog.lua"); local EnterTextDialog = commonlib.gettable("MyCompany.Aries.Game.GUI.EnterTextDialog"); EnterTextDialog.ShowPage(title, function(result) if(result and result~="") then local vars = CmdParser.ParseNumberList(result, nil, "|,%s"); if(result and vars[1] and vars[2] and vars[3]) then local x, y, z = BlockEngine:real_bottom(vars[1], vars[2], vars[3]) self:BeginUpdate(); self:AddKeyFrameByName("x", nil, x); self:AddKeyFrameByName("y", nil, y); self:AddKeyFrameByName("z", nil, z); self:EndUpdate(); self:FrameMovePlaying(0); if(callbackFunc) then callbackFunc(true); end end end end, old_value) elseif(keyname == "parent") then NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/EditParentLinkPage.lua"); local EditParentLinkPage = commonlib.gettable("MyCompany.Aries.Game.Movie.EditParentLinkPage"); EditParentLinkPage.ShowPage(strTime, self, function(values) if(values.target=="") then -- this will automatically add a key frame, when link is removed. self:KeyTransform(); end self:AddKeyFrameByName(keyname, nil, values); self:FrameMovePlaying(0); if(target~="") then -- this will automatically add a key frame at the position. self:KeyTransform(); end if(callbackFunc) then callbackFunc(true); end end, old_value); end end function Actor:FrameMoveRecording(deltaTime) local curTime = self:GetTime(); local entity = self.entity; if(not entity or not curTime) then return end entity:UpdatePosition(); local x,y,z = entity:GetPosition(); self:BeginUpdate(); self:AutoAddKey("x", curTime, x); self:AutoAddKey("y", curTime, y); self:AutoAddKey("z", curTime, z); self:EndUpdate(); end function Actor:FrameMovePlaying(deltaTime) local curTime = self:GetTime(); local entity = self.entity; if(not entity or not curTime) then return end local new_x, new_y, new_z, yaw, roll, pitch = self:ComputePosAndRotation(curTime); if(new_x) then entity:SetPosition(new_x, new_y, new_z); else local movieClip = self:GetMovieClip(); if(movieClip) then new_x, new_y, new_z = movieClip:GetOrigin(); new_y = new_y + BlockEngine.blocksize; entity:SetPosition(new_x, new_y, new_z); end end local LightType = self:GetValue("LightType", curTime) if(LightType) then entity:SetLightType(LightType); end local Diffuse = self:GetValue("Diffuse", curTime) if(Diffuse) then entity:SetDiffuse(Diffuse); end local Ambient = self:GetValue("Ambient", curTime) if(Ambient) then entity:SetAmbient(Ambient); end local Specular = self:GetValue("Specular", curTime) if(Specular) then entity:SetSpecular(Specular); end local Range = self:GetValue("Range", curTime) if(Range) then entity:SetRange(Range); end local Falloff = self:GetValue("Falloff", curTime) if(Falloff) then entity:SetFalloff(Falloff); end local Attenuation0 = self:GetValue("Attenuation0", curTime) if(Attenuation0) then entity:SetAttenuation0(Attenuation0); end local Attenuation1 = self:GetValue("Attenuation1", curTime) if(Attenuation1) then entity:SetAttenuation1(Attenuation1); end local Attenuation2 = self:GetValue("Attenuation2", curTime) if(Attenuation2) then entity:SetAttenuation2(Attenuation2); end local Theta = self:GetValue("Theta", curTime) if(Theta) then entity:SetTheta(Theta); end local Phi = self:GetValue("Phi", curTime) if(Phi) then entity:SetPhi(Phi); end entity:SetFacing(yaw or 0); entity:SetPitch(pitch or 0); entity:SetRoll(roll or 0); end function Actor:ComputePosAndRotation(curTime) local new_x = self:GetValue("x", curTime); local new_y = self:GetValue("y", curTime); local new_z = self:GetValue("z", curTime); local yaw = self:GetValue("facing", curTime); local roll = self:GetValue("roll", curTime); local pitch = self:GetValue("pitch", curTime); -- animate linking to another actor's bone animation. local parent, _, parentActor, keypath = self:GetParentLink(curTime); if(keypath and parentActor and parentActor.ComputeWorldTransform)then local p_x, p_y, p_z, p_roll, p_pitch, p_yaw, p_scale = parentActor:ComputeWorldTransform(keypath, curTime, parent.pos, parent.rot, parent.use_rot); if(p_x) then new_x, new_y, new_z = p_x, p_y, p_z; if(p_roll) then roll, pitch, yaw = p_roll, p_pitch, p_yaw; end if(p_scale) then -- scale = p_scale * (scale or 1); end else if(self.last_unknown_keypath~=keypath and keypath and keypath~="") then -- here we just wait 500 and try again only once for a given bone keypath. self.last_unknown_keypath = keypath; self.loader_timer = self.loader_timer or commonlib.Timer:new({callbackFunc = function(timer) self:FrameMovePlaying(0); end}) LOG.std(nil, "info", "ActorLight", "parent bone may be async loading, wait 500ms"); self.loader_timer:Change(500, nil); end end end return new_x, new_y, new_z, yaw, roll, pitch; end
gpl-2.0
knixeur/notion
etc/cfg_notion.lua
2
5459
-- -- Notion main configuration file -- -- This file only includes some settings that are rather frequently altered. -- The rest of the settings are in cfg_notioncore.lua and individual modules' -- configuration files (cfg_modulename.lua). -- -- When any binding and other customisations that you want are minor, it is -- recommended that you include them in a copy of this file in ~/.notion/. -- -- Set default modifiers. The default is the 'windows' key; it is usually mapped -- to Mod4 on Xorg-based systems. Any other modifier, such as Alt, can be used -- instead. The 'xmodmap' tool can be used to get/set which key codes correspond -- to which modifiers, and the 'xev' tool can be used to see what codes are -- generated by particular keys. --META="Mod4+" --ALTMETA="Mod4+Shift+" -- Terminal emulator. --XTERM="xterm" -- Edit file command, mod_query.query_editfile --EDIT_COMMAND="run-mailcap --action=edit" -- View file command, mod_query.query_viewfile --VIEW_COMMAND="xdg-open" -- Some basic settings. ioncore.set{ -- Maximum delay between clicks in milliseconds to be considered a -- double click. --dblclick_delay=250, -- For keyboard resize, time (in milliseconds) to wait after latest -- key press before automatically leaving resize mode (and doing -- the resize in case of non-opaque move). --kbresize_delay=1500, -- Opaque resize? --opaque_resize=false, -- Movement commands warp the pointer to frames instead of just -- changing focus. Enabled by default. --warp=true, -- Margin to use when warping the cursor (in pixels), -- to inset from the edge of the frame. --warp_margin=5, -- Placement to use when positioning the cursor in the frame -- (as a factor from 0-1). -- Where an x,y value: -- * (0.0, 0.0) for top-left. -- * (1.0, 1.0) for bottom-right. -- * (0.5, 0.5) for the center of the frame. --warp_factor_x=0.0, --warp_factor_y=0.0, -- Should a managing MPlex switch to a newly mapped client window? --switchto=true, -- Should notification tooltips be displayed for hidden workspaces with -- activity? --screen_notify=true, -- Specifies where to add new regions on the mutually exclusive list of a -- frame. One of ''last'', ''next'' (for after current), ''next-act'' -- (for after current and anything with activity right after it). --frame_default_index="next", -- Put transients in nested frames. --framed_transients=true, -- Float window placement method: -- one of 'udlr' (up down left right), 'lrud' (left right up down), 'pointer' or 'random'. --float_placement_method="udlr", -- Auto-unsqueeze transients/menus/queries/etc. --unsqueeze=true, -- Float non-transient dialog type windows. -- Can be useful for applications that try to place their own dialog windows. --window_dialog_float=true, -- Autoraise regions in groups on goto. \\ --autoraise=true, -- Automatically save layout on restart and exit. --autosave_layout=true, -- Mouse focus mode; set to "sloppy" if you want the focus to follow the -- mouse, and to "disabled" otherwise. --mousefocus="sloppy", -- Controls Notion's reaction to stacking requests sent by clients. Set to -- "ignore" to ignore these requests, and to "activate" to set the activity -- flag on a window that requests to be stacked "Above". --window_stacking_request="ignore", -- Time (in ms) that a window has to be focussed in order to be added to the -- focus list. Set this to <=0 (or comment it out) to disable the logic, and -- update the focus list immediately. --focuslist_insert_delay=1000, -- If enabled, activity notifiers are displayed on ALL the screens, not just -- the screen that contains the window producing the notification. This is -- only relevant on multi-head setups. By default this is disabled. --activity_notification_on_all_screens=false, -- If enabled, a workspace indicator comes up at the bottom-left of the -- screen when a new workspace is selected. This indicator stays active for -- only as long as indicated by this variable (in ms). Timeout values <=0 -- disable the indicator altogether. This is disabled by default. --workspace_indicator_timeout=0, } -- Load default settings. The file cfg_defaults loads all the files -- commented out below, except mod_statusbar. If you do not want to load -- something, comment out this line, and uncomment the lines corresponding -- to the modules or configuration files that you want, below. -- Note that mod_dock and mod_statusbar are mutually exclusive. dopath("cfg_defaults") -- Load some kludges to make apps behave better. --dopath("cfg_kludges") -- Define some layouts. --dopath("cfg_layouts") -- Load some modules. --dopath("mod_query") --dopath("mod_menu") --dopath("mod_tiling") --dopath("mod_statusbar") --dopath("mod_dock") --dopath("mod_sp") --dopath("mod_notionflux") --dopath("mod_xrandr") --dopath("net_client_list") -- -- loads cfg_bindings --dopath("cfg_notioncore") -- -- Common customisations -- -- Uncommenting the following lines should get you plain-old-menus instead -- of query-menus. --defbindings("WScreen", { -- kpress(ALTMETA.."F12", "mod_menu.menu(_, _sub, 'mainmenu', {big=true})"), --}) -- --defbindings("WMPlex.toplevel", { -- kpress(META.."M", "mod_menu.menu(_, _sub, 'ctxmenu')"), --})
lgpl-2.1
lyzardiar/seal2d
luasrc/seal/event.lua
1
2083
local sdl_enum = require "seal.sdl_enum" local event = {} local MOUSE_EVENTS = {} local touch_event = {} function touch_event.new(type, x, y, dx, dy) local obj = { type = type, x = x, y = y, dx = dx, dy = dy, captered = {}, current_target = nil, stop = false } setmetatable(obj, {__index = touch_event} ) return obj end function touch_event:add_captured(sprite) self.captered[#self.captered+1] = sprite end function touch_event:stop_bubble() self.stop = true end local tmp_event local function on_touch(type, x, y, dx, dy, root) if type == 'begin' then tmp_event = touch_event.new(type, x, WINDOW_HEIGHT - y, dx, dy) root:touch_test(tmp_event) return end if tmp_event then tmp_event.type = type root:touch_test(tmp_event) if type == 'end' then tmp_event = nil end end end MOUSE_EVENTS[sdl_enum.SDL_MOUSEBUTTONDOWN] = function(e, ...) on_touch('begin', e.x, e.y, 0, 0, ...) end MOUSE_EVENTS[sdl_enum.SDL_MOUSEMOTION] = function(e, ...) on_touch('move', e.x, e.y, e.xrel, e.yrel, ...) end MOUSE_EVENTS[sdl_enum.SDL_MOUSEBUTTONUP] = function(e, ...) on_touch('end', e.x, e.y, 0, 0, ...) end MOUSE_EVENTS[sdl_enum.SDL_MOUSEWHEEL] = function(e, ...) end MOUSE_EVENTS[sdl_enum.SDL_FINGERDOWN] = function(e, ...) -- on_touch('begin' e.x, e.y, e.dx, e.dy, ...) end MOUSE_EVENTS[sdl_enum.SDL_FINGERMOTION] = function(e, ...) -- on_touch(e.x, e.y, e.dx, e.dy, ...) end MOUSE_EVENTS[sdl_enum.SDL_FINGERUP] = function(e, ...) -- on_touch(e.x, e.y, e.dx, e.dy, ...) end MOUSE_EVENTS[sdl_enum.SDL_DOLLARGESTURE] = function(e, ...) print_r(e) end MOUSE_EVENTS[sdl_enum.SDL_DOLLARRECORD] = function(e, ...) print_r(e) end MOUSE_EVENTS[sdl_enum.SDL_MULTIGESTURE] = function(e, ...) print_r(e) end function event.mouse(e, root) local f = MOUSE_EVENTS[e.type] if not f then print('no event for ', e.type) else f(e, root) end end return event
mit
Ferk/Dungeontest
mods/default/mapgen.lua
1
18580
-- -- Aliases for map generator outputs -- minetest.register_alias("mapgen_stone", "default:stone") minetest.register_alias("mapgen_dirt", "default:dirt") minetest.register_alias("mapgen_dirt_with_grass", "default:dirt_with_grass") minetest.register_alias("mapgen_sand", "default:sand") minetest.register_alias("mapgen_water_source", "default:water_source") minetest.register_alias("mapgen_river_water_source", "default:river_water_source") minetest.register_alias("mapgen_lava_source", "default:lava_source") minetest.register_alias("mapgen_gravel", "default:gravel") minetest.register_alias("mapgen_desert_stone", "default:desert_stone") minetest.register_alias("mapgen_desert_sand", "default:desert_sand") minetest.register_alias("mapgen_dirt_with_snow", "default:dirt_with_snow") minetest.register_alias("mapgen_snowblock", "default:snowblock") minetest.register_alias("mapgen_snow", "default:snow") minetest.register_alias("mapgen_ice", "default:ice") minetest.register_alias("mapgen_sandstone", "default:sandstone") -- Flora minetest.register_alias("mapgen_tree", "default:tree") minetest.register_alias("mapgen_leaves", "default:leaves") minetest.register_alias("mapgen_apple", "default:apple") minetest.register_alias("mapgen_jungletree", "default:jungletree") minetest.register_alias("mapgen_jungleleaves", "default:jungleleaves") minetest.register_alias("mapgen_junglegrass", "default:junglegrass") minetest.register_alias("mapgen_pine_tree", "default:pine_tree") minetest.register_alias("mapgen_pine_needles", "default:pine_needles") -- Dungeons minetest.register_alias("mapgen_cobble", "default:cobble") minetest.register_alias("mapgen_stair_cobble", "stairs:stair_cobble") minetest.register_alias("mapgen_mossycobble", "default:mossycobble") minetest.register_alias("mapgen_sandstonebrick", "default:sandstonebrick") minetest.register_alias("mapgen_stair_sandstonebrick", "stairs:stair_sandstonebrick") -- -- Register biomes -- -- All mapgens except mgv6 and singlenode function default.register_biomes() minetest.clear_registered_biomes() -- Permanent ice minetest.register_biome({ name = "glacier", node_dust = "default:snowblock", node_top = "default:snowblock", depth_top = 1, node_filler = "default:snowblock", depth_filler = 3, node_stone = "default:ice", node_water_top = "default:ice", depth_water_top = 10, --node_water = "", y_min = -8, y_max = 31000, heat_point = -5, humidity_point = 50, }) minetest.register_biome({ name = "glacier_ocean", node_dust = "default:snowblock", node_top = "default:gravel", depth_top = 1, node_filler = "default:gravel", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -9, y_max = -9, heat_point = -5, humidity_point = 50, }) -- Cold minetest.register_biome({ name = "tundra", node_dust = "default:snow", node_top = "default:dirt_with_snow", depth_top = 1, node_filler = "default:dirt", depth_filler = 0, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 2, y_max = 31000, heat_point = 20, humidity_point = 30, }) minetest.register_biome({ name = "tundra_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -9, y_max = 1, heat_point = 20, humidity_point = 30, }) minetest.register_biome({ name = "taiga", node_dust = "default:snow", node_top = "default:snowblock", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 2, y_max = 31000, heat_point = 20, humidity_point = 70, }) minetest.register_biome({ name = "taiga_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -112, y_max = 1, heat_point = 20, humidity_point = 70, }) -- Cool minetest.register_biome({ name = "stone_grassland", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 0, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 6, y_max = 31000, heat_point = 45, humidity_point = 30, }) minetest.register_biome({ name = "stone_grassland_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -9, y_max = 5, heat_point = 45, humidity_point = 30, }) minetest.register_biome({ name = "coniferous_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 6, y_max = 31000, heat_point = 45, humidity_point = 70, }) minetest.register_biome({ name = "coniferous_forest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -9, y_max = 5, heat_point = 45, humidity_point = 70, }) -- Warm minetest.register_biome({ name = "sandstone_grassland", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 0, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 6, y_max = 31000, heat_point = 70, humidity_point = 30, }) minetest.register_biome({ name = "sandstone_grassland_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -9, y_max = 5, heat_point = 70, humidity_point = 30, }) minetest.register_biome({ name = "deciduous_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 6, y_max = 31000, heat_point = 70, humidity_point = 70, }) minetest.register_biome({ name = "deciduous_forest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -9, y_max = 5, heat_point = 70, humidity_point = 70, }) -- Hot minetest.register_biome({ name = "desert", --node_dust = "", node_top = "default:desert_sand", depth_top = 1, node_filler = "default:desert_sand", depth_filler = 1, node_stone = "default:desert_stone", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 1, y_max = 31000, heat_point = 95, humidity_point = 10, }) minetest.register_biome({ name = "desert_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, node_stone = "default:desert_stone", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -9, y_max = 0, heat_point = 95, humidity_point = 10, }) minetest.register_biome({ name = "savanna", --node_dust = "", node_top = "default:dirt_with_dry_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 1, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 5, y_max = 31000, heat_point = 95, humidity_point = 50, }) minetest.register_biome({ name = "savanna_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -9, y_max = 4, heat_point = 95, humidity_point = 50, }) minetest.register_biome({ name = "rainforest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 1, y_max = 31000, heat_point = 95, humidity_point = 90, }) minetest.register_biome({ name = "rainforest_swamp", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = 0, y_max = 0, heat_point = 95, humidity_point = 90, }) minetest.register_biome({ name = "rainforest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", y_min = -9, y_max = -1, heat_point = 95, humidity_point = 90, }) end -- -- Register decorations -- -- Mgv6 function default.register_mgv6_decorations() minetest.clear_registered_decorations() -- Papyrus minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass"}, sidelen = 8, noise_params = { offset = -0.3, scale = 0.7, spread = {x = 100, y = 100, z = 100}, seed = 354, octaves = 3, persist = 0.7 }, y_min = 1, y_max = 1, decoration = "default:papyrus", height = 2, height_max = 4, spawn_by = "default:water_source", num_spawn_by = 1, }) -- Cacti minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand"}, sidelen = 16, noise_params = { offset = -0.012, scale = 0.024, spread = {x = 100, y = 100, z = 100}, seed = 230, octaves = 3, persist = 0.6 }, y_min = 1, y_max = 30, decoration = "default:cactus", height = 3, height_max = 4, }) -- Long grasses for length = 1, 5 do minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0, scale = 0.007, spread = {x = 100, y = 100, z = 100}, seed = 329, octaves = 3, persist = 0.6 }, y_min = 1, y_max = 30, decoration = "default:grass_"..length, }) end -- Dry shrubs minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand", "default:dirt_with_snow"}, sidelen = 16, noise_params = { offset = 0, scale = 0.035, spread = {x = 100, y = 100, z = 100}, seed = 329, octaves = 3, persist = 0.6 }, y_min = 1, y_max = 30, decoration = "default:dry_shrub", }) end -- All mapgens except mgv6 and singlenode local function register_grass_decoration(offset, scale, length) minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass", "default:sand"}, sidelen = 16, noise_params = { offset = offset, scale = scale, spread = {x=200, y=200, z=200}, seed = 329, octaves = 3, persist = 0.6 }, biomes = { "stone_grassland", "stone_grassland_ocean", "sandstone_grassland", "sandstone_grassland_ocean", "deciduous_forest", "deciduous_forest_ocean", "coniferous_forest", "coniferous_forest_ocean", }, y_min = 5, y_max = 31000, decoration = "default:grass_"..length, }) end local function register_dry_grass_decoration(offset, scale, length) minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_dry_grass"}, sidelen = 16, noise_params = { offset = offset, scale = scale, spread = {x=200, y=200, z=200}, seed = 329, octaves = 3, persist = 0.6 }, biomes = {"savanna"}, y_min = 5, y_max = 31000, decoration = "default:dry_grass_"..length, }) end function default.register_decorations() minetest.clear_registered_decorations() -- Apple tree minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.04, scale = 0.02, spread = {x=250, y=250, z=250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"deciduous_forest"}, y_min = 6, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/apple_tree.mts", flags = "place_center_x, place_center_z", }) -- Jungle tree minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass", "default:dirt"}, sidelen = 80, fill_ratio = 0.09, biomes = {"rainforest", "rainforest_swamp"}, y_min = 0, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/jungle_tree.mts", flags = "place_center_x, place_center_z", }) -- Taiga and temperate forest pine tree minetest.register_decoration({ deco_type = "schematic", place_on = {"default:snowblock", "default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.04, scale = 0.02, spread = {x=250, y=250, z=250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"taiga", "coniferous_forest"}, y_min = 2, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/pine_tree.mts", flags = "place_center_x, place_center_z", }) -- Acacia tree minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_dry_grass"}, sidelen = 80, noise_params = { offset = 0, scale = 0.003, spread = {x=250, y=250, z=250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"savanna"}, y_min = 6, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/acacia_tree.mts", flags = "place_center_x, place_center_z", rotation = "random", }) -- Large cactus minetest.register_decoration({ deco_type = "schematic", place_on = {"default:desert_sand"}, sidelen = 80, noise_params = { offset = -0.0005, scale = 0.0015, spread = {x=200, y=200, z=200}, seed = 230, octaves = 3, persist = 0.6 }, biomes = {"desert"}, y_min = 2, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/large_cactus.mts", flags = "place_center_x", rotation = "random", }) -- Cactus minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand"}, sidelen = 80, noise_params = { offset = -0.0005, scale = 0.0015, spread = {x=200, y=200, z=200}, seed = 230, octaves = 3, persist = 0.6 }, biomes = {"desert"}, y_min = 2, y_max = 31000, decoration = "default:cactus", height = 2, height_max = 5, }) -- Papyrus minetest.register_decoration({ deco_type = "schematic", place_on = {"default:sand"}, sidelen = 16, noise_params = { offset = -0.3, scale = 0.7, spread = {x=200, y=200, z=200}, seed = 354, octaves = 3, persist = 0.7 }, biomes = {"savanna_ocean", "desert_ocean"}, y_min = 0, y_max = 0, schematic = minetest.get_modpath("default").."/schematics/papyrus.mts", }) -- Grasses register_grass_decoration(-0.03, 0.09, 5) register_grass_decoration(-0.015, 0.075, 4) register_grass_decoration(0, 0.06, 3) register_grass_decoration(0.015, 0.045, 2) register_grass_decoration(0.03, 0.03, 1) -- Dry grasses register_dry_grass_decoration(0.01, 0.05, 5) register_dry_grass_decoration(0.03, 0.03, 4) register_dry_grass_decoration(0.05, 0.01, 3) register_dry_grass_decoration(0.07, -0.01, 2) register_dry_grass_decoration(0.09, -0.03, 1) -- Junglegrass minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass"}, sidelen = 80, fill_ratio = 0.1, biomes = {"rainforest"}, y_min = 1, y_max = 31000, decoration = "default:junglegrass", }) -- Dry shrub minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand", "default:dirt_with_snow"}, sidelen = 16, noise_params = { offset = 0, scale = 0.02, spread = {x=200, y=200, z=200}, seed = 329, octaves = 3, persist = 0.6 }, biomes = {"desert", "tundra"}, y_min = 2, y_max = 31000, decoration = "default:dry_shrub", }) end -- -- Generate nyan cats -- -- All mapgens except singlenode function default.make_nyancat(pos, facedir, length) local tailvec = {x = 0, y = 0, z = 0} if facedir == 0 then tailvec.z = 1 elseif facedir == 1 then tailvec.x = 1 elseif facedir == 2 then tailvec.z = -1 elseif facedir == 3 then tailvec.x = -1 else facedir = 0 tailvec.z = 1 end local p = {x = pos.x, y = pos.y, z = pos.z} minetest.set_node(p, {name = "default:nyancat", param2 = facedir}) for i = 1, length do p.x = p.x + tailvec.x p.z = p.z + tailvec.z minetest.set_node(p, {name = "default:nyancat_rainbow", param2 = facedir}) end end function default.generate_nyancats(minp, maxp, seed) local height_min = -31000 local height_max = -32 if maxp.y < height_min or minp.y > height_max then return end local y_min = math.max(minp.y, height_min) local y_max = math.min(maxp.y, height_max) local volume = (maxp.x - minp.x + 1) * (y_max - y_min + 1) * (maxp.z - minp.z + 1) local pr = PseudoRandom(seed + 9324342) local max_num_nyancats = math.floor(volume / (16 * 16 * 16)) for i = 1, max_num_nyancats do if pr:next(0, 1000) == 0 then local x0 = pr:next(minp.x, maxp.x) local y0 = pr:next(minp.y, maxp.y) local z0 = pr:next(minp.z, maxp.z) local p0 = {x = x0, y = y0, z = z0} default.make_nyancat(p0, pr:next(0, 3), pr:next(3, 15)) end end end -- -- Detect mapgen to select functions -- -- Mods using singlenode mapgen can call these functions to enable -- the use of minetest.generate_ores or minetest.generate_decorations local mg_name = minetest.get_mapgen_setting("mg_name") if mg_name == "v6" then --default.register_ores() default.register_mgv6_decorations() --minetest.register_on_generated(default.generate_nyancats) elseif mg_name ~= "singlenode" then --default.register_ores() default.register_biomes() default.register_decorations() --minetest.register_on_generated(default.generate_nyancats) end
gpl-3.0
TerminalShell/zombiesurvival
gamemode/vgui/pworth.lua
1
11312
hook.Add("SetWave", "CloseWorthOnWave1", function(wave) if wave > 0 then if pWorth and pWorth:Valid() then pWorth:Close() end hook.Remove("SetWave", "CloseWorthOnWave1") end end) local cvarDefaultCart = CreateClientConVar("zs_defaultcart", "", true, false) local function DefaultDoClick(btn) if cvarDefaultCart:GetString() == btn.Name then RunConsoleCommand("zs_defaultcart", "") surface.PlaySound("buttons/button11.wav") else RunConsoleCommand("zs_defaultcart", btn.Name) surface.PlaySound("buttons/button14.wav") end timer.Simple(0.1, MakepWorth) end local WorthRemaining = 0 local WorthButtons = {} local function CartDoClick(self, silent, force) local id = self.ID local tab = FindStartingItem(id) if not tab then return end if self.On then self.On = nil self:SetImage("icon16/cart_add.png") if not silent then surface.PlaySound("buttons/button18.wav") end self:SetTooltip("Add to cart") WorthRemaining = WorthRemaining + tab.Worth else if WorthRemaining < tab.Worth and not force then surface.PlaySound("buttons/button8.wav") return end self.On = true self:SetImage("icon16/cart_delete.png") if not silent then surface.PlaySound("buttons/button17.wav") end self:SetTooltip("Remove from cart") WorthRemaining = WorthRemaining - tab.Worth end pWorth.WorthLab:SetText("Worth: ".. WorthRemaining) if WorthRemaining <= 0 then pWorth.WorthLab:SetTextColor(COLOR_RED) elseif WorthRemaining <= GAMEMODE.StartingWorth * 0.25 then pWorth.WorthLab:SetTextColor(COLOR_YELLOW) else pWorth.WorthLab:SetTextColor(COLOR_LIMEGREEN) end pWorth.WorthLab:SizeToContents() end local function Checkout(tobuy) if tobuy and #tobuy > 0 then gamemode.Call("SuppressArsenalUpgrades", 1) RunConsoleCommand("worthcheckout", unpack(tobuy)) if pWorth and pWorth:Valid() then pWorth:Close() end else surface.PlaySound("buttons/combine_button_locked.wav") end end local function CheckoutDoClick(self) local tobuy = {} for _, btn in pairs(WorthButtons) do if btn and btn.On and btn.ID then table.insert(tobuy, btn.ID) end end Checkout(tobuy) end local function RandDoClick(self) gamemode.Call("SuppressArsenalUpgrades", 1) RunConsoleCommand("worthrandom") if pWorth and pWorth:Valid() then pWorth:Close() end end GM.SavedCarts = {} hook.Add("Initialize", "LoadCarts", function() if file.Exists("FQD_ZS_carts.txt", "DATA") then GAMEMODE.SavedCarts = Deserialize(file.Read("FQD_ZS_carts.txt")) or {} end end) local function LoadCart(cartid, silent) if GAMEMODE.SavedCarts[cartid] then MakepWorth() for _, id in pairs(GAMEMODE.SavedCarts[cartid][2]) do for __, btn in pairs(WorthButtons) do if btn and (btn.ID == id or GAMEMODE.Items[id] and GAMEMODE.Items[id].Signature == btn.ID) then btn:DoClick(true, true) end end end if not silent then surface.PlaySound("buttons/combine_button1.wav") end end end local function LoadDoClick(self) LoadCart(self.ID) end local function SaveCurrentCart(name) local tobuy = {} for _, btn in pairs(WorthButtons) do if btn and btn.On and btn.ID then table.insert(tobuy, btn.ID) end end for i, cart in ipairs(GAMEMODE.SavedCarts) do if string.lower(cart[1]) == string.lower(name) then cart[1] = name cart[2] = tobuy file.Write("FQD_ZS_carts.txt", Serialize(GAMEMODE.SavedCarts)) print("Saved cart "..tostring(name)) LoadCart(i, true) return end end GAMEMODE.SavedCarts[#GAMEMODE.SavedCarts + 1] = {name, tobuy} file.Write("FQD_ZS_carts.txt", Serialize(GAMEMODE.SavedCarts)) print("Saved cart "..tostring(name)) LoadCart(#GAMEMODE.SavedCarts, true) end local function SaveDoClick(self) Derma_StringRequest("Save cart", "Enter a name for this cart.", "Name", function(strTextOut) SaveCurrentCart(strTextOut) end, function(strTextOut) end, "OK", "Cancel") end local function DeleteDoClick(self) if GAMEMODE.SavedCarts[self.ID] then table.remove(GAMEMODE.SavedCarts, self.ID) file.Write("FQD_ZS_carts.txt", Serialize(GAMEMODE.SavedCarts)) surface.PlaySound("buttons/button19.wav") MakepWorth() end end local function QuickCheckDoClick(self) if GAMEMODE.SavedCarts[self.ID] then Checkout(GAMEMODE.SavedCarts[self.ID][2]) end end function MakepWorth() if pWorth and pWorth:Valid() then pWorth:Remove() pWorth = nil end local maxworth = GAMEMODE.StartingWorth WorthRemaining = maxworth local wid, hei = 480, 480 local frame = vgui.Create("DFrame") pWorth = frame frame:SetSize(wid, hei) frame:SetDeleteOnClose(false) frame:SetKeyboardInputEnabled(false) frame:SetTitle("Choose your starting arsenal") local propertysheet = vgui.Create("DPropertySheet", frame) propertysheet:StretchToParent(4, 24, 4, 50) local list = vgui.Create("DPanelList", propertysheet) propertysheet:AddSheet("Favorites", list, "icon16/heart.png", false, false) list:EnableVerticalScrollbar(true) list:SetWide(propertysheet:GetWide() - 16) list:SetSpacing(2) list:SetPadding(2) local savebutton = EasyButton(nil, "Save the current cart", 0, 10) savebutton.DoClick = SaveDoClick list:AddItem(savebutton) local fontname local panhei if #GAMEMODE.SavedCarts >= 8 then panfont = "DefaultFontBold" panhei = 24 else panfont = "ZSHUDFontSmall" panhei = 40 end local defaultcart = cvarDefaultCart:GetString() for i, savetab in ipairs(GAMEMODE.SavedCarts) do local cartpan = vgui.Create("DPanel") cartpan:SetCursor("pointer") cartpan:SetSize(list:GetWide(), panhei) local cartname = savetab[1] local x = 8 if defaultcart == cartname then local defimage = vgui.Create("DImage", cartpan) defimage:SetImage("icon16/heart.png") defimage:SizeToContents() defimage:SetMouseInputEnabled(true) defimage:SetTooltip("This is your default cart.\nIf you join the game late then you'll spawn with this cart.") defimage:SetPos(x, cartpan:GetTall() * 0.5 - defimage:GetTall() * 0.5) x = x + defimage:GetWide() + 4 end local cartnamelabel = EasyLabel(cartpan, cartname, panfont) cartnamelabel:SetPos(x, cartpan:GetTall() * 0.5 - cartnamelabel:GetTall() * 0.5) x = cartpan:GetWide() - 20 local checkbutton = vgui.Create("DImageButton", cartpan) checkbutton:SetImage("icon16/accept.png") checkbutton:SizeToContents() checkbutton:SetTooltip("Purchase this saved cart.") x = x - checkbutton:GetWide() - 4 checkbutton:SetPos(x, cartpan:GetTall() * 0.5 - checkbutton:GetTall() * 0.5) checkbutton.ID = i checkbutton.DoClick = QuickCheckDoClick local loadbutton = vgui.Create("DImageButton", cartpan) loadbutton:SetImage("icon16/folder_go.png") loadbutton:SizeToContents() loadbutton:SetTooltip("Load this saved cart.") x = x - loadbutton:GetWide() - 4 loadbutton:SetPos(x, cartpan:GetTall() * 0.5 - loadbutton:GetTall() * 0.5) loadbutton.ID = i loadbutton.DoClick = LoadDoClick local defaultbutton = vgui.Create("DImageButton", cartpan) defaultbutton:SetImage("icon16/heart.png") defaultbutton:SizeToContents() if cartname == defaultcart then defaultbutton:SetTooltip("Remove this cart as your default.") else defaultbutton:SetTooltip("Make this cart your default.") end x = x - defaultbutton:GetWide() - 4 defaultbutton:SetPos(x, cartpan:GetTall() * 0.5 - defaultbutton:GetTall() * 0.5) defaultbutton.Name = cartname defaultbutton.DoClick = DefaultDoClick local deletebutton = vgui.Create("DImageButton", cartpan) deletebutton:SetImage("icon16/bin.png") deletebutton:SizeToContents() deletebutton:SetTooltip("Delete this saved cart.") x = x - deletebutton:GetWide() - 4 deletebutton:SetPos(x, cartpan:GetTall() * 0.5 - loadbutton:GetTall() * 0.5) deletebutton.ID = i deletebutton.DoClick = DeleteDoClick list:AddItem(cartpan) end local isclassic = GAMEMODE:IsClassicMode() for catid, catname in ipairs(GAMEMODE.ItemCategories) do local list = vgui.Create("DPanelList", propertysheet) list:SetPaintBackground(false) propertysheet:AddSheet(catname, list, GAMEMODE.ItemCategoryIcons[catid], false, false) list:EnableVerticalScrollbar(true) list:SetWide(propertysheet:GetWide() - 16) list:SetSpacing(2) list:SetPadding(2) for i, tab in ipairs(GAMEMODE.Items) do if tab.Category == catid and tab.WorthShop then local itempan = vgui.Create("DPanel") itempan:SetSize(list:GetWide(), 40) list:AddItem(itempan) local mdlframe = vgui.Create("DPanel", itempan) mdlframe:SetSize(32, 32) mdlframe:SetPos(4, 4) local mdl = tab.Model or (weapons.GetStored(tab.SWEP) or tab).WorldModel if mdl then local mdlpanel = vgui.Create("DModelPanel", mdlframe) mdlpanel:SetSize(mdlframe:GetSize()) mdlpanel:SetModel(mdl) local mins, maxs = mdlpanel.Entity:GetRenderBounds() mdlpanel:SetCamPos(mins:Distance(maxs) * Vector(0.75, 0.75, 0.5)) mdlpanel:SetLookAt((mins + maxs) / 2) end if tab.SWEP or tab.Countables then local counter = vgui.Create("ItemAmountCounter", itempan) counter:SetItemID(i) end local namelab = EasyLabel(itempan, tab.Name or "", "ZSHUDFontSmall") namelab:SetPos(42, itempan:GetTall() * 0.5 - namelab:GetTall() * 0.5) local pricelab = EasyLabel(itempan, tostring(tab.Worth).." Worth", "ZSHUDFontTiny") pricelab:SetPos(itempan:GetWide() - 20 - pricelab:GetWide(), 4) local button = vgui.Create("DImageButton", itempan) button:SetImage("icon16/cart_add.png") button:SizeToContents() button:SetPos(itempan:GetWide() - 20 - button:GetWide(), itempan:GetTall() - button:GetTall() - 4) button:SetTooltip("Add to cart") button.ID = tab.Signature or i button.DoClick = CartDoClick WorthButtons[i] = button if tab.Description then itempan:SetTooltip(tab.Description) end if tab.NoClassicMode and isclassic then itempan:SetAlpha(120) end end end end local worthlab = EasyLabel(frame, "Worth: "..tostring(WorthRemaining), "ZSHUDFontSmall", COLOR_LIMEGREEN) worthlab:SetPos(8, frame:GetTall() - worthlab:GetTall() - 8) frame.WorthLab = worthlab local checkout = EasyButton(frame, "Checkout", 8, 4) checkout:SetPos(frame:GetWide() * 0.5 - checkout:GetWide() * 0.5, frame:GetTall() - checkout:GetTall() - 8) checkout.DoClick = CheckoutDoClick local rand = EasyButton(frame, "Random", 8, 4) rand:SetPos(frame:GetWide() - rand:GetWide() - 8, frame:GetTall() - rand:GetTall() - 8) rand.DoClick = RandDoClick if #GAMEMODE.SavedCarts == 0 then propertysheet:SetActiveTab(propertysheet.Items[math.min(2, #propertysheet.Items)].Tab) end frame:Center() frame:SetAlpha(0) frame:AlphaTo(255, 0.5, 0) frame:MakePopup() return frame end local PANEL = {} PANEL.m_ItemID = 0 PANEL.RefreshTime = 1.5 PANEL.NextRefresh = 0 function PANEL:Init() self:SetFont("DefaultFontSmall") end function PANEL:Think() if CurTime() >= self.NextRefresh then self.NextRefresh = CurTime() + self.RefreshTime self:Refresh() end end function PANEL:Refresh() local count = GAMEMODE:GetCurrentEquipmentCount(self:GetItemID()) if count == 0 then self:SetText(" ") else self:SetText(count) end self:SizeToContents() end function PANEL:SetItemID(id) self.m_ItemID = id end function PANEL:GetItemID() return self.m_ItemID end vgui.Register("ItemAmountCounter", PANEL, "DLabel")
gpl-3.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Windurst_Waters/npcs/Lumomo.lua
1
1038
----------------------------------- -- Area: Windurst Waters -- NPC: Lumomo -- Type: Standard NPC -- @zone: 238 -- @pos: -55.770 -5.499 18.914 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0332); 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
RyMarq/Zero-K
LuaUI/Widgets/chili/Controls/treeview.lua
2
3007
--// ============================================================================= --- TreeView module --- TreeView fields. -- Inherits from Control. -- @see control.Control -- @table TreeView -- @bool[opt = true] autosize whether size is automatically determined -- @int[opt = 1] selected selected item -- @tparam {TreeNode1, TreeNode2, ...} nodes nodes of the tree -- @tparam {func1, fun2, ...} OnSelectNode function listeners for node selection (default {}) TreeView = Control:Inherit{ classname = "treeview", autosize = true, minItemHeight = 16, labelFontsize = 14, defaultWidth = "100%", defaultHeight = "100%", selected = 1, root = nil, nodes = {}, clickTextToToggle = false, defaultExpanded = false, OnSelectNode = {}, } local this = TreeView local inherited = this.inherited --// ============================================================================= local function ParseInitTable(node, nodes) local lastnode = node for i = 1, #nodes do local data = nodes[i] if (type(data) == "table") then ParseInitTable(lastnode, data) else lastnode = node:Add(data) end end end function TreeView:New(obj) local nodes = obj.nodes if (nodes) then obj.children = {} end obj = inherited.New(self, obj) obj.root = TreeViewNode:New{treeview = obj, root = true; minHeight = obj.minItemHeight; expanded = obj.defaultExpanded, clickTextToToggle = obj.clickTextToToggle, labelFontsize = obj.labelFontsize} if (nodes) then ParseInitTable(obj.root, nodes) end obj:AddChild(obj.root) obj:UpdateLayout() local sel = obj.selected obj.selected = false if ((sel or 0) > 0) then obj:Select(sel) end return obj end --// ============================================================================= function TreeView:GetNodeByCaption(caption) return self.root:GetNodeByCaption(caption) end function TreeView:GetNodeByIndex(index) local result = self.root:GetNodeByIndex(index, 0) return (not IsNumber(result)) and result end --// ============================================================================= function TreeView:Select(item) local obj = UnlinkSafe(item) if (type(item) == "number") then obj = self:GetNodeByIndex(item) end if (obj and obj:InheritsFrom("treeviewnode")) then local oldSelected = self.selected self.selected = MakeWeakLink(obj) self.selected:Invalidate() if (oldSelected) then oldSelected:Invalidate() end obj:CallListeners(obj.OnSelectChange, true) if (oldSelected) then oldSelected:CallListeners(oldSelected.OnSelectChange, false) end self:CallListeners(self.OnSelectNode, self.selected, oldSelected) end end --// ============================================================================= function TreeView:UpdateLayout() local c = self.root c:_UpdateConstraints(0, 0, self.clientWidth) c:Realign() if (self.autosize) then self:Resize(nil, c.height, true, true) end return true end --// =============================================================================
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Castle_Oztroja/Zone.lua
1
1123
----------------------------------- -- -- Zone: Castle_Oztroja -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; require("scripts/zones/Castle_Oztroja/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,menuchoice) --print("CSID: ",csid); --print("RESULT: ",menuchoice); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,menuchoice) --print("CSID: ",csid); --print("RESULT: ",menuchoice); end;
gpl-3.0
pakoito/ToME---t-engine4
game/engines/default/engine/ui/Separator.lua
3
5157
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local Base = require "engine.ui.Base" --- A generic UI button module(..., package.seeall, class.inherit(Base)) function _M:init(t) self.dir = assert(t.dir, "no separator dir") self.size = assert(t.size, "no separator size") self.dest_area = {w = 1, h = 1} Base.init(self, t) end function _M:generate() if self.dir == "horizontal" then self.top = self:getUITexture("ui/border_vert_top.png") self.middle = self:getUITexture("ui/border_vert_middle.png") self.bottom = self:getUITexture("ui/border_vert_bottom.png") self.w, self.h = self.middle.w, self.size else self.left = self:getUITexture("ui/border_hor_left.png") self.middle = self:getUITexture("ui/border_hor_middle.png") self.right = self:getUITexture("ui/border_hor_right.png") self.w, self.h = self.size, self.middle.h end self.dest_area.w = self.w self.dest_area.h = self.h end function _M:display(x, y, total_w, nb_keyframes, ox, oy, total_h, loffset_x, loffset_y, dest_area) dest_area = dest_area or self.dest_area loffset_x = loffset_x and loffset_x or 0 loffset_y = loffset_y and loffset_y or 0 total_w = total_w and total_w or 0 total_h = total_h and total_h or 0 local clip_y_start = 0 local clip_y_end = 0 local clip_x_start = 0 local clip_x_end = 0 if total_h < loffset_y then clip_y_start = loffset_y - total_h end if self.dir == "horizontal" then if total_h + self.top.h > loffset_y and total_h < loffset_y + dest_area.h then if total_h + self.top.h > loffset_y + dest_area.h then clip_y_end = total_h + self.top.h - loffset_y - dest_area.h end local one_by_tex_h = 1 / self.top.th self.top.t:toScreenPrecise(x, y, self.top.w, self.top.h - clip_y_start - clip_y_end, 0, self.top.w / self.top.tw, clip_y_start * one_by_tex_h, (self.top.h - clip_y_end) * one_by_tex_h) end clip_y_end = 0 if total_h + self.bottom.h > loffset_y and total_h < loffset_y + dest_area.h then if total_h + self.bottom.h > loffset_y + dest_area.h then clip_y_end = total_h + self.bottom.h - loffset_y - dest_area.h end local one_by_tex_h = 1 / self.bottom.th self.bottom.t:toScreenPrecise(x, y + self.h - self.bottom.h, self.bottom.w, self.bottom.h - clip_y_start - clip_y_end, 0, self.bottom.w / self.bottom.tw, clip_y_start * one_by_tex_h, (self.bottom.h - clip_y_end) * one_by_tex_h) end clip_y_end = 0 if total_h + self.middle.h > loffset_y and total_h < loffset_y + dest_area.h then if total_h + self.middle.h > loffset_y + dest_area.h then clip_y_end = total_h + self.middle.h - loffset_y - dest_area.h end local one_by_tex_h = 1 / self.middle.th self.middle.t:toScreenPrecise(x, y + self.top.h, self.middle.w, self.h - self.top.h - self.bottom.h - clip_y_start - clip_y_end, 0, self.middle.w / self.middle.tw, clip_y_start * one_by_tex_h, (self.h - self.top.h - self.bottom.h - clip_y_end) * one_by_tex_h) end else if total_h + self.left.h > loffset_y and total_h < loffset_y + dest_area.h then if total_h + self.left.h > loffset_y + dest_area.h then clip_y_end = total_h + self.left.h - loffset_y - dest_area.h end local one_by_tex_h = 1 / self.left.th self.left.t:toScreenPrecise(x, y, self.left.w, self.left.h - clip_y_start - clip_y_end, 0, self.left.w / self.left.tw, clip_y_start * one_by_tex_h, (self.left.h - clip_y_end) * one_by_tex_h) end clip_y_end = 0 if total_h + self.right.h > loffset_y and total_h < loffset_y + dest_area.h then if total_h + self.right.h > loffset_y + dest_area.h then clip_y_end = total_h + self.right.h - loffset_y - dest_area.h end local one_by_tex_h = 1 / self.right.th self.right.t:toScreenPrecise(x + self.w - self.right.w, y, self.right.w, self.right.h - clip_y_start - clip_y_end, 0, self.right.w / self.right.tw, clip_y_start * one_by_tex_h, (self.right.h - clip_y_end) * one_by_tex_h) end clip_y_end = 0 if total_h + self.middle.h > loffset_y and total_h < loffset_y + dest_area.h then if total_h + self.middle.h > loffset_y + dest_area.h then clip_y_end = total_h + self.middle.h - loffset_y - dest_area.h end local one_by_tex_h = 1 / self.middle.th self.middle.t:toScreenPrecise(x + self.left.w, y, self.w - self.left.w - self.right.w, self.middle.h - clip_y_start - clip_y_end, 0, (self.w - self.left.w - self.right.w) / self.middle.tw, clip_y_start * one_by_tex_h, (self.middle.h - clip_y_end) * one_by_tex_h) end end end
gpl-3.0
knixeur/notion
contrib/statusd/statusd_iwinfo.lua
6
2844
-- Authors: Relu Patrascu <ikoflexer@gmail.com> -- License: LGPL, version 2.1 or later -- Last Changed: 2004-11-17 -- -- statusd_iwinfo.lua -- -- Copyright (c) Relu Patrascu 2004. -- -- Ion 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 2.1 of the License, or -- (at your option) any later version. -- -- Nov. 5, 2004 -- Disclaimer -- Neither am I a lua expert nor do I have the time to invest in writing -- better code here. I simply needed this utility and it works OK for me. -- I give no guarantees of any kind for this code. Suggestions for -- improvement are welcome. -- ikoflexer at gmail dot com -- Nov 17, 2004 -- ikoflexer at gmail dot com -- -- Made it return a space " " instead of empty string "" -- when /proc/net/wireless doesn't report any interface. -- Otherwise old info lingers in the status bar. if not statusd_iwinfo then statusd_iwinfo = { interval = 10*1000 } end local iwinfo_timer local function get_iwinfo_iwcfg() local f = io.open('/proc/net/wireless', 'r') if not f then return end -- first 2 lines -- headers f:read('*l') f:read('*l') -- the third line has wifi info local s = f:read('*l') f:close() local st, en, iface = 0, 0, 0 if not s then return end st, en, iface = string.find(s, '(%w+):') local f1 = io.popen("/sbin/iwconfig " .. iface) if not f1 then return else local iwOut = f1:read('*a') f1:close() st,en,proto = string.find(iwOut, '(802.11[%-]*%a*)') st,en,ssid = string.find(iwOut, 'ESSID[=:]"([%w+%s*]*)"', en) st,en,bitrate = string.find(iwOut, 'Bit Rate[=:]([%s%w%.]*%/%a+)', en) bitrate = string.gsub(bitrate, "%s", "") st,en,linkq = string.find(iwOut, 'Link Quality[=:](%d+%/%d+)', en) st,en,signal = string.find(iwOut, 'Signal level[=:](%-%d+)', en) st,en,noise = string.find(iwOut, 'Noise level[=:](%-%d+)', en) return proto, ssid, bitrate, linkq, signal, noise end end local function update_iwinfo() local proto, ssid, bitrate, linkq, signal, noise = get_iwinfo_iwcfg() -- In case get_iwinfo_iwcfg doesn't return any values we don't want stupid lua -- errors about concatenating nil values. ssid = ssid or "N/A" bitrate = bitrate or "N/A" linkq = linkq or "N/A" signal = signal or "N/A" noise = noise or "N/A" proto = proto or "N/A" statusd.inform("iwinfo_cfg", ssid.." "..bitrate.." "..linkq.." "..signal.."/"..noise.."dBm "..proto) statusd.inform("iwinfo_ssid", ssid) statusd.inform("iwinfo_bitrate", bitrate) statusd.inform("iwinfo_linkq", linkq) statusd.inform("iwinfo_signal", signal) statusd.inform("iwinfo_noise", noise) statusd.inform("iwinfo_proto", proto) iwinfo_timer:set(statusd_iwinfo.interval, update_iwinfo) end -- Init iwinfo_timer = statusd.create_timer() update_iwinfo()
lgpl-2.1