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
nasomi/darkstar
scripts/zones/Mamook/mobs/Colibri.lua
58
1615
----------------------------------- -- Area: Mamook -- MOB: Colibri ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local delay = mob:getLocalVar("delay"); local LastCast = mob:getLocalVar("LAST_CAST"); local spell = mob:getLocalVar("COPY_SPELL"); if (mob:AnimationSub() == 1) then if (mob:getBattleTime() - LastCast > 30) then mob:setLocalVar("COPY_SPELL", 0); mob:setLocalVar("delay", 0); mob:AnimationSub(0); end if (spell > 0 and mob:hasStatusEffect(EFFECT_SILENCE) == false) then if (delay >= 3) then mob:castSpell(spell); mob:setLocalVar("COPY_SPELL", 0); mob:setLocalVar("delay", 0); mob:AnimationSub(0); else mob:setLocalVar("delay", delay+1); end end end end; ----------------------------------- -- onMagicHit ----------------------------------- function onMagicHit(caster, target, spell) if (spell:tookEffect() and (caster:isPC() or caster:isPet()) and spell:getSpellGroup() ~= SPELLGROUP_BLUE ) then target:setLocalVar("COPY_SPELL", spell:getID()); target:setLocalVar("LAST_CAST", target:getBattleTime()); target:AnimationSub(1); end return 1; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) end;
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/spell_electric_triad_icon.meta.lua
14
1866
return { extra_loadables = { disabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = {}, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = true }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { 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 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
Nelarius/wren
test/benchmark/map_string.lua
9
5150
local adverbs = { "moderately", "really", "slightly", "very" } local adjectives = { "abandoned", "able", "absolute", "academic", "acceptable", "acclaimed", "accomplished", "accurate", "aching", "acidic", "acrobatic", "active", "actual", "adept", "admirable", "admired", "adolescent", "adorable", "adored", "advanced", "adventurous", "affectionate", "afraid", "aged", "aggravating", "aggressive", "agile", "agitated", "agonizing", "agreeable", "ajar", "alarmed", "alarming", "alert", "alienated", "alive", "all", "altruistic", "amazing", "ambitious", "ample", "amused", "amusing", "anchored", "ancient", "angelic", "angry", "anguished", "animated", "annual", "another", "antique", "anxious", "any", "apprehensive", "appropriate", "apt", "arctic", "arid", "aromatic", "artistic", "ashamed", "assured", "astonishing", "athletic", "attached", "attentive", "attractive", "austere", "authentic", "authorized", "automatic", "avaricious", "average", "aware", "awesome", "awful", "awkward", "babyish", "back", "bad", "baggy", "bare", "barren", "basic", "beautiful", "belated", "beloved", "beneficial", "best", "better", "bewitched", "big", "big-hearted", "biodegradable", "bite-sized", "bitter", "black", "black-and-white", "bland", "blank", "blaring", "bleak", "blind", "blissful", "blond", "blue", "blushing", "bogus", "boiling", "bold", "bony", "boring", "bossy", "both", "bouncy", "bountiful", "bowed", "brave", "breakable", "brief", "bright", "brilliant", "brisk", "broken", "bronze", "brown", "bruised", "bubbly", "bulky", "bumpy", "buoyant", "burdensome", "burly", "bustling", "busy", "buttery", "buzzing", "calculating", "calm", "candid", "canine", "capital", "carefree", "careful", "careless", "caring", "cautious", "cavernous", "celebrated", "charming", "cheap", "cheerful", "cheery", "chief", "chilly", "chubby", "circular", "classic", "clean", "clear", "clear-cut", "clever", "close", "closed", "cloudy", "clueless", "clumsy", "cluttered", "coarse", "cold", "colorful", "colorless", "colossal", "comfortable", "common", "compassionate", "competent", "complete", "complex", "complicated", "composed", "concerned", "concrete", "confused", "conscious", "considerate", "constant", "content", "conventional", "cooked", "cool", "cooperative", "coordinated", "corny", "corrupt", "costly", "courageous", "courteous", "crafty" } local animals = { "aardvark", "african buffalo", "albatross", "alligator", "alpaca", "ant", "anteater", "antelope", "ape", "armadillo", "baboon", "badger", "barracuda", "bat", "bear", "beaver", "bee", "bison", "black panther", "blue jay", "boar", "butterfly", "camel", "capybara", "carduelis", "caribou", "cassowary", "cat", "caterpillar", "cattle", "chamois", "cheetah", "chicken", "chimpanzee", "chinchilla", "chough", "clam", "cobra", "cockroach", "cod", "cormorant", "coyote", "crab", "crane", "crocodile", "crow", "curlew", "deer", "dinosaur", "dog", "dolphin", "domestic pig", "donkey", "dotterel", "dove", "dragonfly", "duck", "dugong", "dunlin", "eagle", "echidna", "eel", "elephant seal", "elephant", "elk", "emu", "falcon", "ferret", "finch", "fish", "flamingo", "fly", "fox", "frog", "gaur", "gazelle", "gerbil", "giant panda", "giraffe", "gnat", "goat", "goldfish", "goose", "gorilla", "goshawk", "grasshopper", "grouse", "guanaco", "guinea fowl", "guinea pig", "gull", "hamster", "hare", "hawk", "hedgehog", "heron", "herring", "hippopotamus", "hornet", "horse", "human", "hummingbird", "hyena", "ibex", "ibis", "jackal", "jaguar", "jay", "jellyfish", "kangaroo", "kingfisher", "koala", "komodo dragon", "kookabura", "kouprey", "kudu", "lapwing", "lark", "lemur", "leopard", "lion", "llama", "lobster", "locust", "loris", "louse", "lyrebird", "magpie", "mallard", "manatee", "mandrill", "mantis", "marten", "meerkat", "mink", "mole", "mongoose", "monkey", "moose", "mosquito", "mouse", "mule", "narwhal", "newt", "nightingale", "octopus", "okapi", "opossum", "oryx", "ostrich", "otter", "owl", "oyster", "parrot", "partridge", "peafowl", "pelican", "penguin", "pheasant", "pigeon", "pinniped", "polar bear", "pony", "porcupine", "porpoise", "prairie dog", "quail", "quelea", "quetzal", "rabbit", "raccoon", "ram", "rat", "raven", "red deer", "red panda", "reindeer", "rhinoceros", "rook", "salamander", "salmon", "sand dollar", "sandpiper", "sardine", "scorpion", "sea lion", "sea urchin", "seahorse", "shark", "sheep", "shrew", "skunk", "snail", "snake", "sparrow", "spider", "spoonbill", "squid", "wallaby", "wildebeest" } local keys = {} for _, animal in ipairs(animals) do for _, adjective in ipairs(adjectives) do for _, adverb in ipairs(adverbs) do table.insert(keys, adverb .. " " .. adjective .. " " .. animal) end end end local start = os.clock() local map = {} local i = 0 for _, key in ipairs(keys) do map[key] = i i = i + 1 end local sum = 0 for _, key in ipairs(keys) do sum = sum + map[key] end for _, key in ipairs(keys) do map[key] = nil end io.write(string.format("%d\n", sum)) io.write(string.format("elapsed: %.8f\n", os.clock() - start))
mit
nasomi/darkstar
scripts/zones/Port_Bastok/npcs/Denvihr.lua
36
1563
----------------------------------- -- Area: Port Bastok -- NPC: Denvihr -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,DENVIHR_SHOP_DIALOG); stock = { 0x02BB, 5688,1, --Oak Log 0x0284, 1800,1, --Mythril Ore 0x0343, 225,1, --Flax Flower 0x02BA, 86,2, --Ash Log 0x02B6, 2543,2, --Chestnut Log 0x0283, 810,2, --Iron Ore 0x0341, 18,2, --Moko Grass 0x11DA, 50,2, --Bird Egg 0x0280, 10,3, --Copper Ore 0x0088, 1800,3 --Kaiserin Cosmetics } showNationShop(player, BASTOK, 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
telergybot/kelidestan5454
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
Hello23-Ygopro/ygopro-ds
expansions/script/c27002014.lua
1
1195
--BT2-012 Repeated Force Vegito local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,CHARACTER_VEGITO,SPECIAL_TRAIT_SAIYAN) ds.AddPlayProcedure(c,COLOR_RED,1,6) --union-potara ds.EnableUnionPotara(c,scard.unipfilter1,scard.unipfilter2,nil,nil,5) --triple strike ds.EnableTripleStrike(c) --power up ds.AddSingleAutoAttack(c,0,nil,ds.hinttg,scard.powop) end scard.dragon_ball_super_card=true scard.combo_cost=1 --union-potara scard.unipfilter1=aux.FilterBoolFunction(Card.IsCharacter,CHARACTER_SON_GOKU) scard.unipfilter2=aux.FilterBoolFunction(Card.IsCharacter,CHARACTER_VEGETA) --power up function scard.powop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToSkill(e) or c:IsFacedown() then return end ds.GainSkillUpdatePower(c,c,1,scard.powval) end function scard.powval(e,c) local tp=c:GetControler() local ct1=Duel.GetMatchingGroupCount(ds.DropAreaFilter(Card.IsCharacter),tp,DS_LOCATION_DROP,0,nil,CHARACTER_SON_GOKU)*5000 local ct2=Duel.GetMatchingGroupCount(ds.DropAreaFilter(Card.IsCharacter),tp,DS_LOCATION_DROP,0,nil,CHARACTER_VEGETA)*5000 return ct1+ct2 end
gpl-3.0
mkjanke/Focus-Points
focuspoints.lrdevplugin/AppleDelegates.lua
5
2121
--[[ Copyright 2016 Whizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ A collection of delegate functions to be passed into the DefaultPointRenderer when the camera is Apple (iPhone, iPad) --]] local LrStringUtils = import "LrStringUtils" local LrErrors = import 'LrErrors' require "Utils" AppleDelegates = {} --[[ -- metaData - the metadata as read by exiftool --]] function AppleDelegates.getAfPoints(photo, metaData) local imageWidth = ExifUtils.findFirstMatchingValue(metaData, { "Image Width", "Exif Image Width" }) local imageHeight = ExifUtils.findFirstMatchingValue(metaData, { "Image Height", "Exif Image Height" }) if imageWidth == nil or imageHeight == nil then return nil end local orgPhotoWidth, orgPhotoHeight = DefaultPointRenderer.getNormalizedDimensions(photo) local xScale = orgPhotoWidth / imageWidth local yScale = orgPhotoHeight / imageHeight local subjectArea = split(ExifUtils.findFirstMatchingValue(metaData, { "Subject Area" }), " ") if subjectArea == nil then LrErrors.throwUserError("Could not find Subject Area data within the image.") return nil end local x = subjectArea[1] * xScale local y = subjectArea[2] * yScale local w = subjectArea[3] * xScale local h = subjectArea[4] * yScale local result = { pointTemplates = DefaultDelegates.pointTemplates, points = { } } if w > 0 and h > 0 then table.insert(result.points, { pointType = DefaultDelegates.POINTTYPE_AF_SELECTED_INFOCUS, x = x, y = y, width = w, height = h }) end return result end
apache-2.0
nasomi/darkstar
scripts/zones/Port_Windurst/npcs/Boronene.lua
38
1036
----------------------------------- -- Area: Port Windurst -- NPC: Boronene -- Type: Moghouse Renter -- @zone: 240 -- @pos 201.651 -13 229.584 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x027e); 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
nasomi/darkstar
scripts/zones/Kazham-Jeuno_Airship/npcs/Joosef.lua
19
2039
----------------------------------- -- Area: Kazham-Jeuno Airship -- NPC: Joosef -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham-Jeuno_Airship/TextIDs"] = nil; require("scripts/zones/Kazham-Jeuno_Airship/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 1 do vHour = vHour - 6; end local message = WILL_REACH_KAZHAM; if (vHour == -5) then if (vMin >= 48) then vHour = 3; message = WILL_REACH_JEUNO; else vHour = 0; end elseif (vHour == -4) then vHour = 2; message = WILL_REACH_JEUNO; elseif (vHour == -3) then vHour = 1; message = WILL_REACH_JEUNO; elseif (vHour == -2) then if (vMin <= 49) then vHour = 0; message = WILL_REACH_JEUNO; else vHour = 3; end elseif (vHour == -1) then vHour = 2; elseif (vHour == 0) then vHour = 1; end local vMinutes = 0; if (message == WILL_REACH_JEUNO) then vMinutes = (vHour * 60) + 49 - vMin; else -- WILL_REACH_KAZHAM vMinutes = (vHour * 60) + 48 - vMin; end if (vMinutes <= 30) then if ( message == WILL_REACH_KAZHAM) then message = IN_KAZHAM_MOMENTARILY; else -- WILL_REACH_JEUNO message = IN_JEUNO_MOMENTARILY; end elseif (vMinutes < 60) then vHour = 0; end player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5)); 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
nasomi/darkstar
scripts/zones/Outer_Horutoto_Ruins/npcs/_ne4.lua
19
2631
----------------------------------- -- Area: Outer Horutoto Ruins -- NPC: Strange Apparatus -- @pos: -574 0 739 194 ----------------------------------- package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil; require("scripts/zones/Outer_Horutoto_Ruins/TextIDs"); require("scripts/globals/strangeapparatus"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local trade = tradeToStrApp(player, trade); if (trade ~= nil) then if ( trade == 1) then -- good trade local drop = player:getLocalVar("strAppDrop"); local dropQty = player:getLocalVar("strAppDropQty"); local docStatus = 0; -- Assistant if (hasStrAppDocStatus(player)) then docStatus = 1; -- Doctor end player:startEvent(0x0042, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0); else -- wrong chip, spawn elemental nm spawnElementalNM(player); delStrAppDocStatus(player); player:messageSpecial(SYS_OVERLOAD); player:messageSpecial(YOU_LOST_THE, trade); end else -- Invalid trade, lose doctor status delStrAppDocStatus(player); player:messageSpecial(DEVICE_NOT_WORKING); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local docStatus = 0; -- Assistant if (hasStrAppDocStatus(player)) then docStatus = 1; -- Doctor else player:setLocalVar( "strAppPass", 1); end player:startEvent(0x0040, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u", option); if (csid == 0x0040) then if (hasStrAppDocStatus(player) == false) then local docStatus = 1; -- Assistant if ( option == strAppPass(player)) then -- Good password docStatus = 0; -- Doctor giveStrAppDocStatus(player); end player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0042) then local drop = player:getLocalVar("strAppDrop"); local dropQty = player:getLocalVar("strAppDropQty"); if (drop ~= 0) then if ( dropQty == 0) then dropQty = 1; end player:addItem(drop, dropQty); player:setLocalVar("strAppDrop", 0); player:setLocalVar("strAppDropQty", 0); end end end;
gpl-3.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
37
8552
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sys = require "luci.sys" m = Map("dhcp", translate("DHCP and DNS"), translate("Dnsmasq is a combined <abbr title=\"Dynamic Host Configuration Protocol" .. "\">DHCP</abbr>-Server and <abbr title=\"Domain Name System\">DNS</abbr>-" .. "Forwarder for <abbr title=\"Network Address Translation\">NAT</abbr> " .. "firewalls")) s = m:section(TypedSection, "dnsmasq", translate("Server Settings")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("files", translate("Resolv and Hosts Files")) s:tab("tftp", translate("TFTP Settings")) s:tab("advanced", translate("Advanced Settings")) s:taboption("general", Flag, "domainneeded", translate("Domain required"), translate("Don't forward <abbr title=\"Domain Name System\">DNS</abbr>-Requests without " .. "<abbr title=\"Domain Name System\">DNS</abbr>-Name")) s:taboption("general", Flag, "authoritative", translate("Authoritative"), translate("This is the only <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" .. "abbr> in the local network")) s:taboption("files", Flag, "readethers", translate("Use <code>/etc/ethers</code>"), translate("Read <code>/etc/ethers</code> to configure the <abbr title=\"Dynamic Host " .. "Configuration Protocol\">DHCP</abbr>-Server")) s:taboption("files", Value, "leasefile", translate("Leasefile"), translate("file where given <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" .. "abbr>-leases will be stored")) s:taboption("files", Flag, "noresolv", translate("Ignore resolve file")).optional = true rf = s:taboption("files", Value, "resolvfile", translate("Resolve file"), translate("local <abbr title=\"Domain Name System\">DNS</abbr> file")) rf:depends("noresolv", "") rf.optional = true s:taboption("files", Flag, "nohosts", translate("Ignore Hosts files")).optional = true hf = s:taboption("files", DynamicList, "addnhosts", translate("Additional Hosts files")) hf:depends("nohosts", "") hf.optional = true s:taboption("advanced", Flag, "boguspriv", translate("Filter private"), translate("Do not forward reverse lookups for local networks")) s:taboption("advanced", Flag, "filterwin2k", translate("Filter useless"), translate("Do not forward requests that cannot be answered by public name servers")) s:taboption("advanced", Flag, "localise_queries", translate("Localise queries"), translate("Localise hostname depending on the requesting subnet if multiple IPs are available")) s:taboption("general", Value, "local", translate("Local server"), translate("Local domain specification. Names matching this domain are never forwarded and are resolved from DHCP or hosts files only")) s:taboption("general", Value, "domain", translate("Local domain"), translate("Local domain suffix appended to DHCP names and hosts file entries")) s:taboption("advanced", Flag, "expandhosts", translate("Expand hosts"), translate("Add local domain suffix to names served from hosts files")) s:taboption("advanced", Flag, "nonegcache", translate("No negative cache"), translate("Do not cache negative replies, e.g. for not existing domains")) s:taboption("advanced", Flag, "strictorder", translate("Strict order"), translate("<abbr title=\"Domain Name System\">DNS</abbr> servers will be queried in the " .. "order of the resolvfile")).optional = true bn = s:taboption("advanced", DynamicList, "bogusnxdomain", translate("Bogus NX Domain Override"), translate("List of hosts that supply bogus NX domain results")) bn.optional = true bn.placeholder = "67.215.65.132" s:taboption("general", Flag, "logqueries", translate("Log queries"), translate("Write received DNS requests to syslog")).optional = true df = s:taboption("general", DynamicList, "server", translate("DNS forwardings"), translate("List of <abbr title=\"Domain Name System\">DNS</abbr> " .. "servers to forward requests to")) df.optional = true df.placeholder = "/example.org/10.1.2.3" rp = s:taboption("general", Flag, "rebind_protection", translate("Rebind protection"), translate("Discard upstream RFC1918 responses")) rp.rmempty = false rl = s:taboption("general", Flag, "rebind_localhost", translate("Allow localhost"), translate("Allow upstream responses in the 127.0.0.0/8 range, e.g. for RBL services")) rl:depends("rebind_protection", "1") rd = s:taboption("general", DynamicList, "rebind_domain", translate("Domain whitelist"), translate("List of domains to allow RFC1918 responses for")) rd:depends("rebind_protection", "1") rd.datatype = "host" rd.placeholder = "ihost.netflix.com" pt = s:taboption("advanced", Value, "port", translate("<abbr title=\"Domain Name System\">DNS</abbr> server port"), translate("Listening port for inbound DNS queries")) pt.optional = true pt.datatype = "port" pt.placeholder = 53 qp = s:taboption("advanced", Value, "queryport", translate("<abbr title=\"Domain Name System\">DNS</abbr> query port"), translate("Fixed source port for outbound DNS queries")) qp.optional = true qp.datatype = "port" qp.placeholder = translate("any") lm = s:taboption("advanced", Value, "dhcpleasemax", translate("<abbr title=\"maximal\">Max.</abbr> <abbr title=\"Dynamic Host Configuration " .. "Protocol\">DHCP</abbr> leases"), translate("Maximum allowed number of active DHCP leases")) lm.optional = true lm.datatype = "uinteger" lm.placeholder = translate("unlimited") em = s:taboption("advanced", Value, "ednspacket_max", translate("<abbr title=\"maximal\">Max.</abbr> <abbr title=\"Extension Mechanisms for " .. "Domain Name System\">EDNS0</abbr> packet size"), translate("Maximum allowed size of EDNS.0 UDP packets")) em.optional = true em.datatype = "uinteger" em.placeholder = 1280 cq = s:taboption("advanced", Value, "dnsforwardmax", translate("<abbr title=\"maximal\">Max.</abbr> concurrent queries"), translate("Maximum allowed number of concurrent DNS queries")) cq.optional = true cq.datatype = "uinteger" cq.placeholder = 150 s:taboption("tftp", Flag, "enable_tftp", translate("Enable TFTP server")).optional = true tr = s:taboption("tftp", Value, "tftp_root", translate("TFTP server root"), translate("Root directory for files served via TFTP")) tr.optional = true tr:depends("enable_tftp", "1") tr.placeholder = "/" db = s:taboption("tftp", Value, "dhcp_boot", translate("Network boot image"), translate("Filename of the boot image advertised to clients")) db.optional = true db:depends("enable_tftp", "1") db.placeholder = "pxelinux.0" m:section(SimpleSection).template = "admin_network/lease_status" s = m:section(TypedSection, "host", translate("Static Leases"), translate("Static leases are used to assign fixed IP addresses and symbolic hostnames to " .. "DHCP clients. They are also required for non-dynamic interface configurations where " .. "only hosts with a corresponding lease are served.") .. "<br />" .. translate("Use the <em>Add</em> Button to add a new lease entry. The <em>MAC-Address</em> " .. "indentifies the host, the <em>IPv4-Address</em> specifies to the fixed address to " .. "use and the <em>Hostname</em> is assigned as symbolic name to the requesting host.")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" name = s:option(Value, "name", translate("Hostname")) name.datatype = "hostname" name.rmempty = true mac = s:option(Value, "mac", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address")) mac.datatype = "list(macaddr)" mac.rmempty = true ip = s:option(Value, "ip", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) ip.datatype = "or(ip4addr,'ignore')" hostid = s:option(Value, "hostid", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Suffix (hex)")) sys.net.arptable(function(entry) ip:value(entry["IP address"]) mac:value( entry["HW address"], entry["HW address"] .. " (" .. entry["IP address"] .. ")" ) end) function ip.validate(self, value, section) local m = mac:formvalue(section) or "" local n = name:formvalue(section) or "" if value and #n == 0 and #m == 0 then return nil, translate("One of hostname or mac address must be specified!") end return Value.validate(self, value, section) end return m
gpl-2.0
nasomi/darkstar
scripts/zones/Metalworks/npcs/Ayame.lua
17
2816
----------------------------------- -- Area: Metalworks -- NPC: Ayame -- Involved in Missions -- Starts and Finishes Quest: True Strength -- @pos 133 -19 34 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,TRUE_STRENGTH) == QUEST_ACCEPTED) then if (trade:hasItemQty(1100,1) and trade:getItemCount() == 1) then -- Trade Xalmo Feather player:startEvent(0x02ed); -- Finish Quest "True Strength" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local trueStrength = player:getQuestStatus(BASTOK,TRUE_STRENGTH); local WildcatBastok = player:getVar("WildcatBastok"); if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,9) == false) then player:startEvent(0x03a7); elseif (player:getCurrentMission(BASTOK) == THE_CRYSTAL_LINE and player:hasKeyItem(C_L_REPORTS)) then player:startEvent(0x02c8); elseif (trueStrength == QUEST_AVAILABLE and player:getMainJob() == 2 and player:getMainLvl() >= 50) then player:startEvent(0x02ec); -- Start Quest "True Strength" else player:startEvent(0x02bd); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x02c8) then finishMissionTimeline(player,1,csid,option); elseif (csid == 0x02ec) then player:addQuest(BASTOK,TRUE_STRENGTH); elseif (csid == 0x02ed) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14215); -- Temple Hose else player:tradeComplete(); player:addTitle(PARAGON_OF_MONK_EXCELLENCE); player:addItem(14215); player:messageSpecial(ITEM_OBTAINED,14215); -- Temple Hose player:addFame(BASTOK,AF3_FAME); player:completeQuest(BASTOK,TRUE_STRENGTH); end elseif (csid == 0x03a7) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",9,true); end end;
gpl-3.0
telmomenezes/lablove
basic_command_line.lua
1
1540
parameterString = "" function getNumberParameter(paramName, paramDefault, shortName) param = getCommandLineParameter(paramName) paramOut = 0.0 if param == "" then paramOut = paramDefault else paramOut = tonumber(param) end if ((shortName ~= nil) and (paramOut ~= 0)) then parameterString = parameterString .. shortName .. paramOut end return paramOut end function getBoolParameter(paramName, paramDefault, shortName) param = getCommandLineParameter(paramName) result = false if param == "" then result = paramDefault else if param == "true" then result = true else result = false end end if result then parameterString = parameterString .. "_" .. shortName .. "_" end return result end function getStringParameter(paramName, paramDefault, shortName) param = getCommandLineParameter(paramName) paramOut = param if param == "" then paramOut = paramDefault end if ((shortName ~= nil) and (paramOut ~= "")) then parameterString = parameterString .. shortName .. paramOut end return paramOut end screenWidth = getNumberParameter("swidth", 800) screenHeight = getNumberParameter("sheight", 600) fullScreen = getBoolParameter("fullscreen", false) noGraphics = getBoolParameter("nograph", false) seedIndex = getNumberParameter("seedindex", -1) timeLimit = getNumberParameter("timelimit", 0) random = getBoolParameter("random", false)
gpl-2.0
Wouterz90/SuperSmashDota
Game/scripts/vscripts/abilities/centaur.lua
1
8117
centaur_special_side = class({}) function centaur_special_side:OnAbilityPhaseStart() if not self:GetCaster():CanCast(self) then return false end if not self:IsCooldownReady() then return false end local caster = self:GetCaster() --caster:EmitSound("Hero_Centaur.HoofStomp") StartAnimation(caster, {duration=self:GetCastPoint(), activity=ACT_DOTA_CAST_ABILITY_2 , rate=self:GetCastPoint()/0.5 }) return true end function centaur_special_side:OnAbilityPhaseInterrupted() -- Cancel animations! local caster = self:GetCaster() --caster:StopSound("Hero_Centaur.HoofStomp") EndAnimation(caster) end function centaur_special_side:OnSpellStart() local caster = self:GetCaster() local direction = self.mouseVectorDistance local ability = self StoreSpecialKeyValues(self) caster:EmitSound("Hero_Centaur.DoubleEdge") local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_centaur/centaur_double_edge.vpcf", PATTACH_ABSORIGIN, caster) ParticleManager:SetParticleControl(particle, 0, caster:GetAbsOrigin()+caster:GetForwardVector()*self.radius+Vector(0,0,100)) ParticleManager:SetParticleControl(particle, 1, caster:GetAbsOrigin()) ParticleManager:SetParticleControl(particle, 2, caster:GetAbsOrigin()) ParticleManager:SetParticleControl(particle, 4, caster:GetAbsOrigin()) ParticleManager:SetParticleControl(particle, 5, caster:GetAbsOrigin()+caster:GetForwardVector()*self.radius+Vector(0,0,100)) Timers:CreateTimer(1,function() ParticleManager:DestroyParticle(particle,false) ParticleManager:ReleaseParticleIndex(particle) end) local units = FindUnitsInRadius(caster:GetTeam(), caster:GetAbsOrigin()+caster:GetForwardVector()*self.radius+Vector(0,0,100), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, 0, false) units = FilterUnitsBasedOnHeight(units,caster:GetAbsOrigin()+caster:GetForwardVector()*self.radius+Vector(0,0,100),self.radius) for _,unit in pairs(units) do local damageTable = { victim = unit, attacker = caster, damage = self:GetSpecialValueFor("damage") + RandomInt(0,self:GetSpecialValueFor("damage_offset")), damage_type = DAMAGE_TYPE_MAGICAL, ability = self, } ApplyDamage(damageTable) end local damageTable = { victim = caster, attacker = caster, damage = self.self_damage, damage_type = DAMAGE_TYPE_MAGICAL, ability = self, } ApplyDamage(damageTable) end centaur_special_bottom = class({}) function centaur_special_bottom:OnAbilityPhaseStart() if not self:GetCaster():CanCast(self) then return false end if not self:IsCooldownReady() then return false end local caster = self:GetCaster() --caster:EmitSound("Hero_Centaur.HoofStomp") StartAnimation(self:GetCaster(), {duration=self:GetCastPoint(), activity=ACT_DOTA_CAST_ABILITY_2, rate=1}) return true end function centaur_special_bottom:OnAbilityPhaseInterrupted() -- Cancel animations! local caster = self:GetCaster() --caster:StopSound("Hero_Centaur.HoofStomp.Loop") EndAnimation(caster) end function centaur_special_bottom:OnSpellStart() local caster = self:GetCaster() local direction = self.mouseVector local ability = self StoreSpecialKeyValues(self) caster:EmitSound("Hero_Centaur.HoofStomp") local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_centaur/centaur_warstomp.vpcf", PATTACH_ABSORIGIN, caster) ParticleManager:SetParticleControl(particle, 0, caster:GetAbsOrigin()) ParticleManager:SetParticleControl(particle, 1, Vector(self.radius, 1, 1)) ParticleManager:SetParticleControl(particle, 2, caster:GetAbsOrigin()) Timers:CreateTimer(1,function() ParticleManager:DestroyParticle(particle,false) ParticleManager:ReleaseParticleIndex(particle) end) local units = FindUnitsInRadius(caster:GetTeam(), caster:GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, 0, false) units = FilterUnitsBasedOnHeight(units,caster:GetAbsOrigin(),self.radius) for _,unit in pairs(units) do local damageTable = { victim = unit, attacker = caster, damage = self.damage + RandomInt(0,self.damage_offset), damage_type = DAMAGE_TYPE_MAGICAL, ability = self, } ApplyDamage(damageTable) unit:AddNewModifier(caster,self,"modifier_smash_stun",{duration = self.stun_duration}) end end LinkLuaModifier("modifier_centaur_stampede_smash","abilities/centaur.lua",LUA_MODIFIER_MOTION_NONE) centaur_special_top = class({}) function centaur_special_top:OnAbilityPhaseStart() if not self:GetCaster():CanCast(self) then return false end if not self:IsCooldownReady() then return false end if self:GetCaster().jumps > 3 then return end local caster = self:GetCaster() StoreSpecialKeyValues(self) caster:EmitSound("Hero_Centaur.Stampede.Cast") StartAnimation(self:GetCaster(), {duration=self.duration, activity=ACT_DOTA_CENTAUR_STAMPEDE, rate=1}) return true end function centaur_special_top:OnAbilityPhaseInterrupted() local caster = self:GetCaster() caster:StopSound("Hero_Centaur.Stampede.Cast") EndAnimation(caster) end function centaur_special_top:OnSpellStart() local caster = self:GetCaster() local radius = self:GetSpecialValueFor("radius") caster:AddNewModifier(caster,self,"modifier_centaur_stampede_smash",{duration = self.duration,x=self.mouseVector.x,z=self.mouseVector.z}) end modifier_centaur_stampede_smash = class({}) function modifier_centaur_stampede_smash:OnCreated(keys) if IsServer() then self.direction = Vec(keys.x,keys.z) StoreSpecialKeyValues(self,self:GetAbility()) self.targets = {} self:StartIntervalThink(FrameTime()) self:GetCaster():EmitSound("Hero_Centaur.Stampede.Movement") --self:GetCaster().movespeedFactor = self:GetCaster().movespeedFactor + self.bonus_speed_factor --self:GetCaster().jumpfactor = self:GetCaster().jumpfactor + self.bonus_speed_factor self.particle = ParticleManager:CreateParticle("particles/units/heroes/hero_centaur/centaur_stampede.vpcf", PATTACH_ABSORIGIN_FOLLOW, self.parent) ParticleManager:SetParticleControl(self.particle, 0, self:GetParent():GetAbsOrigin()) self:AddParticle(self.particle, false, false, -1, false, false) end end function modifier_centaur_stampede_smash:OnIntervalThink() local caster = self:GetCaster() Physics2D:SetStaticVelocity(caster,"centaur_stampede",self.direction*30) local units = FindUnitsInRadius(caster:GetTeam(), caster:GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, 0, false) units = FilterUnitsBasedOnHeight(units,caster:GetAbsOrigin(),self.radius) for _,unit in pairs(units) do if not self.targets[unit] then self.targets[unit] = true local damageTable = { victim = unit, attacker = caster, damage = self.damage + RandomInt(0,self.damage_offset), damage_type = DAMAGE_TYPE_MAGICAL, ability = self:GetAbility(), } ApplyDamage(damageTable) unit:AddNewModifier(caster,self:GetAbility(),"modifier_smash_stun",{duration = self.stun_duration}) end end end function modifier_centaur_stampede_smash:OnDestroy() if IsServer() then self:GetCaster():StopSound("Hero_Centaur.Stampede.Movement") self:GetCaster().jumps = 3 Physics2D:SetStaticVelocity(self:GetCaster(),"centaur_stampede",Vector(0,1)*30) --self:GetCaster().movespeedFactor = self:GetCaster().movespeedFactor - self.bonus_speed_factor --self:GetCaster().jumpfactor = self:GetCaster().jumpfactor - self.bonus_speed_factor Timers:CreateTimer(1,function() ParticleManager:DestroyParticle(self.particle,false) ParticleManager:ReleaseParticleIndex(self.particle) end) end end function modifier_centaur_stampede_smash:GetEffectName() return "particles/units/heroes/hero_centaur/centaur_stampede_overhead.vpcf" end function modifier_centaur_stampede_smash:GetEffectAttachType() return PATTACH_OVERHEAD_FOLLOW end
mit
nasomi/darkstar
scripts/zones/Nashmau/npcs/Tsutsuroon.lua
38
1260
----------------------------------- -- Area: Nashmau -- NPC: Tsutsuroon -- Type: Tenshodo Merchant -- @pos -15.193 0.000 31.356 53 ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/keyitems"); require("scripts/zones/Nashmau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then if (player:sendGuild(60431, 1, 23, 7)) then player:showText(npc,TSUTSUROON_SHOP_DIALOG); end else -- player:startEvent(0x0096); 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
nasomi/darkstar
scripts/zones/Giddeus/npcs/Laa_Mozi.lua
17
1983
----------------------------------- -- Area: Giddeus -- NPC: Laa Mozi -- Involved in Mission 1-3 -- @pos -22 0 148 145 ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/zones/Giddeus/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE) then if (player:hasKeyItem(FOOD_OFFERINGS)) then -- We have the offerings player:startEvent(0x002d); else if (player:getVar("laa_talk") == 1) then -- npc: You want your offering back? player:startEvent(0x002e); elseif (player:getVar("laa_talk") == 2) then -- npc: You'll have to crawl back to treasure chamber, etc player:startEvent(0x002f); else -- We don't have the offerings yet or anymore player:startEvent(0x0030); end end else player:startEvent(0x0030); end end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x002d) then player:delKeyItem(FOOD_OFFERINGS); player:setVar("laa_talk",1); if (player:hasKeyItem(DRINK_OFFERINGS) == false) then player:setVar("MissionStatus",2); end elseif (csid == 0x002e) then player:setVar("laa_talk",2); end end;
gpl-3.0
nicholas-leonard/nn
Max.lua
8
1917
local Max, parent = torch.class('nn.Max', 'nn.Module') function Max:__init(dimension, nInputDims) parent.__init(self) dimension = dimension or 1 self.dimension = dimension -- do not assign default value to nInputDims or it will break backward compatibility self.nInputDims = nInputDims end function Max:_getPositiveDimension(input) local dimension = self.dimension if dimension < 0 then dimension = input:dim() + dimension + 1 elseif self.nInputDims and input:dim()==(self.nInputDims+1) then dimension = dimension + 1 end return dimension end function Max:_lazyInit() self._output = self._output or self.output.new() if not self._indices then if torch.typename(self.output):find('torch%.Cuda.*Tensor') then self._indices = torch.CudaLongTensor and torch.CudaLongTensor() or torch.CudaTensor() else self._indices = torch.LongTensor() end end end function Max:updateOutput(input) self:_lazyInit() local dimension = self:_getPositiveDimension(input) torch.max(self._output, self._indices, input, dimension) if input:dim() > 1 then self.output:set(self._output:select(dimension, 1)) else self.output:set(self._output) end return self.output end function Max:updateGradInput(input, gradOutput) self:_lazyInit() local dimension = self:_getPositiveDimension(input) local gradOutputView if input:dim() > 1 then gradOutputView = nn.utils.addSingletonDimension(gradOutput, dimension) else gradOutputView = gradOutput end self.gradInput:resizeAs(input):zero():scatter(dimension, self._indices, gradOutputView) return self.gradInput end function Max:type(type, tensorCache) self._indices = nil parent.type(self, type, tensorCache) return self end function Max:clearState() nn.utils.clear(self, '_indices', '_output') return parent.clearState(self) end
bsd-3-clause
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Charmealaut.lua
38
1045
----------------------------------- -- Area: Northern San d'Oria -- NPC: Charmealaut -- Type: Merchant -- @zone: 231 -- @pos 0.000 -0.501 29.303 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0300); 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
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/protocols/ppp/luasrc/model/cbi/admin_network/proto_ppp.lua
59
3761
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local device, username, password local ipv6, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty*S*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", Flag, "ipv6", translate("Enable IPv6 negotiation on the PPP link")) ipv6.default = ipv6.disabled end defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)"
gpl-2.0
thesabbir/luci
applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/mactodevinfo.lua
61
1058
-- Copyright 2009 Daniel Dickinson -- Licensed to the public under the Apache License 2.0. m = Map("mactodevinfo", luci.i18n.translate("MAC Device Info Overrides"), translate("Override the information returned by the MAC to Device Info Script (mac-to-devinfo) for a specified range of MAC Addresses")) s = m:section(TypedSection, "mactodevinfo", translate("MAC Device Override"), translate("MAC range and information used to override system and IEEE databases")) s.addremove = true s.anonymous = true v = s:option(Value, "name", translate("Name")) v.optional = true v = s:option(Value, "maclow", translate("Beginning of MAC address range")) v.optional = false v = s:option(Value, "machigh", translate("End of MAC address range")) v.optional = false v = s:option(Value, "vendor", translate("Vendor")) v.optional = false v = s:option(Value, "devtype", translate("Device Type")) v.optional = false v = s:option(Value, "model", translate("Model")) v.optional = false v = s:option(Value, "ouiowneroverride", translate("OUI Owner")) v.optional = true return m
apache-2.0
nasomi/darkstar
scripts/globals/items/marinara_pizza_+1.lua
14
1646
----------------------------------------- -- ID: 5744 -- Item: marinara_pizza +1 -- Food Effect: 4hours, All Races ----------------------------------------- -- Health Points 25 -- Attack +21% (cap 55) -- Accuracy +11% (cap 58) -- Undead Killer ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5744); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 25); target:addMod(MOD_FOOD_ATTP, 21); target:addMod(MOD_FOOD_ATT_CAP, 55); target:addMod(MOD_FOOD_ACCP, 11); target:addMod(MOD_FOOD_ACC_CAP, 58); target:addMod(MOD_UNDEAD_KILLER, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 25); target:delMod(MOD_FOOD_ATTP, 21); target:delMod(MOD_FOOD_ATT_CAP, 55); target:delMod(MOD_FOOD_ACCP, 11); target:delMod(MOD_FOOD_ACC_CAP, 58); target:delMod(MOD_UNDEAD_KILLER, 5); end;
gpl-3.0
nasomi/darkstar
scripts/globals/abilities/tranquility.lua
28
1191
----------------------------------- -- Ability: Tranquility -- Your next white magic spell will generate less enmity. -- Obtained: Scholar Level 75 Tier 2 Merit Points -- Recast Time: Stratagem Charge -- Duration: 1 white magic spell or 60 seconds, whichever occurs first -- -- Level |Charges |Recharge Time per Charge -- ----- -------- --------------- -- 10 |1 |4:00 minutes -- 30 |2 |2:00 minutes -- 50 |3 |1:20 minutes -- 70 |4 |1:00 minute -- 90 |5 |48 seconds ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_TRANQUILITY) then return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) player:addStatusEffect(EFFECT_TRANQUILITY,player:getMerit(MERIT_TRANQUILITY),0,60); return EFFECT_TRANQUILITY; end;
gpl-3.0
Ingenious-Gaming/Starfall
lua/starfall/sfderma.lua
1
22972
-- Starfall Derma -- This is for easily creating derma ui in the style of the Starfall Editor -- Any derma added should not have anything to do with SF.Editor table apart from design elements e.g. colours, icons -- Starfall Frame PANEL = {} PANEL.windows = {} function PANEL:Init () self.windows[ #self.windows + 1 ] = self self.lockParent = nil self.lockChildren = {} self.locked = false local frame = self self:ShowCloseButton( false ) self:SetDraggable( true ) self:SetSizable( true ) self:SetScreenLock( true ) self:SetDeleteOnClose( false ) self:MakePopup() self:SetVisible( false ) self.components = {} self._PerformLayout = self.PerformLayout function self:PerformLayout ( ... ) local w, h = self:GetSize() if w < 105 + self.components[ "buttonHolder" ]:GetWide() then w = 105 + self.components[ "buttonHolder" ]:GetWide() end if h < 315 then h = 315 end self:SetSize( w, h ) self:_PerformLayout( ... ) end -- Button Holder local buttonHolder = vgui.Create( "DPanel", self ) buttonHolder.buttons = {} buttonHolder.Paint = function () end buttonHolder:SetHeight( 22 ) local spacing = 3 function buttonHolder:PerformLayout ( ... ) local wide = 0 for k, v in pairs( self.buttons ) do wide = wide + v.button:GetWide() + spacing end self:SetWide( wide ) self:SetPos( frame:GetWide() - 5 - self:GetWide(), 5 ) local pos = self:GetWide() + spacing for k, v in pairs( self.buttons ) do pos = pos - spacing - v.button:GetWide() v.button:SetPos( pos, 0 ) end end function buttonHolder:addButton ( name, button ) self.buttons[ #self.buttons + 1 ] = { name = name, button = button } button:PerformLayout() self:PerformLayout() end function buttonHolder:getButton ( buttonName ) for k, v in pairs( self.buttons ) do if v.name == buttonName then return v.button end end end function buttonHolder:removeButton ( button ) if button == nil then return end for k, v in pairs( self.buttons ) do if v.button == button or v.name == button then v.button:Remove() self.buttons[ k ] = nil end end end self:AddComponent( "buttonHolder", buttonHolder ) -- End Button Holder local buttonClose = vgui.Create( "StarfallButton", buttonHolder ) buttonClose:SetText( "Close" ) function buttonClose:DoClick () frame:close() end buttonHolder:addButton( "Close", buttonClose ) local buttonLock = vgui.Create( "StarfallButton", buttonHolder ) buttonLock:SetText( "Unlocked" ) function buttonLock:DoClick () if self.active then self.active = false self:SetText( "Unlocked" ) frame.locked = false else if frame.lockParent then self.active = true self:SetText( "Locked" ) frame.locked = true end end end buttonHolder:addButton( "Lock", buttonLock ) end function PANEL:Think () -- Overwriting default think function, mostly copied from default function local mousex = math.Clamp( gui.MouseX(), 1, ScrW() - 1 ) local mousey = math.Clamp( gui.MouseY(), 1, ScrH() - 1 ) self.Dragged = false self.Resized = false if self.Dragging and not self.locked then self.Dragged = true local x = mousex - self.Dragging[ 1 ] local y = mousey - self.Dragging[ 2 ] -- Lock to screen bounds if screenlock is enabled if self:GetScreenLock() then x = math.Clamp( x, 0, ScrW() - self:GetWide() ) y = math.Clamp( y, 0, ScrH() - self:GetTall() ) end -- Edge snapping local minChildX = ScrW() local minX = 0 for k, v in pairs( self.lockChildren ) do if v.locked then if v:GetPos() < minChildX then minChildX = v:GetPos() minX = v:GetWide() end end end if minChildX > x then minX = 0 end local maxChildX = 0 local maxX = 0 for k, v in pairs( self.lockChildren ) do if v.locked then if v:GetPos() + v:GetWide() > maxChildX then maxChildX = v:GetPos() + v:GetWide() maxX = v:GetWide() end end end if maxChildX < x + self:GetWide() then maxX = 0 end if x < 10 and x > -10 then x = 0 elseif x + self:GetWide() > ScrW() - 10 and x + self:GetWide() < ScrW() + 10 then x = ScrW() - self:GetWide() elseif x < minX + 10 and x > minX - 10 then x = minX elseif x + self:GetWide() > ScrW() - maxX - 10 and x + self:GetWide() < ScrW() - maxX + 10 then x = ScrW() - maxX - self:GetWide() end if y < 10 then y = 0 elseif y + self:GetTall() > ScrH() - 10 then y = ScrH() - self:GetTall() end for k, v in pairs( self.windows ) do if v == self or not v:IsVisible() or table.HasValue( self.lockChildren, v ) and v.locked then goto skip end local vx, vy = v:GetPos() local snapped = false self.lockParent = nil v:removeLockChild( self ) -- Not very easy to read but it works if y >= vy and y <= vy + v:GetTall() or y + self:GetTall() >= vy and y + self:GetTall() <= vy + v:GetTall() or y <= vy and y + self:GetTall() >= vy + v:GetTall() then if x > vx - 10 and x < vx + 10 then x = vx self:lock( v ) snapped = true elseif x > vx + v:GetWide() - 10 and x < vx + v:GetWide() + 10 then x = vx + v:GetWide() self:lock( v ) snapped = true elseif x + self:GetWide() > vx - 10 and x + self:GetWide() < vx + 10 then x = vx - self:GetWide() self:lock( v ) snapped = true elseif x + self:GetWide() > vx + v:GetWide() - 10 and x + self:GetWide() < vx + v:GetWide() + 10 then x = vx + v:GetWide() - self:GetWide() self:lock( v ) snapped = true end end if x >= vx and x <= vx + v:GetWide() or x + self:GetWide() >= vx and x + self:GetWide() <= vx + v:GetWide() or x <= vx and x + self:GetWide() >= vx + v:GetWide() then if y > vy - 10 and y < vy + 10 then y = vy self:lock( v ) snapped = true elseif y > vy + v:GetTall() - 10 and y < vy + v:GetTall() + 10 then y = vy + v:GetTall() self:lock( v ) snapped = true elseif y + self:GetTall() > vy - 10 and y + self:GetTall() < vy + 10 then y = vy - self:GetTall() self:lock( v ) snapped = true elseif y + self:GetTall() > vy + v:GetTall() - 10 and y + self:GetTall() < vy + v:GetTall() + 10 then y = vy + v:GetTall() - self:GetTall() self:lock( v ) snapped = true end end if snapped then break end ::skip:: end local dx, dy = self:GetPos() dx = x - dx dy = y - dy self:SetPos( x, y ) self:moveLockChildren( dx, dy ) end if self.Sizing then self.Resized = true local x = self.Sizing[ 1 ] and mousex - self.Sizing[ 1 ] or self:GetWide() local y = self.Sizing[ 2 ] and mousey - self.Sizing[ 2 ] or self:GetTall() local px, py = self:GetPos() if x < self.m_iMinWidth then x = self.m_iMinWidth elseif x > ScrW() - px and self:GetScreenLock() then x = ScrW() - px end if y < self.m_iMinHeight then y = self.m_iMinHeight elseif y > ScrH() - py and self:GetScreenLock() then y = ScrH() - py end for k, v in pairs( self.windows ) do if v == self or not v:IsVisible() then goto skip end local vx, vy = v:GetPos() -- Not very easy to read but it works if py >= vy and py <= vy + v:GetTall() or py + y >= vy and py + y <= vy + v:GetTall() or py <= vy and py + y >= vy + v:GetTall() then if px + x > vx - 10 and px + x < vx + 10 then x = vx - px elseif px + x > vx + v:GetWide() - 10 and px + x < vx + v:GetWide() + 10 then x = vx + v:GetWide() - px end end if px >= vx and px <= vx + v:GetWide() or px + x >= vx and px + x <= vx + v:GetWide() or px <= vx and px + x >= vx + v:GetWide() then if py + y > vy - 10 and py + y < vy + 10 then y = vy - py elseif py + y > vy + v:GetTall() - 10 and py + y < vy + v:GetTall() + 10 then y = vy + v:GetTall() - py end end ::skip:: end self:SetSize( x, y ) end if self.Hovered and self.m_bSizable and mousex > ( self.x + self:GetWide() - 20 ) and mousey > ( self.y + self:GetTall() - 20 ) then self:SetCursor( "sizenwse" ) elseif self.Hovered and self.m_bSizable and mousex > ( self.x + self:GetWide() - 5 ) then self:SetCursor( "sizewe" ) elseif self.Hovered and self.m_bSizable and mousey > ( self.y + self:GetTall() - 5 ) then self:SetCursor( "sizens" ) elseif self.Hovered and self:GetDraggable() and mousey < ( self.y + 24 ) and not self.locked then self:SetCursor( "sizeall" ) else self:SetCursor( "arrow" ) end -- Don't allow the frame to go higher than 0 if self.y < 0 then self:SetPos( self.x, 0 ) end self:OnThink() self.Dragged = nil self.Resized = nil end function PANEL:OnThink () end function PANEL:OnMousePressed () -- Pretty much copied from default function again if self.m_bSizable then if gui.MouseX() > ( self.x + self:GetWide() - 20 ) and gui.MouseY() > ( self.y + self:GetTall() - 20 ) then self.Sizing = { gui.MouseX() - self:GetWide(), gui.MouseY() - self:GetTall() } self:MouseCapture( true ) return end if gui.MouseX() > ( self.x + self:GetWide() - 5 ) then self.Sizing = { gui.MouseX() - self:GetWide(), nil } self:MouseCapture( true ) return end if gui.MouseY() > ( self.y + self:GetTall() - 5 ) then self.Sizing = { nil, gui.MouseY() - self:GetTall() } self:MouseCapture( true ) return end end if self:GetDraggable() and gui.MouseY() < ( self.y + 24 ) then self.Dragging = { gui.MouseX() - self.x, gui.MouseY() - self.y } self:MouseCapture( true ) return end end function PANEL:AddComponent ( name, component ) self.components[ name ] = component end function PANEL:addLockChild ( frame ) if table.HasValue( self.lockChildren, frame ) then return end self.lockChildren[ #self.lockChildren + 1 ] = frame end function PANEL:removeLockChild ( frame ) if not table.HasValue( self.lockChildren, frame ) then return end table.RemoveByValue( self.lockChildren, frame ) end function PANEL:setLockParent ( frame ) self.lockParent = frame end function PANEL:lock ( frame ) self:setLockParent( frame ) frame:addLockChild( self ) end function PANEL:moveLockChildren ( x, y ) for k, v in pairs( self.lockChildren ) do if v.locked then local vx, vy = v:GetPos() v:SetPos( vx + x, vy + y ) v:moveLockChildren( x, y ) end end end PANEL.Paint = function ( panel, w, h ) draw.RoundedBox( 0, 0, 0, w, h, SF.Editor.colors.dark ) end function PANEL:open () for k, v in pairs( self.lockChildren ) do if v.locked then v:open() end end self:SetVisible( true ) self:SetKeyBoardInputEnabled( true ) self:MakePopup() self:InvalidateLayout( true ) self:OnOpen() end function PANEL:close () for k, v in pairs( self.lockChildren ) do if v.locked then v:close() end end self:OnClose() self:SetKeyBoardInputEnabled( false ) self:Close() end function PANEL:OnOpen () end function PANEL:OnClose () end vgui.Register( "StarfallFrame", PANEL, "DFrame" ) -- End Starfall Frame -------------------------------------------------------------- -------------------------------------------------------------- -- Starfall Button PANEL = {} function PANEL:Init () self:SetText( "" ) self:SetSize( 22, 22 ) end function PANEL:SetIcon ( icon ) self.icon = SF.Editor.icons[ icon ] end function PANEL:PerformLayout () if self:GetText() ~= "" then self:SizeToContentsX() self:SetWide( self:GetWide() + 14 ) end end PANEL.Paint = function ( button, w, h ) if button.Hovered or button.active then draw.RoundedBox( 0, 0, 0, w, h, button.backgroundHoverCol or SF.Editor.colors.med ) else draw.RoundedBox( 0, 0, 0, w, h, button.backgroundCol or SF.Editor.colors.meddark ) end if button.icon then surface.SetDrawColor( SF.Editor.colors.medlight ) surface.SetMaterial( button.icon ) surface.DrawTexturedRect( 2, 2, w - 4, h - 4 ) end end function PANEL:UpdateColours ( skin ) return self:SetTextStyleColor( self.labelCol or SF.Editor.colors.light ) end function PANEL:SetHoverColor ( col ) self.backgroundHoverCol = col end function PANEL:SetColor ( col ) self.backgroundCol = col end function PANEL:SetLabelColor ( col ) self.labelCol = col end function PANEL:DoClick () end vgui.Register( "StarfallButton", PANEL, "DButton" ) -- End Starfall Button -------------------------------------------------------------- -------------------------------------------------------------- -- Starfall Panel PANEL = {} PANEL.Paint = function ( panel, w, h ) draw.RoundedBox( 0, 0, 0, w, h, SF.Editor.colors.light ) end vgui.Register( "StarfallPanel", PANEL, "DPanel" ) -- End Starfall Panel -------------------------------------------------------------- -------------------------------------------------------------- -- Tab Holder PANEL = {} function PANEL:Init () self:SetTall( 22 ) self.offsetTabs = 0 self.tabs = {} local parent = self self.offsetRight = vgui.Create( "StarfallButton", self ) self.offsetRight:SetVisible( false ) self.offsetRight:SetSize( 22, 22 ) self.offsetRight:SetIcon( "arrowr" ) function self.offsetRight:PerformLayout () local wide = 0 if parent.offsetLeft:IsVisible() then wide = parent.offsetLeft:GetWide() + 2 end for i = parent.offsetTabs + 1, #parent.tabs do if wide + parent.tabs[ i ]:GetWide() > parent:GetWide() - self:GetWide() - 2 then break else wide = wide + parent.tabs[ i ]:GetWide() + 2 end end self:SetPos( wide, 0 ) end function self.offsetRight:DoClick () parent.offsetTabs = parent.offsetTabs + 1 if parent.offsetTabs > #parent.tabs - 1 then parent.offsetTabs = #parent.tabs - 1 end parent:InvalidateLayout() end self.offsetLeft = vgui.Create( "StarfallButton", self ) self.offsetLeft:SetVisible( false ) self.offsetLeft:SetSize( 22, 22 ) self.offsetLeft:SetIcon( "arrowl" ) function self.offsetLeft:DoClick () parent.offsetTabs = parent.offsetTabs - 1 if parent.offsetTabs < 0 then parent.offsetTabs = 0 end parent:InvalidateLayout() end self.menuoptions = {} self.menuoptions[ #self.menuoptions + 1 ] = { "Close", function () if not self.targetTab then return end self:removeTab( self.targetTab ) self.targetTab = nil end } self.menuoptions[ #self.menuoptions + 1 ] = { "Close Other Tabs", function () if not self.targetTab then return end local n = 1 while #self.tabs ~= 1 do v = self.tabs[ n ] if v ~= self.targetTab then self:removeTab( v ) else n = 2 end end self.targetTab = nil end } end PANEL.Paint = function () end function PANEL:PerformLayout () local parent = self:GetParent() self:SetWide( parent:GetWide() - 10 ) self.offsetRight:PerformLayout() self.offsetLeft:PerformLayout() local offset = 0 if self.offsetLeft:IsVisible() then offset = self.offsetLeft:GetWide() + 2 end for i = 1, self.offsetTabs do offset = offset - self.tabs[ i ]:GetWide() - 2 end local bool = false for k, v in pairs( self.tabs ) do v:SetPos( offset, 0 ) if offset < 0 then v:SetVisible( false ) elseif offset + v:GetWide() > self:GetWide() - self.offsetRight:GetWide() - 2 then v:SetVisible( false ) bool = true else v:SetVisible( true ) end offset = offset + v:GetWide() + 2 end if bool then self.offsetRight:SetVisible( true ) else self.offsetRight:SetVisible( false ) end if self.offsetTabs > 0 then self.offsetLeft:SetVisible( true ) else self.offsetLeft:SetVisible( false ) end end function PANEL:addTab ( text ) local panel = self local tab = vgui.Create( "StarfallButton", self ) tab:SetText( text ) tab.isTab = true function tab:DoClick () panel:selectTab( self ) end function tab:DoRightClick () panel.targetTab = self local menu = vgui.Create( "DMenu", panel:GetParent() ) for k, v in pairs( panel.menuoptions ) do local option, func = v[ 1 ], v[ 2 ] if func == "SPACER" then menu:AddSpacer() else menu:AddOption( option, func ) end end menu:Open() end function tab:DoMiddleClick () panel:removeTab( self ) end self.tabs[ #self.tabs + 1 ] = tab return tab end function PANEL:removeTab ( tab ) local tabIndex if type( tab ) == "number" then tabIndex = tab tab = self.tabs[ tab ] else tabIndex = self:getTabIndex( tab ) end table.remove( self.tabs, tabIndex ) tab:Remove() self:OnRemoveTab( tabIndex ) end function PANEL:getActiveTab () for k,v in pairs( self.tabs ) do if v.active then return v end end end function PANEL:getTabIndex ( tab ) return table.KeyFromValue( self.tabs, tab ) end function PANEL:selectTab ( tab ) if type( tab ) == "number" then tab = self.tabs[ tab ] end if tab == nil then return end if self:getActiveTab() == tab then return end for k,v in pairs( self.tabs ) do v.active = false end tab.active = true if self:getTabIndex( tab ) <= self.offsetTabs then self.offsetTabs = self:getTabIndex( tab ) - 1 elseif not tab:IsVisible() then while not tab:IsVisible() do self.offsetTabs = self.offsetTabs + 1 self:PerformLayout() end end end function PANEL:OnRemoveTab ( tabIndex ) end vgui.Register( "StarfallTabHolder", PANEL, "DPanel" ) -- End Tab Holder -------------------------------------------------------------- -------------------------------------------------------------- -- File Tree local invalid_filename_chars = { ["*"] = "", ["?"] = "", [">"] = "", ["<"] = "", ["|"] = "", ["\\"] = "", ['"'] = "", } PANEL = {} function PANEL:Init () end function PANEL:setup ( folder ) self.folder = folder self.Root = self.RootNode:AddFolder( folder, folder, "DATA", true ) self.Root:SetExpanded( true ) end function PANEL:reloadTree () self.Root:Remove() self:setup( self.folder ) end function PANEL:DoRightClick ( node ) self:openMenu( node ) end function PANEL:openMenu ( node ) local menu if node:GetFileName() then menu = "file" elseif node:GetFolder() then menu = "folder" end self.menu = vgui.Create( "DMenu", self:GetParent() ) if menu == "file" then self.menu:AddOption( "Open", function () self:OnNodeSelected( node ) end ) self.menu:AddSpacer() self.menu:AddOption( "Rename", function () Derma_StringRequestNoBlur( "Rename file", "", string.StripExtension( node:GetText() ), function ( text ) if text == "" then return end text = string.gsub( text, ".", invalid_filename_chars ) local saveFile = "starfall/"..text..".txt" local contents = file.Read( node:GetFileName() ) file.Delete( node:GetFileName() ) file.Write( saveFile, contents ) SF.AddNotify( LocalPlayer(), "File renamed as " .. saveFile .. ".", NOTIFY_GENERIC, 7, NOTIFYSOUND_DRIP3 ) self:reloadTree() end ) end ) self.menu:AddSpacer() self.menu:AddOption( "Delete", function () Derma_Query( "Are you sure you want to delete this file?", "Delete file", "Delete", function () file.Delete( node:GetFileName() ) SF.AddNotify( LocalPlayer(), "File deleted: " .. node:GetFileName(), NOTIFY_GENERIC, 7, NOTIFYSOUND_DRIP3 ) self:reloadTree() end, "Cancel" ) end ) elseif menu == "folder" then self.menu:AddOption( "New file", function () Derma_StringRequestNoBlur( "New file", "", "", function ( text ) if text == "" then return end text = string.gsub( text, ".", invalid_filename_chars ) local saveFile = node:GetFolder().."/"..text..".txt" file.Write( saveFile, "" ) SF.AddNotify( LocalPlayer(), "New file: " .. saveFile, NOTIFY_GENERIC, 7, NOTIFYSOUND_DRIP3 ) self:reloadTree() end ) end ) self.menu:AddSpacer() self.menu:AddOption( "New folder", function () Derma_StringRequestNoBlur( "New folder", "", "", function ( text ) if text == "" then return end text = string.gsub( text, ".", invalid_filename_chars ) local saveFile = node:GetFolder().."/"..text file.CreateDir( saveFile ) SF.AddNotify( LocalPlayer(), "New folder: " .. saveFile, NOTIFY_GENERIC, 7, NOTIFYSOUND_DRIP3 ) self:reloadTree() end ) end ) end self.menu:Open() end derma.DefineControl( "StarfallFileTree", "", PANEL, "DTree" ) -- End File Tree -------------------------------------------------------------- -------------------------------------------------------------- -- File Browser PANEL = {} function PANEL:Init () self:Dock( FILL ) self:DockMargin( 0, 5, 0, 0 ) self.Paint = function () end local tree = vgui.Create( "StarfallFileTree", self ) tree:Dock( FILL ) self.tree = tree local searchBox = vgui.Create( "DTextEntry", self ) searchBox:Dock( TOP ) searchBox:SetValue( "Search..." ) searchBox._OnGetFocus = searchBox.OnGetFocus function searchBox:OnGetFocus () if self:GetValue() == "Search..." then self:SetValue( "" ) end searchBox:_OnGetFocus() end searchBox._OnLoseFocus = searchBox.OnLoseFocus function searchBox:OnLoseFocus () if self:GetValue() == "" then self:SetText( "Search..." ) end searchBox:_OnLoseFocus() end function searchBox:OnChange () if self:GetValue() == "" then tree:reloadTree() return end tree.Root.ChildNodes:Clear() local function containsFile ( dir, search ) local files, folders = file.Find( dir .. "/*", "DATA" ) for k, file in pairs( files ) do if string.find( string.lower( file ), string.lower( search ) ) then return true end end for k, folder in pairs( folders ) do if containsFile( dir .. "/" .. folder, search ) then return true end end return false end local function addFiles ( search, dir, node ) local allFiles, allFolders = file.Find( dir .. "/*", "DATA" ) for k, v in pairs( allFolders ) do if containsFile( dir .. "/" .. v, search ) then local newNode = node:AddNode( v ) newNode:SetExpanded( true ) addFiles( search, dir .. "/" .. v, newNode ) end end for k, v in pairs( allFiles ) do if string.find( string.lower( v ), string.lower( search ) ) then node:AddNode( v, "icon16/page_white.png" ) end end end addFiles( self:GetValue():PatternSafe(), "starfall", tree.Root ) tree.Root:SetExpanded( true ) end self.searchBox = searchBox end function PANEL:getComponents () return self.searchBox, self.tree end derma.DefineControl( "StarfallFileBrowser", "", PANEL, "DPanel" ) -- End File Browser
bsd-3-clause
nasomi/darkstar
scripts/zones/Windurst_Waters/npcs/Fuepepe.lua
17
3657
----------------------------------- -- Area: Windurst Waters -- NPC: Fuepepe -- Starts and Finishes Quest: Teacher's Pet -- Involved in Quest: Making the grade, Class Reunion -- @zone = 238 -- @pos = 161 -2 161 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED and player:getVar("QuestMakingTheGrade_prog") == 0) then if (trade:hasItemQty(544,1) and trade:getItemCount() == 1 and trade:getGil() == 0) then player:startEvent(0x01c7); -- Quest Progress: Test Papers Shown and told to deliver them to principal end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local gradestatus = player:getQuestStatus(WINDURST,MAKING_THE_GRADE); local prog = player:getVar("QuestMakingTheGrade_prog"); -- 1 = answers found -- 2 = gave test answers to principle -- 3 = spoke to chomoro if (player:getQuestStatus(WINDURST,TEACHER_S_PET) == QUEST_COMPLETED and gradestatus == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >=3 and player:getQuestStatus(WINDURST,LET_SLEEPING_DOGS_LIE) ~= QUEST_ACCEPTED) then player:startEvent(0x01ba); -- Quest Start elseif (gradestatus == QUEST_ACCEPTED) then if (prog == 0) then player:startEvent(0x01bb); -- Get Test Sheets Reminder elseif (prog == 1) then player:startEvent(0x01c8); -- Deliver Test Sheets Reminder elseif (prog == 2 or prog == 3) then player:startEvent(0x01ca); -- Quest Finish end elseif (gradestatus == QUEST_COMPLETED and player:needToZone() == true) then player:startEvent(0x01cb); -- After Quest ------------------------------------------------------- -- Class Reunion elseif (player:getQuestStatus(WINDURST,CLASS_REUNION) == QUEST_ACCEPTED and player:getVar("ClassReunionProgress") >= 3 and player:getVar("ClassReunion_TalkedToFupepe") ~= 1) then player:startEvent(0x0331); -- he tells you about Uran-Mafran ------------------------------------------------------- else player:startEvent(0x1a7); -- Standard Conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x01ba and option == 1) then -- Quest Start player:addQuest(WINDURST,MAKING_THE_GRADE); elseif (csid == 0x01c7) then -- Quest Progress: Test Papers Shown and told to deliver them to principal player:setVar("QuestMakingTheGrade_prog",1); elseif (csid == 0x01ca) then -- Quest Finish if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4855); else player:completeQuest(WINDURST,MAKING_THE_GRADE); player:addFame(WINDURST,WIN_FAME*75); player:addItem(4855); player:messageSpecial(ITEM_OBTAINED,4855); player:setVar("QuestMakingTheGrade_prog",0); player:needToZone(true); end elseif (csid == 0x0331) then player:setVar("ClassReunion_TalkedToFupepe",1); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Windurst_Woods/npcs/Jack_of_Spades.lua
33
1329
----------------------------------- -- Area: Windurst Woods -- NPC: Jack of Spades -- Adventurer's Assistant -- Working 100% ------------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); AdventurerCoupon = trade:hasItemQty(536,1); if (AdventurerCoupon == true and count == 1) then player:startEvent(0x271a,GIL_RATE*50); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2719,0,4); 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 == 0x271a) then player:tradeComplete(); player:addGil(GIL_RATE*50); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/bowl_of_eyeball_soup.lua
35
1403
----------------------------------------- -- ID: 4453 -- Item: Bowl of Eyeball Soup -- Food Effect: 180Min, All Races ----------------------------------------- -- Charisma -10 -- Health Regen While Healing 4 -- Accuracy 12 -- Ranged ACC 12 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4453); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_CHR, -10); target:addMod(MOD_HPHEAL, 4); target:addMod(MOD_ACC, 12); target:addMod(MOD_RACC, 12); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_CHR, -10); target:delMod(MOD_HPHEAL, 4); target:delMod(MOD_ACC, 12); target:delMod(MOD_RACC, 12); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Port_Windurst/npcs/Ohruru.lua
17
4679
----------------------------------- -- Area: Windurst Waters -- NPC: Ohruru -- Starts & Finishes Repeatable Quest: Catch me if you can -- Working 90% -- Involved in Quest: Wonder Wands -- Note: Animation for his "Cure" is not functioning. Unable to capture option 1, so if the user says no, he heals them anyways. -- @zone = 240 -- @pos = -108 -5 94 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- player:delQuest(WINDURST,CATCH_IT_IF_YOU_CAN); -- ======== FOR TESTING ONLY ==========----- -- ======== FOR TESTING ONLY ==========----- -- if (player:getVar("QuestCatchItIfYouCan_var") == 0 and player:hasStatusEffect(EFFECT_MUTE) == false and player:hasStatusEffect(EFFECT_BANE) == false and player:hasStatusEffect(EFFECT_PLAGUE) == false) then -- rand = math.random(1,3); -- if (rand == 1) then -- player:addStatusEffect(EFFECT_MUTE,0,0,100); -- elseif (rand == 2) then -- player:addStatusEffect(EFFECT_BANE,0,0,100); -- elseif (rand == 3) then -- player:addStatusEffect(EFFECT_PLAGUE,0,0,100); -- end -- end -- ======== FOR TESTING ONLY ==========----- Catch = player:getQuestStatus(WINDURST,CATCH_IT_IF_YOU_CAN); WonderWands = player:getQuestStatus(WINDURST,WONDER_WANDS); if (WonderWands == QUEST_ACCEPTED) then player:startEvent(0x0102,0,17053); elseif (Catch == 0) then prog = player:getVar("QuestCatchItIfYouCan_var"); if (prog == 0) then player:startEvent(0x00e6); -- CATCH IT IF YOU CAN: Before Quest 1 player:setVar("QuestCatchItIfYouCan_var",1); elseif (prog == 1) then player:startEvent(0x00fd); -- CATCH IT IF YOU CAN: Before Start player:setVar("QuestCatchItIfYouCan_var",2); elseif (prog == 2) then player:startEvent(0x00e7); -- CATCH IT IF YOU CAN: Before Quest 2 end elseif (Catch >= 1 and (player:hasStatusEffect(EFFECT_MUTE) == true or player:hasStatusEffect(EFFECT_BANE) == true or player:hasStatusEffect(EFFECT_PLAGUE) == true)) then player:startEvent(0x00f6); -- CATCH IT IF YOU CAN: Quest Turn In 1 elseif (Catch >= 1 and player:needToZone()) then player:startEvent(0x00ff); -- CATCH IT IF YOU CAN: After Quest elseif (Catch == 1 and player:hasStatusEffect(EFFECT_MUTE) == false and player:hasStatusEffect(EFFECT_BANE) == false and player:hasStatusEffect(EFFECT_PLAGUE) == false) then rand = math.random(1,2); if (rand == 1) then player:startEvent(0x00f8); -- CATCH IT IF YOU CAN: During Quest 1 else player:startEvent(0x00fb); -- CATCH IT IF YOU CAN: During Quest 2 end elseif (WonderWands == QUEST_COMPLETED) then player:startEvent(0x0109); else player:startEvent(0x00e6); -- STANDARD CONVERSATION end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x00e7) then player:addQuest(WINDURST,CATCH_IT_IF_YOU_CAN); elseif (csid == 0x00f6 and option == 0) then player:needToZone(true); if (player:hasStatusEffect(EFFECT_MUTE) == true) then player:delStatusEffect(EFFECT_MUTE); player:addGil(GIL_RATE*1000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1000); elseif (player:hasStatusEffect(EFFECT_BANE) == true) then player:delStatusEffect(EFFECT_BANE); player:addGil(GIL_RATE*1200); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1200); elseif (player:hasStatusEffect(EFFECT_PLAGUE) == true) then player:delStatusEffect(EFFECT_PLAGUE); player:addGil(GIL_RATE*1500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500); end player:setVar("QuestCatchItIfYouCan_var",0); if (player:getQuestStatus(WINDURST,CATCH_IT_IF_YOU_CAN) == QUEST_ACCEPTED) then player:completeQuest(WINDURST,CATCH_IT_IF_YOU_CAN); player:addFame(WINDURST,WIN_FAME*75); else player:addFame(WINDURST,WIN_FAME*8); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Selbina/npcs/Humilitie.lua
39
1459
----------------------------------- -- Area: Selbina -- NPC: Humilitie -- Reports the time remaining before boat arrival. -- @pos 17.979 -2.39 -58.800 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Based on scripts/zones/Mhaura/Dieh_Yamilsiah.lua local timer = 1152 - ((os.time() - 1009810800)%1152); local direction = 0; -- Arrive, 1 for depart local waiting = 216; -- Offset for Mhaura if (timer <= waiting) then direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart" else timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival end player:startEvent(231,timer,direction); 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
nasomi/darkstar
scripts/zones/RuLude_Gardens/npcs/Crooked_Arrow.lua
34
1393
----------------------------------- -- Area: Ru'Lud Gardens -- NPC: Crooked Arrow -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/zones/RuLude_Gardens/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,1) == false) then player:startEvent(10090); else player:startEvent(0x0095); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 10090) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",1,true); end end;
gpl-3.0
vavrusa/luajit-libuv
test/http_test.lua
2
3259
require 'uv/util/strict' local loop = require 'uv.loop' local http = require 'uv.http' local join = require 'uv/util/join' local expect = require 'uv/util/expect' -------------------------------------------------------------------------------- -- basic server -------------------------------------------------------------------------------- loop.run(function() local server = http.listen('127.0.0.1', 7000, function(request) expect.equal(request.ip, '127.0.0.1') expect.equal(request.method, 'GET') expect.equal(request.path, '/path/to/route') expect.equal(request.query, 'a=1&b=2') expect.equal(request.headers['User-Agent'], 'test') return { status = 200, headers = { Expires = '-1' }, body = 'hello world' } end) local response = http.request { url = 'http://127.0.0.1:7000/path/to/route?a=1&b=2', headers = { ['User-Agent'] = 'test' }, } expect.equal(response.status, 200) expect.equal(response.headers['Expires'], '-1') expect.equal(response.headers['Content-Length'], '11') expect.equal(response.body, 'hello world') local response = http.request{ host = '127.0.0.1', port = 7000, path = '/path/to/route', query = 'a=1&b=2', headers = { ['User-Agent'] = 'test' }, } expect.equal(response.status, 200) expect.equal(response.headers['Expires'], '-1') expect.equal(response.headers['Content-Length'], '11') expect.equal(response.body, 'hello world') server:close() end) loop.run(function() local server = http.listen('127.0.0.1', 7000, function(request) expect.equal(request.method, 'POST') return { status = 200 } end) for i = 1, 10 do local response = http.request { url = 'http://127.0.0.1:7000/?a=1&b=2', method = 'post', body = 'b=3&c=4', } collectgarbage() end collectgarbage() server:close() end) -- loop.run(function() -- local response = http.request{ -- url = 'http://pygments.appspot.com/', -- method = 'post', body = 'lang=lua&code=print', -- } -- end) -------------------------------------------------------------------------------- -- manually invoked event loop -------------------------------------------------------------------------------- do local server, response join(coroutine.create(function() server = http.listen('127.0.0.1', 7000, function(request) return { status = 200, body = 'ok' } end) end)) join(coroutine.create(function() response = http.request { url = 'http://127.0.0.1:7000/' } server:close() end)) loop.run() expect.equal(response.body, 'ok') end -------------------------------------------------------------------------------- -- dates -------------------------------------------------------------------------------- do expect.equal(http.format_date(1408986974LL), 'Mon, 25 Aug 2014 17:16:14 GMT') -- expect.equal(http.parse_date('Mon, 25 Aug 2014 17:16:14 GMT'), 1408986974LL) expect.equal(http.format_date(784111777), 'Sun, 06 Nov 1994 08:49:37 GMT') expect.equal(http.parse_date('Sun, 06 Nov 1994 08:49:37 GMT'), 784111777) expect.equal(http.parse_date('Sunday, 06-Nov-94 08:49:37 GMT'), 784111777) expect.equal(http.parse_date('Sun Nov 6 08:49:37 1994'), 784111777) expect.equal(http.parse_date('asdf'), nil) end
mit
nasomi/darkstar
scripts/zones/Castle_Oztroja/MobIDs.lua
65
1606
----------------------------------- -- Area: Castle Oztroja (151) -- Comments: -- posX, posY, posZ -- (Taken from 'mob_spawn_points' table) ----------------------------------- -- Mee_Deggi_the_Punisher Mee_Deggi_the_Punisher=17395800; Mee_Deggi_the_Punisher_PH={ [17395798] = '1', -- -207.840, -0.498, 109.939 [17395766] = '1', -- -178.119, -0.644, 153.039 [17395769] = '1', -- -188.253, -0.087, 158.955 [17395783] = '1', -- -233.116, -0.741, 172.067 [17395784] = '1', -- -254.302, -0.057, 163.759 [17395799] = '1', -- -227.415, -4.340, 145.213 [17395761] = '1', -- -207.370, -0.056, 106.537 [17395775] = '1' -- -235.639, -0.063, 103.280 }; -- Moo_Ouzi_the_Swiftblade Moo_Ouzi_the_Swiftblade=17395816; Moo_Ouzi_the_Swiftblade_PH={ [17395809] = '1', -- -18.415, -0.075, -92.889 [17395813] = '1' -- -38.689, 0.191, -101.068 }; -- Quu_Domi_the_Gallant Quu_Domi_the_Gallant=17395870; Quu_Domi_the_Gallant_PH={ [17395844] = '1', -- 103.948, -1.250, -189.869 [17395845] = '1', -- 67.103, -0.079, -176.981 [17395853] = '1', -- 99.000, -0.181, -149.000 [17395831] = '1', -- 46.861, 0.343, -176.989 [17395868] = '1', -- 35.847, -0.500, -101.685 [17395867] = '1', -- 59.000, -4.000, -131.000 [17395829] = '1' -- 33.832, -0.068, -176.627 }; -- Yaa_Haqa_the_Profane Yaa_Haqa_the_Profane=17395954; Yaa_Haqa_the_Profane_PH={ [17395950] = '1', -- -24.719, -16.250, -139.678 [17395951] = '1', -- -22.395, -16.250, -139.341 [17395952] = '1', -- -25.044, -16.250, -141.534 [17395953] = '1' -- -32.302, -16.250, -139.169 };
gpl-3.0
sbx320/lua_utils
ooplib.lua
1
2776
local __CLASSNAME__ local __BASECLASSES__ local __CLASSES__ = {} local __MEMBERS__ local __IS_STATIC = false function static_class(name) __IS_STATIC = true return class(name) end function maybeExtends(name) if name == extends then return extends else return buildClass(name) end end local __MEMBERNAME__ function buildMember(data) __MEMBERS__[__MEMBERNAME__] = data end function buildClass(definition) __CLASSES__[__CLASSNAME__] = definition _G[__CLASSNAME__] = definition definition.__CLASSNAME__ = __CLASSNAME__ definition.__members__ = __MEMBERS__ local parents = {} for k, v in pairs(__BASECLASSES__) do parents[k] = __CLASSES__[v] end -- Prepare parent members local defaults = {} for k, class in pairs(parents) do for name, member in pairs(class.__members__) do defaults[name] = member.default end end for k, v in pairs(__MEMBERS__) do defaults[k] = v.default end setmetatable(definition, { __index = function(self, key) for k, v in pairs(parents) do if v[key] then return v[key] end end end; __call = function(...) local member = defaults local instance = setmetatable({ __members__ = member, __class__ = definition }, { __index = function(self, key) if definition.__members__[key] then if definition.__members__[key].get then return definition.__members__[key].get(self) end return self.__members__[key] end return definition[key] end; -- Todo: Other metamethods __newindex = function(self, key, value) if definition.__members__[key] then if definition.__members__[key].set then if not definition.__members__[key].set(self, value) then return end end self.__members__[key] = value end -- Implicit member creation -- If you want, replace this by an error -- and make sure to add this line above -- to ensure proper setting for non-setter -- members self.__members__[key] = value end }) return instance end; }) if __IS_STATIC then if definition.constructor then definition:constructor() end end __IS_STATIC = false end function class(name) __CLASSNAME__ = name __BASECLASSES__ = {} __MEMBERS__ = {} return maybeExtends end function extends(name) if type(name) == "string" then -- Handle base classes __BASECLASSES__[#__BASECLASSES__+1] = name return extends else -- Handle class definition return buildClass(name) end end function member(name) __MEMBERNAME__ = name __MEMBERS__[name] = {} return buildMember end
mit
nasomi/darkstar
scripts/globals/items/bowl_of_mushroom_stew.lua
35
1464
----------------------------------------- -- ID: 4544 -- Item: mushroom_stew -- Food Effect: 3hours, All Races ----------------------------------------- -- Magic Points 40 -- Strength -1 -- Mind 4 -- MP Recovered While Healing 4 -- Enmity -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4544); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 40); target:addMod(MOD_STR, -1); target:addMod(MOD_MND, 4); target:addMod(MOD_MPHEAL, 4); target:addMod(MOD_ENMITY, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 40); target:delMod(MOD_STR, -1); target:delMod(MOD_MND, 4); target:delMod(MOD_MPHEAL, 4); target:delMod(MOD_ENMITY, -4); end;
gpl-3.0
coolflyreg/gs
common/protocols/validator.lua
1
1855
local errorcode = require("protocols.errorcode") validator = validator or { checkLegalCharacters = function(str, legalCharacters) -- return true for legal, false for illegal local i = 1 local j = 1 local byte_str = 0 local byte_chars = 0 local contains = false for i = 1, string.len(str) do byte_str = string.byte(str, i) contains = false for j = 1, string.len(legalCharacters) do byte_chars = string.byte(legalCharacters, j) if (byte_str == byte_chars) then contains = true break end end if (not contains) then return false end end return true end, checkUserName = function(username) if (not username or username == "") then return errorcode.USER_NAME_EMPTY end if (string.len(username) < 6 or string.len(username) > 20) then return errorcode.USER_NAME_LENGTH_ERROR end if (not validator.checkLegalCharacters(username, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@")) then return errorcode.USER_NAME_ILLEGAL end return errorcode.OK end, checkPassword = function(password) if (not password or password == "") then return errorcode.PASSWORD_EMPTY end if (string.len(password) < 6 or string.len(password) > 20) then return errorcode.PASSWORD_LENGTH_ERROR end if (not validator.checkLegalCharacters(password, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@!#$%^&*<>,.?;:")) then return errorcode.PASSWORD_ILLEGAL end return errorcode.OK end, } return validator
gpl-2.0
cristiandonosoc/unexperiments
03-Point Of No Return/lib/advanced_tile_loader/external/numberlua.lua
16
2633
-- dmlib.bit -- Bitwise operations implemented entirely in Lua. -- Represents bit arrays as non-negative Lua numbers.[1] -- Can represent 32-bit bit arrays, when Lua is compiled -- with lua_Number being double-precision IEEE 754 floating point. -- -- Based partly on Roberto Ierusalimschy's post -- in http://lua-users.org/lists/lua-l/2002-09/msg00134.html . -- -- References -- -- [1] http://lua-users.org/wiki/FloatingPoint -- -- (c) 2008 David Manura. Licensed under the same terms as Lua (MIT). local function memoize(f) local mt = {} local t = setmetatable({}, mt) function mt:__index(k) local v = f(k); t[k] = v return v end return t end local function make_bitop_uncached(t, m) local function bitop(a, b) local res,p = 0,1 while a ~= 0 and b ~= 0 do local am, bm = a%m, b%m res = res + t[am][bm]*p a = (a - am) / m b = (b - bm) / m p = p*m end res = res + (a+b)*p return res end return bitop end local function make_bitop(t) local op1 = make_bitop_uncached(t,2^1) local op2 = memoize(function(a) return memoize(function(b) return op1(a, b) end) end) return make_bitop_uncached(op2, 2^(t.n or 1)) end local bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4} local F8 = 2^32 - 1 local function bnot(a) return F8 - a end local function band(a,b) return ((a+b) - bxor(a,b))/2 end local function bor(a,b) return F8 - band(F8 - a, F8 - b) end local M = {} M.bxor = bxor M.bnot = bnot M.band = band M.bor = bor return M --[[ LICENSE Copyright (C) 2008, David Manura. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (end license) --]]
mit
mlem/wesnoth
data/ai/micro_ais/cas/ca_herding_dog_move.lua
26
1767
local H = wesnoth.require "lua/helper.lua" local AH = wesnoth.require "ai/lua/ai_helper.lua" local LS = wesnoth.require "lua/location_set.lua" local function get_dog(cfg) local dogs = AH.get_units_with_moves { side = wesnoth.current.side, { "and", cfg.filter }, { "not", { { "filter_adjacent", { side = wesnoth.current.side, { "and", cfg.filter_second } } } } } } return dogs[1] end local ca_herding_dog_move = {} function ca_herding_dog_move:evaluation(ai, cfg) -- As a final step, any dog not adjacent to a sheep moves within herding_perimeter if get_dog(cfg) then return cfg.ca_score end return 0 end function ca_herding_dog_move:execution(ai, cfg) -- We simply move the first dog first, order does not matter local dog = get_dog(cfg) local herding_perimeter = LS.of_pairs(wesnoth.get_locations(cfg.filter_location)) -- Find average distance of herding_perimeter from center local av_dist = 0 herding_perimeter:iter( function(x, y, v) av_dist = av_dist + H.distance_between(x, y, cfg.herd_x, cfg.herd_y) end) av_dist = av_dist / herding_perimeter:size() local best_hex = AH.find_best_move(dog, function(x, y) -- Prefer hexes on herding_perimeter, or close to it -- Or, if dog cannot get there, prefer to be av_dist from the center local rating = 0 if herding_perimeter:get(x, y) then rating = rating + 1000 + math.random(99) / 100. else rating = rating - math.abs(H.distance_between(x, y, cfg.herd_x, cfg.herd_y) - av_dist) + math.random(99) / 100. end return rating end) AH.movefull_stopunit(ai, dog, best_hex) end return ca_herding_dog_move
gpl-2.0
nasomi/darkstar
scripts/globals/abilities/stutter_step.lua
28
8023
----------------------------------- -- Ability: Stutter Step -- Applies Weakened Daze. Lowers the targets magic resistance. If successful, you will earn two Finishing Moves. -- Obtained: Dancer Level 40 -- TP Required: 10% -- Recast Time: 00:05 -- Duration: First Step lasts 1 minute, each following Step extends its current duration by 30 seconds. ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/weaponskills"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getAnimation() ~= 1) then return MSGBASIC_REQUIRES_COMBAT,0; else if (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 10) then return MSGBASIC_NOT_ENOUGH_TP,0; else return 0,0; end end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(EFFECT_TRANCE) then player:delTP(10); end; local hit = 3; local effect = 1; if math.random() <= getHitRate(player,target,true,player:getMod(MOD_STEP_ACCURACY)) then hit = 7; local mjob = player:getMainJob(); local daze = 1; if (mjob == 19) then if (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_1)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_1):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_1); if (player:hasStatusEffect(EFFECT_PRESTO)) then target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30); daze = 3; effect = 3; else target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,duration+30); daze = 2; effect = 2; end elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_2)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_2):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_2); if (player:hasStatusEffect(EFFECT_PRESTO)) then target:addStatusEffect(EFFECT_WEAKENED_DAZE_4,1,0,duration+30); daze = 3; effect = 4; else target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30); daze = 2; effect = 3; end elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_3)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_3):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_3); if (player:hasStatusEffect(EFFECT_PRESTO)) then target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30); daze = 3; effect = 5; else target:addStatusEffect(EFFECT_WEAKENED_DAZE_4,1,0,duration+30); daze = 2; effect = 4; end elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_4)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_4):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_4); if (player:hasStatusEffect(EFFECT_PRESTO)) then daze = 3; else daze = 2; end target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,duration+30); effect = 5; elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_5)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_5):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_5); target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30); daze = 1; effect = 5; else if (player:hasStatusEffect(EFFECT_PRESTO)) then target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,60); daze = 3; effect = 2; else target:addStatusEffect(EFFECT_WEAKENED_DAZE_1,1,0,60); daze = 2; effect = 1; end end; else if (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_1)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_1):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_1); target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,duration+30); effect = 2; elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_2)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_2):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_2); target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30); effect = 3; elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_3)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_3):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_3); target:addStatusEffect(EFFECT_WEAKENED_DAZE_4,1,0,duration+30); effect = 4; elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_4)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_4):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_4); target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30); effect = 5; elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_5)) then local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_5):getDuration(); target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_5); target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30); effect = 5; else target:addStatusEffect(EFFECT_WEAKENED_DAZE_1,1,0,60); effect = 1; end; end if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_1); player:addStatusEffect(EFFECT_FINISHING_MOVE_1+daze,1,0,7200); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_2); player:addStatusEffect(EFFECT_FINISHING_MOVE_2+daze,1,0,7200); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_3); if (daze > 2) then daze = 2; end; player:addStatusEffect(EFFECT_FINISHING_MOVE_3+daze,1,0,7200); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_4); player:addStatusEffect(EFFECT_FINISHING_MOVE_5,1,0,7200); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then else player:addStatusEffect(EFFECT_FINISHING_MOVE_1 - 1 + daze,1,0,7200); end; else ability:setMsg(158); end return effect, getStepAnimation(player:getWeaponSkillType(SLOT_MAIN)), hit; end;
gpl-3.0
nasomi/darkstar
scripts/globals/weaponskills/aeolian_edge.lua
30
1342
-- Aeolian Edge -- Dagger weapon skill -- Delivers an area attack that deals wind elemental damage. Damage varies with TP. -- Skill Level: 290 -- Aligned with the Breeze Gorget, Soil Gorget & Thunder Gorget. -- Aligned with the Breeze Belt, Soil Belt & Thunder Belt. -- Element: Wind -- Skillchain Properties: Impaction / Scission / Detonation -- Modifiers: DEX:28%; INT:28% -- 100%TP 200%TP 300%TP -- 2.75 3.50 4 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 2.75; params.ftp200 = 3.50; params.ftp300 = 4; params.str_wsc = 0.0; params.dex_wsc = 0.28; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.28; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_WIND; params.skill = SKILL_DAG; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.4;params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Maxsteam/99998888
plugins/isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
anthillsocial/bicrophonic1
lib/json.lua
14
15828
----------------------------------------------------------------------------- -- JSON4Lua: JSON encoding / decoding support for the Lua language. -- json Module. -- Author: Craig Mason-Jones -- Homepage: http://json.luaforge.net/ -- Version: 0.9.40 -- This module is released under the MIT License (MIT). -- Please see LICENCE.txt for details. -- -- USAGE: -- This module exposes two functions: -- encode(o) -- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string. -- decode(json_string) -- Returns a Lua object populated with the data encoded in the JSON string json_string. -- -- REQUIREMENTS: -- compat-5.1 if using Lua 5.0 -- -- CHANGELOG -- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix). -- Fixed Lua 5.1 compatibility issues. -- Introduced json.null to have null values in associative arrays. -- encode() performance improvement (more than 50%) through table.concat rather than .. -- Introduced decode ability to ignore /**/ comments in the JSON string. -- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Imports and dependencies ----------------------------------------------------------------------------- local math = require('math') local string = require("string") local table = require("table") local base = _G ----------------------------------------------------------------------------- -- Module declaration ----------------------------------------------------------------------------- module("json") -- Public functions -- Private functions local decode_scanArray local decode_scanComment local decode_scanConstant local decode_scanNumber local decode_scanObject local decode_scanString local decode_scanWhitespace local encodeString local isArray local isEncodable ----------------------------------------------------------------------------- -- PUBLIC FUNCTIONS ----------------------------------------------------------------------------- --- Encodes an arbitrary Lua object / variable. -- @param v The Lua object / variable to be JSON encoded. -- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode) function encode (v) -- Handle nil values if v==nil then return "null" end local vtype = base.type(v) -- Handle strings if vtype=='string' then return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string end -- Handle booleans if vtype=='number' or vtype=='boolean' then return base.tostring(v) end -- Handle tables if vtype=='table' then local rval = {} -- Consider arrays separately local bArray, maxCount = isArray(v) if bArray then for i = 1,maxCount do table.insert(rval, encode(v[i])) end else -- An object, not an array for i,j in base.pairs(v) do if isEncodable(i) and isEncodable(j) then table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j)) end end end if bArray then return '[' .. table.concat(rval,',') ..']' else return '{' .. table.concat(rval,',') .. '}' end end -- Handle null values if vtype=='function' and v==null then return 'null' end base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v)) end --- Decodes a JSON string and returns the decoded value as a Lua data structure / value. -- @param s The string to scan. -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1. -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil, -- and the position of the first character after -- the scanned JSON object. function decode(s, startPos) startPos = startPos and startPos or 1 startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']') local curChar = string.sub(s,startPos,startPos) -- Object if curChar=='{' then return decode_scanObject(s,startPos) end -- Array if curChar=='[' then return decode_scanArray(s,startPos) end -- Number if string.find("+-0123456789.e", curChar, 1, true) then return decode_scanNumber(s,startPos) end -- String if curChar==[["]] or curChar==[[']] then return decode_scanString(s,startPos) end if string.sub(s,startPos,startPos+1)=='/*' then return decode(s, decode_scanComment(s,startPos)) end -- Otherwise, it must be a constant return decode_scanConstant(s,startPos) end --- The null function allows one to specify a null value in an associative array (which is otherwise -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null } function null() return null -- so json.null() will also return null ;-) end ----------------------------------------------------------------------------- -- Internal, PRIVATE functions. -- Following a Python-like convention, I have prefixed all these 'PRIVATE' -- functions with an underscore. ----------------------------------------------------------------------------- --- Scans an array from JSON into a Lua object -- startPos begins at the start of the array. -- Returns the array and the next starting position -- @param s The string being scanned. -- @param startPos The starting position for the scan. -- @return table, int The scanned array as a table, and the position of the next character to scan. function decode_scanArray(s,startPos) local array = {} -- The return value local stringLen = string.len(s) base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s ) startPos = startPos + 1 -- Infinite loop for array elements repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.') local curChar = string.sub(s,startPos,startPos) if (curChar==']') then return array, startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.') object, startPos = decode(s,startPos) table.insert(array,object) until false end --- Scans a comment and discards the comment. -- Returns the position of the next character following the comment. -- @param string s The JSON string to scan. -- @param int startPos The starting position of the comment function decode_scanComment(s, startPos) base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos) local endPos = string.find(s,'*/',startPos+2) base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos) return endPos+2 end --- Scans for given constants: true, false or null -- Returns the appropriate Lua type, and the position of the next character to read. -- @param s The string being scanned. -- @param startPos The position in the string at which to start scanning. -- @return object, int The object (true, false or nil) and the position at which the next character should be -- scanned. function decode_scanConstant(s, startPos) local consts = { ["true"] = true, ["false"] = false, ["null"] = nil } local constNames = {"true","false","null"} for i,k in base.pairs(constNames) do --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k) if string.sub(s,startPos, startPos + string.len(k) -1 )==k then return consts[k], startPos + string.len(k) end end base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos) end --- Scans a number from the JSON encoded string. -- (in fact, also is able to scan numeric +- eqns, which is not -- in the JSON spec.) -- Returns the number, and the position of the next character -- after the number. -- @param s The string being scanned. -- @param startPos The position at which to start scanning. -- @return number, int The extracted number and the position of the next character to scan. function decode_scanNumber(s,startPos) local endPos = startPos+1 local stringLen = string.len(s) local acceptableChars = "+-0123456789.e" while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true) and endPos<=stringLen ) do endPos = endPos + 1 end local stringValue = 'return ' .. string.sub(s,startPos, endPos-1) local stringEval = base.loadstring(stringValue) base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON object into a Lua object. -- startPos begins at the start of the object. -- Returns the object and the next starting position. -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return table, int The scanned object as a table and the position of the next character to scan. function decode_scanObject(s,startPos) local object = {} local stringLen = string.len(s) local key, value base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s) startPos = startPos + 1 repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.') local curChar = string.sub(s,startPos,startPos) if (curChar=='}') then return object,startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.') -- Scan the key key, startPos = decode(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos) startPos = decode_scanWhitespace(s,startPos+1) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) value, startPos = decode(s,startPos) object[key]=value until false -- infinite loop while key-value pairs are found end --- Scans a JSON string from the opening inverted comma or single quote to the -- end of the string. -- Returns the string extracted as a Lua string, -- and the position of the next non-string character -- (after the closing inverted comma or single quote). -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return string, int The extracted string as a Lua string, and the next character to parse. function decode_scanString(s,startPos) base.assert(startPos, 'decode_scanString(..) called without start position') local startChar = string.sub(s,startPos,startPos) base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string') local escaped = false local endPos = startPos + 1 local bEnded = false local stringLen = string.len(s) repeat local curChar = string.sub(s,endPos,endPos) -- Character escaping is only used to escape the string delimiters if not escaped then if curChar==[[\]] then escaped = true else bEnded = curChar==startChar end else -- If we're escaped, we accept the current character come what may escaped = false end endPos = endPos + 1 base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos) until bEnded local stringValue = 'return ' .. string.sub(s, startPos, endPos-1) local stringEval = base.loadstring(stringValue) base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON string skipping all whitespace from the current start position. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached. -- @param s The string being scanned -- @param startPos The starting position where we should begin removing whitespace. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string -- was reached. function decode_scanWhitespace(s,startPos) local whitespace=" \n\r\t" local stringLen = string.len(s) while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do startPos = startPos + 1 end return startPos end --- Encodes a string to be JSON-compatible. -- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-) -- @param s The string to return as a JSON encoded (i.e. backquoted string) -- @return The string appropriately escaped. function encodeString(s) s = string.gsub(s,'\\','\\\\') s = string.gsub(s,'"','\\"') s = string.gsub(s,"'","\\'") s = string.gsub(s,'\n','\\n') s = string.gsub(s,'\t','\\t') return s end -- Determines whether the given Lua type is an array or a table / dictionary. -- We consider any table an array if it has indexes 1..n for its n items, and no -- other data in the table. -- I think this method is currently a little 'flaky', but can't think of a good way around it yet... -- @param t The table to evaluate as an array -- @return boolean, number True if the table can be represented as an array, false otherwise. If true, -- the second returned value is the maximum -- number of indexed elements in the array. function isArray(t) -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable -- (with the possible exception of 'n') local maxIndex = 0 for k,v in base.pairs(t) do if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair if (not isEncodable(v)) then return false end -- All array elements must be encodable maxIndex = math.max(maxIndex,k) else if (k=='n') then if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements else -- Else of (k=='n') if isEncodable(v) then return false end end -- End of (k~='n') end -- End of k,v not an indexed pair end -- End of loop across all pairs return true, maxIndex end --- Determines whether the given Lua object / table / variable can be JSON encoded. The only -- types that are JSON encodable are: string, boolean, number, nil, table and json.null. -- In this implementation, all other types are ignored. -- @param o The object to examine. -- @return boolean True if the object should be JSON encoded, false if it should be ignored. function isEncodable(o) local t = base.type(o) return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null) end
gpl-2.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27001007.lua
1
1113
--BT1-005 Furthering Destruction Champa local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,CHARACTER_CHAMPA,SPECIAL_TRAIT_GOD) ds.AddPlayProcedure(c,COLOR_RED,2,1) --give skill ds.AddSingleAutoCombo(c,0,nil,scard.sktg,scard.skop,DS_EFFECT_FLAG_CARD_CHOOSE,scard.skcon) end scard.dragon_ball_super_card=true scard.combo_cost=1 function scard.skcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttacker():IsControler(tp) end function scard.skfilter(c) return Duel.GetAttacker()==c end function scard.sktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc==Duel.GetAttacker() end if chk==0 then return true end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TARGET) Duel.SelectTarget(tp,scard.skfilter,tp,DS_LOCATION_IN_PLAY,0,1,1,nil) end function scard.skop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if not tc or not tc:IsRelateToSkill(e) then return end --double strike ds.GainSkillDoubleStrike(e:GetHandler(),tc,1,RESET_PHASE+PHASE_DAMAGE) end
gpl-3.0
thesabbir/luci
applications/luci-app-diag-devinfo/luasrc/controller/luci_diag/devinfo_common.lua
61
5427
-- Copyright 2009 Daniel Dickinson -- Licensed to the public under the Apache License 2.0. module("luci.controller.luci_diag.devinfo_common", package.seeall) require("luci.i18n") require("luci.util") require("luci.sys") require("luci.cbi") require("luci.model.uci") local translate = luci.i18n.translate local DummyValue = luci.cbi.DummyValue local SimpleSection = luci.cbi.SimpleSection function index() return -- no-op end function run_processes(outnets, cmdfunc) i = next(outnets, nil) while (i) do outnets[i]["output"] = luci.sys.exec(cmdfunc(outnets, i)) i = next(outnets, i) end end function parse_output(devmap, outnets, haslink, type, mini, debug) local curnet = next(outnets, nil) while (curnet) do local output = outnets[curnet]["output"] local subnet = outnets[curnet]["subnet"] local ports = outnets[curnet]["ports"] local interface = outnets[curnet]["interface"] local netdevs = {} devlines = luci.util.split(output) if not devlines then devlines = {} table.insert(devlines, output) end local j = nil j = next(devlines, j) local found_a_device = false while (j) do if devlines[j] and ( devlines[j] ~= "" ) then found_a_device = true local devtable local row = {} devtable = luci.util.split(devlines[j], ' | ') row["ip"] = devtable[1] if (not mini) then row["mac"] = devtable[2] end if ( devtable[4] == 'unknown' ) then row["vendor"] = devtable[3] else row["vendor"] = devtable[4] end row["type"] = devtable[5] if (not mini) then row["model"] = devtable[6] end if (haslink) then row["config_page"] = devtable[7] end if (debug) then row["raw"] = devlines[j] end table.insert(netdevs, row) end j = next(devlines, j) end if not found_a_device then local row = {} row["ip"] = curnet if (not mini) then row["mac"] = "" end if (type == "smap") then row["vendor"] = luci.i18n.translate("No SIP devices") else row["vendor"] = luci.i18n.translate("No devices detected") end row["type"] = luci.i18n.translate("check other networks") if (not mini) then row["model"] = "" end if (haslink) then row["config_page"] = "" end if (debug) then row["raw"] = output end table.insert(netdevs, row) end local s if (type == "smap") then if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet .. " (" .. subnet .. ":" .. ports .. interfacestring .. ")") end s.template = "diag/smapsection" else if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet .. " (" .. subnet .. interfacestring .. ")") end end s:option(DummyValue, "ip", translate("IP Address")) if (not mini) then s:option(DummyValue, "mac", translate("MAC Address")) end s:option(DummyValue, "vendor", translate("Vendor")) s:option(DummyValue, "type", translate("Device Type")) if (not mini) then s:option(DummyValue, "model", translate("Model")) end if (haslink) then s:option(DummyValue, "config_page", translate("Link to Device")) end if (debug) then s:option(DummyValue, "raw", translate("Raw")) end curnet = next(outnets, curnet) end end function get_network_device(interface) local state = luci.model.uci.cursor_state() state:load("network") local dev return state:get("network", interface, "ifname") end function cbi_add_networks(field) uci.cursor():foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then field:value(section[".name"]) end end ) field.titleref = luci.dispatcher.build_url("admin", "network", "network") end function config_devinfo_scan(map, scannet) local o o = scannet:option(luci.cbi.Flag, "enable", translate("Enable")) o.optional = false o.rmempty = false o = scannet:option(luci.cbi.Value, "interface", translate("Interface")) o.optional = false luci.controller.luci_diag.devinfo_common.cbi_add_networks(o) local scansubnet scansubnet = scannet:option(luci.cbi.Value, "subnet", translate("Subnet")) scansubnet.optional = false o = scannet:option(luci.cbi.Value, "timeout", translate("Timeout"), translate("Time to wait for responses in seconds (default 10)")) o.optional = true o = scannet:option(luci.cbi.Value, "repeat_count", translate("Repeat Count"), translate("Number of times to send requests (default 1)")) o.optional = true o = scannet:option(luci.cbi.Value, "sleepreq", translate("Sleep Between Requests"), translate("Milliseconds to sleep between requests (default 100)")) o.optional = true end
apache-2.0
nasomi/darkstar
scripts/globals/items/loach_slop.lua
35
1529
----------------------------------------- -- ID: 5669 -- Item: loach_slop -- Food Effect: 3Hour,Group Food, All Races ----------------------------------------- -- Accuracy % 7 -- Accuracy Cap 15 -- HP % 7 -- HP Cap 15 -- Evasion 3 -- (Did Not Add Group Food Effect) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5669); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_ACCP, 7); target:addMod(MOD_FOOD_ACC_CAP, 15); target:addMod(MOD_FOOD_HPP, 7); target:addMod(MOD_FOOD_HP_CAP, 15); target:addMod(MOD_EVA, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_ACCP, 7); target:delMod(MOD_FOOD_ACC_CAP, 15); target:delMod(MOD_FOOD_HPP, 7); target:delMod(MOD_FOOD_HP_CAP, 15); target:delMod(MOD_EVA, 3); end;
gpl-3.0
nasomi/darkstar
scripts/globals/chocobo.lua
32
4958
------------------------------------------------- -- Chocobo functions -- Info from: -- http://wiki.ffxiclopedia.org/wiki/Chocobo_Renter -- http://ffxi.allakhazam.com/wiki/Traveling_in_Vana'diel ------------------------------------------------- require("scripts/globals/settings"); --[[----------------------------------------------- Description: chocobo = Zone, { [1] Base price, [2] Amount added to base price, [3] Amount discounted per time interval, [4] Amount of seconds before price decay, [5] Quest "A Chocobo Riding Game" chance } --]]----------------------------------------------- local chocobo = {230,{baseprice = 100,addedprice = 20,decayprice = 5,decaytime = 60,questchance = 0.10}, -- Southern San d'Oria 234,{baseprice = 100,addedprice = 20,decayprice = 5,decaytime = 60,questchance = 0.10}, -- Bastok Mines 241,{baseprice = 100,addedprice = 20,decayprice = 5,decaytime = 60,questchance = 0.10}, -- Windurst Woods 244,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Upper Jeuno 245,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Lower Jeuno 246,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Port Jeuno 250,{baseprice = 90,addedprice = 10,decayprice = 5,decaytime = 60,questchance = 0.10}, -- Kazham 252,{baseprice = 90,addedprice = 10,decayprice = 5,decaytime = 60,questchance = 0.00}, -- Norg 247,{baseprice = 90,addedprice = 10,decayprice = 5,decaytime = 60,questchance = 0.00}, -- Rabao 102,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- La Theine Plateau 108,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Konschtat Highlands 117,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Tahrongi Canyon 114,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Eastern Altepa Desert 124,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Yhoator Jungle 48,{baseprice = 250,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Al Zahbi 51,{baseprice = 200,addedprice = 20,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Wajaom Woodlands 80,{baseprice = 150,addedprice = 20,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Southern San d'Oria [S] 87,{baseprice = 150,addedprice = 20,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Bastok Markets [S] 94,{baseprice = 150,addedprice = 20,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Windurst Waters [S] 82,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Jugner Forest [S] 90,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}, -- Pashhow Marshlands [S] 97,{baseprice = 200,addedprice = 25,decayprice = 5,decaytime = 90,questchance = 0.00}}; -- Meriphataud Mountains [S] --------------------------------------- -- Set chocobo Prices on server start --------------------------------------- function setChocoboPrices() for u = 1, table.getn(chocobo), 2 do SetServerVariable("[CHOCOBO]["..chocobo[u].."]Price", chocobo[u + 1].baseprice); SetServerVariable("[CHOCOBO]["..chocobo[u].."]Time", os.time(t)); end end; --------------------------------------- -- return chocobo Price --------------------------------------- function getChocoboPrice(player) local zone = player:getZoneID(); local price = 0; for u = 1, table.getn(chocobo), 2 do if (chocobo[u] == zone) then local last_price = GetServerVariable("[CHOCOBO]["..zone.."]Price"); local last_time = GetServerVariable("[CHOCOBO]["..zone.."]Time"); price = last_price - (math.floor((os.time(t) - last_time) / chocobo[u + 1].decaytime) * chocobo[u + 1].decayprice); if (price < chocobo[u + 1].baseprice) then price = chocobo[u + 1].baseprice; end break; end end return price; end --------------------------------------- -- update chocobo Price --------------------------------------- function updateChocoboPrice(player, price) local zone = player:getZoneID(); for u = 1, table.getn(chocobo), 2 do if (chocobo[u] == zone) then SetServerVariable("[CHOCOBO]["..chocobo[u].."]Price", price + chocobo[u + 1].addedprice); SetServerVariable("[CHOCOBO]["..chocobo[u].."]Time", os.time(t)); break; end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Yhoator_Jungle/npcs/Emila_RK.lua
30
3051
----------------------------------- -- Area: Yhoator Jungle -- NPC: Emila, R.K. -- Border Conquest Guards -- @pos -84.113 -0.449 224.902 124 ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Yhoator_Jungle/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ELSHIMOUPLANDS; local csid = 0x7ffa; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27001005.lua
1
1578
--BT1-003 Assassin Hit local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableLeaderAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_ALIEN,CHARACTER_HIT) --draw ds.AddSingleAutoAttack(c,0,nil,ds.hinttg,scard.drop) --negate skill local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(sid,1)) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_CHAINING) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL) e1:SetRange(DS_LOCATION_LEADER) e1:SetCountLimit(1) e1:SetCondition(scard.negcon) e1:SetTarget(scard.negtg) e1:SetOperation(scard.negop) c:RegisterEffect(e1) end scard.dragon_ball_super_card=true scard.leader_front=sid-1 --draw function scard.drop(e,tp,eg,ep,ev,re,r,rp) Duel.Draw(tp,1,DS_REASON_SKILL) local c=e:GetHandler() if not c:IsRelateToSkill(e) or c:IsFacedown() then return end --power up ds.GainSkillUpdatePower(c,c,2,5000) end --negate skill function scard.negcon(e,tp,eg,ep,ev,re,r,rp) return rp==1-tp and re:IsHasCategory(DS_CATEGORY_BLOCKER) and Duel.IsChainDisablable(ev) end function scard.negfilter(c) return c:IsColor(COLOR_RED) and c:IsAbleToDrop() end scard.negtg=ds.CheckCardFunction(scard.negfilter,LOCATION_HAND,0) function scard.negop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TODROP) local g=Duel.SelectMatchingCard(tp,Card.IsColor,tp,LOCATION_HAND,0,1,1,nil,COLOR_RED) if g:GetCount()==0 or Duel.SendtoDrop(g,DS_REASON_SKILL)==0 then return end if not re:GetHandler():IsRelateToSkill(re) then return end Duel.NegateSkill(ev) end
gpl-3.0
nasomi/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Sorrowful_Sage.lua
29
2456
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Sorrowful Sage -- Type: Assault Mission Giver -- @pos 134.096 0.161 -30.401 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/besieged"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local rank = getMercenaryRank(player); local haveimperialIDtag; local tokens = 3;--player:getAssaultPoint(ILRUSI_ASSAULT_POINT); if (player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)) then haveimperialIDtag = 1; else haveimperialIDtag = 0; end if (rank > 0) then player:startEvent(278,rank,haveimperialIDtag,tokens,player:getCurrentAssault()); else player:startEvent(284); -- no rank end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 278) then local categorytype = bit.band(option, 0x0F); if (categorytype == 3) then -- low grade item local item = bit.rshift(option, 16); elseif (categorytype == 4) then -- medium grade item local item = bit.rshift(option, 16); elseif (categorytype == 5) then -- high grade item local item = bit.rshift(option, 16); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 278) then local selectiontype = bit.band(option, 0xF); if (selectiontype == 1) then -- taken assault mission player:addAssault(bit.rshift(option,4)); player:delKeyItem(IMPERIAL_ARMY_ID_TAG); player:addKeyItem(NYZUL_ISLE_ASSAULT_ORDERS); player:messageSpecial(KEYITEM_OBTAINED,NYZUL_ISLE_ASSAULT_ORDERS); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Lower_Delkfutts_Tower/npcs/Cermet_Door.lua
17
1161
----------------------------------- -- Area: Lower Delkfutt's Tower -- NPC: Cermet Door -- Notes: Leads to Upper Delkfutt's Tower. -- @pos 524 16 20 184 ----------------------------------- require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0014); -- missing walk-through animation, but it's the best I could find. return 1; end; ----------------------------------- -- onEventUpdate Action ----------------------------------- function onEventUpdate(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if (csid == 0x0014 and option == 1) then player:setPos(313, 16, 20, 128, 0x9E); -- to Upper Delkfutt's Tower end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Boneyard_Gully/bcnms/head_wind.lua
17
1705
----------------------------------- -- Area: Boneyard_Gully -- Name: head_wind -- BCNM: 672 ----------------------------------- package.loaded["scripts/zones/Boneyard_Gully/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Boneyard_Gully/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 5) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); player:setVar("COP_Ulmia_s_Path",6); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then player:addExp(1000); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Windurst_Waters/npcs/Maqu_Molpih.lua
30
1701
----------------------------------- -- Area: Windurst Waters -- NPC: Maqu Molpih -- Only sells when Windurst controlls Aragoneu Region -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/events/harvest_festivals") require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) onHalloweenTrade(player,trade,npc); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(ARAGONEU); if (RegionOwner ~= WINDURST) then player:showText(npc,MAQUMOLPIH_CLOSED_DIALOG); else player:showText(npc,MAQUMOLPIH_OPEN_DIALOG); stock = { 0x0277, 36, --Horo Flour 0x0275, 44, --Millioncorn 0x113F, 114, --Roasted Corn 0x1199, 92, --Sunflower Seeds 0x0349, 36 --Yagudo Feather } showShop(player,WINDURST,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
EnjoyHacking/nn
SpatialZeroPadding.lua
44
5655
local SpatialZeroPadding, parent = torch.class('nn.SpatialZeroPadding', 'nn.Module') function SpatialZeroPadding:__init(pad_l, pad_r, pad_t, pad_b) parent.__init(self) self.pad_l = pad_l self.pad_r = pad_r or self.pad_l self.pad_t = pad_t or self.pad_l self.pad_b = pad_b or self.pad_l end function SpatialZeroPadding:updateOutput(input) if input:dim() == 3 then -- sizes local h = input:size(2) + self.pad_t + self.pad_b local w = input:size(3) + self.pad_l + self.pad_r if w < 1 or h < 1 then error('input is too small') end self.output:resize(input:size(1), h, w) self.output:zero() -- crop input if necessary local c_input = input if self.pad_t < 0 then c_input = c_input:narrow(2, 1 - self.pad_t, c_input:size(2) + self.pad_t) end if self.pad_b < 0 then c_input = c_input:narrow(2, 1, c_input:size(2) + self.pad_b) end if self.pad_l < 0 then c_input = c_input:narrow(3, 1 - self.pad_l, c_input:size(3) + self.pad_l) end if self.pad_r < 0 then c_input = c_input:narrow(3, 1, c_input:size(3) + self.pad_r) end -- crop outout if necessary local c_output = self.output if self.pad_t > 0 then c_output = c_output:narrow(2, 1 + self.pad_t, c_output:size(2) - self.pad_t) end if self.pad_b > 0 then c_output = c_output:narrow(2, 1, c_output:size(2) - self.pad_b) end if self.pad_l > 0 then c_output = c_output:narrow(3, 1 + self.pad_l, c_output:size(3) - self.pad_l) end if self.pad_r > 0 then c_output = c_output:narrow(3, 1, c_output:size(3) - self.pad_r) end -- copy input to output c_output:copy(c_input) elseif input:dim() == 4 then -- sizes local h = input:size(3) + self.pad_t + self.pad_b local w = input:size(4) + self.pad_l + self.pad_r if w < 1 or h < 1 then error('input is too small') end self.output:resize(input:size(1), input:size(2), h, w) self.output:zero() -- crop input if necessary local c_input = input if self.pad_t < 0 then c_input = c_input:narrow(3, 1 - self.pad_t, c_input:size(3) + self.pad_t) end if self.pad_b < 0 then c_input = c_input:narrow(3, 1, c_input:size(3) + self.pad_b) end if self.pad_l < 0 then c_input = c_input:narrow(4, 1 - self.pad_l, c_input:size(4) + self.pad_l) end if self.pad_r < 0 then c_input = c_input:narrow(4, 1, c_input:size(4) + self.pad_r) end -- crop outout if necessary local c_output = self.output if self.pad_t > 0 then c_output = c_output:narrow(3, 1 + self.pad_t, c_output:size(3) - self.pad_t) end if self.pad_b > 0 then c_output = c_output:narrow(3, 1, c_output:size(3) - self.pad_b) end if self.pad_l > 0 then c_output = c_output:narrow(4, 1 + self.pad_l, c_output:size(4) - self.pad_l) end if self.pad_r > 0 then c_output = c_output:narrow(4, 1, c_output:size(4) - self.pad_r) end -- copy input to output c_output:copy(c_input) else error('input must be 3 or 4-dimensional') end return self.output end function SpatialZeroPadding:updateGradInput(input, gradOutput) if input:dim() == 3 then self.gradInput:resizeAs(input):zero() -- crop gradInput if necessary local cg_input = self.gradInput if self.pad_t < 0 then cg_input = cg_input:narrow(2, 1 - self.pad_t, cg_input:size(2) + self.pad_t) end if self.pad_b < 0 then cg_input = cg_input:narrow(2, 1, cg_input:size(2) + self.pad_b) end if self.pad_l < 0 then cg_input = cg_input:narrow(3, 1 - self.pad_l, cg_input:size(3) + self.pad_l) end if self.pad_r < 0 then cg_input = cg_input:narrow(3, 1, cg_input:size(3) + self.pad_r) end -- crop gradOutout if necessary local cg_output = gradOutput if self.pad_t > 0 then cg_output = cg_output:narrow(2, 1 + self.pad_t, cg_output:size(2) - self.pad_t) end if self.pad_b > 0 then cg_output = cg_output:narrow(2, 1, cg_output:size(2) - self.pad_b) end if self.pad_l > 0 then cg_output = cg_output:narrow(3, 1 + self.pad_l, cg_output:size(3) - self.pad_l) end if self.pad_r > 0 then cg_output = cg_output:narrow(3, 1, cg_output:size(3) - self.pad_r) end -- copy gradOuput to gradInput cg_input:copy(cg_output) elseif input:dim() == 4 then self.gradInput:resizeAs(input):zero() -- crop gradInput if necessary local cg_input = self.gradInput if self.pad_t < 0 then cg_input = cg_input:narrow(3, 1 - self.pad_t, cg_input:size(3) + self.pad_t) end if self.pad_b < 0 then cg_input = cg_input:narrow(3, 1, cg_input:size(3) + self.pad_b) end if self.pad_l < 0 then cg_input = cg_input:narrow(4, 1 - self.pad_l, cg_input:size(4) + self.pad_l) end if self.pad_r < 0 then cg_input = cg_input:narrow(4, 1, cg_input:size(4) + self.pad_r) end -- crop gradOutout if necessary local cg_output = gradOutput if self.pad_t > 0 then cg_output = cg_output:narrow(3, 1 + self.pad_t, cg_output:size(3) - self.pad_t) end if self.pad_b > 0 then cg_output = cg_output:narrow(3, 1, cg_output:size(3) - self.pad_b) end if self.pad_l > 0 then cg_output = cg_output:narrow(4, 1 + self.pad_l, cg_output:size(4) - self.pad_l) end if self.pad_r > 0 then cg_output = cg_output:narrow(4, 1, cg_output:size(4) - self.pad_r) end -- copy gradOuput to gradInput cg_input:copy(cg_output) else error('input must be 3 or 4-dimensional') end return self.gradInput end function SpatialZeroPadding:__tostring__() return torch.type(self) .. string.format('(l=%d,r=%d,t=%d,b=%d)', self.pad_l, self.pad_r, self.pad_t, self.pad_b) end
bsd-3-clause
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/model/cbi/luci_statistics/unixsock.lua
80
1455
--[[ Luci configuration model for statistics - collectd unixsock plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Unixsock Plugin Configuration"), translate( "The unixsock plugin creates a unix socket which can be used " .. "to read collected data from a running collectd instance." )) -- collectd_unixsock config section s = m:section( NamedSection, "collectd_unixsock", "luci_statistics" ) -- collectd_unixsock.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_unixsock.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile" ) socketfile.default = "/var/run/collect-query.socket" socketfile:depends( "enable", 1 ) -- collectd_unixsock.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup" ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_unixsock.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms" ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) return m
gpl-2.0
haka-security/haka
modules/protocol/tcp/test/create.lua
2
1191
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. -- Test that will duplicate a tcp connection local ipv4 = require("protocol/ipv4") require("protocol/tcp") require("protocol/tcp_connection") -- just to be safe, to avoid the test to run in an infinite loop local counter = 10 haka.rule { on = haka.dissectors.tcp.events.receive_packet, eval = function (pkt) if pkt.dstport == 4444 or pkt.srcport == 4444 then if counter == 0 then error("loop detected") end counter = counter-1 local npkt = haka.dissectors.packet.create() npkt = haka.dissectors.ipv4.create(npkt) npkt.ttl = pkt.ttl npkt.dst = pkt.dst npkt.src = pkt.src npkt = haka.dissectors.tcp.create(npkt) npkt.window_size = pkt.window_size npkt.seq = pkt.seq+1000 if pkt.ack_seq ~= 0 then npkt.ack_seq = pkt.ack_seq+1000 end npkt.flags.all = pkt.flags.all npkt.dstport = pkt.dstport+10 npkt.srcport = pkt.srcport+10 local payload = pkt.payload:clone() npkt.payload:append(payload) npkt:inject() end end }
mpl-2.0
jkeywo/KFactorioMods
k-ruins_0.1.1/stdlib/log/logger.lua
8
4009
--- Logger module -- @module Logger Logger = {} --- Creates a new logger object.<p> -- In debug mode, the logger writes immediately. Otherwise the loggers buffers lines. -- The logger flushes after 60 seconds has elapsed since the last message. -- <p> -- When loggers are created, a table of options may be specified. The valid options are: -- <code> -- log_ticks -- whether to include the game tick timestamp in logs. Defaults to false. -- file_extension -- a string that overides the default 'log' file extension. -- force_append -- each time a logger is created, it will always append, instead of -- -- the default behavior, which is to write out a new file, then append -- </code> -- -- @usage --LOGGER = Logger.new('cool_mod_name') --LOGGER.log("this msg will be logged!") -- -- @usage --LOGGER = Logger.new('cool_mod_name', 'test', true) --LOGGER.log("this msg will be logged and written immediately in test.log!") -- -- @usage --LOGGER = Logger.new('cool_mod_name', 'test', true, { file_extension = data }) --LOGGER.log("this msg will be logged and written immediately in test.data!") -- -- @param mod_name [required] the name of the mod to create the logger for -- @param log_name (optional, default: 'main') the name of the logger -- @param debug_mode (optional, default: false) toggles the debug state of logger. -- @param options (optional) table with optional arguments -- @return the logger instance function Logger.new(mod_name, log_name, debug_mode, options) if not mod_name then error("Logger must be given a mod_name as the first argument") end if not log_name then log_name = "main" end if not options then options = {} end local Logger = {mod_name = mod_name, log_name = log_name, debug_mode = debug_mode, buffer = {}, last_written = 0, ever_written = false} --- Logger options Logger.options = { log_ticks = options.log_ticks or false, -- whether to add the ticks in the timestamp, default false file_extension = options.file_extension or 'log', -- extension of the file, default: log force_append = options.force_append or false, -- append the file on first write, default: false } Logger.file_name = 'logs/' .. Logger.mod_name .. '/' .. Logger.log_name .. '.' .. Logger.options.file_extension Logger.ever_written = Logger.options.force_append --- Logs a message -- @param msg a string, the message to log -- @return true if the message was written, false if it was queued for a later write function Logger.log(msg) local format = string.format if _G.game then local tick = game.tick local floor = math.floor local time_s = floor(tick/60) local time_minutes = floor(time_s/60) local time_hours = floor(time_minutes/60) if Logger.options.log_ticks then table.insert(Logger.buffer, format("%02d:%02d:%02d.%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, tick - time_s*60, msg)) else table.insert(Logger.buffer, format("%02d:%02d:%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, msg)) end -- write the log every minute if (Logger.debug_mode or (tick - Logger.last_written) > 3600) then return Logger.write() end else table.insert(Logger.buffer, format("00:00:00: %s\n", msg)) end return false end --- Writes out all buffered messages immediately -- @return true if there any messages were written, false if not function Logger.write() if _G.game then Logger.last_written = game.tick game.write_file(Logger.file_name, table.concat(Logger.buffer), Logger.ever_written) Logger.buffer = {} Logger.ever_written = true return true end return false end return Logger end return Logger
mit
KlonZK/Zero-K
units/cremcom1.lua
2
8158
unitDef = { unitname = [[cremcom1]], name = [[Knight Commander]], description = [[Mobile Assault Commander, Builds at 10 m/s]], acceleration = 0.18, activateWhenBuilt = true, amphibious = [[1]], autoHeal = 5, brakeRate = 0.375, buildCostEnergy = 1200, buildCostMetal = 1200, buildDistance = 120, builder = true, buildoptions = { }, buildPic = [[cremcom.png]], buildTime = 1200, canAttack = true, canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[45 50 45]], collisionVolumeTest = 1, collisionVolumeType = [[CylY]], commander = true, corpse = [[DEAD]], customParams = { cloakstealth = [[1]], description_de = [[Mobiler Sturmkommandant, Baut mit 10 M/s]], description_pl = [[Wszechstronny Dowodca, moc 10 m/s]], helptext = [[The Knight Commander is a well-balanced command platform that can mount most modules, with decent speed, armor, and regeneration.]], helptext_de = [[Der Knight Commander bietet ein sehr ausgeglichenes Ger?t, das mit den meisten Modulen ausger?tet werden kann, mit anständiger Geschwindigkeit und Panzerung. Seine Basiswaffe ist ein Allzwecklaser und bei entsprechender Aufr?tung erhält er eine Disintegratorkanone.]], helptext_pl = [[Knight to wszechstronny Dowodca, ktory moze uzywac wiekszosci modulow i ma dobra predkosc, wytrzymalosc i samonaprawe.]], level = [[1]], statsname = [[armcom1]], soundok = [[heavy_bot_move]], soundselect = [[bot_select]], soundbuild = [[builder_start]], --lups_unit_fxs = { "commandShieldBlue" }, commtype = [[6]], }, energyMake = 6, energyStorage = 0, energyUse = 0, explodeAs = [[ESTOR_BUILDINGEX]], footprintX = 2, footprintZ = 2, hideDamage = false, iconType = [[commander1]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, mass = 411, maxDamage = 2500, maxSlope = 36, maxVelocity = 1.35, maxWaterDepth = 5000, metalMake = 4, metalStorage = 0, minCloakDistance = 75, modelCenterOffset = [[0 1 0]], movementClass = [[AKBOT2]], noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]], norestrict = [[1]], objectName = [[cremcom.s3o]], script = [[cremcom.lua]], seismicSignature = 16, selfDestructAs = [[ESTOR_BUILDINGEX]], sfxtypes = { explosiongenerators = { [[custom:BEAMWEAPON_MUZZLE_BLUE]], [[custom:NONE]], }, }, showNanoSpray = false, showPlayerName = true, side = [[ARM]], sightDistance = 500, sonarDistance = 300, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 26, terraformSpeed = 600, turnRate = 1148, upright = true, workerTime = 10, weapons = { [1] = { def = [[FAKELASER]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, [5] = { def = [[LASER]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { FAKELASER = { name = [[Fake Laser]], areaOfEffect = 12, beamlaser = 1, beamTime = 0.1, coreThickness = 0.5, craterBoost = 0, craterMult = 0, damage = { default = 0, subs = 0, }, duration = 0.11, edgeEffectiveness = 0.99, explosionGenerator = [[custom:flash1green]], fireStarter = 70, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 5.53, minIntensity = 1, noSelfDamage = true, range = 300, reloadtime = 0.11, rgbColor = [[0 1 0]], soundStart = [[weapon/laser/laser_burn5]], soundTrigger = true, texture1 = [[largelaser]], texture2 = [[flare]], texture3 = [[flare]], texture4 = [[smallflare]], thickness = 5.53, tolerance = 10000, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 900, }, LASER = { name = [[Commander Laser]], areaOfEffect = 12, beamlaser = 1, beamTime = 0.1, coreThickness = 0.5, craterBoost = 0, craterMult = 0, damage = { default = 16.5, subs = 8.25, }, duration = 0.11, edgeEffectiveness = 0.99, explosionGenerator = [[custom:flash1blue]], fireStarter = 70, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 3, minIntensity = 1, noSelfDamage = true, range = 300, reloadtime = 0.11, rgbColor = [[0 1 1]], soundStart = [[weapon/laser/pulse_laser3]], soundTrigger = true, texture1 = [[largelaser]], texture2 = [[flare]], texture3 = [[flare]], texture4 = [[smallflare]], thickness = 3, tolerance = 10000, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 900, }, }, featureDefs = { DEAD = { description = [[Wreckage - Knight Commander]], blocking = true, category = [[corpses]], damage = 2500, energy = 0, featureDead = [[HEAP]], featurereclamate = [[SMUDGE01]], footprintX = 3, footprintZ = 3, height = [[20]], hitdensity = [[100]], metal = 480, object = [[cremcom_dead.s3o]], reclaimable = true, reclaimTime = 480, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Knight Commander]], blocking = false, category = [[heaps]], damage = 2500, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 2, footprintZ = 2, hitdensity = [[100]], metal = 240, object = [[debris2x2c.s3o]], reclaimable = true, reclaimTime = 240, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ cremcom1 = unitDef })
gpl-2.0
KlonZK/Zero-K
LuaUI/Widgets/chili_new/controls/control.lua
8
38837
--//============================================================================= --- Control module --- Control fields. -- Inherits from Object. -- @see object.Object -- @table Control -- @tparam {left,top,right,bottom} padding table of padding, (default {5,5,5,5}) -- @number[opt=1.5] borderThickness border thickness in pixels -- @tparam {r,g,b,a} borderColor border color {r,g,b,a}, (default {1,1,1,0.6}) -- @tparam {r,g,b,a} borderColor2 border color second {r,g,b,a}, (default {0,0,0,0.8}) -- @tparam {r,g,b,a} backgroundColor background color {r,g,b,a}, (default {0.8,0.8,1,0.4}) -- @tparam {r,g,b,a} focusColor focus color {r,g,b,a}, (default {0.2,0.2,1,0.6}) -- @bool[opt=false] autosize whether size will be determined automatically -- @bool[opt=false] draggable can control be dragged -- @bool[opt=false] resizable can control be resized -- @int[opt=10] minWidth minimum width -- @int[opt=10] minHeight minimum height -- @int[opt=1e9] maxWidth maximum width -- @int[opt=1e9] maxHeight maximum height -- @tparam {func1,fun2,...} OnResize table of function listeners for size changes, (default {}) Control = Object:Inherit{ classname = 'control', padding = {5, 5, 5, 5}, borderThickness = 1.5, borderColor = {1.0, 1.0, 1.0, 0.6}, borderColor2 = {0.0, 0.0, 0.0, 0.8}, backgroundColor = {0.8, 0.8, 1.0, 0.4}, focusColor = {0.2, 0.2, 1.0, 0.6}, autosize = false, savespace = true, --// iff autosize==true, it shrinks the control to the minimum needed space, if disabled autosize _normally_ only enlarges the control resizeGripSize = {11, 11}, dragGripSize = {10, 10}, dragUseGrip = false, draggable = false, resizable = false, tweakDragUseGrip = false, tweakDraggable = false, tweakResizable = false, minWidth = 10, minHeight = 10, maxWidth = 1e9, maxHeight = 1e9, fixedRatio = false, tooltip = nil, --// JUST TEXT font = { font = "FreeSansBold.otf", size = 14, shadow = false, outline = false, outlineWidth = 3, outlineWeight = 3, color = {1,1,1,1}, outlineColor = {0,0,0,1}, autoOutlineColor = true, }, state = { focused = false, hovered = false, checked = false, selected = false, --FIXME implement pressed = false, enabled = true, --FIXME implement }, skin = nil, skinName = nil, drawcontrolv2 = nil, --// disable backward support with old DrawControl gl state (with 2.1 self.xy translation isn't needed anymore) noSelfHitTest = true, OnResize = {}, } local this = Control local inherited = this.inherited --//============================================================================= function Control:New(obj) --// backward compability BackwardCompa(obj) if obj.DrawControl then obj._hasCustomDrawControl = true end --// load the skin for this control obj.classname = self.classname theme.LoadThemeDefaults(obj) SkinHandler.LoadSkin(obj, self) --// we want to initialize the children ourself (see downwards) local cn = obj.children obj.children = nil obj = inherited.New(self,obj) if obj._hasCustomDrawControl then if not obj.drawcontrolv2 then local w = obj._widget or {whInfo = { name = "unknown" } } local fmtStr = [[You are using a custom %s::DrawControl in widget "%s". Please note that with Chili 2.1 the (self.x, self.y) translation is moved a level up and does not need to be done in DrawControl anymore. When you adjusted your code set `drawcontrolv2 = true` in the respective control to disable this message.]] Spring.Log("Chili", "warning", fmtStr:format(obj.name, w.whInfo.name)) else obj._hasCustomDrawControl = false end end local p = obj.padding if (obj.clientWidth) then obj.width = obj.clientWidth + p[1] + p[3] end if (obj.clientHeight) then obj.height = obj.clientHeight + p[2] + p[4] end --// create font obj.font = Font:New(obj.font) obj.font:SetParent(obj) obj:DetectRelativeBounds() obj:AlignControl() --// add children after UpdateClientArea! (so relative width/height can be applied correctly) if (cn) then for i=1,#cn do obj:AddChild(cn[i], true) end end return obj end --- Removes the control. function Control:Dispose(...) gl.DeleteList(self._all_dlist) self._all_dlist = nil gl.DeleteList(self._children_dlist) self._children_dlist = nil gl.DeleteList(self._own_dlist) self._own_dlist = nil gl.DeleteTexture(self._tex_all) self._tex_all = nil gl.DeleteTexture(self._tex_children) self._tex_children = nil if gl.DeleteFBO then gl.DeleteRBO(self._stencil_all) self._stencil_all = nil gl.DeleteRBO(self._stencil_children) self._stencil_children = nil gl.DeleteFBO(self._fbo_all) self._fbo_all = nil gl.DeleteFBO(self._fbo_children) self._fbo_children = nil end inherited.Dispose(self,...) self.font:SetParent() end --//============================================================================= --- Sets the control's parent object. -- @tparam object.Object obj parent object function Control:SetParent(obj) inherited.SetParent(self,obj) self:RequestRealign() end --- Adds a child object to the control -- @tparam object.Object obj child object -- @param dontUpdate if true won't trigger a RequestRealign() function Control:AddChild(obj, dontUpdate) inherited.AddChild(self,obj) if (not dontUpdate) then self:RequestRealign() end end --- Removes a child object from the control -- @tparam object.Object obj child object function Control:RemoveChild(obj) local found = inherited.RemoveChild(self,obj) if (found) then self:RequestRealign() end return found end --//============================================================================= function Control:_GetMaxChildConstraints(child) return 0, 0, self.clientWidth, self.clientHeight end function Control:DetectRelativeBounds() --// we need min 2 x-dim coords to define a rect! local numconstraints = 0 if (self.x) then numconstraints = numconstraints + 1 end if (self.right) then numconstraints = numconstraints + 1 end if (self.width) then numconstraints = numconstraints + 1 end if (numconstraints<2) then if (numconstraints==0) then self.x = 0 self.width = self.defaultWidth or 0 else if (self.width) then self.x = 0 else self.width = self.defaultWidth or 0 end end end --// we need min 2 y-dim coords to define a rect! numconstraints = 0 if (self.y) then numconstraints = numconstraints + 1 end if (self.bottom) then numconstraints = numconstraints + 1 end if (self.height) then numconstraints = numconstraints + 1 end if (numconstraints<2) then if (numconstraints==0) then self.y = 0 self.height = self.defaultHeight or 0 else if (self.height) then self.y = 0 else self.height = self.defaultHeight or 0 end end end --// check which constraints are relative self._givenBounds = { left = self.x, top = self.y, width = self.width, height = self.height, right = self.right, bottom = self.bottom, } local rb = { left = IsRelativeCoord(self.x) and self.x, top = IsRelativeCoord(self.y) and self.y, width = IsRelativeCoord(self.width) and self.width, height = IsRelativeCoord(self.height) and self.height, right = self.right, bottom = self.bottom, } self._relativeBounds = rb self._isRelative = (rb.left or rb.top or rb.width or rb.height or rb.right or rb.bottom)and(true) --// initialize relative constraints with 0 self.x = ((not rb.left) and self.x) or 0 self.y = ((not rb.top) and self.y) or 0 self.width = ((not rb.width) and self.width) or 0 self.height = ((not rb.height) and self.height) or 0 --self.right = (type(self.right)=='number')and(self.right>0)and(self.right) or 0 --self.bottom = (type(self.bottom)=='number')and(self.bottom>0)and(self.bottom) or 0 end function Control:GetRelativeBox(savespace) local t = {self.x, self.y, self.width, self.height} if (savespace) then t = {0,0,self.minWidth,self.minHeight} end if (not self._isRelative) then return t end local p = self.parent if (not p) then return t end --// FIXME use pl & pt too!!! local pl,pt,pw,ph = p:_GetMaxChildConstraints(self) local givBounds = self._givenBounds local relBounds = self._relativeBounds local left = self.x local top = self.y local width = (savespace and self.minWidth) or self.width local height = (savespace and self.minHeight) or self.height --// ProcessRelativeCoord is defined in util.lua if (relBounds.left) then left = ProcessRelativeCoord(relBounds.left, pw) end if (relBounds.top) then top = ProcessRelativeCoord(relBounds.top, ph) end if (relBounds.width) then width = ProcessRelativeCoord(relBounds.width, pw) end if (relBounds.height) then height = ProcessRelativeCoord(relBounds.height, ph) end if (relBounds.right) then if (not givBounds.left) then left = pw - width - ProcessRelativeCoord(relBounds.right, pw) else width = pw - left - ProcessRelativeCoord(relBounds.right, pw) end end if (relBounds.bottom) then if (not givBounds.top) then top = ph - height - ProcessRelativeCoord(relBounds.bottom, ph) else height = ph - top - ProcessRelativeCoord(relBounds.bottom, ph) end end return {left, top, width, height} end --//============================================================================= function Control:UpdateClientArea(dontRedraw) local padding = self.padding self.clientWidth = self.width - padding[1] - padding[3] self.clientHeight = self.height - padding[2] - padding[4] self.clientArea = { padding[1], padding[2], self.clientWidth, self.clientHeight } if (self.parent)and(self.parent:InheritsFrom('control')) then --FIXME sometimes this makes self:RequestRealign() redundant! try to reduce the Align() calls somehow self.parent:RequestRealign() end if (self.width ~= self._oldwidth_uca)or(self.height ~= self._oldheight_uca) then self:RequestRealign() self._oldwidth_uca = self.width self._oldheight_uca = self.height end if not dontRedraw then self:Invalidate() end --FIXME only when RTT! self:CallListeners(self.OnResize) --FIXME more arguments and filter unchanged resizes end function Control:AlignControl() local newBox = self:GetRelativeBox() self:_UpdateConstraints(newBox[1], newBox[2], newBox[3], newBox[4]) end function Control:RequestRealign(savespace) if (not self._inRealign) then self._realignRequested = true self.__savespace = savespace self:RequestUpdate() end end function Control:DisableRealign() self._realignDisabled = (self._realignDisabled or 0) + 1 end function Control:EnableRealign() self._realignDisabled = ((self._realignDisabled or 0)>1 and self._realignDisabled - 1) or nil if (self._realignRequested) then self:Realign() self._realignRequested = nil end end function Control:Realign(savespace) if (not self._realignDisabled) then if (not self._inRealign) then self._savespace = savespace or self.savespace self._inRealign = true self:AlignControl() --FIXME still needed? local childrenAligned = self:UpdateLayout() self._realignRequested = nil if (not childrenAligned) then self:RealignChildren() end self._inRealign = nil self._savespace = nil end else self:RequestRealign(savespace) end end function Control:UpdateLayout() if (self.autosize) then self:RealignChildren(true) local neededWidth, neededHeight = self:GetChildrenMinimumExtents() local relativeBox = self:GetRelativeBox(self._savespace or self.savespace) neededWidth = math.max(relativeBox[3], neededWidth) neededHeight = math.max(relativeBox[4], neededHeight) neededWidth = neededWidth - self.padding[1] - self.padding[3] neededHeight = neededHeight - self.padding[2] - self.padding[4] if (self.debug) then local cminextW, cminextH = self:GetChildrenMinimumExtents() Spring.Echo("Control:UpdateLayout", self.name, "GetChildrenMinimumExtents", cminextW, cminextH, "GetRelativeBox", relativeBox[3], relativeBox[4], "savespace", self._savespace) end self:Resize(neededWidth, neededHeight, true, true) self:RealignChildren() self:AlignControl() --FIXME done twice!!! (1st in Realign) return true end end function Control:RealignChildren(savespace) self:CallChildren("Realign", savespace) end --//============================================================================= --- Sets the control's position -- @int x x-coordinate -- @int y y-coordinate -- @int w width -- @int h height -- @param clientArea TODO -- @bool dontUpdateRelative TODO function Control:SetPos(x, y, w, h, clientArea, dontUpdateRelative) local changed = false local redraw = false --//FIXME add an API for relative constraints changes if (x)and(type(x) == "number") then if (self.x ~= x) then self.x = x changed = true end if (not dontUpdateRelative) then if (self._relativeBounds.left ~= x) then self._relativeBounds.left = false self._givenBounds.left = x self._relativeBounds.right = false self._givenBounds.right = false changed = true end end end if (y)and(type(y) == "number") then if (self.y ~= y) then self.y = y changed = true end if (not dontUpdateRelative) then if (self._relativeBounds.top ~= y) then self._relativeBounds.top = false self._givenBounds.top = y self._relativeBounds.bottom = false self._givenBounds.bottom = false changed = true end end end if (w)and(type(w) == "number") then w = (clientArea)and(w+self.padding[1]+self.padding[3]) or (w) w = math.max( w, self.minWidth ) w = math.min( w, self.maxWidth ) if (self.width ~= w) then self.width = w changed = true redraw = true end if (not dontUpdateRelative) then if (self._relativeBounds.width ~= w) then self._relativeBounds.width = IsRelativeCoord(w) and w self._givenBounds.width = w changed = true redraw = true end end end if (h)and(type(h) == "number") then h = (clientArea)and(h+self.padding[2]+self.padding[4]) or (h) h = math.max( h, self.minHeight ) h = math.min( h, self.maxHeight ) if (self.height ~= h) then self.height = h changed = true redraw = true end if (not dontUpdateRelative) then if (self._relativeBounds.height ~= h) then self._relativeBounds.height = IsRelativeCoord(h) and h self._givenBounds.height = h changed = true redraw = true end end end if (changed)or(not self.clientArea) then self:UpdateClientArea(not redraw) end end --- Sets the control's relative position -- @int x x-coordinate -- @int y y-coordinate -- @int w width -- @int h height -- @param clientArea TODO -- @bool dontUpdateRelative TODO function Control:SetPosRelative(x, y, w, h, clientArea, dontUpdateRelative) local changed = false local redraw = false --//FIXME add an API for relative constraints changes if x then if (not IsRelativeCoord(x)) then if (self.x ~= x) then self.x = x changed = true end end if (not dontUpdateRelative) then if (self._relativeBounds.left ~= x) then self._relativeBounds.left = IsRelativeCoord(x) and x self._givenBounds.left = x changed = true end end end if y then if (not IsRelativeCoord(y)) then if (self.y ~= y) then self.y = y changed = true end end if (not dontUpdateRelative) then if (self._relativeBounds.top ~= y) then self._relativeBounds.top = IsRelativeCoord(y) and y self._givenBounds.top = y changed = true end end end if w then if (not IsRelativeCoord(w)) then w = (clientArea)and(w+self.padding[1]+self.padding[3]) or (w) w = math.max( w, self.minWidth ) w = math.min( w, self.maxWidth ) if (self.width ~= w) then self.width = w changed = true redraw = true end end if (not dontUpdateRelative) then if (self._relativeBounds.width ~= w) then self._relativeBounds.width = IsRelativeCoord(w) and w self._givenBounds.width = w changed = true redraw = true end end end if h then if (not IsRelativeCoord(h)) then h = (clientArea)and(h+self.padding[2]+self.padding[4]) or (h) h = math.max( h, self.minHeight ) h = math.min( h, self.maxHeight ) if (self.height ~= h) then self.height = h changed = true redraw = true end end if (not dontUpdateRelative) then if (self._relativeBounds.height ~= h) then self._relativeBounds.height = IsRelativeCoord(h) and h self._givenBounds.height = h changed = true redraw = true end end end if (changed)or(not self.clientArea) then self:UpdateClientArea(not redraw) end end --- Resize the control -- @int w width -- @int h height -- @param clientArea TODO -- @bool dontUpdateRelative TODO function Control:Resize(w, h, clientArea, dontUpdateRelative) self:SetPosRelative(nil, nil, w, h, clientArea, dontUpdateRelative) end function Control:_UpdateConstraints(x, y, w, h) --// internal used self:SetPos(x, y, w, h, false, true) end --//============================================================================= function Control:GetMinimumExtents() local maxRight, maxBottom = 0,0 if (self.autosize) then --// FIXME handle me correctly!!! (:= do the parent offset) maxRight, maxBottom = self:GetChildrenMinimumExtents() end if (not self._isRelative) then local right = self.x + self.width local bottom = self.y + self.height maxRight = math.max(maxRight, right) maxBottom = math.max(maxBottom, bottom) else local cgb = self._givenBounds local crb = self._relativeBounds local left, width, right = 0,0,0 if (not crb.width) then if (self.autosize) then width = self.width or 0 else width = cgb.width or 0 end end if (not crb.left) then left = cgb.left or 0 end if (not IsRelativeCoord(crb.right)) then right = crb.right or 0 end local totalWidth = left + width + right local top, height, bottom = 0,0,0 if (not crb.height) then height = cgb.height or 0 end if (not crb.top) then top = cgb.top or 0 end if (not IsRelativeCoord(crb.bottom)) then bottomt = crb.bottom or 0 end local totalHeight = top + height + bottom --[[ if (crb.width) then width = cgb.width or 0 end if (crb.left) then left = cgb.left or 0 end if (IsRelativeCoord(cgb.right)) then right = cgb.right or 0 end ... --]] totalWidth = math.max(totalWidth, self.minWidth) totalHeight = math.max(totalHeight, self.minHeight) totalWidth = math.min(totalWidth, self.maxWidth) totalHeight = math.min(totalHeight, self.maxHeight) maxRight = math.max(maxRight, totalWidth) maxBottom = math.max(maxBottom, totalHeight) end return maxRight, maxBottom end function Control:GetChildrenMinimumExtents() local minWidth = 0 local minHeight = 0 local cn = self.children for i=1,#cn do local c = cn[i] if (c.GetMinimumExtents) then local width, height = c:GetMinimumExtents() minWidth = math.max(minWidth, width) minHeight = math.max(minHeight, height) end end if (minWidth + minHeight > 0) then local padding = self.padding minWidth = minWidth + padding[1] + padding[3] minHeight = minHeight + padding[2] + padding[4] end return minWidth, minHeight end function Control:GetCurrentExtents() local minLeft, minTop, maxRight, maxBottom = self:GetChildrenCurrentExtents() local left = self.x local top = self.y local right = self.x + self.width local bottom = self.y + self.height if (left < minLeft) then minLeft = left end if (top < minTop ) then minTop = top end if (right > maxRight) then maxRight = right end if (bottom > maxBottom) then maxBottom = bottom end return minLeft, minTop, maxRight, maxBottom end function Control:GetChildrenCurrentExtents() local minLeft = 0 local minTop = 0 local maxRight = 0 local maxBottom = 0 local cn = self.children for i=1,#cn do local c = cn[i] if (c.GetCurrentExtents) then local left, top, right, bottom = c:GetCurrentExtents() minLeft = math.min(minLeft, left) minTop = math.min(minTop, top) maxRight = math.max(maxRight, right) maxBottom = math.max(maxBottom, bottom) end end return minLeft, minTop, maxRight, maxBottom end --//============================================================================= function Control:StartResizing(x,y) --//FIXME the x,y aren't needed check how drag is handled! self.resizing = { mouse = {x, y}, size = {self.width, self.height}, pos = {self.x, self.y}, } end function Control:StopResizing(x,y) self.resizing = false end function Control:StartDragging(x,y) self.dragging = true end function Control:StopDragging(x,y) self.dragging = false end --//============================================================================= function Control:LocalToClient(x,y) local ca = self.clientArea return x - ca[1], y - ca[2] end function Control:ClientToLocal(x,y) local ca = self.clientArea return x + ca[1], y + ca[2] end function Control:ParentToClient(x,y) local ca = self.clientArea return x - self.x - ca[1], y - self.y - ca[2] end function Control:ClientToParent(x,y) local ca = self.clientArea return x + self.x + ca[1], y + self.y + ca[2] end function Control:InClientArea(x,y) local clientArea = self.clientArea return x>=clientArea[1] and y>=clientArea[2] and x<=clientArea[1]+clientArea[3] and y<=clientArea[2]+clientArea[4] end --//============================================================================= --- Requests a redraw of the control. function Control:Invalidate() self._needRedraw = true self._needRedrawSelf = nil self:RequestUpdate() end --- Requests a redraw of the control. function Control:InvalidateSelf() self._needRedraw = true self._needRedrawSelf = true self:RequestUpdate() end --//============================================================================= function Control:InstantUpdate() if self:IsInView() then if self._needRedraw then self:Update() else self._in_update = true self:_UpdateChildrenDList() self:_UpdateAllDList() self._in_update = false end end end function Control:Update() if self._realignRequested then self:Realign(self.__savespace) self._realignRequested = false end if self._needRedraw then if self:IsInView() then self._in_update = true self:_UpdateOwnDList() if not self._needRedrawSelf then self:_UpdateChildrenDList() end self:_UpdateAllDList() self._in_update = false self._needRedraw = false self._needRedrawSelf = false self._redrawSelfCounter = (self._redrawSelfCounter or 0) + 1 end end end --//============================================================================= function Control:_CheckIfRTTisAppreciated() if self._cantUseRTT then return false end if self:InheritsFrom("window") then if self._usingRTT then return (((self._redrawSelfCounter or 1) / (self._redrawCounter or 1)) < 0.2) else return (((self._redrawSelfCounter or 1) / (self._redrawCounter or 1)) < 0.1) end else if (self._redrawCounter or 0) > 300 then return (((self._redrawSelfCounter or 1) / (self._redrawCounter or 1)) < 0.03) end end end function Control:_UpdateOwnDList() if not self.parent then return end if not self:IsInView() then return end self:CallChildren('_UpdateOwnDList') gl.DeleteList(self._own_dlist) --self._own_dlist = nil --self._own_dlist = gl.CreateList(self.DrawControl, self) end function Control:_UpdateChildrenDList() if not self.parent then return end if not self:IsInView() then return end if self:InheritsFrom("scrollpanel") and not self._cantUseRTT then local contentX,contentY,contentWidth,contentHeight = unpack4(self.contentArea) if (contentWidth <= 0)or(contentHeight <= 0) then return end self:CreateViewTexture("children", contentWidth, contentHeight, self.DrawChildrenForList, self, true) end end function Control:_UpdateAllDList() if not self.parent then return end if not self:IsInView() then return end if (self.width <= 0)or(self.height <= 0) then return end local RTT = self:_CheckIfRTTisAppreciated() if RTT then self._usingRTT = true self:CreateViewTexture("all", self.width, self.height, self.DrawForList, self) else local suffix_name = "all" local texname = "_tex_" .. suffix_name local texStencilName = "_stencil_" .. suffix_name local fboName = "_fbo_" .. suffix_name local texw = "_texw_" .. suffix_name local texh = "_texh_" .. suffix_name gl.DeleteFBO(self[fboName]) gl.DeleteTexture(self[texname]) gl.DeleteRBO(self[texStencilName]) self[texStencilName] = nil self[texname] = nil self[fboName] = nil self[texw] = nil self[texh] = nil self._usingRTT = false end --gl.DeleteList(self._all_dlist) --self._all_dlist = gl.CreateList(self.DrawForList,self) if (self.parent)and(not self.parent._needRedraw)and(self.parent._UpdateAllDList) then TaskHandler.RequestInstantUpdate(self.parent) end end function Control:_SetupRTT(fnc, self_, drawInContentRect, ...) gl.Clear(GL.COLOR_BUFFER_BIT, 0,0,0,1) gl.Clear(GL.STENCIL_BUFFER_BIT, 0) --// no need to push/pop cause gl.ActiveFBO already does so gl.MatrixMode(GL.MODELVIEW) gl.Translate(-1,1,0) if not drawInContentRect then gl.Scale(2/self.width, -2/self.height, 1) gl.Translate(-self.x, -self.y, 0) else local clientX,clientY,clientWidth,clientHeight = unpack4(self.clientArea) local contentX,contentY,contentWidth,contentHeight = unpack4(self.contentArea) gl.Scale(2/contentWidth, -2/contentHeight, 1) gl.Translate(-(clientX - self.scrollPosX), -(clientY - self.scrollPosY), 0) end gl.Color(1,1,1,1) gl.AlphaTest(false) gl.StencilTest(true) gl.StencilFunc(GL.EQUAL, 0, 0xFF) gl.StencilOp(GL_KEEP, GL_KEEP, GL_KEEP) gl.BlendFuncSeparate(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA, GL.ZERO, GL.ONE_MINUS_SRC_ALPHA) fnc(self_, ...) --[[ --//Render a red quad to indicate that RTT is used for the respective control gl.Color(1,0,0,0.5) if not drawInContentRect then gl.Rect(self.x,self.y,self.x+50,self.y+50) else gl.Rect(0,0,50,50) end gl.Color(1,1,1,1) --]] gl.Blending("reset") gl.StencilTest(false) end local staticRttTextureParams = { min_filter = GL.NEAREST, mag_filter = GL.NEAREST, wrap_s = GL.CLAMP, wrap_t = GL.CLAMP, border = false, } local staticDepthStencilTarget = { format = GL_DEPTH24_STENCIL8, } function Control:CreateViewTexture(suffix_name, width, height, fnc, ...) if not gl.CreateFBO or not gl.BlendFuncSeparate then self._cantUseRTT = true self._usingRTT = false return end local texname = "_tex_" .. suffix_name local texw = "_texw_" .. suffix_name local texh = "_texh_" .. suffix_name local texStencilName = "_stencil_" .. suffix_name local fboName = "_fbo_" .. suffix_name local fbo = self[fboName] or gl.CreateFBO() local texColor = self[texname] local texStencil = self[texStencilName] if (width ~= self[texw])or(height ~= self[texh]) then self[texw] = width self[texh] = height fbo.color0 = nil fbo.stencil = nil gl.DeleteTexture(texColor) gl.DeleteRBO(texStencil) texColor = gl.CreateTexture(width, height, staticRttTextureParams) texStencil = gl.CreateRBO(width, height, staticDepthStencilTarget) fbo.color0 = texColor fbo.stencil = texStencil end if (not (fbo and texColor and texStencil))or(not gl.IsValidFBO(fbo)) then gl.DeleteFBO(fbo) gl.DeleteTexture(texColor) gl.DeleteRBO(texStencil) self[texw] = nil self[texh] = nil self[texStencilName] = nil self[texname] = nil self[fboName] = nil self._cantUseRTT = true self._usingRTT = false return end EnterRTT() self._inrtt = true gl.ActiveFBO(fbo, true, Control._SetupRTT, self, fnc, ...) self._inrtt = false LeaveRTT() self[texname] = texColor self[texStencilName] = texStencil self[fboName] = fbo end --//============================================================================= function Control:_DrawInClientArea(fnc,...) local clientX,clientY,clientWidth,clientHeight = unpack4(self.clientArea) gl.PushMatrix() gl.Translate(clientX, clientY, 0) local sx,sy = self:LocalToScreen(clientX,clientY) sy = select(2,gl.GetViewSizes()) - (sy + clientHeight) if PushLimitRenderRegion(self, sx, sy, clientWidth, clientHeight) then fnc(...) PopLimitRenderRegion(self, sx, sy, clientWidth, clientHeight) end gl.PopMatrix() end function Control:IsInView() if UnlinkSafe(self.parent) then return self.parent:IsRectInView(self.x, self.y, self.width, self.height) end return false end function Control:IsChildInView(child) return self:IsRectInView(child.x, child.y, child.width, child.height) end function Control:IsRectInView(x,y,w,h) if (not self.parent) then return false end local rect1 = {x,y,w,h} local rect2 = {0,0,self.clientArea[3],self.clientArea[4]} local inview = AreRectsOverlapping(rect1,rect2) if not(inview) then return false end local px,py = self:ClientToParent(x,y) return (self.parent):IsRectInView(px,py,w,h) end function Control:_DrawChildrenInClientArea(event) self:_DrawInClientArea(self.CallChildrenInverseCheckFunc, self, self.IsChildInView, event or 'Draw') end function Control:_DrawChildrenInClientAreaWithoutViewCheck(event) self:_DrawInClientArea(self.CallChildrenInverse, self, event or 'Draw') end --//============================================================================= --//FIXME move resize and drag to Window class!!!! function Control:DrawBackground() --// gets overriden by the skin/theme end function Control:DrawDragGrip() --// gets overriden by the skin/theme end function Control:DrawResizeGrip() --// gets overriden by the skin/theme end function Control:DrawBorder() --// gets overriden by the skin/theme ?????? end function Control:DrawGrips() -- FIXME this thing is a hack, fix it - todo ideally make grips appear only when mouse hovering over it local drawResizeGrip = self.resizable local drawDragGrip = self.draggable and self.dragUseGrip --[[if IsTweakMode() then drawResizeGrip = drawResizeGrip or self.tweakResizable drawDragGrip = (self.tweakDraggable and self.tweakDragUseGrip) end--]] if drawResizeGrip then self:DrawResizeGrip() end if drawDragGrip then self:DrawDragGrip() end end function Control:DrawControl() self:DrawBackground() self:DrawBorder() end function Control:DrawForList() self._redrawCounter = (self._redrawCounter or 0) + 1 if (not self._in_update and not self._usingRTT and self:_CheckIfRTTisAppreciated()) then self:InvalidateSelf() end if (self._tex_all and not self._inrtt) then gl.PushMatrix() gl.Translate(self.x, self.y, 0) gl.BlendFuncSeparate(GL.ONE, GL.SRC_ALPHA, GL.ZERO, GL.SRC_ALPHA) gl.Color(1,1,1,1) gl.Texture(0, self._tex_all) gl.TexRect(0, 0, self.width, self.height) gl.Texture(0, false) gl.BlendFuncSeparate(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA, GL.ZERO, GL.ONE_MINUS_SRC_ALPHA) gl.PopMatrix() return elseif (self._all_dlist) then gl.PushMatrix() gl.Translate(self.x, self.y, 0) gl.CallList(self._all_dlist); gl.PopMatrix() return end gl.PushMatrix() gl.Translate(self.x, self.y, 0) if (self._own_dlist) then gl.CallList(self._own_dlist) else if self._hasCustomDrawControl then gl.Translate(-self.x, -self.y, 0) self:DrawControl() gl.Translate(self.x, self.y, 0) else self:DrawControl() end end local clientX,clientY,clientWidth,clientHeight = unpack4(self.clientArea) if (clientWidth > 0)and(clientHeight > 0) then if (self._tex_children) then gl.BlendFuncSeparate(GL.ONE, GL.SRC_ALPHA, GL.ZERO, GL.SRC_ALPHA) gl.Color(1,1,1,1) gl.Texture(0, self._tex_children) local contX,contY,contWidth,contHeight = unpack4(self.contentArea) local s = self.scrollPosX / contWidth local t = 1 - self.scrollPosY / contHeight local u = s + clientWidth / contWidth local v = t - clientHeight / contHeight gl.TexRect(clientX, clientY, clientX + clientWidth, clientY + clientHeight, s, t, u, v) gl.Texture(0, false) gl.BlendFuncSeparate(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA, GL.ZERO, GL.ONE_MINUS_SRC_ALPHA) elseif (self._children_dlist) then self:_DrawInClientArea(gl.CallList, self._children_dlist) else self:DrawChildrenForList() end if (self.DrawControlPostChildren) then self:DrawControlPostChildren() end end self:DrawGrips() gl.PopMatrix() end function Control:Draw() self._redrawCounter = (self._redrawCounter or 0) + 1 if (not self._in_update and not self._usingRTT and self:_CheckIfRTTisAppreciated()) then self:InvalidateSelf() end if (self.width <= 0)or(self.height <= 0) then return end if (self._tex_all) then gl.PushMatrix() gl.Translate(self.x, self.y, 0) gl.BlendFunc(GL.ONE, GL.SRC_ALPHA) gl.Color(1,1,1,1) gl.Texture(0, self._tex_all) gl.TexRect(0, 0, self.width, self.height) gl.Texture(0, false) gl.Blending("reset") gl.PopMatrix() return elseif (self._all_dlist) then gl.PushMatrix() gl.Translate(self.x, self.y, 0) gl.CallList(self._all_dlist); gl.PopMatrix() return end gl.PushMatrix() gl.Translate(self.x, self.y, 0) if (self._own_dlist) then gl.CallList(self._own_dlist) else if self._hasCustomDrawControl then gl.Translate(-self.x, -self.y, 0) self:DrawControl() gl.Translate(self.x, self.y, 0) else self:DrawControl() end end if (self._children_dlist) then self:_DrawInClientArea(gl.CallList, self._children_dlist) else self:DrawChildren(); end if (self.DrawControlPostChildren) then self:DrawControlPostChildren(); end self:DrawGrips(); gl.PopMatrix() end function Control:TweakDraw() if (next(self.children)) then self:_DrawChildrenInClientArea('TweakDraw') end end function Control:DrawChildren() if (next(self.children)) then self:_DrawChildrenInClientArea('Draw') end end function Control:DrawChildrenForList() if (next(self.children)) then self:_DrawChildrenInClientAreaWithoutViewCheck('DrawForList') end end --//============================================================================= local function InLocalRect(cx,cy,w,h) return (cx>=0)and(cy>=0)and(cx<=w)and(cy<=h) end function Control:HitTest(x,y) if (not self.disableChildrenHitTest) then if self:InClientArea(x,y) then local cax,cay = self:LocalToClient(x,y) local children = self.children for i=1,#children do local c = children[i] if (c) then local cx,cy = c:ParentToLocal(cax,cay) if InLocalRect(cx,cy,c.width,c.height) then local obj = c:HitTest(cx,cy) if (obj) then return obj end end end end end end if (self.NCHitTest) then local nchit = self:NCHitTest(x,y) if (nchit) then return nchit end end if (not self.noSelfHitTest) and (self.tooltip or (#self.OnMouseDown > 0) or (#self.OnMouseUp > 0) or (#self.OnClick > 0) or (#self.OnDblClick > 0) or (#self.OnMouseMove > 0) or (#self.OnMouseWheel > 0)) then return self end return false end function Control:MouseDown(x, y, ...) if (self.NCMouseDown) then local result = self:NCMouseDown(x, y) if (result) then return result end end if (not self.disableChildrenHitTest) then if self:InClientArea(x,y) then local cx,cy = self:LocalToClient(x,y) local obj = inherited.MouseDown(self, cx, cy, ...) if (obj) then return obj end end end if (self.NCMouseDownPostChildren) then local result = self:NCMouseDownPostChildren(x, y) if (result) then return result end end end function Control:MouseMove(x, y, dx, dy, ...) if self.dragging then self:SetPos(self.x + dx, self.y + dy) return self elseif self.resizing then local oldState = self.resizing local deltaMousePosX = x - oldState.mouse[1] local deltaMousePosY = y - oldState.mouse[2] local w = math.max( self.minWidth, oldState.size[1] + deltaMousePosX ) local h = math.max( self.minHeight, oldState.size[2] + deltaMousePosY ) if self.fixedRatio == true then local ratioyx = self.height/self.width local ratioxy = self.width/self.height local oldSize = oldState.size local oldxy = oldSize[1]/oldSize[2] local oldyx = oldSize[2]/oldSize[1] if (ratioxy-oldxy < ratioyx-oldyx) then w = h*oldxy else h = w*oldyx end end self:SetPos(nil,nil,w,h) return self end local cx,cy = self:LocalToClient(x,y) return inherited.MouseMove(self, cx, cy, dx, dy, ...) end function Control:MouseUp(x, y, ...) self.resizing = nil self.dragging = nil local cx,cy = self:LocalToClient(x,y) return inherited.MouseUp(self, cx, cy, ...) end function Control:MouseClick(x, y, ...) local cx,cy = self:LocalToClient(x,y) return inherited.MouseClick(self, cx, cy, ...) end function Control:MouseDblClick(x, y, ...) local cx,cy = self:LocalToClient(x,y) return inherited.MouseDblClick(self, cx, cy, ...) end function Control:MouseWheel(x, y, ...) local cx,cy = self:LocalToClient(x,y) return inherited.MouseWheel(self, cx, cy, ...) end --[[ function Control:KeyPress(...) return inherited.KeyPress(self, ...) end function Control:TextInput(...) return inherited.TextInput(self, ...) end --]] function Control:FocusUpdate(...) self:InvalidateSelf() return inherited.FocusUpdate(self, ...) end function Control:MouseOver(...) inherited.MouseOver(self, ...) self.state.hovered = true self:InvalidateSelf() end function Control:MouseOut(...) inherited.MouseOut(self, ...) self.state.hovered = false self:InvalidateSelf() end --//=============================================================================
gpl-2.0
chuanli11/CNNMRF
transfer_CNNMRF_wrapper.lua
1
22761
require 'torch' require 'nn' require 'image' require 'paths' require 'loadcaffe' paths.dofile('mylib/myoptimizer.lua') paths.dofile('mylib/tv.lua') paths.dofile('mylib/mrf.lua') paths.dofile('mylib/helper.lua') paths.dofile('mylib/content.lua') torch.setdefaulttensortype('torch.FloatTensor') -- float as default tensor type local function main(params) os.execute('mkdir data/result/') os.execute('mkdir data/result/trans/') os.execute('mkdir data/result/trans/MRF/') os.execute(string.format('mkdir %s', params.output_folder)) local net = nn.Sequential() local next_content_idx = 1 local i_net_layer = 0 local num_calls = 0 local content_losses = {} local content_layers = {} local i_content_layer = 0 local next_mrf_idx = 1 local mrf_losses = {} local mrf_layers = {} local i_mrf_layer = 0 local input_image local output_image local cur_res local content_layers_pretrained = params.content_layers local mrf_layers_pretrained = params.mrf_layers ----------------------------------------------------------------------------------- -- read images ----------------------------------------------------------------------------------- local source_image = image.load(string.format('data/content/%s.jpg', params.content_name), 3) local target_image = image.load(string.format('data/style/%s.jpg', params.style_name), 3) source_image = image.scale(source_image, params.max_size, 'bilinear') target_image = image.scale(target_image, params.max_size, 'bilinear') local render_height = source_image:size()[2] local render_width = source_image:size()[3] local source_image_caffe = preprocess(source_image):float() local target_image_caffe = preprocess(target_image):float() local pyramid_source_image_caffe = {} for i_res = 1, params.num_res do pyramid_source_image_caffe[i_res] = image.scale(source_image_caffe, math.ceil(source_image:size()[3] * math.pow(0.5, params.num_res - i_res)), math.ceil(source_image:size()[2] * math.pow(0.5, params.num_res - i_res)), 'bilinear') end local pyramid_target_image_caffe = {} for i_res = 1, params.num_res do pyramid_target_image_caffe[i_res] = image.scale(target_image_caffe, math.ceil(target_image:size()[3] * math.pow(0.5, params.num_res - i_res)), math.ceil(target_image:size()[2] * math.pow(0.5, params.num_res - i_res)), 'bilinear') end ------------------------------------------------------------------------------------------------------ -- local function for adding a content layer ------------------------------------------------------------------------------------------------------ local function add_content() local source = pyramid_source_image_caffe[cur_res]:clone() if params.gpu >= 0 then if params.backend == 'cudnn' then source = source:cuda() else source = source:cl() end end local feature = net:forward(source):clone() -- generate the content target using content image if params.gpu >= 0 then if params.backend == 'cudnn' then feature = feature:cuda() else feature = feature:cl() end end local norm = params.normalize_gradients print(params.normalize_gradients) local loss_module = nn.ContentLoss(params.content_weight, feature, norm):float() if params.gpu >= 0 then if params.backend == 'cudnn' then loss_module:cuda() else loss_module:cl() end end i_content_layer = i_content_layer + 1 i_net_layer = i_net_layer + 1 next_content_idx = next_content_idx + 1 net:add(loss_module) table.insert(content_losses, loss_module) table.insert(content_layers, i_content_layer, i_net_layer) end local function update_content(idx_layer, idx_content) local source = pyramid_source_image_caffe[cur_res]:clone() if params.gpu >= 0 then if params.backend == 'cudnn' then source = source:cuda() else source = source:cl() end end net:forward(source) local feature = net:get(idx_layer).output:clone() if params.gpu >= 0 then if params.backend == 'cudnn' then feature = feature:cuda() else feature = feature:cl() end end local norm = params.normalize_gradients local loss_module = nn.ContentLoss(params.content_weight, feature, norm):float() if params.gpu >= 0 then if params.backend == 'cudnn' then loss_module:cuda() else loss_module:cl() end end net:get(idx_layer):update(loss_module) end -- -------------------------------------------------------------------------------------------------------- -- -- local function for adding a mrf layer, with image rotation andn scaling -- -------------------------------------------------------------------------------------------------------- local function add_mrf() local mrf_module = nn.MRFMM() i_mrf_layer = i_mrf_layer + 1 i_net_layer = i_net_layer + 1 next_mrf_idx = next_mrf_idx + 1 if params.gpu >= 0 then if params.backend == 'cudnn' then mrf_module:cuda() else mrf_module:cl() end end net:add(mrf_module) table.insert(mrf_losses, mrf_module) table.insert(mrf_layers, i_mrf_layer, i_net_layer) return true end local function build_mrf(id_mrf) -------------------------------------------------------- -- deal with target -------------------------------------------------------- local target_images_caffe = {} for i_r = -params.target_num_rotation, params.target_num_rotation do local alpha = params.target_step_rotation * i_r local min_x, min_y, max_x, max_y = computeBB(pyramid_target_image_caffe[cur_res]:size()[3], pyramid_target_image_caffe[cur_res]:size()[2], alpha) local target_image_rt_caffe = image.rotate(pyramid_target_image_caffe[cur_res], alpha, 'bilinear') target_image_rt_caffe = target_image_rt_caffe[{{1, target_image_rt_caffe:size()[1]}, {min_y, max_y}, {min_x, max_x}}] for i_s = -params.target_num_scale, params.target_num_scale do local max_sz = math.floor(math.max(target_image_rt_caffe:size()[2], target_image_rt_caffe:size()[3]) * torch.pow(params.target_step_scale, i_s)) local target_image_rt_s_caffe = image.scale(target_image_rt_caffe, max_sz, 'bilinear') if params.gpu >= 0 then if params.backend == 'cudnn' then target_image_rt_s_caffe = target_image_rt_s_caffe:cuda() else target_image_rt_s_caffe = target_image_rt_s_caffe:cl() end end table.insert(target_images_caffe, target_image_rt_s_caffe) end end -- compute the coordinates on the pixel layer local target_x local target_y local target_x_per_image = {} local target_y_per_image = {} local target_imageid -- print('*****************************************************') -- print(string.format('build target mrf')); -- print('*****************************************************') for i_image = 1, #target_images_caffe do -- print(string.format('image %d, ', i_image)) net:forward(target_images_caffe[i_image]) local target_feature_map = net:get(mrf_layers[id_mrf] - 1).output:float() if params.mrf_patch_size[id_mrf] > target_feature_map:size()[2] or params.mrf_patch_size[id_mrf] > target_feature_map:size()[3] then print('target_images is not big enough for patch') print('target_images size: ') print(target_feature_map:size()) print('patch size: ') print(params.mrf_patch_size[id_mrf]) do return end end local target_x_, target_y_ = drill_computeMRFfull(target_feature_map, params.mrf_patch_size[id_mrf], params.target_sample_stride[id_mrf], -1) local x = torch.Tensor(target_x_:nElement() * target_y_:nElement()) local y = torch.Tensor(target_x_:nElement() * target_y_:nElement()) local target_imageid_ = torch.Tensor(target_x_:nElement() * target_y_:nElement()):fill(i_image) local count = 1 for i_row = 1, target_y_:nElement() do for i_col = 1, target_x_:nElement() do x[count] = target_x_[i_col] y[count] = target_y_[i_row] count = count + 1 end end if i_image == 1 then target_x = x:clone() target_y = y:clone() target_imageid = target_imageid_:clone() else target_x = torch.cat(target_x, x, 1) target_y = torch.cat(target_y, y, 1) target_imageid = torch.cat(target_imageid, target_imageid_, 1) end table.insert(target_x_per_image, x) table.insert(target_y_per_image, y) end -- end for i_image = 1, #target_images do -- print('*****************************************************') -- print(string.format('collect mrf')); -- print('*****************************************************') local num_channel_mrf = net:get(mrf_layers[id_mrf] - 1).output:size()[1] local target_mrf = torch.Tensor(target_x:nElement(), num_channel_mrf * params.mrf_patch_size[id_mrf] * params.mrf_patch_size[id_mrf]) local tensor_target_mrf = torch.Tensor(target_x:nElement(), num_channel_mrf, params.mrf_patch_size[id_mrf], params.mrf_patch_size[id_mrf]) local count_mrf = 1 for i_image = 1, #target_images_caffe do -- print(string.format('image %d, ', i_image)); net:forward(target_images_caffe[i_image]) -- sample mrf on mrf_layers local tensor_target_mrf_, target_mrf_ = sampleMRFAndTensorfromLocation2(target_x_per_image[i_image], target_y_per_image[i_image], net:get(mrf_layers[id_mrf] - 1).output:float(), params.mrf_patch_size[id_mrf]) target_mrf[{{count_mrf, count_mrf + target_mrf_:size()[1] - 1}, {1, target_mrf:size()[2]}}] = target_mrf_:clone() tensor_target_mrf[{{count_mrf, count_mrf + target_mrf_:size()[1] - 1}, {1, tensor_target_mrf:size()[2]}, {1, tensor_target_mrf:size()[3]}, {1, tensor_target_mrf:size()[4]}}] = tensor_target_mrf_:clone() count_mrf = count_mrf + target_mrf_:size()[1] tensor_target_mrf_ = nil target_mrf_ = nil collectgarbage() end --for i_image = 1, #target_images do local target_mrfnorm = torch.sqrt(torch.sum(torch.cmul(target_mrf, target_mrf), 2)):resize(target_mrf:size()[1], 1, 1) -------------------------------------------------------- -- process source -------------------------------------------------------- -- print('*****************************************************') -- print(string.format('process source image')); -- print('*****************************************************') if params.gpu >= 0 then if params.backend == 'cudnn' then net:forward(pyramid_source_image_caffe[cur_res]:cuda()) else net:forward(pyramid_source_image_caffe[cur_res]:cl()) end else net:forward(pyramid_source_image_caffe[cur_res]) end local source_feature_map = net:get(mrf_layers[id_mrf] - 1).output:float() if params.mrf_patch_size[id_mrf] > source_feature_map:size()[2] or params.mrf_patch_size[id_mrf] > source_feature_map:size()[3] then print('source_image_caffe is not big enough for patch') print('source_image_caffe size: ') print(source_feature_map:size()) print('patch size: ') print(params.mrf_patch_size[id_mrf]) do return end end local source_xgrid, source_ygrid = drill_computeMRFfull(source_feature_map:float(), params.mrf_patch_size[id_mrf], params.source_sample_stride[id_mrf], -1) local source_x = torch.Tensor(source_xgrid:nElement() * source_ygrid:nElement()) local source_y = torch.Tensor(source_xgrid:nElement() * source_ygrid:nElement()) local count = 1 for i_row = 1, source_ygrid:nElement() do for i_col = 1, source_xgrid:nElement() do source_x[count] = source_xgrid[i_col] source_y[count] = source_ygrid[i_row] count = count + 1 end end -- local tensor_target_mrfnorm = torch.repeatTensor(target_mrfnorm:float(), 1, net:get(mrf_layers[id_mrf] - 1).output:size()[2] - (params.mrf_patch_size[id_mrf] - 1), net:get(mrf_layers[id_mrf] - 1).output:size()[3] - (params.mrf_patch_size[id_mrf] - 1)) -- print('*****************************************************') -- print(string.format('call layer implemetation')); -- print('*****************************************************') local nInputPlane = target_mrf:size()[2] / (params.mrf_patch_size[id_mrf] * params.mrf_patch_size[id_mrf]) local nOutputPlane = target_mrf:size()[1] local kW = params.mrf_patch_size[id_mrf] local kH = params.mrf_patch_size[id_mrf] local dW = 1 local dH = 1 local input_size = source_feature_map:size() local source_xgrid_, source_ygrid_ = drill_computeMRFfull(source_feature_map:float(), params.mrf_patch_size[id_mrf], 1, -1) local response_size = torch.LongStorage(3) response_size[1] = nOutputPlane response_size[2] = source_ygrid_:nElement() response_size[3] = source_xgrid_:nElement() net:get(mrf_layers[id_mrf]):implement(params.mode, target_mrf, tensor_target_mrf, target_mrfnorm, source_x, source_y, input_size, response_size, nInputPlane, nOutputPlane, kW, kH, 1, 1, params.mrf_confidence_threshold[id_mrf], params.mrf_weight[id_mrf], params.gpu_chunck_size_1, params.gpu_chunck_size_2, params.backend, params.gpu) target_mrf = nil tensor_target_mrf = nil source_feature_map = nil collectgarbage() end -------------------------------------------------------------------------------------------------------- -- local function for printing inter-mediate result -------------------------------------------------------------------------------------------------------- local function maybe_print(t, loss) local verbose = (params.print_iter > 0 and t % params.print_iter == 0) if verbose then print(string.format('Iteration %d, %d', t, params.num_iter[cur_res])) end end -------------------------------------------------------------------------------------------------------- -- local function for saving inter-mediate result -------------------------------------------------------------------------------------------------------- local function maybe_save(t) local should_save = params.save_iter > 0 and t % params.save_iter == 0 should_save = should_save or t == params.num_iter if should_save then local disp = deprocess(input_image:float()) disp = image.minmax{tensor=disp, min=0, max=1} disp = image.scale(disp, render_width, render_height, 'bilinear') local filename = string.format('%s/res_%d_%d.jpg', params.output_folder, cur_res, t) image.save(filename, disp) end end -------------------------------------------------------------------------------------------------------- -- local function for computing energy -------------------------------------------------------------------------------------------------------- local function feval(x) num_calls = num_calls + 1 net:forward(x) local grad = net:backward(x, dy) local loss = 0 collectgarbage() maybe_print(num_calls, loss) maybe_save(num_calls) -- optim.lbfgs expects a vector for gradients return loss, grad:view(grad:nElement()) end ------------------------------------------------------------------------------- -- initialize network ------------------------------------------------------------------------------- if params.gpu >= 0 then if params.backend == 'cudnn' then require 'cutorch' require 'cunn' cutorch.setDevice(params.gpu + 1) else require 'cltorch' require 'clnn' cltorch.setDevice(params.gpu + 1) end else params.backend = 'nn' end if params.backend == 'cudnn' then require 'cudnn' end local loadcaffe_backend = params.backend if params.backend == 'clnn' then loadcaffe_backend = 'nn' end local cnn = loadcaffe.load(params.proto_file, params.model_file, loadcaffe_backend):float() if params.gpu >= 0 then if params.backend == 'cudnn' then cnn:cuda() else cnn:cl() end end print('cnn succesfully loaded') for i_res = 1, params.num_res do local timer = torch.Timer() cur_res = i_res num_calls = 0 local optim_state = { maxIter = params.num_iter[i_res], nCorrection = params.nCorrection, verbose=true, tolX = 0, tolFun = 0, } -- initialize image and target if i_res == 1 then if params.ini_method == 'random' then input_image = torch.randn(pyramid_source_image_caffe[i_res]:size()):float():mul(0.001) elseif params.ini_method == 'image' then input_image = pyramid_source_image_caffe[i_res]:clone():float() else error('Invalid init type') end if params.gpu >= 0 then if params.backend == 'cudnn' then input_image = input_image:cuda() else input_image = input_image:cl() end end ----------------------------------------------------- -- add a tv layer ----------------------------------------------------- if params.tv_weight > 0 then local tv_mod = nn.TVLoss(params.tv_weight):float() if params.gpu >= 0 then if params.backend == 'cudnn' then tv_mod:cuda() else tv_mod:cl() end end i_net_layer = i_net_layer + 1 net:add(tv_mod) end for i = 1, #cnn do if next_content_idx <= #content_layers_pretrained or next_mrf_idx <= #mrf_layers_pretrained then local layer = cnn:get(i) i_net_layer = i_net_layer + 1 net:add(layer) -- add a content_losses layer if i == content_layers_pretrained[next_content_idx] then add_content() end -- -- add mrfstatsyn layer if i == mrf_layers_pretrained[next_mrf_idx] then if add_mrf() == false then print('build network failed: adding mrf layer failed') do return end end end end end -- for i = 1, #cnn do cnn = nil collectgarbage() print(net) print('content_layers: ') for i = 1, #content_layers do print(content_layers[i]) end print('mrf_layers: ') for i = 1, #mrf_layers do print(mrf_layers[i]) end print('network has been built.') else input_image = image.scale(input_image:float(), pyramid_source_image_caffe[i_res]:size()[3], pyramid_source_image_caffe[i_res]:size()[2], 'bilinear'):clone() if params.gpu >= 0 then if params.backend == 'cudnn' then input_image = input_image:cuda() else input_image = input_image:cl() end end -- -- update content layers for i_layer = 1, #content_layers do update_content(content_layers[i_layer], i_layer) -- print(string.format('content_layers %d has been updated', content_layers[i_layer])) end end print('*****************************************************') print(string.format('Synthesis started at resolution ', cur_res)) print('*****************************************************') print('Implementing mrf layers ...') for i = 1, #mrf_layers do if build_mrf(i) == false then print('build_mrf failed') do return end end end local mask = torch.Tensor(input_image:size()):fill(1) if params.gpu >= 0 then if params.backend == 'cudnn' then mask = mask:cuda() else mask = mask:cl() end end y = net:forward(input_image) dy = input_image.new(#y):zero() -- do optimizatoin local x, losses = mylbfgs(feval, input_image, optim_state, nil, mask) local t = timer:time().real print(string.format('Synthesis finished at resolution %d, %f seconds', cur_res, t)) end net = nil source_image = nil target_image = nil pyramid_source_image_caffe = nil pyramid_target_image_caffe = nil input_image = nil output_image = nil content_losses = nil content_layers = nil mrf_losses = nil mrf_layers = nil optim_state = nil collectgarbage() collectgarbage() end -- end of main local function run_test(content_name, style_name, ini_method, max_size, num_res, num_iter, mrf_layers, mrf_weight, mrf_patch_size, mrf_num_rotation, mrf_num_scale, mrf_sample_stride, mrf_synthesis_stride, mrf_confidence_threshold, content_layers, content_weight, tv_weight, mode, gpu_chunck_size_1, gpu_chunck_size_2, backend) -- local clock = os.clock -- function sleep(n) -- seconds -- local t0 = clock() -- while clock() - t0 <= n do end -- end local timer_TEST = torch.Timer() local flag_state = 1 local params = {} -- externally set paramters params.content_name = content_name params.style_name = style_name params.ini_method = ini_method params.max_size = max_size or 384 params.num_res = num_res or 3 params.num_iter = num_iter or {100, 100, 100} params.mrf_layers = mrf_layers or {12, 21} params.mrf_weight = mrf_weight or {1e-4, 1e-4} params.mrf_patch_size = mrf_patch_size or {3, 3} params.target_num_rotation = mrf_num_rotation or 0 params.target_num_scale = mrf_num_scale or 0 params.target_sample_stride = mrf_sample_stride or {2, 2} params.source_sample_stride = mrf_synthesis_stride or {2, 2} params.mrf_confidence_threshold = mrf_confidence_threshold or {0, 0} params.content_layers = content_layers or {21} params.content_weight = content_weight or 2e1 params.tv_weight = tv_weight or 1e-3 params.mode = mode or 'speed' params.gpu_chunck_size_1 = gpu_chunck_size_1 or 256 params.gpu_chunck_size_2 = gpu_chunck_size_2 or 16 params.backend = backend or 'cudnn' -- fixed parameters params.target_step_rotation = math.pi/24 params.target_step_scale = 1.05 params.output_folder = string.format('data/result/trans/MRF/%s_TO_%s',params.content_name, params.style_name) params.proto_file = 'data/models/VGG_ILSVRC_19_layers_deploy.prototxt' params.model_file = 'data/models/VGG_ILSVRC_19_layers.caffemodel' params.gpu = 0 params.nCorrection = 25 params.print_iter = 10 params.save_iter = 10 params.output_folder = string.format('data/result/trans/MRF/%s_TO_%s',params.content_name, params.style_name) main(params) local t_test = timer_TEST:time().real print(string.format('Total time: %f seconds', t_test)) -- sleep(1) return flag_state end return { run_test = run_test, main = main }
mit
KlonZK/Zero-K
scripts/benzcom.lua
4
9320
include "constants.lua" local spSetUnitShieldState = Spring.SetUnitShieldState -------------------------------------------------------------------------------- -- pieces -------------------------------------------------------------------------------- local pieceMap = Spring.GetUnitPieceMap(unitID) local HAS_GATTLING = pieceMap.rgattlingflare and true or false local HAS_BONUS_CANNON = pieceMap.bonuscannonflare and true or false local torso = piece 'torso' local rcannon_flare= HAS_GATTLING and piece('rgattlingflare') or piece('rcannon_flare') local barrels= HAS_GATTLING and piece 'barrels' or nil local lcannon_flare = HAS_BONUS_CANNON and piece('bonuscannonflare') or piece('lnanoflare') local lnanoflare = piece 'lnanoflare' local lnanohand = piece 'lnanohand' local larm = piece 'larm' local rarm = piece 'rarm' local pelvis = piece 'pelvis' local rupleg = piece 'rupleg' local lupleg = piece 'lupleg' local rhand = piece 'rhand' local lleg = piece 'lleg' local lfoot = piece 'lfoot' local rleg = piece 'rleg' local rfoot = piece 'rfoot' local smokePiece = {torso} local nanoPieces = {lnanoflare} -------------------------------------------------------------------------------- -- constants -------------------------------------------------------------------------------- local SIG_MOVE = 1 local SIG_LASER = 2 local SIG_DGUN = 4 local SIG_RESTORE_LASER = 8 local SIG_RESTORE_DGUN = 16 local TORSO_SPEED_YAW = math.rad(300) local ARM_SPEED_PITCH = math.rad(180) local PACE = 1.6 local BASE_VELOCITY = UnitDefNames.benzcom1.speed or 1.25*30 local VELOCITY = UnitDefs[unitDefID].speed or BASE_VELOCITY PACE = PACE * VELOCITY/BASE_VELOCITY local THIGH_FRONT_ANGLE = -math.rad(40) local THIGH_FRONT_SPEED = math.rad(40) * PACE local THIGH_BACK_ANGLE = math.rad(20) local THIGH_BACK_SPEED = math.rad(40) * PACE local SHIN_FRONT_ANGLE = math.rad(35) local SHIN_FRONT_SPEED = math.rad(60) * PACE local SHIN_BACK_ANGLE = math.rad(5) local SHIN_BACK_SPEED = math.rad(60) * PACE local ARM_FRONT_ANGLE = -math.rad(15) local ARM_FRONT_SPEED = math.rad(14.5) * PACE local ARM_BACK_ANGLE = math.rad(5) local ARM_BACK_SPEED = math.rad(14.5) * PACE local ARM_PERPENDICULAR = math.rad(90) --[[ local FOREARM_FRONT_ANGLE = -math.rad(15) local FOREARM_FRONT_SPEED = math.rad(40) * PACE local FOREARM_BACK_ANGLE = -math.rad(10) local FOREARM_BACK_SPEED = math.rad(40) * PACE ]]-- local TORSO_ANGLE_MOTION = math.rad(8) local TORSO_SPEED_MOTION = math.rad(7)*PACE local RESTORE_DELAY_LASER = 4000 local RESTORE_DELAY_DGUN = 2500 -------------------------------------------------------------------------------- -- vars -------------------------------------------------------------------------------- local isMoving, isLasering, isDgunning, gunLockOut, shieldOn = false, false, false, false, true local restoreHeading, restorePitch = 0, 0 local flamers = {} local starBLaunchers = {} local wepTable = UnitDefs[unitDefID].weapons wepTable.n = nil for index, weapon in pairs(wepTable) do local weaponDef = WeaponDefs[weapon.weaponDef] if weaponDef.type == "Flame" then flamers[index] = true elseif weaponDef.type == "StarburstLauncher" then starBLaunchers[index] = true --Spring.Echo("sbl found") end end wepTable = nil -------------------------------------------------------------------------------- -- funcs -------------------------------------------------------------------------------- local function Walk() Signal(SIG_WALK) SetSignalMask(SIG_WALK) while true do --left leg up, right leg back Turn(lupleg, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED) Turn(lleg, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED) Turn(rupleg, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED) Turn(rleg, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED) if not(isLasering or isDgunning) then --left arm back, right arm front Turn(torso, y_axis, TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION) -- Turn(larm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED) -- Turn(rarm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED) end WaitForTurn(lupleg, x_axis) Sleep(0) --right leg up, left leg back Turn(lupleg, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED) Turn(lleg, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED) Turn(rupleg, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED) Turn(rleg, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED) if not(isLasering or isDgunning) then --left arm front, right arm back Turn(torso, y_axis, -TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION) -- Turn(larm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED) -- Turn(rarm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED) end WaitForTurn(rupleg, x_axis) Sleep(0) end end local function RestoreLegs() Signal(SIG_WALK) SetSignalMask(SIG_WALK) Move(pelvis, y_axis, 0, 1) Turn(rupleg, x_axis, 0, math.rad(200)) Turn(rleg, x_axis, 0, math.rad(200)) Turn(lupleg, x_axis, 0, math.rad(200)) Turn(lleg, x_axis, 0, math.rad(200)) Turn(torso, y_axis, 0, math.rad(200)) Turn(larm, x_axis, 0, math.rad(200)) Turn(rarm, x_axis, 0, math.rad(200)) end function script.Create() Hide(rcannon_flare) Hide(lnanoflare) -- Turn(larm, x_axis, math.rad(30)) -- Turn(rarm, x_axis, math.rad(-10)) -- Turn(rhand, x_axis, math.rad(41)) -- Turn(lnanohand, x_axis, math.rad(36)) StartThread(SmokeUnit, smokePiece) Spring.SetUnitNanoPieces(unitID, nanoPieces) end function script.StartMoving() isMoving = true StartThread(Walk) end function script.StopMoving() isMoving = false StartThread(RestoreLegs) end local function RestoreLaser() Signal(SIG_RESTORE_LASER) SetSignalMask(SIG_RESTORE_LASER) Sleep(RESTORE_DELAY_LASER) isLasering = false Turn(larm, x_axis, 0, ARM_SPEED_PITCH) Turn(lnanohand, x_axis, 0, ARM_SPEED_PITCH) Turn(rarm, x_axis, restorePitch, ARM_SPEED_PITCH) Turn(rhand, x_axis, 0, ARM_SPEED_PITCH) Turn(torso, y_axis, restoreHeading, TORSO_SPEED_YAW) if HAS_GATTLING then Spin(barrels, z_axis, 100) Sleep(200) Turn(barrels, z_axis, 0, ARM_SPEED_PITCH) end end local function RestoreDGun() Signal(SIG_RESTORE_DGUN) SetSignalMask(SIG_RESTORE_DGUN) Sleep(RESTORE_DELAY_DGUN) isDgunning = false Turn(larm, x_axis, 0, ARM_SPEED_PITCH) Turn(lnanohand, x_axis, 0, ARM_SPEED_PITCH) Turn(rarm, x_axis, restorePitch, ARM_SPEED_PITCH) Turn(rhand, x_axis, 0, ARM_SPEED_PITCH) Turn(torso, y_axis, restoreHeading, TORSO_SPEED_YAW) end function script.AimWeapon(num, heading, pitch) if num >= 5 then Signal(SIG_LASER) SetSignalMask(SIG_LASER) isLasering = true Turn(rarm, x_axis, math.rad(0) -pitch, ARM_SPEED_PITCH) Turn(torso, y_axis, heading, TORSO_SPEED_YAW) Turn(rhand, x_axis, math.rad(0), ARM_SPEED_PITCH) WaitForTurn(torso, y_axis) WaitForTurn(rarm, x_axis) StartThread(RestoreLaser) return true elseif num == 3 then if starBLaunchers[num] then pitch = ARM_PERPENDICULAR end Signal(SIG_DGUN) SetSignalMask(SIG_DGUN) isDgunning = true Turn(larm, x_axis, math.rad(0) -pitch, ARM_SPEED_PITCH) Turn(torso, y_axis, heading, TORSO_SPEED_YAW) Turn(lnanohand, x_axis, math.rad(0), ARM_SPEED_PITCH) WaitForTurn(torso, y_axis) WaitForTurn(rarm, x_axis) StartThread(RestoreDGun) return true elseif num == 2 or num == 4 then Sleep(100) return (shieldOn) end return false end function script.FireWeapon(num) if num == 5 then EmitSfx(rcannon_flare, 1024) elseif num == 3 then EmitSfx(lcannon_flare, 1026) end end function script.Shot(num) if num == 5 then EmitSfx(rcannon_flare, 1025) elseif num == 3 then EmitSfx(lcannon_flare, 1027) end if flamers[num] then --GG.LUPS.FlameShot(unitID, unitDefID, _, num) end end function script.AimFromWeapon(num) return torso end function script.QueryWeapon(num) if num == 3 then return lcannon_flare elseif num == 2 or num == 4 then return torso end return rcannon_flare end function script.StopBuilding() SetUnitValue(COB.INBUILDSTANCE, 0) Turn(larm, x_axis, 0, ARM_SPEED_PITCH) restoreHeading, restorePitch = 0, 0 StartThread(RestoreDGun) end function script.StartBuilding(heading, pitch) restoreHeading, restorePitch = heading, pitch Turn(larm, x_axis, math.rad(-30) - pitch, ARM_SPEED_PITCH) if not (isDgunning) then Turn(torso, y_axis, heading, TORSO_SPEED_YAW) end SetUnitValue(COB.INBUILDSTANCE, 1) end function script.QueryNanoPiece() GG.LUPS.QueryNanoPiece(unitID,unitDefID,Spring.GetUnitTeam(unitID),lnanoflare) return lnanoflare end function script.Activate() --spSetUnitShieldState(unitID, 2, true) end function script.Deactivate() --spSetUnitShieldState(unitID, 2, false) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity < 0.5 then Explode(torso, sfxNone) Explode(larm, sfxNone) Explode(rarm, sfxNone) Explode(pelvis, sfxNone) Explode(lupleg, sfxNone) Explode(rupleg, sfxNone) Explode(lnanoflare, sfxNone) Explode(rhand, sfxNone) Explode(lleg, sfxNone) Explode(rleg, sfxNone) return 1 else Explode(torso, sfxShatter) Explode(larm, sfxSmoke + sfxFire + sfxExplode) Explode(rarm, sfxSmoke + sfxFire + sfxExplode) Explode(pelvis, sfxShatter) Explode(lupleg, sfxShatter) Explode(rupleg, sfxShatter) Explode(lnanoflare, sfxSmoke + sfxFire + sfxExplode) Explode(rhand, sfxSmoke + sfxFire + sfxExplode) Explode(lleg, sfxShatter) Explode(rleg, sfxShatter) return 2 end end
gpl-2.0
meisme/ProjectPorcupine
Assets/StreamingAssets/LUA/Overlay.lua
10
2025
-- Example of overlay function -- Input: tile, the current tile for which the -- overlay wants to display the data -- Input: world, world class -- Return: an integer (by default should be scaled between 0 and 255) function oxygenValueAt(tile) if tile == nil then return 0 end room = tile.room if room == nil then return 0 end if (room.GetGasAmount("O2") > 0) then return 128 end return 0 end -- Returns room id or null if room or tile invalid function roomNumberValueAt(tile) if tile == nil or tile.room == nil then return 0 else return tile.room.ID end end -- Returns a magic value if furniture in tile is a power gen function powerValueAt(tile) zero = 128 -- This is middle between 0 and 256 multiplier = 12,8 -- For now 1 power is 40 in overlay if (tile == nil or tile.furniture == nil or tile.furniture.PowerConnection == nil) then return zero end if (tile.furniture.PowerConnection.IsPowerConsumer) then zero = zero - tile.furniture.PowerConnection.InputRate * multiplier end if (tile.furniture.PowerConnection.IsPowerProducer) then zero = zero + tile.furniture.PowerConnection.OutputRate * multiplier end return ModUtils.Clamp(zero, 0, 256) end -- Return temperature (in K) in current tile function temperatureValueAt(tile, world) --if world == nil or world.current == nil or world.current.temperature == nil then -- return -1 --end --if tile == nil then -- return -2 --end return math.max(math.min(world.temperature.GetTemperature(tile.X, tile.Y, tile.Z) / 3, 254), 0) end -- Returns coloring of thermal diffusivity of tile function thermalDiffusivityValueAt(tile, world) if tile == nil then return 255 else return math.max(math.min(254*world.temperature.GetThermalDiffusivity(tile.X, tile.Y, tile.Z))) end end -- Dummy function, will be implemented function heatGenerationValueAt(tile, world) return 0 end
gpl-3.0
KlonZK/Zero-K
LuaRules/Configs/MetalSpots/Altored_Arctic.lua
17
3564
return { spots = { {x = 7832, z = 3208, metal = 1.1840000152588}, {x = 6152, z = 3816, metal = 1.9776002168655}, {x = 1128, z = 6520, metal = 1.1296001672745}, {x = 1928, z = 6312, metal = 1.8752002716064}, {x = 7256, z = 2984, metal = 1.4048000574112}, {x = 6296, z = 6936, metal = 1.1055999994278}, {x = 3256, z = 488, metal = 1.2800002098083}, {x = 5352, z = 1160, metal = 1.2832000255585}, {x = 152, z = 3160, metal = 1.2016000747681}, {x = 232, z = 5688, metal = 1.1391999721527}, {x = 3480, z = 4744, metal = 1.8528002500534}, {x = 3016, z = 984, metal = 1.2912000417709}, {x = 2120, z = 4456, metal = 1.8432002067566}, {x = 2008, z = 5064, metal = 0.8}, {x = 1176, z = 7736, metal = 0.85}, {x = 3320, z = 3512, metal = 2.0240001678467}, {x = 2904, z = 616, metal = 1.2799999713898}, {x = 7320, z = 488, metal = 0.8}, {x = 1864, z = 1368, metal = 0.85}, {x = 4920, z = 6072, metal = 0.85}, {x = 2520, z = 7752, metal = 1.1696000099182}, {x = 6680, z = 6488, metal = 0.8}, {x = 2024, z = 1848, metal = 1.7472001314163}, {x = 6952, z = 3992, metal = 1.8863999843597}, {x = 584, z = 840, metal = 0.8}, {x = 6360, z = 2632, metal = 1.1504000425339}, {x = 6120, z = 5064, metal = 0.8}, {x = 1512, z = 1960, metal = 1.8016002178192}, {x = 5352, z = 712, metal = 1.1520000696182}, {x = 3208, z = 7832, metal = 1.3472000360489}, {x = 952, z = 488, metal = 0.8}, {x = 3800, z = 6152, metal = 1.7152000665665}, {x = 7304, z = 5432, metal = 1.2832001447678}, {x = 4648, z = 4712, metal = 1.8704000711441}, {x = 2552, z = 6456, metal = 1.2832002639771}, {x = 7736, z = 808, metal = 0.8}, {x = 3992, z = 2008, metal = 1.8384000062943}, {x = 5096, z = 7640, metal = 1.2160001993179}, {x = 3240, z = 6072, metal = 0.85}, {x = 6408, z = 1368, metal = 1.3008000850677}, {x = 5432, z = 6376, metal = 1.1920000314713}, {x = 2840, z = 7320, metal = 1.2400000095367}, {x = 4952, z = 792, metal = 1.1599999666214}, {x = 6808, z = 1864, metal = 0.85}, {x = 1736, z = 5768, metal = 1.1472001075745}, {x = 4056, z = 1288, metal = 1.902400135994}, {x = 5976, z = 4424, metal = 1.8352001905441}, {x = 904, z = 3080, metal = 1.2704000473022}, {x = 7480, z = 2744, metal = 1.0960000753403}, {x = 5688, z = 7752, metal = 1.1888000965118}, {x = 7096, z = 7752, metal = 0.85}, {x = 408, z = 7112, metal = 0.85}, {x = 5416, z = 7176, metal = 1.8271999359131}, {x = 7720, z = 7112, metal = 0.8}, {x = 2008, z = 3288, metal = 0.85}, {x = 4248, z = 4008, metal = 1.9248002767563}, {x = 4808, z = 3464, metal = 1.8000000715256}, {x = 4168, z = 7112, metal = 1.8704000711441}, {x = 6344, z = 1880, metal = 1.689600110054}, {x = 1960, z = 6808, metal = 0.8}, {x = 5688, z = 1704, metal = 1.1376001834869}, {x = 3128, z = 2120, metal = 0.85}, {x = 536, z = 2712, metal = 1.1296000480652}, {x = 1976, z = 3976, metal = 1.8224002122879}, {x = 808, z = 5464, metal = 1.1407999992371}, {x = 456, z = 5048, metal = 1.1647999286652}, {x = 6520, z = 5592, metal = 1.100800037384}, {x = 7816, z = 5496, metal = 1.2976001501083}, {x = 2728, z = 1752, metal = 1.1648000478745}, {x = 1688, z = 2760, metal = 1.4112000465393}, {x = 7464, z = 4920, metal = 1.1439999341965}, {x = 4520, z = 2104, metal = 1.8736000061035}, {x = 4360, z = 6328, metal = 1.977599978447}, {x = 6344, z = 6392, metal = 1.8496000766754}, {x = 5272, z = 1976, metal = 0.8}, {x = 6040, z = 3256, metal = 0.85}, {x = 1464, z = 4200, metal = 1.8784000873566}, {x = 4089, z = 4127, metal = 1.8912000656128}, {x = 3922, z = 4201, metal = 1.7120002508163}, } }
gpl-2.0
KlonZK/Zero-K
LuaRules/Gadgets/unit_transport_ai_buttons.lua
10
9075
-- $Id: unit_transport_ai_buttons.lua 3986 2009-02-22 01:56:11Z licho $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "TransportAIbuttons", desc = "Adds buttons for transport AI widget", author = "Licho", date = "1.11.2007,30.3.2013", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -- «COMMON» ------------------------------------------------------------------ -------------------------------------------------------------------------------- if (gadgetHandler:IsSyncedCode()) then -------------------------------------------------------------------------------- -- «SYNCED» ------------------------------------------------------------------ -------------------------------------------------------------------------------- --Speed-ups local FindUnitCmdDesc = Spring.FindUnitCmdDesc; local InsertUnitCmdDesc = Spring.InsertUnitCmdDesc; local RemoveUnitCmdDesc = Spring.RemoveUnitCmdDesc; local GiveOrderToUnit = Spring.GiveOrderToUnit; local GetUnitDefID = Spring.GetUnitDefID; local GetTeamUnits = Spring.GetTeamUnits; local CMD_WAIT = CMD.WAIT; local CMD_ONOFF = CMD.ONOFF; local CMD_REPEAT = CMD.REPEAT; local CMD_MOVE_STATE = CMD.MOVE_STATE; local CMD_FIRE_STATE = CMD.FIRE_STATE; local CMD_ONOFF = CMD.ONOFF local gaiaID = Spring.GetGaiaTeamID(); -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- commands include("LuaRules/Configs/customcmds.h.lua") local embarkCmdDesc = { id = CMD_EMBARK, --defined in customcmds.h.lua type = CMDTYPE.ICON, name = 'Embark', cursor = 'Attack', action = 'embark', tooltip = 'Transport to location, or queue Embark point (SHIFT)', params = {"alt"} } local disembarkCmdDesc = { id = CMD_DISEMBARK, --defined in customcmds.h.lua type = CMDTYPE.ICON, name = 'Disembark', cursor = 'Attack', action = 'disembark', tooltip = 'Transport to location, or queue Disembark point (SHIFT)', params = {"alt", "ctrl"} } local transportToCmdDesc = { id = CMD_TRANSPORTTO, --defined in customcmds.h.lua type = CMDTYPE.ICON_MAP, --has coordinate name = 'TransportTo', hidden = true, cursor = 'Attack', action = 'transportto', tooltip = 'Transport To location.', } local transDefs = { [ UnitDefNames['corvalk'].id ] = true, [ UnitDefNames['corbtrans'].id ] = true, } local factDefs = { [ UnitDefNames['factorycloak'].id ] = true, [ UnitDefNames['factoryshield'].id ] = true, [ UnitDefNames['factoryspider'].id ] = true, [ UnitDefNames['factoryjump'].id ] = true, [ UnitDefNames['factoryhover'].id ] = true, [ UnitDefNames['factoryveh'].id ] = true, [ UnitDefNames['factorytank'].id ] = true, [ UnitDefNames['factoryamph'].id ] = true, } local hasTransports = {} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function AddCmdDesc(unitID) local insertID = 500 InsertUnitCmdDesc(unitID, insertID+1, embarkCmdDesc); InsertUnitCmdDesc(unitID, insertID+2, disembarkCmdDesc); InsertUnitCmdDesc(unitID, insertID+3, transportToCmdDesc); end local function RemoveCmdDesc(unitID) local cmdEmbarkID = FindUnitCmdDesc(unitID, CMD_EMBARK) RemoveUnitCmdDesc(unitID, cmdEmbarkID); local cmdDisembarkID = FindUnitCmdDesc(unitID, CMD_DISEMBARK) RemoveUnitCmdDesc(unitID, cmdDisembarkID); local cmdTransportToID = FindUnitCmdDesc(unitID, CMD_TRANSPORTTO) RemoveUnitCmdDesc(unitID, cmdTransportToID); end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function IsTransportable(unitDefID) ud = UnitDefs[unitDefID] if (ud == nil) then return false end udc = ud.springCategories return (udc~= nil and ud.speed > 0 and not ud.canFly) end function gadget:UnitCreated(unitID, unitDefID, teamID) if (hasTransports[teamID]) then if (IsTransportable(unitDefID) or factDefs[unitDefID]) then AddCmdDesc(unitID) end elseif (transDefs[unitDefID]) then hasTransports[teamID] = true for _, id in pairs(GetTeamUnits(teamID)) do local def = GetUnitDefID(id) if (IsTransportable(def) or factDefs[def]) then AddCmdDesc(id) end end end end function gadget:UnitDestroyed(unitID, unitDefID, teamID, attackerID, attackerDefID, attackerTeamID) if (transDefs[unitDefID]) then local teamUnit =GetTeamUnits(teamID) local haveAnotherTransport =false for _, id in pairs(teamUnit) do local def = GetUnitDefID(id) if id~=unitID and (transDefs[def]) then haveAnotherTransport = true break end end if not haveAnotherTransport then hasTransports[teamID] = false for _, id in pairs(teamUnit) do local def = GetUnitDefID(id) if (IsTransportable(def) or factDefs[def]) then RemoveCmdDesc(id) end end end end end function gadget:UnitTaken(unitID, unitDefID, oldTeamID, teamID) gadget:UnitCreated(unitID, unitDefID, teamID) --add embark/disembark command gadget:UnitDestroyed(unitID, unitDefID, oldTeamID) --remove embark/disembark command end function gadget:UnitGiven(unitID) -- minor hack unrelated to transport ai - enable captured unit GiveOrderToUnit(unitID, CMD_ONOFF, { 1 }, { }) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:Initialize() gadgetHandler:RegisterCMDID(CMD_EMBARK); gadgetHandler:RegisterCMDID(CMD_DISEMBARK); for _,unitID in pairs(Spring.GetAllUnits()) do local unitDefID = GetUnitDefID(unitID); gadget:UnitCreated(unitID, unitDefID, Spring.GetUnitTeam(unitID)); end gadgetHandler:RegisterGlobal('taiEmbark', taiEmbark) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:AllowCommand_GetWantedCommand() return {[CMD_EMBARK] = true, [CMD_DISEMBARK] = true, [CMD_TRANSPORTTO] = true} end function gadget:AllowCommand_GetWantedUnitDefID() return true end function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) if (cmdID == CMD_EMBARK) or (cmdID == CMD_DISEMBARK) or (cmdID == CMD_TRANSPORTTO) then if cmdID == CMD_TRANSPORTTO and (cmdOptions.shift) then return true end --transportTo cannot properly support queue, block when in SHIFT local opt = {"alt"} local embark =true if (cmdID == CMD_DISEMBARK and cmdOptions.shift) then opt[#opt+1] = "ctrl" --Note: Disembark only when in SHIFT mode ("ctrl" is used to mark disembark point) embark = false --prevent enter into priority queue end if (cmdOptions.shift) then opt[#opt+1] = "shift" end if cmdID == CMD_TRANSPORTTO then --only CMD_TRANSPORTTO have coordinate parameter. GiveOrderToUnit(unitID, CMD.MOVE, {cmdParams[1],cmdParams[2],cmdParams[3]}, opt) -- This move command determine transport_AI destination. end GiveOrderToUnit(unitID, CMD_WAIT, {}, opt) --Note: transport AI use CMD_WAIT to identify transport unit. "Ctrl" will flag enter/exit transport point. SendToUnsynced("taiEmbark", unitID, teamID, embark, cmdOptions.shift) --this will put unit into transport_AI's priority (see: unit_transport_ai.lua) return false end return true end -------------------------------------------------------------------------------- -- «SYNCED» ------------------------------------------------------------------ -------------------------------------------------------------------------------- else -------------------------------------------------------------------------------- -- «UNSYNCED» ---------------------------------------------------------------- -------------------------------------------------------------------------------- function WrapToLuaUI(_,unitID,teamID, embark, shift) if (Script.LuaUI('taiEmbark')) then Script.LuaUI.taiEmbark(unitID,teamID, embark, shift) end end function gadget:Initialize() gadgetHandler:AddSyncAction('taiEmbark',WrapToLuaUI) end -------------------------------------------------------------------------------- -- «UNSYNCED» ---------------------------------------------------------------- -------------------------------------------------------------------------------- end -------------------------------------------------------------------------------- -- «COMMON» ------------------------------------------------------------------ --------------------------------------------------------------------------------
gpl-2.0
brimworks/luv
tests/test-process.lua
3
2465
return require('lib/tap')(function (test) test("test disable_stdio_inheritance", function (print, p, expect, uv) uv.disable_stdio_inheritance() end) test("process stdout", function (print, p, expect, uv) local stdout = uv.new_pipe(false) local handle, pid handle, pid = uv.spawn(uv.exepath(), { args = {"-e", "print 'Hello World'"}, stdio = {nil, stdout}, }, expect(function (code, signal) p("exit", {code=code, signal=signal}) uv.close(handle) end)) p{ handle=handle, pid=pid } uv.read_start(stdout, expect(function (err, chunk) p("stdout", {err=err,chunk=chunk}) assert(not err, err) uv.close(stdout) end)) end) if require('ffi').os == "Windows" then return end test("spawn and kill by pid", function (print, p, expect, uv) local handle, pid handle, pid = uv.spawn("sleep", { args = {1}, }, expect(function (status, signal) p("exit", handle, {status=status,signal=signal}) assert(status == 0) assert(signal == 2) uv.close(handle) end)) p{handle=handle,pid=pid} uv.kill(pid, "sigint") end) test("spawn and kill by handle", function (print, p, expect, uv) local handle, pid handle, pid = uv.spawn("sleep", { args = {1}, }, expect(function (status, signal) p("exit", handle, {status=status,signal=signal}) assert(status == 0) assert(signal == 15) uv.close(handle) end)) p{handle=handle,pid=pid} uv.process_kill(handle, "sigterm") end) test("invalid command", function (print, p, expect, uv) local handle, err handle, err = uv.spawn("ksjdfksjdflkjsflksdf", {}, function(exit, code) assert(false) end) assert(handle == nil) assert(err) end) test("process stdio", function (print, p, expect, uv) local stdin = uv.new_pipe(false) local stdout = uv.new_pipe(false) local handle, pid handle, pid = uv.spawn("cat", { stdio = {stdin, stdout}, }, expect(function (code, signal) p("exit", {code=code, signal=signal}) uv.close(handle) end)) p{ handle=handle, pid=pid } uv.read_start(stdout, expect(function (err, chunk) p("stdout", {err=err,chunk=chunk}) assert(not err, err) uv.close(stdout) end)) uv.write(stdin, "Hello World") uv.shutdown(stdin, expect(function () uv.close(stdin) end)) end) end)
apache-2.0
iamgreaser/seabase
pkg/base/obj/floor.lua
1
1419
--[[ Copyright (C) 2013 Ben "GreaseMonkey" Russell & contributors This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ]] function floor_new(cfg) local this = { x = cfg.x, y = cfg.y, layer = LAYER.FLOOR, name = "Floor", has_tiles = true, }; this.this = this if cfg.has_tiles ~= nil then this.has_tiles = cfg.has_tiles end function this.draw(img, sec_current, sec_delta, bx, by) local tx, ty = 2, 0 if this.has_tiles then tx = 1 end common.img_blit(img_tiles, bx, by, BF_AM_THRES, 16*tx, 16*ty, 16, 16, img) end function this.examine() cons_print("EX: That's a floor.") end return this end
gpl-2.0
KlonZK/Zero-K
LuaRules/Gadgets/91_unit_nanoframe_death.lua
4
5097
-- $Id: unit_terraform.lua 3299 2008-11-25 07:25:57Z google frog $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Nano Frame Death Handeling_91", desc = "Makes nanoframes explode if above X% completetion and makes dying nanoframes leave wrecks.", author = "Google Frog", date = "Mar 29, 2009", license = "GNU GPL, v2 or later", layer = -10, enabled = (Game.version:find('91.0') == 1) and (Game.version:find('91.0.1') == nil) } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (not gadgetHandler:IsSyncedCode()) then return false -- no unsynced code end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Speedups local spSetUnitHealth = Spring.SetUnitHealth local spGetUnitHealth = Spring.GetUnitHealth local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitBuildFacing = Spring.GetUnitBuildFacing local spCreateUnit = Spring.CreateUnit local spDestroyUnit = Spring.DestroyUnit local spGetUnitSelfDTime = Spring.GetUnitSelfDTime local spSetFeatureResurrect = Spring.SetFeatureResurrect local spSetFeatureHealth = Spring.SetFeatureHealth local spSetFeatureReclaim = Spring.SetFeatureReclaim local spGetGroundHeight = Spring.GetGroundHeight local spCreateFeature = Spring.CreateFeature local spValidUnitID = Spring.ValidUnitID -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local units = {} local unitsCount = 0 local exclude = { "armmex", "cormex" } local excludeDefID = {} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local unitFromFactory = {} local isAFactory = {} function gadget:UnitCreated(unitID,unitDefID,_,builderID) local ud = UnitDefs[unitDefID] if ud and ud.isFactory then isAFactory[unitID] = true end if builderID and isAFactory[builderID] then unitFromFactory[unitID] = true end end local function ScrapUnit(unitID, unitDefID, team, progress, face) if (unitDefID and UnitDefs[unitDefID] and UnitDefs[unitDefID].wreckName and FeatureDefNames[UnitDefs[unitDefID].wreckName]) then local wreck = UnitDefs[unitDefID].wreckName if (wreck and FeatureDefNames[wreck]) then local nextWreck = FeatureDefNames[wreck].deathFeature if nextWreck and FeatureDefNames[nextWreck] then wreck = FeatureDefNames[wreck].deathFeature if progress < 0.5 then nextWreck = FeatureDefNames[wreck].deathFeature if nextWreck and FeatureDefNames[nextWreck] then wreck = FeatureDefNames[wreck].deathFeature progress = progress * 2 end end end local x, _, z = spGetUnitPosition(unitID) local y = spGetGroundHeight(x, z) if (progress == 0) then progress = 0.001 end local featureID = spCreateFeature(wreck, x, y, z) -- _, team local maxHealth = FeatureDefNames[wreck].maxHealth spSetFeatureReclaim(featureID, progress) --spSetFeatureResurrect(featureID, UnitDefs[unitDefID].name, face) spSetFeatureHealth(featureID, progress*maxHealth) end end end function gadget:UnitDestroyed(unitID, unitDefID, unitTeam) local health, _,_,_,progress = spGetUnitHealth(unitID) if (progress == 1) or (health > 0 and unitFromFactory[unitID]) or GG.wasMorphedTo[unitID] then isAFactory[unitID] = nil unitFromFactory[unitID] = nil return end local face = (spGetUnitBuildFacing(unitID) or 1) -- exclude mexes to break recursion with overdrive gadget if (progress > 0.8) then if (not excludeDefID[unitDefID]) then local x,y,z = spGetUnitPosition(unitID) local id = spCreateUnit(unitDefID,x,y,z,face,unitTeam) if id then unitsCount = unitsCount+1 units[unitsCount] = id end end return end if (progress > 0.05) then ScrapUnit(unitID, unitDefID, unitTeam, progress, face) end isAFactory[unitID] = nil unitFromFactory[unitID] = nil end function gadget:GameFrame(n) if (unitsCount ~= 0) then for i=1, unitsCount do if spValidUnitID(units[i]) then spDestroyUnit(units[i],true,false) end units[i] = nil end unitsCount = 0 end end function gadget:Initialize() for i,v in ipairs(exclude) do local def = UnitDefNames[v] if def then excludeDefID[def.id] = true end end for _, unitID in ipairs(Spring.GetAllUnits()) do local unitDefID = Spring.GetUnitDefID(unitID) local team = Spring.GetUnitTeam(unitID) gadget:UnitCreated(unitID, unitDefID, team) end GG.wasMorphedTo = GG.wasMorphedTo or {} end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
fivejjs/treelstm
models/BinaryTreeLSTM.lua
10
5977
--[[ A Binary Tree-LSTM with input at the leaf nodes. --]] local BinaryTreeLSTM, parent = torch.class('treelstm.BinaryTreeLSTM', 'treelstm.TreeLSTM') function BinaryTreeLSTM:__init(config) parent.__init(self, config) self.gate_output = config.gate_output if self.gate_output == nil then self.gate_output = true end -- a function that instantiates an output module that takes the hidden state h as input self.output_module_fn = config.output_module_fn self.criterion = config.criterion -- leaf input module self.leaf_module = self:new_leaf_module() self.leaf_modules = {} -- composition module self.composer = self:new_composer() self.composers = {} -- output module self.output_module = self:new_output_module() self.output_modules = {} end function BinaryTreeLSTM:new_leaf_module() local input = nn.Identity()() local c = nn.Linear(self.in_dim, self.mem_dim)(input) local h if self.gate_output then local o = nn.Sigmoid()(nn.Linear(self.in_dim, self.mem_dim)(input)) h = nn.CMulTable(){o, nn.Tanh()(c)} else h = nn.Tanh()(c) end local leaf_module = nn.gModule({input}, {c, h}) if self.leaf_module ~= nil then share_params(leaf_module, self.leaf_module) end return leaf_module end function BinaryTreeLSTM:new_composer() local lc, lh = nn.Identity()(), nn.Identity()() local rc, rh = nn.Identity()(), nn.Identity()() local new_gate = function() return nn.CAddTable(){ nn.Linear(self.mem_dim, self.mem_dim)(lh), nn.Linear(self.mem_dim, self.mem_dim)(rh) } end local i = nn.Sigmoid()(new_gate()) -- input gate local lf = nn.Sigmoid()(new_gate()) -- left forget gate local rf = nn.Sigmoid()(new_gate()) -- right forget gate local update = nn.Tanh()(new_gate()) -- memory cell update vector local c = nn.CAddTable(){ -- memory cell nn.CMulTable(){i, update}, nn.CMulTable(){lf, lc}, nn.CMulTable(){rf, rc} } local h if self.gate_output then local o = nn.Sigmoid()(new_gate()) -- output gate h = nn.CMulTable(){o, nn.Tanh()(c)} else h = nn.Tanh()(c) end local composer = nn.gModule( {lc, lh, rc, rh}, {c, h}) if self.composer ~= nil then share_params(composer, self.composer) end return composer end function BinaryTreeLSTM:new_output_module() if self.output_module_fn == nil then return nil end local output_module = self.output_module_fn() if self.output_module ~= nil then share_params(output_module, self.output_module) end return output_module end function BinaryTreeLSTM:forward(tree, inputs) local lloss, rloss = 0, 0 if tree.num_children == 0 then self:allocate_module(tree, 'leaf_module') tree.state = tree.leaf_module:forward(inputs[tree.leaf_idx]) else self:allocate_module(tree, 'composer') -- get child hidden states local lvecs, lloss = self:forward(tree.children[1], inputs) local rvecs, rloss = self:forward(tree.children[2], inputs) local lc, lh = self:unpack_state(lvecs) local rc, rh = self:unpack_state(rvecs) -- compute state and output tree.state = tree.composer:forward{lc, lh, rc, rh} end local loss if self.output_module ~= nil then self:allocate_module(tree, 'output_module') tree.output = tree.output_module:forward(tree.state[2]) if self.train then loss = self.criterion:forward(tree.output, tree.gold_label) + lloss + rloss end end return tree.state, loss end function BinaryTreeLSTM:backward(tree, inputs, grad) local grad_inputs = torch.Tensor(inputs:size()) self:_backward(tree, inputs, grad, grad_inputs) return grad_inputs end function BinaryTreeLSTM:_backward(tree, inputs, grad, grad_inputs) local output_grad = self.mem_zeros if tree.output ~= nil and tree.gold_label ~= nil then output_grad = tree.output_module:backward( tree.state[2], self.criterion:backward(tree.output, tree.gold_label)) end self:free_module(tree, 'output_module') if tree.num_children == 0 then grad_inputs[tree.leaf_idx] = tree.leaf_module:backward( inputs[tree.leaf_idx], {grad[1], grad[2] + output_grad}) self:free_module(tree, 'leaf_module') else local lc, lh, rc, rh = self:get_child_states(tree) local composer_grad = tree.composer:backward( {lc, lh, rc, rh}, {grad[1], grad[2] + output_grad}) self:free_module(tree, 'composer') -- backward propagate to children self:_backward(tree.children[1], inputs, {composer_grad[1], composer_grad[2]}, grad_inputs) self:_backward(tree.children[2], inputs, {composer_grad[3], composer_grad[4]}, grad_inputs) end tree.state = nil tree.output = nil end function BinaryTreeLSTM:parameters() local params, grad_params = {}, {} local cp, cg = self.composer:parameters() tablex.insertvalues(params, cp) tablex.insertvalues(grad_params, cg) local lp, lg = self.leaf_module:parameters() tablex.insertvalues(params, lp) tablex.insertvalues(grad_params, lg) if self.output_module ~= nil then local op, og = self.output_module:parameters() tablex.insertvalues(params, op) tablex.insertvalues(grad_params, og) end return params, grad_params end -- -- helper functions -- function BinaryTreeLSTM:unpack_state(state) local c, h if state == nil then c, h = self.mem_zeros, self.mem_zeros else c, h = unpack(state) end return c, h end function BinaryTreeLSTM:get_child_states(tree) local lc, lh, rc, rh if tree.children[1] ~= nil then lc, lh = self:unpack_state(tree.children[1].state) end if tree.children[2] ~= nil then rc, rh = self:unpack_state(tree.children[2].state) end return lc, lh, rc, rh end function BinaryTreeLSTM:clean(tree) tree.state = nil tree.output = nil self:free_module(tree, 'leaf_module') self:free_module(tree, 'composer') self:free_module(tree, 'output_module') for i = 1, tree.num_children do self:clean(tree.children[i]) end end
gpl-2.0
parsaalemi/antispambot
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
dajhorn/openwrt-packages
net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/interfaceconfig.lua
74
7228
-- ------ extra functions ------ -- function interfaceCheck() metricValue = ut.trim(sys.exec("uci -p /var/state get network." .. arg[1] .. ".metric")) if metricValue == "" then -- no metric errorNoMetric = 1 else -- if metric exists create list of interface metrics to compare against for duplicates uci.cursor():foreach("mwan3", "interface", function (section) local metricValue = ut.trim(sys.exec("uci -p /var/state get network." .. section[".name"] .. ".metric")) metricList = metricList .. section[".name"] .. " " .. metricValue .. "\n" end ) -- compare metric against list local metricDuplicateNumbers, metricDuplicates = sys.exec("echo '" .. metricList .. "' | awk '{print $2}' | uniq -d"), "" for line in metricDuplicateNumbers:gmatch("[^\r\n]+") do metricDuplicates = sys.exec("echo '" .. metricList .. "' | grep '" .. line .. "' | awk '{print $1}'") errorDuplicateMetricList = errorDuplicateMetricList .. metricDuplicates end if sys.exec("echo '" .. errorDuplicateMetricList .. "' | grep -w " .. arg[1]) ~= "" then errorDuplicateMetric = 1 end end -- check if this interface has a higher reliability requirement than track IPs configured local trackingNumber = tonumber(ut.trim(sys.exec("echo $(uci -p /var/state get mwan3." .. arg[1] .. ".track_ip) | wc -w"))) if trackingNumber > 0 then local reliabilityNumber = tonumber(ut.trim(sys.exec("uci -p /var/state get mwan3." .. arg[1] .. ".reliability"))) if reliabilityNumber and reliabilityNumber > trackingNumber then errorReliability = 1 end end -- check if any interfaces are not properly configured in /etc/config/network or have no default route in main routing table if ut.trim(sys.exec("uci -p /var/state get network." .. arg[1])) == "interface" then local interfaceDevice = ut.trim(sys.exec("uci -p /var/state get network." .. arg[1] .. ".ifname")) if interfaceDevice == "uci: Entry not found" or interfaceDevice == "" then errorNetConfig = 1 errorRoute = 1 else local routeCheck = ut.trim(sys.exec("route -n | awk '{if ($8 == \"" .. interfaceDevice .. "\" && $1 == \"0.0.0.0\" && $3 == \"0.0.0.0\") print $1}'")) if routeCheck == "" then errorRoute = 1 end end else errorNetConfig = 1 errorRoute = 1 end end function interfaceWarnings() -- display warning messages at the top of the page local warns, lineBreak = "", "" if errorReliability == 1 then warns = "<font color=\"ff0000\"><strong>WARNING: this interface has a higher reliability requirement than there are tracking IP addresses!</strong></font>" lineBreak = "<br /><br />" end if errorRoute == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this interface has no default route in the main routing table!</strong></font>" lineBreak = "<br /><br />" end if errorNetConfig == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this interface is configured incorrectly or not at all in /etc/config/network!</strong></font>" lineBreak = "<br /><br />" end if errorNoMetric == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this interface has no metric configured in /etc/config/network!</strong></font>" elseif errorDuplicateMetric == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this and other interfaces have duplicate metrics configured in /etc/config/network!</strong></font>" end return warns end -- ------ interface configuration ------ -- dsp = require "luci.dispatcher" sys = require "luci.sys" ut = require "luci.util" arg[1] = arg[1] or "" metricValue = "" metricList = "" errorDuplicateMetricList = "" errorNoMetric = 0 errorDuplicateMetric = 0 errorRoute = 0 errorNetConfig = 0 errorReliability = 0 interfaceCheck() m5 = Map("mwan3", translate("MWAN Interface Configuration - " .. arg[1]), translate(interfaceWarnings())) m5.redirect = dsp.build_url("admin", "network", "mwan", "configuration", "interface") mwan_interface = m5:section(NamedSection, arg[1], "interface", "") mwan_interface.addremove = false mwan_interface.dynamic = false enabled = mwan_interface:option(ListValue, "enabled", translate("Enabled")) enabled.default = "1" enabled:value("1", translate("Yes")) enabled:value("0", translate("No")) track_ip = mwan_interface:option(DynamicList, "track_ip", translate("Tracking IP"), translate("This IP address will be pinged to dermine if the link is up or down. Leave blank to assume interface is always online")) track_ip.datatype = "ipaddr" reliability = mwan_interface:option(Value, "reliability", translate("Tracking reliability"), translate("Acceptable values: 1-100. This many Tracking IP addresses must respond for the link to be deemed up")) reliability.datatype = "range(1, 100)" reliability.default = "1" count = mwan_interface:option(ListValue, "count", translate("Ping count")) count.default = "1" count:value("1") count:value("2") count:value("3") count:value("4") count:value("5") timeout = mwan_interface:option(ListValue, "timeout", translate("Ping timeout")) timeout.default = "2" timeout:value("1", translate("1 second")) timeout:value("2", translate("2 seconds")) timeout:value("3", translate("3 seconds")) timeout:value("4", translate("4 seconds")) timeout:value("5", translate("5 seconds")) timeout:value("6", translate("6 seconds")) timeout:value("7", translate("7 seconds")) timeout:value("8", translate("8 seconds")) timeout:value("9", translate("9 seconds")) timeout:value("10", translate("10 seconds")) interval = mwan_interface:option(ListValue, "interval", translate("Ping interval")) interval.default = "5" interval:value("1", translate("1 second")) interval:value("3", translate("3 seconds")) interval:value("5", translate("5 seconds")) interval:value("10", translate("10 seconds")) interval:value("20", translate("20 seconds")) interval:value("30", translate("30 seconds")) interval:value("60", translate("1 minute")) interval:value("300", translate("5 minutes")) interval:value("600", translate("10 minutes")) interval:value("900", translate("15 minutes")) interval:value("1800", translate("30 minutes")) interval:value("3600", translate("1 hour")) down = mwan_interface:option(ListValue, "down", translate("Interface down"), translate("Interface will be deemed down after this many failed ping tests")) down.default = "3" down:value("1") down:value("2") down:value("3") down:value("4") down:value("5") down:value("6") down:value("7") down:value("8") down:value("9") down:value("10") up = mwan_interface:option(ListValue, "up", translate("Interface up"), translate("Downed interface will be deemed up after this many successful ping tests")) up.default = "3" up:value("1") up:value("2") up:value("3") up:value("4") up:value("5") up:value("6") up:value("7") up:value("8") up:value("9") up:value("10") metric = mwan_interface:option(DummyValue, "metric", translate("Metric"), translate("This displays the metric assigned to this interface in /etc/config/network")) metric.rawhtml = true function metric.cfgvalue(self, s) if errorNoMetric == 0 then return metricValue else return "&#8212;" end end return m5
gpl-2.0
KlonZK/Zero-K
LuaRules/Gadgets/dbg_animator.lua
7
6670
------------------------ function gadget:GetInfo() return { name = "Animator", desc = "v0.002 Moves and turns pieces.", author = "CarRepairer & knorke", date = "2010-03-05", license = "raubkopierer sind verbrecher", layer = 0, enabled = false, } end local function tobool(val) local t = type(val) if (t == 'nil') then return false elseif (t == 'boolean') then return val elseif (t == 'number') then return (val ~= 0) elseif (t == 'string') then return ((val ~= '0') and (val ~= 'false')) end return false end local devMode = tobool(Spring.GetModOptions().devmode) --if not devMode then return end local echo = Spring.Echo if (gadgetHandler:IsSyncedCode()) then Spring.SetGameRulesParam('devmode', 1) local function explode(div,str) if (div=='') then return false end local pos,arr = 0,{} -- for each divider found for st,sp in function() return string.find(str,div,pos,true) end do table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider pos = sp + 1 -- Jump past current divider end table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider return arr end local function WriteCurrent( unitID ) local env = true -- Spring.UnitScript.GetScriptEnv(unitID) if not env then return end local allpieces = Spring.GetUnitPieceMap(unitID) local s = "function POSENAME (mspeed, tspeed)\n" local allpieces2 = {} for pname,pid in pairs(allpieces) do allpieces2[#allpieces2+1] = { pname,pid } end table.sort(allpieces2, function(a,b) return a[1] < b[1]; end ) local unitDefID = Spring.GetUnitDefID(unitID) local swapYandZ = UnitDefs[unitDefID].model.type ~= 's3o' --for pname,pid in pairs(allpieces) do for _,item in pairs(allpieces2) do local pname = item[1] local pid = item[2] --local pieceInfo = Spring.GetUnitPieceInfo( unitID, pid ) --local pname = pieceInfo.name --local mx,my,mz = Spring.UnitScript.GetPieceTranslation (p) local rx,ry,rz = Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetPieceRotation, pid) local px,py,pz = Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetPieceTranslation, pid) -- [[ s=s.. "\tMove (" .. pname .. ", x_axis, " ..px ..", mspeed)\n" s=s.. "\tMove (" .. pname .. ", y_axis, " ..py ..", mspeed)\n" s=s.. "\tMove (" .. pname .. ", z_axis, " ..pz ..", mspeed)\n" if swapYandZ then s=s.. "\tTurn (" .. pname .. ", x_axis, math.rad(" .. math.deg(rx) .."), tspeed)\n" s=s.. "\tTurn (" .. pname .. ", y_axis, math.rad(" .. math.deg(rz) .."), tspeed)\n" s=s.. "\tTurn (" .. pname .. ", z_axis, math.rad(" .. math.deg(ry) .."), tspeed)\n" else s=s.. "\tTurn (" .. pname .. ", x_axis, math.rad(" .. math.deg(rx) .."), tspeed)\n" s=s.. "\tTurn (" .. pname .. ", y_axis, math.rad(" .. math.deg(ry) .."), tspeed)\n" s=s.. "\tTurn (" .. pname .. ", z_axis, math.rad(" .. math.deg(rz) .."), tspeed)\n" end --]] end s=s.. "end" echo (s) end local function Reset(unitID) local env = true -- Spring.UnitScript.GetScriptEnv(unitID) if env and Spring.UnitScript.GetPieceRotation then local allpieces = Spring.GetUnitPieceMap(unitID) for pname,pid in pairs(allpieces) do for axisnum = 1,3 do Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Move, pid, axisnum, 0 ) Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Turn, pid, axisnum, 0 ) end end end end local function CallUnitScript(unitID, funcName, ...) if Spring.UnitScript.GetScriptEnv(unitID) and Spring.UnitScript.GetScriptEnv(unitID).script[funcName] then Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetScriptEnv(unitID).script[funcName], ...) end end function gadget:RecvLuaMsg(msg, playerID) if not Spring.IsCheatingEnabled() then return end --echo (msg) pre = "animator" --if (msg:find(pre,1,true)) then Spring.Echo ("its a loveNtrolls message") end local data = explode( '|', msg ) if data[1] ~= pre then return end local cmd = data[2] local param1 = data[3] local param2 = data[4] local param3 = data[5] local param4 = data[6] if cmd == 'sel' and param1 then local unitID = param1+0 --convert to int! euID = unitID --Spring.Echo ("now editing: " .. euID) elseif cmd == 'getpieceinfo' and param1 and param2 then local unitID = param1+0 --convert to int! local pieceNum = param2+0 --convert to int! local env = true -- Spring.UnitScript.GetScriptEnv(unitID) if env and Spring.UnitScript.GetPieceRotation then local rx,ry,rz = Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetPieceRotation, pieceNum) local px,py,pz = Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetPieceTranslation, pieceNum) local pieceInfo = {rx, ry, rz, px,py,pz} SendToUnsynced("PieceInfo", table.concat(pieceInfo,'|') ) end elseif cmd == 'move' or cmd == 'turn' then local axis = param1 local unitID = param2+0 --convert to num! local pieceNum = param3+0 --convert to num! local val = param4+0 --convert to num! local axisnum = 1 if axis == 'y' then axisnum = 2 elseif axis == 'z' then axisnum = 3 end local env = true --Spring.UnitScript.GetScriptEnv(unitID) if env then if cmd == 'move' then Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Move, pieceNum, axisnum, val ) elseif cmd == 'turn' then Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Turn, pieceNum, axisnum, val ) end echo("> " .. cmd .. ' on ' .. axis .. '-axis to ' .. val) end elseif cmd == 'write' then local unitID = param1+0 --convert to num! WriteCurrent(unitID) elseif cmd == 'reset' then local unitID = param1+0 --convert to num! Reset(unitID) elseif cmd == 'hide' then local unitID = param1+0 --convert to num! local pieceNum = param2+0 --convert to num! Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Hide, pieceNum ) elseif cmd == 'show' then local unitID = param1+0 --convert to num! local pieceNum = param2+0 --convert to num! Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Show, pieceNum ) elseif cmd == 'testthread' then local unitID = param1+0 --convert to num! CallUnitScript(unitID, "TestThread" ) end --Spring.Echo ("RecvLuaMsg: " .. msg .. " from " .. playerID) end function gadget:Initialize() end else -- ab hier unsync local function PieceInfo(_, pieceInfo) Script.LuaUI.PieceInfo(pieceInfo) end function gadget:Initialize() gadgetHandler:AddSyncAction("PieceInfo", PieceInfo) end function gadget:Shutdown() gadgetHandler:RemoveSyncAction("PieceInfo") end end
gpl-2.0
complynx/nodemcu-IoT
lua_modules/yeelink/yeelink_lib.lua
73
3136
-- *************************************************************************** -- Yeelink Updata Libiary Version 0.1.2 r1 -- -- Written by Martin -- but based on a script of zhouxu_o from bbs.nodemcu.com -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** --==========================Module Part====================== local moduleName = ... local M = {} _G[moduleName] = M --=========================Local Args======================= local dns = "0.0.0.0" local device = "" local sensor = "" local apikey = "" --================================ local debug = true --<<<<<<<<<<<<< Don't forget to "false" it before using --================================ local sk=net.createConnection(net.TCP, 0) local datapoint = 0 --====DNS the yeelink ip advance(in order to save RAM)===== if wifi.sta.getip() == nil then print("Please Connect WIFI First") tmr.alarm(1,1000,1,function () if wifi.sta.getip() ~= nil then tmr.stop(1) sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) end end) end sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) --========Set the init function=========== --device->number --sensor->number -- apikey must be -> string <- -- e.g. xxx.init(00000,00000,"123j12b3jkb12k4b23bv54i2b5b3o4") --======================================== function M.init(_device, _sensor, _apikey) device = tostring(_device) sensor = tostring(_sensor) apikey = _apikey if dns == "0.0.0.0" then tmr.alarm(2,5000,1,function () if dns == "0.0.0.0" then print("Waiting for DNS...") end end) return false else return dns end end --========Check the DNS Status=========== --if DNS success, return the address(string) --if DNS fail(or processing), return nil -- -- --======================================== function M.getDNS() if dns == "0.0.0.0" then return nil else return dns end end --=====Update to Yeelink Sever(At least 10s per sencods))===== -- datapoint->number -- --e.g. xxx.update(233.333) --============================================================ function M.update(_datapoint) datapoint = tostring(_datapoint) sk:on("connection", function(conn) print("connect OK...") local a=[[{"value":]] local b=[[}]] local st=a..datapoint..b sk:send("POST /v1.0/device/"..device.."/sensor/"..sensor.."/datapoints HTTP/1.1\r\n" .."Host: www.yeelink.net\r\n" .."Content-Length: "..string.len(st).."\r\n"--the length of json is important .."Content-Type: application/x-www-form-urlencoded\r\n" .."U-ApiKey:"..apikey.."\r\n" .."Cache-Control: no-cache\r\n\r\n" ..st.."\r\n" ) end) sk:on("receive", function(sck, content) if debug then print("\r\n"..content.."\r\n") else print("Date Receive") end end) sk:connect(80,dns) end --================end========================== return M
mit
annulen/premake-dev-rgeary
tests/config/test_fileconfig.lua
1
2521
-- -- tests/config/test_fileconfig.lua -- Test the config object's file configuration accessor. -- Copyright (c) 2012 Jason Perkins and the Premake project -- T.config_fileconfig = { } local suite = T.config_fileconfig local project = premake5.project local config = premake5.config -- -- Setup and teardown -- local sln, prj, fcfg function suite.setup() sln, prj = test.createsolution() end local function prepare(filename) local cfg = project.getconfig(prj, "Debug") fcfg = config.getfileconfig(cfg, path.join(os.getcwd(), filename or "hello.c")) end -- -- A file specified at the project level should be present in all configurations. -- function suite.isPresent_onProjectLevel() files "hello.c" prepare() test.isnotnil(fcfg) end -- -- A file specified only in the current configuration should return a value. -- function suite.isPresent_onCurrentConfigOnly() configuration "Debug" files "hello.c" prepare() test.isnotnil(fcfg) end -- -- A file specified only in a different configuration should return nil. -- function suite.isNotPresent_onDifferentConfigOnly() configuration "Release" files "hello.c" prepare() test.isnil(fcfg) end -- -- A file specified at the project, and excluded in the current configuration -- should return nil. -- function suite.isNotPresent_onExcludedInCurrent() files "hello.c" configuration "Debug" excludes "hello.c" prepare() test.isnil(fcfg) end -- -- A file specified at the project, and excluded in a different configuration -- should return a value. -- function suite.isNotPresent_onExcludedInCurrent() files "hello.c" configuration "Release" excludes "hello.c" prepare() test.isnotnil(fcfg) end -- -- A build option specified on a specific set of files should appear in the -- file configuration -- function suite.settingIsPresent_onFileSpecificFilter() files "hello.c" configuration "**.c" buildoptions "-Xc" prepare() test.isequal({ "-Xc" }, fcfg.buildoptions) end -- -- A "not" filter should not provide the positive match for a -- file configuration filename mask. -- function suite.fileIsUnmatched_onNotFilter() files "hello.c" configuration "not Debug" buildoptions "-Xc" prepare() test.isnil(fcfg.buildoptions) end -- -- Check case-sensitivity of file name tests. -- function suite.fileMatches_onCaseMismatch() files "Hello.c" configuration "**/HeLLo.c" buildoptions "-Xc" prepare("Hello.c") test.isequal({ "-Xc" }, fcfg.buildoptions) end
bsd-3-clause
thuehn/Minstrel-Blues
measurement/minstrel-measurement/tests/config.lua
2
2204
config = require ('Config') require ('misc') pprint = require ('pprint') assert ( Config.load_config ( "tests/config_file.lua" ) ) assert ( ctrl == "A" ) assert ( table_size ( connections ) == 2 ) assert ( table_size ( nodes ) == 6 ) local a = Config.find_node ( "A", nodes ) local b = Config.find_node ( "B", nodes ) local c = Config.find_node ( "C", nodes ) local d = Config.find_node ( "D", nodes ) local e = Config.find_node ( "E", nodes ) local f = Config.find_node ( "F", nodes ) assert ( a.name == "A" ) assert ( a.ctrl_if == "eth0" ) assert ( a.radio == "radio0" ) assert ( b.name == "B" ) assert ( Config.cnode_to_string ( b ) == "B\tradio1\teth1" ) assert ( c.name == "C" ) local c2 = Config.create_config ( "C2", "eth1", "radio1" ) assert ( c2.name == "C2" ) assert ( c2.ctrl_if == "eth1" ) assert ( c2.radio == "radio1" ) assert ( d.name == "D" ) assert ( e.name == "E" ) assert ( f.name == "F" ) local fname local rc = os.getenv("HOME") .. "/.minstrelmrc" if ( isFile ( rc ) ) then fname = rc end assert ( Config.get_config_fname ( nil ) == fname ) assert ( Config.get_config_fname ( "config_file.lua" ) == "config_file.lua" ) Config.set_config_from_arg ( d, 'ctrl_if', "wlp1s0" ) assert ( d.ctrl_if == "wlp1s0" ) local x = Config.select_config ( nodes, "A" ) assert ( x ~= nil ) assert ( x.name == "A" ) local nodes_selected = Config.select_configs ( nodes, {"A", "D"} ) assert ( table_size ( nodes_selected ) == 2 ) assert ( nodes_selected[1].name == "A" ) assert ( nodes_selected[2].name == "D" ) local con_names = Config.list_connections ( connections ) assert ( table_size ( con_names ) == 2 ) assert ( con_names[1] == "A" ) assert ( con_names[2] == "D" ) local con1 = Config.get_connections ( connections, "A" ) assert ( con1[1] == "B" ) assert ( con1[2] == "C" ) local con2 = Config.get_connections ( connections, "D" ) assert ( con2[1] == "E" ) local aps = Config.accesspoints ( nodes, connections ) assert ( table_size ( aps ) == 2 ) assert ( aps[1].name == "A" ) assert ( aps[2].name == "D" ) local stations = ( Config.stations ( nodes, connections ) ) assert ( stations[1].name == "B" ) assert ( stations[2].name == "C" ) assert ( stations[3].name == "E" )
gpl-2.0
KlonZK/Zero-K
units/armstiletto_laser.lua
2
5945
unitDef = { unitname = [[armstiletto_laser]], name = [[Thunderbird]], description = [[Disarming Lightning Bomber]], amphibious = true, buildCostEnergy = 550, buildCostMetal = 550, buildPic = [[armstiletto_laser.png]], buildTime = 550, canAttack = true, canDropFlare = false, canFly = true, canMove = true, canSubmerge = false, category = [[FIXEDWING]], collide = false, collisionVolumeOffsets = [[0 0 4]], collisionVolumeScales = [[45 20 50]], collisionVolumeTest = 1, collisionVolumeType = [[box]], corpse = [[DEAD]], cruiseAlt = 180, customParams = { description_bp = [[Bombardeiro de desarmar]], description_de = [[Entwaffnungbomber]], description_fr = [[Bombardier desarmant]], description_pl = [[Bombowiec rozbrajajacy]], helptext = [[Fast bomber armed with a lightning generator that disarms units in a wide area under it.]], helptext_bp = [[Bombardeiro rapido, que dispara raios de desarmar.]], helptext_de = [[Schneller Entwaffnungbomber, der mit einem Stossspannungsgenerator zum Entwaffnen großflächiger Gebiete bewaffnet ist.]], helptext_fr = [[Rapide, armé de canons desarmant pouvant désarmer les unités dans une large bande.]], helptext_pl = [[Szybki bombowiec, ktory jest w stanie rozbroic jednostki w szerokim obszarze.]], modelradius = [[10]], }, explodeAs = [[GUNSHIPEX]], floater = true, footprintX = 3, footprintZ = 3, iconType = [[bomberriot]], idleAutoHeal = 5, idleTime = 1800, maxAcc = 0.5, maxDamage = 1000, maxFuel = 1000000, maxVelocity = 9, minCloakDistance = 75, noChaseCategory = [[TERRAFORM FIXEDWING LAND SHIP SWIM GUNSHIP SUB HOVER]], objectName = [[stiletto.s3o]], script = [[armstiletto_laser.lua]], seismicSignature = 0, selfDestructAs = [[GUNSHIPEX]], sightDistance = 660, stealth = false, turnRadius = 130, weapons = { { def = [[BOGUS_BOMB]], badTargetCategory = [[SWIM LAND SHIP HOVER]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]], }, { def = [[ARMBOMBLIGHTNING]], mainDir = [[0 -1 0]], maxAngleDif = 0, onlyTargetCategory = [[NONE]], }, }, weaponDefs = { ARMBOMBLIGHTNING = { name = [[Lightning]], areaOfEffect = 192, avoidFeature = false, avoidFriendly = false, beamTime = 0.01, burst = 80, burstRate = 0.3, cameraShake = 150, canattackground = false, collideFriendly = false, coreThickness = 0.6, craterBoost = 0, craterMult = 0, customParams = { disarmDamageMult = 1, disarmDamageOnly = 1, disarmTimer = 16, -- seconds }, damage = { default = 675, }, edgeEffectiveness = 0.4, explosionGenerator = [[custom:WHITE_LIGHTNING_BOMB]], fireStarter = 90, impulseBoost = 0, impulseFactor = 0, intensity = 12, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 5, minIntensity = 1, range = 730, reloadtime = 10, rgbColor = [[1 1 1]], sprayAngle = 6000, texture1 = [[lightning]], texture2 = [[flare]], texture3 = [[flare]], texture4 = [[smallflare]], thickness = 10, tileLength = 50, tolerance = 32767, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 2250, }, BOGUS_BOMB = { name = [[Fake Bomb]], avoidFeature = false, avoidFriendly = false, burst = 2, burstrate = 1, collideFriendly = false, damage = { default = 0, }, explosionGenerator = [[custom:NONE]], interceptedByShieldType = 1, intensity = 0, manualBombSettings = true, myGravity = 0.8, noSelfDamage = true, range = 500, reloadtime = 10, sprayangle = 64000, weaponType = [[AircraftBomb]], }, }, featureDefs = { DEAD = { description = [[Wreckage - Thunderbird]], blocking = true, damage = 1000, energy = 0, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, metal = 220, object = [[Stiletto_dead.s3o]], reclaimable = true, reclaimTime = 220, }, HEAP = { description = [[Debris - Thunderbird]], blocking = false, damage = 1000, energy = 0, footprintX = 3, footprintZ = 3, metal = 110, object = [[debris2x2c.s3o]], reclaimable = true, reclaimTime = 110, }, }, } return lowerkeys({ armstiletto_laser = unitDef })
gpl-2.0
zcsteele/turbo
turbo/socket_ffi.lua
7
15050
--- Turbo.lua Socket Module -- -- Copyright 2013 John Abrahamsen -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local log = require "turbo.log" local util = require "turbo.util" local ffi = require "ffi" local platform = require "turbo.platform" require "turbo.cdef" local octal = function (s) return tonumber(s, 8) end local hex = function (s) return tonumber(s, 16) end local F = {} F.F_DUPFD = 0 F.F_GETFD = 1 F.F_SETFD = 2 F.F_GETFL = 3 F.F_SETFL = 4 local O = {} if ffi.arch == "mipsel" then O.O_ACCMODE = octal("0003") O.O_RDONLY = octal("00") O.O_WRONLY = octal("01") O.O_RDWR = octal("02") O.O_CREAT = octal("0400") O.O_EXCL = octal("2000") O.O_NOCTTY = octal("4000") O.O_TRUNC = octal("1000") O.O_APPEND = octal("0010") O.O_NONBLOCK = octal("0200") O.O_NDELAY = O.O_NONBLOCK O.O_SYNC = octal("0020") O.O_FSYNC = O.O_SYNC O.O_ASYNC = octal("10000") else O.O_ACCMODE = octal("0003") O.O_RDONLY = octal("00") O.O_WRONLY = octal("01") O.O_RDWR = octal("02") O.O_CREAT = octal("0100") O.O_EXCL = octal("0200") O.O_NOCTTY = octal("0400") O.O_TRUNC = octal("01000") O.O_APPEND = octal("02000") O.O_NONBLOCK = octal("04000") O.O_NDELAY = O.O_NONBLOCK O.O_SYNC = octal("04010000") O.O_FSYNC = O.O_SYNC O.O_ASYNC = octal("020000") end local SOCK = {} if ffi.arch == "mipsel" then SOCK.SOCK_STREAM = 2 SOCK.SOCK_DGRAM = 1 SOCK.SOCK_RAW = 3 SOCK.SOCK_RDM = 4 SOCK.SOCK_SEQPACKET = 5 SOCK.SOCK_DCCP = 6 SOCK.SOCK_PACKET = 10 SOCK.SOCK_CLOEXEC = octal("02000000") SOCK.SOCK_NONBLOCK = octal("0200") else SOCK.SOCK_STREAM = 1 SOCK.SOCK_DGRAM = 2 SOCK.SOCK_RAW = 3 SOCK.SOCK_RDM = 4 SOCK.SOCK_SEQPACKET = 5 SOCK.SOCK_DCCP = 6 SOCK.SOCK_PACKET = 10 SOCK.SOCK_CLOEXEC = octal("02000000") SOCK.SOCK_NONBLOCK = octal("040009") end --[[ Protocol families. ]] local PF = {} PF.PF_UNSPEC = 0 --[[ Unspecified. ]] PF.PF_LOCAL = 1 --[[ Local to host (pipes and file-domain). ]] PF.PF_UNIX = PF.PF_LOCAL --[[ POSIX name for PF.PF_LOCAL. ]] PF.PF_FILE = PF.PF_LOCAL --[[ Another non-standard name for PF.PF_LOCAL. ]] PF.PF_INET = 2 --[[ IP protocol family. ]] PF.PF_AX25 = 3 --[[ Amateur Radio AX.25. ]] PF.PF_IPX = 4 --[[ Novell Internet Protocol. ]] PF.PF_APPLETALK = 5 --[[ Appletalk DDP. ]] PF.PF_NETROM = 6 --[[ Amateur radio NetROM. ]] PF.PF_BRIDGE = 7 --[[ Multiprotocol bridge. ]] PF.PF_ATMPVC = 8 --[[ ATM PVCs. ]] PF.PF_X25 = 9 --[[ Reserved for X.25 project. ]] PF.PF_INET6 = 10 --[[ IP version 6. ]] PF.PF_ROSE = 11 --[[ Amateur Radio X.25 PLP. ]] PF.PF_DECnet = 12 --[[ Reserved for DECnet project. ]] PF.PF_NETBEUI = 13 --[[ Reserved for 802.2LLC project. ]] PF.PF_SECURITY = 14 --[[ Security callback pseudo AF. ]] PF.PF_KEY = 15 --[[ PF.PF_KEY key management API. ]] PF.PF_NETLINK = 16 PF.PF_ROUTE = PF.PF_NETLINK --[[ Alias to emulate 4.4BSD. ]] PF.PF_PACKET = 17 --[[ Packet family. ]] PF.PF_ASH = 18 --[[ Ash. ]] PF.PF_ECONET = 19 --[[ Acorn Econet. ]] PF.PF_ATMSVC = 20 --[[ ATM SVCs. ]] PF.PF_RDS = 21 --[[ RDS sockets. ]] PF.PF_SNA = 22 --[[ Linux SNA Project ]] PF.PF_IRDA = 23 --[[ IRDA sockets. ]] PF.PF_PPPOX = 24 --[[ PPPoX sockets. ]] PF.PF_WANPIPE = 25 --[[ Wanpipe API sockets. ]] PF.PF_LLC = 26 --[[ Linux LLC. ]] PF.PF_CAN = 29 --[[ Controller Area Network. ]] PF.PF_TIPC = 30 --[[ TIPC sockets. ]] PF.PF_BLUETOOTH = 31 --[[ Bluetooth sockets. ]] PF.PF_IUCV = 32 --[[ IUCV sockets. ]] PF.PF_RXRPC = 33 --[[ RxRPC sockets. ]] PF.PF_ISDN = 34 --[[ mISDN sockets. ]] PF.PF_PHONET = 35 --[[ Phonet sockets. ]] PF.PF_IEEE802154 = 36 --[[ IEEE 802.15.4 sockets. ]] PF.PF_CAIF = 37 --[[ CAIF sockets. ]] PF.PF_ALG = 38 --[[ Algorithm sockets. ]] PF.PF_NFC = 39 --[[ NFC sockets. ]] PF.PF_MAX = 40 --[[ For now.. ]] --[[ Address families. ]] local AF = {} AF.AF_UNSPEC = PF.PF_UNSPEC AF.AF_LOCAL = PF.PF_LOCAL AF.AF_UNIX = PF.PF_UNIX AF.AF_FILE = PF.PF_FILE AF.AF_INET = PF.PF_INET AF.AF_AX25 = PF.PF_AX25 AF.AF_IPX = PF.PF_IPX AF.AF_APPLETALK = PF.PF_APPLETALK AF.AF_NETROM = PF.PF_NETROM AF.AF_BRIDGE = PF.PF_BRIDGE AF.AF_ATMPVC = PF.PF_ATMPVC AF.AF_X25 = PF.PF_X25 AF.AF_INET6 = PF.PF_INET6 AF.AF_ROSE = PF.PF_ROSE AF.AF_DECnet = PF.PF_DECnet AF.AF_NETBEUI = PF.PF_NETBEUI AF.AF_SECURITY = PF.PF_SECURITY AF.AF_KEY = PF.PF_KEY AF.AF_NETLINK = PF.PF_NETLINK AF.AF_ROUTE = PF.PF_ROUTE AF.AF_PACKET = PF.PF_PACKET AF.AF_ASH = PF.PF_ASH AF.AF_ECONET = PF.PF_ECONET AF.AF_ATMSVC = PF.PF_ATMSVC AF.AF_RDS = PF.PF_RDS AF.AF_SNA = PF.PF_SNA AF.AF_IRDA = PF.PF_IRDA AF.AF_PPPOX = PF.PF_PPPOX AF.AF_WANPIPE = PF.PF_WANPIPE AF.AF_LLC = PF.PF_LLC AF.AF_CAN = PF.PF_CAN AF.AF_TIPC = PF.PF_TIPC AF.AF_BLUETOOTH = PF.PF_BLUETOOTH AF.AF_IUCV = PF.PF_IUCV AF.AF_RXRPC = PF.PF_RXRPC AF.AF_ISDN = PF.PF_ISDN AF.AF_PHONET = PF.PF_PHONET AF.AF_IEEE802154 = PF.PF_IEEE802154 AF.AF_CAIF = PF.PF_CAIF AF.AF_ALG = PF.PF_ALG AF.AF_NFC = PF.PF_NFC AF.AF_MAX = PF.PF_MAX local SOL = {} if ffi.arch == "mipsel" then SOL.SOL_SOCKET = octal("177777") -- 0xFFFF else SOL.SOL_SOCKET = 1 end local SO = {} if ffi.arch == "mipsel" then SO.SO_DEBUG = 1 SO.SO_REUSEADDR = 4 SO.SO_TYPE = hex("1008") SO.SO_ERROR = hex("1007") SO.SO_DONTROUTE = hex("0010") SO.SO_BROADCAST = hex("0020") SO.SO_SNDBUF = hex("1001") SO.SO_RCVBUF = hex("1002") SO.SO_SNDBUFFORCE = 31 SO.SO_RCVBUFFORCE = 33 SO.SO_KEEPALIVE = 8 SO.SO_OOBINLINE = hex("0100") SO.SO_NO_CHECK = 11 SO.SO_PRIORITY = 12 SO.SO_LINGER = hex("0080") SO.SO_BSDCOMPAT = 14 SO.SO_PASSCRED = 17 SO.SO_PEERCRED = 18 SO.SO_RCVLOWAT = hex("1004") SO.SO_SNDLOWAT = hex("1003") SO.SO_RCVTIMEO = hex("1006") SO.SO_SNDTIMEO = hex("1005") SO.SO_SECURITY_AUTHENTICATION = 22 SO.SO_SECURITY_ENCRYPTION_TRANSPORT = 23 SO.SO_SECURITY_ENCRYPTION_NETWORK = 24 SO.SO_BINDTODEVICE = 25 SO.SO_ATTACH_FILTER = 26 SO.SO_DETACH_FILTER = 27 SO.SO_PEERNAME = 28 SO.SO_TIMESTAMP = 29 SO.SCM_TIMESTAMP = SO.SO_TIMESTAMP SO.SO_ACCEPTCONN = hex("1009") SO.SO_PEERSEC = 30 SO.SO_PASSSEC = 34 SO.SO_TIMESTAMPNS = 35 SCM_TIMESTAMPNS = SO.SO_TIMESTAMPNS SO.SO_MARK = 36 SO.SO_TIMESTAMPING = 37 SO.SCM_TIMESTAMPING= SO.SO_TIMESTAMPING SO.SO_PROTOCOL = hex("1028") SO.SO_DOMAIN = hex("1029") SO.SO_RXQ_OVFL = 40 --SO.SO_WIFI_STATUS = 41 --SO.SCM_WIFI_STATUS = SO.SO_WIFI_STATUS --SO.SO_PEEK_OFF = 42 --SO.SO_NOFCS = 43 else SO.SO_DEBUG = 1 SO.SO_REUSEADDR = 2 SO.SO_TYPE = 3 SO.SO_ERROR = 4 SO.SO_DONTROUTE = 5 SO.SO_BROADCAST = 6 SO.SO_SNDBUF = 7 SO.SO_RCVBUF = 8 SO.SO_SNDBUFFORCE = 32 SO.SO_RCVBUFFORCE = 33 SO.SO_KEEPALIVE = 9 SO.SO_OOBINLINE = 10 SO.SO_NO_CHECK = 11 SO.SO_PRIORITY = 12 SO.SO_LINGER = 13 SO.SO_BSDCOMPAT = 14 SO.SO_PASSCRED = 16 SO.SO_PEERCRED = 17 SO.SO_RCVLOWAT = 18 SO.SO_SNDLOWAT = 19 SO.SO_RCVTIMEO = 20 SO.SO_SNDTIMEO = 21 SO.SO_SECURITY_AUTHENTICATION = 22 SO.SO_SECURITY_ENCRYPTION_TRANSPORT = 23 SO.SO_SECURITY_ENCRYPTION_NETWORK = 24 SO.SO_BINDTODEVICE = 25 SO.SO_ATTACH_FILTER = 26 SO.SO_DETACH_FILTER = 27 SO.SO_PEERNAME = 28 SO.SO_TIMESTAMP = 29 SO.SCM_TIMESTAMP = SO.SO_TIMESTAMP SO.SO_ACCEPTCONN = 30 SO.SO_PEERSEC = 31 SO.SO_PASSSEC = 34 SO.SO_TIMESTAMPNS = 35 SCM_TIMESTAMPNS = SO.SO_TIMESTAMPNS SO.SO_MARK = 36 SO.SO_TIMESTAMPING = 37 SO.SCM_TIMESTAMPING= SO.SO_TIMESTAMPING SO.SO_PROTOCOL = 38 SO.SO_DOMAIN = 39 SO.SO_RXQ_OVFL = 40 SO.SO_WIFI_STATUS = 41 SO.SCM_WIFI_STATUS = SO.SO_WIFI_STATUS SO.SO_PEEK_OFF = 42 SO.SO_NOFCS = 43 end local E if ffi.arch == "mipsel" then E = { EAGAIN = 11, EWOULDBLOCK = 11, EINPROGRESS = 150, ECONNRESET = 131, EPIPE = 32 } else E = { EAGAIN = 11, EWOULDBLOCK = 11, EINPROGRESS = 115, ECONNRESET = 104, EPIPE = 32 } end if platform.__LINUX__ and not _G.__TURBO_USE_LUASOCKET__ then -- Linux FFI functions. local function strerror(errno) local cstr = ffi.C.strerror(errno); return ffi.string(cstr); end local function resolv_hostname(str) local in_addr_arr = {} local hostent = ffi.C.gethostbyname(str) if hostent == nil then return -1 end local inaddr = ffi.cast("struct in_addr **", hostent.h_addr_list) local i = 0 while inaddr[i] ~= nil do in_addr_arr[#in_addr_arr + 1] = inaddr[i][0] i = i + 1 end return { in_addr = in_addr_arr, addrtype = tonumber(hostent.h_addrtype), name = ffi.string(hostent.h_name) } end local function set_nonblock_flag(fd) local flags = ffi.C.fcntl(fd, F.F_GETFL, 0); if flags == -1 then return -1, "fcntl GETFL failed." end if (bit.band(flags, O.O_NONBLOCK) ~= 0) then return 0 end flags = bit.bor(flags, O.O_NONBLOCK) rc = ffi.C.fcntl(fd, F.F_SETFL, flags) if rc == -1 then return -1, "fcntl set O_NONBLOCK failed." end return 0 end local setopt = ffi.new("int32_t[1]") local function set_reuseaddr_opt(fd) setopt[0] = 1 local rc = ffi.C.setsockopt(fd, SOL.SOL_SOCKET, SO.SO_REUSEADDR, setopt, ffi.sizeof("int32_t")) if rc ~= 0 then errno = ffi.errno() return -1, string.format("setsockopt SO_REUSEADDR failed. %s", strerror(errno)) end return 0 end --- Create new non blocking socket for use in IOStream. -- If family or stream type is not set AF_INET and SOCK_STREAM is used. local function new_nonblock_socket(family, stype, protocol) local fd = ffi.C.socket(family or AF.AF_INET, stype or SOCK.SOCK_STREAM, protocol or 0) if fd == -1 then errno = ffi.errno() return -1, string.format("Could not create socket. %s", strerror(errno)) end local rc, msg = set_nonblock_flag(fd) if (rc ~= 0) then return rc, msg end return fd end local value = ffi.new("int32_t[1]") local socklen = ffi.new("socklen_t[1]", ffi.sizeof("int32_t")) local function get_socket_error(fd) local rc = ffi.C.getsockopt(fd, SOL.SOL_SOCKET, SO.SO_ERROR, ffi.cast("void *", value), socklen) if rc ~= 0 then return -1 else return 0, tonumber(value[0]) end end local export = util.tablemerge(SOCK, util.tablemerge(F, util.tablemerge(O, util.tablemerge(AF, util.tablemerge(PF, util.tablemerge(SOL, util.tablemerge(SO, E))))))) return util.tablemerge({ strerror = strerror, resolv_hostname = resolv_hostname, getaddrinfo = ffi.C.getaddrinfo, set_nonblock_flag = set_nonblock_flag, set_reuseaddr_opt = set_reuseaddr_opt, new_nonblock_socket = new_nonblock_socket, get_socket_error = get_socket_error, INADDR_ANY = 0x00000000, INADDR_BROADCAST = 0xffffffff, INADDR_NONE = 0xffffffff, }, export) else -- LuaSocket version. local luasocket = require "socket" --- Create new non blocking socket for use in IOStream. -- If family or stream type is not set AF_INET and SOCK_STREAM is used. local function new_nonblock_socket(family, stype, protocol) family = family or AF.AF_INET stype = stype or SOCK.SOCK_STREAM assert(family == AF.AF_INET or AF.AF_INET6, "LuaSocket only support AF_INET or AF_INET6") assert(stype == SOCK.SOCK_DGRAM or SOCK.SOCK_STREAM, "LuaSocket only support SOCK_DGRAM and SOCK_STREAM.") local sock if stype == SOCK.SOCK_DGRAM then sock = socket.udp() elseif stype == SOCK.SOCK_STREAM then sock = socket.tcp() end sock:settimeout(0) sock:setoption("keepalive", true) return sock end local export = util.tablemerge(SOCK, util.tablemerge(F, util.tablemerge(O, util.tablemerge(AF, util.tablemerge(PF, util.tablemerge(SOL, util.tablemerge(SO, E))))))) return util.tablemerge({ new_nonblock_socket = new_nonblock_socket, INADDR_ANY = 0x00000000, INADDR_BROADCAST = 0xffffffff, INADDR_NONE = 0xffffffff, }, export) end
apache-2.0
ids1024/naev
dat/factions/spawn/proteron.lua
1
3427
include("dat/factions/spawn/common.lua") -- @brief Spawns a small patrol fleet. function spawn_patrol () local pilots = {} local r = rnd.rnd() if r < 0.5 then scom.addPilot( pilots, "Proteron Derivative", 20 ); elseif r < 0.8 then scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); else scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); end return pilots end -- @brief Spawns a medium sized squadron. function spawn_squad () local pilots = {} local r = rnd.rnd() if r < 0.5 then scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); elseif r < 0.8 then scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Kahan", 65 ); else scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Kahan", 65 ); scom.addPilot( pilots, "Proteron Kahan", 65 ); end return pilots end -- @brief Spawns a capship with escorts. function spawn_capship () pilots.__fleet = true local pilots = {} local r = rnd.rnd() -- Generate the capship scom.addPilot( pilots, "Proteron Archimedes", 140 ) -- Generate the escorts r = rnd.rnd() if r < 0.5 then scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); elseif r < 0.8 then scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Kahan", 65 ); else scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Derivative", 20 ); scom.addPilot( pilots, "Proteron Kahan", 65 ); scom.addPilot( pilots, "Proteron Kahan", 65 ); end return pilots end -- @brief Creation hook. function create ( max ) local weights = {} -- Create weights for spawn table weights[ spawn_patrol ] = 100 weights[ spawn_squad ] = math.max(1, -80 + 0.80 * max) weights[ spawn_capship ] = math.max(1, -500 + 1.70 * max) -- Create spawn table base on weights spawn_table = scom.createSpawnTable( weights ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( 0, scom.presence(spawn_data), max ) end -- @brief Spawning hook function spawn ( presence, max ) local pilots -- Over limit if presence > max then return 5 end -- Actually spawn the pilots pilots = scom.spawn( spawn_data ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( presence, scom.presence(spawn_data), max ), pilots end
gpl-3.0
sdgdsffdsfff/Luawa
request.lua
2
3356
-- Luawa -- File: request.lua -- Desc: holds/prepares request data (gets & posts) local setmetatable = setmetatable local ngx = ngx local luawa = require('luawa.core') local request = {} -- Init function request:_init() self.session = luawa.session self.utils = luawa.utils end -- Start function request:_start() --read post data/args ngx.req.read_body() --prepare new cookies table ngx.ctx.new_cookies = {} --get/parse cookies ngx.ctx.cookies = {} local cookie_header = ngx.req.get_headers()['cookie'] if cookie_header then for k, v in cookie_header:gmatch('([^;]+)') do local a, b, key, value = k:find('([^=]+)=([^=]+)') if key and value then ngx.ctx.cookies[self.utils.trim(key)] = value end end end end -- Request end, send cookie headers, forget them function request:_end() self:setHeader('Set-Cookie', ngx.ctx.new_cookies) ngx.header['Set-Cookie'] = ngx.ctx.new_cookies end -- Set a response header function request:setHeader(key, value) ngx.header[key] = self.new_cookies ngx.req.set_header(key, value) end -- Set a response cookie function request:setCookie(key, value, expire, path, domain, secure, httponly) if not path then path = '/' end if not expire then expire = 3600 end if not domain then domain = luawa.request.hostname end --basic cookie string local string = key .. '=' .. value .. '; Path=' .. path .. '; Expires=' .. ngx.cookie_time(os.time() + expire) --extras if domain then string = string .. '; Domain=' .. domain end if secure then string = string .. '; Secure' end if httponly then string = string .. '; HttpOnly' end --insert into cookies, to be dumped at end table.insert(ngx.ctx.new_cookies, string) --and set internal cookie for any further requests ngx.ctx.cookies[key] = value end -- Delete a cookie (set it to expire 60m ago) function request:deleteCookie(key) self:setCookie(key, '', -3600, '/') end -- Redirect function request:redirect(url, message_type, message_text) if message_type and message_text then self.session:addMessage(message_type, message_text) end --redirect return luawa:redirect(url) end --immutable request data local meta_functions = { --tables get = function() return ngx.req.get_uri_args() end, post = function() return ngx.req.get_post_args(luawa.limit_post) end, cookie = function() return ngx.ctx.cookies end, header = function() return ngx.req.get_headers() end, --single values method = function() return ngx.req.get_method() end, remote_addr = function() return ngx.var.remote_addr end, hostname = function() local header = ngx.req.get_headers().host local a, b, host, port = header:find('^([^:]+):?([0-9]*)$') return host end, hostport = function() local header = ngx.req.get_headers().host local a, b, host, port = header:find('^([^:]+):?([0-9]*)$') return port end } --bind metatable => metafuncs local mt = { __index = function(table, key) if meta_functions[key] then return meta_functions[key]() end end } setmetatable(request, mt) return request
mit
KlonZK/Zero-K
scripts/shipraider.lua
4
3353
include "constants.lua" local base = piece 'base' local hull = piece 'hull' local gunf = piece 'gunf' local barrelfl = piece 'barrelfl' local flarefl = piece 'flarefl' local barrelfr = piece 'barrelfr' local flarefr = piece 'flarefr' local gunb = piece 'gunb' local barrelbl = piece 'barrelbl' local flarebl = piece 'flarebl' local barrelbr = piece 'barrelbr' local flarebr = piece 'flarebr' local wake1 = piece 'wake1' local wake2 = piece 'wake2' local smokePiece = {gunf, hull, gunb} local turretData = { { gun = gunb, barrelRight = barrelbr, barrelLeft = barrelbl, flares = {flarebr, flarebl}, SIG_AIM = 2, SIG_RESTORE = 4, shot = 1, gunRestore = math.rad(180), }, { gun = gunf, barrelRight = barrelfr, barrelLeft = barrelfl, flares = {flarefr, flarefl}, SIG_AIM = 16, SIG_RESTORE = 32, shot = 1, gunRestore = 0, } } local gun_1, gun_2 -- Signal definitions local SIG_AIM = 2 local SIG_AIM_2 = 4 local SIG_MOVE = 8 local SIG_RESTORE = 16 local RESTORE_DELAY = 3000 function script.Create() StartThread(SmokeUnit, smokePiece) Turn(gunb, y_axis, math.rad(-180)) end local function MoveThread() Signal(SIG_MOVE) SetSignalMask(SIG_MOVE) while true do EmitSfx(wake1, 2) EmitSfx(wake2, 2) Sleep(300) end end function script.StartMoving() StartThread(MoveThread) end function script.StopMoving() Signal(SIG_MOVE) end local function RestoreAfterDelay(num) local turret = turretData[num] Signal(turret.SIG_RESTORE) SetSignalMask(turret.SIG_RESTORE) Sleep(RESTORE_DELAY) Turn(turret.gun, y_axis, turret.gunRestore, math.rad(90)) Turn(turret.barrelRight, x_axis, 0, math.rad(50)) Turn(turret.barrelLeft, x_axis, 0, math.rad(50)) end function script.AimWeapon(num, heading, pitch) local turret = turretData[num] Signal(turret.SIG_AIM) SetSignalMask(turret.SIG_AIM) Turn(turret.gun, y_axis, heading, math.rad(800)) -- Was 375 Turn(turret.barrelRight, x_axis, -pitch, math.rad(150)) Turn(turret.barrelLeft, x_axis, -pitch, math.rad(150)) WaitForTurn(turret.gun, y_axis) WaitForTurn(turret.barrelRight, x_axis) StartThread(RestoreAfterDelay, num) return true end function script.Shot(num) local turret = turretData[num] EmitSfx(turret.flares[turret.shot], 1024) EmitSfx(turret.gun, 1025) turret.shot = 3 - turret.shot end function script.AimFromWeapon(num) return turretData[num].gun end function script.QueryWeapon(num) local turret = turretData[num] return turret.flares[turret.shot] end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if (severity <= 0.25) then Explode(hull, sfxNone) Explode(gunf, sfxNone) Explode(base, sfxNone) Explode(gunb, sfxNone) Explode(barrelfr, sfxNone) return 1 end if severity <= 50 then Explode(hull, sfxNone) Explode(gunf, sfxFall) Explode(base, sfxNone) Explode(gunb, sfxFall) Explode(barrelbr, sfxFall) return 1 end if severity <= 99 then Explode(hull, sfxShatter) Explode(gunf, sfxFall) Explode(base, sfxNone) Explode(gunb, sfxFall) Explode(barrelbr, sfxFall) Explode(barrelfr, sfxFall) Explode(barrelfl, sfxFall) return 2 end Explode(hull, sfxShatter) Explode(gunf, sfxFall) Explode(base, sfxNone) Explode(gunb, sfxFall) Explode(barrelbr, sfxFall) Explode(barrelfr, sfxFall) Explode(barrelfl, sfxFall) return 2 end
gpl-2.0
mbattersby/LiteMount
UI/MountsFilter.lua
1
9473
--[[---------------------------------------------------------------------------- LiteMount/UI/MountsFilter.lua Options frame for the mount list. Copyright 2011-2021 Mike Battersby ----------------------------------------------------------------------------]]-- local _, LM = ... local L = LM.Localize local MENU_SPLIT_SIZE = 20 --[[------------------------------------------------------------------------]]-- LiteMountFilterMixin = {} function LiteMountFilterMixin:OnLoad() LM.UIFilter.RegisterCallback(self, "OnFilterChanged", "Update") end function LiteMountFilterMixin:Update() if LM.UIFilter.IsFiltered() then self.FilterButton.ClearButton:Show() else self.FilterButton.ClearButton:Hide() end end function LiteMountFilterMixin:Attach(parent, fromPoint, frame, toPoint, xOff, yOff) self:SetParent(parent) self:ClearAllPoints() self:SetPoint(fromPoint, frame, toPoint, xOff, yOff) self.Search:SetFocus() end --[[------------------------------------------------------------------------]]-- LiteMountSearchBoxMixin = {} function LiteMountSearchBoxMixin:OnTextChanged() SearchBoxTemplate_OnTextChanged(self) LM.UIFilter.SetSearchText(self:GetText()) end --[[------------------------------------------------------------------------]]-- LiteMountFilterClearMixin = {} function LiteMountFilterClearMixin:OnClick() LM.UIFilter.Clear() end --[[------------------------------------------------------------------------]]-- LiteMountFilterButtonMixin = {} function LiteMountFilterButtonMixin:OnClick() ToggleDropDownMenu(1, nil, self.FilterDropDown, self, 74, 15) end local DROPDOWNS = { ['COLLECTED'] = { value = 'COLLECTED', text = COLLECTED, checked = function () return LM.UIFilter.IsOtherChecked("COLLECTED") end, set = function (v) LM.UIFilter.SetOtherFilter("COLLECTED", v) end }, ['NOT_COLLECTED'] = { value = 'NOT_COLLECTED', text = NOT_COLLECTED, checked = function () return LM.UIFilter.IsOtherChecked("NOT_COLLECTED") end, set = function (v) LM.UIFilter.SetOtherFilter("NOT_COLLECTED", v) end }, ['UNUSABLE'] = { value = 'UNUSABLE', text = MOUNT_JOURNAL_FILTER_UNUSABLE, checked = function () return LM.UIFilter.IsOtherChecked("UNUSABLE") end, set = function (v) LM.UIFilter.SetOtherFilter("UNUSABLE", v) end }, ['HIDDEN'] = { value = 'HIDDEN', text = L.LM_HIDDEN, checked = function () return LM.UIFilter.IsOtherChecked("HIDDEN") end, set = function (v) LM.UIFilter.SetOtherFilter("HIDDEN", v) end }, ['PRIORITY'] = { value = 'PRIORITY', text = L.LM_PRIORITY, checked = function (k) return LM.UIFilter.IsPriorityChecked(k) end, set = function (k, v) LM.UIFilter.SetPriorityFilter(k, v) end, setall = function (v) LM.UIFilter.SetAllPriorityFilters(v) end, menulist = function () return LM.UIFilter.GetPriorities() end, gettext = function (k) return LM.UIFilter.GetPriorityText(k) end, }, ['TYPE'] = { value = 'TYPE', text = TYPE, checked = function (k) return LM.UIFilter.IsTypeChecked(k) end, set = function (k, v) LM.UIFilter.SetTypeFilter(k, v) end, setall = function (v) LM.UIFilter.SetAllTypeFilters(v) end, menulist = function () return LM.UIFilter.GetTypes() end, gettext = function (k) return LM.UIFilter.GetTypeText(k) end, }, ['GROUP'] = { value = 'GROUP', text = L.LM_GROUP, checked = function (k) return LM.UIFilter.IsGroupChecked(k) end, set = function (k, v) LM.UIFilter.SetGroupFilter(k, v) end, setall = function (v) LM.UIFilter.SetAllGroupFilters(v) end, menulist = function () return LM.UIFilter.GetGroups() end, gettext = function (k) return LM.UIFilter.GetGroupText(k) end, }, ['FLAG'] = { value = 'FLAG', text = L.LM_FLAG, checked = function (k) return LM.UIFilter.IsFlagChecked(k) end, set = function (k, v) LM.UIFilter.SetFlagFilter(k, v) end, setall = function (v) LM.UIFilter.SetAllFlagFilters(v) end, menulist = function () return LM.UIFilter.GetFlags() end, gettext = function (k) return LM.UIFilter.GetFlagText(k) end, }, ['FAMILY'] = { value = 'FAMILY', text = L.LM_FAMILY, checked = function (k) return LM.UIFilter.IsFamilyChecked(k) end, set = function (k, v) LM.UIFilter.SetFamilyFilter(k, v) end, setall = function (v) LM.UIFilter.SetAllFamilyFilters(v) end, menulist = function () return LM.UIFilter.GetFamilies() end, gettext = function (k) return LM.UIFilter.GetFamilyText(k) end, }, ['SOURCES'] = { value = 'SOURCES', text = SOURCES, checked = function (k) return LM.UIFilter.IsSourceChecked(k) end, set = function (k, v) LM.UIFilter.SetSourceFilter(k, v) end, setall = function (v) LM.UIFilter.SetAllSourceFilters(v) end, menulist = function () return LM.UIFilter.GetSources() end, gettext = function (k) return LM.UIFilter.GetSourceText(k) end, }, } local function InitDropDownSection(template, self, level, menuList) local info = UIDropDownMenu_CreateInfo() info.keepShownOnClick = true info.isNotRadio = true if level == 1 then if not template.menulist then info.text = template.text info.func = function (_, _, _, v) template.set(v) end info.checked = function () return template.checked() end UIDropDownMenu_AddButton(info, level) else info.hasArrow = true info.notCheckable = true info.text = template.text info.value = template.value info.menuList = template.menulist() UIDropDownMenu_AddButton(info, level) end return end if level == 2 then info.notCheckable = true info.text = CHECK_ALL info.func = function () template.setall(true) UIDropDownMenu_Refresh(self, nil, level) end UIDropDownMenu_AddButton(info, level) info.text = UNCHECK_ALL info.func = function () template.setall(false) UIDropDownMenu_Refresh(self, nil, level) end UIDropDownMenu_AddButton(info, level) -- UIDropDownMenu_AddSeparator(level) end info.notCheckable = nil -- The complicated stride calc is because the %s...%s entries are super -- annoying and so we want to max out the number of entries in the leafs -- but still need to make sure each menu is small enough. if #menuList > MENU_SPLIT_SIZE * 1.5 then info.notCheckable = true info.hasArrow = true info.func = nil local stride = 1 while #menuList/stride > MENU_SPLIT_SIZE do stride = stride * MENU_SPLIT_SIZE end for i = 1, #menuList, stride do local j = math.min(#menuList, i+stride-1) info.menuList = LM.tSlice(menuList, i, j) local f = template.gettext(info.menuList[1]) local t = template.gettext(info.menuList[#info.menuList]) info.text = format('%s...%s', f, t) info.value = template.value UIDropDownMenu_AddButton(info, level) end else for _, k in ipairs(menuList) do info.text = template.gettext(k) info.arg1 = k info.func = function (_, _, _, v) if IsShiftKeyDown() then template.setall(false) template.set(k, true) else template.set(k, v) end UIDropDownMenu_Refresh(self, nil, level) end info.checked = function () return template.checked(k) end UIDropDownMenu_AddButton(info, level) end end end function LiteMountFilterButtonMixin:Initialize(level, menuList) if level == nil then return end if level == 1 then ---- 1. COLLECTED ---- InitDropDownSection(DROPDOWNS.COLLECTED, self, level, menuList) ---- 2. NOT COLLECTED ---- InitDropDownSection(DROPDOWNS.NOT_COLLECTED, self, level, menuList) ---- 3. UNUSABLE ---- InitDropDownSection(DROPDOWNS.UNUSABLE, self, level, menuList) ---- 4. HIDDEN ---- InitDropDownSection(DROPDOWNS.HIDDEN, self, level, menuList) ---- 5. GROUP ---- InitDropDownSection(DROPDOWNS.GROUP, self, level, menuList) ---- 6. FLAG ---- InitDropDownSection(DROPDOWNS.FLAG, self, level, menuList) ---- 7. TYPE ---- InitDropDownSection(DROPDOWNS.TYPE, self, level, menuList) ---- 8. FAMILY ---- InitDropDownSection(DROPDOWNS.FAMILY, self, level, menuList) ---- 9. SOURCES ---- InitDropDownSection(DROPDOWNS.SOURCES, self, level, menuList) ---- 10. PRIORITY ---- InitDropDownSection(DROPDOWNS.PRIORITY, self, level, menuList) else InitDropDownSection(DROPDOWNS[UIDROPDOWNMENU_MENU_VALUE], self, level, menuList) end end function LiteMountFilterButtonMixin:OnLoad() UIDropDownMenu_Initialize(self.FilterDropDown, self.Initialize, "MENU") end
gpl-2.0
twoscomplement/tundra
scripts/tundra/tools/msvc-winsdk.lua
28
4318
-- msvc-winsdk.lua - Use Microsoft Windows SDK 7.1 or later to build. module(..., package.seeall) local native = require "tundra.native" local os = require "os" if native.host_platform ~= "windows" then error("the msvc toolset only works on windows hosts") end local function get_host_arch() local snative = native.getenv("PROCESSOR_ARCHITECTURE") local swow = native.getenv("PROCESSOR_ARCHITEW6432", "") if snative == "AMD64" or swow == "AMD64" then return "x64" elseif snative == "IA64" or swow == "IA64" then return "itanium"; else return "x86" end end local compiler_dirs = { ["x86"] = { ["x86"] = "bin\\", ["x64"] = "bin\\x86_amd64\\", ["itanium"] = "bin\\x86_ia64\\", }, ["x64"] = { ["x86"] = "bin\\", ["x64"] = { ["11.0"] = "bin\\x86_amd64\\", "bin\\amd64\\" }, ["itanium"] = "bin\\x86_ia64\\", }, ["itanium"] = { ["x86"] = "bin\\x86_ia64\\", ["itanium"] = "bin\\ia64\\", }, } local function setup(env, options) options = options or {} local target_arch = options.TargetArch or "x86" local host_arch = options.HostArch or get_host_arch() local vcversion = options.VcVersion or "10.0" local binDir = compiler_dirs[host_arch][target_arch][vcversion] or compiler_dirs[host_arch][target_arch][1] or compiler_dirs[host_arch][target_arch] if not binDir then errorf("can't build target arch %s on host arch %s", target_arch, host_arch) end local sdkDir; local sdkDirIncludes; local sdkLibDir; local vcLibDir; if vcversion == "11.0" then local sdk_key = "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.0" sdkDir = assert(native.reg_query("HKLM", sdk_key, "InstallationFolder")) sdkDirIncludes = { sdkDir .. "\\INCLUDE\\UM", sdkDir .. "\\INCLUDE\\SHARED" } sdkLibDir = "LIB\\win8\\um\\" vcLibDir = "LIB" if "x86" == target_arch then sdkLibDir = sdkLibDir .. "x86" elseif "x64" == target_arch then sdkLibDir = sdkLibDir .. "x64" vcLibDir = "LIB\\amd64" elseif "arm" == target_arch then sdkLibDir = sdkLibDir .. "arm" end else local sdk_key = "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows" sdkDir = assert(native.reg_query("HKLM", sdk_key, "CurrentInstallFolder")) sdkDirIncludes = { sdkDir .. "\\INCLUDE" }; sdkLibDir = "LIB" vcLibDir = "LIB" if "x64" == target_arch then sdkLibDir = "LIB\\x64" vcLibDir = "LIB\\amd64" elseif "itanium" == target_arch then sdkLibDir = "LIB\\IA64" vcLibDir = "LIB\\IA64" end end local vc_key = "SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7" local vc_dir = assert(native.reg_query("HKLM", vc_key, vcversion)) if vc_dir:sub(-1) ~= '\\' then vc_dir = vc_dir .. '\\' end local cl_exe = '"' .. vc_dir .. binDir .. "cl.exe" ..'"' local lib_exe = '"' .. vc_dir .. binDir .. "lib.exe" ..'"' local link_exe = '"' .. vc_dir .. binDir .. "link.exe" ..'"' env:set('CC', cl_exe) env:set('CXX', cl_exe) env:set('LIB', lib_exe) env:set('LD', link_exe) -- Set up the MS SDK associated with visual studio env:set_external_env_var("WindowsSdkDir", sdkDir) env:set_external_env_var("INCLUDE", table.concat(sdkDirIncludes, ";") .. ";" .. vc_dir .. "\\INCLUDE") local rc_exe print("vcversion", vcversion) if vcversion == "11.0" then rc_exe = '"' .. sdkDir .. "\\bin\\x86\\rc.exe" ..'"' else rc_exe = '"' .. sdkDir .. "\\bin\\rc.exe" ..'"' end env:set('RC', rc_exe) local libString = sdkDir .. "\\" .. sdkLibDir .. ";" .. vc_dir .. "\\" .. vcLibDir env:set_external_env_var("LIB", libString) env:set_external_env_var("LIBPATH", libString) local path = { } local vc_root = vc_dir:sub(1, -4) if binDir ~= "\\bin\\" then path[#path + 1] = vc_dir .. "\\bin" end path[#path + 1] = vc_root .. "Common7\\Tools" -- drop vc\ at end path[#path + 1] = vc_root .. "Common7\\IDE" -- drop vc\ at end path[#path + 1] = sdkDir path[#path + 1] = vc_dir .. binDir path[#path + 1] = env:get_external_env_var('PATH') env:set_external_env_var("PATH", table.concat(path, ';')) end function apply(env, options) -- Load basic MSVC environment setup first. We're going to replace the paths to -- some tools. tundra.unitgen.load_toolset('msvc', env) setup(env, options) end
gpl-3.0
focusworld/focus_asp
plugins/boobs.lua
150
1613
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. ًں”‍", "!butts: Get a butts NSFW image. ًں”‍" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
LordZamy/pokemon-love
src/player/controller.lua
1
2053
PlayerController = {} local player function PlayerController:init(playerObject) -- set local copy of player to reference passed in object player = playerObject -- load sprite sheet player:sheet("assets/spritesheets/player_animations.png") -- set up grid -- basic player animations are 16x22 per sprite player:grid(16, 22, player:sheet():getWidth(), player:sheet():getHeight(), 0, 0, 0) -- create animations defineAnimations() -- starting animation self.changeAnimation("walk_down") end -- updates player position every frame function PlayerController:update(dt) player.pos.x = player.pos.x - (player.pos.x - player.targetPos.x) * dt * player.speed player.pos.y = player.pos.y - (player.pos.y - player.targetPos.y) * dt * player.speed end function defineAnimations() local duration = 0.4 -- walk down player:animation("walk_down", player:frames(1, 1, 1, 2, 1, 1, 1, 3), duration) -- walk left player:animation("walk_left", player:frames(2, 1, 2, 2, 2, 1, 2, 3), duration) -- walk up player:animation("walk_up", player:frames(3, 1, 3, 2, 3, 1, 3, 3), duration) -- walk right player:animation("walk_right", player:frames(4, 1, 4, 2, 4, 1, 4, 3), duration) end -- method to interface with player animation change function PlayerController.changeAnimation(name) player:animation(name) end -- moves player and sets new animation function PlayerController:move(direction) self.changeAnimation("walk_" .. direction) self.snapTo(direction) end -- sets the player's target position for grid snapping function PlayerController.snapTo(direction) if direction == "up" then player.targetPos.y = player.targetPos.y - GRID_SZ elseif direction == "down" then player.targetPos.y = player.targetPos.y + GRID_SZ elseif direction == "left" then player.targetPos.x = player.targetPos.x - GRID_SZ elseif direction == "right" then player.targetPos.x = player.targetPos.x + GRID_SZ end end return PlayerController
mit
KlonZK/Zero-K
effects/emg.lua
25
12010
-- emg_shells_m -- emg_hit -- flashplosion -- flashmuzzle1 -- emg_hit_he -- brawlimpacts -- brawlermuzzle -- emg_shells_l -- emg_hit_water return { ["emg_shells_m"] = { usedefaultexplosions = false, shells = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 1 1 1 1 1]], directional = true, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, -0.5, 0]], numparticles = 1, particlelife = 45, particlelifespread = 0, particlesize = 2.5, particlesizespread = 0, particlespeed = 3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[shell]], }, }, }, ["emg_hit"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 8, ttl = 4, color = { [1] = 1, [2] = 0.75, [3] = 0, }, }, sparks = { class = [[CSimpleParticleSystem]], count = 1, ground = true, unit = 1, properties = { airdrag = 0.97, colormap = [[1 1 0 0.01 1 1 0 0.01 1 0.5 0 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 40, emitvector = [[dir]], gravity = [[0, -0.2, 0]], numparticles = 4, particlelife = 7, particlelifespread = 0, particlesize = 6, particlesizespread = 0, particlespeed = 3, particlespeedspread = 4, pos = [[0, 1, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, splash = { class = [[CExpGenSpawner]], count = 1, nounit = 1, properties = { delay = 0, explosiongenerator = [[custom:EMG_HIT_WATER]], pos = [[0, 0, 0]], }, }, }, ["flashplosion"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 12, ttl = 3, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 0 0.01 1 1 0 0.01 1 0.5 0 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 40, emitvector = [[dir]], gravity = [[0, -0.2, 0]], numparticles = 4, particlelife = 7, particlelifespread = 0, particlesize = 6, particlesizespread = 0, particlespeed = 3, particlespeedspread = 4, pos = [[0, 1, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flashmuzzle1"] = { bitmapmuzzleflame = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 1 1 0.07 1 0.7 0 0.01 0.9 0.3 0 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[flowerflash]], length = 18, sidetexture = [[plasma2]], size = 12, sizegrowth = 1, ttl = 3, }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.4, flashsize = 35, ttl = 3, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0, }, }, }, ["emg_hit_he"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.25, flashsize = 48, ttl = 3, color = { [1] = 1, [2] = 0.94999998807907, [3] = 0.5, }, }, groundsmoke = { class = [[CSimpleParticleSystem]], count = 3, ground = true, unit = 1, properties = { airdrag = 0.8, colormap = [[1 1 0 1 1 0.25 0 0.8 0 0 0 0.6 0 0 0 0.4 0 0 0 0.2 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 90, emitvector = [[0, 1, 0]], gravity = [[0, 0.2, 0]], numparticles = 1, particlelife = 10, particlelifespread = 5, particlesize = 4, particlesizespread = 4, particlespeed = 2, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[smokesmall]], }, }, main = { air = true, class = [[heatcloud]], count = 1, ground = true, water = true, properties = { heat = 6, heatfalloff = 1, maxheat = 6, pos = [[0, 1, 0]], size = 1, sizegrowth = 8, speed = [[0, 1, 0]], texture = [[explo]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 0.95 0.5 0.01 1 0.95 0.5 0.01 1 0.95 0.5 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 90, emitvector = [[0, 1, 0]], gravity = [[0, -0.2, 0]], numparticles = 16, particlelife = 10, particlelifespread = 0, particlesize = 2, particlesizespread = 1, particlespeed = 1, particlespeedspread = 6, pos = [[0, 1, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, watermist = { class = [[CSimpleParticleSystem]], count = 3, water = true, properties = { airdrag = 0.8, colormap = [[0.75 0.75 1 1 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 90, emitvector = [[0, 1, 0]], gravity = [[0, 0.2, 0]], numparticles = 1, particlelife = 10, particlelifespread = 5, particlesize = 4, particlesizespread = 4, particlespeed = 2, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[smokesmall]], }, }, }, ["brawlimpacts"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 12, ttl = 3, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 0 0.01 1 1 0 0.01 1 0.5 0 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 90, emitvector = [[dir]], gravity = [[0, -0.4, 0]], numparticles = 4, particlelife = 14, particlelifespread = 0, particlesize = 6, particlesizespread = 0, particlespeed = 5, particlespeedspread = 10, pos = [[0, 1, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["brawlermuzzle"] = { bitmapmuzzleflame = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 1 0 0.01 1 0.5 0 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0.1, fronttexture = [[flowerflash]], length = 18, sidetexture = [[plasma2]], size = 12, sizegrowth = 1, ttl = 3, }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 35, ttl = 3, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0, }, }, }, ["emg_shells_l"] = { usedefaultexplosions = false, shells = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 1 1 1 1 1]], directional = true, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, -0.5, 0]], numparticles = 1, particlelife = 15, particlelifespread = 0, particlesize = 2.5, particlesizespread = 0, particlespeed = 3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[shell]], }, }, }, ["emg_hit_water"] = { splash = { class = [[CBitmapMuzzleFlame]], count = 2, water = true, properties = { colormap = [[0.45 0.45 0.5 0.5 0.045 0.045 0.05 0.05]], dir = [[-0.1 r0.2, 1, -0.1 r0.2]], frontoffset = 0, fronttexture = [[splashbase]], length = [[10 r4]], sidetexture = [[splashside]], size = [[2 r1]], sizegrowth = 1, ttl = 12, }, }, }, }
gpl-2.0
ld-test/pdh
examples/monitor_by_name.lua
2
2037
local PROCESS_NAME = arg[1] or "notepad" local COUNTER_NAME = arg[2] or "% Processor Time" local pdh = require "pdh" local T = pdh.translate_path local assert = function(...) if not ... then return assert(..., tostring((select(2, ...)))) end return ... end local query = pdh.query() local counterPid = assert(query:add_counter(T[[\Process(*)\ID Process]])) local counterCpu = assert(query:add_counter(T([[\Process(*)\]] .. COUNTER_NAME))) local process_list = {} query:collect() pdh.sleep(100) while true do query:collect() -- support active instance list if #process_list == 0 then print("Enter counterPid") while true do local instance = 0 local _, status = counterPid:as_double_array(function(i, name, pid) if name == PROCESS_NAME then table.insert(process_list, {i, name, pid}) end end) if status then print("counterPid collect:", status) if status:no() == pdh.PDH_CSTATUS_INVALID_DATA then process_list = {} else pdh.sleep(1000) end else pdh.sleep(1000) end if #process_list > 0 then break end query:collect() end end print("Leave counterPid") -- display processor usage if #process_list > 0 then print("Enter counterCpu") while true do local _, status = counterCpu:as_double_array(function(i, name, cpu) for instance, t in ipairs(process_list) do if t[1] == i then -- ??? invalid list if name ~= t[2] then process_list = {} return false end local name = name .. '#' .. (instance - 1) name = counterCpu:path():gsub("%*#0", name):gsub("%*", name) local pid = t[3] print(os.date(), name, pid, cpu) end end end) if status then print("counterCpu collect:", status) if status:no() == pdh.PDH_CSTATUS_INVALID_DATA then process_list = {} end end print("-------------------------------") if #process_list == 0 then break end pdh.sleep(1000) query:collect() end end print("Leave counterCpu") end
mit
mohammadclashclash/telefree
plugins/all.lua
264
4202
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'chat stats! \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) if not data[tostring(target)] then return 'Group is not added.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group \n \n" local settings = show_group_settings(target) text = text.."Group settings \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\n"..modlist local link = get_link(target) text = text.."\n\n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] and msg.to.id ~= our_id then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end return end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
caa-dev-apps/libcef_v2
LuaJIT-2.0.0-beta8/dynasm/dasm_arm.lua
2
29255
------------------------------------------------------------------------------ -- DynASM ARM module. -- -- Copyright (C) 2005-2011 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "arm", description = "DynASM ARM module", version = "1.3.0", vernum = 10300, release = "2011-05-05", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable, rawget = assert, setmetatable, rawget local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub local concat, sort, insert = table.concat, table.sort, table.insert -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", "IMM12", "IMM16", "IMML8", "IMML12", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Return 8 digit hex number. local function tohex(x) return sub(format("%08x", x), -8) -- Avoid 64 bit portability problem in Lua. end -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0x000fffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") if n <= 0x000fffff then insert(actlist, pos+1, n) n = map_action.ESC * 0x10000 end actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. -- Ext. register name -> int. name. local map_archdef = { sp = "r13", lr = "r14", pc = "r15", } -- Int. register name -> ext. name. local map_reg_rev = { r13 = "sp", r14 = "lr", r15 = "pc", } local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) return map_reg_rev[s] or s end local map_shift = { lsl = 0, lsr = 1, asr = 2, ror = 3, } local map_cond = { eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7, hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14, hs = 2, lo = 3, } ------------------------------------------------------------------------------ -- Template strings for ARM instructions. local map_op = { -- Basic data processing instructions. and_3 = "e0000000DNPs", eor_3 = "e0200000DNPs", sub_3 = "e0400000DNPs", rsb_3 = "e0600000DNPs", add_3 = "e0800000DNPs", adc_3 = "e0a00000DNPs", sbc_3 = "e0c00000DNPs", rsc_3 = "e0e00000DNPs", tst_2 = "e1100000NP", teq_2 = "e1300000NP", cmp_2 = "e1500000NP", cmn_2 = "e1700000NP", orr_3 = "e1800000DNPs", mov_2 = "e1a00000DPs", bic_3 = "e1c00000DNPs", mvn_2 = "e1e00000DPs", and_4 = "e0000000DNMps", eor_4 = "e0200000DNMps", sub_4 = "e0400000DNMps", rsb_4 = "e0600000DNMps", add_4 = "e0800000DNMps", adc_4 = "e0a00000DNMps", sbc_4 = "e0c00000DNMps", rsc_4 = "e0e00000DNMps", tst_3 = "e1100000NMp", teq_3 = "e1300000NMp", cmp_3 = "e1500000NMp", cmn_3 = "e1700000NMp", orr_4 = "e1800000DNMps", mov_3 = "e1a00000DMps", bic_4 = "e1c00000DNMps", mvn_3 = "e1e00000DMps", lsl_3 = "e1a00000DMws", lsr_3 = "e1a00020DMws", asr_3 = "e1a00040DMws", ror_3 = "e1a00060DMws", rrx_2 = "e1a00060DMs", -- Multiply and multiply-accumulate. mul_3 = "e0000090NMSs", mla_4 = "e0200090NMSDs", umaal_4 = "e0400090DNMSs", -- v6 mls_4 = "e0600090DNMSs", -- v6T2 umull_4 = "e0800090DNMSs", umlal_4 = "e0a00090DNMSs", smull_4 = "e0c00090DNMSs", smlal_4 = "e0e00090DNMSs", -- Halfword multiply and multiply-accumulate. smlabb_4 = "e1000080NMSD", -- v5TE smlatb_4 = "e10000a0NMSD", -- v5TE smlabt_4 = "e10000c0NMSD", -- v5TE smlatt_4 = "e10000e0NMSD", -- v5TE smlawb_4 = "e1200080NMSD", -- v5TE smulwb_3 = "e12000a0NMS", -- v5TE smlawt_4 = "e12000c0NMSD", -- v5TE smulwt_3 = "e12000e0NMS", -- v5TE smlalbb_4 = "e1400080NMSD", -- v5TE smlaltb_4 = "e14000a0NMSD", -- v5TE smlalbt_4 = "e14000c0NMSD", -- v5TE smlaltt_4 = "e14000e0NMSD", -- v5TE smulbb_3 = "e1600080NMS", -- v5TE smultb_3 = "e16000a0NMS", -- v5TE smulbt_3 = "e16000c0NMS", -- v5TE smultt_3 = "e16000e0NMS", -- v5TE -- Miscellaneous data processing instructions. clz_2 = "e16f0f10DM", -- v5T rev_2 = "e6bf0f30DM", -- v6 rev16_2 = "e6bf0fb0DM", -- v6 revsh_2 = "e6ff0fb0DM", -- v6 sel_3 = "e6800fb0DNM", -- v6 usad8_3 = "e780f010NMS", -- v6 usada8_4 = "e7800010NMSD", -- v6 rbit_2 = "e6ff0f30DM", -- v6T2 movw_2 = "e3000000DW", -- v6T2 movt_2 = "e3400000DW", -- v6T2 -- Note: the X encodes width-1, not width. sbfx_4 = "e7a00050DMvX", -- v6T2 ubfx_4 = "e7e00050DMvX", -- v6T2 -- Note: the X encodes the msb field, not the width. bfc_3 = "e7c0001fDvX", -- v6T2 bfi_4 = "e7c00010DMvX", -- v6T2 -- Packing and unpacking instructions. pkhbt_3 = "e6800010DNM", pkhbt_4 = "e6800010DNMv", -- v6 pkhtb_3 = "e6800050DNM", pkhtb_4 = "e6800050DNMv", -- v6 sxtab_3 = "e6a00070DNM", sxtab_4 = "e6a00070DNMv", -- v6 sxtab16_3 = "e6800070DNM", sxtab16_4 = "e6800070DNMv", -- v6 sxtah_3 = "e6b00070DNM", sxtah_4 = "e6b00070DNMv", -- v6 sxtb_2 = "e6af0070DM", sxtb_3 = "e6af0070DMv", -- v6 sxtb16_2 = "e68f0070DM", sxtb16_3 = "e68f0070DMv", -- v6 sxth_2 = "e6bf0070DM", sxth_3 = "e6bf0070DMv", -- v6 uxtab_3 = "e6e00070DNM", uxtab_4 = "e6e00070DNMv", -- v6 uxtab16_3 = "e6c00070DNM", uxtab16_4 = "e6c00070DNMv", -- v6 uxtah_3 = "e6f00070DNM", uxtah_4 = "e6f00070DNMv", -- v6 uxtb_2 = "e6ef0070DM", uxtb_3 = "e6ef0070DMv", -- v6 uxtb16_2 = "e6cf0070DM", uxtb16_3 = "e6cf0070DMv", -- v6 uxth_2 = "e6ff0070DM", uxth_3 = "e6ff0070DMv", -- v6 -- Saturating instructions. qadd_3 = "e1000050DMN", -- v5TE qsub_3 = "e1200050DMN", -- v5TE qdadd_3 = "e1400050DMN", -- v5TE qdsub_3 = "e1600050DMN", -- v5TE -- Note: the X for ssat* encodes sat_imm-1, not sat_imm. ssat_3 = "e6a00010DXM", ssat_4 = "e6a00010DXMp", -- v6 usat_3 = "e6e00010DXM", usat_4 = "e6e00010DXMp", -- v6 ssat16_3 = "e6a00f30DXM", -- v6 usat16_3 = "e6e00f30DXM", -- v6 -- Parallel addition and subtraction. sadd16_3 = "e6100f10DNM", -- v6 sasx_3 = "e6100f30DNM", -- v6 ssax_3 = "e6100f50DNM", -- v6 ssub16_3 = "e6100f70DNM", -- v6 sadd8_3 = "e6100f90DNM", -- v6 ssub8_3 = "e6100ff0DNM", -- v6 qadd16_3 = "e6200f10DNM", -- v6 qasx_3 = "e6200f30DNM", -- v6 qsax_3 = "e6200f50DNM", -- v6 qsub16_3 = "e6200f70DNM", -- v6 qadd8_3 = "e6200f90DNM", -- v6 qsub8_3 = "e6200ff0DNM", -- v6 shadd16_3 = "e6300f10DNM", -- v6 shasx_3 = "e6300f30DNM", -- v6 shsax_3 = "e6300f50DNM", -- v6 shsub16_3 = "e6300f70DNM", -- v6 shadd8_3 = "e6300f90DNM", -- v6 shsub8_3 = "e6300ff0DNM", -- v6 uadd16_3 = "e6500f10DNM", -- v6 uasx_3 = "e6500f30DNM", -- v6 usax_3 = "e6500f50DNM", -- v6 usub16_3 = "e6500f70DNM", -- v6 uadd8_3 = "e6500f90DNM", -- v6 usub8_3 = "e6500ff0DNM", -- v6 uqadd16_3 = "e6600f10DNM", -- v6 uqasx_3 = "e6600f30DNM", -- v6 uqsax_3 = "e6600f50DNM", -- v6 uqsub16_3 = "e6600f70DNM", -- v6 uqadd8_3 = "e6600f90DNM", -- v6 uqsub8_3 = "e6600ff0DNM", -- v6 uhadd16_3 = "e6700f10DNM", -- v6 uhasx_3 = "e6700f30DNM", -- v6 uhsax_3 = "e6700f50DNM", -- v6 uhsub16_3 = "e6700f70DNM", -- v6 uhadd8_3 = "e6700f90DNM", -- v6 uhsub8_3 = "e6700ff0DNM", -- v6 -- Load/store instructions. str_2 = "e4000000DL", str_3 = "e4000000DL", str_4 = "e4000000DL", strb_2 = "e4400000DL", strb_3 = "e4400000DL", strb_4 = "e4400000DL", ldr_2 = "e4100000DL", ldr_3 = "e4100000DL", ldr_4 = "e4100000DL", ldrb_2 = "e4500000DL", ldrb_3 = "e4500000DL", ldrb_4 = "e4500000DL", strh_2 = "e00000b0DL", strh_3 = "e00000b0DL", ldrh_2 = "e01000b0DL", ldrh_3 = "e01000b0DL", ldrd_2 = "e00000d0DL", ldrd_3 = "e00000d0DL", -- v5TE ldrsb_2 = "e01000d0DL", ldrsb_3 = "e01000d0DL", strd_2 = "e00000f0DL", strd_3 = "e00000f0DL", -- v5TE ldrsh_2 = "e01000f0DL", ldrsh_3 = "e01000f0DL", ldm_2 = "e8900000nR", ldmia_2 = "e8900000nR", ldmfd_2 = "e8900000nR", ldmda_2 = "e8100000nR", ldmfa_2 = "e8100000nR", ldmdb_2 = "e9100000nR", ldmea_2 = "e9100000nR", ldmib_2 = "e9900000nR", ldmed_2 = "e9900000nR", stm_2 = "e8800000nR", stmia_2 = "e8800000nR", stmfd_2 = "e8800000nR", stmda_2 = "e8000000nR", stmfa_2 = "e8000000nR", stmdb_2 = "e9000000nR", stmea_2 = "e9000000nR", stmib_2 = "e9800000nR", stmed_2 = "e9800000nR", pop_1 = "e8bd0000R", push_1 = "e92d0000R", -- Branch instructions. b_1 = "ea000000B", bl_1 = "eb000000B", blx_1 = "e12fff30C", bx_1 = "e12fff10M", -- Miscellaneous instructions. nop_0 = "e1a00000", mrs_1 = "e10f0000D", bkpt_1 = "e1200070K", -- v5T svc_1 = "ef000000T", swi_1 = "ef000000T", ud_0 = "e7f001f0", -- NYI: Advanced SIMD and VFP instructions. -- NYI instructions, since I have no need for them right now: -- swp, swpb, strex, ldrex, strexd, ldrexd, strexb, ldrexb, strexh, ldrexh -- msr, nopv6, yield, wfe, wfi, sev, dbg, bxj, smc, srs, rfe -- cps, setend, pli, pld, pldw, clrex, dsb, dmb, isb -- stc, ldc, mcr, mcr2, mrc, mrc2, mcrr, mcrr2, mrrc, mrrc2, cdp, cdp2 } -- Add mnemonics for "s" variants. do local t = {} for k,v in pairs(map_op) do if sub(v, -1) == "s" then local v2 = sub(v, 1, 2)..char(byte(v, 3)+1)..sub(v, 4, -2) t[sub(k, 1, -3).."s"..sub(k, -2)] = v2 end end for k,v in pairs(t) do map_op[k] = v end end ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r1?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r(1?[0-9])$") if r then r = tonumber(r) if r <= 15 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_gpr_pm(expr) local pm, expr2 = match(expr, "^([+-]?)(.*)$") return parse_gpr(expr2), (pm == "-") end local function parse_reglist(reglist) reglist = match(reglist, "^{%s*([^}]*)}$") if not reglist then werror("register list expected") end local rr = 0 for p in gmatch(reglist..",", "%s*([^,]*),") do local rbit = 2^parse_gpr(gsub(p, "%s+$", "")) if ((rr - (rr % rbit)) / rbit) % 2 ~= 0 then werror("duplicate register `"..p.."'") end rr = rr + rbit end return rr end local function parse_imm(imm, bits, shift, scale, signed) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then if n % 2^scale == 0 then n = n / 2^scale if signed then if n >= 0 then if n < 2^(bits-1) then return n*2^shift end else if n >= -(2^(bits-1))-1 then return (n+2^bits)*2^shift end end else if n >= 0 and n <= 2^bits-1 then return n*2^shift end end end werror("out of range immediate `"..imm.."'") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_imm12(imm) local n = tonumber(imm) if n then local m = n for i=0,-15,-1 do if m >= 0 and m <= 255 and n % 1 == 0 then return m + (i%16) * 256 end local t = m % 4 m = (m - t) / 4 + t * 2^30 end werror("out of range immediate `"..imm.."'") else waction("IMM12", 0, imm) return 0 end end local function parse_imm16(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then if n >= 0 and n <= 65535 and n % 1 == 0 then local t = n % 4096 return (n - t) * 16 + t end werror("out of range immediate `"..imm.."'") else waction("IMM16", 32*16, imm) return 0 end end local function parse_imm_load(imm, ext) local n = tonumber(imm) if n then if ext then if n >= -255 and n <= 255 then local up = 0x00800000 if n < 0 then n = -n; up = 0 end return (n-(n%16))*16+(n%16) + up end else if n >= -4095 and n <= 4095 then if n >= 0 then return n+0x00800000 end return -n end end werror("out of range immediate `"..imm.."'") else waction(ext and "IMML8" or "IMML12", 32768 + 32*(ext and 8 or 12), imm) return 0 end end local function parse_shift(shift, gprok) if shift == "rrx" then return 3 * 32 else local s, s2 = match(shift, "^(%S+)%s*(.*)$") s = map_shift[s] if not s then werror("expected shift operand") end if sub(s2, 1, 1) == "#" then return parse_imm(s2, 5, 7, 0, false) + s * 32 else if not gprok then werror("expected immediate shift operand") end return parse_gpr(s2) * 256 + s * 32 + 16 end end end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end local function parse_load(params, nparams, n, op) local oplo = op % 256 local ext, ldrd = (oplo ~= 0), (oplo == 208) local d if (ldrd or oplo == 240) then d = ((op - (op % 4096)) / 4096) % 16 if d % 2 ~= 0 then werror("odd destination register") end end local pn = params[n] local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") local p2 = params[n+1] if not p1 then if not p2 then if match(pn, "^[<>=%-]") or match(pn, "^extern%s+") then local mode, n, s = parse_label(pn, false) waction("REL_"..mode, n + (ext and 0x1800 or 0x0800), s, 1) return op + 15 * 65536 + 0x01000000 + (ext and 0x00400000 or 0) end local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local d, tp = parse_gpr(reg) if tp then waction(ext and "IMML8" or "IMML12", 32768 + 32*(ext and 8 or 12), format(tp.ctypefmt, tailr)) return op + d * 65536 + 0x01000000 + (ext and 0x00400000 or 0) end end end werror("expected address operand") end if wb == "!" then op = op + 0x00200000 end if p2 then if wb == "!" then werror("bad use of '!'") end local p3 = params[n+2] op = op + parse_gpr(p1) * 65536 local imm = match(p2, "^#(.*)$") if imm then local m = parse_imm_load(imm, ext) if p3 then werror("too many parameters") end op = op + m + (ext and 0x00400000 or 0) else local m, neg = parse_gpr_pm(p2) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 then op = op + parse_shift(p3) end end else local p1a, p2 = match(p1, "^([^,%s]*)%s*(.*)$") op = op + parse_gpr(p1a) * 65536 + 0x01000000 if p2 ~= "" then local imm = match(p2, "^,%s*#(.*)$") if imm then local m = parse_imm_load(imm, ext) op = op + m + (ext and 0x00400000 or 0) else local p2a, p3 = match(p2, "^,%s*([^,%s]*)%s*,?%s*(.*)$") local m, neg = parse_gpr_pm(p2a) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 ~= "" then if ext then werror("too many parameters") end op = op + parse_shift(p3) end end else if wb == "!" then werror("bad use of '!'") end op = op + (ext and 0x00c00000 or 0x00800000) end end return op end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return sub(template, 9) end local op = tonumber(sub(template, 1, 8), 16) local n = 1 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions. if secpos+3 > maxsecpos then wflush() end local pos = wpos() -- Process each character. for p in gmatch(sub(template, 9), ".") do if p == "D" then op = op + parse_gpr(params[n]) * 4096; n = n + 1 elseif p == "N" then op = op + parse_gpr(params[n]) * 65536; n = n + 1 elseif p == "S" then op = op + parse_gpr(params[n]) * 256; n = n + 1 elseif p == "M" then op = op + parse_gpr(params[n]); n = n + 1 elseif p == "P" then local imm = match(params[n], "^#(.*)$") if imm then op = op + parse_imm12(imm) + 0x02000000 else op = op + parse_gpr(params[n]) end n = n + 1 elseif p == "p" then op = op + parse_shift(params[n], true); n = n + 1 elseif p == "L" then op = parse_load(params, nparams, n, op) elseif p == "B" then local mode, n, s = parse_label(params[n], false) waction("REL_"..mode, n, s, 1) elseif p == "C" then -- blx gpr vs. blx label. local p = params[n] if match(p, "^([%w_]+):(r1?[0-9])$") or match(p, "^r(1?[0-9])$") then op = op + parse_gpr(p) else if op < 0xe0000000 then werror("unconditional instruction") end local mode, n, s = parse_label(p, false) waction("REL_"..mode, n, s, 1) op = 0xfa000000 end elseif p == "n" then local r, wb = match(params[n], "^([^!]*)(!?)$") op = op + parse_gpr(r) * 65536 + (wb == "!" and 0x00200000 or 0) n = n + 1 elseif p == "R" then op = op + parse_reglist(params[n]); n = n + 1 elseif p == "W" then op = op + parse_imm16(params[n]); n = n + 1 elseif p == "v" then op = op + parse_imm(params[n], 5, 7, 0, false); n = n + 1 elseif p == "w" then local imm = match(params[n], "^#(.*)$") if imm then op = op + parse_imm(params[n], 5, 7, 0, false); n = n + 1 else op = op + parse_gpr(params[n]) * 256 + 16 end elseif p == "X" then op = op + parse_imm(params[n], 5, 16, 0, false); n = n + 1 elseif p == "K" then local imm = tonumber(match(params[n], "^#(.*)$")); n = n + 1 if not imm or imm % 1 ~= 0 or imm < 0 or imm > 0xffff then werror("bad immediate operand") end local t = imm % 16 op = op + (imm - t) * 16 + t elseif p == "T" then op = op + parse_imm(params[n], 24, 0, 0, false); n = n + 1 elseif p == "s" then -- Ignored. else assert(false) end end wputpos(pos, op) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = function(t, k) local v = map_coreop[k] if v then return v end local cc = sub(k, -4, -3) local cv = map_cond[cc] if cv then local v = rawget(t, sub(k, 1, -5)..sub(k, -2)) if type(v) == "string" then return format("%x%s", cv, sub(v, 2)) end end end }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
annulen/premake-dev-rgeary
tests/actions/codeblocks/codeblocks_files.lua
21
1664
-- -- tests/actions/codeblocks/codeblocks_files.lua -- Validate generation of files block in CodeLite C/C++ projects. -- Copyright (c) 2011 Jason Perkins and the Premake project -- T.codeblocks_files = { } local suite = T.codeblocks_files local codeblocks = premake.codeblocks -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) codeblocks.files(prj) end -- -- Test grouping and nesting -- function suite.SimpleSourceFile() files { "hello.cpp" } prepare() test.capture [[ <Unit filename="hello.cpp"> </Unit> ]] end function suite.SingleFolderLevel() files { "src/hello.cpp" } prepare() test.capture [[ <Unit filename="src/hello.cpp"> </Unit> ]] end function suite.MultipleFolderLevels() files { "src/greetings/hello.cpp" } prepare() test.capture [[ <Unit filename="src/greetings/hello.cpp"> </Unit> ]] end -- -- Test source file type handling -- function suite.CFileInCppProject() files { "hello.c" } prepare() test.capture [[ <Unit filename="hello.c"> <Option compilerVar="CC" /> </Unit> ]] end function suite.WindowsResourceFile() files { "hello.rc" } prepare() test.capture [[ <Unit filename="hello.rc"> <Option compilerVar="WINDRES" /> </Unit> ]] end function suite.PchFile() files { "hello.h" } pchheader "hello.h" prepare() test.capture [[ <Unit filename="hello.h"> <Option compilerVar="CPP" /> <Option compile="1" /> <Option weight="0" /> <Add option="-x c++-header" /> </Unit> ]] end
bsd-3-clause
aqasaeed/megazeus
bot/utils.lua
239
13499
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
KlonZK/Zero-K
units/dante.lua
3
11238
unitDef = { unitname = [[dante]], name = [[Dante]], description = [[Assault/Riot Strider]], acceleration = 0.0984, brakeRate = 0.2392, buildCostEnergy = 3500, buildCostMetal = 3500, builder = false, buildPic = [[dante.png]], buildTime = 3500, canAttack = true, canDGun = true, canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], collisionVolumeTest = 1, corpse = [[DEAD]], customParams = { description_fr = [[Mechwarrior d'Assaut]], description_de = [[Sturm/Riotroboter]], description_pl = [[Robot szturmowo-bojowy]], helptext = [[The Dante is a heavy combat unit that specializes in getting close and melting its target. Its flamethrower and twin heatrays aren't extraordinary, but its incendiary rockets can be fired in a salvo of twenty that devastates a wide swath of terrain.]], helptext_fr = [[]], helptext_de = [[Der Dante ist eine schwere Sturmeinheit f? den Fronteinsatz, wenn herkömmliche Mittel versagen. Sein Flammenwerfer und doppelläufiger Heat Ray sind zwar nichts besonderes, doch seine Brandraketen können in 20-Schuss Salven breite Schneisen in das Gelände schlagen.]], helptext_pl = [[Dante to ciezka jednostka bojowa, ktora specjalizuje sie w zadawaniu ciezkich obrazen w bezposredniej walce. Posiada promien cieplny, miotacz ognia i rakiety podpalajace, ktore moze wystrzelic w salwie.]], }, explodeAs = [[CRAWL_BLASTSML]], footprintX = 4, footprintZ = 4, iconType = [[t3riot]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, losEmitHeight = 35, mass = 716, maxDamage = 11000, maxSlope = 36, maxVelocity = 1.75, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[KBOT4]], noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE SUB]], objectName = [[dante.s3o]], script = [[dante.lua]], seismicSignature = 4, selfDestructAs = [[CRAWL_BLASTSML]], sfxtypes = { explosiongenerators = { [[custom:SLASHMUZZLE]], [[custom:SLASHREARMUZZLE]], [[custom:RAIDMUZZLE]], }, }, side = [[CORE]], sightDistance = 600, smoothAnim = true, trackOffset = 0, trackStrength = 8, trackStretch = 0.6, trackType = [[ComTrack]], trackWidth = 38, turnRate = 597, upright = true, workerTime = 0, weapons = { { def = [[NAPALM_ROCKETS]], badTargetCategory = [[FIXEDWING GUNSHIP]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[HEATRAY]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[NAPALM_ROCKETS_SALVO]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[DANTE_FLAMER]], badTargetCategory = [[FIREPROOF]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP FIXEDWING]], }, }, weaponDefs = { DANTE_FLAMER = { name = [[Flamethrower]], areaOfEffect = 96, avoidFeature = false, avoidFriendly = false, collideFeature = false, collideGround = false, coreThickness = 0, craterBoost = 0, craterMult = 0, cegTag = [[flamer]], customParams = { flamethrower = [[1]], setunitsonfire = "1", burntime = [[450]], }, damage = { default = 15, subs = 0.15, }, duration = 0.01, explosionGenerator = [[custom:SMOKE]], fallOffRate = 1, fireStarter = 100, impulseBoost = 0, impulseFactor = 0, intensity = 0.3, interceptedByShieldType = 1, noExplode = true, noSelfDamage = true, --predictBoost = 1, range = 340, reloadtime = 0.16, rgbColor = [[1 1 1]], soundStart = [[weapon/flamethrower]], soundTrigger = true, texture1 = [[flame]], thickness = 0, tolerance = 5000, turret = true, weaponType = [[LaserCannon]], weaponVelocity = 800, }, HEATRAY = { name = [[Heat Ray]], accuracy = 512, areaOfEffect = 20, beamWeapon = true, cegTag = [[HEATRAY_CEG]], coreThickness = 0.5, craterBoost = 0, craterMult = 0, damage = { default = 49, planes = 49, subs = 2.45, }, duration = 0.3, dynDamageExp = 1, dynDamageInverted = false, explosionGenerator = [[custom:HEATRAY_HIT]], fallOffRate = 1, fireStarter = 90, heightMod = 1, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, lodDistance = 10000, projectiles = 2, proximityPriority = 4, range = 430, reloadtime = 0.1, rgbColor = [[1 0.1 0]], rgbColor2 = [[1 1 0.25]], soundStart = [[weapon/heatray_fire]], thickness = 3, tolerance = 5000, turret = true, weaponType = [[LaserCannon]], weaponVelocity = 500, }, NAPALM_ROCKETS = { name = [[Napalm Rockets]], areaOfEffect = 228, burst = 2, burstrate = 0.1, cegTag = [[missiletrailredsmall]], craterBoost = 0, craterMult = 0, customParams = { setunitsonfire = "1", burnchance = "1", }, damage = { default = 120.8, subs = 6, }, edgeEffectiveness = 0.75, explosionGenerator = [[custom:napalm_koda]], fireStarter = 250, fixedlauncher = true, flightTime = 1.8, impulseBoost = 0, impulseFactor = 0.1, interceptedByShieldType = 2, model = [[wep_m_hailstorm.s3o]], range = 460, reloadtime = 2, smokedelay = [[0.1]], smokeTrail = true, soundHit = [[weapon/missile/rapid_rocket_hit]], soundStart = [[weapon/missile/rapid_rocket_fire]], soundwater = [[SplsSml]], sprayAngle = 1000, startsmoke = [[1]], startVelocity = 150, tolerance = 6500, tracks = false, turnRate = 8000, turret = true, weaponAcceleration = 100, weaponTimer = 1.8, weaponType = [[MissileLauncher]], weaponVelocity = 800, wobble = 10000, }, NAPALM_ROCKETS_SALVO = { name = [[Napalm Rocket Salvo]], areaOfEffect = 228, avoidFeature = false, avoidFriendly = false, avoidNeutral = false, burst = 10, burstrate = 0.1, cegTag = [[missiletrailredsmall]], commandfire = true, craterBoost = 0, craterMult = 0, customParams = { setunitsonfire = "1", burnchance = "1", }, damage = { default = 120.8, subs = 6, }, dance = 15, edgeEffectiveness = 0.75, explosionGenerator = [[custom:napalm_koda]], fireStarter = 250, fixedlauncher = true, flightTime = 1.8, impulseBoost = 0, impulseFactor = 0.1, interceptedByShieldType = 2, model = [[wep_m_hailstorm.s3o]], projectiles = 2, range = 460, reloadtime = 20, smokedelay = [[0.1]], smokeTrail = true, soundHit = [[weapon/missile/rapid_rocket_hit]], soundStart = [[weapon/missile/rapid_rocket_fire]], soundwater = [[SplsSml]], sprayAngle = 8000, startsmoke = [[1]], startVelocity = 200, tolerance = 6500, tracks = false, trajectoryHeight = 0.18, turnRate = 3000, turret = true, weaponAcceleration = 100, weaponTimer = 1.8, weaponType = [[MissileLauncher]], weaponVelocity = 800, wobble = 8000, }, }, featureDefs = { DEAD = { description = [[Wreckage - Dante]], blocking = true, category = [[corpses]], damage = 11000, energy = 0, featureDead = [[HEAP]], featurereclamate = [[SMUDGE01]], footprintX = 3, footprintZ = 3, height = [[40]], hitdensity = [[100]], metal = 1400, object = [[dante_dead.s3o]], reclaimable = true, reclaimTime = 1400, world = [[All Worlds]], }, HEAP = { description = [[Debris - Dante]], blocking = false, category = [[heaps]], damage = 11000, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 4, footprintZ = 4, hitdensity = [[100]], metal = 700, object = [[debris4x4c.s3o]], reclaimable = true, reclaimTime = 700, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ dante = unitDef })
gpl-2.0
KlonZK/Zero-K
LuaUI/i18nlib/spec/i18n_variants_spec.lua
21
2057
require 'spec.assert_same' local variants = require 'i18n.variants' describe("i18n.variants", function() it("is a table", function() assert_equal('table', type(variants)) end) describe(".ancestry", function() it("returns just the locale for simple locales", function() assert_same(variants.ancestry('en'), {'en'}) end) it("returns self and parents for composite locales", function() assert_same(variants.ancestry('en-US-texas'), {'en-US-texas', 'en-US', 'en'}) end) end) describe(".isParent", function() it("works as expected", function() assert_true(variants.isParent('en', 'en-US')) assert_false(variants.isParent('en-US', 'en')) assert_false(variants.isParent('en', 'fr')) assert_false(variants.isParent('en', 'english')) assert_false(variants.isParent('en', 'en')) end) end) describe(".root", function() it("returns just the locale for simple locales", function() assert_equal('en', variants.root('en')) end) it("returns the root for composite locales", function() assert_equal('en', variants.root('en-US')) end) end) describe(".fallbacks", function() describe("when given locales of the same ancestry", function() it("returns the locale ancestry if given exactly the same locale twice", function() assert_same(variants.fallbacks('en-US','en-US'), {'en-US', 'en'}) end) it("returns the locale ancestry if fallbackLocale is parent of locale", function() assert_same(variants.fallbacks('en-US','en'), {'en-US', 'en'}) end) it("returns the fallbackLocale ancestry if locale is parent of fallbackLocale", function() assert_same(variants.fallbacks('en','en-US'), {'en-US', 'en'}) end) end) describe("when given two different locales", function() it("returns the first locale first, followed by the fallback locale ancestry", function() assert_same(variants.fallbacks('fr-CA', 'en-US'), {'fr-CA', 'fr', 'en-US', 'en'}) end) end) end) end)
gpl-2.0
zzzaidddddd/zzaiddd
plugins/map.lua
1
1873
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ (@zzaiddd) : المطور ▀▄ ▄▀ ▀▄ ▄▀ (@zzzaiddd) : قناة ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_staticmap(area) local api = base_api .. "/staticmap?" -- Get a sense of scale local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local receiver = get_receiver(msg) local lat,lng,url = get_staticmap(matches[1]) -- Send the actual location, is a google maps link send_location(receiver, lat, lng, ok_cb, false) -- Send a picture of the map, which takes scale into account send_photo_from_url(receiver, url) -- Return a link to the google maps stuff is now not needed anymore return nil end return { description = "Get Man Location by Name", usage = "/خريطه (name) : get map and location", patterns = {"^خريطه (.*)$"}, run = run } end
gpl-2.0
caricatura/Healbot
HealBot/HealBot_Skins.lua
1
131598
local LSM = HealBot_Libs_LSM() --LibStub("LibSharedMedia-3.0") --local vResetSkinPrevSkin="" local frameScale = 1 local bheight= 20 local bWidth = 120 local pWidth = 120 local EnemyTargetBarSize=40 local bOutline = 1 local btextheight,btextheight2=10,10 local btextoutline,btextoutline2=1,1 local b,bar,icon,txt,pIcon,expire,count=nil,nil,nil,nil,nil,nil,nil,nil local Aux1,Aux2,Aux3,Aux4,Aux5,Aux6,Aux7,AuxBelow,AuxAbove,AuxLeft,AuxRight=nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil local AuxIdx={[1]={},[2]={},[3]={},[4]={},[5]={},[6]={},[7]={},[8]={},[9]={}} local icon1,expire1,count1,icon51,expire51,count51=nil,nil,nil,nil,nil,nil local barScale,h,hwidth,hheight,iScale,diScale,itScale,x,hcpct=nil,nil,nil,nil,nil,nil,nil,nil,nil local abtSize = {[0]=1,[1]=1,[2]=1,[3]=2,[4]=2,[5]=2,[6]=3,[7]=3,[8]=3,[9]=3,[10]=4,[11]=4,[12]=4,[13]=4,[14]=4,[15]=5} local auxWidth,auxHeight, auxTmp=0,0,0 local lIconWidth,rIconWidth,bIconHeight=0,0,0 local barOffsetV, barOffsetH, barOffsetH2=0,0,0 local maxIcons=0 local AuxOverlapOffset=0 local maxScale=0 local tBarsConcat={} local iAnchors={["ICON"]="", ["BUTTON"]="", ["DOUBLE"]="", ["RELATIVE"]="", ["TXTCOUNT"]="", ["TXTEXPIRE"]="", ["TXTEXPIREX"]=1, ["TXTCOUNTX"]=1} local tabconcat=table.concat local function HealBot_Skins_Concat(elements) return tabconcat(tBarsConcat,"",1,elements) end function HealBot_Skins_AdjustSpecialBarWidth(button) EnemyTargetBarSize=(Healbot_Config_Skins.Enemy[Healbot_Config_Skins.Current_Skin]["ENEMYTARGETSIZE"]/100) if HealBot_Panel_isSpecialUnit(button.unit)==1 then bWidth=bWidth*(1-EnemyTargetBarSize) bWidth=bWidth-(Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][button.frame]["CMARGIN"]+(bOutline*2)) if Healbot_Config_Skins.Enemy[Healbot_Config_Skins.Current_Skin]["DOUBLEWIDTH"] then bWidth=bWidth*2 end HealBot_Text_setEnemySizeWidth("EnemySizeWidth1", bWidth) else bWidth=bWidth*EnemyTargetBarSize if Healbot_Config_Skins.Enemy[Healbot_Config_Skins.Current_Skin]["DOUBLEWIDTH"] then bWidth=bWidth*2 end HealBot_Text_setEnemySizeWidth("EnemySizeWidth2", bWidth) HealBot_Action_SetBackSpecialWidth(10, bWidth) end end function HealBot_Skins_ResetSkinWidth(button) frameScale = Healbot_Config_Skins.Frame[Healbot_Config_Skins.Current_Skin][button.frame]["SCALE"] bWidth = ceil(Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][button.frame]["WIDTH"]*frameScale); bOutline = ceil(Healbot_Config_Skins.BarCol[Healbot_Config_Skins.Current_Skin][button.frame]["BOUT"]*frameScale); if HealBot_Panel_isSpecialUnit(button.unit)>0 then HealBot_Skins_AdjustSpecialBarWidth(button) end button.gref["Bar"]:SetWidth(bWidth) button.gref["Back"]:SetWidth(bWidth+(bOutline*2)) button.gref["InHeal"]:SetWidth(bWidth) button.gref["Absorb"]:SetWidth(bWidth) button:SetWidth(bWidth) for x=1,9 do button.gref.aux[x]:SetWidth(ceil(bWidth*Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["SIZE"])) end end function HealBot_Skins_setIconAnchors(onBar, position, extra) if extra then if onBar==1 then if position==1 then iAnchors["ICON"]="LEFT"; iAnchors["BUTTON"]="LEFT"; elseif position==2 then iAnchors["ICON"]="RIGHT"; iAnchors["BUTTON"]="RIGHT"; elseif position==3 then iAnchors["ICON"]="TOP"; iAnchors["BUTTON"]="TOP"; elseif position==4 then iAnchors["ICON"]="BOTTOM"; iAnchors["BUTTON"]="BOTTOM"; elseif position==5 then iAnchors["ICON"]="TOPLEFT"; iAnchors["BUTTON"]="TOPLEFT"; elseif position==6 then iAnchors["ICON"]="TOPRIGHT"; iAnchors["BUTTON"]="TOPRIGHT"; elseif position==7 then iAnchors["ICON"]="BOTTOMLEFT"; iAnchors["BUTTON"]="BOTTOMLEFT"; else iAnchors["ICON"]="BOTTOMRIGHT"; iAnchors["BUTTON"]="BOTTOMRIGHT"; end elseif onBar==2 then if position==1 then iAnchors["ICON"]="RIGHT"; iAnchors["BUTTON"]="LEFT"; else iAnchors["ICON"]="LEFT"; iAnchors["BUTTON"]="RIGHT"; end else if position==1 then iAnchors["ICON"]="TOPLEFT"; iAnchors["BUTTON"]="BOTTOMLEFT"; elseif position==2 then iAnchors["ICON"]="TOPRIGHT"; iAnchors["BUTTON"]="BOTTOMRIGHT"; else iAnchors["ICON"]="TOP"; iAnchors["BUTTON"]="BOTTOM"; end end elseif onBar==1 then if position==1 then iAnchors["ICON"]="BOTTOMLEFT"; iAnchors["BUTTON"]="BOTTOMLEFT"; iAnchors["DOUBLE"]="TOPLEFT"; iAnchors["RELATIVE"]="BOTTOMRIGHT"; iAnchors["TXTCOUNT"]="TOPRIGHT"; iAnchors["TXTEXPIRE"]="BOTTOMLEFT"; iAnchors["TXTEXPIREX"]=-2; iAnchors["TXTCOUNTX"]=2 elseif position==2 then iAnchors["ICON"]="BOTTOMRIGHT"; iAnchors["BUTTON"]="BOTTOMRIGHT"; iAnchors["DOUBLE"]="TOPRIGHT"; iAnchors["RELATIVE"]="BOTTOMLEFT"; iAnchors["TXTCOUNT"]="TOPLEFT"; iAnchors["TXTEXPIRE"]="BOTTOMRIGHT"; iAnchors["TXTEXPIREX"]=2; iAnchors["TXTCOUNTX"]=-1 elseif position==3 then iAnchors["ICON"]="TOPLEFT"; iAnchors["BUTTON"]="TOPLEFT"; iAnchors["DOUBLE"]="BOTTOMLEFT"; iAnchors["RELATIVE"]="TOPRIGHT"; iAnchors["TXTCOUNT"]="TOPRIGHT"; iAnchors["TXTEXPIRE"]="BOTTOMLEFT"; iAnchors["TXTEXPIREX"]=-2; iAnchors["TXTCOUNTX"]=2 elseif position==4 then iAnchors["ICON"]="TOPRIGHT"; iAnchors["BUTTON"]="TOPRIGHT"; iAnchors["DOUBLE"]="BOTTOMRIGHT"; iAnchors["RELATIVE"]="TOPLEFT"; iAnchors["TXTCOUNT"]="TOPLEFT"; iAnchors["TXTEXPIRE"]="BOTTOMRIGHT"; iAnchors["TXTEXPIREX"]=2; iAnchors["TXTCOUNTX"]=-1 elseif position==5 then iAnchors["ICON"]="BOTTOMRIGHT"; iAnchors["BUTTON"]="BOTTOM"; iAnchors["DOUBLE"]="TOPRIGHT"; iAnchors["RELATIVE"]="BOTTOMLEFT"; iAnchors["TXTCOUNT"]="TOPLEFT"; iAnchors["TXTEXPIRE"]="BOTTOMRIGHT"; iAnchors["TXTEXPIREX"]=2; iAnchors["TXTCOUNTX"]=-1 elseif position==6 then iAnchors["ICON"]="BOTTOMLEFT"; iAnchors["BUTTON"]="BOTTOM"; iAnchors["DOUBLE"]="TOPLEFT"; iAnchors["RELATIVE"]="BOTTOMRIGHT"; iAnchors["TXTCOUNT"]="TOPRIGHT"; iAnchors["TXTEXPIRE"]="BOTTOMLEFT"; iAnchors["TXTEXPIREX"]=-2; iAnchors["TXTCOUNTX"]=2 elseif position==7 then iAnchors["ICON"]="TOPRIGHT"; iAnchors["BUTTON"]="TOP"; iAnchors["DOUBLE"]="BOTTOMRIGHT"; iAnchors["RELATIVE"]="TOPLEFT"; iAnchors["TXTCOUNT"]="TOPLEFT"; iAnchors["TXTEXPIRE"]="BOTTOMRIGHT"; iAnchors["TXTEXPIREX"]=2; iAnchors["TXTCOUNTX"]=-1 else iAnchors["ICON"]="TOPLEFT"; iAnchors["BUTTON"]="TOP"; iAnchors["DOUBLE"]="BOTTOMLEFT"; iAnchors["RELATIVE"]="TOPRIGHT"; iAnchors["TXTCOUNT"]="TOPRIGHT"; iAnchors["TXTEXPIRE"]="BOTTOMLEFT"; iAnchors["TXTEXPIREX"]=-2; iAnchors["TXTCOUNTX"]=2 end elseif onBar==2 then if position==1 then iAnchors["ICON"]="BOTTOMRIGHT"; iAnchors["BUTTON"]="BOTTOMLEFT"; iAnchors["DOUBLE"]="TOPRIGHT"; iAnchors["RELATIVE"]="BOTTOMLEFT"; iAnchors["TXTCOUNT"]="TOPLEFT"; iAnchors["TXTEXPIRE"]="BOTTOMRIGHT"; iAnchors["TXTEXPIREX"]=2; iAnchors["TXTCOUNTX"]=-1 elseif position==2 then iAnchors["ICON"]="BOTTOMLEFT"; iAnchors["BUTTON"]="BOTTOMRIGHT"; iAnchors["DOUBLE"]="TOPLEFT"; iAnchors["RELATIVE"]="BOTTOMRIGHT"; iAnchors["TXTCOUNT"]="TOPRIGHT"; iAnchors["TXTEXPIRE"]="BOTTOMLEFT"; iAnchors["TXTEXPIREX"]=-2; iAnchors["TXTCOUNTX"]=2 elseif position==3 then iAnchors["ICON"]="TOPRIGHT"; iAnchors["BUTTON"]="TOPLEFT"; iAnchors["DOUBLE"]="BOTTOMRIGHT"; iAnchors["RELATIVE"]="TOPLEFT"; iAnchors["TXTCOUNT"]="TOPLEFT"; iAnchors["TXTEXPIRE"]="BOTTOMRIGHT"; iAnchors["TXTEXPIREX"]=2; iAnchors["TXTCOUNTX"]=-1 else iAnchors["ICON"]="TOPLEFT"; iAnchors["BUTTON"]="TOPRIGHT"; iAnchors["DOUBLE"]="BOTTOMLEFT"; iAnchors["RELATIVE"]="TOPRIGHT"; iAnchors["TXTCOUNT"]="TOPRIGHT"; iAnchors["TXTEXPIRE"]="BOTTOMLEFT"; iAnchors["TXTEXPIREX"]=-2; iAnchors["TXTCOUNTX"]=2 end else if position==1 then iAnchors["ICON"]="TOPLEFT"; iAnchors["BUTTON"]="BOTTOMLEFT"; iAnchors["DOUBLE"]="BOTTOMLEFT"; iAnchors["RELATIVE"]="TOPRIGHT"; iAnchors["TXTCOUNT"]="TOPRIGHT"; iAnchors["TXTEXPIRE"]="BOTTOMLEFT"; iAnchors["TXTEXPIREX"]=-2; iAnchors["TXTCOUNTX"]=2 else iAnchors["ICON"]="TOPRIGHT"; iAnchors["BUTTON"]="BOTTOMRIGHT"; iAnchors["DOUBLE"]="BOTTOMRIGHT"; iAnchors["RELATIVE"]="TOPLEFT"; iAnchors["TXTCOUNT"]="TOPLEFT"; iAnchors["TXTEXPIRE"]="BOTTOMRIGHT"; iAnchors["TXTEXPIREX"]=2; iAnchors["TXTCOUNTX"]=-1 end end end function HealBot_Skins_ResetSkin(barType,button,numcols) if button and button.frame then frameScale = Healbot_Config_Skins.Frame[Healbot_Config_Skins.Current_Skin][button.frame]["SCALE"] bheight= ceil(Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][button.frame]["HEIGHT"]*frameScale); bWidth = ceil(Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][button.frame]["WIDTH"]*frameScale); bOutline = ceil(Healbot_Config_Skins.BarCol[Healbot_Config_Skins.Current_Skin][button.frame]["BOUT"]*frameScale); btextheight=ceil(Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][button.frame]["HEIGHT"]*frameScale); btextheight2=ceil(Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][button.frame]["HHEIGHT"]*frameScale) btextoutline=Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][button.frame]["OUTLINE"]; btextoutline2=Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][button.frame]["HOUTLINE"] end if barType=="bar" then auxHeight=0 auxWidth=0 lIconWidth=0 rIconWidth=0 bIconHeight=0 barOffsetH2=0 barOffsetV=bOutline barOffsetH=bOutline b=button if b.skinreset then for x=1,9 do if Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]>1 then if Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["ANCHOR"]<3 then if Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["ANCHOR"]==1 then auxTmp=Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["DEPTH"]+Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["OFFSET"] if auxTmp<0 then auxTmp=0 end barOffsetV=barOffsetV+auxTmp end auxTmp=auxHeight auxHeight=auxHeight+Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["DEPTH"] auxHeight=auxHeight+Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["OFFSET"] if auxHeight<auxTmp then auxHeight=auxTmp end else if Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["ANCHOR"]==3 then auxTmp=Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["DEPTH"]+barOffsetH+Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["OFFSET"] if auxTmp<0 then auxTmp=0 end barOffsetH=auxTmp--barOffsetH+auxTmp else auxTmp=Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["DEPTH"]+barOffsetH+Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["OFFSET"] if auxTmp<0 then auxTmp=0 end barOffsetH2=auxTmp end auxTmp=auxWidth auxWidth=auxWidth+Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["DEPTH"] auxWidth=auxWidth+Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["OFFSET"] if auxWidth<auxTmp then auxWidth=auxTmp end end end end auxHeight=ceil(auxHeight*frameScale) auxWidth=ceil(auxWidth*frameScale) maxScale=0 if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["BUFFONBAR"]>1 then if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["MAXBICONS"]>0 then maxIcons=Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["MAXBICONS"] elseif Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SHOWRC"] and Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["RCANCHOR"]==2 then maxIcons=1 else maxIcons=0 end if Healbot_Config_Skins.RaidIcon[Healbot_Config_Skins.Current_Skin][button.frame]["SHOW"] and Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["TARGETANCHOR"]==2 then maxIcons=maxIcons+1 end if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SHOWCLASS"] and Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["CLASSANCHOR"]==2 then maxIcons=maxIcons+1 end if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SHOWDIR"] and Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["OORANCHOR"]==2 then maxIcons=maxIcons+1 end if maxIcons>12 then maxIcons=12 end if maxIcons>0 then if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["BUFFONBAR"]==2 then if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["BUFFANCHOR"]==1 or Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["BUFFANCHOR"]==3 then if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["BUFFDOUBLE"] then lIconWidth=lIconWidth+floor((floor(bheight* Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SCALE"])/2)*ceil(maxIcons/2)) else lIconWidth=lIconWidth+floor((bheight* Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SCALE"])*maxIcons) end else if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["BUFFDOUBLE"] then rIconWidth=rIconWidth+floor((floor(bheight* Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SCALE"])/2)*ceil(maxIcons/2)) else rIconWidth=rIconWidth+floor((bheight* Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SCALE"])*maxIcons) end end else maxScale=Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SCALE"] end end end if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DEBUFFONBAR"]>1 then if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["MAXDICONS"]>0 then maxIcons=Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["MAXDICONS"] elseif Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SHOWRC"] and Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["RCANCHOR"]==1 then maxIcons=1 else maxIcons=0 end if Healbot_Config_Skins.RaidIcon[Healbot_Config_Skins.Current_Skin][button.frame]["SHOW"] and Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["TARGETANCHOR"]==1 then maxIcons=maxIcons+1 end if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SHOWCLASS"] and Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["CLASSANCHOR"]==1 then maxIcons=maxIcons+1 end if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["SHOWDIR"] and Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["OORANCHOR"]==1 then maxIcons=maxIcons+1 end if maxIcons>8 then maxIcons=8 end if maxIcons>0 then if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DEBUFFONBAR"]==2 then if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DEBUFFANCHOR"]==1 or Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DEBUFFANCHOR"]==3 then if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DEBUFFDOUBLE"] then lIconWidth=lIconWidth+floor((floor(bheight* Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DSCALE"])/2)*ceil(maxIcons/2)) else lIconWidth=lIconWidth+floor((bheight* Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DSCALE"])*maxIcons) end else if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DEBUFFDOUBLE"] then rIconWidth=rIconWidth+floor((floor(bheight* Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DSCALE"])/2)*ceil(maxIcons/2)) else rIconWidth=rIconWidth+floor((bheight* Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DSCALE"])*maxIcons) end end elseif Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DSCALE"]>maxScale then maxScale=Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][button.frame]["DSCALE"] end end end if maxScale>0 then bIconHeight=bIconHeight+floor(bheight*maxScale) bIconHeight=ceil(bIconHeight*frameScale) end pWidth=bWidth if HealBot_Panel_isSpecialUnit(button.unit)>0 then HealBot_Skins_AdjustSpecialBarWidth(button) if Healbot_Config_Skins.Enemy[Healbot_Config_Skins.Current_Skin]["DOUBLEWIDTH"] then pWidth=pWidth*(2-(pWidth/7800)) end end HealBot_Action_SetBackBarHeightWidth(button.frame, (bheight+auxHeight+bIconHeight+(bOutline*2)), (pWidth+auxWidth+lIconWidth+rIconWidth+(bOutline*2))) b.gref["Bar"]:SetHeight(bheight); b.gref["Bar"]:SetWidth(bWidth) b.gref["Back"]:SetHeight(bheight+auxHeight+bIconHeight+(bOutline*2)) b.gref["Back"]:SetWidth(bWidth+auxWidth+lIconWidth+rIconWidth+(bOutline*2)) b.gref["InHeal"]:SetHeight(bheight); b.gref["InHeal"]:SetWidth(bWidth) b.gref["Absorb"]:SetHeight(bheight); b.gref["Absorb"]:SetWidth(bWidth) if Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][b.frame]["OFIX"]==1 then b.gref["Bar"]:SetOrientation("HORIZONTAL"); b.gref["InHeal"]:SetOrientation("HORIZONTAL"); b.gref["Back"]:SetOrientation("HORIZONTAL"); b.gref["Absorb"]:SetOrientation("HORIZONTAL"); else b.gref["Bar"]:SetOrientation("VERTICAL"); b.gref["InHeal"]:SetOrientation("VERTICAL"); b.gref["Back"]:SetOrientation("VERTICAL"); b.gref["Absorb"]:SetOrientation("VERTICAL"); end tBarsConcat[1]="f" tBarsConcat[2]=b.frame tBarsConcat[3]="_HealBot_Action" local gaf = _G[HealBot_Skins_Concat(3)] b:SetFrameLevel(gaf:GetFrameLevel()+ 1); b.gref["Back"]:SetFrameLevel(b:GetFrameLevel()+ 1); -- Background b.gref["Absorb"]:SetFrameLevel(button.gref["Back"]:GetFrameLevel()+ 1); -- Absorbs b.gref["InHeal"]:SetFrameLevel(b.gref["Absorb"]:GetFrameLevel()+ 1); -- Incoming Heal b.gref["Bar"]:SetFrameLevel(b.gref["InHeal"]:GetFrameLevel()+ 1); -- Health -- b.gref["Bar"]:SetTexture(LSM:Fetch('statusbar',Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][b.frame]["TEXTURE"]),false); b.gref["Bar"]:SetStatusBarTexture(LSM:Fetch('statusbar',Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][b.frame]["TEXTURE"])); b.gref["Bar"]:GetStatusBarTexture():SetHorizTile(false) b.gref["Bar"]:ClearAllPoints() b.gref["Bar"]:SetPoint("BOTTOMLEFT",b.gref["Back"],"BOTTOMLEFT",barOffsetH+lIconWidth,barOffsetV+bIconHeight) b.gref.txt["text"]:SetFont(LSM:Fetch('font',Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["FONT"]), btextheight, HealBot_Font_Outline[btextoutline]); b.gref.txt["text2"]:SetFont(LSM:Fetch('font',Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HFONT"]), btextheight2, HealBot_Font_Outline[btextoutline2]); for x=1,9 do b.gref.auxtxt[x]:SetFont(LSM:Fetch('font',Healbot_Config_Skins.AuxBarText[Healbot_Config_Skins.Current_Skin][b.frame]["FONT"]), ceil(Healbot_Config_Skins.AuxBarText[Healbot_Config_Skins.Current_Skin][b.frame]["HEIGHT"]*frameScale), HealBot_Font_Outline[Healbot_Config_Skins.AuxBarText[Healbot_Config_Skins.Current_Skin][b.frame]["OUTLINE"]]); b.gref.auxtxt[x]:ClearAllPoints(); if Healbot_Config_Skins.AuxBarText[Healbot_Config_Skins.Current_Skin][b.frame]["ALIGN"]==1 then b.gref.auxtxt[x]:SetPoint("LEFT",b.gref.aux[x],"LEFT",4,0+Healbot_Config_Skins.AuxBarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) elseif Healbot_Config_Skins.AuxBarText[Healbot_Config_Skins.Current_Skin][b.frame]["ALIGN"]==2 then b.gref.auxtxt[x]:SetPoint("CENTER",b.gref.aux[x],"CENTER",0,0+Healbot_Config_Skins.AuxBarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) else b.gref.auxtxt[x]:SetPoint("RIGHT",b.gref.aux[x],"RIGHT",-4,0+Healbot_Config_Skins.AuxBarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) end end b.gref.txt["text"]:ClearAllPoints(); b.gref.txt["text2"]:ClearAllPoints(); b.gref["Back"]:SetStatusBarTexture(LSM:Fetch('statusbar',Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][b.frame]["TEXTURE"])); b.gref["Back"]:GetStatusBarTexture():SetHorizTile(false) b.gref["Absorb"]:SetStatusBarTexture(LSM:Fetch('statusbar',Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][b.frame]["TEXTURE"])); b.gref["Absorb"]:GetStatusBarTexture():SetHorizTile(false) if Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["ALIGN"]==1 then if Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==3 then b.gref.txt["text2"]:SetPoint("LEFT",b.gref["Bar"],"LEFT",4+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET2"],5+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET"]) b.gref.txt["text"]:SetPoint("LEFT",b.gref.txt["text2"],"RIGHT",4,Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) elseif Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==2 then b.gref.txt["text"]:SetPoint("LEFT",b.gref["Bar"],"LEFT",4+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET2"],5+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) else b.gref.txt["text"]:SetPoint("LEFT",b.gref["Bar"],"LEFT",4,5+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) end elseif Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["ALIGN"]==2 then if Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==2 then b.gref.txt["text"]:SetPoint("RIGHT",b.gref["Bar"],"CENTER",0+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET2"],5+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) elseif Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==3 then b.gref.txt["text"]:SetPoint("LEFT",b.gref["Bar"],"CENTER",0+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET2"],5+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) else b.gref.txt["text"]:SetPoint("CENTER",b.gref["Bar"],"CENTER",0,5+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) end else if Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==2 then b.gref.txt["text2"]:SetPoint("RIGHT",b.gref["Bar"],"RIGHT",-4+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET2"],5+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET"]) b.gref.txt["text"]:SetPoint("RIGHT",b.gref.txt["text2"],"LEFT",-4,Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) elseif Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==3 then b.gref.txt["text"]:SetPoint("RIGHT",b.gref["Bar"],"RIGHT",-4+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET2"],5+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) else b.gref.txt["text"]:SetPoint("RIGHT",b.gref["Bar"],"RIGHT",-4,5+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["OFFSET"]) end end if Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==1 then if Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HALIGN"]==1 then b.gref.txt["text2"]:SetPoint("LEFT",b.gref["Bar"],"LEFT",4,-7+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET"]) elseif Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HALIGN"]==2 then b.gref.txt["text2"]:SetPoint("CENTER",b.gref["Bar"],"CENTER",0,-7+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET"]) else b.gref.txt["text2"]:SetPoint("RIGHT",b.gref["Bar"],"RIGHT",-4,-7+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET"]) end elseif Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==2 and Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["ALIGN"]<3 then b.gref.txt["text2"]:SetPoint("LEFT",b.gref.txt["text"],"RIGHT",4,Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET"]) elseif Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==3 and Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["ALIGN"]>1 then b.gref.txt["text2"]:SetPoint("RIGHT",b.gref.txt["text"],"LEFT",-4,Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET"]) elseif Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==4 then b.gref.txt["text2"]:SetPoint("TOP",b.gref.txt["text"],"BOTTOM",0+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET2"],-2+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET"]) elseif Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HLTHTXTANCHOR"]==5 then b.gref.txt["text2"]:SetPoint("BOTTOM",b.gref.txt["text"],"TOP",0+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET2"],2+Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][b.frame]["HOFFSET"]) end b.gref["InHeal"]:SetStatusBarTexture(LSM:Fetch('statusbar',Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][b.frame]["TEXTURE"])); b.gref["InHeal"]:GetStatusBarTexture():SetHorizTile(false) b:SetHeight(bheight); b:SetWidth(bWidth) AuxBelow,AuxAbove,AuxLeft,AuxRight=b.gref["Bar"],b.gref["Bar"],b.gref["Bar"],b.gref["Bar"] AuxOverlapOffset=0 for x=1,9 do if Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]>1 then b.gref.aux[x]:ClearAllPoints() if Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["ANCHOR"]<3 then b.gref.aux[x]:SetOrientation("HORIZONTAL") if Healbot_Config_Skins.AuxBarFrame[Healbot_Config_Skins.Current_Skin][button.frame]["OVERLAP"]==2 then b.gref.aux[x]:SetWidth(ceil((bWidth+auxWidth)*Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["SIZE"])) AuxOverlapOffset=ceil((bWidth+auxWidth)*(1-Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["SIZE"]))/2 else b.gref.aux[x]:SetWidth(ceil(bWidth*Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["SIZE"])) end b.gref.aux[x]:SetHeight(Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["DEPTH"]) if Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["ANCHOR"]==1 then b.gref.aux[x]:SetPoint("TOP",AuxBelow,"BOTTOM",0,0-Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["OFFSET"]) AuxBelow=b.gref.aux[x] else b.gref.aux[x]:SetPoint("BOTTOM",AuxAbove,"TOP",0,Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["OFFSET"]) AuxAbove=b.gref.aux[x] end if Healbot_Config_Skins.AuxBarFrame[Healbot_Config_Skins.Current_Skin][button.frame]["OVERLAP"]==2 then b.gref.aux[x]:SetPoint("RIGHT",b.gref["Back"],"RIGHT",-(bOutline+AuxOverlapOffset),0) end else b.gref.aux[x]:SetOrientation("VERTICAL") b.gref.aux[x]:SetWidth(Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["DEPTH"]) if Healbot_Config_Skins.AuxBarFrame[Healbot_Config_Skins.Current_Skin][button.frame]["OVERLAP"]==1 then b.gref.aux[x]:SetHeight(ceil((bheight+auxHeight)*Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["SIZE"])) b.gref.aux[x]:SetPoint("TOP",b.gref["Back"],"TOP",0,-(bOutline+1)) else b.gref.aux[x]:SetHeight(ceil(bheight*Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["SIZE"])) end if Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["ANCHOR"]==3 then b.gref.aux[x]:SetPoint("RIGHT",AuxLeft,"LEFT",0-Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["OFFSET"],0) AuxLeft=b.gref.aux[x] else b.gref.aux[x]:SetPoint("LEFT",AuxRight,"RIGHT",Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["OFFSET"],0) AuxRight=b.gref.aux[x] end end if HealBot_retLuVars("TestBarsOn") then b.gref.aux[x]:SetValue(1000) if Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]==2 then b.gref.aux[x]:SetStatusBarColor(0.8,1,0.8,1) elseif Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]==3 then b.gref.aux[x]:SetStatusBarColor(0.7,0.9,0.7,1) elseif Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]==4 then b.gref.aux[x]:SetStatusBarColor(0.8,0.8,0.9,1) elseif Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]==5 then b.gref.aux[x]:SetStatusBarColor(1,0,0,1) elseif Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]==6 then b.gref.aux[x]:SetStatusBarColor(1,1,0,1) elseif Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]==7 then b.gref.aux[x]:SetStatusBarColor(0.5,0.7,0.5,1) elseif Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]==8 then b.gref.aux[x]:SetStatusBarColor(0.5,0.5,1,1) elseif Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]==9 then b.gref.aux[x]:SetStatusBarColor(1,1,1,1) elseif Healbot_Config_Skins.AuxBar[Healbot_Config_Skins.Current_Skin][x][button.frame]["USE"]==10 then b.gref.aux[x]:SetStatusBarColor(0.2,0.2,1,1) end end b.gref.aux[x]:SetFrameLevel(b.gref["Back"]:GetFrameLevel()+ 1) b.gref.aux[x]:SetStatusBarTexture(LSM:Fetch('statusbar',Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][b.frame]["TEXTURE"])) b.gref.aux[x]:GetStatusBarTexture():SetHorizTile(false) else b.gref.aux[x]:SetStatusBarColor(0,0,0,0) end end b.skinreset=false end if b.icon.reset then iScale=(bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["SCALE"])-2 if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFDOUBLE"] then iScale=floor(((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["SCALE"])-2)*0.485) end for x=1,12 do b.gref.icon[x]:SetHeight(iScale); b.gref.icon[x]:SetWidth(iScale); b.gref.txt.expire[x]:SetFont(LSM:Fetch('font',Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFFONT"]), Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFHEIGHT"], HealBot_Font_Outline[Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFOUTLINE"]]); b.gref.txt.count[x]:SetFont(LSM:Fetch('font',Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFFONT"]), Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFHEIGHT"], HealBot_Font_Outline[Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFOUTLINE"]]); end if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["DEBUFFDOUBLE"] then diScale=floor(((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["DSCALE"])-2)*0.485) else diScale=(bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["DSCALE"])-2 end for x=51,58 do b.gref.icon[x]:SetHeight(diScale); b.gref.icon[x]:SetWidth(diScale); b.gref.txt.expire[x]:SetFont(LSM:Fetch('font',Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["FONT"]), Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["HEIGHT"], HealBot_Font_Outline[Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["OUTLINE"]]); b.gref.txt.count[x]:SetFont(LSM:Fetch('font',Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["FONT"]), Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["HEIGHT"], HealBot_Font_Outline[Healbot_Config_Skins.IconText[Healbot_Config_Skins.Current_Skin][b.frame]["OUTLINE"]]); end button.gref.indicator.aggro["Iconal1"]:SetAlpha(0) button.gref.indicator.aggro["Iconal2"]:SetAlpha(0) button.gref.indicator.aggro["Iconal3"]:SetAlpha(0) button.gref.indicator.aggro["Iconar1"]:SetAlpha(0) button.gref.indicator.aggro["Iconar2"]:SetAlpha(0) button.gref.indicator.aggro["Iconar3"]:SetAlpha(0) button.gref.indicator.mana[1]:SetAlpha(0) button.gref.indicator.mana[2]:SetAlpha(0) button.gref.indicator.mana[3]:SetAlpha(0) for x=1,5 do button.gref.indicator.power[x]:SetAlpha(0); end if HealBot_Action_retLuVars("UnitPowerMax")==3 then button.gref.indicator.power[1]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","-9","1"); button.gref.indicator.power[2]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","0","1"); button.gref.indicator.power[3]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","9","1"); elseif HealBot_Action_retLuVars("UnitPowerMax")==4 then button.gref.indicator.power[1]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","-12","1"); button.gref.indicator.power[2]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","-4","1"); button.gref.indicator.power[3]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","4","1"); button.gref.indicator.power[4]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","12","1"); else button.gref.indicator.power[1]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","-14","1"); button.gref.indicator.power[2]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","-7","1"); button.gref.indicator.power[3]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","0","1"); button.gref.indicator.power[4]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","7","1"); button.gref.indicator.power[5]:SetPoint("BOTTOM",button.gref["Bar"],"BOTTOM","14","1"); end HealBot_Skins_setIconAnchors(Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFONBAR"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFANCHOR"]) b.gref.icon[1]:ClearAllPoints(); b.gref.icon[1]:SetPoint(iAnchors["ICON"],b,iAnchors["BUTTON"],0,0); b.gref.txt.expire[1]:ClearAllPoints() b.gref.txt.expire[1]:SetPoint(iAnchors["TXTEXPIRE"],b.gref.icon[1],iAnchors["TXTEXPIRE"],iAnchors["TXTEXPIREX"],0) b.gref.txt.count[1]:ClearAllPoints() b.gref.txt.count[1]:SetPoint(iAnchors["TXTCOUNT"],b.gref.icon[1],iAnchors["TXTCOUNT"],iAnchors["TXTCOUNTX"],0) for x=2,12 do b.gref.icon[x]:ClearAllPoints() if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["BUFFDOUBLE"] then if (x/2)==floor(x/2) then b.gref.icon[x]:SetPoint(iAnchors["ICON"],b.gref.icon[x-1],iAnchors["DOUBLE"],0,0) else b.gref.icon[x]:SetPoint(iAnchors["ICON"],b.gref.icon[x-2],iAnchors["RELATIVE"],0,0) end else b.gref.icon[x]:SetPoint(iAnchors["ICON"],b.gref.icon[x-1],iAnchors["RELATIVE"],0,0) end b.gref.txt.expire[x]:ClearAllPoints() b.gref.txt.expire[x]:SetPoint(iAnchors["TXTEXPIRE"],b.gref.icon[x],iAnchors["TXTEXPIRE"],iAnchors["TXTEXPIREX"],0) b.gref.txt.count[x]:ClearAllPoints() b.gref.txt.count[x]:SetPoint(iAnchors["TXTCOUNT"],b.gref.icon[x],iAnchors["TXTCOUNT"],iAnchors["TXTCOUNTX"],0) end HealBot_Skins_setIconAnchors(Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["DEBUFFONBAR"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["DEBUFFANCHOR"]) b.gref.icon[51]:ClearAllPoints() b.gref.icon[51]:SetPoint(iAnchors["ICON"],b,iAnchors["BUTTON"],0,0) b.gref.txt.expire[51]:ClearAllPoints() b.gref.txt.expire[51]:SetPoint(iAnchors["TXTEXPIRE"],b.gref.icon[51],iAnchors["TXTEXPIRE"],iAnchors["TXTEXPIREX"],0) b.gref.txt.count[51]:ClearAllPoints() b.gref.txt.count[51]:SetPoint(iAnchors["TXTCOUNT"],b.gref.icon[51],iAnchors["TXTCOUNT"],iAnchors["TXTCOUNTX"],0) for x=52,58 do b.gref.icon[x]:ClearAllPoints() if Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["DEBUFFDOUBLE"] then if (x/2)==floor(x/2) then b.gref.icon[x]:SetPoint(iAnchors["ICON"],b.gref.icon[x-1],iAnchors["DOUBLE"],0,0) else b.gref.icon[x]:SetPoint(iAnchors["ICON"],b.gref.icon[x-2],iAnchors["RELATIVE"],0,0) end else b.gref.icon[x]:SetPoint(iAnchors["ICON"],b.gref.icon[x-1],iAnchors["RELATIVE"],0,0) end b.gref.txt.expire[x]:ClearAllPoints() b.gref.txt.expire[x]:SetPoint(iAnchors["TXTEXPIRE"],b.gref.icon[x],iAnchors["TXTEXPIRE"],iAnchors["TXTEXPIREX"],0) b.gref.txt.count[x]:ClearAllPoints() b.gref.txt.count[x]:SetPoint(iAnchors["TXTCOUNT"],b.gref.icon[x],iAnchors["TXTCOUNT"],iAnchors["TXTCOUNTX"],0) end -- Class/Role 91 HealBot_Skins_setIconAnchors(Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["CLASSONBAR"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["CLASSANCHOR"], true) b.gref.icon[91]:ClearAllPoints() b.gref.icon[91]:SetPoint(iAnchors["ICON"],b,iAnchors["BUTTON"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["CLASSHOFFSET"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["CLASSVOFFSET"]) b.gref.icon[91]:SetHeight((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["CLASSSCALE"])-2) b.gref.icon[91]:SetWidth((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["CLASSSCALE"])-2) -- Raid Target 92 HealBot_Skins_setIconAnchors(Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["TARGETONBAR"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["TARGETANCHOR"], true) b.gref.icon[92]:ClearAllPoints() b.gref.icon[92]:SetPoint(iAnchors["ICON"],b,iAnchors["BUTTON"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["TARGETHOFFSET"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["TARGETVOFFSET"]) b.gref.icon[92]:SetHeight((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["TARGETSCALE"])-2) b.gref.icon[92]:SetWidth((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["TARGETSCALE"])-2) -- Ready Check 93 HealBot_Skins_setIconAnchors(Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["RCONBAR"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["RCANCHOR"], true) b.gref.icon[93]:ClearAllPoints() b.gref.icon[93]:SetPoint(iAnchors["ICON"],b,iAnchors["BUTTON"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["RCHOFFSET"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["RCVOFFSET"]) b.gref.icon[93]:SetHeight((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["RCSCALE"])-2) b.gref.icon[93]:SetWidth((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["RCSCALE"])-2) -- Out of range 94 HealBot_Skins_setIconAnchors(Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["OORONBAR"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["OORANCHOR"], true) b.gref.icon[94]:ClearAllPoints() b.gref.icon[94]:SetPoint(iAnchors["ICON"],b,iAnchors["BUTTON"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["OORHOFFSET"], Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["OORVOFFSET"]) b.gref.icon[94]:SetHeight((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["OORSCALE"])-2) b.gref.icon[94]:SetWidth((bheight*Healbot_Config_Skins.Icons[Healbot_Config_Skins.Current_Skin][b.frame]["OORSCALE"])-2) b.icon.reset=false end elseif barType=="header" then h=button bar = _G[h:GetName().."Bar"] local back = _G[h:GetName().."Bar5"] hwidth = ceil((bWidth+(bOutline*2))*Healbot_Config_Skins.HeadBar[Healbot_Config_Skins.Current_Skin][h.frame]["WIDTH"]) hheight = ceil(Healbot_Config_Skins.HeadBar[Healbot_Config_Skins.Current_Skin][h.frame]["HEIGHT"]*frameScale) h:SetHeight(hheight); h:SetWidth(hwidth); back:SetHeight(hheight) back:SetWidth(hwidth) HealBot_Action_SetBackHeaderHeightWidth(h.frame, hheight, hwidth) back:SetStatusBarColor(0,0,0,0) bar:SetStatusBarTexture(LSM:Fetch('statusbar',Healbot_Config_Skins.HeadBar[Healbot_Config_Skins.Current_Skin][h.frame]["TEXTURE"])); bar:GetStatusBarTexture():SetHorizTile(false) bar:SetMinMaxValues(0,100); bar:SetValue(100); bar:SetStatusBarColor(Healbot_Config_Skins.HeadBar[Healbot_Config_Skins.Current_Skin][h.frame]["R"], Healbot_Config_Skins.HeadBar[Healbot_Config_Skins.Current_Skin][h.frame]["G"], Healbot_Config_Skins.HeadBar[Healbot_Config_Skins.Current_Skin][h.frame]["B"], Healbot_Config_Skins.HeadBar[Healbot_Config_Skins.Current_Skin][h.frame]["A"]); bar:SetHeight(hheight); bar:SetWidth(hwidth); tBarsConcat[1]=bar:GetName() tBarsConcat[2]="_text" bar.txt = _G[HealBot_Skins_Concat(2)]; tBarsConcat[2]="_text2" bar.txt2 = _G[HealBot_Skins_Concat(2)]; bar.txt:SetFont(LSM:Fetch('font',Healbot_Config_Skins.HeadText[Healbot_Config_Skins.Current_Skin][h.frame]["FONT"]), Healbot_Config_Skins.HeadText[Healbot_Config_Skins.Current_Skin][h.frame]["HEIGHT"], HealBot_Font_Outline[Healbot_Config_Skins.HeadText[Healbot_Config_Skins.Current_Skin][h.frame]["OUTLINE"]]); bar.txt:SetTextColor(Healbot_Config_Skins.HeadText[Healbot_Config_Skins.Current_Skin][h.frame]["R"], Healbot_Config_Skins.HeadText[Healbot_Config_Skins.Current_Skin][h.frame]["G"], Healbot_Config_Skins.HeadText[Healbot_Config_Skins.Current_Skin][h.frame]["B"], Healbot_Config_Skins.HeadText[Healbot_Config_Skins.Current_Skin][h.frame]["A"]); bar.txt:SetPoint("CENTER",bar,"CENTER",0,Healbot_Config_Skins.HeadText[Healbot_Config_Skins.Current_Skin][h.frame]["OFFSET"]) bar:EnableMouse(false) bar.txt2:SetTextColor(0,0,0,0); bar:ClearAllPoints() bar:SetPoint("CENTER",back,"CENTER",0,0) h:Disable(); elseif barType=="frameheader" then tBarsConcat[1]="f" tBarsConcat[2]=numcols tBarsConcat[3]="_HealBot_Action" local g=_G[HealBot_Skins_Concat(3)] if g:IsVisible() and g:GetRight() and g:GetLeft() then HealBot_Action_setFrameHeader(numcols, frameScale) end elseif barType=="hbfocus" then tBarsConcat[1]="HealBot_Action_HealUnit" tBarsConcat[2]=button.id tBarsConcat[3]="Bar" bar = _G[HealBot_Skins_Concat(3)] bar:SetStatusBarTexture(LSM:Fetch('statusbar',Healbot_Config_Skins.HealBar[Healbot_Config_Skins.Current_Skin][button.frame]["TEXTURE"])); bar:GetStatusBarTexture():SetHorizTile(false) bar:SetStatusBarColor(1,1,1,1); tBarsConcat[1]=bar:GetName() tBarsConcat[2]="_text" bar.txt = _G[HealBot_Skins_Concat(2)]; tBarsConcat[2]="_text2" bar.txt2 = _G[HealBot_Skins_Concat(2)]; bar.txt:SetFont(LSM:Fetch('font',Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][button.frame]["FONT"]), btextheight, HealBot_Font_Outline[btextoutline]); bar.txt:SetTextColor(0,0,0,1); bar.txt2:SetFont(LSM:Fetch('font',Healbot_Config_Skins.BarText[Healbot_Config_Skins.Current_Skin][button.frame]["HFONT"]), btextheight2, HealBot_Font_Outline[btextoutline2]); bar.txt2:SetTextColor(0,0,0,1); iScale=0.84 iScale=iScale+(numcols/10) bar:SetWidth(bWidth*iScale) button:SetWidth(bWidth*iScale) bar:SetHeight(bheight); button:SetHeight(bheight); bar.txt:SetText(HEALBOT_ACTION_HBFOCUS) barScale = bar:GetScale(); bar:SetScale(barScale + 0.01); bar:SetScale(barScale); else HealBot_Panel_ResetHeaders() HealBot_setOptions_Timer(80) HealBot_setOptions_Timer(50) --if vResetSkinPrevSkin~=Healbot_Config_Skins.Current_Skin then -- vResetSkinPrevSkin=Healbot_Config_Skins.Current_Skin --HealBot_setOptions_Timer(800) --end end --HealBot_setCall("HealBot_Skins_ResetSkin") end function HealBot_Skins_Check_Skin(SkinName, fromImport) if Healbot_Config_Skins.ExtraIncGroup then Healbot_Config_Skins.ExtraIncGroup=nil end if Healbot_Config_Skins.BarsHide then Healbot_Config_Skins.BarsHide=nil end if Healbot_Config_Skins.EmergIncMonitor then Healbot_Config_Skins.EmergIncMonitor=nil end if Healbot_Config_Skins.IncludeGroup then Healbot_Config_Skins.IncludeGroup=nil end if not HealBot_Config.SkinDefault[SkinName] then HealBot_Config.SkinDefault[SkinName]={} end if Healbot_Config_Skins.General[SkinName]["STICKYSENSITIVITY"] then Healbot_Config_Skins.General[SkinName]["STICKYSENSITIVITY"]=nil end if HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_SOLO]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_SOLO]=false end if HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_PARTY]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_PARTY]=false end if HealBot_Config.SkinDefault[SkinName][HEALBOT_OPTIONS_RAID10]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_OPTIONS_RAID10]=false end if HealBot_Config.SkinDefault[SkinName][HEALBOT_OPTIONS_RAID25]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_OPTIONS_RAID25]=false end if HealBot_Config.SkinDefault[SkinName][HEALBOT_OPTIONS_RAID40]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_OPTIONS_RAID40]=false end if HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_ARENA]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_ARENA]=false end if HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_BG10]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_BG10]=false end if HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_BG15]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_BG15]=false end if HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_BG40]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_BG40]=false end if HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_PETBATTLE]==nil then HealBot_Config.SkinDefault[SkinName][HEALBOT_WORD_PETBATTLE]=false end if not Healbot_Config_Skins.HealGroups[SkinName] then Healbot_Config_Skins.HealGroups[SkinName]={ [1] = {["NAME"]=HEALBOT_OPTIONS_SELFHEALS_en,["STATE"]=false,["FRAME"]=1}, [2] = {["NAME"]=HEALBOT_OPTIONS_TANKHEALS_en,["STATE"]=true,["FRAME"]=1}, [3] = {["NAME"]=HEALBOT_CLASSES_HEALERS_en,["STATE"]=false,["FRAME"]=1}, [4] = {["NAME"]=HEALBOT_OPTIONS_GROUPHEALS_en,["STATE"]=true,["FRAME"]=1}, [5] = {["NAME"]=HEALBOT_OPTIONS_EMERGENCYHEALS_en,["STATE"]=true,["FRAME"]=1}, [6] = {["NAME"]=HEALBOT_OPTIONS_MYTARGET_en,["STATE"]=true,["FRAME"]=1}, [7] = {["NAME"]=HEALBOT_VEHICLE_en,["STATE"]=false,["FRAME"]=6}, [8] = {["NAME"]=HEALBOT_OPTIONS_PETHEALS_en,["STATE"]=false,["FRAME"]=7}, [9] = {["NAME"]=HEALBOT_OPTIONS_TARGETHEALS_en,["STATE"]=false,["FRAME"]=8}, [10] = {["NAME"]=HEALBOT_FOCUS_en,["STATE"]=false,["FRAME"]=9}, [11] = {["NAME"]=HEALBOT_CUSTOM_CASTBY_ENEMY_en,["STATE"]=false,["FRAME"]=10},} else for id=1,11 do if Healbot_Config_Skins.HealGroups[SkinName][id]["NAME"]=="Targets" then Healbot_Config_Skins.HealGroups[SkinName][id]["NAME"]=HEALBOT_OPTIONS_TARGETHEALS break end if Healbot_Config_Skins.HealGroups[SkinName][id]["NAME"]=="My Targets" then Healbot_Config_Skins.HealGroups[SkinName][id]["NAME"]=HEALBOT_OPTIONS_MYTARGET break end end local freeHealGroups={} table.insert(freeHealGroups,HEALBOT_OPTIONS_SELFHEALS_en) table.insert(freeHealGroups,HEALBOT_OPTIONS_TANKHEALS_en) table.insert(freeHealGroups,HEALBOT_CLASSES_HEALERS_en) table.insert(freeHealGroups,HEALBOT_OPTIONS_GROUPHEALS_en) table.insert(freeHealGroups,HEALBOT_OPTIONS_EMERGENCYHEALS_en) table.insert(freeHealGroups,HEALBOT_OPTIONS_MYTARGET_en) table.insert(freeHealGroups,HEALBOT_VEHICLE_en) table.insert(freeHealGroups,HEALBOT_OPTIONS_PETHEALS_en) table.insert(freeHealGroups,HEALBOT_OPTIONS_TARGETHEALS_en) table.insert(freeHealGroups,HEALBOT_FOCUS_en) table.insert(freeHealGroups,HEALBOT_CUSTOM_CASTBY_ENEMY_en) for gl=1,11 do if not Healbot_Config_Skins.HealGroups[SkinName][gl] then Healbot_Config_Skins.HealGroups[SkinName][gl]={} end if Healbot_Config_Skins.HealGroups[SkinName][gl]["NAME"] then local mti=0 for z=1, #freeHealGroups do if Healbot_Config_Skins.HealGroups[SkinName][gl]["NAME"]==freeHealGroups[z] then mti=z end end if mti>0 then table.remove(freeHealGroups,mti) end end end for gl=1,11 do if not Healbot_Config_Skins.HealGroups[SkinName][gl]["NAME"] then Healbot_Config_Skins.HealGroups[SkinName][gl]["NAME"]=freeHealGroups[1] table.remove(freeHealGroups,1) end if not Healbot_Config_Skins.HealGroups[SkinName][gl]["STATE"] then Healbot_Config_Skins.HealGroups[SkinName][gl]["STATE"]=false end if not Healbot_Config_Skins.HealGroups[SkinName][gl]["FRAME"] then if Healbot_Config_Skins.HealGroups[SkinName][gl]["NAME"]==HEALBOT_CUSTOM_CASTBY_ENEMY_en then Healbot_Config_Skins.HealGroups[SkinName][gl]["FRAME"]=10 elseif Healbot_Config_Skins.HealGroups[SkinName][gl]["NAME"]==HEALBOT_FOCUS_en then Healbot_Config_Skins.HealGroups[SkinName][gl]["FRAME"]=9 elseif Healbot_Config_Skins.HealGroups[SkinName][gl]["NAME"]==HEALBOT_OPTIONS_TARGETHEALS_en then Healbot_Config_Skins.HealGroups[SkinName][gl]["FRAME"]=8 elseif Healbot_Config_Skins.HealGroups[SkinName][gl]["NAME"]==HEALBOT_OPTIONS_PETHEALS_en then Healbot_Config_Skins.HealGroups[SkinName][gl]["FRAME"]=7 elseif Healbot_Config_Skins.HealGroups[SkinName][gl]["NAME"]==HEALBOT_VEHICLE_en then Healbot_Config_Skins.HealGroups[SkinName][gl]["FRAME"]=6 else Healbot_Config_Skins.HealGroups[SkinName][gl]["FRAME"]=1 end end end end if not Healbot_Config_Skins.HeadText[SkinName] then Healbot_Config_Skins.HeadText[SkinName]={} end if not Healbot_Config_Skins.HeadBar[SkinName] then Healbot_Config_Skins.HeadBar[SkinName]={} end if not Healbot_Config_Skins.Anchors[SkinName] then Healbot_Config_Skins.Anchors[SkinName]={} end if not Healbot_Config_Skins.FrameAlias[SkinName] then Healbot_Config_Skins.FrameAlias[SkinName]={} end if not Healbot_Config_Skins.FrameAliasBar[SkinName] then Healbot_Config_Skins.FrameAliasBar[SkinName]={} end if not Healbot_Config_Skins.HealBar[SkinName] then Healbot_Config_Skins.HealBar[SkinName]={} end if not Healbot_Config_Skins.BarCol[SkinName] then Healbot_Config_Skins.BarCol[SkinName]={} end if not Healbot_Config_Skins.AuxBarText[SkinName] then Healbot_Config_Skins.AuxBarText[SkinName]={} end if not Healbot_Config_Skins.BarIACol[SkinName] then Healbot_Config_Skins.BarIACol[SkinName]={} end if not Healbot_Config_Skins.BarText[SkinName] then Healbot_Config_Skins.BarText[SkinName]={} end if not Healbot_Config_Skins.BarTextCol[SkinName] then Healbot_Config_Skins.BarTextCol[SkinName]={} end if not Healbot_Config_Skins.Icons[SkinName] then Healbot_Config_Skins.Icons[SkinName]={} end if not Healbot_Config_Skins.RaidIcon[SkinName] then Healbot_Config_Skins.RaidIcon[SkinName]={} end if not Healbot_Config_Skins.IconText[SkinName] then Healbot_Config_Skins.IconText[SkinName]={} end if not Healbot_Config_Skins.Frame[SkinName] then Healbot_Config_Skins.Frame[SkinName]={} end if not Healbot_Config_Skins.StickyFrames[SkinName] then Healbot_Config_Skins.StickyFrames[SkinName]={} end if not Healbot_Config_Skins.Healing[SkinName] then Healbot_Config_Skins.Healing[SkinName]={} end if not Healbot_Config_Skins.General[SkinName] then Healbot_Config_Skins.General[SkinName]={} end if not Healbot_Config_Skins.BarSort[SkinName] then Healbot_Config_Skins.BarSort[SkinName]={} end if not Healbot_Config_Skins.Chat[SkinName] then Healbot_Config_Skins.Chat[SkinName]={} end if not Healbot_Config_Skins.Enemy[SkinName] then Healbot_Config_Skins.Enemy[SkinName]={} end if not Healbot_Config_Skins.FocusGroups[SkinName] then Healbot_Config_Skins.FocusGroups[SkinName]={} end if not Healbot_Config_Skins.BarVisibility[SkinName] then Healbot_Config_Skins.BarVisibility[SkinName]={} end if not Healbot_Config_Skins.BarAggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName]={} end if not Healbot_Config_Skins.AuxBar[SkinName] then Healbot_Config_Skins.AuxBar[SkinName]={} end if not Healbot_Config_Skins.AuxBarFrame[SkinName] then Healbot_Config_Skins.AuxBarFrame[SkinName]={} end for g=1,9 do if not Healbot_Config_Skins.AuxBar[SkinName][g] then Healbot_Config_Skins.AuxBar[SkinName][g]={} end end for gl=1,10 do if Healbot_Config_Skins.BarVisibility[SkinName][gl]["INCCLASSES"] then Healbot_Config_Skins.BarVisibility[SkinName][gl]["INCCLASSES"]=nil end if not Healbot_Config_Skins.HeadText[SkinName][gl] then Healbot_Config_Skins.HeadText[SkinName][gl]={} end if not Healbot_Config_Skins.HeadBar[SkinName][gl] then Healbot_Config_Skins.HeadBar[SkinName][gl]={} end if not Healbot_Config_Skins.Anchors[SkinName][gl] then Healbot_Config_Skins.Anchors[SkinName][gl]={} end if not Healbot_Config_Skins.FrameAlias[SkinName][gl] then Healbot_Config_Skins.FrameAlias[SkinName][gl]={} end if not Healbot_Config_Skins.FrameAliasBar[SkinName][gl] then Healbot_Config_Skins.FrameAliasBar[SkinName][gl]={} end if not Healbot_Config_Skins.HealBar[SkinName][gl] then Healbot_Config_Skins.HealBar[SkinName][gl]={} end if not Healbot_Config_Skins.BarCol[SkinName][gl] then Healbot_Config_Skins.BarCol[SkinName][gl]={} end if not Healbot_Config_Skins.AuxBarText[SkinName][gl] then Healbot_Config_Skins.AuxBarText[SkinName][gl]={} end if not Healbot_Config_Skins.BarIACol[SkinName][gl] then Healbot_Config_Skins.BarIACol[SkinName][gl]={} end if not Healbot_Config_Skins.BarText[SkinName][gl] then Healbot_Config_Skins.BarText[SkinName][gl]={} end if not Healbot_Config_Skins.BarTextCol[SkinName][gl] then Healbot_Config_Skins.BarTextCol[SkinName][gl]={} end if not Healbot_Config_Skins.Icons[SkinName][gl] then Healbot_Config_Skins.Icons[SkinName][gl]={} end if not Healbot_Config_Skins.RaidIcon[SkinName][gl] then Healbot_Config_Skins.RaidIcon[SkinName][gl]={} end if not Healbot_Config_Skins.IconText[SkinName][gl] then Healbot_Config_Skins.IconText[SkinName][gl]={} end if not Healbot_Config_Skins.Frame[SkinName][gl] then Healbot_Config_Skins.Frame[SkinName][gl]={} end if not Healbot_Config_Skins.StickyFrames[SkinName][gl] then Healbot_Config_Skins.StickyFrames[SkinName][gl]={} end if not Healbot_Config_Skins.BarVisibility[SkinName][gl] then Healbot_Config_Skins.BarVisibility[SkinName][gl]={} end if not Healbot_Config_Skins.BarSort[SkinName][gl] then Healbot_Config_Skins.BarSort[SkinName][gl]={} end if not Healbot_Config_Skins.BarAggro[SkinName][gl] then Healbot_Config_Skins.BarAggro[SkinName][gl]={} end for g=1,9 do if not Healbot_Config_Skins.AuxBar[SkinName][g][gl] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]={} end end if not Healbot_Config_Skins.AuxBarFrame[SkinName][gl] then Healbot_Config_Skins.AuxBarFrame[SkinName][gl]={} end end for g=1,8 do if Healbot_Config_Skins.FocusGroups[SkinName][g]==nil then Healbot_Config_Skins.FocusGroups[SkinName][g]=true end end for gl=1,10 do if Healbot_Config_Skins.Icons[SkinName][gl]["ONBAR"] then Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFONBAR"]=Healbot_Config_Skins.Icons[SkinName][gl]["ONBAR"] Healbot_Config_Skins.Icons[SkinName][gl]["BUFFONBAR"]=Healbot_Config_Skins.Icons[SkinName][gl]["ONBAR"] Healbot_Config_Skins.Icons[SkinName][gl]["ONBAR"]=nil end if Healbot_Config_Skins.Icons[SkinName][gl]["POSITION"] then if Healbot_Config_Skins.Icons[SkinName][gl]["POSITION"]==2 then Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFANCHOR"]=1 Healbot_Config_Skins.Icons[SkinName][gl]["BUFFANCHOR"]=2 Healbot_Config_Skins.Icons[SkinName][gl]["CLASSANCHOR"]=1 Healbot_Config_Skins.Icons[SkinName][gl]["TARGETANCHOR"]=1 Healbot_Config_Skins.Icons[SkinName][gl]["RCANCHOR"]=1 Healbot_Config_Skins.Icons[SkinName][gl]["OORANCHOR"]=1 else Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFANCHOR"]=2 Healbot_Config_Skins.Icons[SkinName][gl]["BUFFANCHOR"]=1 Healbot_Config_Skins.Icons[SkinName][gl]["CLASSANCHOR"]=2 Healbot_Config_Skins.Icons[SkinName][gl]["TARGETANCHOR"]=2 Healbot_Config_Skins.Icons[SkinName][gl]["RCANCHOR"]=2 Healbot_Config_Skins.Icons[SkinName][gl]["OORANCHOR"]=2 end Healbot_Config_Skins.Icons[SkinName][gl]["POSITION"]=nil end if Healbot_Config_Skins.Icons[SkinName][gl]["DOUBLE"] then Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFDOUBLE"]=Healbot_Config_Skins.Icons[SkinName][gl]["DOUBLE"] Healbot_Config_Skins.Icons[SkinName][gl]["BUFFDOUBLE"]=Healbot_Config_Skins.Icons[SkinName][gl]["DOUBLE"] Healbot_Config_Skins.Icons[SkinName][gl]["DOUBLE"]=nil end if Healbot_Config_Skins.Icons[SkinName][gl]["SHOWBUFF"] then Healbot_Config_Skins.Icons[SkinName][gl]["SHOWBUFF"]=nil end if Healbot_Config_Skins.Icons[SkinName][gl]["SHOWDEBUFF"] then Healbot_Config_Skins.Icons[SkinName][gl]["SHOWDEBUFF"]=nil end if Healbot_Config_Skins.BarText[SkinName][gl]["CLASSTYPE"] then if Healbot_Config_Skins.BarText[SkinName][gl]["CLASSONBAR"] and Healbot_Config_Skins.BarText[SkinName][gl]["CLASSTYPE"]<2 then Healbot_Config_Skins.Icons[SkinName][gl]["SHOWCLASS"]=true Healbot_Config_Skins.BarText[SkinName][gl]["CLASSONBAR"]=false Healbot_Config_Skins.Icons[SkinName][gl]["SHOWROLE"]=Healbot_Config_Skins.BarText[SkinName][gl]["SHOWROLE"] end Healbot_Config_Skins.BarText[SkinName][gl]["CLASSTYPE"]=nil end if Healbot_Config_Skins.BarVisibility[SkinName][gl]["ALERTIC"]==nil then Healbot_Config_Skins.BarVisibility[SkinName][gl]["ALERTIC"]=Healbot_Config_Skins.Healing[SkinName]["ALERTIC"] or 0.98 end if Healbot_Config_Skins.BarVisibility[SkinName][gl]["ALERTOC"]==nil then Healbot_Config_Skins.BarVisibility[SkinName][gl]["ALERTOC"]=Healbot_Config_Skins.Healing[SkinName]["ALERTOC"] or 0.9 end if Healbot_Config_Skins.BarSort[SkinName][gl]["RAIDORDER"]==nil then if Healbot_Config_Skins.Sort and Healbot_Config_Skins.Sort[SkinName] then Healbot_Config_Skins.BarSort[SkinName][gl]["RAIDORDER"]=Healbot_Config_Skins.Sort[SkinName]["RAIDORDER"] or 3 else Healbot_Config_Skins.BarSort[SkinName][gl]["RAIDORDER"]=3 end end if Healbot_Config_Skins.BarSort[SkinName][gl]["SUBORDER"]==nil then if Healbot_Config_Skins.Sort and Healbot_Config_Skins.Sort[SkinName] then Healbot_Config_Skins.BarSort[SkinName][gl]["SUBORDER"]=Healbot_Config_Skins.Sort[SkinName]["SUBORDER"] or 1 else Healbot_Config_Skins.BarSort[SkinName][gl]["SUBORDER"]=1 end end if Healbot_Config_Skins.BarSort[SkinName][gl]["OORLAST"]==nil then if Healbot_Config_Skins.Sort and Healbot_Config_Skins.Sort[SkinName] then Healbot_Config_Skins.BarSort[SkinName][gl]["OORLAST"]=Healbot_Config_Skins.Sort[SkinName]["OORLAST"] or false else Healbot_Config_Skins.BarSort[SkinName][gl]["OORLAST"]=false end end if Healbot_Config_Skins.BarSort[SkinName][gl]["SUBPF"]==nil then if Healbot_Config_Skins.Sort and Healbot_Config_Skins.Sort[SkinName] then Healbot_Config_Skins.BarSort[SkinName][gl]["SUBPF"]=Healbot_Config_Skins.Sort[SkinName]["SUBPF"] or true else Healbot_Config_Skins.BarSort[SkinName][gl]["SUBPF"]=true end end if Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOW"]==nil then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOW"]=Healbot_Config_Skins.Aggro[SkinName]["SHOW"] or true else Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOW"]=true end end if Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWBARS"]==nil then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWBARS"]=Healbot_Config_Skins.Aggro[SkinName]["SHOWBARS"] or true else Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWBARS"]=true end end if Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWTEXT"]==nil then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWTEXT"]=Healbot_Config_Skins.Aggro[SkinName]["SHOWTEXT"] or true else Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWTEXT"]=true end end if Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWIND"]==nil then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWIND"]=Healbot_Config_Skins.Aggro[SkinName]["SHOWIND"] or true else Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWIND"]=true end end if Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWBARSPCT"]==nil then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWBARSPCT"]=Healbot_Config_Skins.Aggro[SkinName]["SHOWBARSPCT"] or false else Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWBARSPCT"]=false end end if Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWTEXTPCT"]==nil then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWTEXTPCT"]=Healbot_Config_Skins.Aggro[SkinName]["SHOWTEXTPCT"] or true else Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWTEXTPCT"]=true end end if not Healbot_Config_Skins.BarAggro[SkinName][gl]["ALERT"] then Healbot_Config_Skins.BarAggro[SkinName][gl]["ALERT"]=2 end if not Healbot_Config_Skins.BarAggro[SkinName][gl]["ALERTIND"] then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["ALERTIND"]=Healbot_Config_Skins.Aggro[SkinName]["ALERTIND"] or 2 else Healbot_Config_Skins.BarAggro[SkinName][gl]["ALERTIND"]=2 end end if not Healbot_Config_Skins.BarAggro[SkinName][gl]["R"] then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["R"]=Healbot_Config_Skins.Aggro[SkinName]["R"] or 1 else Healbot_Config_Skins.BarAggro[SkinName][gl]["R"]=1 end end if not Healbot_Config_Skins.BarAggro[SkinName][gl]["G"] then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["G"]=Healbot_Config_Skins.Aggro[SkinName]["G"] or 0 else Healbot_Config_Skins.BarAggro[SkinName][gl]["G"]=0 end end if not Healbot_Config_Skins.BarAggro[SkinName][gl]["B"] then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["B"]=Healbot_Config_Skins.Aggro[SkinName]["B"] or 0 else Healbot_Config_Skins.BarAggro[SkinName][gl]["B"]=0 end end if not Healbot_Config_Skins.BarAggro[SkinName][gl]["TEXTFORMAT"] then if Healbot_Config_Skins.Aggro and Healbot_Config_Skins.Aggro[SkinName] then Healbot_Config_Skins.BarAggro[SkinName][gl]["TEXTFORMAT"]=Healbot_Config_Skins.Aggro[SkinName]["TEXTFORMAT"] or 3 else Healbot_Config_Skins.BarAggro[SkinName][gl]["TEXTFORMAT"]=3 end end if Healbot_Config_Skins.BarVisibility[SkinName][gl]["HIDEOOR"]==nil then Healbot_Config_Skins.BarVisibility[SkinName][gl]["HIDEOOR"]=false end if Healbot_Config_Skins.Frame[SkinName][gl]["TIPLOC"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["TIPLOC"]=5 end if not Healbot_Config_Skins.Frame[SkinName][gl]["AUTOCLOSE"] then Healbot_Config_Skins.Frame[SkinName][gl]["AUTOCLOSE"]=1 elseif Healbot_Config_Skins.Frame[SkinName][gl]["AUTOCLOSE"]==true then Healbot_Config_Skins.Frame[SkinName][gl]["AUTOCLOSE"]=2 end if Healbot_Config_Skins.Frame[SkinName][gl]["OPENSOUND"]~=nil then Healbot_Config_Skins.Frame[SkinName][gl]["OPENSOUND"]=nil end if not Healbot_Config_Skins.Frame[SkinName][gl]["LOCKED"] then Healbot_Config_Skins.Frame[SkinName][gl]["LOCKED"]=1 elseif Healbot_Config_Skins.Frame[SkinName][gl]["LOCKED"]==true then Healbot_Config_Skins.Frame[SkinName][gl]["LOCKED"]=2 end if Healbot_Config_Skins.Frame[SkinName][gl]["SCALE"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["SCALE"]=1 end if Healbot_Config_Skins.Frame[SkinName][gl]["BACKR"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["BACKR"]=0.2 end if Healbot_Config_Skins.Frame[SkinName][gl]["BACKG"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["BACKG"]=0.2 end if Healbot_Config_Skins.Frame[SkinName][gl]["BACKB"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["BACKB"]=0.7 end if Healbot_Config_Skins.Frame[SkinName][gl]["BACKA"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["BACKA"]=0.1 end if Healbot_Config_Skins.Frame[SkinName][gl]["BORDERR"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["BORDERR"]=0.2 end if Healbot_Config_Skins.Frame[SkinName][gl]["BORDERG"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["BORDERG"]=0.2 end if Healbot_Config_Skins.Frame[SkinName][gl]["BORDERB"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["BORDERB"]=0.2 end if Healbot_Config_Skins.Frame[SkinName][gl]["BORDERA"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["BORDERA"]=0.4 end if Healbot_Config_Skins.Frame[SkinName][gl]["SFOFFSETH"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["SFOFFSETH"]=0 end if Healbot_Config_Skins.Frame[SkinName][gl]["SFOFFSETV"]==nil then Healbot_Config_Skins.Frame[SkinName][gl]["SFOFFSETV"]=0 end if Healbot_Config_Skins.StickyFrames[SkinName][gl]["STUCK"]==nil then Healbot_Config_Skins.StickyFrames[SkinName][gl]["STUCK"]=false end if Healbot_Config_Skins.StickyFrames[SkinName][gl]["STUCKTO"]==nil then Healbot_Config_Skins.StickyFrames[SkinName][gl]["STUCKTO"]=0 end if Healbot_Config_Skins.StickyFrames[SkinName][gl]["STUCKPOINT"]==nil then Healbot_Config_Skins.StickyFrames[SkinName][gl]["STUCKPOINT"]="NONE" end if Healbot_Config_Skins.StickyFrames[SkinName][gl]["STUCKTOPOINT"]==nil then Healbot_Config_Skins.StickyFrames[SkinName][gl]["STUCKTOPOINT"]="NONE" end if Healbot_Config_Skins.IconText[SkinName][gl]["DURTHRH"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["DURTHRH"]=9 end if Healbot_Config_Skins.IconText[SkinName][gl]["BUFFDURTHRH"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["BUFFDURTHRH"]=Healbot_Config_Skins.IconText[SkinName][gl]["DURTHRH"] end if Healbot_Config_Skins.IconText[SkinName][gl]["DURWARN"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["DURWARN"]=3 end if Healbot_Config_Skins.IconText[SkinName][gl]["BUFFDURWARN"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["BUFFDURWARN"]=Healbot_Config_Skins.IconText[SkinName][gl]["DURWARN"] end if Healbot_Config_Skins.IconText[SkinName][gl]["SCNT"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["SCNT"]=true end if Healbot_Config_Skins.IconText[SkinName][gl]["BUFFSCNT"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["BUFFSCNT"]=Healbot_Config_Skins.IconText[SkinName][gl]["SCNT"] end if Healbot_Config_Skins.IconText[SkinName][gl]["SSCNT"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["SSCNT"]=false end if Healbot_Config_Skins.IconText[SkinName][gl]["BUFFSSCNT"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["BUFFSSCNT"]=Healbot_Config_Skins.IconText[SkinName][gl]["SSCNT"] end if Healbot_Config_Skins.IconText[SkinName][gl]["SDUR"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["SDUR"]=true end if Healbot_Config_Skins.IconText[SkinName][gl]["BUFFSDUR"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["BUFFSDUR"]=Healbot_Config_Skins.IconText[SkinName][gl]["SDUR"] end if Healbot_Config_Skins.IconText[SkinName][gl]["SSDUR"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["SSDUR"]=true end if Healbot_Config_Skins.IconText[SkinName][gl]["BUFFSSDUR"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["BUFFSSDUR"]=Healbot_Config_Skins.IconText[SkinName][gl]["SSDUR"] end if Healbot_Config_Skins.IconText[SkinName][gl]["FONT"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["FONT"]=HealBot_Default_Font end if Healbot_Config_Skins.IconText[SkinName][gl]["BUFFFONT"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["BUFFFONT"]=Healbot_Config_Skins.IconText[SkinName][gl]["FONT"] end if Healbot_Config_Skins.IconText[SkinName][gl]["OUTLINE"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["OUTLINE"]=2 end if Healbot_Config_Skins.IconText[SkinName][gl]["BUFFOUTLINE"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["BUFFOUTLINE"]=Healbot_Config_Skins.IconText[SkinName][gl]["OUTLINE"] end if Healbot_Config_Skins.RaidIcon[SkinName][gl]["SHOW"]==nil then Healbot_Config_Skins.RaidIcon[SkinName][gl]["SHOW"]=true end if Healbot_Config_Skins.RaidIcon[SkinName][gl]["STAR"]==nil then Healbot_Config_Skins.RaidIcon[SkinName][gl]["STAR"]=true end if Healbot_Config_Skins.RaidIcon[SkinName][gl]["CIRCLE"]==nil then Healbot_Config_Skins.RaidIcon[SkinName][gl]["CIRCLE"]=true end if Healbot_Config_Skins.RaidIcon[SkinName][gl]["DIAMOND"]==nil then Healbot_Config_Skins.RaidIcon[SkinName][gl]["DIAMOND"]=true end if Healbot_Config_Skins.RaidIcon[SkinName][gl]["TRIANGLE"]==nil then Healbot_Config_Skins.RaidIcon[SkinName][gl]["TRIANGLE"]=true end if Healbot_Config_Skins.RaidIcon[SkinName][gl]["MOON"]==nil then Healbot_Config_Skins.RaidIcon[SkinName][gl]["MOON"]=true end if Healbot_Config_Skins.RaidIcon[SkinName][gl]["SQUARE"]==nil then Healbot_Config_Skins.RaidIcon[SkinName][gl]["SQUARE"]=true end if Healbot_Config_Skins.RaidIcon[SkinName][gl]["CROSS"]==nil then Healbot_Config_Skins.RaidIcon[SkinName][gl]["CROSS"]=true end if Healbot_Config_Skins.RaidIcon[SkinName][gl]["SKULL"]==nil then Healbot_Config_Skins.RaidIcon[SkinName][gl]["SKULL"]=true end if Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFONBAR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFONBAR"]=1 end if Healbot_Config_Skins.Icons[SkinName][gl]["BUFFONBAR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["BUFFONBAR"]=1 end if fromImport then Healbot_Config_Skins.Icons[SkinName][gl]["CLASSONBAR"]=1 Healbot_Config_Skins.Icons[SkinName][gl]["TARGETONBAR"]=1 Healbot_Config_Skins.Icons[SkinName][gl]["RCONBAR"]=1 Healbot_Config_Skins.Icons[SkinName][gl]["OORONBAR"]=1 else if Healbot_Config_Skins.Icons[SkinName][gl]["CLASSONBAR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["CLASSONBAR"]=1 end if Healbot_Config_Skins.Icons[SkinName][gl]["TARGETONBAR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["TARGETONBAR"]=1 end if Healbot_Config_Skins.Icons[SkinName][gl]["RCONBAR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["RCONBAR"]=1 end if Healbot_Config_Skins.Icons[SkinName][gl]["OORONBAR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["OORONBAR"]=1 end end if Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFDOUBLE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFDOUBLE"]=false end if Healbot_Config_Skins.Icons[SkinName][gl]["BUFFDOUBLE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["BUFFDOUBLE"]=false end if Healbot_Config_Skins.Icons[SkinName][gl]["SHOWRC"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["SHOWRC"]=true end if Healbot_Config_Skins.Icons[SkinName][gl]["SHOWDIR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["SHOWDIR"]=false end if Healbot_Config_Skins.Icons[SkinName][gl]["SHOWDIRMOUSE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["SHOWDIRMOUSE"]=false end if Healbot_Config_Skins.Icons[SkinName][gl]["SCALE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["SCALE"]=0.7 end if Healbot_Config_Skins.Icons[SkinName][gl]["DSCALE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["DSCALE"]=Healbot_Config_Skins.Icons[SkinName][gl]["SCALE"] end if Healbot_Config_Skins.Icons[SkinName][gl]["I15EN"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["I15EN"]=true end if Healbot_Config_Skins.Icons[SkinName][gl]["BUFFI15EN"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["BUFFI15EN"]=Healbot_Config_Skins.Icons[SkinName][gl]["I15EN"] end if Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFANCHOR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["DEBUFFANCHOR"]=1 end if Healbot_Config_Skins.Icons[SkinName][gl]["BUFFANCHOR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["BUFFANCHOR"]=2 end if Healbot_Config_Skins.Icons[SkinName][gl]["CLASSANCHOR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["CLASSANCHOR"]=1 end if Healbot_Config_Skins.Icons[SkinName][gl]["TARGETANCHOR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["TARGETANCHOR"]=1 end if Healbot_Config_Skins.Icons[SkinName][gl]["RCANCHOR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["RCANCHOR"]=1 end if Healbot_Config_Skins.Icons[SkinName][gl]["OORANCHOR"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["OORANCHOR"]=1 end if Healbot_Config_Skins.Icons[SkinName][gl]["FADE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["FADE"]=false end if Healbot_Config_Skins.Icons[SkinName][gl]["BUFFFADE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["BUFFFADE"]=Healbot_Config_Skins.Icons[SkinName][gl]["FADE"] end if not Healbot_Config_Skins.Icons[SkinName][gl]["FADESECS"] then Healbot_Config_Skins.Icons[SkinName][gl]["FADESECS"]=15 end if not Healbot_Config_Skins.Icons[SkinName][gl]["BUFFFADESECS"] then Healbot_Config_Skins.Icons[SkinName][gl]["BUFFFADESECS"]=Healbot_Config_Skins.Icons[SkinName][gl]["FADESECS"] end if Healbot_Config_Skins.Icons[SkinName][gl]["MAXDICONS"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["MAXDICONS"]=3 end if Healbot_Config_Skins.Icons[SkinName][gl]["MAXBICONS"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["MAXBICONS"]=8 end if Healbot_Config_Skins.Icons[SkinName][gl]["SHOWCLASS"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["SHOWCLASS"]=false end if Healbot_Config_Skins.Icons[SkinName][gl]["SHOWROLE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["SHOWROLE"]=false end if not Healbot_Config_Skins.Icons[SkinName][gl]["CLASSVOFFSET"] then Healbot_Config_Skins.Icons[SkinName][gl]["CLASSVOFFSET"]=0 end if Healbot_Config_Skins.Icons[SkinName][gl]["CLASSHOFFSET"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["CLASSHOFFSET"]=0 end if Healbot_Config_Skins.Icons[SkinName][gl]["CLASSSCALE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["CLASSSCALE"]=0.5 end if Healbot_Config_Skins.Icons[SkinName][gl]["CLASSEN"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["CLASSEN"]=false end if not Healbot_Config_Skins.Icons[SkinName][gl]["TARGETVOFFSET"] then Healbot_Config_Skins.Icons[SkinName][gl]["TARGETVOFFSET"]=0 end if Healbot_Config_Skins.Icons[SkinName][gl]["TARGETHOFFSET"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["TARGETHOFFSET"]=0 end if Healbot_Config_Skins.Icons[SkinName][gl]["TARGETSCALE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["TARGETSCALE"]=0.5 end if Healbot_Config_Skins.Icons[SkinName][gl]["TARGETEN"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["TARGETEN"]=false end if not Healbot_Config_Skins.Icons[SkinName][gl]["RCVOFFSET"] then Healbot_Config_Skins.Icons[SkinName][gl]["RCVOFFSET"]=0 end if Healbot_Config_Skins.Icons[SkinName][gl]["RCHOFFSET"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["RCHOFFSET"]=0 end if Healbot_Config_Skins.Icons[SkinName][gl]["RCSCALE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["RCSCALE"]=0.5 end if Healbot_Config_Skins.Icons[SkinName][gl]["RCEN"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["RCEN"]=false end if not Healbot_Config_Skins.Icons[SkinName][gl]["OORVOFFSET"] then Healbot_Config_Skins.Icons[SkinName][gl]["OORVOFFSET"]=0 end if Healbot_Config_Skins.Icons[SkinName][gl]["OORHOFFSET"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["OORHOFFSET"]=0 end if Healbot_Config_Skins.Icons[SkinName][gl]["OORSCALE"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["OORSCALE"]=0.5 end if Healbot_Config_Skins.Icons[SkinName][gl]["OOREN"]==nil then Healbot_Config_Skins.Icons[SkinName][gl]["OOREN"]=false end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCR"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCR"]=1 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCG"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCG"]=1 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCB"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCB"]=0 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCA"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCA"]=0.95 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCDA"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCDA"]=0.5 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["NAME"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NAME"]=2 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCR"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCR"]=1 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCG"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCG"]=1 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCB"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCB"]=0 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCA"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCA"]=0.95 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCDA"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCDA"]=0.5 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["HLTH"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["HLTH"]=2 end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["NDEBUFF"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NDEBUFF"]=false end if Healbot_Config_Skins.BarTextCol[SkinName][gl]["HDEBUFF"]==nil then Healbot_Config_Skins.BarTextCol[SkinName][gl]["HDEBUFF"]=false end if Healbot_Config_Skins.BarText[SkinName][gl]["FONT"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["FONT"]=HealBot_Default_Font end if Healbot_Config_Skins.BarText[SkinName][gl]["HFONT"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HFONT"]=HealBot_Default_Font end if Healbot_Config_Skins.BarText[SkinName][gl]["HEIGHT"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HEIGHT"]=10 end if Healbot_Config_Skins.BarText[SkinName][gl]["HHEIGHT"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HHEIGHT"]=10 end if Healbot_Config_Skins.BarText[SkinName][gl]["SHOWROLE"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["SHOWROLE"]=true end if Healbot_Config_Skins.BarText[SkinName][gl]["CLASSONBAR"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["CLASSONBAR"]=false end if Healbot_Config_Skins.BarText[SkinName][gl]["OFFSET"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["OFFSET"]=0 end if Healbot_Config_Skins.BarText[SkinName][gl]["HOFFSET"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HOFFSET"]=0 end if Healbot_Config_Skins.BarText[SkinName][gl]["NAMEONBAR"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["NAMEONBAR"]=true end if Healbot_Config_Skins.BarText[SkinName][gl]["HLTHONBAR"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HLTHONBAR"]=true end if Healbot_Config_Skins.BarText[SkinName][gl]["IGNOREONFULL"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["IGNOREONFULL"]=true end if Healbot_Config_Skins.BarText[SkinName][gl]["ALIGN"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["ALIGN"]=2 end if Healbot_Config_Skins.BarText[SkinName][gl]["HALIGN"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HALIGN"]=2 end if Healbot_Config_Skins.BarText[SkinName][gl]["HOFFSET2"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HOFFSET2"]=0 end if Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]=2 end if Healbot_Config_Skins.BarText[SkinName][gl]["INCABSORBS"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["INCABSORBS"]=1 end if Healbot_Config_Skins.BarText[SkinName][gl]["OVERHEAL"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["OVERHEAL"]=1 end if Healbot_Config_Skins.BarText[SkinName][gl]["HLTHTXTANCHOR"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HLTHTXTANCHOR"]=1 end if Healbot_Config_Skins.BarText[SkinName][gl]["NUMFORMAT1"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["NUMFORMAT1"]=1 end if Healbot_Config_Skins.BarText[SkinName][gl]["NUMFORMAT2"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["NUMFORMAT2"]=1 end if Healbot_Config_Skins.BarText[SkinName][gl]["OUTLINE"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["OUTLINE"]=1 end if Healbot_Config_Skins.BarText[SkinName][gl]["HOUTLINE"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HOUTLINE"]=1 end if Healbot_Config_Skins.BarText[SkinName][gl]["HLTHTYPE"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HLTHTYPE"]=1 end if Healbot_Config_Skins.BarText[SkinName][gl]["MAXCHARS"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["MAXCHARS"]=0 end if Healbot_Config_Skins.BarText[SkinName][gl]["HMAXCHARS"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["HMAXCHARS"]=0 end if Healbot_Config_Skins.BarText[SkinName][gl]["TAGDC"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["TAGDC"]=HEALBOT_DISCONNECTED_TAG end if Healbot_Config_Skins.BarText[SkinName][gl]["TAGRIP"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["TAGRIP"]=HEALBOT_DEAD_TAG end if Healbot_Config_Skins.BarText[SkinName][gl]["TAGOOR"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["TAGOOR"]=HEALBOT_OUTOFRANGE_TAG end if Healbot_Config_Skins.BarText[SkinName][gl]["TAGR"]==nil then Healbot_Config_Skins.BarText[SkinName][gl]["TAGR"]=HEALBOT_RESERVED_TAG end if Healbot_Config_Skins.BarIACol[SkinName][gl]["IC"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["IC"]=3 end if Healbot_Config_Skins.BarIACol[SkinName][gl]["IR"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["IR"]=0.2 end if Healbot_Config_Skins.BarIACol[SkinName][gl]["IG"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["IG"]=1 end if Healbot_Config_Skins.BarIACol[SkinName][gl]["IB"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["IB"]=0.2 end if Healbot_Config_Skins.BarIACol[SkinName][gl]["IA"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["IA"]=0.82 end if Healbot_Config_Skins.BarIACol[SkinName][gl]["AC"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["AC"]=3 end if Healbot_Config_Skins.BarIACol[SkinName][gl]["AR"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["AR"]=1 end if Healbot_Config_Skins.BarIACol[SkinName][gl]["AG"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["AG"]=1 end if Healbot_Config_Skins.BarIACol[SkinName][gl]["AB"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["AB"]=1 end if Healbot_Config_Skins.BarIACol[SkinName][gl]["AA"]==nil then Healbot_Config_Skins.BarIACol[SkinName][gl]["AA"]=0.78 end if Healbot_Config_Skins.BarCol[SkinName][gl]["HLTH"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["HLTH"]=1 end if Healbot_Config_Skins.BarCol[SkinName][gl]["BACK"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["BACK"]=1 end if Healbot_Config_Skins.BarCol[SkinName][gl]["HR"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["HR"]=0.4 end if Healbot_Config_Skins.BarCol[SkinName][gl]["HG"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["HG"]=0.7 end if Healbot_Config_Skins.BarCol[SkinName][gl]["HB"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["HB"]=0.7 end if Healbot_Config_Skins.BarCol[SkinName][gl]["HA"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["HA"]=1 end if Healbot_Config_Skins.BarCol[SkinName][gl]["ORA"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["ORA"]=0.4 end if Healbot_Config_Skins.BarCol[SkinName][gl]["DISA"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["DISA"]=0.1 end if Healbot_Config_Skins.BarCol[SkinName][gl]["BR"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["BR"]=0.4 end if Healbot_Config_Skins.BarCol[SkinName][gl]["BG"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["BG"]=0.7 end if Healbot_Config_Skins.BarCol[SkinName][gl]["BB"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["BB"]=0.7 end if Healbot_Config_Skins.BarCol[SkinName][gl]["BA"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["BA"]=0 end if Healbot_Config_Skins.BarCol[SkinName][gl]["BOUT"]==nil then Healbot_Config_Skins.BarCol[SkinName][gl]["BOUT"]=1 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["SHOW"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["SHOW"]=true end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["FONT"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["FONT"]=HealBot_Default_Font end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["HEIGHT"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["HEIGHT"]=9 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["OFFSET"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["OFFSET"]=0 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["ALIGN"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["ALIGN"]=2 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["OUTLINE"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["OUTLINE"]=1 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["MAXCHARS"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["MAXCHARS"]=0 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLTYPE"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLTYPE"]=1 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLR"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLR"]=1 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLG"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLG"]=1 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLB"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLB"]=1 end if Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLA"]==nil then Healbot_Config_Skins.AuxBarText[SkinName][gl]["COLA"]=0.98 end if Healbot_Config_Skins.HeadText[SkinName][gl]["OUTLINE"]==nil then Healbot_Config_Skins.HeadText[SkinName][gl]["OUTLINE"]=1 end if Healbot_Config_Skins.HeadText[SkinName][gl]["FONT"]==nil then Healbot_Config_Skins.HeadText[SkinName][gl]["FONT"]=HealBot_Default_Font end if Healbot_Config_Skins.HeadText[SkinName][gl]["HEIGHT"]==nil then Healbot_Config_Skins.HeadText[SkinName][gl]["HEIGHT"]=9 end if Healbot_Config_Skins.HeadText[SkinName][gl]["OFFSET"]==nil then Healbot_Config_Skins.HeadText[SkinName][gl]["OFFSET"]=0 end if Healbot_Config_Skins.HeadText[SkinName][gl]["R"]==nil then Healbot_Config_Skins.HeadText[SkinName][gl]["R"]=1 end if Healbot_Config_Skins.HeadText[SkinName][gl]["G"]==nil then Healbot_Config_Skins.HeadText[SkinName][gl]["G"]=1 end if Healbot_Config_Skins.HeadText[SkinName][gl]["B"]==nil then Healbot_Config_Skins.HeadText[SkinName][gl]["B"]=0.1 end if Healbot_Config_Skins.HeadText[SkinName][gl]["A"]==nil then Healbot_Config_Skins.HeadText[SkinName][gl]["A"]=0.7 end if Healbot_Config_Skins.HeadBar[SkinName][gl]["SHOW"]==nil then Healbot_Config_Skins.HeadBar[SkinName][gl]["SHOW"]=false end if Healbot_Config_Skins.HeadBar[SkinName][gl]["TEXTURE"]==nil then Healbot_Config_Skins.HeadBar[SkinName][gl]["TEXTURE"]=HealBot_Default_Textures[10].name end if Healbot_Config_Skins.HeadBar[SkinName][gl]["WIDTH"]==nil then Healbot_Config_Skins.HeadBar[SkinName][gl]["WIDTH"]=0.7 end if Healbot_Config_Skins.HeadBar[SkinName][gl]["HEIGHT"]==nil then Healbot_Config_Skins.HeadBar[SkinName][gl]["HEIGHT"]=20 elseif Healbot_Config_Skins.HeadBar[SkinName][gl]["HEIGHT"]<2 then local bheight=(Healbot_Config_Skins.HealBar[SkinName][gl]["HEIGHT"]) Healbot_Config_Skins.HeadBar[SkinName][gl]["HEIGHT"]=ceil(bheight*Healbot_Config_Skins.HeadBar[SkinName][gl]["HEIGHT"]) end if Healbot_Config_Skins.HeadBar[SkinName][gl]["R"]==nil then Healbot_Config_Skins.HeadBar[SkinName][gl]["R"]=0.1 end if Healbot_Config_Skins.HeadBar[SkinName][gl]["G"]==nil then Healbot_Config_Skins.HeadBar[SkinName][gl]["G"]=0.7 end if Healbot_Config_Skins.HeadBar[SkinName][gl]["B"]==nil then Healbot_Config_Skins.HeadBar[SkinName][gl]["B"]=0.1 end if Healbot_Config_Skins.HeadBar[SkinName][gl]["A"]==nil then Healbot_Config_Skins.HeadBar[SkinName][gl]["A"]=0.4 end if Healbot_Config_Skins.HealBar[SkinName][gl]["CMARGIN"]==nil then Healbot_Config_Skins.HealBar[SkinName][gl]["CMARGIN"]=2 end if Healbot_Config_Skins.HealBar[SkinName][gl]["GRPCOLS"]==nil then Healbot_Config_Skins.HealBar[SkinName][gl]["GRPCOLS"]=false end if Healbot_Config_Skins.HealBar[SkinName][gl]["POWERCNT"]==nil then Healbot_Config_Skins.HealBar[SkinName][gl]["POWERCNT"]=true end if Healbot_Config_Skins.HealBar[SkinName][gl]["TEXTURE"]==nil then Healbot_Config_Skins.HealBar[SkinName][gl]["TEXTURE"]=HealBot_Default_Textures[8].name end if Healbot_Config_Skins.HealBar[SkinName][gl]["TEXTURE"]=="Empty" then Healbot_Config_Skins.HealBar[SkinName][gl]["TEXTURE"]="Smooth" end if Healbot_Config_Skins.HealBar[SkinName][gl]["HEIGHT"]==nil then Healbot_Config_Skins.HealBar[SkinName][gl]["HEIGHT"]=25 end if Healbot_Config_Skins.HealBar[SkinName][gl]["WIDTH"]==nil then Healbot_Config_Skins.HealBar[SkinName][gl]["WIDTH"]=144 end if Healbot_Config_Skins.HealBar[SkinName][gl]["NUMCOLS"]==nil then Healbot_Config_Skins.HealBar[SkinName][gl]["NUMCOLS"]=2 end if Healbot_Config_Skins.HealBar[SkinName][gl]["RMARGIN"]==nil then Healbot_Config_Skins.HealBar[SkinName][gl]["RMARGIN"]=1 end if Healbot_Config_Skins.HealBar[SkinName][gl]["OFIX"]==nil then Healbot_Config_Skins.HealBar[SkinName][gl]["OFIX"]=1 end if Healbot_Config_Skins.HealBar[SkinName][gl]["LOWMANA"]==nil then if Healbot_Config_Skins.General[SkinName]["LOWMANA"] then Healbot_Config_Skins.HealBar[SkinName][gl]["LOWMANA"]=Healbot_Config_Skins.General[SkinName]["LOWMANA"] else Healbot_Config_Skins.HealBar[SkinName][gl]["LOWMANA"]=1 end end if Healbot_Config_Skins.HealBar[SkinName][gl]["LOWMANACOMBAT"]==nil then if Healbot_Config_Skins.General[SkinName]["LOWMANACOMBAT"] then Healbot_Config_Skins.HealBar[SkinName][gl]["LOWMANACOMBAT"]=Healbot_Config_Skins.General[SkinName]["LOWMANACOMBAT"] else Healbot_Config_Skins.HealBar[SkinName][gl]["LOWMANACOMBAT"]=true end end for g=1,9 do if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["COLOUR"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["COLOUR"]=1 end if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["ANCHOR"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["ANCHOR"]=1 end if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["OFFSET"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["OFFSET"]=1 end if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["DEPTH"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["DEPTH"]=5 end if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["SIZE"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["SIZE"]=0.98 end if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["USE"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["USE"]=1 end if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["R"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["R"]=1 end if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["G"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["G"]=1 end if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["B"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["B"]=1 end if not Healbot_Config_Skins.AuxBar[SkinName][g][gl]["OTYPE"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["OTYPE"]=1 end if Healbot_Config_Skins.AuxBar[SkinName][g][gl]["A"] then Healbot_Config_Skins.AuxBar[SkinName][g][gl]["A"]=nil end end if not Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OVERLAP"] then Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OVERLAP"]=1 end if Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OFREQ"] then if not Healbot_Config_Skins.General[SkinName]["OFREQ"] then for g=1,9 do if Healbot_Config_Skins.AuxBar[SkinName][g][gl]["OTYPE"]==2 then Healbot_Config_Skins.General[SkinName]["OFREQ"]=Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OFREQ"] end end end Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OFREQ"]=nil end if Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OMIN"] then if not Healbot_Config_Skins.General[SkinName]["OMIN"] then for g=1,9 do if Healbot_Config_Skins.AuxBar[SkinName][g][gl]["OTYPE"]==2 then Healbot_Config_Skins.General[SkinName]["OMIN"]=Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OMIN"] end end end Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OMIN"]=nil end if Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OMAX"] then if not Healbot_Config_Skins.General[SkinName]["OMAX"] then for g=1,9 do if Healbot_Config_Skins.AuxBar[SkinName][g][gl]["OTYPE"]==2 then Healbot_Config_Skins.General[SkinName]["OMAX"]=Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OMAX"] end end end Healbot_Config_Skins.AuxBarFrame[SkinName][gl]["OMAX"]=nil end if Healbot_Config_Skins.Anchors[SkinName][gl]["FRAME"]==nil then Healbot_Config_Skins.Anchors[SkinName][gl]["FRAME"]=1 end if Healbot_Config_Skins.Anchors[SkinName][gl]["BARS"]==nil then Healbot_Config_Skins.Anchors[SkinName][gl]["BARS"]=1 end if Healbot_Config_Skins.Anchors[SkinName][gl]["GROW"]==nil then Healbot_Config_Skins.Anchors[SkinName][gl]["GROW"]=2 end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["NAME"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["NAME"]="" end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["SHOW"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["SHOW"]=false end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["FONT"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["FONT"]=HealBot_Default_Font end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["SIZE"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["SIZE"]=12 end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["OUTLINE"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["OUTLINE"]=1 end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["OFFSET"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["OFFSET"]=0 end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["R"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["R"]=1 end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["G"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["G"]=1 end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["B"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["B"]=1 end if Healbot_Config_Skins.FrameAlias[SkinName][gl]["A"]==nil then Healbot_Config_Skins.FrameAlias[SkinName][gl]["A"]=1 end if Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["TEXTURE"]==nil then Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["TEXTURE"]=HealBot_Default_Textures[10].name end if Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["WIDTH"]==nil then Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["WIDTH"]=0.7 end if Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["HEIGHT"]==nil then Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["HEIGHT"]=20 end if Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["R"]==nil then Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["R"]=0.1 end if Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["G"]==nil then Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["G"]=0.25 end if Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["B"]==nil then Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["B"]=0.25 end if Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["A"]==nil then Healbot_Config_Skins.FrameAliasBar[SkinName][gl]["A"]=0.5 end if Healbot_Config_Skins.Anchors[SkinName][gl]["Y"]==nil then Healbot_Config_Skins.Anchors[SkinName][gl]["Y"]=(49+gl) end if Healbot_Config_Skins.Anchors[SkinName][gl]["X"]==nil then Healbot_Config_Skins.Anchors[SkinName][gl]["X"]=(49+gl) end if Healbot_Config_Skins.Anchors[SkinName][gl]["Y"]>100 or Healbot_Config_Skins.Anchors[SkinName][gl]["X"]>100 then Healbot_Config_Skins.Anchors[SkinName][gl]["Y"]=HealBot_Comm_round(((Healbot_Config_Skins.Anchors[SkinName][gl]["Y"]/GetScreenHeight())*100),2) Healbot_Config_Skins.Anchors[SkinName][gl]["X"]=HealBot_Comm_round(((Healbot_Config_Skins.Anchors[SkinName][gl]["X"]/GetScreenWidth())*100),2) end if Healbot_Config_Skins.IconText[SkinName][gl]["HEIGHT"]==nil then if Healbot_Config_Skins.IconText[SkinName][gl]["SCALE"] then local iScale=Healbot_Config_Skins.HealBar[SkinName][gl]["HEIGHT"]*(Healbot_Config_Skins.Icons[SkinName][gl]["SCALE"]*0.7) Healbot_Config_Skins.IconText[SkinName][gl]["HEIGHT"]=floor(iScale*Healbot_Config_Skins.IconText[SkinName][gl]["SCALE"]) Healbot_Config_Skins.IconText[SkinName][gl]["SCALE"]=nil if Healbot_Config_Skins.IconText[SkinName][gl]["HEIGHT"]>12 then Healbot_Config_Skins.IconText[SkinName][gl]["HEIGHT"]=12 end if Healbot_Config_Skins.IconText[SkinName][gl]["HEIGHT"]<8 then Healbot_Config_Skins.IconText[SkinName][gl]["HEIGHT"]=8 end else Healbot_Config_Skins.IconText[SkinName][gl]["HEIGHT"]=10 end end if Healbot_Config_Skins.IconText[SkinName][gl]["BUFFHEIGHT"]==nil then Healbot_Config_Skins.IconText[SkinName][gl]["BUFFHEIGHT"]=Healbot_Config_Skins.IconText[SkinName][gl]["HEIGHT"] end if Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]>3 then if Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]==4 then Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]=2 Healbot_Config_Skins.BarText[SkinName][gl]["IGNOREONFULL"]=false elseif Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]==5 then Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]=3 Healbot_Config_Skins.BarText[SkinName][gl]["IGNOREONFULL"]=false elseif Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]==6 then Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]=2 Healbot_Config_Skins.BarText[SkinName][gl]["INCABSORBS"]=2 elseif Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]==7 then Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]=3 Healbot_Config_Skins.BarText[SkinName][gl]["INCABSORBS"]=3 elseif Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]==8 then Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]=2 Healbot_Config_Skins.BarText[SkinName][gl]["INCABSORBS"]=2 Healbot_Config_Skins.BarText[SkinName][gl]["IGNOREONFULL"]=false else Healbot_Config_Skins.BarText[SkinName][gl]["INCHEALS"]=3 Healbot_Config_Skins.BarText[SkinName][gl]["INCABSORBS"]=3 Healbot_Config_Skins.BarText[SkinName][gl]["IGNOREONFULL"]=false end elseif Healbot_Config_Skins.BarTextCol[SkinName][gl]["ER"] then Healbot_Config_Skins.BarText[SkinName][gl]["INCABSORBS"]=1 end Healbot_Config_Skins.BarText[SkinName][gl]["DOUBLE"]=nil if Healbot_Config_Skins.BarText[SkinName][gl]["CLASSCOL"]~=nil then if not Healbot_Config_Skins.BarText[SkinName][gl]["CLASSCOL"] then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NAME"]=3 Healbot_Config_Skins.BarTextCol[SkinName][gl]["HLTH"]=3 else Healbot_Config_Skins.BarTextCol[SkinName][gl]["NAME"]=2 Healbot_Config_Skins.BarTextCol[SkinName][gl]["HLTH"]=2 end end Healbot_Config_Skins.BarText[SkinName][gl]["CLASSCOL"]=nil if Healbot_Config_Skins.BarTextCol[SkinName][gl]["EA"] then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCA"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["EA"] Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCA"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["EA"] end Healbot_Config_Skins.BarTextCol[SkinName][gl]["EA"]=nil if Healbot_Config_Skins.BarTextCol[SkinName][gl]["DA"] then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCDA"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["DA"] Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCDA"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["DA"] end Healbot_Config_Skins.BarTextCol[SkinName][gl]["DA"]=nil Healbot_Config_Skins.BarTextCol[SkinName][gl]["CA"]=nil if Healbot_Config_Skins.BarTextCol[SkinName][gl]["ER"] then Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCR"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["ER"] Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCR"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["ER"] Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCG"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["EG"] Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCG"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["EG"] Healbot_Config_Skins.BarTextCol[SkinName][gl]["NCB"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["EB"] Healbot_Config_Skins.BarTextCol[SkinName][gl]["HCB"]=Healbot_Config_Skins.BarTextCol[SkinName][gl]["EB"] end Healbot_Config_Skins.BarTextCol[SkinName][gl]["ER"]=nil Healbot_Config_Skins.BarTextCol[SkinName][gl]["EG"]=nil Healbot_Config_Skins.BarTextCol[SkinName][gl]["EB"]=nil Healbot_Config_Skins.BarTextCol[SkinName][gl]["DR"]=nil Healbot_Config_Skins.BarTextCol[SkinName][gl]["DG"]=nil Healbot_Config_Skins.BarTextCol[SkinName][gl]["DB"]=nil Healbot_Config_Skins.BarTextCol[SkinName][gl]["CR"]=nil Healbot_Config_Skins.BarTextCol[SkinName][gl]["CG"]=nil Healbot_Config_Skins.BarTextCol[SkinName][gl]["CB"]=nil if HealBot_Config_Buffs.CBshownAB then for x=1,9 do Healbot_Config_Skins.AuxBar[SkinName][7][x]["USE"]=9 Healbot_Config_Skins.AuxBar[SkinName][7][x]["DEPTH"]=1 Healbot_Config_Skins.AuxBar[SkinName][7][x]["ANCHOR"]=2 end end HealBot_Config_Buffs.CBshownAB=nil HealBot_Config_Buffs.HealBot_CBWarnRange_Aggro=nil if HealBot_Config_Buffs.CDCshownAB then for x=1,9 do Healbot_Config_Skins.AuxBar[SkinName][8][x]["USE"]=10 Healbot_Config_Skins.AuxBar[SkinName][8][x]["DEPTH"]=1 Healbot_Config_Skins.AuxBar[SkinName][8][x]["ANCHOR"]=2 end end HealBot_Config_Cures.CDCshownAB=nil HealBot_Config_Cures.HealBot_CDCWarnRange_Aggro=nil if Healbot_Config_Skins.BarHighlight and Healbot_Config_Skins.BarHighlight[SkinName] and Healbot_Config_Skins.BarHighlight[SkinName][gl]["CBAR"] then Healbot_Config_Skins.AuxBar[SkinName][6][gl]["USE"]=8 Healbot_Config_Skins.AuxBar[SkinName][6][gl]["DEPTH"]=1 Healbot_Config_Skins.AuxBar[SkinName][6][gl]["ANCHOR"]=2 end if Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOW"] and Healbot_Config_Skins.HealBar[SkinName][gl]["AGGROSIZE"] and Healbot_Config_Skins.HealBar[SkinName][gl]["AGGROSIZE"]>0 then Healbot_Config_Skins.AuxBar[SkinName][5][gl]["USE"]=5 if Healbot_Config_Skins.HealBar[SkinName][gl]["AGGROSIZE"]>1 then Healbot_Config_Skins.AuxBar[SkinName][5][gl]["DEPTH"]=ceil(Healbot_Config_Skins.HealBar[SkinName][gl]["AGGROSIZE"]/1.5) else Healbot_Config_Skins.AuxBar[SkinName][5][gl]["DEPTH"]=1 end end if Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWBARSPCT"] then Healbot_Config_Skins.AuxBar[SkinName][4][gl]["USE"]=6 Healbot_Config_Skins.AuxBar[SkinName][4][gl]["DEPTH"]=2 end Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWBARSPCT"]=nil Healbot_Config_Skins.BarAggro[SkinName][gl]["SHOWBARS"]=nil Healbot_Config_Skins.BarHighlight=nil if Healbot_Config_Skins.HealBar[SkinName][gl]["POWERSIZE"] and Healbot_Config_Skins.HealBar[SkinName][gl]["POWERSIZE"]>0 then Healbot_Config_Skins.AuxBar[SkinName][1][gl]["USE"]=4 if Healbot_Config_Skins.HealBar[SkinName][gl]["POWERSIZE"]>1 then Healbot_Config_Skins.AuxBar[SkinName][1][gl]["DEPTH"]=ceil(Healbot_Config_Skins.HealBar[SkinName][gl]["POWERSIZE"]/1.5) else Healbot_Config_Skins.AuxBar[SkinName][1][gl]["DEPTH"]=1 end end Healbot_Config_Skins.HealBar[SkinName][gl]["POWERSIZE"]=nil Healbot_Config_Skins.HealBar[SkinName][gl]["AGGROSIZE"]=nil Healbot_Config_Skins.BarAggro[SkinName][gl]["FREQ"]=nil Healbot_Config_Skins.BarAggro[SkinName][gl]["MINA"]=nil Healbot_Config_Skins.BarAggro[SkinName][gl]["MAXA"]=nil end if Healbot_Config_Skins.Healing[SkinName]["ALERTIC"] then Healbot_Config_Skins.Healing[SkinName]["ALERTIC"]=nil end if Healbot_Config_Skins.Healing[SkinName]["ALERTOC"] then Healbot_Config_Skins.Healing[SkinName]["ALERTOC"]=nil end if Healbot_Config_Skins.Sort then Healbot_Config_Skins.Sort=nil end if Healbot_Config_Skins.Aggro then Healbot_Config_Skins.Aggro=nil end if Healbot_Config_Skins.Highlight then Healbot_Config_Skins.Highlight=nil end if Healbot_Config_Skins.Author[SkinName]==nil then Healbot_Config_Skins.Author[SkinName] = HEALBOT_WORDS_UNKNOWN end if Healbot_Config_Skins.Healing[SkinName]["GROUPPETS"]==nil then Healbot_Config_Skins.Healing[SkinName]["GROUPPETS"]=true end if Healbot_Config_Skins.Healing[SkinName]["SELFPET"]==nil then Healbot_Config_Skins.Healing[SkinName]["SELFPET"]=false end if Healbot_Config_Skins.Healing[SkinName]["TALWAYSSHOW"] then Healbot_Config_Skins.Healing[SkinName]["TARGETINCOMBAT"]=3 Healbot_Config_Skins.Healing[SkinName]["TALWAYSSHOW"]=nil end if Healbot_Config_Skins.Healing[SkinName]["TARGETINCOMBAT"]==nil then Healbot_Config_Skins.Healing[SkinName]["TARGETINCOMBAT"]=2 end if Healbot_Config_Skins.Healing[SkinName]["FALWAYSSHOW"] then Healbot_Config_Skins.Healing[SkinName]["FOCUSINCOMBAT"]=3 Healbot_Config_Skins.Healing[SkinName]["FALWAYSSHOW"]=nil end if not Healbot_Config_Skins.Healing[SkinName]["FOCUSINCOMBAT"] then Healbot_Config_Skins.Healing[SkinName]["FOCUSINCOMBAT"]=2 end if Healbot_Config_Skins.Healing[SkinName]["TONLYFRIEND"]==nil then Healbot_Config_Skins.Healing[SkinName]["TONLYFRIEND"]=false end if Healbot_Config_Skins.Healing[SkinName]["FONLYFRIEND"]==nil then Healbot_Config_Skins.Healing[SkinName]["FONLYFRIEND"]=false end if Healbot_Config_Skins.Healing[SkinName]["TEXRAID"]==nil then Healbot_Config_Skins.Healing[SkinName]["TEXRAID"]=false end if Healbot_Config_Skins.Healing[SkinName]["FEXRAID"]==nil then Healbot_Config_Skins.Healing[SkinName]["FEXRAID"]=false end if Healbot_Config_Skins.General[SkinName]["HIDEPARTYF"]==nil then Healbot_Config_Skins.General[SkinName]["HIDEPARTYF"]=false end if Healbot_Config_Skins.General[SkinName]["HIDEPTF"]==nil then Healbot_Config_Skins.General[SkinName]["HIDEPTF"]=false end if Healbot_Config_Skins.General[SkinName]["HIDEBOSSF"]==nil then Healbot_Config_Skins.General[SkinName]["HIDEBOSSF"]=false end if Healbot_Config_Skins.General[SkinName]["HIDERAIDF"]==nil then Healbot_Config_Skins.General[SkinName]["HIDERAIDF"]=true end if Healbot_Config_Skins.General[SkinName]["FLUIDBARS"]==nil then Healbot_Config_Skins.General[SkinName]["FLUIDBARS"]=false end if Healbot_Config_Skins.General[SkinName]["FLUIDFREQ"]==nil then Healbot_Config_Skins.General[SkinName]["FLUIDFREQ"]=10 end if Healbot_Config_Skins.General[SkinName]["STICKYFRAME"]==nil then Healbot_Config_Skins.General[SkinName]["STICKYFRAME"]=false end if not Healbot_Config_Skins.General[SkinName]["FOCUSGROUPS"] then Healbot_Config_Skins.General[SkinName]["FOCUSGROUPS"]=1 end if not Healbot_Config_Skins.General[SkinName]["FGDIMMING"] then Healbot_Config_Skins.General[SkinName]["FGDIMMING"]=2.5 end if not Healbot_Config_Skins.General[SkinName]["OFREQ"] then Healbot_Config_Skins.General[SkinName]["OFREQ"]=0.07 end if not Healbot_Config_Skins.General[SkinName]["OMIN"] then Healbot_Config_Skins.General[SkinName]["OMIN"]=0.1 end if not Healbot_Config_Skins.General[SkinName]["OMAX"] then Healbot_Config_Skins.General[SkinName]["OMAX"]=0.95 end if Healbot_Config_Skins.Chat[SkinName]["NOTIFY"]==nil then Healbot_Config_Skins.Chat[SkinName]["NOTIFY"]=1 end if Healbot_Config_Skins.Chat[SkinName]["MSG"]==nil then Healbot_Config_Skins.Chat[SkinName]["MSG"]=HEALBOT_NOTIFYOTHERMSG end if Healbot_Config_Skins.Chat[SkinName]["RESONLY"]==nil then Healbot_Config_Skins.Chat[SkinName]["RESONLY"]=true end if Healbot_Config_Skins.Chat[SkinName]["EOCOOM"]==nil then Healbot_Config_Skins.Chat[SkinName]["EOCOOM"]=false end if not Healbot_Config_Skins.Chat[SkinName]["EOCOOMV"] then Healbot_Config_Skins.Chat[SkinName]["EOCOOMV"]=20 end if Healbot_Config_Skins.DuplicateBars[SkinName]==nil then Healbot_Config_Skins.DuplicateBars[SkinName]=false end if Healbot_Config_Skins.Enemy[SkinName]["INCSELF"]==nil then Healbot_Config_Skins.Enemy[SkinName]["INCSELF"]=false end if Healbot_Config_Skins.Enemy[SkinName]["INCTANKS"]==nil then Healbot_Config_Skins.Enemy[SkinName]["INCTANKS"]=true end if Healbot_Config_Skins.Enemy[SkinName]["INCMYTAR"]==nil then Healbot_Config_Skins.Enemy[SkinName]["INCMYTAR"]=false end if Healbot_Config_Skins.Enemy[SkinName]["INCARENA"]==nil then Healbot_Config_Skins.Enemy[SkinName]["INCARENA"]=true end if Healbot_Config_Skins.Enemy[SkinName]["INCARENAPETS"]==nil then Healbot_Config_Skins.Enemy[SkinName]["INCARENAPETS"]=false end if Healbot_Config_Skins.Enemy[SkinName]["NUMBOSS"]==nil then Healbot_Config_Skins.Enemy[SkinName]["NUMBOSS"]=2 end if Healbot_Config_Skins.Enemy[SkinName]["HIDE"] then Healbot_Config_Skins.Frame[SkinName][10]["AUTOCLOSE"]=2 Healbot_Config_Skins.Enemy[SkinName]["HIDE"]=nil elseif Healbot_Config_Skins.Enemy[SkinName]["HIDE"]==false then Healbot_Config_Skins.Enemy[SkinName]["HIDE"]=nil end if not Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWSELF"] then Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWSELF"]=2 elseif Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWSELF"]==true then Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWSELF"]=1 end if not Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWTANK"] then Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWTANK"]=2 elseif Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWTANK"]==true then Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWTANK"]=1 end if not Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWLIST"] then Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWLIST"]=2 elseif Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWLIST"]==true then Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWLIST"]=1 end if not Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWARENA"] then Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWARENA"]=2 elseif Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWARENA"]==true then Healbot_Config_Skins.Enemy[SkinName]["INCOMBATSHOWARENA"]=1 end if not Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWPTAR"] then Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWPTAR"]=1 elseif Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWPTAR"]==true then Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWPTAR"]=2 end if not Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWARENA"] then Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWARENA"]=2 elseif Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWARENA"]==true then Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWARENA"]=3 end if not Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWMYTAR"] then Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWMYTAR"]=1 elseif Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWMYTAR"]==true then Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWMYTAR"]=2 end if not Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWTANK"] then Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWTANK"]=1 elseif Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWTANK"]==true then Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWTANK"]=2 end if Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWBOSS"]==nil then Healbot_Config_Skins.Enemy[SkinName]["EXISTSHOWBOSS"]=true end if Healbot_Config_Skins.Enemy[SkinName]["ENEMYTARGET"]==nil then Healbot_Config_Skins.Enemy[SkinName]["ENEMYTARGET"]=false end if Healbot_Config_Skins.Enemy[SkinName]["ENEMYTARGETSIZE"]==nil then Healbot_Config_Skins.Enemy[SkinName]["ENEMYTARGETSIZE"]=40 end if Healbot_Config_Skins.Enemy[SkinName]["DOUBLEWIDTH"]==nil then Healbot_Config_Skins.Enemy[SkinName]["DOUBLEWIDTH"]=false end if Healbot_Config_Skins.Enemy[SkinName]["INCDPS"] then Healbot_Config_Skins.Enemy[SkinName]["INCDPS"]=nil end if Healbot_Config_Skins.Enemy[SkinName]["FRAME"] then Healbot_Config_Skins.Enemy[SkinName]["FRAME"]=nil end if Healbot_Config_Skins.General[SkinName]["LOWMANA"] then Healbot_Config_Skins.General[SkinName]["LOWMANA"]=nil end if Healbot_Config_Skins.General[SkinName]["LOWMANACOMBAT"] then Healbot_Config_Skins.General[SkinName]["LOWMANACOMBAT"]=nil end -- Fix Frames for id=1,10 do if Healbot_Config_Skins.HealGroups[SkinName][id]["NAME"]==HEALBOT_CUSTOM_CASTBY_ENEMY_en then HealBot_Options_HealGroupSwap(SkinName, 11, id) break end end for id=1,9 do if Healbot_Config_Skins.HealGroups[SkinName][id]["NAME"]==HEALBOT_FOCUS_en then HealBot_Options_HealGroupSwap(SkinName, 10, id) break end end for id=1,8 do if Healbot_Config_Skins.HealGroups[SkinName][id]["NAME"]==HEALBOT_OPTIONS_TARGETHEALS_en then HealBot_Options_HealGroupSwap(SkinName, 9, id) break end end for id=1,7 do if Healbot_Config_Skins.HealGroups[SkinName][id]["NAME"]==HEALBOT_OPTIONS_PETHEALS_en then HealBot_Options_HealGroupSwap(SkinName, 8, id) break end end for id=1,6 do if Healbot_Config_Skins.HealGroups[SkinName][id]["NAME"]==HEALBOT_VEHICLE_en then HealBot_Options_HealGroupSwap(SkinName, 7, id) break end end Healbot_Config_Skins.HealGroups[SkinName][11]["FRAME"]=10 Healbot_Config_Skins.HealGroups[SkinName][10]["FRAME"]=9 Healbot_Config_Skins.HealGroups[SkinName][9]["FRAME"]=8 if Healbot_Config_Skins.HealGroups[SkinName][8]["FRAME"]>7 or Healbot_Config_Skins.HealGroups[SkinName][8]["FRAME"]==6 then Healbot_Config_Skins.HealGroups[SkinName][8]["FRAME"]=7 end if Healbot_Config_Skins.HealGroups[SkinName][7]["FRAME"]>6 then Healbot_Config_Skins.HealGroups[SkinName][7]["FRAME"]=6 end Healbot_Config_Skins.FrameAlias[SkinName][6]["ALIAS"]=HEALBOT_VEHICLE_en Healbot_Config_Skins.FrameAlias[SkinName][7]["ALIAS"]=HEALBOT_OPTIONS_PETHEALS_en Healbot_Config_Skins.FrameAlias[SkinName][8]["ALIAS"]=HEALBOT_OPTIONS_TARGETHEALS_en Healbot_Config_Skins.FrameAlias[SkinName][9]["ALIAS"]=HEALBOT_FOCUS_en Healbot_Config_Skins.FrameAlias[SkinName][10]["ALIAS"]=HEALBOT_CUSTOM_CASTBY_ENEMY_en for id=1,6 do if Healbot_Config_Skins.HealGroups[SkinName][id]["FRAME"]>5 then Healbot_Config_Skins.HealGroups[SkinName][id]["FRAME"]=1 end end --HealBot_setCall("HealBot_Skins_Check_Skin") end
gpl-2.0
lawnight/skynet
service/launcher.lua
24
3372
local skynet = require "skynet" local core = require "skynet.core" require "skynet.manager" -- import manager apis local string = string local services = {} local command = {} local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK) local function handle_to_address(handle) return tonumber("0x" .. string.sub(handle , 2)) end local NORET = {} function command.LIST() local list = {} for k,v in pairs(services) do list[skynet.address(k)] = v end return list end function command.STAT() local list = {} for k,v in pairs(services) do local ok, stat = pcall(skynet.call,k,"debug","STAT") if not ok then stat = string.format("ERROR (%s)",v) end list[skynet.address(k)] = stat end return list end function command.KILL(_, handle) handle = handle_to_address(handle) skynet.kill(handle) local ret = { [skynet.address(handle)] = tostring(services[handle]) } services[handle] = nil return ret end function command.MEM() local list = {} for k,v in pairs(services) do local ok, kb, bytes = pcall(skynet.call,k,"debug","MEM") if not ok then list[skynet.address(k)] = string.format("ERROR (%s)",v) else list[skynet.address(k)] = string.format("%.2f Kb (%s)",kb,v) end end return list end function command.GC() for k,v in pairs(services) do skynet.send(k,"debug","GC") end return command.MEM() end function command.REMOVE(_, handle, kill) services[handle] = nil local response = instance[handle] if response then -- instance is dead response(not kill) -- return nil to caller of newservice, when kill == false instance[handle] = nil end -- don't return (skynet.ret) because the handle may exit return NORET end local function launch_service(service, ...) local param = table.concat({...}, " ") local inst = skynet.launch(service, param) local response = skynet.response() if inst then services[inst] = service .. " " .. param instance[inst] = response else response(false) return end return inst end function command.LAUNCH(_, service, ...) launch_service(service, ...) return NORET end function command.LOGLAUNCH(_, service, ...) local inst = launch_service(service, ...) if inst then core.command("LOGON", skynet.address(inst)) end return NORET end function command.ERROR(address) -- see serivce-src/service_lua.c -- init failed local response = instance[address] if response then response(false) instance[address] = nil end services[address] = nil return NORET end function command.LAUNCHOK(address) -- init notice local response = instance[address] if response then response(true, address) instance[address] = nil end return NORET end -- for historical reasons, launcher support text command (for C service) skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, unpack = skynet.tostring, dispatch = function(session, address , cmd) if cmd == "" then command.LAUNCHOK(address) elseif cmd == "ERROR" then command.ERROR(address) else error ("Invalid text command " .. cmd) end end, } skynet.dispatch("lua", function(session, address, cmd , ...) cmd = string.upper(cmd) local f = command[cmd] if f then local ret = f(address, ...) if ret ~= NORET then skynet.ret(skynet.pack(ret)) end else skynet.ret(skynet.pack {"Unknown command"} ) end end) skynet.start(function() end)
mit
KlonZK/Zero-K
effects/yellow_lightning.lua
8
19026
-- yellow_lightning_bomb -- yellow_lightning_bluebolts -- yellow_lightning_groundflash -- yellow_lightning_bomb_yellowbolts -- yellow_lightning_muzzle -- yellow_lightning_yellowbolts -- yellow_lightning_bomb_bluebolts -- yellow_lightningplosion -- yellow_lightning_stormbolt return { ["mixed_white_lightning_bomb_small"] = { usedefaultexplosions = true, groundflash = { circlealpha = 1, circlegrowth = 2, flashalpha = 1.3, flashsize = 25, ground = true, water = true, ttl = 4, color = { [1] = 1, [2] = 0.9, [3] = 0.65, }, }, whitebolts = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 3, explosiongenerator = [[custom:WHITE_LIGHTNING_BOMB_BOLTS_SMALL]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 2, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.1, color = [[1,1,1]], dir = [[-5 r10,-5 r10,-5 r10]], length = 10, width = 1.5, }, }, }, ["white_lightning_bomb"] = { whitebolts = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 3, explosiongenerator = [[custom:WHITE_LIGHTNING_BOMB_BOLTS]], pos = [[0, 0, 0]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.3, flashsize = 32, ground = true, water = true, ttl = 12, color = { [1] = 1, [2] = 1, [3] = 1, }, }, pikes = { air = true, class = [[explspike]], count = 2, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.1, color = [[1,1,1]], dir = [[-15 r30,-15 r30,-15 r30]], length = 16, width = 2, }, }, }, ["white_lightning_bomb_bolts_small"] = { bluebolts = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[1 1 1 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01 1 1 1 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 3, particlelife = 1.5, particlelifespread = 3, particlesize = 20, particlesizespread = 0, particlespeed = 2, particlespeedspread = 0, pos = [[0, 1.0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[whitelightb]], }, }, }, ["white_lightning_bomb_bolts"] = { bluebolts = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[1 1 1 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01 1 1 1 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 5, particlelife = 2, particlelifespread = 5, particlesize = 40, particlesizespread = 0, particlespeed = 2, particlespeedspread = 0, pos = [[0, 1.0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[whitelightb]], }, }, }, ["yellow_lightning_stormbolt"] = { groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.3, flashsize = 32, ttl = 3, color = { [1] = 1, [2] = 1, [3] = 1, }, }, lightningballs = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0 0 0 0.01 1 1 1 0.01 0 0 0 0.01]], directional = true, emitrot = 80, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 3, particlelifespread = 0, particlesize = 2, particlesizespread = 20, particlespeed = 0.01, particlespeedspread = 0, pos = [[-10 r20, 1.0, -10 r20]], sizegrowth = 0, sizemod = 1.0, texture = [[whitelightb]], }, }, }, ["yellow_lightning_bomb"] = { bluebolts = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 3, explosiongenerator = [[custom:YELLOW_LIGHTNING_BOMB_BLUEBOLTS]], pos = [[0, 0, 0]], }, }, electricstorm = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = [[10 r200]], explosiongenerator = [[custom:YELLOW_LIGHTNING_STORMBOLT]], pos = [[-100 r200, 1, -100 r200]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.3, flashsize = 32, ttl = 12, color = { [1] = 1, [2] = 1, [3] = 0.25, }, }, pikes = { air = true, class = [[explspike]], count = 2, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.1, color = [[1,1,0.25]], dir = [[-15 r30,-15 r30,-15 r30]], length = 16, width = 2, }, }, yellowbolts = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 3, explosiongenerator = [[custom:YELLOW_LIGHTNING_BOMB_YELLOWBOLTS]], pos = [[0, 0, 0]], }, }, }, ["yellow_lightning_bluebolts"] = { ["electric thingies"] = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[1 1 0.25 0.01 1 1 0.25 0.01 0.5 0.5 1 0.01 1 1 0.25 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 5, particlelife = 2, particlelifespread = 5, particlesize = 40, particlesizespread = 0, particlespeed = 2, particlespeedspread = 0, pos = [[0, 1.0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[whitelightb]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 0.2 0.01 1 1 0.4 0.01 0.0 0.0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 60, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 40, particlelife = 20, particlelifespread = 5, particlesize = 5, particlesizespread = 0, particlespeed = 5, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[spark]], }, }, }, ["yellow_lightning_groundflash"] = { groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.3, flashsize = 46, ttl = 12, color = { [1] = 1, [2] = 1, [3] = 0.25, }, }, }, ["yellow_lightning_bomb_yellowbolts"] = { yellowbolts = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.1, colormap = [[1 1 0.25 0.01 1 1 0.25 0.01 1 1 0.25 0.01 1 1 0.25 0.01 1 1 0.25 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 5, particlelife = 8, particlelifespread = 4, particlesize = 15, particlesizespread = 15, particlespeed = 20, particlespeedspread = 20, pos = [[0, 1.0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[whitelightb]], }, }, }, ["yellow_lightning_muzzle"] = { usedefaultexplosions = false, lightball = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0.7 0.6 0 0.01 1 0.85 0 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 20, particlelifespread = 0, particlesize = 15, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[lightb3]], }, }, lightball2 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0 0 0 0.01 0.3 0.25 0 0.01 0.7 0.6 0 0.01 1 0.85 0 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 20, particlelifespread = 0, particlesize = 15, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[lightb4]], }, }, lightring = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0.7 0.7 0 0.01 1 1 0 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 20, particlelifespread = 0, particlesize = 1, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[lightring]], }, }, }, ["yellow_lightning_yellowbolts"] = { ["electric thingies2"] = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.1, colormap = [[1 1 0.25 0.01 1 1 0.25 0.01 1 1 0.25 0.01 1 1 0.25 0.01 1 1 0.25 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 10, particlelife = 8, particlelifespread = 4, particlesize = 15, particlesizespread = 15, particlespeed = 20, particlespeedspread = 20, pos = [[0, 1.0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[whitelightb]], }, }, }, ["yellow_lightning_bomb_bluebolts"] = { bluebolts = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[1 1 0.25 0.01 1 1 0.25 0.01 0.5 0.5 1 0.01 1 1 0.25 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 5, particlelife = 2, particlelifespread = 5, particlesize = 40, particlesizespread = 0, particlespeed = 2, particlespeedspread = 0, pos = [[0, 1.0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[whitelightb]], }, }, }, ["yellow_lightningplosion"] = { bluebolts = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:YELLOW_LIGHTNING_BLUEBOLTS]], pos = [[0, 0, 0]], }, }, electricstorm = { air = true, class = [[CExpGenSpawner]], count = 20, ground = true, water = true, properties = { delay = [[10 r200]], explosiongenerator = [[custom:YELLOW_LIGHTNING_STORMBOLT]], pos = [[-100 r200, 1, -100 r200]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.3, flashsize = 86, ttl = 12, color = { [1] = 1, [2] = 1, [3] = 0.25, }, }, pikes = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.1, color = [[1,1,0.25]], dir = [[-15 r30,-15 r30,-15 r30]], length = 30, width = 5, }, }, yellowbolts = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 3, explosiongenerator = [[custom:YELLOW_LIGHTNING_YELLOWBOLTS]], pos = [[0, 0, 0]], }, }, }, ["yellow_lightning_stormbolt"] = { groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.3, flashsize = 32, ttl = 3, color = { [1] = 1, [2] = 1, [3] = 0.25, }, }, lightningballs = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0 0 0 0.01 1 1 0.25 0.01 0 0 0 0.01]], directional = true, emitrot = 80, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 3, particlelifespread = 0, particlesize = 2, particlesizespread = 20, particlespeed = 0.01, particlespeedspread = 0, pos = [[-10 r20, 1.0, -10 r20]], sizegrowth = 0, sizemod = 1.0, texture = [[whitelightb]], }, }, }, }
gpl-2.0
hacker44-h44/original
plugins/GroupManager.lua
39
11325
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "This service is private for SUDO (@shayansoft)" end local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group '..string.gsub(group_name, '_', ' ')..' created, check messages list...' end local function set_description(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = deskripsi save_data(_config.moderation.data, data) return 'Set this message for about=>\n\n'..deskripsi end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'Group have not about' end local about = data[tostring(msg.to.id)][data_cat] return about end local function set_rules(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set this message for rules=>\n\n'..rules end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'Group have not rules' end local rules = data[tostring(msg.to.id)][data_cat] return rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Name is already locked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ') save_data(_config.moderation.data, data) return 'Group name locked' end end local function unlock_group_name(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Name is already unlocked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Members are already locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members locked' end local function unlock_group_member(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Members are already unlocked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Photo is already locked' else data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Send group photo now' end local function unlock_group_photo(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Photo is already unlocked' else data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo unlocked' end end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Group photo save and set', ok_cb, false) else print('Error: '..msg.id) send_large_msg(receiver, 'Failed, try again', ok_cb, false) end end -- show group settings local function show_group_settings(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local settings = data[tostring(msg.to.id)]['settings'] local text = "Group Settings:\n_________________________\n> Lock Group Name : "..settings.lock_name.."\n> Lock Group Photo : "..settings.lock_photo.."\n> Lock Group Member : "..settings.lock_member.."\n> Anti Spam System : on\n> Anti Spam Mod : kick\n> Anti Spam Action : 10\n> Group Status : active\n> Group Model : free\n> Group Mod : 2\n> Supportion : yes\n> Bot Version : 1.6" return text end function run(msg, matches) --vardump(msg) if matches[1] == 'makegroup' and matches[2] then group_name = matches[2] return create_group(msg) end if not is_chat_msg(msg) then return "This is not group" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if msg.media and is_chat_msg(msg) and is_momod(msg) then if msg.media.type == 'photo' and data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then load_photo(msg.id, set_group_photo, msg) end end end if data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'setabout' and matches[2] then deskripsi = matches[2] return set_description(msg, data) end if matches[1] == 'about' then return get_description(msg, data) end if matches[1] == 'setrules' then rules = matches[2] return set_rules(msg, data) end if matches[1] == 'rules' then return get_rules(msg, data) end if matches[1] == 'group' and matches[2] == '+' then --group lock * if matches[3] == 'name' then return lock_group_name(msg, data) end if matches[3] == 'member' then return lock_group_member(msg, data) end if matches[3] == 'photo' then return lock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == '-' then --group unlock * if matches[3] == 'name' then return unlock_group_name(msg, data) end if matches[3] == 'member' then return unlock_group_member(msg, data) end if matches[3] == 'photo' then return unlock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == '?' then return show_group_settings(msg, data) end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Send new photo now' end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end end end return { description = "Group Manager System", usage = { "/makegroup (name) : create new group", "/about : view group about", "/rules : view group rules", "/setname (name) : set group name", "/setphoto : set group photo", "/setabout (message) : set group about", "/setrules (message) : set group rules", "/group + name : lock group name", "/group + photo : lock group photo", "/group + member : lock group member", "/group - name : unlock group name", "/group - photo : unlock group photo", "/group - member : unlock group member", "/group ? : view group settings" }, patterns = { "^[!/](makegroup) (.*)$", "^[!/](setabout) (.*)$", "^[!/](about)$", "^[!/](setrules) (.*)$", "^[!/](rules)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](group) (+) (.*)$", "^[!/](group) (-) (.*)$", "^[!/](group) (?)$", "^!!tgservice (.+)$", "%[(photo)%]", }, run = run, } end
gpl-2.0
alimashmamali/fff
plugins/google.lua
722
1037
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
dani-sj/mahdii
plugins/google.lua
722
1037
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
Wiladams/REMOTE
tflremote/bmpcodec.lua
1
2572
-- BmpCodec.lua -- Write out a Drawing Context into a -- stream as a BMP encoded image local MemoryStream = require("tflremote.memorystream"); local BinaryStream = require("tflremote.binarystream"); local ImageBitCount = 32; local PixelOffset = 54; local BI_RGB = 0; -- params.CapturedStream = MemoryStream(streamsize); local function GetAlignedByteCount(width, bitsPerPixel, byteAlignment) local nbytes = width * (bitsPerPixel/8); return nbytes + (byteAlignment - (nbytes % byteAlignment)) % byteAlignment end local BmpCodec = {} function BmpCodec.getBmpFileSize(img) rowsize = GetAlignedByteCount(img.width, img.bitcount, 4); pixelarraysize = rowsize * math.abs(img.height); filesize = PixelOffset+pixelarraysize; return filesize; end function BmpCodec.setup(width, height, bitcount, data) rowsize = GetAlignedByteCount(width, bitcount, 4); pixelarraysize = rowsize * math.abs(height); filesize = PixelOffset+pixelarraysize; return { width = width; height = height; bitcount = bitcount; data = data; pixeloffset = 54; rowsize = rowsize; pixelarraysize = pixelarraysize; filesize = filesize; streamsize = GetAlignedByteCount(filesize, 8, 4); } end function BmpCodec.write(BaseStream, img) local bs = BinaryStream:new(BaseStream); filesize = PixelOffset+img.pixelarraysize; -- Write File Header bs:writeByte(string.byte('B')) bs:writeByte(string.byte('M')) bs:writeInt32(filesize); bs:writeInt16(0); bs:writeInt16(0); bs:writeInt32(PixelOffset); -- Bitmap information header bs:writeInt32(40); bs:writeInt32(img.width); -- dibsec.Info.bmiHeader.biWidth bs:writeInt32(-img.height); -- dibsec.Info.bmiHeader.biHeight bs:writeInt16(1); -- dibsec.Info.bmiHeader.biPlanes); bs:writeInt16(img.bitcount); -- dibsec.Info.bmiHeader.biBitCount); bs:writeInt32(BI_RGB); -- dibsec.Info.bmiHeader.biCompression); bs:writeInt32(img.pixelarraysize); -- dibsec.Info.bmiHeader.biSizeImage); bs:writeInt32(0); -- dibsec.Info.bmiHeader.biXPelsPerMeter); bs:writeInt32(0); -- dibsec.Info.bmiHeader.biYPelsPerMeter); bs:writeInt32(0); -- dibsec.Info.bmiHeader.biClrUsed); bs:writeInt32(0); -- dibsec.Info.bmiHeader.biClrImportant); -- Write the actual pixel data BaseStream:writeBytes(img.data, img.pixelarraysize, 0); return filesize; end return BmpCodec;
mit
KlonZK/Zero-K
LuaUI/utility_two.lua
17
1410
-- Utility function for ZK -- Will try to read LUA content from target file and create BACKUP if have a successful read (in user's Spring folder) OR DELETE them if have a failure read -- This prevent corrupted file from being used. -- Note: currently only a "table" is considered a valid file function CheckLUAFileAndBackup(filePath, headerString) local chunk, err = loadfile(filePath) local success = false if (chunk) then --if original content is LUA OK: local tmp = {} setfenv(chunk, tmp) local tab = chunk() if tab and type(tab) == "table" then table.save(chunk(),filePath..".bak",headerString) --write to backup success = true end end if (not success) then --if original content is not LUA OK: Spring.Log("CheckLUAFileAndBackup","warning", tostring(err) .. " (Now will find backup file)") chunk, err = loadfile(filePath..".bak") if (chunk) then --if backup content is LUA OK: local tmp = {} setfenv(chunk, tmp) local tab = chunk() if tab and type(tab) == "table" then table.save(chunk(),filePath,headerString) --overwrite original success = true end end if (not success) then --if backup content is also not LUA OK: Spring.Log("CheckLUAFileAndBackup","warning", tostring(err) .. " (Backup file not available)") Spring.Echo(os.remove (filePath)) --delete original Spring.Echo(os.remove (filePath..".bak")) --delete backup end end end
gpl-2.0
omid1212/sss
bot/seedbot.lua
1
8637
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) -- mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite" }, sudo_users = {1111111,11111111,0,tonumber(our_id)},--Sudo users disabled_channels = {}, realm = {},--Realms Id moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v1 An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Admins @iwals [Founder] @imandaneshi [Developer] @seyedan25 [Manager] Special thanks to awkward_potato Siyanew topkecleon Vamptacus Our channels @teleseedch [English] ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id return group id or user id !help !lock [member|name] Locks [member|name] !unlock [member|name|photo] Unlocks [member|name|photo] !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !newlink create/revoke your group link !link returns group link !owner returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] <text> Save <text> as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] returns user id "!res @username" !log will return group logs !banlist will return group ban list **U can use both "/" and "!" *Only owner and mods can add bots in group *Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
tunneff/tef
deps/luasocket/etc/forward.lua
43
2066
-- load our favourite library local dispatch = require("dispatch") local handler = dispatch.newhandler() -- make sure the user knows how to invoke us if #arg < 1 then print("Usage") print(" lua forward.lua <iport:ohost:oport> ...") os.exit(1) end -- function to move data from one socket to the other local function move(foo, bar) local live while 1 do local data, error, partial = foo:receive(2048) live = data or error == "timeout" data = data or partial local result, error = bar:send(data) if not live or not result then foo:close() bar:close() break end end end -- for each tunnel, start a new server for i, v in ipairs(arg) do -- capture forwarding parameters local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)") assert(iport, "invalid arguments") -- create our server socket local server = assert(handler.tcp()) assert(server:setoption("reuseaddr", true)) assert(server:bind("*", iport)) assert(server:listen(32)) -- handler for the server object loops accepting new connections handler:start(function() while 1 do local client = assert(server:accept()) assert(client:settimeout(0)) -- for each new connection, start a new client handler handler:start(function() -- handler tries to connect to peer local peer = assert(handler.tcp()) assert(peer:settimeout(0)) assert(peer:connect(ohost, oport)) -- if sucessful, starts a new handler to send data from -- client to peer handler:start(function() move(client, peer) end) -- afte starting new handler, enter in loop sending data from -- peer to client move(peer, client) end) end end) end -- simply loop stepping the server while 1 do handler:step() end
lgpl-3.0
jkeywo/KFactorioMods
k-nineworlds_0.0.0/control.lua
1
1950
-- factorio libs require "util" require "config" -- std libs require("stdlib.area.area") require("stdlib.area.position") require("stdlib.area.chunk") require("stdlib.entity.entity") require("stdlib.event.event") require("stdlib.table") -- config DEBUG = true -- nw libs require("lib.core") Scheduler = require("lib.scheduler") -- systems Linked = require("systems.linked-control") Tunnels = require("systems.tunnels-control") Logistics = require("systems.logistics-control") -- worlds Worlds = require("worlds.worlds-control") Midgard = require("worlds.midgard-control") Nidavellir = require("worlds.nidavellir-control") Svartalfheim = require("worlds.svartalfheim-control") -- setup links between terrestrial worlds Midgard.links.down = Nidavellir Midgard.links.up = nil Nidavellir.links.down = Svartalfheim Nidavellir.links.up = Midgard Svartalfheim.links.down = nil Svartalfheim.links.up = Nidavellir -- events local players_loading = {} Event.register(defines.events.on_tick, function( event ) local _new_list = {} for _, _player in pairs(players_loading) do if Midgard.surface.is_chunk_generated( Chunk.from_position( _player.position ) ) then if _player.gui.center.loadingscreen then _player.gui.center.loadingscreen.destroy() end Worlds.teleportTo( Midgard, _player ) else -- update loading screen if not _player.gui.center.loadingscreen then _player.gui.center.add( {type="label", name="loadingscreen", caption="Additional Loading... please do no touch the controls"} ) end table.insert( _new_list, _player ) end end players_loading = _new_list end) Event.register(defines.events.on_player_created, function(event) local player = game.players[event.player_index] if player.surface.name == "nauvis" then Midgard.surface.request_to_generate_chunks( Chunk.from_position( player.position ), 4 ) table.insert( players_loading, player ) end end)
mit