content
stringlengths
5
1.05M
---------------------------- -- @file utils.lua -- @brief -- @author yingx -- @date 2019-08-15 ---------------------------- --执行随机种子 math.randomseed(ngx.now()) local invalid_mobile_id = { ["000000000000000"] = 1, ["111111111111111"] = 1, ["012345678912345"] = 1, ["null"] = 1, ["null_imei"] = 1, ["9774d56d682e549c"] = 1, ["00:00:00:00:00:00"] = 1, ["02:00:00:00:00:00"] = 1, ["00000000-0000-0000-0000-000000000000"] = 1, ["0"] = 1, ["00000000"] = 1, ["unknow"] = 1, ["unknown"] = 1, } local function filterInvalidMobileId(devid) local id = string.lower(devid) if invalid_mobile_id[id] == 1 then return "" else return devid end end local function isValidString(str) return (str ~= nil and str ~= "") end local function isValidTable(v) return (type(v) == "table") end local function genSuv() local str = ngx.localtime() local pat = { ["-"] = "", [":"] = "", [" "] = "", } str = string.gsub(str, "[%W+]", pat) local n = math.random(10000) return string.format("%s%05d", str, n) end local function generateImpId(pid) local id local n = #pid if n <= 8 then id = string.rep("0", 8 - n) id = id .. pid else id = string.sub(pid, 1, 8) end local str = '0123456789abcdef' for i = 1, 24 do local r = math.random(1, 16) id = id .. string.sub(str, r, r) end return id end local function calulateRespTime(context, resp) local elaspe_time = 0 local end_time = 0 if resp and resp.header then end_time = tonumber(resp.header["Elapse-Time"] or "0") end if end_time == 0 then end_time = ngx.now() * 1000 end elaspe_time = end_time - (context.start_time or 0) if elaspe_time < 0 then elaspe_time = -1 end return elaspe_time end local _M = { filterInvalidMobileId = filterInvalidMobileId, isValidString = isValidString, isValidTable = isValidTable, genSuv = genSuv, generateImpId = generateImpId, calulateRespTime = calulateRespTime, } return _M
#!/usr/bin/env lua local io = require("io") local from, tover = ... if not from or not tover then print("Format: prepareNextRelease.lua <from-tag> <tover-tag>") return end local f = assert(io.open("docs/ReleaseNotes-" .. tover .. ".txt", "w")) local headLine = "luajson v" .. tover .. " Release Notes" f:write(headLine, "\n", ("="):rep(#headLine), "\n\n") f:write([[ User Visible Changes -------------------- Plans for next release ---------------------- ]]) local tailLine = "Updates since " .. from f:write(tailLine, "\n", ("="):rep(#tailLine), "\n\n") local data = assert(io.popen("git shortlog " .. from .. "..HEAD | util/processShortlog.lua", "r")) local tail = data:read("*a") data:close() f:write(tail) f:close()
local sonic_screwdriver_max_charge = 200000 local S = technic.getter technic.register_power_tool("technic:sonic_screwdriver", sonic_screwdriver_max_charge) -- screwdriver handler code reused from minetest/minetest_game screwdriver @a9ac480 local ROTATE_FACE = 1 local ROTATE_AXIS = 2 local function nextrange(x, max) x = x + 1 if x > max then x = 0 end return x end -- Handles rotation local function screwdriver_handler(itemstack, user, pointed_thing, mode) if pointed_thing.type ~= "node" then return end local pos = pointed_thing.under if minetest.is_protected(pos, user:get_player_name()) then minetest.record_protection_violation(pos, user:get_player_name()) return end local node = minetest.get_node(pos) local ndef = minetest.registered_nodes[node.name] if not ndef or not ndef.paramtype2 == "facedir" or (ndef.drawtype == "nodebox" and not ndef.node_box.type == "fixed") or node.param2 == nil then return end -- contrary to the default screwdriver, do not check for can_dig, to allow rotating machines with CLU's in them -- this is consistent with the previous sonic screwdriver local meta1 = minetest.deserialize(itemstack:get_metadata()) if not meta1 or not meta1.charge or meta1.charge < 100 then return end minetest.sound_play("technic_sonic_screwdriver", {pos = pos, gain = 0.3, max_hear_distance = 10}) -- Set param2 local rotationPart = node.param2 % 32 -- get first 4 bits local preservePart = node.param2 - rotationPart local axisdir = math.floor(rotationPart / 4) local rotation = rotationPart - axisdir * 4 if mode == ROTATE_FACE then rotationPart = axisdir * 4 + nextrange(rotation, 3) elseif mode == ROTATE_AXIS then rotationPart = nextrange(axisdir, 5) * 4 end node.param2 = preservePart + rotationPart minetest.swap_node(pos, node) if not technic.creative_mode then meta1.charge = meta1.charge - 100 itemstack:set_metadata(minetest.serialize(meta1)) technic.set_RE_wear(itemstack, meta1.charge, sonic_screwdriver_max_charge) end return itemstack end minetest.register_tool("technic:sonic_screwdriver", { description = S("Sonic Screwdriver (left-click rotates face, right-click rotates axis)"), inventory_image = "technic_sonic_screwdriver.png", wear_represents = "technic_RE_charge", on_refill = technic.refill_RE_charge, on_use = function(itemstack, user, pointed_thing) screwdriver_handler(itemstack, user, pointed_thing, ROTATE_FACE) return itemstack end, on_place = function(itemstack, user, pointed_thing) screwdriver_handler(itemstack, user, pointed_thing, ROTATE_AXIS) return itemstack end, }) minetest.register_craft({ output = "technic:sonic_screwdriver", recipe = { {"", "mcl_core:diamond", ""}, {"technic:carbon_plate", "technic:battery", "technic:carbon_plate"}, {"technic:carbon_plate", "mcl_core:iron_ingot", "technic:carbon_plate"} } })
-- VARIABLE INITIALIZATION local thismod = minetest.get_current_modname() local modpath = minetest.get_modpath(thismod) old_expansion = { growNodes = {"default:dirt","default:dirt_with_grass","default:dirt_with_snow"}, growthSources = {}, schems = {}, types = { logs = {"cinnamon", "paperbark"}} } old_expansion.growthSources.names = {"default:dirt", "default:dirt_with_grass", "default:water_source", "default:water_flowing", "default:ice", "default:dirt_with_snow",} old_expansion.growthSources.values = {6, 4, 4, 3, -6, 2} -- FILES TO RUN dofile(modpath.."/support.lua") dofile(modpath.."/nodereg.lua") dofile(modpath.."/itemreg.lua") dofile(modpath.."/framework.lua") --dofile(modpath.."/depends.txt")
-- Add the path to the draggin lua files. -- When building for release you won't/can't do it this way. You should copy the src/draggin -- directory into your program's main directory. package.path = package.path .. ';' .. os.getenv("DRAGGIN_FRAMEWORK") .. '/src/?.lua'
kata = {} function kata.save(sizes, hd) local sum = 0 for index = 1, #sizes do sum = sum + sizes[index] if sum > hd then return index - 1 end end return #sizes end return kata
--[[ Lua --]] local version, name; name = "lua_playground"; version = nil; print(name)
local menu_service = require('services/menu') local net_service = require('services/net') return function() menu_service.load('main-menu') net_service.disconnect() end
local json = require("misc.libs.json") -- JSON Library -- Write command to file; then send signal to python script local function focusTab(id) awful.spawn.with_shell('echo "focusTab ' .. id .. '" >> /tmp/ff-tabs-input; kill -s SIGUSR1 $(pgrep server.py)') end local function removeTab(id) awful.spawn.with_shell('echo "removeTab ' .. id .. '" >> /tmp/ff-tabs-input; kill -s SIGUSR1 $(pgrep server.py)') end local function forceUpdate() awful.spawn.with_shell('echo "fullUpdate" >> /tmp/ff-tabs-input; kill -s SIGUSR1 $(pgrep server.py)') end local function trimLong(t, m) m = m or 20 if #t > m then return t:sub(0, m) else return t end end local function fullClean(list) for _, tab in ipairs(list.children) do local x = tab:get_children_by_id("background_")[1].iconPath if x then awful.spawn("rm " .. x) end end end local function setFavicon(widget, url) local image_widget = widget:get_children_by_id("icon")[1] local bg_widget = widget:get_children_by_id("background_")[1] -- If is base64 encoded image file if string.find(url or "", "data:image/%S+base64,") then local path = os.tmpname() local image = url:gsub("data:image/%S+;base64,", "") awful.spawn.easy_async_with_shell("echo '" .. image .. "' | base64 -d >> " .. path, function(_, err) image_widget.image = path bg_widget.iconPath = path bg_widget.iconId = image:sub(0, 25) if string.len(err) > 0 then print("ERROR:", err) end end) else image_widget.image = _config_dir .. "theme/assets/site.svg" end end local focusBG = "#c5c8c6" local focusFG = "#1d1f21" -- local unFocusFG = "#e0e0e0" --local unFocusBG = "#00000000" local function getIcon(tab) local iconWidget = wibox.widget({ { { { { { { widget = wibox.widget.imagebox, scaling_quality = "best", id = "icon", }, widget = wibox.container.constraint, width = dpi(20), height = dpi(20), }, widget = wibox.container.place, halign = "center", valign = "center", }, { { widget = wibox.widget.textbox, text = trimLong(tab.title or ""), font = "PT Sans", valign = "center", visible = tab.active or false, -- If active show, otherwise dont id = "title", }, widget = wibox.container.margin, left = dpi(5), }, layout = wibox.layout.fixed.horizontal, }, widget = wibox.container.margin, top = dpi(5), left = dpi(8), right = dpi(8), bottom = dpi(5), }, widget = wibox.container.background, bg = tab.active and focusBG or "#00000000", active = tab.active, shape = function(cr, w, h) gears.shape.rounded_rect(cr, w, h, 5) end, buttons = gears.table.join( awful.button({}, mouse.LEFT, function() focusTab(tab.id) end), awful.button({}, mouse.RIGHT, function() removeTab(tab.id) end) ), id = "background_", tabId = tab.id, fg = focusFG, }, widget = wibox.container.place, halign = "center", valign = "center", }) setFavicon(iconWidget, tab.favIconUrl) return iconWidget end -- Setup local export = {} function export.x(c) -- Ignore windows that arent firefox! if c.class ~= "Firefox-esr" then return nil end if client.focus ~= c then print("Client isnt focused!") focusBG = "#282a2e" focusFG = "#e0e0e0" end -- Container local list = wibox.widget({ layout = wibox.layout.fixed.horizontal, spacing = dpi(5), }) -- Setup Connections awesome.connect_signal("custom::update_ff_focused", function(id) for _, child in ipairs(list.children) do local x = child:get_children_by_id("background_")[1] if x.tabId == id then -- if is the selected tab x.bg = focusBG child:get_children_by_id("title")[1].visible = true x.active = true else child:get_children_by_id("title")[1].visible = false x.bg = unFocusBG x.active = false end end end) -- Attempt to re-connect with firefox (mostly for awm restarts!) gears.timer({ timeout = 5, autostart = true, single_shot = true, callback = function() if #list.children == 0 then forceUpdate() end end, }) -- Full Update awesome.connect_signal("custom::update_ff_tabs", function(out) local firefoxTabs = json.decode(out) -- Might not be needed, since this is usually run at the start and the list is empty fullClean(list) list:reset() for _, tab in ipairs(firefoxTabs) do list:add(getIcon(tab)) end end) -- Before Exit / Restart awesome.connect_signal("exit", function() fullClean(list) end) -- Remove Specific Tab awesome.connect_signal("custom::remove_ff_tab", function(id) for idx, tab in ipairs(list.children) do local x = tab:get_children_by_id("background_")[1] if x.tabId == id then if x.iconPath then awful.spawn("rm " .. x.iconPath) end list:remove(idx) end end end) -- New Tab awesome.connect_signal("custom::add_ff_tab", function(payload) local tab = json.decode(payload) list:add(getIcon(tab)) end) -- Update Tab Icon / URL / Etc awesome.connect_signal("custom::update_ff_tab", function(payload) local tab = json.decode(payload) iconId = nil if string.find(tab.favIconUrl, "data:image/%S+base64,") then iconId = (tab.favIconUrl or ""):gsub("data:image/%S+;base64,", "") iconId = string.sub(iconId, 0, 25) end for idx, child in ipairs(list.children) do local x = child:get_children_by_id("background_")[1] -- Check if tab id matches if x.tabId == tab.id then -- and then check if icon has been changed, if not ignore! if iconId and x.iconId ~= iconId then if x.iconPath then awful.spawn("rm " .. x.iconPath) end list:set(idx, getIcon(tab)) end -- if tab is focused, everything else reverts! elseif tab.active then x.bg = unFocusBG end end end) local final = wibox.widget({ { list, widget = wibox.container.margin, top = dpi(5), left = dpi(5), right = dpi(5), bottom = dpi(5), }, widget = wibox.container.background, bg = "#00000000", }) c:connect_signal("unfocus", function() focusBG = "#282a2e" focusFG = "#e0e0e0" for _, tab in ipairs(list.children) do local bg = tab:get_children_by_id("background_")[1] bg.fg = focusFG if bg.active == true then -- is tab focused? bg.bg = focusBG else bg.bg = "#00000000" end end end) c:connect_signal("focus", function() focusBG = "#c5c8c6" focusFG = "#1d1f21" for _, tab in ipairs(list.children) do local bg = tab:get_children_by_id("background_")[1] bg.fg = focusFG if bg.active == true then -- is tab focused? bg.bg = focusBG else bg.bg = "#00000000" end end end) return final end --[[ Add ff-tabs-indicator widget when firefox is active and when it isnt remove it! TODO: Add support for running multiple instances of firefox! --]] function export.attach() local ll client.connect_signal("focus", function(c) if c.class == "Firefox-esr" then ll = ll or export.x(c) mouse.screen.left_mod:add(ll) end end) client.connect_signal("unfocus", function(c) if c.class == "Firefox-esr" then mouse.screen.left_mod:remove(#mouse.screen.left_mod.children) end end) end return export
--[[ Replacement tool for creative building (Mod for MineTest) Copyright (C) 2013 Sokomine This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] -- Version 3.0 -- Changelog: -- 09.12.2017 * Got rid of outdated minetest.env -- * Fixed error in protection function. -- * Fixed minor bugs. -- * Added blacklist -- 02.10.2014 * Some more improvements for inspect-tool. Added craft-guide. -- 01.10.2014 * Added inspect-tool. -- 12.01.2013 * If digging the node was unsuccessful, then the replacement will now fail -- (instead of destroying the old node with its metadata; i.e. chests with content) -- 20.11.2013 * if the server version is new enough, minetest.is_protected is used -- in order to check if the replacement is allowed -- 24.04.2013 * param1 and param2 are now stored -- * hold sneak + right click to store new pattern -- * right click: place one of the itmes -- * receipe changed -- * inventory image added -- adds a function to check ownership of a node; taken from VanessaEs homedecor mod dofile(minetest.get_modpath("replacer").."/check_owner.lua"); replacer = {}; replacer.blacklist = {}; -- playing with tnt and creative building are usually contradictory -- (except when doing large-scale landscaping in singleplayer) replacer.blacklist[ "tnt:boom"] = true; replacer.blacklist[ "tnt:gunpowder"] = true; replacer.blacklist[ "tnt:gunpowder_burning"] = true; replacer.blacklist[ "tnt:tnt"] = true; -- prevent accidental replacement of your protector replacer.blacklist[ "protector:protect"] = true; replacer.blacklist[ "protector:protect2"] = true; -- adds a tool for inspecting nodes and entities dofile(minetest.get_modpath("replacer").."/inspect.lua"); -- add HUD support for tool information dofile(minetest.get_modpath("replacer").."/hud.lua") minetest.register_tool( "replacer:replacer", { description = "Node replacement tool", groups = {}, inventory_image = "replacer_replacer.png", wield_image = "", wield_scale = {x=1,y=1,z=1}, stack_max = 1, -- it has to store information - thus only one can be stacked liquids_pointable = true, -- it is ok to painit in/with water --[[ -- the tool_capabilities are of nearly no intrest here tool_capabilities = { full_punch_interval = 1.0, max_drop_level=0, groupcaps={ -- For example: fleshy={times={[2]=0.80, [3]=0.40}, maxwear=0.05, maxlevel=1}, snappy={times={[2]=0.80, [3]=0.40}, maxwear=0.05, maxlevel=1}, choppy={times={[3]=0.90}, maxwear=0.05, maxlevel=0} } }, --]] node_placement_prediction = nil, metadata = "default:dirt", -- default replacement: common dirt on_place = function(itemstack, placer, pointed_thing) if( placer == nil or pointed_thing == nil) then return itemstack; -- nothing consumed end local name = placer:get_player_name(); --minetest.chat_send_player( name, "You PLACED this on "..minetest.serialize( pointed_thing ).."."); local keys=placer:get_player_control(); -- just place the stored node if now new one is to be selected if( not( keys["sneak"] )) then return replacer.replace( itemstack, placer, pointed_thing, 0 ); end if( pointed_thing.type ~= "node" ) then -- minetest.chat_send_player( name, " Error: No node selected."); replacer.set_hud(name, " Error: No node selected."); return nil; end local pos = minetest.get_pointed_thing_position( pointed_thing, under ); local node = minetest.get_node_or_nil( pos ); --minetest.chat_send_player( name, " Target node: "..minetest.serialize( node ).." at pos "..minetest.serialize( pos ).."."); local metadata = "default:dirt 0 0"; if( node ~= nil and node.name ) then metadata = node.name..' '..node.param1..' '..node.param2; end itemstack:set_metadata( metadata ); --minetest.chat_send_player( name, "Node replacement tool set to: '"..metadata.."'."); replacer.set_hud(name, "Node replacement tool set to: '"..metadata.."'."); return itemstack; -- nothing consumed but data changed end, -- on_drop = func(itemstack, dropper, pos), on_use = function(itemstack, user, pointed_thing) return replacer.replace( itemstack, user, pointed_thing, above ); end, }) replacer.replace = function( itemstack, user, pointed_thing, mode ) if( user == nil or pointed_thing == nil) then return nil; end local name = user:get_player_name(); --minetest.chat_send_player( name, "You USED this on "..minetest.serialize( pointed_thing ).."."); if( pointed_thing.type ~= "node" ) then --minetest.chat_send_player( name, " Error: No node."); replacer.set_hud(name, " Error: No node."); return nil; end local pos = minetest.get_pointed_thing_position( pointed_thing, mode ); local node = minetest.get_node_or_nil( pos ); --minetest.chat_send_player( name, " Target node: "..minetest.serialize( node ).." at pos "..minetest.serialize( pos ).."."); if( node == nil ) then --minetest.chat_send_player( name, "Error: Target node not yet loaded. Please wait a moment for the server to catch up."); replacer.set_hud(name, "Error: Target node not yet loaded. Please wait a moment for the server to catch up."); return nil; end local item = itemstack:to_table(); -- make sure it is defined if( not( item[ "metadata"] ) or item["metadata"]=="" ) then item["metadata"] = "default:dirt 0 0"; end -- regain information about nodename, param1 and param2 local daten = item[ "metadata"]:split( " " ); -- the old format stored only the node name if( #daten < 3 ) then daten[2] = 0; daten[3] = 0; end -- if someone else owns that node then we can not change it if( replacer_homedecor_node_is_owned(pos, user)) then return nil; end if( node.name and node.name ~= "" and replacer.blacklist[ node.name ]) then --minetest.chat_send_player( name, "Replacing blocks of the type '"..( node.name or "?" ).. --"' is not allowed on this server. Replacement failed."); replacer.set_hud( name, "Replacing blocks of the type '"..( node.name or "?" ).. "' is not allowed on this server. Replacement failed."); return nil; end if( replacer.blacklist[ daten[1] ]) then -- minetest.chat_send_player( name, "Placing blocks of the type '"..( daten[1] or "?" ).. --"' with the replacer is not allowed on this server. Replacement failed."); replacer.set_hud( name, "Placing blocks of the type '"..( daten[1] or "?" ).. "' with the replacer is not allowed on this server. Replacement failed."); return nil; end -- do not replace if there is nothing to be done if( node.name == daten[1] ) then -- the node itshelf remains the same, but the orientation was changed if( node.param1 ~= daten[2] or node.param2 ~= daten[3] ) then minetest.add_node( pos, { name = node.name, param1 = daten[2], param2 = daten[3] } ); end return nil; end -- in survival mode, the player has to provide the node he wants to place if( not(minetest.settings:get_bool("creative_mode") ) and not( minetest.check_player_privs( name, {creative=true}))) then -- players usually don't carry dirt_with_grass around; it's safe to assume normal dirt here -- fortunately, dirt and dirt_with_grass does not make use of rotation if( daten[1] == "default:dirt_with_grass" ) then daten[1] = "default:dirt"; item["metadata"] = "default:dirt 0 0"; end -- does the player carry at least one of the desired nodes with him? if( not( user:get_inventory():contains_item("main", daten[1]))) then --minetest.chat_send_player( name, "You have no further '"..( daten[1] or "?" ).."'. Replacement failed."); replacer.set_hud(name, "You have no further '"..( daten[1] or "?" ).."'. Replacement failed."); return nil; end -- give the player the item by simulating digging if possible if( node.name ~= "air" and node.name ~= "ignore" and node.name ~= "default:lava_source" and node.name ~= "default:lava_flowing" and node.name ~= "default:river_water_source" and node.name ~= "default:river_water_flowing" and node.name ~= "default:water_source" and node.name ~= "default:water_flowing" ) then minetest.node_dig( pos, node, user ); local digged_node = minetest.get_node_or_nil( pos ); if( not( digged_node ) or digged_node.name == node.name ) then --minetest.chat_send_player( name, "Replacing '"..( node.name or "air" ).."' with '"..( item[ "metadata"] or "?" ).."' failed. Unable to remove old node."); replacer.set_hud(name, "Replacing '"..( node.name or "air" ).."' with '"..( item[ "metadata"] or "?" ).."' failed. Unable to remove old node."); return nil; end end -- consume the item user:get_inventory():remove_item("main", daten[1].." 1"); --user:get_inventory():add_item( "main", node.name.." 1"); end --minetest.chat_send_player( name, "Replacing node '"..( node.name or "air" ).."' with '"..( item[ "metadata"] or "?" ).."'."); --minetest.place_node( pos, { name = item[ "metadata" ] } ); minetest.add_node( pos, { name = daten[1], param1 = daten[2], param2 = daten[3] } ); return nil; -- no item shall be removed from inventory end minetest.register_craft({ output = 'replacer:replacer', recipe = { { 'default:chest', '', '' }, { '', 'default:stick', '' }, { '', '', 'default:chest' }, } })
local presetMessages = { ["SIGN"] = "You have joined the league!", ["ASIGN"] = "You have already joined the league!", ["INPROG"] = "The league is already in progress.", } local player = Game.GetLocalPlayer() function OnReceivedMessage(message, color) if presetMessages[message] ~= nil then message = presetMessages[message] end UI.ShowFlyUpText(message, player:GetWorldPosition() + Vector3.UP * 100, { isBig = true, color = color or Color.WHITE, duration = 3, }) end Events.Connect("RPS_PMP", OnReceivedMessage)
ITEM.name = "Marijuana Joint" ITEM.description = "A rolled up cigarette featuring marijuana instead of tobacco." ITEM.model = Model("models/mosi/fallout4/props/junk/cigar.mdl") ITEM.category = "Drugs" ITEM.width = 1 ITEM.height = 1 ITEM.chance = 55 ITEM.functions.Consume = { OnRun = function(itemTable) local client = itemTable.player client:GetCharacter():AddBoost("buff", "str", 20) client:GetCharacter():AddBoost("debuff", "int", -20) client:SetHealth(math.Clamp(client:Health() - 10, 0, client:GetMaxHealth())) hook.Run("SetupDrugTimer", client, client:GetCharacter(), 180) --Seconds end }
local Modules = game:GetService("Players").LocalPlayer.PlayerGui.AvatarEditorInGame.Modules local Rodux = require(Modules.Packages.Rodux) local IncrementTryOnCharacterModelVersion = require(Modules.AvatarExperience.Catalog.Actions.IncrementTryOnCharacterModelVersion) return Rodux.createReducer(0, { [IncrementTryOnCharacterModelVersion.name] = function(state, action) return state + 1 end, })
--Point --author: SukaiPoppuGo if not _POSAPI and not os.loadAPI("/api/pos/turtle.lua") then error("Pos API required", 2) return end if not utils then os.loadAPI("/api/utils.lua") end -- shortcuts local _abs = math.abs local _pow = math.pow local _max = math.max local _min = math.min local _sqrt = math.sqrt local _rep = string.rep local _len = string.len -- _G.Point = {} Point.__index = Point Point.new = function(self, x, y, z) local o = {} local rx, ry, rz = getPos() setmetatable(o, Point) o.type = "Point" o.x = utils.parseCoords(x, rx) o.y = utils.parseCoords(y, ry) o.z = utils.parseCoords(z, rz) return o end Point.__add = function(A, B) return Point:new(A.x + B.x, A.y + B.y, A.z + B.z) end Point.__sub = function(A, B) return Point:new(A.x - B.x, A.y - B.y, A.z - B.z) end Point.__eq = function(A, B) return A.x == B.x and A.y == B.y and A.z == B.z end Point.__lt = function(A, B) -- < return A:distance() < B:distance() end Point.__le = function(A, B) -- <= return A:distance() <= B:distance() end Point.__concat = function(self) return "{"..self.x..","..self._y..","..self._z.."}" end Point.__tostring = function(self) local _x = _rep(" ", _max(0, 5 - _len(self.x)))..self.x local _y = _rep(" ", _max(0, 5 - _len(self.y)))..self.y local _z = _rep(" ", _max(0, 5 - _len(self.z)))..self.z return "{".._x..",".._y..",".._z.."}" end Point.fuelCost = function (A, B) B = B and B or getPos(true) --print("") --print("_abs(B.x - A.x) + _abs(B.y - A.y) + _abs(B.z - A.z)") --print(string.format("(%s) B = (%s) %s, (%s) %s, (%s) %s", type(B), type(B.x), tostring(B.x), type(B.y), tostring(B.y), type(B.z), tostring(B.z))) --print(string.format("(%s) A = (%s) %s, (%s) %s, (%s) %s", type(A), type(A.x), tostring(A.x), type(A.y), tostring(A.y), type(A.z), tostring(A.z))) return _abs(B.x - A.x) + _abs(B.y - A.y) + _abs(B.z - A.z) end Point.distance = function (A, B) B = B and B or getPos(true) return _sqrt(_pow(B.x - A.x, 2) + _pow(B.y - A.y, 2) + _pow(B.z - A.z, 2)) end Point.size = function(A, B) return _abs(B.x - A.x) + 1, _abs(B.y - A.y) + 1, _abs(B.z - A.z) + 1 end Point.volume = function(A, B) local _x, _y, _z = A:size(B) return _x * _y * _z end
if matches[2] then dx.mining:goProspect(matches[3]) else dx.mining:goProspect() end
vim.g.nvim_tree_icons = { default = "", symlink = "", git = { unstaged = "", staged = "S", unmerged = "", renamed = "➜", deleted = "", untracked = "U", ignored = "◌", }, folder = { default = "", open = "", empty = "", empty_open = "", symlink = "", }, } vim.g.nvim_tree_indent_markers = 1 -- 0 by default, this option shows indent markers when folders are open vim.g.nvim_tree_git_hl = 1 -- 0 by default, will enable file highlight for git attributes (can be used without the icons). vim.g.nvim_tree_highlight_opened_files = 1 -- 0 by default, will enable folder and file icon highlight for opened files/directories. local nvim_tree = require "nvim-tree" local nvim_tree_config = require "nvim-tree.config" nvim_tree.setup { disable_netrw = true, hijack_netrw = true, ignore_ft_on_setup = {}, auto_close = true, open_on_tab = false, update_cwd = true, diagnostics = { enable = true, icons = { hint = "", info = "", warning = "", error = "", } }, update_focused_file = { enable = true, update_cwd = true, ignore_list = {} }, filters = { dotfiles = false, custom = {} }, git = { enable = true, ignore = true, timeout = 500, }, view= { width = 30, height = 30, hide_root_folder = false, side = 'left', auto_resize = true, preserve_window_proportions = true, mappings = { custom_only = false, -- In app key maps list = { { key = "h", cb = nvim_tree_config.nvim_tree_callback "close_node" }, -- to collapse expanded nodes } }, number = false, relativenumber = false, signcolumn = "yes" }, trash = { cmd = "trash", require_confirm = true }, } -------------------- Default actions reference ---------------------------------------------------------------------- -- <CR> or o on the root folder will cd in the above directory -- <C-]> will cd in the directory under the cursor -- <BS> will close current opened directory or parent -- type a to add a file. Adding a directory requires leaving a leading / at the end of the path. -- you can add multiple directories by doing foo/bar/baz/f and it will add foo bar and baz directories and f as a file -- type r to rename a file -- type <C-r> to rename a file and omit the filename on input -- type x to add/remove file/directory to cut clipboard -- type c to add/remove file/directory to copy clipboard -- type y will copy name to system clipboard -- type Y will copy relative path to system clipboard -- type gy will copy absolute path to system clipboard -- type p to paste from clipboard. Cut clipboard has precedence over copy (will prompt for confirmation) -- type d to delete a file (will prompt for confirmation) -- type D to trash a file (configured in setup()) -- type ]c to go to next git item -- type [c to go to prev git item -- type - to navigate up to theparent directory of the current file/directory -- type s to open a file with default system application or a folder with default file manager (if you want to change the command used to do it see :h nvim-tree.setup under system_open) -- if the file is a directory, <CR> will open the directory otherwise it will open the file in the buffer near the tree -- if the file is a symlink, <CR> will follow the symlink (if the target is a file) -- <C-v> will open the file in a vertical split -- <C-x> will open the file in a horizontal split -- <C-t> will open the file in a new tab -- <Tab> will open the file as a preview (keeps the cursor in the tree) -- I will toggle visibility of hidden folders / files -- H will toggle visibility of dotfiles (files/folders starting with a .) -- R will refresh the tree -- Double left click acts like <CR> -- Double right click acts like <C-]> -- W will collapse the whole tree -- S will prompt the user to enter a path and then expands the tree to match the path -- . will enter vim command mode with the file the cursor is on -- C-k will toggle a popup with file infos about the file under the cursor
local getChildrenArrayByLevelIndex getChildrenArrayByLevelIndex = function (id, level, index, limit, offset, children, result) level = level - 1 -- current level = maxlevel - level local value = redis.call('get', prefix .. id) if not value then return result end local list = cmsgpack.unpack(value) for i, v in ipairs(list) do local cid = v[1] local hasChild = v[2] -- Should be an array local item = { cid, hasChild } if hasChild ~= 0 and level ~= 0 then if (cid == id) then -- If child ID == current node return redis.error_reply("ERR infinite loop found in 'tchildrenarray' command") end getChildrenArrayByLevelIndex(cid, level, index, limit, offset, children, item) if #item == 2 then v[2] = 0 end end if result then result[#result + 1] = item end if level == 0 and #children ~= limit then -- and index >= offset then -- if this is the level we're looking for children[#children + 1] = cid end if level == 0 then -- if this is the level we're looking for index = index + 1 end end return result end local level = 1 local limit = 50 local offset = 0 local flowover = 'true' local index = 0 if ARGV[2] then if string.upper(ARGV[2]) == 'LEVEL' then if not ARGV[3] then return redis.error_reply("ERR wrong number of arguments for 'tchildrenarray' command") end level = tonumber(ARGV[3]) end end if ARGV[4] then if string.upper(ARGV[4]) == 'LIMIT' then if not ARGV[5] then return redis.error_reply("ERR wrong number of arguments for 'tchildrenarray' command") end limit = tonumber(ARGV[5]) end end if ARGV[6] then if string.upper(ARGV[6]) == 'OFFSET' then if not ARGV[7] then return redis.error_reply("ERR wrong number of arguments for 'tchildrenarray' command") end offset = tonumber(ARGV[7]) end end if ARGV[8] then if string.upper(ARGV[8]) == 'FLOWOVER' then if not ARGV[9] then return redis.error_reply("ERR wrong number of arguments for 'tchildrenarray' command") end flowover = ARGV[9] end end if level == 0 then return nil end -- getChildrenArrayByLevelIndex( -- currentid, // ID of the node (USER SET) -- currentlevel, // Current level reverse index doubles as max level (USER SET) -- index, // Current index of the node in a flat array (NON-USER SET) -- limit, // Max number of nodes to return (USER SET) -- offset, // Offset to start placing nodes in array (USER SET) -- flowover, // Whether to continue after hitting the maxlevel (USER SET) -- Result) // An array local result = {} getChildrenArrayByLevelIndex(id, level, index, limit, offset, result, {}) while #result ~= limit and flowover == 'true' do local size = #result level = level + 1 getChildrenArrayByLevelIndex(id, level, index, limit, offset, result) if size == #result then -- we've hit the end return result end end return result
RECIPE.name = "Manhack" RECIPE.description = "recipeManhackDesc" RECIPE.category = "Assembly" RECIPE.model = "models/manhack.mdl" RECIPE.requirements = { ["manhack_gib01"] = 1, ["manhack_gib02"] = 1, ["manhack_gib03"] = 1, ["manhack_gib04"] = 1, ["manhack_gib05"] = 2, } RECIPE.results = { ["manhack"] = 1 } RECIPE:PostHook("OnCanCraft", function(recipeTable, client) for _, v in pairs(ents.FindByClass("ix_station_workbench")) do if (client:GetPos():DistToSqr(v:GetPos()) < 100 * 100) then return true end end return false, L("noWorkbench") end)
local EventRegistry = {} local EventRegistry_mt = { __index = EventRegistry } function EventRegistry:Create(frame) local event_registry = {} setmetatable(event_registry, EventRegistry_mt) event_registry:Initialize(frame) return event_registry end function EventRegistry:Initialize(frame) self.frame = CreateFrame("Frame", "EventRegistry", frame) self.frame.owner = self self.frame:SetScript("OnEvent", EventRegistry.OnEvent) self.registry = {} self.events_by_unit = {} end function EventRegistry:OnEvent(event, unit) self = self.owner if unit and unit ~= "player" and unit ~= "target" then return end local escaped_unit = unit or "nil" if not self.events_by_unit[unit] then self.events_by_unit[escaped_unit] = {} end self.events_by_unit[escaped_unit][event] = true end function EventRegistry:Run() for unit, events in pairs(self.events_by_unit) do local unescaped_unit = unit == "nil" and nil or unit for event, _ in pairs(events) do for entry, _ in pairs(self.registry[event] or {}) do entry.callback(entry.spell, event, unescaped_unit) end end end self.events_by_unit = {} end function EventRegistry:Register(event, spell, callback) if not self.registry[event] then self.registry[event] = {} self.frame:RegisterEvent(event) end entry = { callback = callback, spell = spell } self.registry[event][entry] = true end function EventRegistry:Unregister(spell) for event, spells in pairs(self.registry) do for entry, _ in pairs(spells) do if entry.spell == spell then spells[entry] = nil end end end end GuiBarHero.EventRegistry = EventRegistry
--[[ Strict variable declarations for Lua 5.1, 5.2 & 5.3 Copyright(C) 2014-2021 Gary V. Vaughan Copyright(C) 2010-2014 Reuben Thomas <rrt@sc3d.org> Copyright(C) 2006-2011 Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> ]] --[[-- Diagnose uses of undeclared variables. All variables(including functions!) must be "declared" through a regular assignment(even assigning `nil` will do) in a strict scope before being used anywhere or assigned to inside a nested scope. Use the callable returned by this module to interpose a strictness check proxy table to the given environment. The callable runs `setfenv` appropriately in Lua 5.1 interpreters to ensure the semantic equivalence. @module std.strict ]] local _ENV = { error = error, getmetatable = getmetatable, pairs = pairs, setfenv = setfenv or function() end, setmetatable = setmetatable, debug_getinfo = debug.getinfo, } setfenv(1, _ENV) --- What kind of variable declaration is this? -- @treturn string 'C', 'Lua' or 'main' local function what() local d = debug_getinfo(3, 'S') return d and d.what or 'C' end return setmetatable({ --- Module table. -- @table strict -- @string version release version identifier version = 'Strict Variable Declaration / 1.2.1-1', --- Require variable declarations before use in scope *env*. -- -- Normally the module @{strict:__call} metamethod is all you need, -- but you can use this method for more complex situations. -- @function strict -- @tparam table env lexical environment table -- @treturn table *env* proxy table with metamethods to enforce strict -- declarations -- @usage -- local _ENV = setmetatable({}, {__index = _G}) -- if require 'std.debug_init'._DEBUG.strict then -- _ENV = require 'std.strict'.strict(_ENV) -- end -- -- ...and for Lua 5.1 compatibility, without triggering undeclared -- -- variable error: -- if rawget(_G, 'setfenv') ~= nil then setfenv(1, _ENV) end strict = function(env) -- The set of declared variables in this scope. local declared = {} --- Environment Metamethods -- @section environmentmetamethods return setmetatable({}, { --- Detect dereference of undeclared variable. -- @function env:__index -- @string n name of the variable being dereferenced __index = function(_, n) local v = env[n] if v ~= nil then declared[n] = true elseif not declared[n] and what() ~= 'C' then error("variable '" .. n .. "' is not declared", 2) end return v end, --- Proxy `len` calls. -- @function env:__len -- @tparam table t strict table __len = function() local len = (getmetatable(env) or {}).__len if len then return len(env) end local n = #env for i = 1, n do if env[i] == nil then return i -1 end end return n end, --- Detect assignment to undeclared variable. -- @function env:__newindex -- @string n name of the variable being declared -- @param v initial value of the variable __newindex = function(_, n, v) local x = env[n] if x == nil and not declared[n] then local w = what() if w ~= 'main' and w ~= 'C' then error("assignment to undeclared variable '" .. n .. "'", 2) end end declared[n] = true env[n] = v end, --- Proxy `pairs` calls. -- @function env:__pairs -- @tparam table t strict table __pairs = function() return ((getmetatable(env) or {}).__pairs or pairs)(env) end, }) end, }, { --- Module Metamethods -- @section modulemetamethods --- Enforce strict variable declarations in *env*. -- @function strict:__call -- @tparam table env lexical environment table -- @tparam[opt=1] int level stack level for `setfenv`, 1 means -- set caller's environment -- @treturn table *env* which must be assigned to `_ENV` -- @usage -- local _ENV = require 'std.strict'(_G) __call = function(self, env, level) env = self.strict(env) setfenv(1 +(level or 1), env) return env end, })
GM.Name = "PeterPVP" GM.Author = "Peter Soboyejo<thepcmrtim@gmail.com>" GM.Email = "thepcmrtim@gmail.com" GM.Website = "http://petersoboyejo.com/" team.SetUp( 0, "Blue", Color(0, 0, 255) ) team.SetUp( 1, "Red", Color(255, 0, 0) ) function GM:Initialize() -- called when the gamemode is first started self.BaseClass.Initialize(self) end
local assets = { Asset("ANIM", "anim/evergreen_new.zip"), --build Asset("ANIM", "anim/evergreen_new_2.zip"), --build Asset("ANIM", "anim/evergreen_tall_old.zip"), Asset("ANIM", "anim/evergreen_short_normal.zip"), Asset("ANIM", "anim/dust_fx.zip"), Asset("SOUND", "sound/forest.fsb"), } local prefabs = { "log", "twigs", "pinecone", "charcoal", "leif", "leif_sparse", "pine_needles" } local builds = { normal = { file="evergreen_new", prefab_name="evergreen", normal_loot = {"log", "log", "pinecone"}, short_loot = {"log"}, tall_loot = {"log", "log", "log", "pinecone", "pinecone"}, drop_pinecones=true, leif="leif", }, sparse = { file="evergreen_new_2", prefab_name="evergreen_sparse", normal_loot = {"log","log"}, short_loot = {"log"}, tall_loot = {"log", "log","log"}, drop_pinecones=false, leif="leif_sparse", }, } local function makeanims(stage) return { idle="idle_"..stage, sway1="sway1_loop_"..stage, sway2="sway2_loop_"..stage, chop="chop_"..stage, fallleft="fallleft_"..stage, fallright="fallright_"..stage, stump="stump_"..stage, burning="burning_loop_"..stage, burnt="burnt_"..stage, chop_burnt="chop_burnt_"..stage, idle_chop_burnt="idle_chop_burnt_"..stage } end local short_anims = makeanims("short") local tall_anims = makeanims("tall") local normal_anims = makeanims("normal") local old_anims = { idle="idle_old", sway1="idle_old", sway2="idle_old", chop="chop_old", fallleft="chop_old", fallright="chop_old", stump="stump_old", burning="idle_olds", burnt="burnt_tall", chop_burnt="chop_burnt_tall", idle_chop_burnt="idle_chop_burnt_tall", } local function dig_up_stump(inst, chopper) inst:Remove() inst.components.lootdropper:SpawnLootPrefab("log") end local function chop_down_burnt_tree(inst, chopper) inst:RemoveComponent("workable") inst.SoundEmitter:PlaySound("dontstarve/forest/treeCrumble") inst.SoundEmitter:PlaySound("dontstarve/wilson/use_axe_tree") inst.AnimState:PlayAnimation(inst.anims.chop_burnt) RemovePhysicsColliders(inst) inst:ListenForEvent("animover", function() inst:Remove() end) inst.components.lootdropper:SpawnLootPrefab("charcoal") inst.components.lootdropper:DropLoot() if inst.pineconetask then inst.pineconetask:Cancel() inst.pineconetask = nil end end local function GetBuild(inst) local build = builds[inst.build] if build == nil then return builds["normal"] end return build end local burnt_highlight_override = {.5,.5,.5} local function OnBurnt(inst, imm) local function changes() if inst.components.burnable then inst.components.burnable:Extinguish() end inst:RemoveComponent("burnable") inst:RemoveComponent("propagator") inst:RemoveComponent("growable") inst:RemoveTag("shelter") inst:RemoveTag("dragonflybait_lowprio") inst:RemoveTag("fire") inst.components.lootdropper:SetLoot({}) if GetBuild(inst).drop_pinecones then inst.components.lootdropper:AddChanceLoot("pinecone", 0.1) end if inst.components.workable then inst.components.workable:SetWorkLeft(1) inst.components.workable:SetOnWorkCallback(nil) inst.components.workable:SetOnFinishCallback(chop_down_burnt_tree) end end if imm then changes() else inst:DoTaskInTime( 0.5, changes) end inst.AnimState:PlayAnimation(inst.anims.burnt, true) inst.AnimState:SetRayTestOnBB(true); inst:AddTag("burnt") inst.highlight_override = burnt_highlight_override end local function PushSway(inst) if math.random() > .5 then inst.AnimState:PushAnimation(inst.anims.sway1, true) else inst.AnimState:PushAnimation(inst.anims.sway2, true) end end local function Sway(inst) if math.random() > .5 then inst.AnimState:PlayAnimation(inst.anims.sway1, true) else inst.AnimState:PlayAnimation(inst.anims.sway2, true) end end local function SetShort(inst) inst.anims = short_anims if inst.components.workable then inst.components.workable:SetWorkLeft(TUNING.EVERGREEN_CHOPS_SMALL) end -- if inst:HasTag("shelter") then inst:RemoveTag("shelter") end inst.components.lootdropper:SetLoot(GetBuild(inst).short_loot) Sway(inst) end local function GrowShort(inst) inst.AnimState:PlayAnimation("grow_old_to_short") inst.SoundEmitter:PlaySound("dontstarve/forest/treeGrowFromWilt") PushSway(inst) end local function SetNormal(inst) inst.anims = normal_anims if inst.components.workable then inst.components.workable:SetWorkLeft(TUNING.EVERGREEN_CHOPS_NORMAL) end -- if inst:HasTag("shelter") then inst:RemoveTag("shelter") end inst.components.lootdropper:SetLoot(GetBuild(inst).normal_loot) Sway(inst) end local function GrowNormal(inst) inst.AnimState:PlayAnimation("grow_short_to_normal") inst.SoundEmitter:PlaySound("dontstarve/forest/treeGrow") PushSway(inst) end local function SetTall(inst) inst.anims = tall_anims if inst.components.workable then inst.components.workable:SetWorkLeft(TUNING.EVERGREEN_CHOPS_TALL) end -- inst:AddTag("shelter") inst.components.lootdropper:SetLoot(GetBuild(inst).tall_loot) Sway(inst) end local function GrowTall(inst) inst.AnimState:PlayAnimation("grow_normal_to_tall") inst.SoundEmitter:PlaySound("dontstarve/forest/treeGrow") PushSway(inst) end local function SetOld(inst) inst.anims = old_anims if inst.components.workable then inst.components.workable:SetWorkLeft(1) end if GetBuild(inst).drop_pinecones then inst.components.lootdropper:SetLoot({"pinecone"}) else inst.components.lootdropper:SetLoot({}) end Sway(inst) end local function GrowOld(inst) inst.AnimState:PlayAnimation("grow_tall_to_old") inst.SoundEmitter:PlaySound("dontstarve/forest/treeWilt") PushSway(inst) end local function inspect_tree(inst) if inst:HasTag("burnt") then return "BURNT" elseif inst:HasTag("stump") then return "CHOPPED" end end local growth_stages = { {name="short", time = function(inst) return GetRandomWithVariance(TUNING.EVERGREEN_GROW_TIME[1].base, TUNING.EVERGREEN_GROW_TIME[1].random) end, fn = function(inst) SetShort(inst) end, growfn = function(inst) GrowShort(inst) end , leifscale=.7 }, {name="normal", time = function(inst) return GetRandomWithVariance(TUNING.EVERGREEN_GROW_TIME[2].base, TUNING.EVERGREEN_GROW_TIME[2].random) end, fn = function(inst) SetNormal(inst) end, growfn = function(inst) GrowNormal(inst) end, leifscale=1 }, {name="tall", time = function(inst) return GetRandomWithVariance(TUNING.EVERGREEN_GROW_TIME[3].base, TUNING.EVERGREEN_GROW_TIME[3].random) end, fn = function(inst) SetTall(inst) end, growfn = function(inst) GrowTall(inst) end, leifscale=1.25 }, {name="old", time = function(inst) return GetRandomWithVariance(TUNING.EVERGREEN_GROW_TIME[4].base, TUNING.EVERGREEN_GROW_TIME[4].random) end, fn = function(inst) SetOld(inst) end, growfn = function(inst) GrowOld(inst) end }, } local function chop_tree(inst, chopper, chops) if chopper and chopper.components.beaverness and chopper.components.beaverness:IsBeaver() then inst.SoundEmitter:PlaySound("dontstarve/characters/woodie/beaver_chop_tree") else inst.SoundEmitter:PlaySound("dontstarve/wilson/use_axe_tree") end local fx = SpawnPrefab("pine_needles_chop") local x, y, z= inst.Transform:GetWorldPosition() fx.Transform:SetPosition(x,y + math.random()*2,z) inst.AnimState:PlayAnimation(inst.anims.chop) inst.AnimState:PushAnimation(inst.anims.sway1, true) --tell any nearby leifs to wake up local pt = Vector3(inst.Transform:GetWorldPosition()) local ents = TheSim:FindEntities(pt.x,pt.y,pt.z, TUNING.LEIF_REAWAKEN_RADIUS, {"leif"}) for k,v in pairs(ents) do if v.components.sleeper and v.components.sleeper:IsAsleep() then v:DoTaskInTime(math.random(), function() v.components.sleeper:WakeUp() end) end v.components.combat:SuggestTarget(chopper) end end local function chop_down_tree(inst, chopper) inst:RemoveComponent("burnable") MakeSmallBurnable(inst) inst:RemoveComponent("propagator") MakeSmallPropagator(inst) inst:RemoveComponent("workable") inst:RemoveTag("shelter") inst.SoundEmitter:PlaySound("dontstarve/forest/treefall") local pt = Vector3(inst.Transform:GetWorldPosition()) local hispos = Vector3(chopper.Transform:GetWorldPosition()) local he_right = (hispos - pt):Dot(TheCamera:GetRightVec()) > 0 if he_right then inst.AnimState:PlayAnimation(inst.anims.fallleft) inst.components.lootdropper:DropLoot(pt - TheCamera:GetRightVec()) else inst.AnimState:PlayAnimation(inst.anims.fallright) inst.components.lootdropper:DropLoot(pt + TheCamera:GetRightVec()) end inst:DoTaskInTime(.4, function() local sz = (inst.components.growable and inst.components.growable.stage > 2) and .5 or .25 GetPlayer().components.playercontroller:ShakeCamera(inst, "FULL", 0.25, 0.03, sz, 6) end) RemovePhysicsColliders(inst) inst.AnimState:PushAnimation(inst.anims.stump) inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.DIG) inst.components.workable:SetOnFinishCallback(dig_up_stump) inst.components.workable:SetWorkLeft(1) inst:AddTag("stump") if inst.components.growable then inst.components.growable:StopGrowing() end inst:AddTag("NOCLICK") inst:DoTaskInTime(2, function() inst:RemoveTag("NOCLICK") end) local days_survived = GetClock().numcycles if days_survived >= TUNING.LEIF_MIN_DAY then if math.random() <= TUNING.LEIF_PERCENT_CHANCE then local numleifs = 1 if days_survived > 30 then numleifs = math.random(2) elseif days_survived > 80 then numleifs = math.random(3) end for k = 1,numleifs do local target = FindEntity(inst, TUNING.LEIF_MAXSPAWNDIST, function(item) if item.components.growable and item.components.growable.stage <= 3 then return item:HasTag("tree") and (not item:HasTag("stump")) and (not item:HasTag("burnt")) and not item.noleif end return false end) if target then target.noleif = true target.leifscale = growth_stages[target.components.growable.stage].leifscale or 1 target:DoTaskInTime(1 + math.random()*3, function() if target and not target:HasTag("stump") and not target:HasTag("burnt") and target.components.growable and target.components.growable.stage <= 3 then local target = target if builds[target.build] and builds[target.build].leif then local leif = SpawnPrefab(builds[target.build].leif) if leif then local scale = target.leifscale local r,g,b,a = target.AnimState:GetMultColour() leif.AnimState:SetMultColour(r,g,b,a) --we should serialize this? leif.components.locomotor.walkspeed = leif.components.locomotor.walkspeed*scale leif.components.combat.defaultdamage = leif.components.combat.defaultdamage*scale leif.components.health.maxhealth = leif.components.health.maxhealth*scale leif.components.health.currenthealth = leif.components.health.currenthealth*scale leif.components.combat.hitrange = leif.components.combat.hitrange*scale leif.components.combat.attackrange = leif.components.combat.attackrange*scale leif.Transform:SetScale(scale,scale,scale) leif.components.combat:SuggestTarget(chopper) leif.sg:GoToState("spawn") target:Remove() leif.Transform:SetPosition(target.Transform:GetWorldPosition()) end end end end) end end end end end local function tree_burnt(inst) OnBurnt(inst) inst.pineconetask = inst:DoTaskInTime(10, function() local pt = Vector3(inst.Transform:GetWorldPosition()) if math.random(0, 1) == 1 then pt = pt + TheCamera:GetRightVec() else pt = pt - TheCamera:GetRightVec() end inst.components.lootdropper:DropLoot(pt) inst.pineconetask = nil end) end local function handler_growfromseed (inst) inst.components.growable:SetStage(1) inst.AnimState:PlayAnimation("grow_seed_to_short") inst.SoundEmitter:PlaySound("dontstarve/forest/treeGrow") PushSway(inst) end local function onsave(inst, data) if inst:HasTag("burnt") or inst:HasTag("fire") then data.burnt = true end if inst:HasTag("stump") then data.stump = true end if inst.build ~= "normal" then data.build = inst.build end end local function onload(inst, data) if data then if not data.build or builds[data.build] == nil then inst.build = "normal" else inst.build = data.build end if data.burnt then inst:AddTag("fire") -- Add the fire tag here: OnEntityWake will handle it actually doing burnt logic elseif data.stump then inst:RemoveComponent("burnable") MakeSmallBurnable(inst) inst:RemoveComponent("workable") inst:RemoveComponent("propagator") MakeSmallPropagator(inst) inst:RemoveComponent("growable") RemovePhysicsColliders(inst) inst.AnimState:PlayAnimation(inst.anims.stump) inst:AddTag("stump") inst:RemoveTag("shelter") inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.DIG) inst.components.workable:SetOnFinishCallback(dig_up_stump) inst.components.workable:SetWorkLeft(1) end end end local function OnEntitySleep(inst) local fire = false if inst:HasTag("fire") then fire = true end inst:RemoveComponent("burnable") inst:RemoveComponent("propagator") inst:RemoveComponent("inspectable") if fire then inst:AddTag("fire") end end local function OnEntityWake(inst) if not inst:HasTag("burnt") and not inst:HasTag("fire") then if not inst.components.burnable then if inst:HasTag("stump") then MakeSmallBurnable(inst) else MakeLargeBurnable(inst) inst.components.burnable:SetFXLevel(5) inst.components.burnable:SetOnBurntFn(tree_burnt) end end if not inst.components.propagator then if inst:HasTag("stump") then MakeSmallPropagator(inst) else MakeLargePropagator(inst) end end elseif not inst:HasTag("burnt") and inst:HasTag("fire") then OnBurnt(inst, true) end if not inst.components.inspectable then inst:AddComponent("inspectable") inst.components.inspectable.getstatus = inspect_tree end end local function makefn(build, stage, data) local function fn(Sim) local l_stage = stage if l_stage == 0 then l_stage = math.random(1,3) end local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() local sound = inst.entity:AddSoundEmitter() MakeObstaclePhysics(inst, .25) local minimap = inst.entity:AddMiniMapEntity() if build == "normal" then minimap:SetIcon("evergreen.png") elseif build == "sparse" then minimap:SetIcon("evergreen_lumpy.png") end minimap:SetPriority(-1) inst:AddTag("tree") inst:AddTag("workable") inst:AddTag("shelter") inst.build = build anim:SetBuild(GetBuild(inst).file) anim:SetBank("evergreen_short") local color = 0.5 + math.random() * 0.5 anim:SetMultColour(color, color, color, 1) ------------------- MakeLargeBurnable(inst) inst.components.burnable:SetFXLevel(5) inst.components.burnable:SetOnBurntFn(tree_burnt) inst.components.burnable:MakeDragonflyBait(1) MakeLargePropagator(inst) ------------------- inst:AddComponent("inspectable") inst.components.inspectable.getstatus = inspect_tree ------------------- inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.CHOP) inst.components.workable:SetOnWorkCallback(chop_tree) inst.components.workable:SetOnFinishCallback(chop_down_tree) ------------------- inst:AddComponent("lootdropper") --------------------- inst:AddComponent("growable") inst.components.growable.stages = growth_stages inst.components.growable:SetStage(l_stage) inst.components.growable.loopstages = true inst.components.growable.springgrowth = true inst.components.growable:StartGrowing() inst.growfromseed = handler_growfromseed --------------------- --PushSway(inst) inst.AnimState:SetTime(math.random()*2) --------------------- inst.OnSave = onsave inst.OnLoad = onload MakeSnowCovered(inst, .01) --------------------- inst:SetPrefabName( GetBuild(inst).prefab_name ) if data =="burnt" then OnBurnt(inst) end if data =="stump" then inst:RemoveComponent("burnable") MakeSmallBurnable(inst) inst:RemoveComponent("workable") inst:RemoveComponent("propagator") MakeSmallPropagator(inst) inst:RemoveComponent("growable") RemovePhysicsColliders(inst) inst.AnimState:PlayAnimation(inst.anims.stump) inst:AddTag("stump") inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.DIG) inst.components.workable:SetOnFinishCallback(dig_up_stump) inst.components.workable:SetWorkLeft(1) end inst.OnEntitySleep = OnEntitySleep inst.OnEntityWake = OnEntityWake return inst end return fn end local function tree(name, build, stage, data) return Prefab("forest/objects/trees/"..name, makefn(build, stage, data), assets, prefabs) end return tree("evergreen", "normal", 0), tree("evergreen_normal", "normal", 2), tree("evergreen_tall", "normal", 3), tree("evergreen_short", "normal", 1), tree("evergreen_sparse", "sparse", 0), tree("evergreen_sparse_normal", "sparse", 2), tree("evergreen_sparse_tall", "sparse", 3), tree("evergreen_sparse_short", "sparse", 1), tree("evergreen_burnt", "normal", 0, "burnt"), tree("evergreen_stump", "normal", 0, "stump")
-- this file is outdated now, I think. -- colors for each theme should live somewhere else because I'm nutty like that. themeColors = { Player = { P1 = HSV(38,0.8,1), P2 = HSV(195,0.8,1), }, Difficulty = { Beginner = color("#ff32f8"), -- light cyan Easy = color("#2cff00"), -- green Medium = color("#fee600"), -- yellow Hard = color("#ff2f39"), -- red Challenge = color("#1cd8ff"), -- light blue Edit = color("0.8,0.8,0.8,1"), -- gray Couple = color("#ed0972"), -- hot pink Routine = color("#ff9a00"), -- orange Difficulty_Beginner = color("0.0,0.9,1.0,1"), -- purple Difficulty_Easy = color("0.9,0.9,0.0,1"), -- green Difficulty_Medium = color("1.0,0.1,0.1,1"), -- yellow Difficulty_Hard = color("0.2,1.0,0.2,1"), -- red Difficulty_Challenge = color("0.2,0.6,1.0,1"), -- light blue Difficulty_Edit = color("0.8,0.8,0.8,1"), -- gray Difficulty_Couple = color("#ed0972"), -- hot pink Difficulty_Routine = color("#ff9a00"), -- orange }, } -- temporary: function StageToColor( stage ) return color("#FFFFFF") end -- specific functions function PlayerColor(pn) return themeColors.Player[ ToEnumShortString(pn) ] end; function CustomDifficultyToColor(diff) return themeColors.Difficulty[diff] or color("1,0,0,1") end; -- judgment colors local tnsColors = { TapNoteScore_W1 = HSV(48,0.2,1), TapNoteScore_W2 = HSV(48,0.8,0.95), TapNoteScore_W3 = HSV(160,0.9,0.8), TapNoteScore_W4 = HSV(200,0.9,1), TapNoteScore_W5 = HSV(320,0.9,1), TapNoteScore_Miss = HSV(0,0.8,0.8) }; function TapNoteScoreToColor(tns) return tnsColors[tns] end
-- Timing is a namespace of functions dealing with time. Timing.OnUpdate is likely to be -- the most familiar timer for any newbies. -- -- local r=Timing.OnUpdate(print, "This is printed every frame!"); -- r() -- Remove the timer -- -- Timing also lets you call a function periodically. All periods in Timing are specified -- in seconds: -- -- Timing.Every(1, print, "Print every 1 second"); -- -- Invocations are dependent on framerate, so a slow or inconsistent framerate can cause -- issues. There's a few different strategies for compensating for this problem, and Timing -- provides them as separate timing functions: -- -- * Periodic - Call function one period after now. Invocations can be lost, and the actual -- time will drift from the scheduled time. However, time between invocations will stay fairly -- constant. -- * Rhythmic - Compensate for drift, so delayed invocations will not delay subsequent -- invocations. Invocations can be lost. Time between individual invocations will vary. -- * Burst - Compensate for delays. Invocations are never lost, but time between invocations -- can be extremely inconsistent. -- -- If you have a good framerate, there will be very little difference between these functions. -- Periodic and Rhythmic are only subtly different from one another. You must use Burst if -- you're depending on a function to be called a certain number of times. -- -- There's also some other neat functions here that aren't timers: -- -- -- Cycle a myPowerText between purple and orange -- local color=Timing.CycleValues(1, "purple", "orange"); -- Timing.Every(.2, function() -- Frames.Color(myPowerText, color); -- myPowerText:SetText(UnitPower("player"); -- end); -- -- -- Spam guild with "FAIL" five times, streaming every .1 seconds. -- local out=Timing.Throttle(.1, Chat.g); -- for i=1, 5 do -- Chatpic.fail(out); -- end; -- I don't try to have FritoMod cover every possible case. If your timing strategy is sufficiently -- complicated, you'll have to write it yourself. -- -- I might eventually write a scheduler that would balance timer invocations and framerate. This -- would take some of the guesswork out of deciding period magnitude. Until then, use your best -- judgement. -- -- Prefer callbacks over timers, as callbacks will only fire on changes. These saved frames add up. if nil ~= require then require "wow/Frame-Events"; require "wow/api/Frame"; require "wow/api/Timing" require "fritomod/basic"; require "fritomod/currying"; require "fritomod/Functions"; require "fritomod/Lists"; require "fritomod/ListenerList"; require "fritomod/Callbacks-Frames"; end; Timing = Timing or {}; do local listeners = ListenerList:New(); listeners:SetRemoveOnFail(true); listeners:SetID("Timing") listeners:AddInstaller(function() if IsCallable(Timing.delegate) then Timing.delegate = Timing.delegate(); end; return Timing.delegate:Start(); end); local Delegate = OOP.Class("Timing.Delegate(WoW)"); function Delegate:Constructor() self.frame = CreateFrame("Frame"); end; function Delegate:Start() return Callbacks.OnUpdate(self.frame, Timing.Tick); end; Timing.delegate = Seal(Delegate, "New"); Timing.LAST_ELAPSED = 0; -- Iterate our timers. -- -- There's never a need to directly call this function unless you're developing or -- testing this addon. function Timing.Tick(delta) Timing.LAST_ELAPSED = delta; -- We don't use currying here to ensure we can override listeners -- during testing. listeners:Fire(); end; -- Adds a function that is fired every update. This is the highest-precision timing -- function though its precision is dependent on framerate. -- -- listener, ... -- the function that is fired every update -- returns -- a function that removes the specified listener function Timing.OnUpdate(func, ...) -- We don't use currying here to ensure we can override listeners -- during testing. return listeners:Add(func, ...); end; -- Replace our listener tables with new ones. -- -- You'll never call this function unless you're developing this addon. function Timing._Mask(newListeners) local oldListeners = listeners; listeners=newListeners; return function() listeners=oldListeners; end; end; end; -- Helper function to construct timers. tickFuncs are called every update, and should -- return what they want elapsed to be. This allows tickFuncs to reset or adjust their -- timer. local function Timer(tickFunc, ...) tickFunc=Curry(tickFunc, ...); return function(period, func, ...) period = Strings.GetTime(period); func = Curry(func, ...); local success, err = true, ""; local function Receiver() success, err = xpcall(func, traceback); end; local elapsed=0; return Timing.OnUpdate(function(delta) delta = Timing.LAST_ELAPSED; elapsed=tickFunc(period, elapsed+delta, Receiver); if not success then -- Reset success success = true; error(err); end; end); end; end; -- Calls the specified function periodically. This timer doesn't try to keep rhythm, -- so the actual time will slowly wander further from the scheduled time. For most uses, -- though, this behavior is tolerable, if not expected. -- -- period -- the length in between calls, in seconds -- func, ... -- the function that is invoked periodically -- returns -- a function that, when invoked, stops this timer. Timing.Periodic = Timer(function(period, elapsed, func) if elapsed >= period then func(); elapsed=0; end; return elapsed; end); function Timing.Every(first, ...) if type(first) == "string" then local time = Strings.GetTime(first); if time > 0 then first = time; end; end; if type(first)=="number" then return Timing.Periodic(first, ...); else return Timing.OnUpdate(first, ...); end; end; -- Calls the specified function rhythmically. This timer will maintain a rhythm; actual -- times will stay close to scheduled times, but distances between individual iterations -- will vary. -- -- This rhythm is local to this function. You'll have to do synchronizing on your own to -- maintain a global rhythm. Timing.Rhythmic = Timer(function(period, elapsed, func) if elapsed >= period then func(); elapsed=elapsed % period; end; return elapsed; end); Timing.Beat=Timing.Rhythmic; Timing.OnBeat=Timing.Rhythmic; -- Calls the specified function periodically. This timer will ensure that the function -- is called for every elapsed period. This is similar to Timing.Rhythmic, but where -- the rhymthic timer could "miss" beats, burst will fire the function as many times as -- necessary to account for them. Timing.Burst = Timer(function(period, elapsed, func) local c=math.floor(elapsed / period); while c > 0 do func(); c=c-1; end; return elapsed % period; end); -- Count down from the specified value, in seconds. The specified function will be -- called each second, starting with seconds - 1 until zero, inclusively. -- -- The returned remover will immediately stop the countdown with no further function -- invocations. function Timing.Countdown(seconds, func, ...) seconds=assert(tonumber(seconds), "Seconds must be a number. Given: "..type(seconds)); assert(seconds > 0, "seconds must be positive. Given: "..tostring(seconds)); func=Curry(func, ...); local r; r=Timing.Rhythmic(1, function() seconds = seconds - 1; if seconds >= 0 then func(seconds); else r(); end; end); return r; end; Timing.CountDown=Timing.Countdown; Timing.Count=Timing.Countdown; function Timing.Interpolate(duration, func, ...) func = Curry(func, ...); duration = Strings.GetTime(duration); local start = GetTime(); return function() local elapsed = GetTime() - start; func(Math.Clamp(0, elapsed / duration, 1)); end; end; function Timing.Modulo(duration, func, ...) func = Curry(func, ...); duration = Strings.GetTime(duration); local start = GetTime(); return function() local elapsed = GetTime() - start; func(Math.Clamp(0, (elapsed / duration) % 1, 1)); end; end; function Timing.Looping(duration, func, ...) func = Curry(func, ...); duration = Strings.GetTime(duration); local start = GetTime(); return function() local elapsed = GetTime() - start; local integral, fraction = math.modf(elapsed / duration); if integral % 2 == 1 then -- Decreasing func(1 - fraction); else -- Increasing func(fraction); end; end; end; -- Cycle between a series of values, based on when this function is called. -- -- This function has no remover since it does not use a timer. -- -- period -- the amount of time for which any given value will be returned. -- value, ... -- the values that will, over time, be used function Timing.CycleValues(period, value, ...) period = Strings.GetTime(period); local values={value, ...}; local time=GetTime(); return function() -- First, get the total elapsed time. -- -- Imagine a 2 second period with 3 values and our elapsed time is 9 seconds. local elapsed=GetTime()-time; -- Then, use modulus to get our elapsed time in the scope of a single period. -- -- elapsed is now 3, due to 9 % ( 3 * 2) elapsed=elapsed % (#values * period); -- Since elapsed is now in the range [0,#values * period), we can use it to -- find which value to return. -- -- math.ceil(3 / 2) == math.ceil(1.5) == 2 elapsed=math.ceil(elapsed / period); return values[math.min(math.max(1, elapsed), #values)]; end; end; -- Throttles invocations for the specified function. Multiple calls to this function -- will only yield one invocation of the specified function. Subsequent calls will be -- ignored until the cooldown time has passed. -- -- This is not a timer; the function is always invoked directly and never as a result -- of an event. If the returned function is never called, the specified function will -- never be invoked. -- -- cooldownTime -- the minimum amount of time between calls to the specified function -- returns -- a function that throttles invocations of function -- see -- Timing.Throttle function Timing.Cooldown(cooldownTime, func, ...) cooldownTime = Strings.GetTime(cooldownTime); func = Curry(func, ...); local lastCall; return function(first, ...) if first==POISON and select("#", ...) == 0 then lastCall=nil; return; end; local current = GetTime(); if lastCall and lastCall + cooldownTime > current then return; end; lastCall = current; func(first, ...); end; end; -- Saves invocations so that func is only called periodically. Excess invocations are -- saved, so you can use this function to "slow down" a stream of data. This function -- is similar to Timing.Cooldown, but cooldown ignores excess invocations instead of -- postponing them. -- -- This function is not undoable, but it can be poisoned. -- -- waitTime -- time to wait between invocations, in seconds -- func, ... -- func that is eventually called -- returns -- a function that receives invocations. The arguments passed to the returned function -- will eventually be passed to func. -- see -- Timing.Cooldown function Timing.Throttle(waitTime, func, ...) waitTime = Strings.GetTime(waitTime); func=Curry(func, ...); local invocations={}; local r; return function(p, ...) if p == POISON then if r then r(); r=nil; end; invocations={}; return; end; table.insert(invocations, {p,...}); if not r then r=Timing.Rhythmic(waitTime, function() if #invocations > 0 then func(unpack(table.remove(invocations, 1))); end; if #invocations==0 then r(); r=nil; end; end); end; end; end; -- Return a timer that, after `wait` seconds, will call `func`. -- -- The timer can be delayed by calling it with special values: -- * If the timer is called with a number, the call to `func` -- will be delayed by that amount. There is no maximum delay, so -- you can delay `func` by a value that's greater than the initial -- `wait`. -- * If the timer is called with POISON, the timer will be -- irrecoverably killed. -- * If the timer is called with nil, this timer will wait -- at least `wait` seconds before calling `func`. -- -- wait -- the initial wait time, in seconds -- func, ... -- the function that may be eventually called -- returns -- a timer that responds to the values listed above function Timing.After(wait, func, ...) wait = Strings.GetTime(wait); func = Curry(func,...); local elapsed = 0; local timer; timer = Timing.OnUpdate(function() delta = Timing.LAST_ELAPSED; elapsed = elapsed + delta; if elapsed >= wait then timer(); timer = nil; func(); end; end); return function(...) if not timer then return; end; if select("#", ...) == 0 or (...) == POISON then timer(); timer = nil; return; end; local delay = ...; elapsed = elapsed - delay; end; end; Callbacks = Callbacks or {}; Callbacks.After = Timing.After;
local ipairs=ipairs local type=type local print=print local naughty=require('naughty') module('z.debug') function print_table(t) for i,element in ipairs(t)do print(i.." type:"..type(element)) end end function dump(e) naughty.notify({text="type"..type(e)}) print ("type"..type(e).."\n") -- if type(e)=='userdata' then print "user data\n" end end function msg(txt) naughty.notify({text="debug:"..txt,timeout=30}) end
-- @docconsts @{ AnchorNone = 0 AnchorTop = 1 AnchorBottom = 2 AnchorLeft = 3 AnchorRight = 4 AnchorVerticalCenter = 5 AnchorHorizontalCenter = 6 LogDebug = 0 LogInfo = 1 LogWarning = 2 LogError = 3 LogFatal = 4 MouseFocusReason = 0 KeyboardFocusReason = 1 ActiveFocusReason = 2 OtherFocusReason = 3 AutoFocusNone = 0 AutoFocusFirst = 1 AutoFocusLast = 2 KeyboardNoModifier = 0 KeyboardCtrlModifier = 1 KeyboardAltModifier = 2 KeyboardCtrlAltModifier = 3 KeyboardShiftModifier = 4 KeyboardCtrlShiftModifier = 5 KeyboardAltShiftModifier = 6 KeyboardCtrlAltShiftModifier = 7 MouseNoButton = 0 MouseLeftButton = 1 MouseRightButton = 2 MouseMidButton = 3 MouseNoWheel = 0 MouseWheelUp = 1 MouseWheelDown = 2 AlignNone = 0 AlignLeft = 1 AlignRight = 2 AlignTop = 4 AlignBottom = 8 AlignHorizontalCenter = 16 AlignVerticalCenter = 32 AlignTopLeft = 5 AlignTopRight = 6 AlignBottomLeft = 9 AlignBottomRight = 10 AlignLeftCenter = 33 AlignRightCenter = 34 AlignTopCenter = 20 AlignBottomCenter = 24 AlignCenter = 48 KeyUnknown = 0 KeyEscape = 1 KeyTab = 2 KeyBackspace = 3 KeyEnter = 5 KeyInsert = 6 KeyDelete = 7 KeyPause = 8 KeyPrintScreen = 9 KeyHome = 10 KeyEnd = 11 KeyPageUp = 12 KeyPageDown = 13 KeyUp = 14 KeyDown = 15 KeyLeft = 16 KeyRight = 17 KeyNumLock = 18 KeyScrollLock = 19 KeyCapsLock = 20 KeyCtrl = 21 KeyShift = 22 KeyAlt = 23 KeyMeta = 25 KeyMenu = 26 KeySpace = 32 -- ' ' KeyExclamation = 33 -- ! KeyQuote = 34 -- " KeyNumberSign = 35 -- # KeyDollar = 36 -- $ KeyPercent = 37 -- % KeyAmpersand = 38 -- & KeyApostrophe = 39 -- ' KeyLeftParen = 40 -- ( KeyRightParen = 41 -- ) KeyAsterisk = 42 -- * KeyPlus = 43 -- + KeyComma = 44 -- , KeyMinus = 45 -- - KeyPeriod = 46 -- . KeySlash = 47 -- / Key0 = 48 -- 0 Key1 = 49 -- 1 Key2 = 50 -- 2 Key3 = 51 -- 3 Key4 = 52 -- 4 Key5 = 53 -- 5 Key6 = 54 -- 6 Key7 = 55 -- 7 Key8 = 56 -- 8 Key9 = 57 -- 9 KeyColon = 58 -- : KeySemicolon = 59 -- ; KeyLess = 60 -- < KeyEqual = 61 -- = KeyGreater = 62 -- > KeyQuestion = 63 -- ? KeyAtSign = 64 -- @ KeyA = 65 -- a KeyB = 66 -- b KeyC = 67 -- c KeyD = 68 -- d KeyE = 69 -- e KeyF = 70 -- f KeyG = 71 -- g KeyH = 72 -- h KeyI = 73 -- i KeyJ = 74 -- j KeyK = 75 -- k KeyL = 76 -- l KeyM = 77 -- m KeyN = 78 -- n KeyO = 79 -- o KeyP = 80 -- p KeyQ = 81 -- q KeyR = 82 -- r KeyS = 83 -- s KeyT = 84 -- t KeyU = 85 -- u KeyV = 86 -- v KeyW = 87 -- w KeyX = 88 -- x KeyY = 89 -- y KeyZ = 90 -- z KeyLeftBracket = 91 -- [ KeyBackslash = 92 -- '\' KeyRightBracket = 93 -- ] KeyCaret = 94 -- ^ KeyUnderscore = 95 -- _ KeyGrave = 96 -- ` KeyLeftCurly = 123 -- { KeyBar = 124 -- | KeyRightCurly = 125 -- } KeyTilde = 126 -- ~ KeyF1 = 128 KeyF2 = 129 KeyF3 = 130 KeyF4 = 131 KeyF5 = 132 KeyF6 = 134 KeyF7 = 135 KeyF8 = 136 KeyF9 = 137 KeyF10 = 138 KeyF11 = 139 KeyF12 = 140 KeyNumpad0 = 141 KeyNumpad1 = 142 KeyNumpad2 = 143 KeyNumpad3 = 144 KeyNumpad4 = 145 KeyNumpad5 = 146 KeyNumpad6 = 147 KeyNumpad7 = 148 KeyNumpad8 = 149 KeyNumpad9 = 150 FirstKey = KeyUnknown LastKey = KeyNumpad9 ExtendedActivate = 0 ExtendedLocales = 1 ExtendedParticles = 2 -- @} KeyCodeDescs = { [KeyUnknown] = 'Unknown', [KeyEscape] = 'Escape', [KeyTab] = 'Tab', [KeyBackspace] = 'Backspace', [KeyEnter] = 'Enter', [KeyInsert] = 'Insert', [KeyDelete] = 'Delete', [KeyPause] = 'Pause', [KeyPrintScreen] = 'PrintScreen', [KeyHome] = 'Home', [KeyEnd] = 'End', [KeyPageUp] = 'PageUp', [KeyPageDown] = 'PageDown', [KeyUp] = 'Up', [KeyDown] = 'Down', [KeyLeft] = 'Left', [KeyRight] = 'Right', [KeyNumLock] = 'NumLock', [KeyScrollLock] = 'ScrollLock', [KeyCapsLock] = 'CapsLock', [KeyCtrl] = 'Ctrl', [KeyShift] = 'Shift', [KeyAlt] = 'Alt', [KeyMeta] = 'Meta', [KeyMenu] = 'Menu', [KeySpace] = 'Space', [KeyExclamation] = '!', [KeyQuote] = '\"', [KeyNumberSign] = '#', [KeyDollar] = '$', [KeyPercent] = '%', [KeyAmpersand] = '&', [KeyApostrophe] = '\'', [KeyLeftParen] = '(', [KeyRightParen] = ')', [KeyAsterisk] = '*', [KeyPlus] = 'Plus', [KeyComma] = ',', [KeyMinus] = '-', [KeyPeriod] = '.', [KeySlash] = '/', [Key0] = '0', [Key1] = '1', [Key2] = '2', [Key3] = '3', [Key4] = '4', [Key5] = '5', [Key6] = '6', [Key7] = '7', [Key8] = '8', [Key9] = '9', [KeyColon] = ':', [KeySemicolon] = ';', [KeyLess] = '<', [KeyEqual] = '=', [KeyGreater] = '>', [KeyQuestion] = '?', [KeyAtSign] = '@', [KeyA] = 'A', [KeyB] = 'B', [KeyC] = 'C', [KeyD] = 'D', [KeyE] = 'E', [KeyF] = 'F', [KeyG] = 'G', [KeyH] = 'H', [KeyI] = 'I', [KeyJ] = 'J', [KeyK] = 'K', [KeyL] = 'L', [KeyM] = 'M', [KeyN] = 'N', [KeyO] = 'O', [KeyP] = 'P', [KeyQ] = 'Q', [KeyR] = 'R', [KeyS] = 'S', [KeyT] = 'T', [KeyU] = 'U', [KeyV] = 'V', [KeyW] = 'W', [KeyX] = 'X', [KeyY] = 'Y', [KeyZ] = 'Z', [KeyLeftBracket] = '[', [KeyBackslash] = '\\', [KeyRightBracket] = ']', [KeyCaret] = '^', [KeyUnderscore] = '_', [KeyGrave] = '`', [KeyLeftCurly] = '{', [KeyBar] = '|', [KeyRightCurly] = '}', [KeyTilde] = '~', [KeyF1] = 'F1', [KeyF2] = 'F2', [KeyF3] = 'F3', [KeyF4] = 'F4', [KeyF5] = 'F5', [KeyF6] = 'F6', [KeyF7] = 'F7', [KeyF8] = 'F8', [KeyF9] = 'F9', [KeyF10] = 'F10', [KeyF11] = 'F11', [KeyF12] = 'F12', [KeyNumpad0] = 'Numpad0', [KeyNumpad1] = 'Numpad1', [KeyNumpad2] = 'Numpad2', [KeyNumpad3] = 'Numpad3', [KeyNumpad4] = 'Numpad4', [KeyNumpad5] = 'Numpad5', [KeyNumpad6] = 'Numpad6', [KeyNumpad7] = 'Numpad7', [KeyNumpad8] = 'Numpad8', [KeyNumpad9] = 'Numpad9', } NetworkMessageTypes = { Boolean = 1, U8 = 2, U16 = 3, U32 = 4, U64 = 5, NumberString = 6, String = 7, Table = 8, } SoundChannels = { Music = 1, Ambient = 2, }
-------------------------------------------------- -- =============== Autorun File =============== -- *** Copyright (c) 2012-2017 by DrVrej, All rights reserved. *** -- No parts of this code or any of its contents may be reproduced, copied, modified or adapted, -- without the prior written consent of the author, unless otherwise indicated for stand-alone materials. -- this addon by Tamcl, newtamcl@foxmail.com -- https://space.bilibili.com/3761568/#!/ -------------------------------------------------- ------------------ Addon Information ------------------ local PublicAddonName = "Improved Anime Bodyguard" local AddonName = "Improved Anime Bodyguard" local AddonType = "SNPC" local AutorunFile = "autorun/anime_bodyguard.lua" ------------------------------------------------------- local VJExists = file.Exists("lua/autorun/vj_base_autorun.lua","GAME") if VJExists == true then include('autorun/vj_controls.lua') local vCat = "Anime Bodyguards" VJ.AddNPC_HUMAN("2B","npc_ab_2b",{"weapon_vj_smg1"},vCat) --index: 1 VJ.AddNPC_HUMAN("Amatsukaze","npc_ab_amatsukaze",{"weapon_vj_smg1"},vCat) --index: 2 VJ.AddNPC_HUMAN("Aqua","npc_ab_aqua",{"weapon_vj_smg1"},vCat) --index: 3 VJ.AddNPC_HUMAN("Astolfo","npc_ab_astolfo",{"weapon_vj_smg1"},vCat) --index: 4 VJ.AddNPC_HUMAN("Asuna","npc_ab_asuna",{"weapon_vj_smg1"},vCat) --index: 5 VJ.AddNPC_HUMAN("Aya Drevis","npc_ab_aya_drevis",{"weapon_vj_smg1"},vCat) --index: 6 VJ.AddNPC_HUMAN("Blake Belladonna","npc_ab_blake_belladonna",{"weapon_vj_smg1"},vCat) --index: 7 VJ.AddNPC_HUMAN("BRS","npc_ab_brs",{"weapon_vj_smg1"},vCat) --index: 8 VJ.AddNPC_HUMAN("Cirno","npc_ab_cirno",{"weapon_vj_smg1"},vCat) --index: 9 VJ.AddNPC_HUMAN("Cleaire","npc_ab_cleaire",{"weapon_vj_smg1"},vCat) --index: 10 VJ.AddNPC_HUMAN("Combine Soldier","npc_ab_combine_soldier",{"weapon_vj_smg1"},vCat) --index: 11 VJ.AddNPC_HUMAN("Creeper Girl","npc_ab_creeper_girl",{"weapon_vj_smg1"},vCat) --index: 12 VJ.AddNPC_HUMAN("Ezo Red Fox","npc_ab_ezo_red_fox",{"weapon_vj_smg1"},vCat) --index: 13 VJ.AddNPC_HUMAN("Friendly Combine Elite","npc_ab_friendly_combine_elite",{"weapon_vj_smg1"},vCat) --index: 14 VJ.AddNPC_HUMAN("God Eater","npc_ab_god_eater",{"weapon_vj_smg1"},vCat) --index: 15 VJ.AddNPC_HUMAN("Hata No Kokoro","npc_ab_hata_no_kokoro",{"weapon_vj_smg1"},vCat) --index: 16 VJ.AddNPC_HUMAN("Hinanawi Tenshi","npc_ab_hinanawi_tenshi",{"weapon_vj_smg1"},vCat) --index: 17 VJ.AddNPC_HUMAN("Izuku Midoriya","npc_ab_izuku_midoriya",{"weapon_vj_smg1"},vCat) --index: 18 VJ.AddNPC_HUMAN("Jaune Arc","npc_ab_jaune_arc",{"weapon_vj_smg1"},vCat) --index: 19 VJ.AddNPC_HUMAN("Kafuu Chino","npc_ab_kafuu_chino",{"weapon_vj_smg1"},vCat) --index: 20 VJ.AddNPC_HUMAN("Kamikaze","npc_ab_kamikaze",{"weapon_vj_smg1"},vCat) --index: 21 VJ.AddNPC_HUMAN("Kanna Kamui","npc_ab_kanna_kamui",{"weapon_vj_smg1"},vCat) --index: 22 VJ.AddNPC_HUMAN("Kashima","npc_ab_kashima",{"weapon_vj_smg1"},vCat) --index: 23 VJ.AddNPC_HUMAN("Katyusha","npc_ab_katyusha",{"weapon_vj_smg1"},vCat) --index: 24 VJ.AddNPC_HUMAN("Kirito","npc_ab_kirito",{"weapon_vj_smg1"},vCat) --index: 25 VJ.AddNPC_HUMAN("Kizuna AI","npc_ab_kizuna_ai",{"weapon_vj_smg1"},vCat) --index: 26 VJ.AddNPC_HUMAN("Kochiya Sanae","npc_ab_kochiya_sanae",{"weapon_vj_smg1"},vCat) --index: 27 VJ.AddNPC_HUMAN("Konata","npc_ab_konata",{"weapon_vj_smg1"},vCat) --index: 28 VJ.AddNPC_HUMAN("L7","npc_ab_l7",{"weapon_vj_smg1"},vCat) --index: 29 VJ.AddNPC_HUMAN("Llenn","npc_ab_llenn",{"weapon_vj_smg1"},vCat) --index: 30 VJ.AddNPC_HUMAN("Megumin","npc_ab_megumin",{"weapon_vj_smg1"},vCat) --index: 31 VJ.AddNPC_HUMAN("Miku","npc_ab_miku",{"weapon_vj_smg1"},vCat) --index: 32 VJ.AddNPC_HUMAN("Miku 2","npc_ab_miku_2",{"weapon_vj_smg1"},vCat) --index: 33 VJ.AddNPC_HUMAN("Mirai Akari","npc_ab_mirai_akari",{"weapon_vj_smg1"},vCat) --index: 34 VJ.AddNPC_HUMAN("Misaka Mikoto","npc_ab_misaka_mikoto",{"weapon_vj_smg1"},vCat) --index: 35 VJ.AddNPC_HUMAN("Murasame","npc_ab_murasame",{"weapon_vj_smg1"},vCat) --index: 36 VJ.AddNPC_HUMAN("Nepgear","npc_ab_nepgear",{"weapon_vj_smg1"},vCat) --index: 37 VJ.AddNPC_HUMAN("Neptune","npc_ab_neptune",{"weapon_vj_smg1"},vCat) --index: 38 VJ.AddNPC_HUMAN("Prinz Eugen","npc_ab_prinz_eugen",{"weapon_vj_smg1"},vCat) --index: 39 VJ.AddNPC_HUMAN("Pyrrha Nikos","npc_ab_pyrrha_nikos",{"weapon_vj_smg1"},vCat) --index: 40 VJ.AddNPC_HUMAN("Ram","npc_ab_ram",{"weapon_vj_smg1"},vCat) --index: 41 VJ.AddNPC_HUMAN("Rem","npc_ab_rem",{"weapon_vj_smg1"},vCat) --index: 42 VJ.AddNPC_HUMAN("Renri Yamine","npc_ab_renri_yamine",{"weapon_vj_smg1"},vCat) --index: 43 VJ.AddNPC_HUMAN("Rin","npc_ab_rin",{"weapon_vj_smg1"},vCat) --index: 44 VJ.AddNPC_HUMAN("Ruby Rose","npc_ab_ruby_rose",{"weapon_vj_smg1"},vCat) --index: 45 VJ.AddNPC_HUMAN("Sagiri Izumi","npc_ab_sagiri_izumi",{"weapon_vj_smg1"},vCat) --index: 46 VJ.AddNPC_HUMAN("Saten Ruiko","npc_ab_saten_ruiko",{"weapon_vj_smg1"},vCat) --index: 47 VJ.AddNPC_HUMAN("Sharo Kirima","npc_ab_sharo_kirima",{"weapon_vj_smg1"},vCat) --index: 48 VJ.AddNPC_HUMAN("Shigure","npc_ab_shigure",{"weapon_vj_smg1"},vCat) --index: 49 VJ.AddNPC_HUMAN("Shimakaze","npc_ab_shimakaze",{"weapon_vj_smg1"},vCat) --index: 50 VJ.AddNPC_HUMAN("Shirai Kuroko","npc_ab_shirai_kuroko",{"weapon_vj_smg1"},vCat) --index: 51 VJ.AddNPC_HUMAN("Shiro","npc_ab_shiro",{"weapon_vj_smg1"},vCat) --index: 52 VJ.AddNPC_HUMAN("Sinon","npc_ab_sinon",{"weapon_vj_smg1"},vCat) --index: 53 VJ.AddNPC_HUMAN("Tohru","npc_ab_tohru",{"weapon_vj_smg1"},vCat) --index: 54 VJ.AddNPC_HUMAN("Uiharu Kazari","npc_ab_uiharu_kazari",{"weapon_vj_smg1"},vCat) --index: 55 VJ.AddNPC_HUMAN("Umaru Doma","npc_ab_umaru_doma",{"weapon_vj_smg1"},vCat) --index: 56 VJ.AddNPC_HUMAN("Uni","npc_ab_uni",{"weapon_vj_smg1"},vCat) --index: 57 VJ.AddNPC_HUMAN("U-511","npc_ab_u_511",{"weapon_vj_smg1"},vCat) --index: 58 VJ.AddNPC_HUMAN("Weiss Schnee","npc_ab_weiss_schnee",{"weapon_vj_smg1"},vCat) --index: 59 VJ.AddNPC_HUMAN("WRS","npc_ab_wrs",{"weapon_vj_smg1"},vCat) --index: 60 VJ.AddNPC_HUMAN("Yang Xiao Long","npc_ab_yang_xiao_long",{"weapon_vj_smg1"},vCat) --index: 61 VJ.AddNPC_HUMAN("Yuudachi","npc_ab_yuudachi",{"weapon_vj_smg1"},vCat) --index: 62 VJ.AddNPC_HUMAN("Zero Two","npc_ab_zero_two",{"weapon_vj_smg1"},vCat) --index: 63 VJ.AddNPC_HUMAN("Zetsune Miku","npc_ab_zetsune_miku",{"weapon_vj_smg1"},vCat) --index: 64 VJ.AddNPC_HUMAN("zuikaku","npc_ab_zuikaku",{"weapon_vj_smg1"},vCat) --index: 65 if SERVER then resource.AddWorkshop("1156321204") end end
package.path = "../?.lua;../webtersen/?.lua;" .. package.path print("LUA MODULES:\n",(package.path:gsub("%;","\n\t"))) local js = require "js" local window = js.global local lut_mod = require 'tersen.lut' local trace_mod = require 'tersen.trace' local tersen_mod = require 'tersen.tersen' local function elem(name) return window.document:getElementById(name) end local submit = elem("submit") function submit:onclick(e) e:preventDefault() elem("processing").style["display"] = "inline" local dict_str = elem("tersen_dict").value local lut = lut_mod.build_from_string(dict_str) trace_mod.trace(lut) local result = tersen_mod.tersen(lut, elem("verbose_text").value) elem("results").innerText = result elem("processing").style["display"] = "none" end
local LOCAL_PLAYER = Game.GetLocalPlayer() function Tick() for _, ability in ipairs(LOCAL_PLAYER:GetAbilities()) do ability:Activate() Task.Wait(1) end end
local skynet = require "skynet" local i = 10 skynet.start(function() skynet.fork(function ( ) while true do skynet.sleep(100) skynet.error("hello bo222y",i) i=i+1 end end) skynet.dispatch("lua", function(_,_,msg) skynet.sleep(100) --skynet.ret(skynet.pack(msg)) end) end)
local sadb local AceConfigDialog = LibStub("AceConfigDialog-3.0") local AceConfig = LibStub("AceConfig-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("SoundAlerter") local self, SoundAlerter = SoundAlerter, SoundAlerter local function initOptions() if SoundAlerter.options.args.general then return end SoundAlerter:OnOptionsCreate() for k, v in SoundAlerter:IterateModules() do if type(v.OnOptionsCreate) == "function" then v:OnOptionsCreate() end end AceConfig:RegisterOptionsTable("SoundAlerter", SoundAlerter.options) end function SoundAlerter:ShowConfig() initOptions() AceConfigDialog:Open("SoundAlerter") end function SoundAlerter:ChangeProfile() sadb = self.db1.profile for k,v in SoundAlerter:IterateModules() do if type(v.ChangeProfile) == 'function' then v:ChangeProfile() end end end function SoundAlerter:AddOption(key, table) self.options.args[key] = table end local function setOption(info, value) local name = info[#info] sadb[name] = value --print(sadb.sapath..name..".mp3") PlaySoundFile(sadb.sapath..name..".mp3"); end local function getOption(info) local name = info[#info] return sadb[name] end function listOption(spellList, listType, ...) local args = {} for k,v in pairs(spellList) do if SoundAlerter.spellList[listType][v] then rawset(args, SoundAlerter.spellList[listType][v], self:spellOptions(k, v)) else print(v) end end return args end function SpellTexture(sid) local spellname,_,icon = GetSpellInfo(sid) if spellname ~= nil then return "\124T"..icon..":24\124t" end end function SpellTextureName(sid) local spellname,_,icon = GetSpellInfo(sid) if spellname ~= nil then return "\124T"..icon..":24\124t"..spellname end end function SoundAlerter:OnOptionsCreate() sadb = self.db1.profile self:AddOption("profiles", LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db1)) self.options.args.profiles.order = -1 self:AddOption('General', { type = 'group', name = "General", desc = "General Options", order = 1, args = { enableArea = { type = 'group', inline = true, name = "General options", set = setOption, get = getOption, args = { all = { type = 'toggle', name = "Enable Everything", desc = "Enables Sound Alerter for BGs, world and arena", order = 1, }, arena = { type = 'toggle', name = "Arena", desc = "Enabled in the arena", disabled = function() return sadb.all end, order = 2, }, battleground = { type = 'toggle', name = "Battleground", desc = "Enable Battleground", disabled = function() return sadb.all end, order = 3, }, field = { type = 'toggle', name = "World", desc = "Enabled outside Battlegrounds and arenas", disabled = function() return sadb.all end, order = 4, }, AlertConditions = { type = 'group', inline = true, order = 9, name = "Alert Conditions", args = { myself = { type = 'toggle', name = L["Target and Focus only"], disabled = function() return sadb.enemyinrange end, desc = "Alert works only when your current target casts a spell, or an enemy casts a spell on you", order = 5, }, enemyinrange = { type = 'toggle', name = "All Enemies in Range", desc = "Alerts are enabled for all enemies in range", disabled = function() return sadb.myself end, order = 6, }, }, }, volumecontrol = { type = 'group', inline = true, order = 10, name = "Volume Control", args = { volumn = { type = 'range', max = 1, min = 0, isPercent = true, step = 0.1, name = "Master Volume", desc = "Sets the master volume so sound alerts can be louder/softer", set = function (info, value) SetCVar ("Sound_MasterVolume",tostring (value)) end, get = function () return tonumber (GetCVar ("Sound_MasterVolume")) end, order = 1, }, volumn2 = { type = 'execute', width = 'normal', name = "Addon sounds only", desc = "Sets other sounds to minimum, only hearing the addon sounds", func = function() SetCVar ("Sound_AmbienceVolume",tostring ("0")); SetCVar ("Sound_SFXVolume",tostring ("0")); SetCVar ("Sound_MusicVolume",tostring ("0")); print("|cffFF7D0ASoundAlerter|r: Addons will only be heard by your Client. To undo this, click the 'reset sound options' button."); end, order = 2, }, volumn3 = { type = 'execute', width = 'normal', name = "Reset volume options", desc = "Resets sound options", func = function() SetCVar ("Sound_MasterVolume",tostring ("1")); SetCVar ("Sound_AmbienceVolume",tostring ("1")); SetCVar ("Sound_SFXVolume",tostring ("1")); SetCVar ("Sound_MusicVolume",tostring ("1")); print("|cffFF7D0ASoundAlerter|r: Sound options reset."); end, order = 3, }, sapath = { type = 'select', name = "Language", desc = "Language of Sounds", values = self.SA_LANGUAGE, order = 3, }, combatText = { type = 'toggle', name = "Combat Text Only", desc = "Disable sounds and use combat text instead", order = 4, } }, }, advance = { type = 'group', inline = true, name = L["Advanced options"], order = 11, args = { debugmode = { type = 'toggle', name = "Debug Mode", desc = "Enable Debugging", order = 3, }, }, }, debugopts = { type = 'group', inline = true, order = 11, hidden = function() return not sadb.debugmode end, name = "Debug options", args = { cspell = { type = 'input', name = "Custom spells entry name", order = 1, }, spelldebug = { type = 'toggle', name = "Spell ID output debugging", order = 2, }, csname = { type = 'input', name = "Spell name", order = 2, }, }, }, importexport = { type = 'group', inline = true, hidden = function() return not sadb.debugmode end, name = "Import/Export", desc = "Import or export custom sound alerts", order = 12, args = { import = { type = 'execute', name = "Import custom sound alerts", order = 1, confirm = true, confirmText = "Are you sure? This will remove all of your current sound alerts", func = function() sadb.custom = nil end, }, export = { type = 'execute', name = "Export encapsulation", order = 2, func = function() local thisw = "@" for k,css in pairs (sadb.custom) do thisw = thisw.."|"..css.name..","..css.soundfilepath..","..(css.spellid and css.spellid or "0").."," for j,l in pairs (sadb.custom[k].eventtype) do thisw = thisw..j..","..tostring(l).."," end end sadb.exportbox = thisw.."#" end, }, exportbox = { type = 'input', name = "Export custom sound alerts", order = 3, }, }, } }, }, } }) self:AddOption('Spells', { type = 'group', name = "Spells", desc = "Spell Options", order = 2, args = { -- INLINE - checkbox to enable / disable spells alerter spellGeneral = { type = 'group', name = "Spell Disables", desc = "Enable certain spell types", inline = true, set = setOption, get = getOption, order = 0, args = { chatalerts = { type = 'toggle', name = "Disable Chat Alerts", desc = "Disbles Chat notifications of special abilities in the chat bar", order = 1, }, interrupt = { type = 'toggle', name = "Disable Interrupted Spells", desc = "Check this option to disable notifications of friendly interrupted spells", order = 2, }, auraApplied = { type = 'toggle', name = "Disable buff applied", desc = "Disables sound notifications of buffs applied", order = 3, }, auraRemoved = { type = 'toggle', name = "Disable Buff down", desc = "Disables sound notifications of buffs down", order = 4, }, castStart = { type = 'toggle', name = "Disable spell casting", desc = "Disables spell casting notifications", order = 5, }, castSuccess = { type = 'toggle', name = "Disable enemy cooldown abilities", desc = "Disbles sound notifications of cooldown abilities", order = 6, }, dEnemyDebuff = { type = 'toggle', name = "Disable Enemy Debuff alerts", desc = "Check this option to disable notifications of enemy debuff/CC alerts", order = 7, }, dEnemyDebuffDown = { type = 'toggle', name = "Disable Enemy Debuff down alerts", desc = "Check this option to disable notifications of enemy debuff/CC alerts", order = 8, }, dArenaPartner = { type = 'toggle', name = "Disable Arena Partner CC alerts", desc = "Check this option to disable notifications of Arena Partner debuff/CC alerts", order = 9, }, dSelfDebuff = { type = 'toggle', name = "Disable Self Debuff alerts", desc = "Check this option to disable notifications of self debuff/CC alerts", order = 10, }, }, }, -- INLINE - Buttons for fast navigation inlineCategories = { type = 'group', name = "", inline = true, order = 1, args = { btnChatAlerter = { type = 'execute', name = "Chat Alerter", order = 10, width = "full", disabled = function() return sadb.chatalerts end, hidden = function() return sadb.chatalerts end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "chatalerter") end, }, btnAura = { type = 'execute', name = "Enemy Aura", order = 11, width = "full", disabled = function() return sadb.auraApplied end, hidden = function() return sadb.auraApplied end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied") end, }, btnAuraDown = { type = 'execute', name = "Enemy Aura Down", order = 12, width = "full", disabled = function() return sadb.auraRemoved end, hidden = function() return sadb.auraRemoved end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved") end, }, btnCastStart = { type = 'execute', name = "Enemy Casting Start", order = 13, width = "full", disabled = function() return sadb.castStart end, hidden = function() return sadb.castStart end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart") end, }, btnCastSucc = { type = 'execute', name = "Enemy Casting Success", order = 14, width = "full", disabled = function() return sadb.castSuccess end, hidden = function() return sadb.castSuccess end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess") end, }, btnEnemyDebuff = { type = 'execute', name = "Enemy Debuff", order = 15, width = "full", disabled = function() return sadb.dEnemyDebuff end, hidden = function() return sadb.dEnemyDebuff end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "enemydebuff") end, }, btnEnemyDebuffDown = { type = 'execute', name = "Enemy Debuff Down", order = 16, width = "full", disabled = function() return sadb.dEnemyDebuffDown end, hidden = function() return sadb.dEnemyDebuffDown end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "enemydebuffdown") end, }, btnFriendDebuff = { type = 'execute', name = "Friend Debuff", order = 17, width = "full", disabled = function() return sadb.dArenaPartner end, hidden = function() return sadb.dArenaPartner end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "FriendDebuff") end, }, btnFriendDebuffSuccess= { type = 'execute', name = "Friend Debuff Success", order = 18, width = "full", disabled = function() return sadb.dArenaPartner end, hidden = function() return sadb.dArenaPartner end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "FriendDebuffSuccess") end, }, btnselfDebuffs = { type = 'execute', name = "self Debuffs", order = 19, width = "full", disabled = function() return sadb.dSelfDebuff end, hidden = function() return sadb.dSelfDebuff end, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "selfDebuffs") end, }, }, }, -- spellauraApplied = { type = 'group', name = "Enemy Aura", desc = "Alerts you when your enemy gains an aura, or uses a cooldown", set = setOption, get = getOption, disabled = function() return sadb.auraApplied end, order = 2, args = { inlineCategories = { type = 'group', inline = true, name = "", order = 0, args = { btnGen = { type = 'execute', name = "General spells", order = 8, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "general") end, }, btnRaces = { type = 'execute', name = "General races", order = 9, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "races") end, }, btnDK = { type = 'execute', name = "Death Knight", order = 10, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "dk") end, }, btnDruid = { type = 'execute', name = "Druid", order = 11, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "druid") end, }, btnHunt = { type = 'execute', name = "Hunter", order = 12, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "hunter") end, }, btnMage = { type = 'execute', name = "Mage", order = 13, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "mage") end, }, btnPaladin = { type = 'execute', name = "Paladin", order = 14, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "paladin") end, }, btnPriest = { type = 'execute', name = "Priest", order = 15, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "priest") end, }, btnRogue = { type = 'execute', name = "Rogue", order = 16, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "rogue") end, }, btnShaman = { type = 'execute', name = "Shaman", order = 17, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "shaman") end, }, btnWarlock = { type = 'execute', name = "Warlock", order = 18, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "warlock") end, }, btnWarrior = { type = 'execute', name = "Warrior", order = 19, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellauraApplied", "warrior") end, }, }, }, general = { type = 'group', name = "General spells", order = 1, args = { class = { type = 'toggle', name = "Alert Class calling for trinketting in Arena", desc = "Alert when an enemy class trinkets in arena", confirm = function() PlaySoundFile(sadb.sapath.."paladin.mp3"); end, order = 1, }, drinking = { type = 'toggle', name = "Alert Drinking in Arena", desc = "Alert when an enemy drinks in arena", order = 2, }, trinket = { type = 'toggle', name = SpellTexture(42292).."PvP Trinket/Every Man for Himself", desc = function () GameTooltip:SetHyperlink(GetSpellLink(42292)); end, descStyle = "custom", order = 3, }, objects = { type = 'group', inline = true, name= "Objects", order = 5, args = listOption({54861,54758},"auraApplied"), }, } }, races = { type = 'group', name = "|cffFFFFFFGeneral races|r", order = 4, args = listOption({58984,26297,20594,33702,7744,28880},"auraApplied"), }, dk = { type = 'group', name = "|cffC41F3BDeath Knight|r", order = 10, args = { dkBlood = { type = 'group', inline = true, name= SpellTexture(48266).." |cffC41F3BBlood|r", order = 5, args = listOption({45529,49028,49016,55233},"auraApplied"), }, spacerFrost = { order = 6, type = "description", name = " " }, dkFrost = { type = 'group', inline = true, name= SpellTexture(48263).."|cffC41F3B Frost |r", order = 10, args = listOption({57623,48792,49039,51271},"auraApplied"), }, spacerUH = { order = 11, type = "description", name = " " }, dkUnholy = { type = 'group', inline = true, name= SpellTexture(48265).."|cffC41F3B Unholy |r", order = 15, args = listOption({48707,51052,49222},"auraApplied"), }, } }, druid = { order = 11, type = 'group', name = "|cffFF7D0ADruid|r", args = { druidBalance= { type = 'group', inline = true, name = SpellTexture(48463).." |cffFF7D0ABalance|r", order = 1, args = listOption({16870,22812,29166,53312,53201,53307},"auraApplied"), }, spacerFeral = { order = 5, type = "description", name = " " }, druidFeral = { type = 'group', inline = true, name = SpellTexture(9634).." |cffFF7D0AFeral Combat|r", order = 6, args = listOption({50334,33357,5229,22842,52610,61336,69369},"auraApplied"), }, spacerResto = { order = 10, type = "description", name = " " }, druidResto = { type = 'group', inline = true, name = SpellTexture(48378).." |cffFF7D0ARestoration|r", order = 11, args = listOption({48470,48469,17116},"auraApplied"), }, } }, hunter = { order = 12, type = 'group', name = "|cffABD473Hunter|r", args = { beastmastery = { type = 'group', inline = true, name = SpellTexture(1515).." |cffABD473 Beast Mastery|r", order = 1, args = listOption({34027,54216,34471},"auraApplied"), }, spacerMM = { order = 5, type = "description", name = " " }, marksman = { type = 'group', inline = true, name = SpellTexture(58434).." |cffABD473Marksmanship|r", order = 6, args = listOption({3045},"auraApplied"), }, spacerSurvival = { order = 10, type = "description", name = " " }, survival = { type = 'group', inline = true, name = SpellTexture(53339).." |cffABD473Survival|r", order = 11, args = listOption({19263,35079},"auraApplied"), }, spacerPet = { order = 15, type = "description", name = " " }, pet = { type = 'group', inline = true, name = "|cffABD473Pet|r", order = 16, args = { Gen = { type = 'group', inline = false, name = "", order = 1, args = listOption({53480,53517,1742},"auraApplied"), }, Crab = { type = 'group', inline = false, name = "|cffABD473Crab|r", order = 1, args = listOption({53476,53479},"auraApplied"), }, Ravager = { type = 'group', inline = false, name = "|cffABD473Ravager|r", order = 1, args = listOption({61684},"auraApplied"), }, }, }, }, }, mage = { order = 13, type = 'group', name = "|cff69CCF0Mage|r", args = { arcane = { order = 1, type = 'group', inline = true, name = SpellTexture(42995).."|cff69CCF0 Arcane |r", args = listOption({12042,66,43020,12043,130,44401},"auraApplied"), }, spacerFire = { order = 5, type = "description", name = " " }, fire = { order = 6, type = 'group', inline = true, name = SpellTexture(42833).."|cff69CCF0 Fire |r", args = listOption({28682,43010,31643,64343,48108},"auraApplied"), }, spacerFrost = { order = 10, type = "description", name = " " }, frost = { order = 11, type = 'group', inline = true, name = SpellTexture(42842).."|cff69CCF0 Frost |r", args = listOption({43012,43039,45438,12472,74396,57761},"auraApplied"), }, }, }, paladin = { order = 14, type = 'group', name = "|cffF58CBAPaladin|r", args = { holy = { order = 1, type = 'group', inline = true, name = SpellTexture(48782).."|cffF58CBA Holy |r", args = listOption({31821,53563,31842,54428,53601,54149},"auraApplied"), }, spacerProt = { order = 5, type = "description", name = " " }, protection = { order = 6, type = 'group', inline = true, name = SpellTexture(48942).."|cffF58CBA Protection |r", args = listOption({498,64205,642,1044,10278,6940,1038,25780,20178},"auraApplied"), }, spacerRet = { order = 10, type = "description", name = " " }, retribution = { order = 11, type = 'group', inline = true, name = SpellTexture(54043).."|cffF58CBA Retribution |r", args = listOption({31884,59578,54203},"auraApplied"), }, }, }, priest = { order = 15, type = 'group', name = "|cffFFFFFFPriest|r", args = { discipline = { order = 1, type = 'group', inline = true, name = SpellTexture(48161).."|cffFFFFFF Discipline |r", args = listOption({6346,48168,33206,10060,48066},"auraApplied"), }, spacerHoly = { order = 5, type = "description", name = " " }, holy = { order = 6, type = 'group', inline = true, name = SpellTexture(48782).."|cffFFFFFF Holy |r", args = listOption({47788},"auraApplied"), }, spacerShadow = { order = 10, type = "description", name = " " }, shadow = { order = 11, type = 'group', inline = true, name = SpellTexture(48125).."|cffFFFFFF Shadow |r", args = listOption({47585,586,15473},"auraApplied"), }, } }, rogue = { type = 'group', name = "|cffFFF569Rogue|r", order = 16, args = { assassination = { order = 1, type = 'group', inline = true, name = SpellTexture(48668).."|cffFFF569 Assassination |r", args = listOption({14177},"auraApplied"), }, spacerCombat = { order = 5, type = "description", name = " " }, combat = { order = 6, type = 'group', inline = true, name = SpellTexture(48657).."|cffFFF569 Combat |r", args = listOption({13750, 26669, 48659, 51690, 11305},"auraApplied"), }, spacerSub = { order = 10, type = "description", name = " " }, subtlety = { order = 11, type = 'group', inline = true, name = SpellTexture(1784).."|cffFFF569 Subtlety |r", args = listOption({31224,51713,57934,45182},"auraApplied"), }, }, }, shaman = { type = 'group', name = "|cff0070DEShaman|r", order = 17, args = { elem = { order = 1, type = 'group', inline = true, name = SpellTexture(49238).."|cff0070DE Elemental Combat |r", args = listOption({16166},"auraApplied"), }, spacerEH = { order = 5, type = "description", name = " " }, EH = { order = 6, type = 'group', inline = true, name = SpellTexture(49281).."|cff0070DE Enhancement |r", args = listOption({2645,32182,30823,53817},"auraApplied"), }, spacerResto = { order = 10, type = "description", name = " " }, Resto = { order = 11, type = 'group', inline = true, name = SpellTexture(49273).."|cff0070DE Restauration |r", args = listOption({49284,57960,16188},"auraApplied"), }, } }, warlock = { type = 'group', name = "|cff9482C9Warlock|r", order = 18, args = { affliction = { order = 1, type = 'group', inline = true, name = SpellTexture(47860).." |cff9482C9Affliction|r", args = listOption({17941},"auraApplied"), }, spacerDemo = { order = 5, type = "description", name = " " }, demonology = { order = 6, type = 'group', inline = true, name = SpellTexture(5500).." |cff9482C9Demonology|r", args = listOption({47891,18708},"auraApplied"), }, spacerDestro = { order = 15, type = "description", name = " " }, destruction = { order = 16, type = 'group', inline = true, name = SpellTexture(47820).." |cff9482C9Destruction|r", args = listOption({54277},"auraApplied"), }, }, }, warrior = { order = 19, type = 'group', name = "|cffC79C6EWarrior|r", args = { arms = { order = 1, type = 'group', inline = true, name = SpellTexture(2457).." |cffC79C6EArms|r", args = listOption({46924,20230,12328,60503},"auraApplied"), }, spacerFury = { order = 5, type = "description", name = " " }, fury = { order = 6, type = 'group', inline = true, name = SpellTexture(2458).." |cffC79C6EFury|r", args = listOption({18499,12292,55694,1719,47436,47440},"auraApplied"), }, spacerProt = { order = 10, type = "description", name = " " }, protection = { order = 11, type = 'group', inline = true, name = SpellTexture(71).." |cffC79C6EProtection|r", args = listOption({12975,2565,871,23920,50227},"auraApplied"), }, }, }, } }, spellAuraRemoved = { type = 'group', name = "Enemy Aura Down", desc = "Alerts you when enemy aura or used cooldowns are off the enemy", set = setOption, get = getOption, disabled = function() return sadb.auraRemoved end, order = 3, args = { inlineCategories = { type = 'group', inline = true, name = "", order = 0, args = { btnGen = { type = 'execute', name = "General spells", order = 8, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "general") end, }, btnRaces = { type = 'execute', name = "General races", order = 9, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "races") end, }, btnDK = { type = 'execute', name = "Death Knight", order = 10, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "dk") end, }, btnDruid = { type = 'execute', name = "Druid", order = 11, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "druid") end, }, btnHunt = { type = 'execute', name = "Hunter", order = 12, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "hunter") end, }, btnMage = { type = 'execute', name = "Mage", order = 13, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "mage") end, }, btnPaladin = { type = 'execute', name = "Paladin", order = 14, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "paladin") end, }, btnPriest = { type = 'execute', name = "Priest", order = 15, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "priest") end, }, btnRogue = { type = 'execute', name = "Rogue", order = 16, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "rogue") end, }, btnShaman = { type = 'execute', name = "Shaman", order = 17, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "shaman") end, }, btnWarlock = { type = 'execute', name = "Warlock", order = 18, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "warlock") end, }, btnWarrior = { type = 'execute', name = "Warrior", order = 19, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellAuraRemoved", "warrior") end, }, }, }, general = { type = 'group', name = "General spells", order = 1, args = { objects = { type = 'group', inline = true, name= "Objects", order = 5, args = listOption({54861,54758},"auraRemoved"), }, } }, races = { type = 'group', name = "|cffFFFFFFGeneral Races|r", order = 4, args = listOption({58984,26297,20594,33702,7744,28880},"auraRemoved"), }, dk = { type = 'group', name = "|cffC41F3BDeath Knight|r", order = 10, args = { dkBlood = { type = 'group', inline = true, name= SpellTexture(48266).." |cffC41F3BBlood|r", order = 5, args = listOption({45529,49028,49016,55233},"auraRemoved"), }, spacerFrost = { order = 6, type = "description", name = " " }, dkFrost = { type = 'group', inline = true, name= SpellTexture(48263).."|cffC41F3B Frost |r", order = 10, args = listOption({57623,48792,49039,51271},"auraRemoved"), }, spacerUH = { order = 11, type = "description", name = " " }, dkUnholy = { type = 'group', inline = true, name= SpellTexture(48265).."|cffC41F3B Unholy |r", order = 15, args = listOption({48707,51052,49222},"auraRemoved"), }, } }, druid = { order = 11, type = 'group', name = "|cffFF7D0ADruid|r", args = { druidBalance= { type = 'group', inline = true, name = SpellTexture(48463).." |cffFF7D0ABalance|r", order = 1, args = listOption({16870,22812,29166,53312,53201,53307},"auraRemoved"), }, spacerFeral = { order = 5, type = "description", name = " " }, druidFeral = { type = 'group', inline = true, name = SpellTexture(9634).." |cffFF7D0AFeral Combat|r", order = 6, args = listOption({50334,33357,5229,22842,52610,61336,69369},"auraRemoved"), }, spacerResto = { order = 10, type = "description", name = " " }, druidResto = { type = 'group', inline = true, name = SpellTexture(48378).." |cffFF7D0ARestoration|r", order = 11, args = listOption({48470,48469,17116},"auraRemoved"), }, } }, hunter = { order = 12, type = 'group', name = "|cffABD473Hunter|r", args = { beastmastery = { type = 'group', inline = true, name = SpellTexture(1515).." |cffABD473 Beast Mastery|r", order = 1, args = listOption({34027,54216,34471},"auraRemoved"), }, spacerMM = { order = 5, type = "description", name = " " }, marksman = { type = 'group', inline = true, name = SpellTexture(58434).." |cffABD473Marksmanship|r", order = 6, args = listOption({3045},"auraRemoved"), }, spacerSurvival = { order = 10, type = "description", name = " " }, survival = { type = 'group', inline = true, name = SpellTexture(53339).." |cffABD473Survival|r", order = 11, args = listOption({19263,35079},"auraRemoved"), }, spacerPet = { order = 15, type = "description", name = " " }, pet = { type = 'group', inline = true, name = "|cffABD473Pet|r", order = 16, args = { Gen = { type = 'group', inline = false, name = "", order = 1, args = listOption({53480,53517,1742},"auraRemoved"), }, Crab = { type = 'group', inline = false, name = "|cffABD473Crab|r", order = 1, args = listOption({53476,53479},"auraRemoved"), }, Ravager = { type = 'group', inline = false, name = "|cffABD473Ravager|r", order = 1, args = listOption({61684},"auraRemoved"), }, }, }, }, }, mage = { order = 13, type = 'group', name = "|cff69CCF0Mage|r", args = { arcane = { order = 1, type = 'group', inline = true, name = SpellTexture(42995).."|cff69CCF0 Arcane |r", args = listOption({12042,66,43020,12043,130,44401},"auraRemoved"), }, spacerFire = { order = 5, type = "description", name = " " }, fire = { order = 6, type = 'group', inline = true, name = SpellTexture(42833).."|cff69CCF0 Fire |r", args = listOption({28682,43010,31643,64343,48108},"auraRemoved"), }, spacerFrost = { order = 10, type = "description", name = " " }, frost = { order = 11, type = 'group', inline = true, name = SpellTexture(42842).."|cff69CCF0 Frost |r", args = listOption({43012,43039,45438,12472,74396,57761},"auraRemoved"), }, }, }, paladin = { order = 14, type = 'group', name = "|cffF58CBAPaladin|r", args = { holy = { order = 1, type = 'group', inline = true, name = SpellTexture(48782).."|cffF58CBA Holy |r", args = listOption({31821,53563,31842,54428,53601,54149},"auraRemoved"), }, spacerProt = { order = 5, type = "description", name = " " }, protection = { order = 6, type = 'group', inline = true, name = SpellTexture(48942).."|cffF58CBA Protection |r", args = listOption({498,64205,642,1044,10278,6940,1038,25780,20178},"auraRemoved"), }, spacerRet = { order = 10, type = "description", name = " " }, retribution = { order = 11, type = 'group', inline = true, name = SpellTexture(54043).."|cffF58CBA Retribution |r", args = listOption({31884,59578,54203},"auraRemoved"), }, }, }, priest = { order = 15, type = 'group', name = "|cffFFFFFFPriest|r", args = { discipline = { order = 1, type = 'group', inline = true, name = SpellTexture(48161).."|cffFFFFFF Discipline |r", args = listOption({6346,48168,33206,10060,48066},"auraRemoved"), }, spacerHoly = { order = 5, type = "description", name = " " }, holy = { order = 6, type = 'group', inline = true, name = SpellTexture(48782).."|cffFFFFFF Holy |r", args = listOption({47788},"auraRemoved"), }, spacerShadow = { order = 10, type = "description", name = " " }, shadow = { order = 11, type = 'group', inline = true, name = SpellTexture(48125).."|cffFFFFFF Shadow |r", args = listOption({47585,586,15473},"auraRemoved"), }, } }, rogue = { type = 'group', name = "|cffFFF569Rogue|r", order = 16, args = { assassination = { order = 1, type = 'group', inline = true, name = SpellTexture(48668).."|cffFFF569 Assassination |r", args = listOption({14177},"auraRemoved"), }, spacerCombat = { order = 5, type = "description", name = " " }, combat = { order = 6, type = 'group', inline = true, name = SpellTexture(48657).."|cffFFF569 Combat |r", args = listOption({13750, 26669, 48659, 51690, 11305},"auraRemoved"), }, spacerSub = { order = 10, type = "description", name = " " }, subtlety = { order = 11, type = 'group', inline = true, name = SpellTexture(1784).."|cffFFF569 Subtlety |r", args = listOption({31224,51713,57934,45182},"auraRemoved"), }, }, }, shaman = { type = 'group', name = "|cff0070DEShaman|r", order = 17, args = { elem = { order = 1, type = 'group', inline = true, name = SpellTexture(49238).."|cff0070DE Elemental Combat |r", args = listOption({16166},"auraRemoved"), }, spacerEH = { order = 5, type = "description", name = " " }, EH = { order = 6, type = 'group', inline = true, name = SpellTexture(49281).."|cff0070DE Enhancement |r", args = listOption({2645,32182,30823,53817},"auraRemoved"), }, spacerResto = { order = 10, type = "description", name = " " }, Resto = { order = 11, type = 'group', inline = true, name = SpellTexture(49273).."|cff0070DE Restauration |r", args = listOption({49284,57960,16188},"auraRemoved"), }, } }, warlock = { type = 'group', name = "|cff9482C9Warlock|r", order = 18, args = { affliction = { order = 1, type = 'group', inline = true, name = SpellTexture(47860).." |cff9482C9Affliction|r", args = listOption({17941},"auraRemoved"), }, spacerDemo = { order = 5, type = "description", name = " " }, demonology = { order = 6, type = 'group', inline = true, name = SpellTexture(5500).." |cff9482C9Demonology|r", args = listOption({47891,18708},"auraRemoved"), }, spacerDestro = { order = 15, type = "description", name = " " }, destruction = { order = 16, type = 'group', inline = true, name = SpellTexture(47820).." |cff9482C9Destruction|r", args = listOption({54277},"auraRemoved"), }, }, }, warrior = { order = 19, type = 'group', name = "|cffC79C6EWarrior|r", args = { arms = { order = 1, type = 'group', inline = true, name = SpellTexture(2457).." |cffC79C6EArms|r", args = listOption({46924,20230,12328,60503},"auraRemoved"), }, spacerFury = { order = 5, type = "description", name = " " }, fury = { order = 6, type = 'group', inline = true, name = SpellTexture(2458).." |cffC79C6EFury|r", args = listOption({18499,12292,55694,1719,47436,47440},"auraRemoved"), }, spacerProt = { order = 10, type = "description", name = " " }, protection = { order = 11, type = 'group', inline = true, name = SpellTexture(71).." |cffC79C6EProtection|r", args = listOption({12975,2565,871,23920,50227},"auraRemoved"), }, }, }, } }, -- spellCastStart = { type = 'group', name = "Enemy Spell Casting", desc = "Alerts you when an enemy is attempting to cast a spell on you or another player", disabled = function() return sadb.castStart end, set = setOption, get = getOption, order = 4, args = { inlineCategories = { type = 'group', inline = true, name = "", order = 0, args = { btnGen = { type = 'execute', name = "General", order = 9, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "general") end, }, --[[btnDK = { type = 'execute', name = "Death Knight", order = 10, width = "full", disabled = true, func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "dk") end, },]] btnDruid = { type = 'execute', name = "Druid", order = 11, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "druid") end, }, btnHunt = { type = 'execute', name = "Hunter", order = 12, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "hunter") end, }, btnMage = { type = 'execute', name = "Mage", order = 13, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "mage") end, }, btnPaladin = { type = 'execute', name = "Paladin", order = 14, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "paladin") end, }, btnPriest = { type = 'execute', name = "Priest", order = 15, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "priest") end, }, btnRogue = { type = 'execute', name = "Rogue", order = 16, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "rogue") end, }, btnShaman = { type = 'execute', name = "Shaman", order = 17, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "shaman") end, }, btnWarlock = { type = 'execute', name = "Warlock", order = 18, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "warlock") end, }, btnWarrior = { type = 'execute', name = "Warrior", order = 19, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastStart", "warrior") end, }, }, }, general = { type = 'group', name = "General Spells", order = 2, args = { bigHeal = { type = 'toggle', name = SpellTexture(48782).."Big Heals", desc = "Heal, Holy Light, Healing Wave, Healing Touch", order = 1, }, resurrection = { type = 'toggle', name = SpellTexture(20609).."Resurrection spells", desc = "Ancestral Spirit, Redemption, etc", order = 2, }, } }, druid = { type = 'group', name = "|cffFF7D0ADruid|r", order = 2, args = { druidBalance= { type = 'group', inline = true, name = SpellTexture(48463).." |cffFF7D0ABalance|r", order = 1, args = listOption({18658,48467,33786,48465,53308,48461},"castStart"), }, --[[spacerFeral = { order = 5, type = "description", name = " " }, druidFeral = { type = 'group', inline = true, name = SpellTexture(9634).." |cffFF7D0AFeral Combat|r", order = 6, args = listOption({},"castStart"), },]] spacerResto = { order = 10, type = "description", name = " " }, druidResto = { type = 'group', inline = true, name = SpellTexture(48378).." |cffFF7D0ARestoration|r", order = 11, args = listOption({48443,48447},"castStart"), }, } }, hunter = { type = 'group', name = "|cffABD473Hunter|r", order = 3, args = { beastmastery = { type = 'group', inline = true, name = SpellTexture(1515).." |cffABD473 Beast Mastery|r", order = 1, args = listOption({982, 14327},"castStart"), }, spacerMM = { order = 5, type = "description", name = " " }, marksman = { type = 'group', inline = true, name = SpellTexture(58434).." |cffABD473Marksmanship|r", order = 6, args = listOption({49052},"castStart"), }, --[[spacerSurvival = { order = 10, type = "description", name = " " }, survival = { type = 'group', inline = true, name = SpellTexture(53339).." |cffABD473Survival|r", order = 11, args = listOption({},"castStart"), },]] }, }, mage = { type = 'group', name = "|cff69CCF0Mage|r", order = 4, args = { arcane = { order = 1, type = 'group', inline = true, name = SpellTexture(42995).."|cff69CCF0 Arcane |r", args = listOption({42897,28271,42846},"castStart"), }, spacerFire = { order = 5, type = "description", name = " " }, fire = { order = 6, type = 'group', inline = true, name = SpellTexture(42833).."|cff69CCF0 Fire |r", args = listOption({42833,42926,47610,42859},"castStart"), }, spacerFrost = { order = 10, type = "description", name = " " }, frost = { order = 11, type = 'group', inline = true, name = SpellTexture(42842).."|cff69CCF0 Frost |r", args = listOption({42842},"castStart"), }, }, }, paladin = { type = 'group', name = "|cffF58CBAPaladin|r", order = 5, args = { holy = { order = 1, type = 'group', inline = true, name = SpellTexture(48782).."|cffF58CBA Holy |r", args = listOption({48801,48785,10326},"castStart"), }, --[[spacerProt = { order = 5, type = "description", name = " " }, protection = { order = 6, type = 'group', inline = true, name = SpellTexture(48942).."|cffF58CBA Protection |r", args = listOption({},"castStart"), },]] --[[spacerRet = { order = 10, type = "description", name = " " }, retribution = { order = 11, type = 'group', inline = true, name = SpellTexture(54043).."|cffF58CBA Retribution |r", args = listOption({},"castStart"), },]] }, }, priest = { type = 'group', name = "|cffFFFFFFPriest|r", order = 6, args = { discipline = { order = 1, type = 'group', inline = true, name = SpellTexture(48161).."|cffFFFFFF Discipline |r", args = listOption({8129,9484,10955,32375},"castStart"), }, spacerHoly = { order = 5, type = "description", name = " " }, holy = { order = 6, type = 'group', inline = true, name = SpellTexture(48782).."|cffFFFFFF Holy |r", args = listOption({48120,48071,48135,48123},"castStart"), }, spacerShadow = { order = 10, type = "description", name = " " }, shadow = { order = 11, type = 'group', inline = true, name = SpellTexture(48125).."|cffFFFFFF Shadow |r", args = listOption({48127,605,48160},"castStart"), }, } }, rogue = { type = 'group', name = "|cffFFF569Rogue|r", order = 7, args = { subtlety = { order = 11, type = 'group', inline = true, name = SpellTexture(1784).."|cffFFF569 Subtlety |r", args = listOption({1842},"castStart"), }, }, }, shaman = { type = 'group', name = "|cff0070DEShaman|r", order = 8, args = { elem = { order = 1, type = 'group', inline = true, name = SpellTexture(49238).."|cff0070DE Elemental Combat |r", args = listOption({49271,51514,60043,49238},"castStart"), }, --[[spacerEH = { order = 5, type = "description", name = " " }, EH = { order = 6, type = 'group', inline = true, name = SpellTexture(49281).."|cff0070DE Enhancement |r", args = listOption({51514},"castStart"), },]] spacerResto = { order = 10, type = "description", name = " " }, Resto = { order = 11, type = 'group', inline = true, name = SpellTexture(49273).."|cff0070DE Restauration |r", args = listOption({49276},"castStart"), }, } }, warlock = { type = 'group', name = "|cff9482C9Warlock|r", order = 9, args = { affliction = { order = 1, type = 'group', inline = true, name = SpellTexture(47860).." |cff9482C9Affliction|r", args = listOption({6215,59164,17928,47836,47843},"castStart"), }, spacerDemo = { order = 5, type = "description", name = " " }, demonology = { order = 6, type = 'group', inline = true, name = SpellTexture(5500).." |cff9482C9Demonology|r", args = listOption({18647,47878,48018,61191,691,688,712,697,30146},"castStart"), }, spacerDestro = { order = 15, type = "description", name = " " }, destruction = { order = 16, type = 'group', inline = true, name = SpellTexture(47820).." |cff9482C9Destruction|r", args = listOption({59172,47811,47838,47815,47825},"castStart"), }, spacerPet = { order = 20, type = "description", name = " " }, pet = { order = 21, type = 'group', inline = true, name = "|cff9482C9Pet|r", args = { succube = { type = 'group', inline = false, name = SpellTexture(712).."|cff9482C9 Succube |r", order = 2, args = listOption({6358},"castStart"), }, --[[voidwalker = { type = 'group', inline = true, name = SpellTexture(697).." Voidwalker", order = 3, args = listOption({ },"castSuccess"), },]] } }, }, }, warrior = { type = 'group', name = "|cffC79C6EWarrior|r", order = 10, args = { arms = { order = 1, type = 'group', inline = true, name = SpellTexture(2457).." |cffC79C6EArms|r", args = listOption({64382},"castStart"), }, --[[spacerFury = { order = 5, type = "description", name = " " }, fury = { order = 6, type = 'group', inline = true, name = SpellTexture(2458).." |cffC79C6EFury|r", args = listOption({},"castStart"), },]] --[[spacerProt = { order = 10, type = "description", name = " " }, protection = { order = 11, type = 'group', inline = true, name = SpellTexture(71).." |cffC79C6EProtection|r", args = listOption({},"castStart"), },]] }, }, }, }, spellCastSuccess = { type = 'group', name = "Enemy Cooldown Abilities", desc = "Alerts you when enemies have used cooldowns", disabled = function() return sadb.castSuccess end, set = setOption, get = getOption, order = 5, args = { inlineCategories = { type = 'group', inline = true, name = "", order = 0, args = { btnGen = { type = 'execute', name = "General", order = 9, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "general") end, }, btnDK = { type = 'execute', name = "Death Knight", order = 10, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "dk") end, }, btnDruid = { type = 'execute', name = "Druid", order = 11, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "druid") end, }, btnHunt = { type = 'execute', name = "Hunter", order = 12, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "hunter") end, }, btnMage = { type = 'execute', name = "Mage", order = 13, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "mage") end, }, btnPaladin = { type = 'execute', name = "Paladin", order = 14, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "paladin") end, }, btnPriest = { type = 'execute', name = "Priest", order = 15, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "priest") end, }, btnRogue = { type = 'execute', name = "Rogue", order = 16, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "rogue") end, }, btnShaman = { type = 'execute', name = "Shaman", order = 17, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "shaman") end, }, btnWarlock = { type = 'execute', name = "Warlock", order = 18, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "warlock") end, }, btnWarrior = { type = 'execute', name = "Warrior", order = 19, width = "full", func = function() AceConfigDialog:SelectGroup("SoundAlerter", "Spells", "spellCastSuccess", "warrior") end, }, }, }, general = { type = 'group', name = "General spells", order = 1, args = { objects = { type = 'group', inline = true, name= "Objects", order = 5, args = listOption({71607,54757},"castSuccess"), }, } }, dk = { type = 'group', name = "|cffC41F3BDeath Knight|r", order = 10, args = { dkBlood = { type = 'group', inline = true, name= SpellTexture(48266).." |cffC41F3BBlood|r", order = 5, args = listOption({49941,48266,49930,56222,48743,55262,49005,50842,48982,47476},"castSuccess"), }, spacerFrost = { order = 6, type = "description", name = " " }, dkFrost = { type = 'group', inline = true, name= SpellTexture(48263).."|cffC41F3B Frost |r", order = 10, args = listOption({45524,49796,47568,48263,55268,49203,49909,47528,51425,56815},"castSuccess"), }, spacerUH = { order = 11, type = "description", name = " " }, dkUnholy = { type = 'group', inline = true, name= SpellTexture(48265).."|cffC41F3B Unholy |r", order = 15, args = listOption({51328,49938,49576,49924,49921,61999,46584,55271,49206,48265},"castSuccess"), }, spacerPet = { order = 16, type = "description", name = " " }, dkpet = { type = 'group', inline = true, name= SpellTexture(42650).." Pet", order = 20, args = listOption({47468,47481,47482,47484},"castSuccess"), }, } }, druid = { type = 'group', name = "|cffFF7D0ADruid|r", order = 11, args = { druidBalance= { type = 'group', inline = true, name = SpellTexture(48463).." |cffFF7D0ABalance|r", order = 1, args = listOption({770,33831,48467,48468,48463,24858,61384},"castSuccess"), }, spacerFeral = { order = 5, type = "description", name = " " }, druidFeral = { type = 'group', inline = true, name = SpellTexture(9634).." |cffFF7D0AFeral Combat|r", order = 6, args = listOption({8983,768,9634,48570,48560,16857,16979,49376,48577,48568,49802,33878,33876,48480,49803,5215,48574,48579,49800,48572,48562,62078,50213,5225,783},"castSuccess"), }, spacerResto = { order = 10, type = "description", name = " " }, druidResto = { type = 'group', inline = true, name = SpellTexture(48378).." |cffFF7D0ARestoration|r", order = 11, args = listOption({2893,48470,48469,48451,17116,48441,2782,18562,33891,53251},"castSuccess"), }, } }, hunter = { type = 'group', name = "|cffABD473Hunter|r", order = 12, args = { beastmastery = { type = 'group', inline = true, name = SpellTexture(1515).." |cffABD473 Beast Mastery|r", order = 1, args = listOption({13161,5118,61847,27044,13163,13159,34074,49071,6991,48990},"castSuccess"), }, spacerMM = { order = 5, type = "description", name = " " }, marksman = { type = 'group', inline = true, name = SpellTexture(58434).." |cffABD473Marksmanship|r", order = 6, args = listOption({49050,49045,53209,5116,20736,1543,53338,61006,49048,23989,3043,49001,34490,19801,3034,58434},"castSuccess"), }, spacerSurvival = { order = 10, type = "description", name = " " }, survival = { type = 'group', inline = true, name = SpellTexture(53339).." |cffABD473Survival|r", order = 11, args = listOption({781,49067,5384,60192,14311,13809,49056,53339,48996,19503,34600,19885,19883,49010},"castSuccess"), }, spacerPet = { order = 15, type = "description", name = " " }, pet = { type = 'group', inline = true, name = "|cffABD473Pet|r", order = 16, args = { Crab = { type = 'group', inline = false, name = "|cffABD473Crab|r", order = 1, args = listOption({61685,52472,53547},"castSuccess"), }, Ravager = { type = 'group', inline = false, name = "|cffABD473Ravager|r", order = 2, args = listOption({53561,53490,52473,61684},"castSuccess"), }, }, }, }, }, mage = { type = 'group', name = "|cff69CCF0Mage|r", order = 13, args = { arcane = { order = 1, type = 'group', inline = true, name = SpellTexture(42995).."|cff69CCF0 Arcane |r", args = listOption({44781,42921,42846,1953,42987,2139,12051,66,55342,475,31589,30449},"castSuccess"), }, spacerFire = { order = 5, type = "description", name = " " }, fire = { order = 6, type = 'group', inline = true, name = SpellTexture(42833).."|cff69CCF0 Fire |r", args = listOption({42945, 42950,42873,55360},"castSuccess"), }, spacerFrost = { order = 10, type = "description", name = " " }, frost = { order = 11, type = 'group', inline = true, name = SpellTexture(42842).."|cff69CCF0 Frost |r", args = listOption({42940,11958, 42931,44572,42917,42914,31687},"castSuccess"), }, spacerPet = { order = 20, type = "description", name = " " }, pet = { order = 21, type = 'group', inline = true, name = "|cff69CCF0Pet|r", args = { waterElem = { type = 'group', inline = false, name = SpellTexture(31687).."|cff9482C9 Felhunter |r", order = 1, args = listOption({33395},"castSuccess"), }, } }, }, }, paladin = { type = 'group', name = "|cffF58CBAPaladin|r", order = 14, args = { holy = { order = 1, type = 'group', inline = true, name = SpellTexture(48782).."|cffF58CBA Holy |r", args = listOption({4987,19746,48819,20216,48825,48817,48788,1152},"castSuccess"), }, spacerProt = { order = 5, type = "description", name = " " }, protection = { order = 6, type = 'group', inline = true, name = SpellTexture(48942).."|cffF58CBA Protection |r", args = listOption({48827,48942,48947,48945,10308,53595,62124,20164,48943,61411},"castSuccess"), }, spacerRet = { order = 10, type = "description", name = " " }, retribution = { order = 11, type = 'group', inline = true, name = SpellTexture(54043).."|cffF58CBA Retribution |r", args = listOption({32223,35395,53385, 48806,53407,20271,53408,20066,54043},"castSuccess"), }, }, }, priest = { type = 'group', name = "|cffFFFFFFPriest|r", order = 15, args = { discipline = { order = 1, type = 'group', inline = true, name = SpellTexture(48161).."|cffFFFFFF Discipline |r", args = listOption({988,53007},"castSuccess"), }, spacerHoly = { order = 5, type = "description", name = " " }, holy = { order = 6, type = 'group', inline = true, name = SpellTexture(48782).."|cffFFFFFF Holy |r", args = listOption({552, 528,48173,48078,48068,48113},"castSuccess"), }, spacerShadow = { order = 10, type = "description", name = " " }, shadow = { order = 11, type = 'group', inline = true, name = SpellTexture(48125).."|cffFFFFFF Shadow |r", args = listOption({48300,48156,53023, 64044,10890,48158,48125,34433,15487},"castSuccess"), }, } }, rogue = { type = 'group', name = "|cffFFF569Rogue|r", order = 16, args = { assassination = { order = 1, type = 'group', inline = true, name = SpellTexture(48668).."|cffFFF569 Assassination |r", args = listOption({48691, 1833,48674,51722,57993,48668,8647,48676,8643,48666,48672},"castSuccess"), }, spacerCombat = { order = 5, type = "description", name = " " }, combat = { order = 6, type = 'group', inline = true, name = SpellTexture(48657).."|cffFFF569 Combat |r", args = listOption({48657,51723, 1776,1766,5938,48638,13877},"castSuccess"), }, spacerSub = { order = 10, type = "description", name = " " }, subtlety = { order = 11, type = 'group', inline = true, name = SpellTexture(1784).."|cffFFF569 Subtlety |r", args = listOption({2094,1725,48660,14183,14185,51724,36554,1784,26889},"castSuccess"), }, }, }, shaman = { type = 'group', name = "|cff0070DEShaman|r", order = 17, args = { elem = { order = 1, type = 'group', inline = true, name = SpellTexture(49238).."|cff0070DE Elemental Combat |r", args = listOption({66843, 66842,66844,49231,2484,2894,61657,49233,49236,58734,8012,58704,58582,59159,57722,57994},"castSuccess"), }, spacerEH = { order = 5, type = "description", name = " " }, EH = { order = 6, type = 'group', inline = true, name = SpellTexture(49281).."|cff0070DE Enhancement |r", args = listOption({2062,51533,58739,58656,58745,8177,60103,49281,58749,58753,17364,58643,8512,3738},"castSuccess"), }, spacerResto = { order = 10, type = "description", name = " " }, Resto = { order = 11, type = 'group', inline = true, name = SpellTexture(49273).."|cff0070DE Restauration |r", args = listOption({51886,8170,526,58757,58774,16190,16188,61301,55198,36936,8143},"castSuccess"), }, } }, warlock = { type = 'group', name = "|cff9482C9Warlock|r", order = 18, args = { affliction = { order = 1, type = 'group', inline = true, name = SpellTexture(47860).." |cff9482C9Affliction|r", args = listOption({47813,47864,47867,18223,47865,11719,50511,47860,47857,5138,47855,17928,57946},"castSuccess"), }, spacerDemo = { order = 5, type = "description", name = " " }, demonology = { order = 6, type = 'group', inline = true, name = SpellTexture(5500).." |cff9482C9Demonology|r", args = listOption({47875,48020,132,47856,1122},"castSuccess"), }, spacerDestro = { order = 15, type = "description", name = " " }, destruction = { order = 16, type = 'group', inline = true, name = SpellTexture(47820).." |cff9482C9Destruction|r", args = listOption({17962,47823,47820,47827,61290,47847},"castSuccess"), }, spacerPet = { order = 20, type = "description", name = " " }, pet = { order = 21, type = 'group', inline = true, name = "|cff9482C9Pet|r", args = { felhunter = { type = 'group', inline = false, name = SpellTexture(691).."|cff9482C9 Felhunter |r", order = 1, args = listOption({19647,48011},"castSuccess"), }, succube = { type = 'group', inline = false, name = SpellTexture(712).."|cff9482C9 Succube |r", order = 2, args = listOption({7870},"castSuccess"), }, --[[voidwalker = { type = 'group', inline = true, name = SpellTexture(697).." Voidwalker", order = 3, args = listOption({ },"castSuccess"), },]] } }, }, }, warrior = { type = 'group', name = "|cffC79C6EWarrior|r", order = 19, args = { arms = { order = 1, type = 'group', inline = true, name = SpellTexture(2457).." |cffC79C6EArms|r", args = listOption({2457,11578,1715,47450,57755,694,47486,7384,47465,47502},"castSuccess"), }, spacerFury = { order = 5, type = "description", name = " " }, fury = { order = 6, type = 'group', inline = true, name = SpellTexture(2458).." |cffC79C6EFury|r", args = listOption({2458,23881,1161,47520,47437,47471,60970,20252,5246,12323,6552,47475,34428,1680},"castSuccess"), }, spacerProt = { order = 10, type = "description", name = " " }, protection = { order = 11, type = 'group', inline = true, name = SpellTexture(71).." |cffC79C6EProtection|r", args = listOption({71,2687,12809,47498,676,3411,57823,72,47488,46968,7386,355},"castSuccess"), }, }, }, }, }, -- enemydebuff = { type = 'group', --inline = true, name = "Enemy Debuff", desc = "Alerts you when you (or your arena partner) have casted a CC on an enemy", disabled = function() return sadb.dEnemyDebuff end, set = setOption, get = getOption, order = 6, args = { fromself = { type = 'group', inline = true, name = "|cffFFF569From Self|r", order = 1, args = listOption({2094,51724,51514,12826,118,33786},"enemyDebuffs"), }, fromarenapartner = { type = 'group', inline = true, name = "|cffFFF569From Arena Partner or affecting your Target|r", order = 2, args = listOption({2094,51724,51514,12826,118,33786},"friendCCenemy"), } }, }, enemydebuffdown = { type = 'group', --inline = true, name = "Enemy Debuff Down", desc = "Alerts you when your (or your arena partner) casted CC's on an enemy is down", disabled = function() return sadb.dEnemyDebuffDown end, set = setOption, get = getOption, order = 7, args = { fromself = { type = 'group', inline = true, name = "|cffFFF569From Self|r", order = 1, args = listOption({2094,51724,51514,12826,118,33786},"enemyDebuffdown"), }, fromarenapartner = { type = 'group', inline = true, name = "|cffFFF569From Arena Partner or affecting your Target|r", desc = "Alerts you if your arena partner casts a spell or your target gets afflicted by a spell", order = 2, args = listOption({2094,51724,51514,12826,118,33786},"enemyDebuffdownAP"), } }, }, -- chatalerter = { type = 'group', name = "Chat Alerts", desc = "Alerts you and others via sending a chat message", disabled = function() return sadb.chatalerts end, set = setOption, get = getOption, order = 1, args = { caonlyTF = { type = 'toggle', name = L["Target and Focus only"], desc = L["Alerts you when your target or focus is applicable to a sound alert"], order = 1, }, chatgroup = { type = 'select', name = L["What channel to alert in"], desc = L["You send a message to either party, raid, say or battleground with your chat alert"], values = self.SA_CHATGROUP, order = 2, }, spells = { type = 'group', inline = true, name = "Spells", order = 3, args = { stealthenemy = { type = 'toggle', name = SpellTextureName(1784), desc = function () GameTooltip:SetHyperlink(GetSpellLink(1784)); end, order = 1, }, blindenemy = { type = 'toggle', name = SpellTexture(2094).."Blind on Enemy", desc = "Enemies you blind will be alerted in chat", order = 3, }, blindselffriend = { type = 'toggle', name = SpellTexture(2094).."Blind on Self/Friend", desc = "Enemies that have blinded you will be alerted", order = 4, }, cycloneenemy = { type = 'toggle', name = SpellTexture(33786).."Cyclone on Enemy", desc = "Enemies you cyclone will be alerted in chat", order = 5, }, cycloneselffriend = { type = 'toggle', name = SpellTexture(33786).."Cyclone on Self/Friend", desc = "Enemies you cyclone will be alerted in chat", order = 6, }, hexenemy = { type = 'toggle', name = SpellTexture(51514).."Hex on Enemy", desc = "Enemies you hex will be alerted in chat", order = 7, }, hexselffriend = { type = 'toggle', name = SpellTexture(51514).."Hex on Self/Friend", desc = "Enemies you hex will be alerted in chat", order = 8, }, fearenemy = { type = 'toggle', name = SpellTexture(5484).."Fear on Enemy", desc = "Enemies you fear will be alerted in chat", order = 9, }, fearselffriend = { type = 'toggle', name = SpellTexture(5484).."Fear on Self/friend", desc = "Enemies you fear will be alerted in chat", order = 10, }, sapenemy = { type = 'toggle', name = SpellTexture(6770).."Sap on Enemy", desc = "Enemies you sapped will be alerted", order = 11, }, bubbleenemy = { type = 'toggle', name = SpellTextureName(642), desc = "Enemies that have casted Divine Shield will be alerted", order = 12, }, polyenemy = { type = 'toggle', name = SpellTextureName(118), desc = "Enemies that have casted Polymorph will be alerted", order = 13, }, vanishenemy = { type = 'toggle', name = SpellTextureName(26889), desc = "Enemies that have casted Vanish will be alerted", order = 13, }, trinketalert = { type = 'toggle', name = GetSpellInfo(42292), desc = function () GameTooltip:SetHyperlink(GetSpellLink(42292)); end, order = 14, }, interruptenemy = { type = 'toggle', name = "Interrupt on Enemy", desc = "Sends a chat message if you have interrupted an enemy's spell.", order = 15, }, interruptself = { type = 'toggle', name = "Interrupt on Self", desc = "Sends a chat message if an enemy has interrupted you.", order = 16, }, chatdownself = { type = 'toggle', name = "Alert enemy debuff down (from self)", desc = "Sends a chat message when an enemies debuff is down that came from yourself (eg. Hex down)", order = 17, }, chatdownfriend = { type = 'toggle', name = "Alert enemy debuff down (from friend)", desc = "Sends a chat message when an enemies debuff is down that came from yourself (eg. Hex down)", order = 17, }, }, }, general = { type = "group", inline = true, name = "General Chat Alerts", args = { enemychat = { type = "input", name = "To Enemy", desc = "Example: '#spell# up on #enemy#' = [Blind] up on Enemyname", order = 1, width = "full", }, friendchat = { type = "input", name = "From Enemy to friend", desc = "Example: '#enemy# casted #spell# on #target# = Enemyname casted [Blind] on FriendName", order = 2, width = "full", }, selfchat = { type = "input", name = "From Enemy to self", desc = "Example: '#enemy# casted #spell# on #target# = Enemyname casted [Blind] on FriendName", order = 3, width = "full", }, enemybuffchat = { type = "input", name = "Enemy buffs/cooldowns", desc = "Example: '#enemy# casted #spell# = Enemyname casted [Stealth]", order = 4, width = "full", }, }, }, saptextfriendg = { type = "group", inline = true, hidden = function() if sadb.sapenemy then return false else return true end end, name = SpellTexture(6770).."Sap on self/friend", order = 13, args = { sapselftext = { type = "input", name = "Sap on Self (Avoid using '#enemy# due to unknown enemy when stealthed)", order = 1, width = "full", }, sapfriendtext = { type = "input", name = "Sap on Friend (Avoid using '#enemy# due to unknown enemy when stealthed)", order = 1, width = "full", }, }, }, trinketalerttextg = { type = "group", inline = true, hidden = function() if sadb.trinketalert then return false else return true end end, name = "PvP trinket text", order = 14, args = { trinketalerttext = { type = 'input', name = "Example: '#enemy# casted #spell#!' = Enemyname casted [PvP Trinket]!", order = 1, width = "full", }, }, }, stealthalerttextg = { type = "group", inline = true, hidden = function() if sadb.stealthenemy then return false else return true end end, name = SpellTextureName(1784), order = 15, args = { stealthTF = { type = 'toggle', name = "Ignore target/focus", order = 2, }, }, }, vanishalerttextg = { type = "group", inline = true, hidden = function() if sadb.vanishenemy then return false else return true end end, name = SpellTextureName(26889), order = 16, args = { vanishTF = { type = 'toggle', name = "Ignore target/focus", order = 2, }, }, }, InterruptTextg = { type = "group", inline = true, name = "Interrupt Text", order = 17, args = { InterruptEnemyText = { name = "Interrupt on Enemy (eg. 'Interrupted #enemy# with #spell#')", hidden = function() if sadb.interruptenemy then return false else return true end end, type = "input", order = 1, width = "full", }, InterruptSelfText = { name = "Interrupts from Enemy (eg. '#enemy# interrupted me with #spell#')", hidden = function() if sadb.interruptself then return false else return true end end, type = "input", order = 1, width = "full", }, }, }, }, }, -- FriendDebuff = { type = 'group', --inline = true, name = "Arena partner Enemy Spell Casting", desc = "Alerts you when an enemy is casting a spell targetted at your arena partner", disabled = function() return sadb.dArenaPartner end, set = setOption, get = getOption, order = 8, args = listOption({51514,118,33786,6215},"friendCCs"), }, FriendDebuffSuccess = { type = 'group', name = "Arena partner CCs/Debuffs", desc = "Alerts you when your arena partner gets CC'd", disabled = function() return sadb.dArenaPartner end, set = setOption, get = getOption, order = 9, args = listOption({14309,2094,10308,51514,12826,33786,6215,2139,51724},"friendCCSuccess"), }, -- selfDebuffs = { type = 'group', --inline = true, name = "Self Debuffs", desc = "Alerts you when you get afflicted by one of these spells when you aren't targeting the enemy.", disabled = function() return sadb.dSelfDebuff end, set = setOption, get = getOption, order = 10, args = listOption({33786,51514,118,6215,14309,13809,5246,17928,2094,51724,10308,47860,5138,44572,20066,34490,19434,47476,51722,61606,19386,6358},"selfDebuff"), }, }, }) self:AddOption('custom', { type = 'group', name = L["Custom Alerts"], desc = L["Create a custom sound or chat alert with text or a sound file"], order = 3, args = { newalert = { type = 'execute', name = function () if sadb.custom[L["New Alert"]] then return L["Rename the New Alert entry"] else return L["New Alert"] end end, order = -1, func = function() sadb.custom[L["New Alert"]] = { name = L["New Alert"], soundfilepath = L["New Alert"]..".[ogg/mp3/wav]", sourceuidfilter = "any", destuidfilter = "any", eventtype = { SPELL_CAST_SUCCESS = true, SPELL_CAST_START = false, SPELL_AURA_APPLIED = false, SPELL_AURA_REMOVED = false, SPELL_INTERRUPT = false, SPELL_SUMMON = false, }, sourcetypefilter = COMBATLOG_FILTER_EVERYTHING, desttypefilter = COMBATLOG_FILTER_EVERYTHING, order = 0, } self:OnOptionsCreate() end, disabled = function () if sadb.custom[L["New Alert"]] then return true else return false end end, }, } }) local function makeoption(key) local keytemp = key self.options.args.custom.args[key] = { type = 'group', name = sadb.custom[key].name, set = function(info, value) local name = info[#info] sadb.custom[key][name] = value end, get = function(info) local name = info[#info] return sadb.custom[key][name] end, order = sadb.custom[key].order, args = { name = { name = L["Spell Entry Name"], desc = L["Menu entry for the spell (eg. Hex down on arena partner)"], type = 'input', set = function(info, value) if sadb.custom[value] then log(L["same name already exists"]) return end sadb.custom[key].name = value sadb.custom[key].order = 100 sadb.custom[value] = sadb.custom[key] sadb.custom[key] = nil --makeoption(value) self.options.args.custom.args[keytemp].name = value key = value end, order = 1, }, spellname = { name = L["Spell Name"], type = 'input', order = 10, hidden = function() return not sadb.custom[key].acceptSpellName end, }, spellid = { name = L["Spell ID"], desc = L["Can be found on OpenWoW, in the URL"], set = function(info, value) local name = info[#info] sadb.custom[key][name] = value if GetSpellInfo(value) then sadb.custom[key].spellname = GetSpellInfo(value) self.options.args.custom.args[keytemp].spellname = GetSpellInfo(value) else sadb.custom[key].spellname = "Invalid Spell ID" self.options.args.custom.args[keytemp].spellname = "Invalid Spell ID" end end, type = 'input', order = 20, pattern = "%d+$", }, remove = { type = 'execute', order = 25, name = L["Remove"], confirm = true, confirmText = L["Are you sure?"], func = function() sadb.custom[key] = nil self.options.args.custom.args[keytemp] = nil end, }, acceptSpellName = { type = 'toggle', name = "Use specific spell name", desc = "Use this in case there are multiple ranks for this spell", order = 26, }, chatAlert = { type = 'toggle', name = "Chat Alert", order = 27, }, test = { type = 'execute', order = 28, name = L["Test"], desc = L["If you don't hear anything, try restarting WoW"], func = function() PlaySoundFile("Interface\\Addons\\SoundAlerter\\CustomSounds\\"..sadb.custom[key].soundfilepath) end, hidden = function() if sadb.custom[key].chatAlert then return true end end, }, soundfilepath = { name = L["File Path"], desc = L["Place your ogg/mp3 custom sound in the CustomSounds folder in Interface/Addons/SoundAlerter/"], type = 'input', width = 'double', order = 27, hidden = function() if sadb.custom[key].chatAlert then return true end end, }, chatalerttext = { name = "Chat Alert Text", desc = "eg. #enemy# casted #spell# on me! (Use '%t' if you're casting a spell on an enemy. )", type = 'input', width = 'double', order = 28, hidden = function() if not sadb.custom[key].chatAlert then return true end end, }, eventtype = { type = 'multiselect', order = 50, name = L["Event type - it's best to have the least amount of event conditions"], values = self.SA_EVENT, get = function(info, k) return sadb.custom[key].eventtype[k] end, set = function(info, k, v) sadb.custom[key].eventtype[k] = v end, }, sourceuidfilter = { type = 'select', order = 61, name = L["Source unit"], desc = L["Is the person who casted the spell your target/focus/mouseover?"], values = self.SA_UNIT, }, sourcetypefilter = { type = 'select', order = 60, name = L["Source of the spell"], desc = L["Who casted the spell? Leave on 'any' if a spell got casted on you"], values = self.SA_TYPE, }, sourcecustomname = { type= 'input', order = 62, name = L["Custom source name"], desc = L["Example: If the spell came from a specific player or boss"], disabled = function() return not (sadb.custom[key].sourceuidfilter == "custom") end, }, destuidfilter = { type = 'select', order = 65, name = L["Spell destination unit"], desc = L["Was the spell destination towards your target/focus/mouseover? (Leave on 'player' if it's yourself)"], values = self.SA_UNIT, }, desttypefilter = { type = 'select', order = 63, name = L["Spell Destination"], desc = L["Who was afflicted by the spell? Leave it on 'any' if it's a spell cast or a buff"], values = self.SA_TYPE, }, destcustomname = { type= 'input', order = 68, name = L["Custom destination name"], disabled = function() return not (sadb.custom[key].destuidfilter == "custom") end, }, --[[NewLine5 = { type = 'header', order = 69, name = "", },]] } } end for key, v in pairs(sadb.custom) do makeoption(key) end end
require('constants') require('stdlib/table') local Entity = require('stdlib/entity/entity') -- Split a string in to tokens using whitespace as a seperator. local function split( str ) local result = {} for sub in string.gmatch( str, "%S+" ) do table.insert( result, sub ) end return result end -- Parse tokens in to an AST we can store and evaluate later. local function parse( tokens ) if #tokens == 0 then return OP_NOP end local c = 1 local parseExpr local peek = function() return tokens[c] end local consume = function() local result = peek() c = c + 1 return result end local parseNum = function() return { val = tonumber(consume()), type = 'num' } end local parseOp = function() local node = { val = consume(), type = 'op', expr = {} } while(peek()) do local expr = parseExpr() if expr then table.insert( node.expr, expr ) else break end end return node end local parseAddress = function(name) local token = consume() if string.find(token, "@%d") then local addr = string.gsub(token, name.."@(%d+)", "%1") return {val = tonumber(addr), pointer = true} else local index = string.gsub(token, name.."(%d+)", "%1") return {val = tonumber(index), pointer = false} end end local parseWire = function(name) local address = parseAddress(name) return { type = "wire", color = name, val = address.val, pointer = address.pointer} end local parseRegister = function(name) local address = parseAddress(name) return { type = "register", location = name, val = address.val, pointer = address.pointer } end local parseReadOnlyRegister = function( name, index ) consume() return { type = "register", location = "mem", val = tonumber(index) } end local parseOutput = function(name) consume() return { type = "register", location = "out" } end local parseLabel = function() local label = consume() return { type = "label", label = label } end parseExpr = function() if peek() then if string.sub(peek(), 1, 1) == "#" then return OP_NOP elseif string.sub(peek(), 1, 1) == ":" then return parseLabel() elseif string.find( peek(), "%d" ) == 1 then return parseNum() elseif string.find(peek(), "red") then return parseWire("red") elseif string.find(peek(), "green") then return parseWire("green") elseif string.find(peek(), "mem") then return parseRegister("mem") elseif string.find(peek(), "out") then return parseOutput("out") elseif string.find(peek(), "ipt") then return parseReadOnlyRegister("ipt", 5) elseif string.find(peek(), "cnr") then return parseReadOnlyRegister("cnr", 6) elseif string.find(peek(), "cng") then return parseReadOnlyRegister("cng", 7) elseif string.find(peek(), "clk") then return parseReadOnlyRegister("clk", 8) else return parseOp() end end end return parseExpr() end --- Throws an exception, the exception has a control character prepended to that --- we can substring the message to only display the error message and not the stack-trace --- to the user. local function exception( val ) error("@"..val, 2) end --- Evaluates an AST. local function eval( ast, control, memory, modules, program_counter, clock ) local wires = {} wires.red = control.get_circuit_network(defines.wire_type.red, defines.circuit_connector_id.combinator_input) wires.green = control.get_circuit_network(defines.wire_type.green, defines.circuit_connector_id.combinator_input) local node, num -- Assertion Helper Functions local assert_inout = function( _ ) if #_ ~= 2 then exception("Expecting two parameters after opcode") end end local assert_in = function( _ ) if #_ ~= 1 then exception("Expecting one parameter after opcode") end end local assert_in_register = function( _ ) if _.type ~= "register" then exception("Expecting 1st parameter to be a memory or output register") end end local assert_in_mem = function( _ ) if _.type ~= "register" or _.location ~= "mem" then exception("Expecting 1st parameter to be a memory register") end end local assert_in_register_or_wire = function( _ ) if not (_.type == "register" or _.type == "wire") then exception("Expecting 1st parameter to be a register or wire input") end end local assert_in_mem_or_val = function( _ ) if not ((_.type == "register" and _.location == "mem") or _.type == "num") then exception("Expecting 1st parameter to be an integer or memory register") end end local assert_in_mem_or_val_or_label = function( _ ) if not ((_.type == "register" and _.location == "mem") or _.type == "num" or _.type == "label") then exception("Expecting 1st parameter to be an integer, memory register or label") end end local assert_in_wire = function( _ ) if _.type ~= "wire" then exception("Expecting 1st parameter to be a wire input") end end local assert_out_mem = function( _ ) if _.type ~= "register" or _.location ~= "mem" then exception("Expecting 2nd parameter to be a memory register") end end local assert_out_register = function( _ ) if _.type ~= "register" then exception("Expecting 2nd parameter to be a memory or output register") end end local assert_out_mem_or_val = function( _ ) if not ((_.type == "register" and _.location == "mem") or _.type == "num") then exception("Expecting 2nd parameter to be an integer or memory register") end end local assert_memory_index_range = function( index, max ) if index == nil then exception("No register address specified.") end if index < 1 or index > max then exception("Invalid memory address: "..index..". Out of range.") end end -- Memory Register Helper Functions -- Read only registers local getmem, setmem local function readOnlyRegister( index ) if index == 5 then return program_counter elseif index == 6 then if wires.red and wires.red.signals then return #wires.red.signals else return 0 end elseif index == 7 then if wires.green and wires.green.signals then return #wires.green.signals else return 0 end elseif index == 8 then return clock end end local memindex = function( _ ) if _.pointer then --assert_memory_index_range(_.val, 8) return getmem(_, true).count else return _.val end end getmem = function( index_expr, ignore_pointer ) local index if not ignore_pointer then index = memindex(index_expr) else index = index_expr.val end if index > 10 and index < 45 then local direction = math.floor(index / 10) local module_index = index - (direction * 10) assert_memory_index_range(module_index, 4) local module = modules[direction] if module then if module.name == "microcontroller-ram" then return table.deepcopy(module.get_control_behavior().get_signal(module_index)) elseif module.name == "microcontroller" then return table.deepcopy(Entity.get_data(module).memory[module_index]) end else exception("Module "..direction.." not found.") end elseif index > 4 then assert_memory_index_range(index, 8) local result = table.deepcopy(NULL_SIGNAL) result.count = readOnlyRegister(index) return result else assert_memory_index_range(index, 4) return table.deepcopy(memory[index]) end end setmem = function( index_expr, value ) local index = memindex(index_expr) local signal = table.deepcopy(value) if index > 10 and index < 45 then local direction = math.floor(index / 10) local module_index = index - (direction * 10) assert_memory_index_range(module_index, 4) local module = modules[direction] if module then if module.name == "microcontroller-ram" then module.get_control_behavior().set_signal(module_index, signal) elseif module.name == "microcontroller" then local other_mc_state = Entity.get_data(module) other_mc_state.memory[module_index] = signal end else exception("Module "..direction.." not found.") end else assert_memory_index_range(index, 4) memory[index] = signal end end local setmem_count = function( index_expr, count ) local value = getmem(index_expr) value.count = count setmem(index_expr, value) end -- Output Register Helper Functions local getout = function() local signalID = control.parameters.parameters.output_signal local value = control.parameters.parameters.first_constant return {signal = signalID, count = value} end local setout = function( value ) local params = control.parameters params.parameters.first_constant = value.count params.parameters.output_signal = value.signal control.parameters = params end local setout_count = function( count ) local params = control.parameters params.parameters.first_constant = count control.parameters = params end -- Multiplex Helper Functions local function getregister( index_expr ) if index_expr.location == 'mem' then return getmem(index_expr) elseif index_expr.location == 'out' then return getout() end end local function setregister( index_expr, value ) if index_expr.location == 'mem' then setmem(index_expr, value) elseif index_expr.location == 'out' then setout(value) end end local function setregister_count( index_expr, count ) if index_expr.location == 'mem' then setmem_count(index_expr, count) elseif index_expr.location == 'out' then setout_count(count) end end local function const_num( number ) return {type = "num", val = number} end local function memcount_or_val( _ ) if _.type == 'num' then return num(_) elseif _.type == 'register' and _.location == 'mem' then return getmem(_).count end end -- Wire Helper Functions local function getwire( _ ) local index = memindex(_) if not wires[_.color] then exception("Tried to access ".._.color.." wire when input not present.") end if wires[_.color].signals then return wires[_.color].signals[index] or NULL_SIGNAL end return NULL_SIGNAL end local function find_signal_in_wire( wire, signal_to_find ) if signal_to_find and wire.signals then for index, wire_signal in pairs(wire.signals) do if wire_signal and wire_signal.signal.name == signal_to_find.signal.name then return wire.signals[index] end end end return NULL_SIGNAL end -- Setup Helper Functions local standard_op = function( _ ) assert_inout(_) local _in = _[1] assert_in_mem_or_val(_in) local _out = _[2] assert_out_mem_or_val(_out) return _in, _out end local test_op = function( _ ) assert_inout(_) local _in = _[1] assert_in_mem_or_val(_in) local _out = _[2] assert_out_mem_or_val(_out) return _in, _out end -------------------- -- OPCODE Functions -------------------- local ops = { -- W = wire -- I = integer constant -- M = memory register -- O = output register -- R = Register (memory or output) -- + = zero, one or more parameters nop = function(_) end, mov = function(_) -- MOV W/R R -- Move local _in = _[1] assert_in_register_or_wire(_in) local out_val = nil if _in.type == 'wire' then out_val = getwire(_in) elseif _in.type == 'register' then out_val = getregister(_in) end if #_ > 2 then for i = 2, #_ do assert_out_register(_[i]) setregister(_[i], out_val) end else local _out = _[2] assert_out_register(_out) setregister(_out, out_val) end end, set = function(_) -- SET M/I R -- Set Count assert_inout(_) local _in = _[1] assert_in_mem_or_val(_in) local _out = _[2] assert_out_register(_out) if _in.type == 'register' then setregister_count(_out, getregister(_in).count) elseif _in.type == 'num' then setregister_count(_out, num(_in)) end end, clr = function(_) -- CLR R+ -- Clear if #_ > 0 then for i, expr in ipairs(_) do setregister(_[i], NULL_SIGNAL) end else for i = 1, #memory do memory[i] = NULL_SIGNAL end for i = 1, 4 do if modules[i] then for k = 1, 4 do setmem(const_num(i*10 + k, NULL_SIGNAL)) end end end setout(NULL_SIGNAL) end end, fir = function(_) -- FIR R -- Find (from) Red assert_in(_) local _in = _[1] assert_in_register(_in) local signal = getregister(_in) local wire_signal = find_signal_in_wire(wires.red, signal) setmem(const_num(1), wire_signal) end, fig = function(_) -- FIG R -- Find (from) Green assert_in(_) local _in = _[1] assert_in_register(_in) local signal = getregister(_in) local wire_signal = find_signal_in_wire(wires.green, signal) setmem(const_num(1), wire_signal) end, swp = function(_) -- SWP R R -- Swap assert_inout(_) local _in = _[1] assert_in_register(_in) local _out = _[2] assert_out_register(_out) local inSignal = getregister(_in) local outSignal = getregister(_out) setregister(_in, outSignal) setregister(_out, inSignal) end, syn = function(_) -- SYN return {type = "sync"} end, add = function(_) -- ADD M/I M/I -- Add local _in, _out = standard_op(_) setmem_count(const_num(1), memcount_or_val(_in) + memcount_or_val(_out)) end, sub = function(_) -- SUB M/I M/I -- Subtract local _in, _out = standard_op(_) setmem_count(const_num(1), memcount_or_val(_in) - memcount_or_val(_out)) end, mul = function(_) -- MUL M/I M/I -- Multiply local _in, _out = standard_op(_) setmem_count(const_num(1), memcount_or_val(_in) * memcount_or_val(_out)) end, div = function(_) -- DIV M/I M/I -- Divide local _in, _out = standard_op(_) setmem_count(const_num(1), memcount_or_val(_in) / memcount_or_val(_out)) end, mod = function(_) -- MOD M/I M/I -- Modulo local _in, _out = standard_op(_) setmem_count(const_num(1), memcount_or_val(_in) % memcount_or_val(_out)) end, pow = function(_) -- POW M/I M/I -- Exponetiation local _in, _out = standard_op(_) setmem_count(const_num(1), memcount_or_val(_in) ^ memcount_or_val(_out)) end, bnd = function(_) -- BND M/I M/I -- Bitwise AND local _in, _out = standard_op(_) local result = bit32.band(memcount_or_val(_in), memcount_or_val(_out)) setmem_count(const_num(1), result) end, bor = function(_) -- BOR M/I M/I -- Bitwise OR local _in, _out = standard_op(_) local result = bit32.bor(memcount_or_val(_in), memcount_or_val(_out)) setmem_count(const_num(1), result) end, bxr = function(_) -- BXR M/I M/I -- Bitwise XOR local _in, _out = standard_op(_) local result = bit32.bxor(memcount_or_val(_in), memcount_or_val(_out)) setmem_count(const_num(1), result) end, bls = function(_) -- BLS M/I M/I -- Bitwise left shift local _in, _out = standard_op(_) local result = bit32.lshift(memcount_or_val(_in), memcount_or_val(_out)) setmem_count(const_num(1), result) end, brs = function(_) -- BRS M/I M/I -- Bitwise right shift local _in, _out = standard_op(_) local result = bit32.rshift(memcount_or_val(_in), memcount_or_val(_out)) setmem_count(const_num(1), result) end, blr = function(_) -- BLR M/I M/I -- Bitwise left rotate local _in, _out = standard_op(_) local result = bit32.lrotate(memcount_or_val(_in), memcount_or_val(_out)) setmem_count(const_num(1), result) end, brr = function(_) -- BRR M/I M/I -- Bitwise right rotate local _in, _out = standard_op(_) local result = bit32.rrotate(memcount_or_val(_in), memcount_or_val(_out)) setmem_count(const_num(1), result) end, bno = function(_) -- BNO M/I M/I -- Bitwise NOT assert_in(_) local _in = _[1] assert_in_mem_or_val(_in) local result = bit32.bnot(memcount_or_val(_in)) setmem_count(const_num(1), result) end, slp = function(_) -- SLP M/I -- Sleep assert_in(_) local _in = _[1] assert_in_mem_or_val(_in) return { type = "sleep", val = memcount_or_val(_in) } end, jmp = function(_) -- JMP M/I/L -- Jump assert_in(_) local _in = _[1] assert_in_mem_or_val_or_label(_in) if _in.type == 'label' then return { type = "jump", label = _in.label } else return { type = "jump", val = memcount_or_val(_in) } end end, hlt = function(_) -- HLT -- Halt return { type = "halt" } end, tgt = function(_) -- TGT M/I M/I -- Test Greater Than local _in, _out = test_op(_) if memcount_or_val(_in) > memcount_or_val(_out) then return { type = "skip" } end end, tlt = function(_) -- TLT M/I M/I -- Test Less Than local _in, _out = test_op(_) if memcount_or_val(_in) < memcount_or_val(_out) then return { type = "skip" } end end, teq = function(_) -- TEQ M/I M/I -- Test Equal (Signal count) local _in, _out = test_op(_) if memcount_or_val(_in) == memcount_or_val(_out) then return { type = "skip" } end end, tnq = function(_) -- TNG M/I M/I -- Test Not Equal (Signal count) local _in, _out = test_op(_) if memcount_or_val(_in) ~= memcount_or_val(_out) then return { type = "skip" } end end, tte = function(_) -- TTE M M -- Test Equal (Signal type) assert_inout(_) local _in = _[1] assert_in_mem(_in) local _out = _[2] assert_out_mem(_out) if getmem(_in).signal.name == getmem(_out).signal.name then return { type = "skip" } end end, ttn = function(_) -- TTN M M -- Test Not Equal (Signal type) assert_inout(_) local _in = _[1] assert_in_mem(_in) local _out = _[2] assert_out_mem(_out) if getmem(_in).signal.name ~= getmem(_out).signal.name then return { type = "skip" } end end, dig = function(_) -- DIG M/I -- Get Digit (from memory1) assert_in(_) local _in = _[1] assert_in_mem_or_val(_in) local i = memcount_or_val(_in) local value = getmem(const_num(1)).count local digit = tonumber(string.sub(tostring(value), -i, -i)) setmem_count(const_num(1), digit) end, dis = function(_) -- DIS M/I M/I -- Set Digit (in memory1) assert_inout(_) local _in = _[1] assert_in_mem_or_val(_in) local _out = _[2] assert_out_mem_or_val(_out) local str_value = tostring(getmem(const_num(1)).count) local selector = string.len(str_value) - memcount_or_val(_in) + 1 local digit = memcount_or_val(_out) local p1 = string.sub(str_value, 1, selector-1) local p2 = string.sub(str_value, selector, selector) local p3 = string.sub(str_value, selector+1, -1) p2 = string.sub(tostring(digit), -1) setmem_count(const_num(1), tonumber(p1..p2..p3)) end, bkr = function(_) -- BKR M/I -- Block until there are at least [a] red signals. assert_in(_) local _in = _[1] assert_in_mem_or_val(_in) local count = memcount_or_val(_in) if wires.red.signals == nil or #wires.red.signals < count then return {type = "block"} end end, bkg = function(_) -- BKG M/I -- Block until there are at least [a] green signals. assert_in(_) local _in = _[1] assert_in_mem_or_val(_in) local count = memcount_or_val(_in) if wires.green.signals == nil or #wires.green.signals < count then return {type = "block"} end end, } -- TODO: Tidy this up, we've got functions being declared in two different ways here -- and also some before the op codes and some after. num = function( _ ) return _.val end node = function( _ ) if _.type == 'num' then return num(_) elseif _.type == 'op' then if not ops[_.val] then exception("Unknown opcode: ".._.val) else return ops[_.val](_.expr) end elseif _.type == 'nop' or _.type == 'label' then -- do nothing else exception("Unable to parse code") end end if ast then local result = node(ast) if type(result) == "number" then exception("Expected an opcode but instead read an integer.") end return result end end local compiler = {} function compiler.compile( lines ) local ast = {} for i, line in ipairs(lines) do ast[i] = parse(split(line)) end return ast end function compiler.eval( ast, control, state ) local status, results = pcall(eval, ast, control, state.memory, state.adjacent_modules, state.program_counter, state.clock) if not status then local start_index = string.find(results, "@") or 1 results = string.sub(results, start_index+1, -1) end return status, results end return compiler
return { { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.05 } } } }, { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.066 } } } }, { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.082 } } } }, { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.1 } } } }, { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.116 } } } }, { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.132 } } } }, { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.15 } } } }, { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.166 } } } }, { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.182 } } } }, { effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.2 } } } }, init_effect = "", name = "", time = 0, color = "red", picture = "", desc = "主炮射程提升,对轻甲伤害提高", stack = 1, id = 14181, icon = 14180, last_effect = "", effect_list = { { type = "BattleBuffFixRange", trigger = { "onAttach" }, arg_list = { bulletRange = 75, weaponRange = 75, index = { 1 } } }, { type = "BattleBuffAddAttr", trigger = { "onAttach" }, arg_list = { attr = "damageAgainstArmorEnhance_1", number = 0.05 } } } }
--////////////////////////////////////////////////////// -- Name: Operation Clear Field Escalation - Navy Module -- Author: Surrexen ༼ つ ◕_◕ ༽つ (づ。◕‿◕。)づ --////////////////////////////////////////////////////// --////MAIN trigger.action.outSound('Background Chatter.ogg') CarrierPhase = 1 --------------------------------------------------------------------------------------------------------------------------------------- --////FUNCTIONS function SEF_CarrierTurning() trigger.action.outText("Admiral Michael Gilday Reports The Carrier Group Will Be Making It's Turn In Another 00:08:34 / 5000m", 15) end function SEF_TarawaTurning() trigger.action.outText("Admiral Michael Gilday Reports The Tarawa Will Be Making It's Turn In Another 00:08:34 / 5000m", 15) end function SEF_BattlePhaseCheckCarrierGroup() if ( Airbase.getByName(AIRBASE.Caucasus.Batumi):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Kobuleti):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Senaki_Kolkhi):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Kutaisi):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Tbilisi_Lochini):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Vaziani):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Soganlug):getCoalition() ~= 2 ) then --Then we must be in Phase 1 return 1 elseif ( Airbase.getByName(AIRBASE.Caucasus.Sukhumi_Babushara):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Gudauta):getCoalition() ~= 2 ) then --Then we must be in Phase 2 return 2 elseif ( Airbase.getByName(AIRBASE.Caucasus.Nalchik):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Beslan):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Mozdok):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Mineralnye_Vody):getCoalition() ~= 2 ) then --Then we must be in Phase 3 return 3 elseif ( Airbase.getByName(AIRBASE.Caucasus.Sochi_Adler):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Maykop_Khanskaya):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Krymsk):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Krasnodar_Pashkovsky):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Krasnodar_Center):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Novorossiysk):getCoalition() ~= 2 or Airbase.getByName(AIRBASE.Caucasus.Gelendzhik):getCoalition() ~= 2 ) then --Then we must be in Phase 4 return 4 else return 1 end end function SEF_CarrierMission() --CarrierPhase = SEF_BattlePhaseCheckCarrierGroup() --Override for now as we don't have a 2nd route implemented if ( CarrierPhase <= 2 ) then CarrierRouteZone1 = ZONE:FindByName("Carrier Route 1 Point 1") CarrierRouteZone2 = ZONE:FindByName("Carrier Route 1 Point 2") CarrierRouteZone3 = ZONE:FindByName("Carrier Route 1 Point 3") CarrierRouteZone4 = ZONE:FindByName("Carrier Route 1 Point 4") CarrierRouteZone5 = ZONE:FindByName("Carrier Route 1 Point 5") CarrierRouteZone6 = ZONE:FindByName("Carrier Route 1 Point 6") CarrierRouteZone7 = ZONE:FindByName("Carrier Route 1 Point 7") CarrierRouteZone8 = ZONE:FindByName("Carrier Route 1 Point 8") CarrierRouteZone9 = ZONE:FindByName("Carrier Route 1 Point 9") CarrierRoutePoint1Vec2 = CarrierRouteZone1:GetVec2() CarrierRoutePoint2Vec2 = CarrierRouteZone2:GetVec2() CarrierRoutePoint3Vec2 = CarrierRouteZone3:GetVec2() CarrierRoutePoint4Vec2 = CarrierRouteZone4:GetVec2() CarrierRoutePoint5Vec2 = CarrierRouteZone5:GetVec2() CarrierRoutePoint6Vec2 = CarrierRouteZone6:GetVec2() CarrierRoutePoint7Vec2 = CarrierRouteZone7:GetVec2() CarrierRoutePoint8Vec2 = CarrierRouteZone8:GetVec2() CarrierRoutePoint9Vec2 = CarrierRouteZone9:GetVec2() trigger.action.outText("Admiral Michael Gilday Reports The Carrier Group Is Executing The Phase 1/2 Mission Plan", 15) else CarrierRouteZone1 = ZONE:FindByName("Carrier Route 2 Point 1") CarrierRouteZone2 = ZONE:FindByName("Carrier Route 2 Point 2") CarrierRouteZone3 = ZONE:FindByName("Carrier Route 2 Point 3") CarrierRouteZone4 = ZONE:FindByName("Carrier Route 2 Point 4") CarrierRouteZone5 = ZONE:FindByName("Carrier Route 2 Point 5") CarrierRouteZone6 = ZONE:FindByName("Carrier Route 2 Point 6") CarrierRouteZone7 = ZONE:FindByName("Carrier Route 2 Point 7") CarrierRouteZone8 = ZONE:FindByName("Carrier Route 2 Point 8") CarrierRouteZone9 = ZONE:FindByName("Carrier Route 2 Point 9") CarrierRoutePoint1Vec2 = CarrierRouteZone1:GetVec2() CarrierRoutePoint2Vec2 = CarrierRouteZone2:GetVec2() CarrierRoutePoint3Vec2 = CarrierRouteZone3:GetVec2() CarrierRoutePoint4Vec2 = CarrierRouteZone4:GetVec2() CarrierRoutePoint5Vec2 = CarrierRouteZone5:GetVec2() CarrierRoutePoint6Vec2 = CarrierRouteZone6:GetVec2() CarrierRoutePoint7Vec2 = CarrierRouteZone7:GetVec2() CarrierRoutePoint8Vec2 = CarrierRouteZone8:GetVec2() CarrierRoutePoint9Vec2 = CarrierRouteZone9:GetVec2() trigger.action.outText("Admiral Michael Gilday Reports The Carrier Group Is Executing The Phase 3/4 Mission Plan", 15) end --////EXECUTE CARRIER MISSION PROFILE CarrierMission = { ["id"] = "Mission", ["params"] = { ["route"] = { ["points"] = { [1] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 2052.9461697281, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = CarrierRoutePoint1Vec2.y, ["x"] = CarrierRoutePoint1Vec2.x, ["ETA_locked"] = false, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "ABE", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 72, ["unitId"] = 1, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1159000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 1, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 7, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_CarrierTurning()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [1] [2] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 4197.5234743132, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = CarrierRoutePoint2Vec2.y, ["x"] = CarrierRoutePoint2Vec2.x, ["ETA_locked"] = false, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "ABE", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 72, ["unitId"] = 1, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1159000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 1, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 7, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [2] [3] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 9283.8062952378, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = CarrierRoutePoint3Vec2.y, ["x"] = CarrierRoutePoint3Vec2.x, ["ETA_locked"] = false, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "ABE", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 72, ["unitId"] = 1, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1159000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 1, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 7, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_CarrierTurning()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [3] [4] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 11524.882414909, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = CarrierRoutePoint4Vec2.y, ["x"] = CarrierRoutePoint4Vec2.x, ["ETA_locked"] = false, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "ABE", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 72, ["unitId"] = 1, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1159000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 1, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 7, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [4] [5] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = CarrierRoutePoint5Vec2.y, ["x"] = CarrierRoutePoint5Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "ABE", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 72, ["unitId"] = 1, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1159000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 1, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 7, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_CarrierTurning()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [5] [6] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = CarrierRoutePoint6Vec2.y, ["x"] = CarrierRoutePoint6Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "ABE", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 72, ["unitId"] = 1, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1159000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 1, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 7, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [6] [7] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = CarrierRoutePoint7Vec2.y, ["x"] = CarrierRoutePoint7Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "ABE", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 72, ["unitId"] = 1, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1159000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 1, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 7, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_CarrierTurning()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [7] [8] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = CarrierRoutePoint8Vec2.y, ["x"] = CarrierRoutePoint8Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "ABE", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 72, ["unitId"] = 1, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1159000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 1, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 7, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [8] [9] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = CarrierRoutePoint9Vec2.y, ["x"] = CarrierRoutePoint9Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "ABE", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 72, ["unitId"] = 1, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1159000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 1, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 7, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_CarrierMission()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [9] }, -- end of ["points"] }, -- end of ["route"] }, --end of ["params"] }--end of Mission GROUP:FindByName("CVN-72 Abraham Lincoln"):SetTask(CarrierMission) end function SEF_TarawaMission() --CarrierPhase = SEF_BattlePhaseCheckCarrierGroup() --Override for now as we don't have a 2nd route implemented if ( CarrierPhase <= 2 ) then TarawaRouteZone1 = ZONE:FindByName("Tarawa Route 1 Point 1") TarawaRouteZone2 = ZONE:FindByName("Tarawa Route 1 Point 2") TarawaRouteZone3 = ZONE:FindByName("Tarawa Route 1 Point 3") TarawaRouteZone4 = ZONE:FindByName("Tarawa Route 1 Point 4") TarawaRouteZone5 = ZONE:FindByName("Tarawa Route 1 Point 5") TarawaRouteZone6 = ZONE:FindByName("Tarawa Route 1 Point 6") TarawaRouteZone7 = ZONE:FindByName("Tarawa Route 1 Point 7") TarawaRouteZone8 = ZONE:FindByName("Tarawa Route 1 Point 8") TarawaRouteZone9 = ZONE:FindByName("Tarawa Route 1 Point 9") TarawaRoutePoint1Vec2 = TarawaRouteZone1:GetVec2() TarawaRoutePoint2Vec2 = TarawaRouteZone2:GetVec2() TarawaRoutePoint3Vec2 = TarawaRouteZone3:GetVec2() TarawaRoutePoint4Vec2 = TarawaRouteZone4:GetVec2() TarawaRoutePoint5Vec2 = TarawaRouteZone5:GetVec2() TarawaRoutePoint6Vec2 = TarawaRouteZone6:GetVec2() TarawaRoutePoint7Vec2 = TarawaRouteZone7:GetVec2() TarawaRoutePoint8Vec2 = TarawaRouteZone8:GetVec2() TarawaRoutePoint9Vec2 = TarawaRouteZone9:GetVec2() trigger.action.outText("Admiral Michael Gilday Reports The Tarawa Is Executing The Phase 1/2 Mission Plan", 15) else TarawaRouteZone1 = ZONE:FindByName("Tarawa Route 2 Point 1") TarawaRouteZone2 = ZONE:FindByName("Tarawa Route 2 Point 2") TarawaRouteZone3 = ZONE:FindByName("Tarawa Route 2 Point 3") TarawaRouteZone4 = ZONE:FindByName("Tarawa Route 2 Point 4") TarawaRouteZone5 = ZONE:FindByName("Tarawa Route 2 Point 5") TarawaRouteZone6 = ZONE:FindByName("Tarawa Route 2 Point 6") TarawaRouteZone7 = ZONE:FindByName("Tarawa Route 2 Point 7") TarawaRouteZone8 = ZONE:FindByName("Tarawa Route 2 Point 8") TarawaRouteZone9 = ZONE:FindByName("Tarawa Route 2 Point 9") TarawaRoutePoint1Vec2 = TarawaRouteZone1:GetVec2() TarawaRoutePoint2Vec2 = TarawaRouteZone2:GetVec2() TarawaRoutePoint3Vec2 = TarawaRouteZone3:GetVec2() TarawaRoutePoint4Vec2 = TarawaRouteZone4:GetVec2() TarawaRoutePoint5Vec2 = TarawaRouteZone5:GetVec2() TarawaRoutePoint6Vec2 = TarawaRouteZone6:GetVec2() TarawaRoutePoint7Vec2 = TarawaRouteZone7:GetVec2() TarawaRoutePoint8Vec2 = TarawaRouteZone8:GetVec2() TarawaRoutePoint9Vec2 = TarawaRouteZone9:GetVec2() trigger.action.outText("Admiral Michael Gilday Reports The Tarawa Is Executing The Phase 3/4 Mission Plan", 15) end --////EXECUTE TARAWA MISSION PROFILE TarawaMission = { ["id"] = "Mission", ["params"] = { ["route"] = { ["points"] = { [1] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 2052.9461697281, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = TarawaRoutePoint1Vec2.y, ["x"] = TarawaRoutePoint1Vec2.x, ["ETA_locked"] = false, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "TRW", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 75, ["unitId"] = 874, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1162000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 874, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 8, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_TarawaTurning()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [1] [2] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 4197.5234743132, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = TarawaRoutePoint2Vec2.y, ["x"] = TarawaRoutePoint2Vec2.x, ["ETA_locked"] = false, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "TRW", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 75, ["unitId"] = 874, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1162000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 874, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 8, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [2] [3] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 9283.8062952378, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = TarawaRoutePoint3Vec2.y, ["x"] = TarawaRoutePoint3Vec2.x, ["ETA_locked"] = false, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "TRW", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 75, ["unitId"] = 874, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1162000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 874, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 8, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_TarawaTurning()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [3] [4] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 11524.882414909, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = TarawaRoutePoint4Vec2.y, ["x"] = TarawaRoutePoint4Vec2.x, ["ETA_locked"] = false, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "TRW", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 75, ["unitId"] = 874, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1162000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 874, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 8, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [4] [5] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = TarawaRoutePoint5Vec2.y, ["x"] = TarawaRoutePoint5Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "TRW", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 75, ["unitId"] = 874, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1162000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 874, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 8, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_TarawaTurning()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [5] [6] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = TarawaRoutePoint6Vec2.y, ["x"] = TarawaRoutePoint6Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "TRW", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 75, ["unitId"] = 874, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1162000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 874, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 8, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [6] [7] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = TarawaRoutePoint7Vec2.y, ["x"] = TarawaRoutePoint7Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "TRW", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 75, ["unitId"] = 874, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1162000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 874, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 8, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_TarawaTurning()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [7] [8] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = TarawaRoutePoint8Vec2.y, ["x"] = TarawaRoutePoint8Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "TRW", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 75, ["unitId"] = 874, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1162000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 874, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 8, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [8] [9] = { ["alt"] = 0, ["type"] = "Turning Point", ["ETA"] = 0, ["alt_type"] = "BARO", ["formation_template"] = "", ["y"] = TarawaRoutePoint9Vec2.y, ["x"] = TarawaRoutePoint9Vec2.x, ["ETA_locked"] = true, ["speed"] = 9.7222222222222, ["action"] = "Turning Point", ["task"] = { ["id"] = "ComboTask", ["params"] = { ["tasks"] = { [1] = { ["number"] = 1, ["auto"] = true, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateBeacon", ["params"] = { ["type"] = 4, ["AA"] = false, ["callsign"] = "TRW", ["modeChannel"] = "X", ["name"] = "TACAN", ["channel"] = 75, ["unitId"] = 874, ["system"] = 3, ["bearing"] = true, ["frequency"] = 1162000000, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [1] [2] = { ["number"] = 2, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "ActivateICLS", ["params"] = { ["unitId"] = 874, ["type"] = 131584, ["name"] = "ICLS", ["channel"] = 8, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [2] [3] = { ["number"] = 3, ["auto"] = false, ["id"] = "WrappedAction", ["enabled"] = true, ["params"] = { ["action"] = { ["id"] = "Option", ["params"] = { ["value"] = true, ["name"] = 20, }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [3] [4] = { ["enabled"] = true, ["auto"] = false, ["id"] = "WrappedAction", ["number"] = 4, ["params"] = { ["action"] = { ["id"] = "Script", ["params"] = { ["command"] = "SEF_TarawaMission()", }, -- end of ["params"] }, -- end of ["action"] }, -- end of ["params"] }, -- end of [4] }, -- end of ["tasks"] }, -- end of ["params"] }, -- end of ["task"] ["speed_locked"] = true, }, -- end of [9] }, -- end of ["points"] }, -- end of ["route"] }, --end of ["params"] }--end of Mission GROUP:FindByName("LHA-1 Tarawa"):SetTask(TarawaMission) end --------------------------------------------------------------------------------------------------------------------------------------- --////MAIN SEF_CarrierMission() SEF_TarawaMission() if ( Group.getByName("CV 1143.5 Admiral Kuznetsov") ) then GROUP:FindByName("CV 1143.5 Admiral Kuznetsov"):PatrolRoute() end if ( Group.getByName("Georgian Navy") ) then GROUP:FindByName("Georgian Navy"):PatrolRoute() end if ( Group.getByName("Sukhumi - Navy") ) then GROUP:FindByName("Sukhumi - Navy"):PatrolRoute() end if ( Group.getByName("Gudauta - Navy") ) then GROUP:FindByName("Gudauta - Navy"):PatrolRoute() end if ( Group.getByName("Sochi - Navy") ) then GROUP:FindByName("Sochi - Navy"):PatrolRoute() end if ( Group.getByName("Red October") ) then GROUP:FindByName("Red October"):PatrolRoute() end if ( Group.getByName("Lazarevskoe - Cargo Ship") ) then GROUP:FindByName("Lazarevskoe - Cargo Ship"):PatrolRoute() end if ( Group.getByName("Pitsunda - Cargo Ship") ) then GROUP:FindByName("Pitsunda - Cargo Ship"):PatrolRoute() end
aliveai_threats.fort={furnishings={"aliveai_threats:toxic_tank","aliveai_threats:labbottle_containing","aliveai_threats:timed_bumb","aliveai_threats:timed_nitrobumb","aliveai_threat_eletric:timed_ebumb","aliveai_threats:landmine","aliveai_threats:deadlock","aliveai_massdestruction:nuclearbarrel"},} minetest.register_tool("aliveai_threats:fortspawner", { description = "fort spawner", range=15, groups={not_in_creative_inventory=1}, inventory_image = "default_stick.png", on_use = function(itemstack, user, pointed_thing) if pointed_thing.type=="node" then aliveai_threats.fort.spawning(pointed_thing.under,1) end end, }) minetest.register_node("aliveai_threats:fort_spawner", { tiles={"default_stone.png"}, groups = {not_in_creative_inventory=1}, is_ground_content = false }) minetest.register_ore({ ore_type = "scatter", ore = "aliveai_threats:fort_spawner", wherein = "group:spreading_dirt_type", clust_scarcity = 20 * 20 * 20, clust_num_ores = 1, clust_size = 1, y_min = -1, y_max = 50, }) minetest.register_ore({ ore_type = "scatter", ore = "aliveai_threats:fort_spawner", wherein = "default:snow", clust_scarcity = 20 * 20 * 20, clust_num_ores = 1, clust_size = 1, y_min = -1, y_max = 50, }) minetest.register_ore({ ore_type = "scatter", ore = "aliveai_threats:fort_spawner", wherein = "default:snowblock", clust_scarcity = 20 * 20 * 20, clust_num_ores = 1, clust_size = 1, y_min = -1, y_max = 50, }) aliveai.register_on_generated("aliveai_threats:fort_spawner",function(pos) minetest.after(0, function(pos) if math.random(1,10)==1 then aliveai_threats.fort.spawning(pos) end end,pos) return "default:stone" end) aliveai_threats.fort.spawning=function(pos,nrnd) if not nrnd and math.random(1,20)~=1 then return end local test1=0 local test2=0 for y=-5,6,1 do for x=-5,31,1 do for z=-5,31,1 do local p={x=pos.x+x,y=pos.y+y,z=pos.z+z} if nrnd and minetest.is_protected(p,"") then return end if y<1 and aliveai.def(p,"walkable") then test1=test1+1 elseif y>0 and aliveai.def(p,"walkable") then test2=test2+1 if test2>3000 then return end end end end end if test1<7000 then return end local door=math.random(11,17) local n local cam local start for y=0,6,1 do for x=-5,31,1 do for z=-5,31,1 do local p={x=pos.x+x,y=pos.y+y,z=pos.z+z} local n="air" local param=0 if y==0 then n="default:silver_sandstone_brick" elseif y==6 and ((x==9 and z==9) or (x==18 and z==18) or (x==18 and z==9) or (x==9 and z==18)) then n="aliveai_threats:secam2" cam=1 elseif y<5 and (x==1 or x==26 or z==1 or z==26) and (x>0 and z>0 and x<27 and z<27) then n="aliveai_threats:chainfence" if aliveai_electric then start=1 end param=1 if x==1 then param=1 elseif x==26 then param=3 elseif z==1 then param=2 else param=0 end elseif (y==1 or y==2) and (((x==door and (z==9 or z==18)) or (z==door and (x==9 or x==18))))then if y==1 then n="aliveai:door_steel" end elseif (y==1 or y==2) and (x==door or z==door) then elseif (y==1 or y==2) and (((x==10 or x==17) and (z>9 and z<18)) or ((z==10 or z==17) and (x>9 and x<18))) then if y==1 then n="aliveai_threats:labtable" elseif math.random(1,3)==1 then n=aliveai_threats.fort.furnishings[math.random(1,#aliveai_threats.fort.furnishings)] end elseif y<5 and (((x==9 or x==18) and (z>8 and z<19)) or ((z==9 or z==18) and (x>8 and x<19))) then n="default:silver_sandstone_brick" elseif y==5 and (x>8 and x<19 and z>8 and z<19) then n="default:silver_sandstone_brick" end if n then minetest.set_node(p,{name=n,param2=param}) if cam then minetest.get_meta(p):set_string("team","nuke") minetest.get_node_timer(p):start(1) cam=nil elseif start then minetest.get_node_timer(p):start(1) start=nil end end end end end if math.random(1,3)==1 then return end for y=-5,0,1 do for x=-4,30,1 do for z=-4,30,1 do local p={x=pos.x+x,y=pos.y+y,z=pos.z+z} local n=nil if y==-5 and ((x<0 or x>26) or (z<0 or z>26)) then n="default:silver_sandstone_brick" elseif x==-4 or x==30 or z==-4 or z==30 then n="default:silver_sandstone_brick" elseif (x>-4 and x<0) or (x>26 and x<30) or (z>-5 and z<0) or (z>26 and z<30) then n="aliveai_threats:slime" elseif x==0 or x==26 or z==0 or z==26 then n="default:silver_sandstone_brick" end if n then minetest.set_node(p,{name=n}) end end end end end minetest.register_node("aliveai_threats:chainfence", { description = "Chain fence", tiles = {"aliveai_threats_chainfence.png"}, drawtype = "nodebox", groups = {cracky=1, not_in_creative_inventory=0,level=3}, sounds = default.node_sound_stone_defaults(), is_ground_content = false, paramtype2 = "facedir", paramtype = "light", node_box = {type="fixed",fixed={-0.5,-0.5,0.45,0.5,0.5,0.5}}, on_punch = function(pos, node, puncher, pointed_thing) if not (puncher:is_player() and minetest.get_meta(pos):get_string("owner")==puncher:get_player_name()) then if aliveai_electric and aliveai.team(puncher)~="nuke" then aliveai_electric.hit(puncher,20,5) end end end, after_place_node = function(pos, placer) if placer:is_player() then minetest.get_meta(pos):set_string("owner",placer:get_player_name()) end end, on_construct = function(pos) if aliveai_electric then minetest.get_node_timer(pos):start(5) end end, on_timer = function (pos, elapsed) if math.random(1,4)~=1 then return true end for i, ob in pairs(minetest.get_objects_inside_radius(pos, 2)) do if aliveai.team(ob)~="nuke" then aliveai_electric.hit(ob,20,5) end end return true end })
local L = LibStub("AceLocale-3.0"):NewLocale("Skada", "enUS", true) L["Include set"] = true L["Include set name in title bar"] = true L["Disable"] = true L["Profiles"] = true L["Hint: Left-Click to toggle Skada window."] = true L["Shift + Left-Click to reset."] = true L["Right-click to open menu"] = true L["Options"] = true L["Appearance"] = true L["A damage meter."] = true L["Skada summary"] = true L["opens the configuration window"] = true L["Memory usage is high. You may want to reset Skada, and enable one of the automatic reset options."] = true L["resets all data"] = true L["Current"] = "Current fight" L["Total"] = "Total" L["All data has been reset."] = true L["Skada: Modes"] = true L["Skada: Fights"] = true -- Options L["Disabled Modules"] = true L["This change requires a UI reload. Are you sure?"] = true L["Tick the modules you want to disable."] = true L["Bar font"] = true L["The font used by all bars."] = true L["Bar font size"] = true L["The font size of all bars."] = true L["Bar texture"] = true L["The texture used by all bars."] = true L["Bar spacing"] = true L["Distance between bars."] = true L["Bar height"] = true L["The height of the bars."] = true L["Bar width"] = true L["The width of the bars."] = true L["Bar color"] = true L["Choose the default color of the bars."] = true L["Max bars"] = true L["The maximum number of bars shown."] = true L["Bar orientation"] = true L["The direction the bars are drawn in."] = true L["Left to right"] = true L["Right to left"] = true L["Combat mode"] = true L["Automatically switch to set 'Current' and this mode when entering combat."] = true L["None"] = true L["Return after combat"] = true L["Return to the previous set and mode after combat ends."] = true L["Show minimap button"] = true L["Toggles showing the minimap button."] = true L["reports the active mode"] = true L["Skada: %s for %s:"] = "Skada: %s for %s:" L["Only keep boss fighs"] = "Only keep boss fights" L["Boss fights will be kept with this on, and non-boss fights are discarded."] = true L["Show raw threat"] = true L["Shows raw threat percentage relative to tank instead of modified for range."] = true L["Lock window"] = "Lock window" L["Locks the bar window in place."] = "Locks the bar window in place." L["Reverse bar growth"] = "Reverse bar growth" L["Bars will grow up instead of down."] = "Bars will grow up instead of down." L["Number format"] = "Number format" L["Controls the way large numbers are displayed."] = "Controls the way large numbers are displayed." L["Number set duplicates"] = "Number set duplicates" L["Append a count to set names with duplicate mob names."] = "Append a count to set names with duplicate mob names." L["Set format"] = "Set format" L["Controls the way set names are displayed."] = "Controls the way set names are displayed." L["Reset on entering instance"] = "Reset on entering instance" L["Controls if data is reset when you enter an instance."] = "Controls if data is reset when you enter an instance." L["Reset on joining a group"] = "Reset on joining a group" L["Controls if data is reset when you join a group."] = "Controls if data is reset when you join a group." L["Reset on leaving a group"] = "Reset on leaving a group" L["Controls if data is reset when you leave a group."] = "Controls if data is reset when you leave a group." L["General options"] = "General options" L["Mode switching"] = "Mode switching" L["Data resets"] = "Data resets" L["Bars"] = "Bars" L["Yes"] = "Yes" L["No"] = "No" L["Ask"] = "Ask" L["Condensed"] = "Condensed" L["Detailed"] = "Detailed" L["'s Death"] = "'s Death" L["Hide when solo"] = "Hide when solo" L["Hides Skada's window when not in a party or raid."] = "Hides Skada's window when not in a party or raid." L["Title bar"] = "Title bar" L["Background texture"] = "Background texture" L["The texture used as the background of the title."] = "The texture used as the background of the title." L["Border texture"] = "Border texture" L["The texture used for the border of the title."] = "The texture used for the border of the title." L["Border thickness"] = "Border thickness" L["The thickness of the borders."] = "The thickness of the borders." L["Background color"] = "Background color" L["The background color of the title."] = "The background color of the title." L["'s "] = "'s " L["Do you want to reset Skada?"] = "Do you want to reset Skada?" L["'s Fails"] = "'s Fails" L["The margin between the outer edge and the background texture."] = "The margin between the outer edge and the background texture." L["Margin"] = "Margin" L["Window height"] = "Window height" L["The height of the window. If this is 0 the height is dynamically changed according to how many bars exist."] = "The height of the window. If this is 0 the height is dynamically changed according to how many bars exist." L["Adds a background frame under the bars. The height of the background frame determines how many bars are shown. This will override the max number of bars setting."] = "Adds a background frame under the bars. The height of the background frame determines how many bars are shown. This will override the max number of bars setting." L["Enable"] = "Enable" L["Background"] = "Background" L["The texture used as the background."] = "The texture used as the background." L["The texture used for the borders."] = "The texture used for the borders." L["The color of the background."] = "The color of the background." L["Data feed"] = "Data feed" L["Choose which data feed to show in the DataBroker view. This requires an LDB display addon, such as Titan Panel."] = "Choose which data feed to show in the DataBroker view. This requires an LDB display addon, such as Titan Panel." L["RDPS"] = "RDPS" L["Damage: Personal DPS"] = "Damage: Personal DPS" L["Damage: Raid DPS"] = "Damage: Raid DPS" L["Threat: Personal Threat"] = "Threat: Personal Threat" L["Data segments to keep"] = "Data segments to keep" L["The number of fight segments to keep. Persistent segments are not included in this."] = "The number of fight segments to keep. Persistent segments are not included in this." L["Alternate color"] = "Alternate color" L["Choose the alternate color of the bars."] = "Choose the alternate color of the bars." L["Threat warning"] = "Threat warning" L["Flash screen"] = "Flash screen" L["This will cause the screen to flash as a threat warning."] = "This will cause the screen to flash as a threat warning." L["Shake screen"] = "Shake screen" L["This will cause the screen to shake as a threat warning."] = "This will cause the screen to shake as a threat warning." L["Play sound"] = "Play sound" L["This will play a sound as a threat warning."] = "This will play a sound as a threat warning." L["Threat sound"] = "Threat sound" L["The sound that will be played when your threat percentage reaches a certain point."] = "The sound that will be played when your threat percentage reaches a certain point." L["Threat threshold"] = "Threat threshold" L["When your threat reaches this level, relative to tank, warnings are shown."] = "When your threat reaches this level, relative to tank, warnings are shown." L["Enables the title bar."] = "Enables the title bar." L["Total healing"] = "Total healing" L["Interrupts"] = "Interrupts" L["Skada Menu"] = "Skada Menu" L["Switch to mode"] = "Switch to mode" L["Report"] = "Report" L["Toggle window"] = "Toggle window" L["Configure"] = "Configure" L["Delete segment"] = "Delete segment" L["Keep segment"] = "Keep segment" L["Mode"] = "Mode" L["Lines"] = "Lines" L["Channel"] = "Channel" L["Send report"] = "Send report" L["No mode selected for report."] = "No mode selected for report." L["Say"] = "Say" L["Raid"] = "Raid" L["Party"] = "Party" L["Guild"] = "Guild" L["Officer"] = "Officer" L["Self"] = "Self" L["'s Healing"] = "'s Healing" L["Enemy damage done"] = "Enemy damage done" L["Enemy damage taken"] = "Enemy damage taken" L["Damage on"] = "Damage on" L["Damage from"] = "Damage from" L["Delete window"] = "Delete window" L["Deletes the chosen window."] = "Deletes the chosen window." L["Choose the window to be deleted."] = "Choose the window to be deleted." L["Enter the name for the new window."] = "Enter the name for the new window." L["Create window"] = "Create window" L["Windows"] = "Windows" L["Switch to segment"] = "Switch to segment" L["Segment"] = "Segment" L["Whisper"] = "Whisper" L["No mode or segment selected for report."] = "No mode or segment selected for report." L["Name of recipient"] = "Name of recipient" L["Resist"] = "Resist" L["Reflect"] = "Reflect" L["Parry"] = "Parry" L["Immune"] = "Immune" L["Evade"] = "Evade" L["Dodge"] = "Dodge" L["Deflect"] = "Deflect" L["Block"] = "Block" L["Absorb"] = "Absorb" L["Last fight"] = "Last fight" L["Disable while hidden"] = "Disable while hidden" L["Skada will not collect any data when automatically hidden."] = "Skada will not collect any data when automatically hidden." L["Data Collection"] = "Data Collection" L["ENABLED"] = "ENABLED" L["DISABLED"] = "DISABLED" L["Rename window"] = "Rename window" L["Enter the name for the window."] = "Enter the name for the window." L["Bar display"] = "Bar display" L["Display system"] = "Display system" L["Choose the system to be used for displaying data in this window."] = "Choose the system to be used for displaying data in this window." L["Hides HPS from the Healing modes."] = "Hides HPS from the Healing modes." L["Do not show HPS"] = "Do not show HPS" L["Do not show DPS"] = "Do not show DPS" L["Hides DPS from the Damage mode."] = "Hides DPS from the Damage mode." L["Class color bars"] = "Class color bars" L["When possible, bars will be colored according to player class."] = "When possible, bars will be colored according to player class." L["Class color text"] = "Class color text" L["When possible, bar text will be colored according to player class."] = "When possible, bar text will be colored according to player class." L["Reset"] = "Reset" L["Show tooltips"] = "Show tooltips" L["Mana gained"] = "Mana gained" L["Shows tooltips with extra information in some modes."] = "Shows tooltips with extra information in some modes." L["Average hit:"] = "Average hit:" L["Maximum hit:"] = "Maximum hit:" L["Minimum hit:"] = "Minimum hit:" L["Absorbs"] = "Absorbs" L["'s Absorbs"] = "'s Absorbs" L["Do not show TPS"] = "Do not show TPS" L["Do not warn while tanking"] = "Do not warn while tanking" L["Hide in PvP"] = "Hide in PvP" L["Hides Skada's window when in Battlegrounds/Arenas."] = "Hides Skada's window when in Battlegrounds/Arenas." L["Healed players"] = "Healed players" L["Healed by"] = "Healed by" L["Absorb details"] = "Absorb details" L["Spell details"] = "Spell details" L["Healing spell list"] = "Healing spell list" L["Damage spell list"] = "Damage spell list" L["Death log"] = "Death log" L["Damage done per player"] = "Damage done per player" L["Damage taken per player"] = "Damage taken per player" L["Damage spell details"] = "Damage spell details" L["Healing spell details"] = "Healing spell details" L["Mana gain spell list"] = "Mana gain spell list" L["List of damaging spells"] = "List of damaging spells" L["Debuff spell list"] = "Debuff spell list" L["Click for"] = "Click for" L["Shift-Click for"] = "Shift-Click for" L["Control-Click for"] = "Control-Click for" L["Default"] = "Default" L["Top right"] = "Top right" L["Top left"] = "Top left" L["Position of the tooltips."] = "Position of the tooltips." L["Tooltip position"] = "Tooltip position" L["Damaged mobs"] = "Damaged mobs" L["Shows a button for opening the menu in the window title bar."] = "Shows a button for opening the menu in the window title bar." L["Show menu button"] = "Show menu button" L["Debuff uptimes"] = true L["'s Debuffs"] = true L["Deaths"] = true L["Damage taken"] = true L["Attack"] = true L["'s Damage taken"] = true L["DPS"] = true L["Damage"] = true L["'s Damage"] = true L["Hit"] = true L["Critical"] = true L["Missed"] = true L["Resisted"] = true L["Blocked"] = true L["Glancing"] = true L["Crushing"] = "Crushing" L["Multistrike"] = STAT_MULTISTRIKE or true -- XXX compat L["Absorbed"] = true L["Dispels"] = true L["Fails"] = true L["'s Fails"] = true L["HPS"] = "HPS" L["Healing"] = true L["'s Healing"] = true L["Overhealing"] = true L["Threat"] = true L["Power"] = true L["Enemies"] = true L["Debuffs"] = true L["DamageTaken"] = "Damage Taken" L["TotalHealing"] = "Total Healing" L["Announce CC breaking to party"] = true L["Ignore Main Tanks"] = true L["%s on %s removed by %s's %s"]= true L["%s on %s removed by %s"]= true L["CC"] = true L["CC breakers"] = true L["CC breaks"] = true L["Start new segment"] = true L["Columns"] = "Columns" L["Overheal"] = "Overheal" L["Percent"] = "Percent" L["TPS"] = "TPS" L["%s dies"] = "%s dies" L["Timestamp"] = "Timestamp" L["Change"] = "Change" L["Health"] = "Health" L["Hide in combat"] = "Hide in combat" L["Hides Skada's window when in combat."] = "Hides Skada's window when in combat." L["Tooltips"] = "Tooltips" L["Informative tooltips"] = "Informative tooltips" L["Shows subview summaries in the tooltips."] = "Shows subview summaries in the tooltips." L["Subview rows"] = "Subview rows" L["The number of rows from each subview to show when using informative tooltips."] = "The number of rows from each subview to show when using informative tooltips." L["Damage done"] = "Damage done" L["Active time"] = "Active time" L["Segment time"] = "Segment time" L["Absorbs and healing"] = "Absorbs and healing" L["Activity"] = true L["Show rank numbers"] = "Show rank numbers" L["Shows numbers for relative ranks for modes where it is applicable."] = "Shows numbers for relative ranks for modes where it is applicable." L["Use focus target"] = "Use focus target" L["Shows threat on focus target, or focus target's target, when available."] = "Shows threat on focus target, or focus target's target, when available." L["Show spark effect"] = "Show spark effect" L["List of damaged players"] = "List of damaged players" L["Damage taken by spell"] = "Damage taken by spell" L["targets"] = "targets" L["Aggressive combat detection"] = "Aggressive combat detection" L["Skada usually uses a very conservative (simple) combat detection scheme that works best in raids. With this option Skada attempts to emulate other damage meters. Useful for running dungeons. Meaningless on boss encounters."] = "Skada usually uses a very conservative (simple) combat detection scheme that works best in raids. With this option Skada attempts to emulate other damage meters. Useful for running dungeons. Meaningless on boss encounters." L["Clickthrough"] = "Clickthrough" L["Disables mouse clicks on bars."] = "Disables mouse clicks on bars." L["DTPS"] = "DTPS" L["Healing taken"] = "Healing taken" L["Wipe mode"] = "Wipe mode" L["Automatically switch to set 'Current' and this mode after a wipe."] = "Automatically switch to set 'Current' and this mode after a wipe." L["Merge pets"] = "Merge pets" L["Merges pets with their owners. Changing this only affects new data."] = "Merges pets with their owners. Changing this only affects new data." L["Show totals"] = "Show totals" L["Shows a extra row with a summary in certain modes."] = "Shows a extra row with a summary in certain modes." L["There is nothing to report."] = "There is nothing to report." L["Buttons"] = "Buttons" L["Buff uptimes"] = "Buff uptimes" L["Buff spell list"] = "Buff spell list" L["'s Buffs"] = "'s Buffs" L["Deletes the chosen window."] = "Deletes the chosen window." L["Delete window"] = "Delete window" L["Window"] = "Window" L["Scale"] = "Scale" L["Sets the scale of the window."] = "Sets the scale of the window." L["Snaps the window size to best fit when resizing."] = "Snaps the window size to best fit when resizing." L["Snap to best fit"] = "Snap to best fit" L["Hide window"] = "Hide window" L["Absorb spells"] = "Absorb spells" L["Choose the background color of the bars."] = "Choose the background color of the bars." L["Font flags"] = "Font flags" L["Sets the font flags."] = "Sets the font flags." L["None"] = "None" L["Outline"] = "Outline" L["Thick outline"] = "Thick outline" L["Monochrome"] = "Monochrome" L["Outlined monochrome"] = "Outlined monochrome" L["The height of the title frame."] = "The height of the title frame." L["Title height"] = "Title height" L["Use class icons where applicable."] = "Use class icons where applicable." L["Class icons"] = "Class icons" L["RealID"] = "RealID" L["Instance"] = "Instance" L["Enemy healing done"] = "Enemy healing done" L["Enemy healing taken"] = "Enemy healing taken" L["Stop"] = "Stop/Resume" L["Autostop"] = "Stop early on wipe" L["Autostop description"] = "Automatically stops the current segment after a certain amount of raid members have died." L["Stop description"] = "Stops or resumes the current segment. Useful for discounting data after a wipe. Can also be set to automatically stop in the settings." L["Segment description"] = "Jump to a specific segment." L["Mode description"] = "Jump to a specific mode." L["Reset description"] = "Resets all fight data except those marked as kept." L["Report description"] = "Opens a dialog that lets you report your data to others in various ways." L["Configure description"] = "Lets you configure the active Skada window." L["Role icons"] = true L["Use role icons where applicable."] = true L["Overhealing spells"] = true L["Whisper Target"] = true L["Always show self"] = true L["Keeps the player shown last even if there is not enough space."] = true L["Strata"] = true L["This determines what other frames will be in front of the frame."] = true L["Fixed bar width"] = true L["If checked, bar width is fixed. Otherwise, bar width depends on the text width."] = true L["Text color"] = true L["Choose the default color."] = true L["Hint: Left-Click to set active mode."] = true L["Right-click to set active set."] = true L["Shift + Left-Click to open menu."] = true L["Title color"] = true L["The text color of the title."] = true L["Border color"] = true L["The color used for the border."] = true L["Tweaks"] = true L["Inline bar display"] = true L["Data text"] = true L["Width"] = true L["Height"] = true L["Tile"] = true L["Tile the background texture."] = true L["Tile size"] = true L["The size of the texture pattern."] = true L["Border"] = true L["General"] = true L["Inline display is a horizontal window style."] = true L["Data text acts as an LDB data feed. It can be integrated in any LDB display such as Titan Panel or ChocolateBar. It also has an optional internal frame."] = true L["Bar display is the normal bar window used by most damage meters. It can be extensively styled."] = true L["Theme applied!"] = true L["Themes"] = true L["Theme"] = true L["Apply theme"] = true L["Save theme"] = true L["Name of your new theme."] = true L["Name"] = true L["Save"] = true L["Apply"] = true L["Delete"] = true L["Delete theme"] = true L["Various tweaks to get around deficiences and problems in the game's combat logs. Carries a small performance penalty."] = true L["Adds a set of standard themes to Skada. Custom themes can also be used."] = true L["Smart"] = true L["Memory usage is high. You may want to reset Skada, and enable one of the automatic reset options."] = true L["Other"] = true L["Energy gained"] = true L["Rage gained"] = true L["Runic power gained"] = true L["Holy power gained"] = true L["Energy gain sources"] = true L["Rage gain sources"] = true L["Holy power gain sources"] = true L["Runic power gain sources"] = true L["Power gains"] = true L["Focus gained"] = true L["Fury gained"] = true L["Pain gained"] = true L["Soul Shards gained"] = true L["Focus gain sources"] = true L["Fury gain sources"] = true L["Pain gain sources"] = true L["Soul Shards gain sources"] = true L["Minimum"] = true L["Maximum"] = true L["Average"] = true L["Spell school colors"] = true L["Use spell school colors where applicable."] = true L["Sort modes by usage"] = true L["The mode list will be sorted to reflect usage instead of alphabetically."] = true L["Smooth bars"] = true L["Animate bar changes smoothly rather than immediately."] = true L["Update frequency"] = true L["How often windows are updated. Shorter for faster updates. Increases CPU usage."] = true L["Buffs"] = true L["Debuffs"] = true L["Healing: Personal HPS"] = true L["Healing: Raid HPS"] = true L["RHPS"] = true L["Friendly Fire"] = true L["List of players damaged"] = true L["List of damaging spells"] = true L["spells"] = true L["targets"] = true L["Shows damage done on players by friendly players."] = true
-- ~~~~~~~~ -- hud.lua -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- In-game HUD elements for Mars Lander -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local HUD = {} HUD.font = love.graphics.newFont(20) -- TODO: Create variables in a init or create function -- Fuel indicator elements HUD.fuel = {x = 20, y = 20, width = SCREEN_WIDTH - 40, height = 50, cornerSize = 15} HUD.fuel.middle = HUD.fuel.x + math.floor(HUD.fuel.width / 2) HUD.fuel.bottom = HUD.fuel.y + HUD.fuel.height HUD.fuel.text = {image=love.graphics.newText(HUD.font, "FUEL")} HUD.fuel.text.width, HUD.fuel.text.height = HUD.fuel.text.image:getDimensions() HUD.fuel.text.x, HUD.fuel.text.y = HUD.fuel.x + 20, HUD.fuel.y + math.floor(HUD.fuel.text.height / 2) local ship = Assets.getImageSet("ship") local flame = Assets.getImageSet("flame") -- ~~~~~~~~~~~~~~~~ -- Local functions -- ~~~~~~~~~~~~~~~~ local function drawFuelIndicator(lander) -- draws the fuel indicator across the top of the screen -- credit: Milon -- refactored by Fox -- Fuel indicator assert(lander.fuel ~= nil) local grad = lander.fuel / lander.fuelCapacity local color = {1, grad, grad} local x, y = HUD.fuel.x, HUD.fuel.y local width, height = HUD.fuel.width, HUD.fuel.height local cornerSize = HUD.fuel.cornerSize love.graphics.setColor(1,1,1,1) love.graphics.rectangle("fill", x, y, width, height, cornerSize, cornerSize) love.graphics.setColor(color) love.graphics.rectangle("fill", x, y, width * grad, height, cornerSize, cornerSize) love.graphics.setColor(0,0.5,1,1) love.graphics.draw(HUD.fuel.text.image, HUD.fuel.text.x, HUD.fuel.text.y) love.graphics.setColor(1,1,1,1) -- center line love.graphics.line(HUD.fuel.middle, y, HUD.fuel.middle, HUD.fuel.bottom) end local function drawOffscreenIndicator(lander) -- draws an indicator when the lander flies off the top of the screen local lineThickness = love.graphics.getLineWidth() love.graphics.setLineWidth(3) local indicatorY = 40 local magnifier = 1.5 local x, y = lander.x - WORLD_OFFSET, ship.height + indicatorY if lander.y < 0 then love.graphics.draw(ship.image, x, y, math.rad(lander.angle), magnifier, magnifier, ship.width/2, ship.height/2) love.graphics.circle("line", x, y, ship.height + 5) love.graphics.polygon("fill", x, lander.y, x - 10, indicatorY - 5, x + 10, indicatorY - 5) if lander.engineOn then love.graphics.draw(flame.image, x, y, math.rad(lander.angle), magnifier, magnifier, flame.width/2, flame.height/2) end end -- restore line thickness love.graphics.setLineWidth(lineThickness) end local function drawMoney(lander) Assets.setFont("font20") love.graphics.print("$" .. lander.money, SCREEN_WIDTH - 100, 75) end local function drawRangefinder(lander) -- determine distance to nearest base and draw indicator local module = Modules.rangefinder if Lander.hasUpgrade(lander, module) then local rawDistance, _ = Fun.GetDistanceToClosestBase(lander.x, Enum.basetypeFuel) -- limit the rangefinder to a maximum distance if rawDistance < Enum.rangefinderMaximumDistance * -1 then rawDistance = Enum.rangefinderMaximumDistance * -1 end if rawDistance > Enum.rangefinderMaximumDistance then rawDistance = Enum.rangefinderMaximumDistance end local absDistance = math.abs(Cf.round(rawDistance, 0)) -- don't draw if close to base if absDistance > 100 then local halfScreenW = SCREEN_WIDTH / 2 if rawDistance <= 0 then Assets.setFont("font20") -- closest base is to the right (forward) love.graphics.print("--> " .. absDistance, halfScreenW - 75, SCREEN_HEIGHT * 0.90) else love.graphics.print("<-- " .. absDistance, halfScreenW - 75, SCREEN_HEIGHT * 0.90) end end end end local function drawHealthIndicator(lander) -- lander.health reports health from 0 (dead) to 100 (best health) local indicatorLength = lander.health * -1 local x = SCREEN_WIDTH - 30 local y = SCREEN_HEIGHT * 0.33 local width = 10 local height = indicatorLength Assets.setFont("font14") love.graphics.print("Health", x - 20, y) -- Draw rectangle love.graphics.setColor(1,0,0,1) love.graphics.rectangle("fill", x, y + 120, width, height) love.graphics.setColor(1,1,1,1) end local function drawShopMenu() -- draws a menu to buy lander parts. This is text based. Hope to make it a full GUI at some point. local gameOver = LANDERS[1].gameOver local isOnLandingPad = Lander.isOnLandingPad(LANDERS[1], Enum.basetypeFuel) if not gameOver and isOnLandingPad then Assets.setFont("font20") -- Create List of available modules for _, module in pairs(Modules) do local string = "%s. Buy %s - $%s \n" itemListString = string.format(string, module.id, module.name, module.cost) -- Draw list of modules local color = {1, 1, 1, 1} local y = SCREEN_HEIGHT * 0.33 if Lander.hasUpgrade(LANDERS[1], module) then color = {.8, .1, .1, .5} end love.graphics.setColor(color) love.graphics.printf(itemListString, 0, y + (20*module.id), SCREEN_WIDTH, "center") love.graphics.setColor(1, 1, 1, 1) end end end local function drawGameOver() Assets.setFont("font16") local text = "You are out of fuel. Game over. Press R to reset" -- try to get centre of screen local x = (SCREEN_WIDTH / 2) - 150 local y = SCREEN_HEIGHT * 0.33 love.graphics.print(text, x, y) end local function drawScore() -- score is simply the amount of forward distance travelled (lander.score) local lineLength = 150 -- printf will wrap after this point local x = SCREEN_WIDTH - 15 - lineLength -- the 15 is an asthetic margin from the right edge local y = SCREEN_HEIGHT * 0.20 local alignment = "right" Assets.setFont("font14") for _,lander in pairs(LANDERS) do -- guard against connecting mplayer clients not having complete data if lander.score ~= nil then local roundedScore = Cf.round(lander.score) local formattedScore = Cf.strFormatThousand(roundedScore) local tempString = lander.name .. ": " .. formattedScore love.graphics.printf(tempString,x,y, lineLength, alignment) y = y + 20 -- prep the y value for the next score (will be ignored for single player) end end end local function drawDebug() Assets.setFont("font14") local lander = LANDERS[1] love.graphics.print("Mass = " .. Cf.round(Lander.getMass(lander), 2), 5, 75) love.graphics.print("Fuel = " .. Cf.round(lander.fuel, 2), 5, 90) love.graphics.print("FPS: " .. love.timer.getFPS(), 10, 120) love.graphics.print("MEM: " .. Cf.round(collectgarbage("count")), 10, 140) love.graphics.print("Ground: " .. #GROUND, 10, 160) love.graphics.print("Objects: " .. #OBJECTS, 10, 180) love.graphics.print("WorldOffsetX: " .. WORLD_OFFSET, 10, 200) end local function drawPortInformation() if IS_A_HOST then love.graphics.setColor(1,1,1,0.50) Assets.setFont("font14") local txt = "Hosting on port: " .. HOST_IP_ADDRESS .. ":" .. GAME_SETTINGS.hostPort love.graphics.printf(txt, 0, 5, SCREEN_WIDTH, "center") love.graphics.setColor(1, 1, 1, 1) end end -- ~~~~~~~~~~~~~~~~~ -- Public functions -- ~~~~~~~~~~~~~~~~~ function HUD.drawPause() -- Simple text based pause screen Assets.setFont("font18") love.graphics.setColor(1,1,1,1) local text = "GAME PAUSED: PRESS <ESC> OR <P> TO RESUME" love.graphics.print(text, SCREEN_WIDTH / 2 - 200, SCREEN_HEIGHT /2) end function HUD.draw() local lander = LANDERS[1] drawFuelIndicator(lander) drawHealthIndicator(lander) drawScore() drawOffscreenIndicator(lander) drawMoney(lander) drawRangefinder(lander) drawPortInformation() if lander.gameOver then drawGameOver() elseif lander.onGround then drawShopMenu() end if DEBUG then drawDebug() end end return HUD
--[[ --MIT License -- --Copyright (c) 2019 manilarome --Copyright (c) 2020 Tom Meyers -- --Permission is hereby granted, free of charge, to any person obtaining a copy --of this software and associated documentation files (the "Software"), to deal --in the Software without restriction, including without limitation the rights --to use, copy, modify, merge, publish, distribute, sublicense, and/or sell --copies of the Software, and to permit persons to whom the Software is --furnished to do so, subject to the following conditions: -- --The above copyright notice and this permission notice shall be included in all --copies or substantial portions of the Software. -- --THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR --IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, --FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE --AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER --LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, --OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE --SOFTWARE. ]] local filesystem = require("gears.filesystem") local mat_colors = require("theme.mat-colors") local theme_dir = filesystem.get_configuration_dir() .. "/theme" local gears = require("gears") local dpi = require("beautiful").xresources.apply_dpi local gtk = require("beautiful.gtk") local config = require("theme.config") local darklight = require("theme.icons.dark-light") local filehandle = require("lib-tde.file") local file_exists = filehandle.exists local theme = {} theme.icons = theme_dir .. "/icons/" theme.font = "Roboto medium 10" theme.monitor_font = "Roboto medium 50" theme.gtk = gtk.get_theme_variables() theme.background_transparency = config["background_transparent"] or "66" -- get all lines from a file, returns an empty -- list/table if the file does not exist local function lines_from(file) if not file_exists(file) then return "/usr/share/backgrounds/tos/default.jpg" end local lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end local function color(value) if value == nil then return nil end return "#" .. value end local function loadtheme(standard, override, prefix) standard["hue_50"] = color(override[prefix .. "hue_50"]) or standard["hue_50"] standard["hue_100"] = color(override[prefix .. "hue_100"]) or standard["hue_100"] standard["hue_200"] = color(override[prefix .. "hue_200"]) or standard["hue_200"] standard["hue_300"] = color(override[prefix .. "hue_300"]) or standard["hue_300"] standard["hue_400"] = color(override[prefix .. "hue_400"]) or standard["hue_400"] standard["hue_500"] = color(override[prefix .. "hue_500"]) or standard["hue_500"] standard["hue_600"] = color(override[prefix .. "hue_600"]) or standard["hue_600"] standard["hue_700"] = color(override[prefix .. "hue_700"]) or standard["hue_700"] standard["hue_800"] = color(override[prefix .. "hue_800"]) or standard["hue_800"] standard["hue_900"] = color(override[prefix .. "hue_900"]) or standard["hue_900"] standard["hue_A100"] = color(override[prefix .. "hue_A100"]) or standard["hue_A100"] standard["hue_A200"] = color(override[prefix .. "hue_A200"]) or standard["hue_A200"] standard["hue_A400"] = color(override[prefix .. "hue_A400"]) or standard["hue_A400"] standard["hue_A700"] = color(override[prefix .. "hue_A700"]) or standard["hue_A700"] return standard end local function darkLightSwitcher(dark, light) if config["background"] == "light" then return light end return dark end -- Colors Pallets -- Custom theme.custom = "#ffffff" -- Primary theme.primary = mat_colors[config["primary"]] or mat_colors.purple -- Accent theme.accent = mat_colors[config["accent"]] or mat_colors.hue_purple -- Background theme.background = mat_colors[config["background"]] or mat_colors.grey theme.primary = loadtheme(theme.primary, config, "primary_") theme.accent = loadtheme(theme.accent, config, "accent_") theme.background = loadtheme(theme.background, config, "background_") theme.text = color(config["text"]) or "#FFFFFF" -- system stat charts in settings app theme.cpu_bar = color(config["cpu_bar"]) or "#f90273" theme.ram_bar = color(config["ram_bar"]) or "#017AFC" theme.disk_bar = color(config["disk_bar"]) or "#fdc400" local awesome_overrides = function(awesome_theme) awesome_theme.dir = "/etc/xdg/tde/theme" --theme.dir = os.getenv("HOME") .. "/code/awesome-pro/themes/pro-dark" awesome_theme.icons = awesome_theme.dir .. "/icons/" local resultset = lines_from(os.getenv("HOME") .. "/.config/tos/theme") awesome_theme.wallpaper = resultset[#resultset] or "/usr/share/backgrounds/tos/default.jpg" awesome_theme.font = "Roboto medium 10" awesome_theme.title_font = "Roboto medium 14" awesome_theme.fg_white = "#ffffffde" awesome_theme.fg_black = "#292929" awesome_theme.fg_normal = color(config["foreground_normal"]) or darkLightSwitcher(awesome_theme.fg_white, awesome_theme.fg_black) awesome_theme.fg_focus = color(config["foreground_focus"]) or darkLightSwitcher("#e4e4e4", "#343434") awesome_theme.fg_urgent = color(config["foreground_urgent"]) or darkLightSwitcher("#CC9393", "#994545") awesome_theme.bat_fg_critical = color(config["foreground_critical"]) or darkLightSwitcher("#232323", "#BEBEBE3") awesome_theme.bg_normal = awesome_theme.background.hue_800 awesome_theme.bg_focus = color(config["background_focus"]) or "#5a5a5a" awesome_theme.bg_urgent = color(config["background_urgent"]) or "#3F3F3F" awesome_theme.bg_systray = awesome_theme.background.hue_800 awesome_theme.bg_modal = color(config["background_modal"]) or darkLightSwitcher("#ffffff35", "#ffffffA0") awesome_theme.bg_modal_title = color(config["background_modal_title"]) or darkLightSwitcher("#ffffff55", "#ffffffD0") awesome_theme.bg_settings_display_number = "#00000070" -- Borders awesome_theme.border_width = dpi(2) awesome_theme.border_normal = awesome_theme.background.hue_800 awesome_theme.border_focus = awesome_theme.primary.hue_300 awesome_theme.border_marked = color(config["border_marked"]) or "#CC9393" -- Notification awesome_theme.transparent = "#00000000" awesome_theme.notification_position = "top_right" awesome_theme.notification_bg = awesome_theme.transparent awesome_theme.notification_margin = dpi(5) awesome_theme.notification_border_width = dpi(0) awesome_theme.notification_border_color = awesome_theme.transparent awesome_theme.notification_spacing = dpi(0) awesome_theme.notification_icon_resize_strategy = "center" awesome_theme.notification_icon_size = dpi(32) -- UI Groups awesome_theme.groups_title_bg = awesome_theme.bg_modal_title awesome_theme.groups_bg = awesome_theme.bg_modal awesome_theme.groups_radius = dpi(9) -- Menu awesome_theme.menu_height = dpi(16) awesome_theme.menu_width = dpi(160) -- Tooltips awesome_theme.tooltip_bg = (color(config["tooltip_bg"]) or awesome_theme.bg_normal) --awesome_theme.tooltip_border_color = '#232323' awesome_theme.tooltip_border_width = 0 awesome_theme.tooltip_shape = function(cr, w, h) gears.shape.rounded_rect(cr, w, h, dpi(6)) end -- Layout awesome_theme.layout_max = darklight(awesome_theme.icons .. "layouts/arrow-expand-all.png") awesome_theme.layout_tile = darklight(awesome_theme.icons .. "layouts/view-quilt.png") awesome_theme.layout_dwindle = darklight(awesome_theme.icons .. "layouts/dwindle.png") awesome_theme.layout_floating = darklight(awesome_theme.icons .. "layouts/floating.png") awesome_theme.layout_fairv = darklight(awesome_theme.icons .. "layouts/fair.png") awesome_theme.layout_fairh = darklight(awesome_theme.icons .. "layouts/fairh.png") awesome_theme.layout_magnifier = darklight(awesome_theme.icons .. "layouts/magnifier.png") -- Taglist taglist_occupied = color(config["taglist_occupied"]) or "#ffffff" awesome_theme.taglist_bg_empty = awesome_theme.background.hue_800 .. "99" awesome_theme.taglist_bg_occupied = "linear:0," .. dpi(48) .. ":0,0:0," .. taglist_occupied .. ":0.11," .. taglist_occupied .. ":0.11," .. awesome_theme.background.hue_800 .. "99" .. awesome_theme.background.hue_800 awesome_theme.taglist_bg_urgent = "linear:0," .. dpi(48) .. ":0,0:0," .. awesome_theme.accent.hue_500 .. ":0.11," .. awesome_theme.accent.hue_500 .. ":0.11," .. awesome_theme.background.hue_800 .. ":1," .. awesome_theme.background.hue_800 awesome_theme.taglist_bg_focus = "linear:0," .. dpi(48) .. ":0,0:0," .. awesome_theme.primary.hue_500 .. ":0.11," .. awesome_theme.primary.hue_500 .. ":0.11," .. awesome_theme.background.hue_800 .. ":1," --[[':1,']] .. awesome_theme.background.hue_800 -- Tasklist awesome_theme.tasklist_font = "Roboto Regular 10" awesome_theme.tasklist_bg_normal = awesome_theme.background.hue_800 .. "99" awesome_theme.tasklist_bg_focus = "linear:0,0:0," .. dpi(48) .. ":0," .. awesome_theme.background.hue_800 .. ":0.95," .. awesome_theme.background.hue_800 .. ":0.95," .. awesome_theme.fg_normal .. ":1," .. awesome_theme.fg_normal awesome_theme.tasklist_bg_urgent = awesome_theme.primary.hue_800 awesome_theme.tasklist_fg_focus = awesome_theme.fg_focus awesome_theme.tasklist_fg_urgent = awesome_theme.fg_urgent awesome_theme.tasklist_fg_normal = awesome_theme.fg_normal awesome_theme.icon_theme = "Papirus-Dark" local out = io.popen( "if [[ -f ~/.config/gtk-3.0/settings.ini ]]; " .. [[then grep "gtk-icon-theme-name" ~/.config/gtk-3.0/settings.ini | awk -F= '{printf $2}'; fi]] ):read("*all") if out ~= nil then awesome_theme.icon_theme = out end --Client awesome_theme.border_width = dpi(0) awesome_theme.border_focus = awesome_theme.primary.hue_500 awesome_theme.border_normal = awesome_theme.primary.hue_800 awesome_theme.border_color = awesome_theme.primary.hue_500 awesome_theme.snap_bg = awesome_theme.primary.hue_700 end return { theme = theme, awesome_overrides = awesome_overrides }
package.path = package.path .. ";data/scripts/lib/?.lua" package.path = package.path .. ";data/scripts/?.lua" include ("galaxy") include ("randomext") include ("stringutility") include ("player") include ("relations") ESCCUtil = include("esccutil") local Placer = include ("placer") local AsyncPirateGenerator = include ("asyncpirategenerator") local SpawnUtility = include ("spawnutility") local EventUT = include ("eventutility") local ITUtil = include("increasingthreatutility") local piratefaction = nil local ships = {} local pirate_reserves = {} local remaining_executioners = 0 local decapTargetPlayer = nil local decapTargetAlliance = nil local decapHatredLevel = 0 local participants = {} --Some consts. local decap_taunts = { "Target verified. Commencing hostilities.", "At the end of the broken path lies death, and death alone.", "There's nowhere left for you to run.", "Endless is the path that leads you from hell.", "Honed is the blade that severs the villain's head.", "This is the end for you.", "This is the end of the road for you. I think you understand why.", "You think it's your right to choose who lives and dies?", "Time to cut the head from the beast.", "There's nowhere to run!", "You die here!", "We'll decorate this sector with your strewn corpses!", "Go down, you murderer!", "An eye for an eye!" } local exit_taunts = { "This is not war anymore.", "You are not our adversary.", "Do not mistake this for mercy.", "We leave you to rot in your pathetic existence.", "Someday, we'll kill you too. But not here. Not today.", "Enjoy your unearned reprieve." } -- Don't remove or alter the following comment, it tells the game the namespace this script lives in. If you remove it, the script will break. -- namespace DecapStrike DecapStrike = {} DecapStrike.attackersGenerated = false DecapStrike._Debug = 0 local _ActiveMods = Mods() DecapStrike._HETActive = false for _, _Xmod in pairs(_ActiveMods) do if _Xmod.id == "1821043731" then --HET DecapStrike._HETActive = true end end if onServer() then --Keep a structure roughly similar to other events that way we can expand this if needed. function DecapStrike.secure() local _MethodName = "Secure" DecapStrike.Log(_MethodName, "securing decap strike") DecapStrike.patchPirateFaction() return { pirate_reserves = pirate_reserves, remainingexecutioners = remaining_executioners, decaptarget = decapTargetPlayer, decapTargetAlliance = decapTargetAlliance, decaphatred = decapHatredLevel, ships = ships, piratefaction = piratefaction.index } end function DecapStrike.restore(data) local _MethodName = "Restore" DecapStrike.Log(_MethodName, "restoring decap strike") pirate_reserves = data.pirate_reserves remaining_executioners = data.remainingexecutioners decapTargetPlayer = data.decaptarget decapTargetAlliance = data.decapTargetAlliance decapHatredLevel = data.decaphatred ships = data.ships piratefaction = Faction(data.piratefaction) DecapStrike.patchPirateFaction() end function DecapStrike.initialize() local _MethodName = "Initialize" if not _restoring then local _Sector = Sector() DecapStrike.Log(_MethodName, "Initializing.") if not EventUT.attackEventAllowed() then DecapStrike.Log(_MethodName, "event not allowed - cancelling decapitation strike") ITUtil.unpauseEvents() terminate() return end local generator = AsyncPirateGenerator(DecapStrike, DecapStrike.onPiratesGenerated) piratefaction = generator:getPirateFaction() --If the pirate faction is craven, add a chance to abort the attack if there's AI defenders. local _Craven = piratefaction:getTrait("craven") if _Craven and _Craven >= 0.25 then local _Galaxy = Galaxy() local _X, _Y = _Sector:getCoordinates() local _Controller = _Galaxy:getControllingFaction(_X, _Y) if _Controller then if _Controller.isAIFaction then local _Rgen = ESCCUtil.getRand() if _Rgen:getInt(1, 5) == 1 then DecapStrike.Log(_MethodName, "Pirates decided to abort the attack due to cowardice.") termiante() return end end end end --Decap strikes work as follows: --Preference is given to players by how much hatred they have. Players are sorted from most to least hated. --A decap strike cannot be done more than once every 3-6 hours. This amount is chosen at random. This, however is on a PER PLAYER basis. --i.e. if KnifeHeart and Cy are both in the same sector and KnifeHeart had a decap strike in the last hour, Cy can still get hit by one. --At least one player in the sector must have at least 50 notoriety and 200 hatred to trigger a decapitation strike event. --Even if both players are eligible for a decap strike event, it starts at a 25% chance at 200 hatred, and caps at a 75% chance at 1000. --So you might still get lucky and skip some decapitation strikes. --Executioner strength is based on the hatred value of the targeted player. --Number of executioners spawn based on the number of ships that the targeted player owns in the sector. It is 1 ex per 3 ships up to 16, then 1 per 2 afterwards. --BUT the pirates aren't stupid. They will add one standard ship to the list of ships for each ship owned by a player who is NOT the targeted player. local ITPlayers = ITUtil.getSectorPlayersByHatred(piratefaction.index) local triggerDecapStrike = false local serverTime = Server().unpausedRuntime for _, p in pairs(ITPlayers) do if p.hatred >= 200 and p.notoriety >= 50 then --eligible for a decap. Check to see when the last decap strike they got hit with was. local nextDecapTime = p.player:getValue("_increasingthreat_next_decap") or -1 DecapStrike.Log(_MethodName, "next decap OK at " .. tostring(nextDecapTime) .. " <= current time is: " .. tostring(serverTime)) if serverTime >= nextDecapTime or nextDecapTime == -1 then local chance = 25 + math.min(50, math.floor(math.max(0, p.hatred - 200) / 16)) DecapStrike.Log(_MethodName, "Chance to initiate decap is " .. tostring(chance) .. " chance") if math.random(100) < chance then --This is it. We set off a decap strike here. triggerDecapStrike = true decapTargetPlayer = p.player decapHatredLevel = p.hatred local nextDecapHrs = math.random(3,6) if DecapStrike._HETActive then nextDecapHrs = nextDecapHrs * 0.6 end local _Vengeful = piratefaction:getTrait("vengeful") if _Vengeful and _Vengeful >= 0.25 then DecapStrike.Log(_MethodName, "Pirates are Vengeful. Decreasing time until next decap strike happens.") local _VengefulFactor = 1.0 if _Vengeful >= 0.25 then _VengefulFactor = 0.8 end if _Vengeful >= 0.75 then _VengefulFactor = 0.7 end nextDecapHrs = nextDecapHrs * _VengefulFactor end DecapStrike.Log(_MethodName, "Next decap will be in " .. tostring(nextDecapHrs) .. " decap hatred level is " .. tostring(decapHatredLevel) .. " || " .. tostring(type(decapHatredLevel))) local nextDecap = serverTime + (3600 * nextDecapHrs) p.player:setValue("_increasingthreat_next_decap", nextDecap) break end else DecapStrike.Log(_MethodName, p.player.name .. " was targeted by a decap strike recently. Checking next potential target.") end else DecapStrike.Log(_MethodName, "Player hatred only " .. tostring(p.hatred) .. " and notoriety is only " .. tostring(p.notoriety) .. " - player isn't eligible for a decap.") end end if triggerDecapStrike then --Count target player ships and non-target player ships. local targetPlayerShips = 0 local nonTargetPlayerShips = 0 local factions = {_Sector:getPresentFactions()} for _, index in pairs(factions) do local faction = Faction(index) if faction then local crafts = {_Sector:getEntitiesByFaction(index)} for _, craft in pairs(crafts) do if craft.isShip or craft.isStation then if faction.isPlayer then if index == decapTargetPlayer.index then DecapStrike.Log(_MethodName, "Ship belongs to target of decap strike. Increasing target player ships value.") targetPlayerShips = targetPlayerShips + 1 else DecapStrike.Log(_MethodName, "Ship does not belong to target. Increasing non target player ships value.") nonTargetPlayerShips = nonTargetPlayerShips + 1 end end if faction.isAlliance then local allx = Alliance(faction.index) if allx:contains(decapTargetPlayer.index) then DecapStrike.Log(_MethodName, "Alliance contains targeted player. Use this to count their ships.") decapTargetAlliance = faction targetPlayerShips = targetPlayerShips + 1 else nonTargetPlayerShips = nonTargetPlayerShips + 1 end end if faction.isAIFaction then --AI ships / stations count double since they get cheater buffs. (i.e. damage multipliers) nonTargetPlayerShips = nonTargetPlayerShips + 2 end end end end end DecapStrike.Log(_MethodName, "Ships owned by target: " .. targetPlayerShips) DecapStrike.Log(_MethodName, "Ships not owned by target: " .. nonTargetPlayerShips) --subtract 1 from this immediately because we are spawning an executioner directly in this block of code. remaining_executioners = math.ceil(math.min(4, targetPlayerShips / 4) + (math.max(0, targetPlayerShips - 16) / 2)) - 1 DecapStrike.Log(_MethodName, "spawning " .. remaining_executioners .. " plus one.") local numberOfOtherShips = nonTargetPlayerShips local _Brutish = piratefaction:getTrait("brutish") if _Brutish and _Brutish >= 0.25 then numberOfOtherShips = math.max(5, math.floor(numberOfOtherShips * 1.3)) end if DecapStrike._HETActive then numberOfOtherShips = math.floor(numberOfOtherShips * 1.5) --50% more ships. remaining_executioners = remaining_executioners + 1 --1 more executioner end local lowThreatTable = ITUtil.getLowThreatTable() local highThreatTable = ITUtil.getHatredTable(decapHatredLevel) for _ = 1, numberOfOtherShips do table.insert(pirate_reserves, highThreatTable[math.random(#highThreatTable)]) end --Create the first wave. It always consists of an executioner. local attackingShips = {} table.insert(attackingShips, "Executioner") local firstWaveExtras = math.random(2, 4) for _ = 1, firstWaveExtras do if next(pirate_reserves) ~= nil then local xShip = table.remove(pirate_reserves) table.insert(attackingShips, xShip) else table.insert(attackingShips, lowThreatTable[math.random(#lowThreatTable)]) end end generator:startBatch() local posCounter = 1 local pirate_positions = generator:getStandardPositions(#attackingShips, 300) for _, p in pairs(attackingShips) do if p == "Executioner" then generator:createScaledExecutioner(pirate_positions[posCounter], decapHatredLevel) else generator:createScaledPirateByName(p, pirate_positions[posCounter]) end posCounter = posCounter + 1 end generator:endBatch() local alertstring = string.format("%s is being targeted by a pirate attack"%_t, decapTargetPlayer.name) _Sector:broadcastChatMessage("Server"%_t, 2, alertstring .. "!") AlertAbsentPlayers(2, alertstring .. " in sector \\s(%1%:%2%)!"%_t, _Sector:getCoordinates()) else DecapStrike.Log(_MethodName, "no decap strike. Terminating the event.") ITUtil.unpauseEvents() terminate() return end end end function DecapStrike.getUpdateInterval() return 10 end --Created Callbacks function DecapStrike.onPiratesGenerated(generated) -- add enemy buffs SpawnUtility.addEnemyBuffs(generated) --Covered IT Extra Scripts local _WilyTrait = piratefaction:getTrait("wily") or 0 SpawnUtility.addITEnemyBuffs(generated, _WilyTrait, decapHatredLevel) for _, ship in pairs(generated) do if valid(ship) then -- this check is necessary because ships could get destroyed before this callback is executed ships[ship.index.string] = true ship:registerCallback("onDestroyed", "onShipDestroyed") end end for _, ship in pairs(generated) do local isexec = ship:getValue("is_executioner") or 0 if isexec == 1 then Sector():broadcastChatMessage(ship, ChatMessageType.Chatter, decap_taunts[math.random(#decap_taunts)]) break end end -- resolve intersections between generated ships Placer.resolveIntersections(generated) DecapStrike.attackersGenerated = true end function DecapStrike.onNextPiratesGenerated(generated) -- add enemy buffs SpawnUtility.addEnemyBuffs(generated) --Covered IT Extra Scripts local _WilyTrait = piratefaction:getTrait("wily") or 0 SpawnUtility.addITEnemyBuffs(generated, _WilyTrait, decapHatredLevel) for _, ship in pairs(generated) do if valid(ship) then -- this check is necessary because ships could get destroyed before this callback is executed ships[ship.index.string] = true ship:registerCallback("onDestroyed", "onShipDestroyed") end end -- resolve intersections between generated ships Placer.resolveIntersections(generated) DecapStrike.attackersGenerated = true end function DecapStrike.onShipDestroyed(shipIndex) ships[shipIndex.string] = nil local ship = Entity(shipIndex) local damagers = {ship:getDamageContributors()} for _, damager in pairs(damagers) do local faction = Faction(damager) if faction and (faction.isPlayer or faction.isAlliance) then participants[damager] = damager end end if #pirate_reserves == 0 and tablelength(ships) == 0 and remaining_executioners == 0 then DecapStrike.endEvent() end end function DecapStrike.update(timeStep) local _MethodName = "Update" DecapStrike.Log(_MethodName, "running decap strike update") if not DecapStrike.attackersGenerated then return end local _PiratesInSector = {Sector():getEntitiesByFaction(piratefaction)} local _PiratesInSectorCt = #_PiratesInSector local noShips = tablelength(ships) if noShips < 25 and _PiratesInSectorCt < 40 then local pirateBatch = {} if remaining_executioners > 0 then table.insert(pirateBatch, "Executioner") local lowThreatTable = ITUtil.getLowThreatTable() local WaveExtras = math.random(2, 4) for _ = 1, WaveExtras do if next(pirate_reserves) ~= nil then local xShip = table.remove(pirate_reserves) table.insert(pirateBatch, xShip) else table.insert(pirateBatch, lowThreatTable[math.random(#lowThreatTable)]) end end remaining_executioners = remaining_executioners - 1 end if #pirateBatch < 5 and #pirate_reserves > 0 then local ins = 5 - #pirateBatch --Keep # of ships from going above 25. if noShips + ins > 25 then ins = 25 - noShips end for _ = 1, ins do if next(pirate_reserves) ~= nil then local xShip = table.remove(pirate_reserves) table.insert(pirateBatch, xShip) end end end local generator = AsyncPirateGenerator(DecapStrike, DecapStrike.onNextPiratesGenerated) generator:startBatch() local posCounter = 1 local pirate_positions = generator:getStandardPositions(#pirateBatch, 300) for _, p in pairs(pirateBatch) do if p == "Executioner" then generator:createScaledExecutioner(pirate_positions[posCounter], decapHatredLevel) else generator:createScaledPirateByName(p, pirate_positions[posCounter]) end posCounter = posCounter + 1 end generator:endBatch() end local decapTargets = 0 local crafts = {Sector():getEntitiesByFaction(decapTargetPlayer.index)} for _, c in pairs(crafts) do if c.isShip or c.isStation then decapTargets = decapTargets + 1 end end if decapTargetAlliance then local acrafts = {Sector():getEntitiesByFaction(decapTargetAlliance.index)} for _, c in pairs(acrafts) do if c.isShip or c.isStation then decapTargets = decapTargets + 1 end end end local sentTaunt = false if decapTargets == 0 then local pcrafts = {Sector():getEntitiesByFaction(piratefaction.index)} pirate_reserves = {} ships = {} for _, pcraft in pairs(pcrafts) do if pcraft.isShip and not sentTaunt then Sector():broadcastChatMessage(pcraft, ChatMessageType.Chatter, exit_taunts[math.random(#exit_taunts)]) sentTaunt = true end if pcraft.isShip then pcraft:addScriptOnce("entity/utility/delayeddelete.lua", random():getFloat(3, 6)) end end end DecapStrike.Log(_MethodName, "pirate reserve count is " .. #pirate_reserves) DecapStrike.Log(_MethodName, "ship count remaining is " .. noShips) if #pirate_reserves == 0 and noShips == 0 and remaining_executioners == 0 then DecapStrike.endEvent() end end function DecapStrike.endEvent() local _MethodName = "End Event" DecapStrike.Log(_MethodName, "ending decap strike") local _IncreasedHatredFor = {} local players = {Sector():getPlayers()} for _, participant in pairs(participants) do local participantFaction = Faction(participant) if participantFaction then if participantFaction.isPlayer and not _IncreasedHatredFor[participantFaction.index] then DecapStrike.Log(_MethodName, "Have not yet increased hatred for faction index " .. tostring(participantFaction.index) .. " - increasing hatred.") DecapStrike.increaseHatred(participantFaction) _IncreasedHatredFor[participantFaction.index] = true end if participantFaction.isAlliance then local _Alliance = Alliance(participant) for _, _Pl in pairs(players) do if _Alliance:contains(_Pl.index) and not _IncreasedHatredFor[_Pl.index] then DecapStrike.increaseHatred(_Pl) _IncreasedHatredFor[_Pl.index] = true else DecapStrike.Log(_MethodName, "Have either increased hatred for faciton index " .. tostring(_Pl.index) .. " or they are not part of the alliance.") end end end end end terminate() end function DecapStrike.patchPirateFaction() if not piratefaction then --needed to patch an issue on Divine Reapers. Not sure why this happens but apparently my previous patch didn't fix it. local generator = AsyncPirateGenerator(DecapStrike, DecapStrike.onPiratesGenerated) piratefaction = generator:getPirateFaction() end end end --region #CLIENT / SERVER CALLS function DecapStrike.increaseHatred(_Faction) local _MethodName = "Increase Hatred" local hatredindex = "_increasingthreat_hatred_" .. piratefaction.index local hatred = _Faction:getValue(hatredindex) local xmultiplier = 1 local _Difficulty = GameSettings().difficulty if _Difficulty == Difficulty.Veteran then xmultiplier = 1.15 elseif _Difficulty == Difficulty.Expert then xmultiplier = 1.3 elseif _Difficulty > Difficulty.Expert then xmultiplier = 1.5 end local hatredincrement = 15 * xmultiplier local _Tempered = piratefaction:getTrait("tempered") if _Tempered then local _TemperedFactor = 1.0 if _Tempered >= 0.25 then _TemperedFactor = 0.8 end if _Tempered >= 0.75 then _TemperedFactor = 0.7 end DecapStrike.Log(_MethodName, "Faction is tempered - hatred multiplier is (" .. tostring(_TemperedFactor) .. ")") hatredincrement = hatredincrement * _TemperedFactor end hatredincrement = math.ceil(hatredincrement) if hatred then DecapStrike.Log(_MethodName, "hatred value is " .. hatred) hatred = hatred + hatredincrement else DecapStrike.Log(_MethodName, "hatred value is 0") hatred = hatredincrement end DecapStrike.Log(_MethodName, "new hatred value is " .. hatred) _Faction:setValue(hatredindex, hatred) if hatred >= 700 then DecapStrike.Log(_MethodName, "Hatred is greater than 700. Setting traits for pirates.") ITUtil.setIncreasingThreatTraits(piratefaction) end end function DecapStrike.Log(_MethodName, _Msg) if DecapStrike._Debug == 1 then print("[IT DecapStrike] - [" .. tostring(_MethodName) .. "] - " .. tostring(_Msg)) end end --endregion
-- Mixes in a large suite of iteration functions to the specified library. This -- mixin allow you to interact with various iterable types with a healthy baseline -- of functionality. -- -- Specifically, this mixin adds a set of generic accessors and modifiers, insertion -- and removal functions, cloning, updating, and reversing. if nil ~= require then require "fritomod/currying"; require "fritomod/Operator"; require "fritomod/Mixins-Iteration"; end; if Mixins == nil then Mixins = {}; end; -- The specified library must provide an Iterator function, as required by -- Mixins.Iteration. Other methods should be provided for various parts of this mixin: -- -- * New - used for cloning, reversing -- * Set - used in Update -- * Delete - will default to Set(iterable, key, nil); -- * Insert - required for Insert* functions -- -- These functions, except for Insert, have defaults, but these assume a table-like -- iterable. -- -- library -- a table that provides an Iterator function -- iteratorFunc -- optional. A function that creates an iterator usable for this library -- returns -- library -- see -- Mixins.Iteration. This mixin is also used on the specified library function Mixins.MutableIteration(library, iteratorFunc) library=library or {}; local lib=library; Mixins.Iteration(library, iteratorFunc); if library.New == nil then -- Returns a new, empty iterable that is usable by this library. -- -- returns -- a new iterable usable by this library -- throws -- if this library does not support this operation function library.New() return {}; end; end; if library.Set == nil then -- Sets the specified pair to the specified iterable, overriding any existing -- values for the specified key. -- -- This is an optional operation. -- -- iterable -- an iterable usable by this library -- key -- the key that will be inserted into this iterable -- value -- the value that will be inserted into this iterable -- returns -- the old value -- throws -- if this library does not support this operation function library.Set(iterable, key, value) assert(type(iterable) == "table", "Iterable is not a table"); local oldValue = iterable[key]; iterable[key] = value; return oldValue; end; end; -- An undoable Set if library.Change == nil then function library.Change(iterable, key, value) local oldValue=library.Get(iterable, key); library.Set(iterable, key, value); return Functions.OnlyOnce(function() library.Set(iterable, key, oldValue); end); end; end; if library.Delete == nil then -- Deletes the specified key from the specified iterable. -- -- iterable -- an iterable usable by this library -- key -- the key that will be deleted from this iterable -- returns -- the value that was at the specified key -- throws -- if this library does not support this operation function library.Delete(iterable, key) return library.Set(iterable, key, nil); end; end; -- Inserts the specified value to the specified iterable. -- -- This is an optional operation. -- -- iterable -- an iterable usable by this library -- value -- the value that will be inserted into this library -- returns -- a function that, when invoked, removes the specified value -- throws -- if this library does not support this operation if library.Insert == nil then -- This function must be explicitly implemented by clients. end; if library.InsertFunction == nil then -- Inserts the specified curried function into the specified iterable. -- -- This is an optional operation. -- -- iterable -- an iterable used by this library -- func, ... -- the function that is inserted into this iterable -- returns -- a function that, when invoked, removes the specified function -- throws -- if this library does not support this operation function library.InsertFunction(iterable, func, ...) return library.Insert(iterable, Curry(func, ...)); end; end; -- Inserts the specified pair into the specified iterable. -- -- This is an optional operation. -- -- The key may or may not be used by this operation. -- -- iterable -- an iterable usable by this library -- key -- the key that will be inserted into this library. It may be discarded. -- value -- the value that will be inserted into this library -- returns -- a function that, when invoked, removes the specified value -- throws -- if this library does not support this operation if library.InsertPair == nil then function library.InsertPair(iterable, key, value) return library.Insert(iterable, value); end; end; if library.InsertAll == nil then -- Inserts all specified values into the specified iterable. -- -- This is an optional operation. -- -- iterable -- an iterable usable by this library -- ... -- the value that will be inserted into this library -- returns -- a function that, when invoked, removes the specified values -- throws -- if this library does not support this operation function library.InsertAll(iterable, ...) assert(type(library.Insert) == "function", "Insert is not implemented by this library"); local removers = {}; for i=1, select("#", ...) do local value = select(i, ...); table.insert(removers, library.Insert(iterable, value)); end; return function() for i=1, #removers do removers[i](); end; removers = {}; end; end; end; if library.InsertAt == nil then -- Inserts the specified value into the specified iterable. -- -- This is an optional operation. -- -- iterable -- an iterable usable by this library -- index -- the location of the inserted item -- value -- the value that will be inserted into this iterable -- returns -- a function that, when invoked, removes the specified value -- throws -- if this library does not support this operation function library.InsertAt(list, index, value) assert(type(library.Insert) == "function", "Insert is not implemented by this library"); if not index then return Lists.Insert(list, value); end; assert(type(index) == "number", "index is not a number. Type: " .. type(index)); table.insert(list, index, value); return Curry(library.Remove, list, value); end; end; if library.InsertAllAt == nil then -- Inserts all of the specified values into the specified iterable. -- -- This is an optional operation. -- -- iterable -- an iterable usable by this library -- index -- the starting location where items are inserted -- ... -- the values that will be inserted into this iterable -- returns -- a function that, when invoked, removes all specified values -- throws -- if this library does not support this operation function library.InsertAllAt(list, index, ...) assert(type(library.Insert) == "function", "Insert is not implemented by this library"); assert(type(index) == "number", "index is not a number. Type: " .. type(index)); local removers = {}; for i=1, select("#", ...) do local value = select(i, ...); table.insert(removers, index, library.Insert(iterable, value)); index = index + 1; end; return function() for i=1, #removers do removers[i](); end; removers = {}; end; end; end; if library.SwapKeys == nil then function library.SwapKeys(iterable, a, b) local temp=library.Get(iterable, a); library.Set(iterable, a, library.Get(iterable, b)); library.Set(iterable, b, temp); end; end; if library.SwapValues == nil then function library.SwapValues(iterable, a, b) return library.SwapKeys(iterable, library.KeyFor(iterable, a), library.KeyFor(iterable, b) ); end; end; if library.Swap == nil then library.Swap = CurryNamedFunction(library, "SwapKeys"); end; if library.Remove == nil then -- Removes the first matching value from the specified iterable, according to the specified -- test and specified target value. -- -- iterable -- an iterable usable by this library. -- targetValue -- the searched value -- testFunc, ... -- optional. The test that performs the search for the specified value -- returns -- the removed key, or nil if no value was removed function library.Remove(iterable, targetValue, testFunc, ...) if testFunc then testFunc = library.NewEqualsTest(testFunc, ...); end; for key, candidate in library.Iterator(iterable) do if testFunc then if testFunc(candidate, targetValue) then return library.Delete(iterable, key); end; else if candidate == targetValue then return library.Delete(iterable, key); end end; end; end; end; if library.RemoveValue == nil then library.RemoveValue = CurryNamedFunction(library, "Remove"); end; if library.RemoveFirst == nil then library.RemoveFirst = CurryNamedFunction(library, "Remove"); end; if library.RemoveAll == nil then -- Removes all matching values from the specified iterable, according to the specified -- test and specified value. -- -- This function does not modify the iterable until every item has been iterated. While -- this minimizes the chance of corrupted iteration, it is also potentially more -- inefficient than a safe, iterable-specific solution. -- -- iterable -- an iterable usable by this library. -- targetValue -- the searched value -- testFunc, ... -- optional. The test that performs the search for the specified value -- returns -- the number of removed elements function library.RemoveAll(iterable, targetValue, testFunc, ...) if testFunc then testFunc = library.NewEqualsTest(testFunc, ...); end; local removedKeys = {}; for key, candidate in library.Iterator(iterable) do if testFunc then if testFunc(candidate, targetValue) then table.insert(removedKeys, key); end else if candidate == targetValue then table.insert(removedKeys, key); end; end; end; for i=#removedKeys, 1, -1 do library.Delete(iterable, removedKeys[i]); end; return #removedKeys; end; end; if library.RemoveLast == nil then -- Removes the last matching value from the specified iterable, according to the specified -- test and specified value. -- -- iterable -- an iterable usable by this library. -- targetValue -- the searched value -- testFunc, ... -- optional. The test that performs the search for the specified value -- returns -- the removed key, or nil if no value was removed function library.RemoveLast(iterable, targetValue, testFunc, ...) testFunc = library.NewEqualsTest(testFunc, ...); for key, candidate in library.ReverseIterator(iterable) do if testFunc(candidate, targetValue) then library.Delete(iterable, key); return key; end; end; end; end; if library.RemoveAt == nil then -- Removes the first matching key from the specified iterable, according to the specified -- test and specified target key. -- -- This is an optional operation. -- -- iterable -- an iterable usable by this library. -- targetKey -- the searched key -- testFunc, ... -- optional. The test that performs the search for the specified value -- returns -- the removed value, or nil if no key was removed function library.RemoveAt(iterable, targetKey, testFunc, ...) testFunc = library.NewEqualsTest(testFunc, ...); for candidate, value in library.Iterator(iterable) do if testFunc(candidate, targetKey) then return library.Delete(iterable, targetKey); end; end; end; end; if library.RemoveAllAt == nil then -- Removes all matching keys from the specified iterable, according to the specified -- test and specified target key. -- -- This function does not modify the iterable until every item has been iterated. While -- this minimizes the chance of corrupted iteration, it is also potentially more -- inefficient than a safe, iterable-specific solution. -- -- This is an optional operation. -- -- iterable -- an iterable usable by this library. -- targetKey -- the searched key -- testFunc, ... -- optional. The test that performs the search for the specified value -- returns -- the number of removed elements function library.RemoveAllAt(iterable, targetKey, testFunc, ...) testFunc = library.NewEqualsTest(testFunc, ...); local removedKeys = {}; for candidate, value in library.Iterator(iterable) do if testFunc(candidate, targetKey) then table.insert(removedKeys, key); end; end; for i=#removedKeys, 1, -1 do library.Delete(iterable, removedKeys[i]); end; return #removedKeys; end; end; if library.RemoveLastAt == nil then -- Removes the last matching key from the specified iterable, according to the specified -- test and specified target key. -- -- This is an optional operation. -- -- iterable -- an iterable usable by this library. -- targetKey -- the searched key -- testFunc, ... -- optional. The test that performs the search for the specified value -- returns -- the removed value, or nil if no key was removed function library.RemoveLastAt(iterable, targetKey, testFunc, ...) testFunc = library.NewEqualsTest(testFunc, ...); for candidate, value in library.ReverseIterator(iterable) do if testFunc(candidate, targetKey) then library.Delete(iterable, key); return value; end; end; end; end; if library.Pop==nil then function library.Pop(iterable, count) count=count or 1; local s=library.Size(iterable); count=math.min(s,count); local final=s-count; local removed=library.New(); while s>final do library.Insert(removed, library.RemoveAt(iterable, s)); s=s-1; end; return removed; end; end; if library.PopOne==nil then function library.PopOne(iterable) return library.RemoveAt(iterable, library.Size(iterable)); end; end; if library.Push==nil then function library.Push(iterable, value) return library.Insert(iterable, value); end; end; if library.Shift==nil then function library.Shift(iterable, count) count=count or 1; local s=library.Size(iterable); count=math.min(s,count); local removed=library.New(); while count>0 do library.Insert(removed, library.RemoveAt(iterable,1)); count=count-1; end; return removed; end; end; if library.ShiftOne==nil then function library.ShiftOne(iterable) if not library.IsEmpty(iterable) then return library.RemoveAt(iterable, 1); end; end; end; if library.Unshift == nil then function library.Unshift(iterable, value) return library.InsertAt(iterable, 1, value); end; end; if library.RotateRight == nil then function library.RotateRight(iterable, count) while count > 0 do library.Unshift(iterable, library.PopOne(iterable)); count = count - 1; end; end; end; if library.RotateLeft == nil then function library.RotateLeft(iterable, count) while count > 0 do library.Push(iterable, library.ShiftOne(iterable)); count = count - 1; end; end; end; if library.Clear == nil then -- Removes every element from the specified iterable. -- -- iterable -- the iterable that is modified by this operation function library.Clear(iterable) local keys = library.Keys(iterable); for i=#keys, 1, -1 do library.Delete(iterable, keys[i]); end; end; end; if library.Clone == nil then -- Returns an iterable that is the clone of the specified iterable. -- -- iterable -- a value that is iterable using library.Iterator -- returns -- a clone of the specified iterable function library.Clone(iterable) local cloned = library.New(); for key, value in library.Iterator(iterable) do library.InsertPair(cloned, key, value); end; return cloned; end; end; if lib.Shuffle == nil then function lib.Shuffle(iterable) for i=1,lib.Size(iterable) do lib.Swap(iterable, lib.Random(iterable), lib.Random(iterable)); end; end; end; if library.Sort == nil then local function Partition(iter, compare, left, right) local m=lib.Get(iter, left+math.floor((right-left)/2)); local i,j=left,right; repeat while compare(lib.Get(iter,i), m) < 0 do i=i+1; end; while compare(lib.Get(iter,j), m) > 0 do j=j-1; end; if i <= j then lib.Swap(iter,i,j); i=i+1; j=j-1; end until i > j; if left < j then Partition(iter, compare, left, j); end; if i < right then Partition(iter, compare, i, right); end; end; function library.Sort(iterable, compareFunc, ...) compareFunc=library.NewComparator(compareFunc, ...); local s=library.Size(iterable); if s < 2 then return iterable; end; assert(s); Partition(iterable, compareFunc, 1, s); return iterable; end; end; if library.Update == nil then -- Updates targetIterable such that updatingIterable is copied over it. -- -- targetIterable -- the target iterable that is affected by this operation -- updatingIterable -- the unmodified iterable that is the source of updates to targetIterable -- func, ... -- the function that performs the update. function library.Update(targetIterable, updatingIterable, func, ...) if not func and select("#", ...) == 0 then func = library.Set; end; for key, value in library.Iterator(updatingIterable) do func(targetIterable, key, value); end; end; end; if library.Reverse == nil then -- Returns a new iterable that is the reverse of the specified iterable -- -- iterable -- the iterable that is reversed -- returns -- a new iterable that contains every element -- throws -- if this library does not support this operation function library.Reverse(iterable) local reversed = library.New(); for value in library.ReverseValueIterator(iterable) do library.InsertPair(reversed, key, value); end; return reversed; end; end; local function trim(remover, iterable, limit) return remover(iterable, library.Size(iterable)-limit); end; if library.ShiftTrim == nil then library.ShiftTrim=CurryFunction(trim, CurryNamedFunction(library, "Shift")); end; library.QueueTrim = CurryNamedFunction(library, "ShiftTrim"); if library.PopTrim == nil then library.PopTrim=CurryFunction(trim, CurryNamedFunction(library, "Pop")); end; library.StackTrim = CurryNamedFunction(library, "PopTrim"); return library; end;
function BadCoderz.ReadReport() local len = net.ReadUInt(16) local data = net.ReadData(len) local json = util.Decompress(data) local table = util.JSONToTable(json) return table end net.Receive("BadCoderz_status_request", function() local codeSmellsScan = net.ReadBool() local compiledFuncsScan = net.ReadBool() local scanOnReboot = net.ReadBool() BadCoderz.ShowUI(codeSmellsScan, compiledFuncsScan, scanOnReboot) end) concommand.Add("BadCoderz", function() if not LocalPlayer():CanUseBadCoderz() then LocalPlayer():ChatPrint("You cannot use badcoderz") return end net.Start("BadCoderz_status_request") net.SendToServer() end) net.Receive("BadCoderz_report_request", function() local active = net.ReadBool() local report = BadCoderz.ReadReport() if (BadCoderz.Derma and IsValid(BadCoderz.Derma)) then BadCoderz.Derma.buttonServerside:UpdateAsync(active, report) end end) net.Receive("BadCoderz_serverside_file_open", function(len) local realPath = net.ReadString() local datalen = net.ReadUInt(16) local data = net.ReadData(datalen) local line if (net.ReadBool()) then line = net.ReadUInt(13) end data = util.Decompress(data) if not data then error("Could not read file data from server : " .. realPath) return end BadCoderz.openLuaPad(data, realPath, line) end) net.Receive("BadCoderz_serverside_bytecode_reader", function(len) assert(GLib, "GLib is missing") local bytecode = util.Decompress(net.ReadData(net.ReadUInt(16))) local pointer = net.ReadString() local stack = net.ReadString() local location = net.ReadString() local code = string.format("--[[\n\n%s\n\n]]\n\n", stack) .. bytecode BadCoderz.openLuaPad(code, "DECOMPILED VIRTUAL FUNCTION : " .. pointer .. " " .. location) end)
Propagation = { Unhandled = 0, Handled = 1 } -- Represents the buttons on the gameboy system Button = { Right = 0, Left = 1, Up = 2, Down = 3, A = 4, B = 5, Select = 6, Start = 7 } -- Virtual keycodes for keyboard input Key = { Unknown = 0x00, Backspace = 0x08, Tab = 0x09, Clear = 0x0C, Enter = 0x0D, Shift = 0x10, Ctrl = 0x11, Alt = 0x12, Pause = 0x13, Caps = 0x14, Esc = 0x1B, Space = 0x20, PageUp = 0x21, PageDown = 0x22, End = 0x23, Home = 0x24, LeftArrow = 0x25, UpArrow = 0x26, RightArrow = 0x27, DownArrow = 0x28, Select = 0x29, Print = 0x2A, Execute = 0x2B, PrintScreen = 0x2C, Insert = 0x2D, Delete = 0x2E, Help = 0x2F, Num0 = 0x30, Num1 = 0x31, Num2 = 0x32, Num3 = 0x33, Num4 = 0x34, Num5 = 0x35, Num6 = 0x36, Num7 = 0x37, Num8 = 0x38, Num9 = 0x39, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4A, K = 0x4B, L = 0x4C, M = 0x4D, N = 0x4E, O = 0x4F, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5A, LeftWin = 0x5B, RightWin = 0x5C, Sleep = 0x5F, NumPad0 = 0x60, NumPad1 = 0x61, NumPad2 = 0x62, NumPad3 = 0x63, NumPad4 = 0x64, NumPad5 = 0x65, NumPad6 = 0x66, NumPad7 = 0x67, NumPad8 = 0x68, NumPad9 = 0x69, Multiply = 0x6A, Add = 0x6B, Separator = 0x6C, Subtract = 0x6D, Decimal = 0x6E, Divide = 0x6F, F1 = 0x70, F2 = 0x71, F3 = 0x72, F4 = 0x73, F5 = 0x74, F6 = 0x75, F7 = 0x76, F8 = 0x77, F9 = 0x78, F10 = 0x79, F11 = 0x7A, F12 = 0x7B, F13 = 0x7C, F14 = 0x7D, F15 = 0x7E, F16 = 0x7F, F17 = 0x80, F18 = 0x81, F19 = 0x82, F20 = 0x83, F21 = 0x84, F22 = 0x85, F23 = 0x86, F24 = 0x87, NumLock = 0x90, Scroll = 0x91, LeftShift = 0xA0, RightShift = 0xA1, LeftCtrl = 0xA2, RightCtrl = 0xA3, LeftMenu = 0xA4, RightMenu = 0xA5 } -- Represents buttons on a game pad Pad = { -- Axis converted to button presses LeftStickLeft = 0, LeftStickRight = 1, LeftStickDown = 2, LeftStickUp = 3, RightStickLeft = 4, RightStickRight = 5, RightStickDown = 6, RightStickUp = 7, -- Actual button presses Start = 44, Select = 45, Left = 46, Right = 47, Up = 48, Down = 49, A = 50, B = 51, X = 52, Y = 53, L1 = 54, R1 = 55, L2 = 56, R2 = 57, L3 = 58, R3 = 59, Home = 60, Button17 = 61, Button18 = 62, Button19 = 63, Button20 = 64, Button21 = 65, Button22 = 66, Button23 = 67, Button24 = 68, Button25 = 69, Button26 = 70, Button27 = 71, Button28 = 72, Button29 = 73, Button30 = 74, Button31 = 75 } MidiNote = { C2 = 0, CSharp2 = 1 }
-- deque.lua: tests for double-ended queue wrapper -- This file is a part of lua-nucleo library -- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license) dofile('lua-nucleo/strict.lua') dofile('lua-nucleo/import.lua') local make_suite = select(1, ...) assert(type(make_suite) == "function") math.randomseed(12345) local ensure, ensure_equals, ensure_tequals, ensure_tdeepequals, ensure_fails_with_substring = import 'lua-nucleo/ensure.lua' { 'ensure', 'ensure_equals', 'ensure_tequals', 'ensure_tdeepequals', 'ensure_fails_with_substring' } local arguments = import 'lua-nucleo/args.lua' { 'arguments' } local tset, tclone, empty_table, tstr = import 'lua-nucleo/table.lua' { 'tset', 'tclone', 'empty_table', 'tstr' } local make_value_generators = import 'test/lib/value_generators.lua' { 'make_value_generators' } -------------------------------------------------------------------------------- local make_deque, deque_exports = import 'lua-nucleo/deque.lua' { 'make_deque' } -------------------------------------------------------------------------------- local test = make_suite("deque", deque_exports) -------------------------------------------------------------------------------- test:factory "make_deque" ((function() return debug.getmetatable(make_deque()).__index -- TODO: Hack end)) test:methods "back" "pop_back" "push_back" "front" "pop_front" "push_front" "size" -------------------------------------------------------------------------------- test "deque-empty-size" (function() local deque = make_deque() ensure_equals("size", deque:size(), 0) end) test "deque-empty-back" (function() local deque = make_deque() ensure_equals("back", deque:back(), nil) end) test "deque-empty-front" (function() local deque = make_deque() ensure_equals("front", deque:front(), nil) end) test "deque-empty-pop_back" (function() local deque = make_deque() ensure_equals("pop_back", deque:pop_back(), nil) end) test "deque-empty-pop_front" (function() local deque = make_deque() ensure_equals("pop_front", deque:pop_front(), nil) end) test "deque-empty-push-pop-back" (function() local deque = make_deque() deque:push_back(42) ensure_equals("size", deque:size(), 1) ensure_equals("back", deque:back(), 42) ensure_equals("front", deque:front(), 42) ensure_equals("pop back", deque:pop_back(), 42) ensure_equals("size empty", deque:size(), 0) ensure_equals("back empty", deque:back(), nil) ensure_equals("front empty", deque:front(), nil) end) test "deque-empty-push-pop-front" (function() local deque = make_deque() deque:push_front(42) ensure_equals("size", deque:size(), 1) ensure_equals("back", deque:back(), 42) ensure_equals("front", deque:front(), 42) ensure_equals("pop front", deque:pop_front(), 42) ensure_equals("size empty", deque:size(), 0) ensure_equals("back empty", deque:back(), nil) ensure_equals("front empty", deque:front(), nil) end) test "deque-empty-push-back-pop-front" (function() local deque = make_deque() deque:push_back(42) ensure_equals("size", deque:size(), 1) ensure_equals("back", deque:back(), 42) ensure_equals("front", deque:front(), 42) ensure_equals("pop front", deque:pop_front(), 42) ensure_equals("size empty", deque:size(), 0) ensure_equals("back empty", deque:back(), nil) ensure_equals("front empty", deque:front(), nil) end) test "deque-empty-push-front-pop-back" (function() local deque = make_deque() deque:push_front(42) ensure_equals("size", deque:size(), 1) ensure_equals("back", deque:back(), 42) ensure_equals("front", deque:front(), 42) ensure_equals("pop back", deque:pop_back(), 42) ensure_equals("size empty", deque:size(), 0) ensure_equals("back empty", deque:back(), nil) ensure_equals("front empty", deque:front(), nil) end) test "deque-empty-over-pop_front" (function() local deque = make_deque() ensure_equals("pop front 1", deque:pop_front(), nil) ensure_equals("pop front 2", deque:pop_front(), nil) ensure_equals("pop front 3", deque:pop_front(), nil) deque:push_front(42) ensure_equals("size", deque:size(), 1) ensure_equals("back", deque:back(), 42) ensure_equals("front", deque:front(), 42) end) test "deque-empty-over-pop_back" (function() local deque = make_deque() ensure_equals("pop back 1", deque:pop_back(), nil) ensure_equals("pop back 2", deque:pop_back(), nil) ensure_equals("pop back 3", deque:pop_back(), nil) deque:push_back(42) ensure_equals("size", deque:size(), 1) ensure_equals("back", deque:back(), 42) ensure_equals("front", deque:front(), 42) end) -------------------------------------------------------------------------------- test "deque-wraps-data" (function() local t = { 42 } local deque = make_deque(t) ensure_equals("deque wraps data", deque, t) -- Direct equality ensure_equals("size", deque:size(), 1) ensure_equals("back", deque:back(), 42) ensure_equals("front", deque:front(), 42) ensure_equals("size", deque:size(), 1) ensure_equals("back", deque:back(), 42) ensure_equals("front", deque:front(), 42) ensure_equals("pop back", deque:pop_back(), 42) ensure_equals("size empty", deque:size(), 0) ensure_equals("back empty", deque:back(), nil) ensure_equals("front empty", deque:front(), nil) end) -------------------------------------------------------------------------------- test "deque-empty-push_back-nil-fails" (function() local deque = make_deque() ensure_fails_with_substring( "push_back nil", function() deque:push_back(nil) end, "deque: can't push nil" ) end) test "deque-empty-pop_back-nil-fails" (function() local deque = make_deque() ensure_fails_with_substring( "push_back nil", function() deque:push_back(nil) end, "deque: can't push nil" ) end) test "deque-empty-pre-set-back" (function() -- A semi-official side effect. local deque = make_deque({ [0] = "EMPTY" }) ensure_equals("empty size", deque:size(), 0) ensure_equals("empty back", deque:back(), nil) ensure_equals("empty pop_back", deque:pop_back(), nil) deque:push_back(42) ensure_equals("non-empty size", deque:size(), 1) ensure_equals("non-empty back", deque:size(), 1) ensure_equals("pop_back", deque:pop_back(), 42) ensure_equals("empty size again", deque:size(), 0) ensure_equals("empty back again", deque:back(), nil) ensure_equals("zero is still there", deque[0], "EMPTY") end) test "deque-on-metatable-fails" (function() local data = setmetatable({ }, { }) ensure_fails_with_substring( "push_back nil", function() make_deque(data) end, "can't create deque on data with metatable" ) end) -------------------------------------------------------------------------------- test "deque-random" (function() local NUM_ITER = 1e4 local MAX_NUM_OPERATIONS = 1e2 local MAX_INITIAL_SIZE = 1e3 local value_generators = make_value_generators(tset({ "userdata" })) local random_value = function() return value_generators[math.random(#value_generators)]() end -- Not using numeric keys in hash part to avoid confusing #t local key_generators = make_value_generators( tset({ "userdata", "no-numbers" }) ) local random_key = function() return key_generators[math.random(#key_generators)]() end local check_once = function() local initial_data = nil if math.random() > 0.5 then -- print("using empty initial data") else -- print("using non-empty initial data") initial_data = { } for i = 1, math.random(MAX_INITIAL_SIZE) do if math.random() > 0.25 then -- Array part initial_data[#initial_data + 1] = random_value() else -- Hash part initial_data[random_key()] = random_value() end end end local expected = { } for k, v in pairs(initial_data or empty_table) do -- Note can't use tclone(), need shallow copy. expected[k] = v end local deque = make_deque(initial_data) local check_ends = function(deque, expected) local expected_size = #expected local expected_back = expected[expected_size] if expected_size == 0 then expected_back = nil end local expected_front = expected[1] ensure_equals("size", deque:size(), expected_size) ensure_equals("back", deque:back(), expected_back) ensure_equals("front", deque:front(), expected_front) return expected_size, expected_back, expected_front end local operations = { -- Push back function(deque, expected) local size, back, front = check_ends(deque, expected) local value = random_value() deque:push_back(value) expected[#expected + 1] = value check_ends(deque, expected) end; -- Push front function(deque, expected) local size, back, front = check_ends(deque, expected) local value = random_value() deque:push_front(value) table.insert(expected, 1, value) check_ends(deque, expected) end; -- Pop back function(deque, expected) local size, back, front = check_ends(deque, expected) --print("BEFORE POP deque ", tstr(deque)) --print("BEFORE POP expected", tstr(expected)) ensure_equals("sanity check", table.remove(expected), back) ensure_equals("pop_back", deque:pop_back(), back) check_ends(deque, expected) end; -- Pop front function(deque, expected) local size, back, front = check_ends(deque, expected) ensure_equals("sanity check", table.remove(expected, 1), front) ensure_equals("pop_front", deque:pop_front(), front) check_ends(deque, expected) end; } check_ends(deque, expected) for i = 1, math.random(MAX_NUM_OPERATIONS) do operations[math.random(#operations)](deque, expected) end check_ends(deque, expected) end for i = 1, NUM_ITER do if i % 1000 == 0 then print("deque check", i, "of", NUM_ITER) end check_once() end end) -------------------------------------------------------------------------------- assert(test:run())
local localization = { mod_description = { en = "Press \"r\" over inventory items to mark as a favorite.", ru = "Нажатие \"r\" над вещами в инвентаре добавляет их в избранное.", }, help_message_1 = { en = "----------FILTERING AND FAVORITES----------", ru = "----------ФИЛЬТРАЦИЯ И ИЗБРАННОЕ----------", }, help_message_2 = { en = "Hover over an inventory item and press \"r\" to set the item as your favorite! Repeat to undo. Favorites won't show on the salvage tab of the forge!", ru = "Наведите курсор на вещь в инвентаре и нажмите \"r\", чтобы добавить её в избранное. Таким же образом вещь можно удалить из избранного. Избранные вещи будут скрыты из списка вещей для сплавки.", }, help_message_3 = { en = "Filter by item name, item type or by trait names. Narrow the search with multiple search terms separated with a comma.", ru = "Отфильтровывайте вещи по их названию, типу, или по названию их свойств. Вы можете сузить поиск, введя несколько условий, и разделив их запятой.", }, help_message_4 = { en = "----------------------------------------------------------------------", }, search_textbox_placeholder = { en = "Search ...", ru = "Найти ...", }, checkbox_show_favorites_only = { en = "Show Favorites Only", ru = "Показывать только избранное", }, fav = { en = "FAV", ru = "ИЗБР.", }, } return localization
local AddonName, AddonTable = ... AddonTable.cooking = { -- Ingredients 43011, 43012, 43013, 43501, }
firstSpawn = true SetManualShutdownLoadingScreenNui(true) local weapons = { "weapon_Knife", "weapon_Nightstick", "weapon_Hammer", "weapon_Bat", "weapon_GolfClub", "weapon_Crowbar", "weapon_Bottle", "weapon_SwitchBlade", "weapon_Pistol", "weapon_CombatPistol", "weapon_APPistol", "weapon_Pistol50", "weapon_FlareGun", "weapon_MarksmanPistol", "weapon_Revolver", "weapon_MicroSMG", "weapon_SMG", "weapon_AssaultSMG", "weapon_CombatPDW", "weapon_AssaultRifle", "weapon_CarbineRifle", "weapon_AdvancedRifle", "weapon_CompactRifle", "weapon_MG", "weapon_CombatMG", "weapon_PumpShotgun", "weapon_SawnOffShotgun", "weapon_AssaultShotgun", "weapon_BullpupShotgun", "weapon_DoubleBarrelShotgun", "weapon_StunGun", "weapon_SniperRifle", "weapon_HeavySniper", "weapon_Grenade", "weapon_StickyBomb", "weapon_SmokeGrenade", "weapon_Molotov", "weapon_FireExtinguisher", "weapon_PetrolCan", "weapon_SNSPistol", "weapon_SpecialCarbine", "weapon_HeavyPistol", "weapon_BullpupRifle", "weapon_VintagePistol", "weapon_Dagger", "weapon_Musket", "weapon_MarksmanRifle", "weapon_HeavyShotgun", "weapon_Gusenberg", "weapon_Hatchet", "weapon_KnuckleDuster", "weapon_Machete", "weapon_MachinePistol", "weapon_Flashlight", "weapon_SweeperShotgun", "weapon_BattleAxe", "weapon_MiniSMG", "weapon_PipeBomb", "weapon_PoolCue", "weapon_Wrench", "weapon_Pistol_Mk2", "weapon_AssaultRifle_Mk2", "weapon_CarbineRifle_Mk2", "weapon_CombatMG_Mk2", "weapon_HeavySniper_Mk2", "weapon_SMG_Mk2", } LoadedPlayerData = false playtime = {} playtime.minute = 0 playtime.hour = 0 playtime.second = 0 zombiekillsthislife = 0 playerkillsthislife = 0 zombiekills = 0 playerkills = 0 locker_money = 0 RegisterNetEvent("requestDaily") AddEventHandler("requestDaily", function(a) Quests[97].finishrequirements = a[1].finishrequirements Quests[97].finishloot = a[1].finishloot Quests[98].finishrequirements = a[2].finishrequirements Quests[98].finishloot = a[2].finishloot Quests[99].finishrequirements = a[3].finishrequirements Quests[99].finishloot = a[3].finishloot GenerateQuestDescriptions() writeLog("\nrequested daily",1) end) -- reqeest daily info Citizen.CreateThread( function() SwitchOutPlayer(PlayerPedId(), 0, 1) RegisterNetEvent('loadPlayerIn') AddEventHandler('loadPlayerIn', function(data) PlayerUniqueId = data.ids TriggerServerEvent("requestDaily") -- prepare our variables humanity = tonumber(data.humanity) local inventory = data.inv local hunger = data.hunger LocalPlayer.state.thirst = data.thirst LocalPlayer.state.hunger = data.hunger local thirst = data.thirst local isInfected = data.isInfected local x,y,z = tonumber(data.x), tonumber(data.y), tonumber(data.z) currentQuest = json.decode(data.currentQuest) finishedQuests = json.decode(data.finishedQuests) -- reset daily wheelspins = data.wheelspins local _,_,day = GetUtcTime() local lastLoginDay = GetResourceKvpInt("last_login_day") if not lastLoginDay or not type(lastLoginDay) == "number" then SetResourceKvpInt("last_login_day",day) elseif lastLoginDay == (day-1) then wheelspins=wheelspins+1 TriggerEvent("showNotification", "Daily Login Reward! Get your Free Wheelspin in the Hub!") end SetResourceKvpInt("last_login_day",day) if lastLoginDay ~= day and currentQuest.id and currentQuest.id >= 97 then AbortQuest(currentQuest.id) end for i,quest in pairs(finishedQuests) do if (quest == 97 or quest == 98 or quest == 99) and GetResourceKvpInt("quest_day") ~= day then table.remove(finishedQuests,i) end end -- set money values consumableItems.count[17] = tonumber(data.money) locker_money = tonumber(data.locker_money) writeLog("\nRecieving Stats...",1) local currentPlayerModel = config.skins.neutral customSkin = data.customskin if not customSkin or customSkin == "" then if humanity > 800 then -- hero skin currentPlayerModel = config.skins.hero elseif humanity < 800 and humanity > 200 then -- neutral skin currentPlayerModel = config.skins.neutral elseif humanity < 200 then -- bandit skin currentPlayerModel = config.skins.bandit end else currentPlayerModel = customSkin end if currentPlayerModel then if not HasModelLoaded(currentPlayerModel) then RequestModel(currentPlayerModel) end while not HasModelLoaded(currentPlayerModel) do Wait(1) end SetPlayerModel(PlayerId(), currentPlayerModel) SetPedRandomComponentVariation(PlayerPedId(), true) end for i,data in ipairs(mysplit(data.playtime, ":")) do if i == 1 then playtime.hour = tonumber(data) elseif i == 2 then playtime.minute = tonumber(data) end end RequestCollisionAtCoord(x+.0,y+.0,z+.0) local currentzcoord = z local L = "wtf" repeat -- do a basic collision request and then request cols until we got our ground z, otherwise it will be 0 Wait(1) RequestCollisionAtCoord(x, y, currentzcoord) foundzcoord,z = GetGroundZFor_3dCoord(x, y, z+9999.0, 0) if foundzcoord then writeLog("\nfound z coord! "..z, 1) end if currentzcoord < -100 then -- if we go too low, go back up foundzcoord = true writeLog("\ndidn't find zcoord :(", 1) z = 500.0 -- force a high up spawn end currentzcoord = currentzcoord-5.0 until foundzcoord GiveWeaponToPed(PlayerPedId(), 0xFBAB5776,1, false, true) -- force player to have a parachute local playerPed = PlayerPedId() SetEntityCoords(playerPed,x+.0,y+.0,z+1.5,1,0,0,1) ShutdownLoadingScreenNui() writeLog("\nshutting down loadscreen", 1) local wt = json.decode(inventory) if wt[1] and not wt[1].id then for i,w in ipairs(wt) do consumableItems.count[i] = w.count if consumableItems[i].requiredbatteries then consumableItems[i].charge = (w.charge or 100) end if consumableItems[i].isWeapon and w.count ~= 0 and w.count ~= 1 then GiveWeaponToPed(PlayerPedId(), consumableItems[i].hash, w.count, false, false) if w.attachments then for _,attachment in pairs(w.attachments) do if DoesWeaponTakeWeaponComponent(consumableItems[i].hash, GetHashKey(attachment)) then GiveWeaponComponentToPed(PlayerPedId(), consumableItems[i].hash, GetHashKey(attachment)) end end end end end else for i,w in ipairs(wt) do consumableItems.count[w.id] = w.count if consumableItems[w.id].requiredbatteries then consumableItems[w.id].charge = (w.charge or 100) end if consumableItems[w.id].isWeapon and w.count ~= 0 and w.count ~= 1 then GiveWeaponToPed(PlayerPedId(), consumableItems[w.id].hash, w.count, false, false) if w.attachments then for _,attachment in pairs(w.attachments) do if DoesWeaponTakeWeaponComponent(consumableItems[w.id].hash, GetHashKey(attachment)) then GiveWeaponComponentToPed(PlayerPedId(), consumableItems[w.id].hash, GetHashKey(attachment)) end end end end end end if not DoesPlayerHaveCBRadio() then -- make sure player has at least the basic CB consumableItems.count[92] = 1 end humanity = humanity+0.001 playerkills = data.playerkills zombiekills = data.zombiekills playerkillsthislife = data.playerkillsthislife zombiekillsthislife = data.zombiekillsthislife SetEntityHealth(PlayerPedId(), data.health) infected = tobool(data.infected) Wait(500) N_0xd8295af639fd9cb8(PlayerPedId()) Wait(5000) LoadedPlayerData = true writeLog("\nDone, we should spawn soon!", 1) end) end) Citizen.CreateThread(function() AddEventHandler("playerSpawned", function() if firstSpawn then TriggerServerEvent("spawnPlayer", GetPlayerServerId(PlayerId())) writeLog("\nRequesting Spawn!", 1) writeLog("\nSent!", 1) firstSpawn = false end Wait(500) SetPedRandomComponentVariation(PlayerPedId(), true) SetNightvision(false) SetSeethrough(false) end) RegisterNetEvent('Z:killedPlayer') AddEventHandler("Z:killedPlayer", function(phumanity,weapon) local playerPed = PlayerPedId() playerkills = playerkills+1 playerkillsthislife = playerkillsthislife+1 if phumanity <= 300 and phumanity >= 200 then humanity = humanity+20 elseif phumanity < 200 and phumanity >= 100 then humanity = humanity+30 elseif phumanity < 100 and phumanity >= 0 then humanity = humanity+45 elseif phumanity < 0 then humanity = humanity+50 else humanity = humanity-50 end if currentQuest.active then if phumanity <= 300 then if Quests[currentQuest.id].finishrequirements.withweapon then if weapon == Quests[currentQuest.id].finishrequirements.withweapon then currentQuest.progress.banditkills = currentQuest.progress.banditkills+1 end else currentQuest.progress.banditkills = currentQuest.progress.banditkills+1 end elseif phumanity >= 700 then if Quests[currentQuest.id].finishrequirements.withweapon then if weapon == Quests[currentQuest.id].finishrequirements.withweapon then currentQuest.progress.herokills = currentQuest.progress.herokills+1 end else currentQuest.progress.herokills = currentQuest.progress.herokills+1 end end end end) end) RegisterNetEvent("c_killedZombie") AddEventHandler("c_killedZombie", function(weapon) if LoadedPlayerData then consumableItems.count[17] = consumableItems.count[17]+1 TriggerServerEvent("AddLegitimateMoney", 1) zombiekillsthislife = zombiekillsthislife+1 zombiekills = zombiekills+1 if currentQuest.active then if Quests[currentQuest.id].finishrequirements.withweapon then if weapon == Quests[currentQuest.id].finishrequirements.withweapon then currentQuest.progress.zombiekills = currentQuest.progress.zombiekills+1 end else currentQuest.progress.zombiekills = currentQuest.progress.zombiekills+1 end end end end) Citizen.CreateThread(function() function initiateSave(disallowTimer) if not LoadedPlayerData then writeLog("\nPlayer Data not Ready, Cancelling Save...", 1) return end local playerPed = PlayerPedId() local posX,posY,posZ = table.unpack(GetEntityCoords(playerPed,true)) local hunger = LocalPlayer.state.hunger local thirst = LocalPlayer.state.thirst local playerkills = playerkills local zombiekills = zombiekills local playerkillsthislife = playerkillsthislife local zombiekillsthislife = zombiekillsthislife local wheelspins = wheelspins local money = consumableItems.count[17] if money > 500000000 then money = 0 -- naughty cheater protection end if locker_money > 10000 then locker_money = 0 end local PedItems = {} for i,theItem in ipairs(consumableItems) do local attachments = {} local count = consumableItems.count[i] if i ~= 17 and count > 1000 and not consumableItems[i].isWeapon then TriggerServerEvent("AntiCheese:CustomFlag", "Item Cheating", "had "..consumableItems.count[i].." "..(consumableItems[i].multipleCase or consumableItems[i].name)..".") count = 0 --naughty cheater protection consumableItems[i].count = 0 end if consumableItems[i].isWeapon then if HasPedGotWeapon(PlayerPedId(), consumableItems[i].hash, false) then if consumableItems[i].hasammo == false then consumableItems.count[i] = 1 count = 1 else consumableItems.count[i] = GetAmmoInPedWeapon(PlayerPedId(), consumableItems[i].hash) count = GetAmmoInPedWeapon(PlayerPedId(), consumableItems[i].hash) end for _,attachment in ipairs(weaponComponents) do if DoesWeaponTakeWeaponComponent(consumableItems[i].hash, GetHashKey(attachment.hash)) and HasPedGotWeaponComponent(PlayerPedId(), consumableItems[i].hash, GetHashKey(attachment.hash)) then table.insert(attachments, attachment.hash) end end else consumableItems.count[i] = 0 count = 0 end end if #attachments == 0 then attachments = nil end local charge = consumableItems[i].charge if consumableItems.count[i] > 0 then table.insert(PedItems, {id = i, count = count, attachments = attachments, charge = charge}) end end local PedItems = json.encode(PedItems) local quest = {} local finquests = json.encode(finishedQuests) if currentQuest.active then quest = json.encode(currentQuest) else quest = json.encode({}) end local data = { posX = posX, posY = posY, posZ = posZ, hunger = hunger, thirst = thirst, inv = PedItems, health = GetEntityHealth(PlayerPedId()), playerkillsthislife = playerkillsthislife, zombiekillsthislife = zombiekillsthislife, playerkills = playerkills, zombiekills = zombiekills, humanity = humanity, money = money, infected = infected, playtime = playtime, currentQuest = quest, finishedQuests = finquests, locker_money = locker_money, wheelspins = wheelspins } TriggerServerEvent("SavePlayerData",data) writeLog("\nSaving PlayerData!", 1) if disallowTimer ~= true then SetTimeout(60000, initiateSave) end end SetTimeout(60000, initiateSave) end) -- playtime calculation Citizen.CreateThread(function() while true do Citizen.Wait(1000) if playtime.second then playtime.second = playtime.second+1 if playtime.second >= 60 then playtime.second = 0 playtime.minute = playtime.minute+1 end if playtime.minute >= 60 then playtime.minute = 0 playtime.hour = playtime.hour+1 end end end end) RegisterNetEvent('playerRegistered') AddEventHandler("playerRegistered", function() writeLog("\nplayer registered", 1) TriggerServerEvent("requestDaily") local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(), true)) local currentzcoord = z repeat -- do a basic collision request and then request cols until we got our ground z, otherwise it will be 0 Wait(1) RequestCollisionAtCoord(x, y, currentzcoord) foundzcoord,z = GetGroundZFor_3dCoord(x, y, z+9999.0, 0) if foundzcoord then writeLog("\nfound z coord! "..z, 1) end if currentzcoord < -100 then -- if we go too low, go back up foundzcoord = true writeLog("\ndidn't find zcoord :(", 1) z = 500.0 -- force a high up spawn end currentzcoord = currentzcoord-5.0 until foundzcoord ShutdownLoadingScreenNui() -- shut down loading screen writeLog("\nshutting down loadscreen", 1) SetEntityCoords(PlayerPedId(), x, y, z+1.0, 0, 0, 0, false) -- teleport player to ground playerkillsthislife = 0 zombiekillsthislife = 0 wheelspins = 1 infected = false for i, count in pairs(config.startItems) do consumableItems.count[i] = count end TriggerServerEvent("SetLegitimateMoney", config.startMoney) consumableItems.count[17] = config.startMoney Wait(300) N_0xd8295af639fd9cb8(PlayerPedId()) -- move camera back to player Wait(8000) writeLog("\nplayer registered ", 1) LoadedPlayerData = true end) RegisterNetEvent('SetCorrectedMoney') AddEventHandler("SetCorrectedMoney", function(value) consumableItems.count[17] = value end) Citizen.CreateThread(function() local last = 0 repeat if DoesEntityExist(PlayerPedId()) then FreezeEntityPosition(PlayerPedId(), true) SetEntityProofs(PlayerPedId(), true, true, true, true, true, true, true, true) end HideHUDThisFrame() Wait(0) until LoadedPlayerData FreezeEntityPosition(PlayerPedId(),false) SetEntityProofs(PlayerPedId(), false, false, false, false, false, false, false, false) end)
local K, C = unpack(select(2, ...)) local _G = _G local SetCVar = _G.SetCVar local SetInsertItemsLeftToRight = _G.SetInsertItemsLeftToRight local UnloadBlizzardFrames = CreateFrame("Frame") UnloadBlizzardFrames:RegisterEvent("PLAYER_LOGIN") UnloadBlizzardFrames:RegisterEvent("ADDON_LOADED") UnloadBlizzardFrames:SetScript("OnEvent", function() if InCombatLockdown() then return end local UIHider = K.UIFrameHider if C["Raid"].Enable then -- Hide Default RaidFrame local function HideRaid() if InCombatLockdown() then return end K.HideObject(CompactRaidFrameManager) local compact_raid = CompactRaidFrameManager_GetSetting("IsShown") if compact_raid and compact_raid ~= "0" then CompactRaidFrameManager_SetSetting("IsShown", "0") end end CompactRaidFrameManager:HookScript("OnShow", HideRaid) if CompactRaidFrameManager_UpdateShown then hooksecurefunc("CompactRaidFrameManager_UpdateShown", HideRaid) end CompactRaidFrameContainer:UnregisterAllEvents() -- Hide Raid Interface Options. InterfaceOptionsFrameCategoriesButton10:SetHeight(0.00001) InterfaceOptionsFrameCategoriesButton10:SetAlpha(0) end if (C["Unitframe"].Enable) then K.KillMenuOption(true, "InterfaceOptionsCombatPanelTargetOfTarget") if (InterfaceOptionsUnitFramePanelPartyBackground) then InterfaceOptionsUnitFramePanelPartyBackground:Hide() InterfaceOptionsUnitFramePanelPartyBackground:SetAlpha(0) end if (PartyMemberBackground) then PartyMemberBackground:SetParent(UIHider) PartyMemberBackground:Hide() PartyMemberBackground:SetAlpha(0) end end if C["General"].AutoScale then Advanced_UseUIScale:Kill() Advanced_UIScaleSlider:Kill() end if (C["ActionBar"].Cooldowns) then SetCVar("countdownForCooldowns", 0) K.KillMenuOption(true, "InterfaceOptionsActionBarsPanelCountdownCooldowns") end if (C["ActionBar"].Enable) then InterfaceOptionsActionBarsPanelAlwaysShowActionBars:Kill() InterfaceOptionsActionBarsPanelBottomLeft:Kill() InterfaceOptionsActionBarsPanelBottomRight:Kill() InterfaceOptionsActionBarsPanelRight:Kill() InterfaceOptionsActionBarsPanelRightTwo:Kill() end if (C["Nameplates"].Enable) then SetCVar("ShowClassColorInNameplate", 1) K.KillMenuOption(true, "InterfaceOptionsNamesPanelUnitNameplatesMakeLarger") K.KillMenuOption(true, "InterfaceOptionsNamesPanelUnitNameplatesAggroFlash") end if (C["Minimap"].Enable) then K.KillMenuOption(true, "InterfaceOptionsDisplayPanelRotateMinimap") end if (C["Inventory"].Enable) then SetInsertItemsLeftToRight(C["Inventory"].ReverseLoot) end if not C["Party"].Enable and not C["Raid"].Enable then C["Raid"].RaidUtility = false end end)
-- Return an abstract syntax tree local M = {} local format = string.format local util = require("lunamark.util") local generic = require("lunamark.writer.generic") local entities = require("lunamark.entities") function M.new(options) local options = options or {} local AST = generic.new(options) function AST.merge(result) local function walk(t) local out = {} for i = 1,#t do local typ = type(t[i]) if typ == "string" and #t[i] > 0 then if type(out[#out]) == "string" then out[#out] = out[#out] .. t[i] else out[#out+1] = t[i] end elseif typ == "table" then out[#out+1] = walk(t[i]) out[#out].tag = t[i].tag -- Copy attributes for key,value in pairs(t[i]) do if type(key)=="string" then out[#out][key] = value end end elseif typ == "function" then out[#out+1] = t[i]() end end return out end return walk(result) -- return result end AST.genericCommand = function(name) return function(s) local node = { tag = name } node[1] = s return node end end AST.strong = AST.genericCommand("strong") AST.paragraph = AST.genericCommand("paragraph") AST.code = AST.genericCommand("code") AST.emphasis = AST.genericCommand("emphasis") AST.blockquote = AST.genericCommand("blockquote") AST.verbatim = AST.genericCommand("verbatim") AST.header = function (s,level) return (AST.genericCommand("sect"..level))(s) end AST.listitem = AST.genericCommand("listitem") AST.bulletlist = function (items) local node = {tag = "bulletlist"} for i=1,#items do node[i] = AST.listitem(items[i]) end return node end AST.link = function(lab, src, tit) return { [1] = lab, tag = "link", href = src } end AST.image = function(lab, src, tit) return { tag = "image", src=src, [1]=lab } end return AST end return M
if not cleaner.unsafe then return end local aux = dofile(cleaner.modpath .. "/misc_functions.lua") local ores_data = aux.get_world_data().ores for _, ore in ipairs(ores_data.remove) do cleaner.register_ore_removal(ore) end core.register_on_mods_loaded(function() for _, ore in ipairs(cleaner.get_remove_ores()) do cleaner.log("action", "unregistering ore: " .. ore) cleaner.remove_ore(ore) end end)
require "src/core/arrays" local stack = {} stack.__index = stack function stack.new() local self = setmetatable({}, stack) self.list = {} return self end function stack.push(self, value) table.insert(self.list, value) end function stack.pop(self) local value = self:top() self.list[#(self.list)] = nil return value end function stack.length(self) return #(self.list) end function stack.top(self) return last(self.list) end function stack.empty(self) return 0 == #(self.list) end function stack.to_array(self) return copy(self.list) end return stack
---@class CS.UnityEngine.Pose : CS.System.ValueType ---@field public position CS.UnityEngine.Vector3 ---@field public rotation CS.UnityEngine.Quaternion ---@field public forward CS.UnityEngine.Vector3 ---@field public right CS.UnityEngine.Vector3 ---@field public up CS.UnityEngine.Vector3 ---@field public identity CS.UnityEngine.Pose ---@type CS.UnityEngine.Pose CS.UnityEngine.Pose = { } ---@return CS.UnityEngine.Pose ---@param position CS.UnityEngine.Vector3 ---@param rotation CS.UnityEngine.Quaternion function CS.UnityEngine.Pose.New(position, rotation) end ---@overload fun(): string ---@return string ---@param optional format string function CS.UnityEngine.Pose:ToString(format) end ---@overload fun(lhs:CS.UnityEngine.Pose): CS.UnityEngine.Pose ---@return CS.UnityEngine.Pose ---@param lhs CS.UnityEngine.Transform function CS.UnityEngine.Pose:GetTransformedBy(lhs) end ---@overload fun(obj:CS.System.Object): boolean ---@return boolean ---@param other CS.UnityEngine.Pose function CS.UnityEngine.Pose:Equals(other) end ---@return number function CS.UnityEngine.Pose:GetHashCode() end ---@return boolean ---@param a CS.UnityEngine.Pose ---@param b CS.UnityEngine.Pose function CS.UnityEngine.Pose.op_Equality(a, b) end ---@return boolean ---@param a CS.UnityEngine.Pose ---@param b CS.UnityEngine.Pose function CS.UnityEngine.Pose.op_Inequality(a, b) end return CS.UnityEngine.Pose
--[[------------------------------------------------------------------ ARMOUR Vignette effects to reflect player's current suit battery level ]]-------------------------------------------------------------------- if CLIENT then -- Parameters local WIDTH, HEIGHT = 163, 41; local VIGNETTE_YELLOW = surface.GetTextureID("vighud/vignette_yellow"); local VIGNETTE_BLUE = surface.GetTextureID("vighud/vignette_blue"); local KEVLAR_ICON = Material("vighud/kevlar.png"); local BATTERY_ICON = Material("vighud/battery.png"); VGNTK.HEV_COLOUR = Color(255, 230, 10, 255); local ARMOUR_COLOUR = Color(0, 200, 255); local ARMOUR_ADD_COLOUR = Color(0, 133, 200); local ARMOUR_DMG_COLOUR = Color(215, 60, 10); local ARMOUR_BACKGROUND_COLOUR = Color(255, 255, 255, 6); local WHITE = Color(255, 255, 255); local SW, SH, SM = 9, 6, 5; local TIME = 4; local ARMOUR_DELAY = 1; local ARMOUR_SPEED = 2; -- Variables local lastap = 0; local apanim = 0; local maanim = 0; local nextap = 0; local new = 0; local aptime = 0; local apt = 0; local dmg = 0; local time = 0; local tick = 0; local armourFlash = false; local wasDead = false; -- Create scaled font surface.CreateFont( "vgntk_label", { font = "Verdana", size = math.Round(14 * VGNTK:GetScale()), weight = 1000, antialias = true }); -- Internal function; animates the armour indicator local function Animate(armour, mode) -- Animate HEV monitor if (mode == 3 and armour > 0) then new = Lerp(FrameTime() * 2.4, new, 0); end -- Register as dead if (not LocalPlayer():Alive()) then wasDead = true; end -- Detect damage if lastap ~= armour then if lastap > armour then if armour > 0 and armour <= 20 and VGNTK:IsArmourVignetteEnabled() then apanim = 1; -- Activate effect elseif armour <= 0 and not wasDead and VGNTK:IsArmourDepleteFlashEnabled() then apt = 1; new = 1; maanim = 1; end -- Reset variables armourFlash = false; else if ((not armourFlash and armour >= 100) or armour >= 200) and VGNTK:IsArmourFullFlashEnabled() then maanim = 1; armourFlash = true; end -- Screen blink effect end -- trigger damage animation if (dmg == armour) then dmg = lastap; end -- update armour variant indicator time = CurTime() + ARMOUR_DELAY; aptime = CurTime() + TIME; lastap = armour; wasDead = false; end -- Fade in/out if (aptime > CurTime() or armour <= 20 or VGNTK:IsArmourAlwaysShown()) and armour > 0 then apt = Lerp(FrameTime() * 12, apt, 1); else apt = math.max(Lerp(FrameTime() * 8, apt, -0.02), 0); end -- Cool off apanim = math.max(Lerp(FrameTime(), apanim, -0.02), 0); -- Damage maanim = math.max(Lerp(FrameTime() * 3, maanim, -0.02), 0); -- 100%/0% effect -- Damage animation if (mode >= 1 and time < CurTime() and tick < CurTime()) then if (dmg > armour) then dmg = math.max(dmg - ARMOUR_SPEED, armour); elseif (dmg < armour) then dmg = math.min(dmg + ARMOUR_SPEED, armour); end tick = CurTime() + 0.01; end -- Display armour amount when pressed the key if (input.IsKeyDown(VGNTK:GetShowKey())) then aptime = CurTime() + TIME; end end -- Internal function; draws a aux power styled bar local function DrawBar(x, y, w, h, m, amount, value, col, a) -- Background for i=0, amount do draw.RoundedBox(0, x + math.Round((w + m) * VGNTK:GetScale()) * i, y, math.Round(w * VGNTK:GetScale()), math.Round(h * VGNTK:GetScale()), Color(col.r * 0.8, col.g * 0.8, col.b * 0.8, col.a * 0.4 * a)); end -- Foreground if (value <= 0) then return; end for i=0, math.Round(value * amount) do draw.RoundedBox(0, x + math.Round((w + m) * VGNTK:GetScale()) * i, y, math.Round(w * VGNTK:GetScale()), math.Round(h * VGNTK:GetScale()), Color(col.r, col.g, col.b, col.a * a)); end end -- Internal function; draws the HEV suit monitor local function DrawHEVMonitor(armour) draw.RoundedBox(6, 25 * VGNTK:GetScale(), ScrH() - (HEIGHT + 20) * VGNTK:GetScale(), WIDTH * VGNTK:GetScale(), HEIGHT * VGNTK:GetScale(), Color(VGNTK.HEV_COLOUR.r * new, VGNTK.HEV_COLOUR.g * new,VGNTK.HEV_COLOUR.b * new, (70 + 100 * new) * apt)); draw.SimpleText("SUIT POWER", "vgntk_label", 38 * VGNTK:GetScale(), ScrH() - (HEIGHT + 15) * VGNTK:GetScale(), Color(VGNTK.HEV_COLOUR.r, VGNTK.HEV_COLOUR.g, VGNTK.HEV_COLOUR.b, VGNTK.HEV_COLOUR.a * apt)); DrawBar(38 * VGNTK:GetScale(), ScrH() - (HEIGHT - 5) * VGNTK:GetScale(), SW, SH, SM, 9, armour * 0.01, VGNTK.HEV_COLOUR, apt); end -- Internal function; draws an icon representing the current armour level local function DrawArmourIcon(armour, mode, over100, damage) local w, h = 64 * VGNTK:GetScale(), 64 * VGNTK:GetScale(); local x, y = (ScrW() * 0.2) - (32 * VGNTK:GetScale()), ScrH() - (20 * VGNTK:GetScale()) - h; if (VGNTK:IsArmourOnCorner()) then x = math.ceil(20 * VGNTK:GetScale()); end local alpha = 1; if (over100) then alpha = 0.5; end local a, d = armour * 0.01, damage * 0.01; local colour = ARMOUR_DMG_COLOUR; local aColour = VGNTK:GetArmourColour(); local bright = VGNTK:GetArmourBackgroundBrightness(); local bColour = Color(255 * bright, 255 * bright, 255 * bright, aColour.a * VGNTK:GetArmourBackgroundAlpha() * apt); if (armour > damage) then d = armour * 0.01; a = damage * 0.01; colour = ARMOUR_ADD_COLOUR; end -- detect if damage was taken aColour.a = aColour.a * apt * alpha; colour.a = aColour.a * 0.5 * alpha; render.PushFilterMag( TEXFILTER.ANISOTROPIC ); render.PushFilterMin( TEXFILTER.ANISOTROPIC ); if (mode == 1) then surface.SetMaterial(KEVLAR_ICON); else surface.SetMaterial(BATTERY_ICON); end -- Draw background render.SetScissorRect(x, y, x + w, y + h * (1 - a), true); surface.SetDrawColor(bColour); surface.DrawTexturedRect(x, y, w, h); -- Draw difference render.SetScissorRect(x, y + (h * math.abs(1 - d)), x + w, y + (h * (1 - a)), true); surface.SetDrawColor(colour); surface.DrawTexturedRect(x, y, w, h); -- Draw current level render.SetScissorRect(x, y + (h * (1 - a)), x + w, y + h, true); surface.SetDrawColor(aColour); surface.DrawTexturedRect(x, y, w, h); render.SetScissorRect(0, 0, 0, 0, false); render.PopFilterMag(); render.PopFilterMin(); end -- Internal function; draws the vignette and blinking effects local function DrawArmour(mode) local texture = VIGNETTE_BLUE; local colour = ARMOUR_COLOUR; if (mode == 3) then texture = VIGNETTE_YELLOW; colour = VGNTK.HEV_COLOUR; end -- Draw vignette surface.SetDrawColor(WHITE); surface.SetTexture(texture) surface.DrawTexturedRect(0 - (ScrW() * (1-apanim)), 0 - (ScrH() * (1-apanim)), ScrW() * (1 + 2 * (1-apanim)), ScrH() * (1 + 2 * (1-apanim))); -- Draw full screen flash draw.RoundedBox(0, 0, 0, ScrW(), ScrH(), Color(colour.r, colour.g, colour.b, 30 * maanim)); end --[[------------------------------------------------------------------ Draws the armour overlay @param {boolean} HEV mode ]]-------------------------------------------------------------------- function VGNTK:DrawArmourOverlay(mode) if (not VGNTK:ShouldDrawHealth()) then return end local armour = LocalPlayer():Armor(); Animate(armour, mode); DrawArmour(mode); if (mode >= 1 and mode < 3) then DrawArmourIcon(math.min(armour, 100), mode, armour > 100, math.min(dmg, 100)); if (armour > 100) then DrawArmourIcon(math.min(armour - 100, 100), mode, nil, dmg - 100); end elseif (mode >= 3) then DrawHEVMonitor(armour); end end end
---@meta ---#if VERSION >=5.4 then ---#DES 'require>5.4' ---@param modname string ---@return any ---@return any loaderdata function require(modname) end ---#else ---#DES 'require<5.3' ---@param modname string ---@return any function require(modname) end ---#end ---#DES 'package' ---@class packagelib ---#DES 'package.config' ---@field config string ---#DES 'package.cpath' ---@field cpath string ---#DES 'package.loaded' ---@field loaded table ---#DES 'package.path' ---@field path string ---#DES 'package.preload' ---@field preload table package = {} ---@version <5.1 ---#DES 'package.loaders' package.loaders = {} ---#DES 'package.loadlib' ---@param libname string ---@param funcname string ---@return any function package.loadlib(libname, funcname) end ---#DES 'package.searchers' ---@version >5.2 package.searchers = {} ---#DES 'package.searchpath' ---@version >5.2,JIT ---@param name string ---@param path string ---@param sep? string ---@param rep? string ---@return string? filename ---@return string? errmsg function package.searchpath(name, path, sep, rep) end ---#DES 'package.seeall' ---@version <5.1 ---@param module table function package.seeall(module) end return package
object_tangible_loot_creature_loot_generic_liver_s02 = object_tangible_loot_creature_loot_generic_shared_liver_s02:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_generic_liver_s02, "object/tangible/loot/creature/loot/generic/liver_s02.iff")
local Cutscene = {} local self = Cutscene function Cutscene.start(cutscene) if self.current_coroutine and coroutine.status(self.current_coroutine) ~= "dead" then error("Attempt to start a cutscene while already in a cutscene . dumbass ,,") self.current_coroutine = nil end local func = nil if type(cutscene) == "string" then func = Mod.info.script_chunks["scripts/world/cutscenes/" .. cutscene] if not func then error("Attempt to load cutscene \"" .. cutscene .. "\", but it wasn't found. Dumbass") end elseif type(cutscene) == "function" then func = cutscene else error("Attempt to start cutscene with argument of type " .. type(cutscene)) end self.delay_timer = 0 if self.textbox then self.textbox:remove() end self.textbox = nil self.textbox_actor = nil if self.choicebox then self.choicebox:remove() end self.choicebox = nil self.move_targets = {} self.camera_target = nil self.camera_start = nil self.camera_move_time = 0 self.camera_move_timer = 0 self.camera_move_after = nil self.current_coroutine = coroutine.create(func) Game.lock_input = true Game.cutscene_active = true --[[Overworld.cutscene_active = true Overworld.lock_player_input = true Overworld.can_open_menu = false]] self.choice = 0 self.resume() end function Cutscene.isActive() return self.current_coroutine ~= nil end function Cutscene.wait(seconds) if self.current_coroutine then self.delay_timer = seconds coroutine.yield() end end function Cutscene.pause() if self.current_coroutine then coroutine.yield() end end function Cutscene.resume() if self.current_coroutine then local ok, msg = coroutine.resume(self.current_coroutine) if not ok then error(msg) end end end -- Main update function of the module function Cutscene.update(dt) if self.current_coroutine then local done_moving = {} for chara,target in pairs(self.move_targets) do local ex, ey = chara:getExactPosition() if ex == target[2] and ey == target[3] then table.insert(done_moving, chara) if target[5] then chara:setFacing(target[5]) end end local tx = Utils.approach(ex, target[2], target[4] * DTMULT) local ty = Utils.approach(ey, target[3], target[4] * DTMULT) if target[1] then chara:moveTo(tx, ty) else chara:setExactPosition(tx, ty) end end for _,v in ipairs(done_moving) do self.move_targets[v] = nil end if self.camera_target then self.camera_move_timer = Utils.approach(self.camera_move_timer, self.camera_move_time, dt) Game.world.camera.x = Utils.lerp(self.camera_start[1], self.camera_target[1], self.camera_move_timer / self.camera_move_time) Game.world.camera.y = Utils.lerp(self.camera_start[2], self.camera_target[2], self.camera_move_timer / self.camera_move_time) Game.world:updateCamera() if self.camera_move_timer == self.camera_move_time then self.camera_target = nil if self.camera_move_after then self.camera_move_after() end end end if coroutine.status(self.current_coroutine) == "dead" and not self.camera_target then -- TODO: ALLOW THE PLAYER TO OPEN THE MENU OR SOMETHING Game.lock_input = false Game.cutscene_active = false if self.textbox then self.textbox:remove() self.textbox = nil end if self.choicebox then self.choicebox:remove() self.choicebox = nil end self.current_coroutine = nil return end if coroutine.status(self.current_coroutine) == "suspended" then if self.delay_timer > 0 then self.delay_timer = self.delay_timer - dt if self.delay_timer <= 0 then self.resume() end end end end end function Cutscene.getCharacter(id, index) local i = 0 for _,chara in ipairs(Game.stage:getObjects(Character)) do if chara.actor.id == id then i = i + 1 if not index or index == i then return chara end end end end function Cutscene.detachFollowers() for _,follower in ipairs(Game.followers) do follower.following = false end end function Cutscene.attachFollowers(return_speed, facing) for _,follower in ipairs(Game.followers) do follower.following = true return_speed = return_speed or 6 if return_speed ~= true and return_speed > 0 then local tx, ty = follower:getTargetPosition() self.walkTo(follower, tx, ty, return_speed, facing) end end end function Cutscene.alignFollowers(facing, x, y) Game.world.player:alignFollowers(facing, x, y) end function Cutscene.keepFollowerPositions() Game.world.player:keepFollowerPositions() end function Cutscene.resetSprites() Game.world.player:resetSprite() for _,follower in ipairs(Game.world.followers) do follower:resetSprite() end end function Cutscene.look(chara, dir) if type(chara) == "string" then chara = self.getCharacter(chara) end chara:setFacing(dir) end function Cutscene.walkTo(chara, x, y, speed, facing) if type(chara) == "string" then chara = self.getCharacter(chara) end local ex, ey = chara:getExactPosition() if ex ~= x or ey ~= y then self.move_targets[chara] = {true, x, y, speed or 4, facing} end end function Cutscene.setSprite(chara, sprite, speed) if type(chara) == "string" then chara = self.getCharacter(chara) end chara:setSprite(sprite) if speed then chara:play(speed, true) end end function Cutscene.setAnimation(chara, anim) if type(chara) == "string" then chara = self.getCharacter(chara) end chara:setAnimation(anim) end function Cutscene.spin(chara, speed) if type(chara) == "string" then chara = self.getCharacter(chara) end chara:spin(speed) end function Cutscene.slideTo(chara, x, y, speed) if type(chara) == "string" then chara = self.getCharacter(chara) end local ex, ey = chara:getExactPosition() if ex ~= x or ey ~= y then self.move_targets[chara] = {false, x, y, speed or 4} end end function Cutscene.shakeCharacter(chara, x, y) if type(chara) == "string" then chara = self.getCharacter(chara) end chara:shake(x, y) end function Cutscene.shakeCamera(x, y) Game.world.shake_x = x or 0 Game.world.shake_y = y or x or 0 end function Cutscene.detachCamera() Game.world.camera_attached = false end function Cutscene.attachCamera(time) local tx, ty = Game.world:getCameraTarget() self.panTo(tx, ty, time or 0.8, function() Game.world.camera_attached = true end) end function Cutscene.setSpeaker(actor) if isClass(actor) and actor:includes(Character) then actor = actor.actor end self.textbox_actor = actor end function Cutscene.panTo(...) local args = {...} local time = 1 local after = nil if type(args[1]) == "number" then self.camera_target = {args[1], args[2]} time = args[3] or time after = args[4] elseif type(args[1]) == "string" then local marker = Game.world.markers[args[1]] self.camera_target = {marker.center_x, marker.center_y} time = args[2] or time after = args[3] elseif isClass(args[1]) and args[1]:includes(Character) then local chara = args[1] self.camera_target = {chara:getRelativePos(chara.width/2, chara.height/2)} time = args[2] or time after = args[3] else self.camera_target = {Game.world:getCameraTarget()} end self.camera_start = {Game.world.camera.x, Game.world.camera.y} self.camera_move_time = time or 0.8 self.camera_move_timer = 0 self.camera_move_after = after end function Cutscene.text(text, portrait, actor, options) if type(actor) == "table" then options = actor actor = nil end if self.textbox then self.textbox:remove() end if self.choicebox then self.choicebox:remove() self.choicebox = nil end self.textbox = Textbox(56, 344, 529, 103) self.textbox.layer = 1 Game.stage:addChild(self.textbox) actor = actor or self.textbox_actor if actor then self.textbox:setActor(actor) end options = options or {} if options["top"] then local bx, by = self.textbox:getBorder() self.textbox.y = by end self.textbox.active = true self.textbox.visible = true self.textbox:setFace(portrait, options["x"], options["y"]) self.textbox:setText(text) self.auto_advance = options["auto"] if self.current_coroutine then coroutine.yield() end end function Cutscene.choicer(choices, options) if self.textbox then self.textbox:remove() self.textbox = nil end if self.choicebox then self.choicebox:remove() end self.choicebox = Choicebox(56, 344, 529, 103) self.choicebox.layer = 1 Game.stage:addChild(self.choicebox) for _,choice in ipairs(choices) do self.choicebox:addChoice(choice) end options = options or {} if options["top"] then local bx, by = self.choicebox:getBorder() self.choicebox.y = by end self.choicebox.active = true self.choicebox.visible = true if self.current_coroutine then coroutine.yield() end end --[[ function Cutscenes:SpawnTextbox(text,portrait,options) self.delay_from_textbox = true local top = true if options and options["top"] ~= nil then top = options["top"] else top = Overworld.player.y - Misc.cameraY < 230 end OverworldTextbox.SetText(text,top,portrait,options) coroutine.yield() end]] return Cutscene
project( "Utils" ) currentSourceDir = path.join( sourceDir, "Core", "Utils" ) currentBinaryDir = path.join( binaryDir, "Core", "Utils" ) kind( "StaticLib" ) targetdir( path.join( outputDir, "%{cfg.architecture}", "%{cfg.buildcfg}", staticLibDir ) ) location( currentBinaryDir ) files{ "**.hpp", "**.inl", "**.cpp" } vpaths{ ["Header Files"] = "**.hpp" } vpaths{ ["Header Files"] = "**.inl" } vpaths{ ["Source Files"] = "**.cpp" }
package.path = '../lib/?.lua;' .. package.path require 'busted.runner'() require '../lib/utils' describe("Reverse Table", function() it("should reverse a table", function() foo = {1, 2, 3, 4, 5} rev = {5, 4, 3, 2, 1} utils.reverse_table(foo) assert.are_same(foo, rev) end) end) describe("Find next power of two from string", function() it("Should be true for these common cases", function() c1 = "500 1 1" c2 = "1023 1 1" c3 = "2040 1 1" c4 = "4091 1 1" c5 = "8183 1 1" c6 = "400 1 512" c7 = "1000 1 1024" c8 = "2001 1 2048" c9 = "4003 1 4096" c10 = "8100 1 8192" assert.are.same(utils.get_max_fft_size(c1), "512") assert.are.same(utils.get_max_fft_size(c2), "1024") assert.are.same(utils.get_max_fft_size(c3), "2048") assert.are.same(utils.get_max_fft_size(c4), "4096") assert.are.same(utils.get_max_fft_size(c5), "8192") assert.are.same(utils.get_max_fft_size(c6), "512") assert.are.same(utils.get_max_fft_size(c7), "1024") assert.are.same(utils.get_max_fft_size(c8), "2048") assert.are.same(utils.get_max_fft_size(c9), "4096") assert.are.same(utils.get_max_fft_size(c10), "8192") end) end) describe("Find next power of 2", function() it("Return a power of two for these", function() c1 = 3 c2 = 5 c3 = 7 c4 = 9 c5 = 12 c6 = 40000 c7 = 19 c8 = 500 c9 = 1000 assert.are_same(utils.next_pow_str(c1), '4') assert.are_same(utils.next_pow_str(c2), '8') assert.are_same(utils.next_pow_str(c3), '8') assert.are_same(utils.next_pow_str(c4), '16') assert.are_same(utils.next_pow_str(c5), '16') assert.are_same(utils.next_pow_str(c6), '65536') assert.are_same(utils.next_pow_str(c7), '32') assert.are_same(utils.next_pow_str(c8), '512') assert.are_same(utils.next_pow_str(c9), '1024') end) end) describe("Samples to seconds", function() it("Should return the proper conversion for the sample rate", function() c1 = 44100 c2 = 22050 c3 = 4410 c4 = 17640 assert.are_same(utils.sampstos(c1, 44100), 1) assert.are_same(utils.sampstos(c1, 48000), 0.91875) assert.are_same(utils.sampstos(c2, 44100), 0.5) assert.are_same(utils.sampstos(c3, 44100), 0.1) assert.are_same(utils.sampstos(c4, 44100), 0.4) end) end) describe("Seconds to samples", function() it("Should return the proper conversion for the sample rate", function() c1 = 1 c2 = 1.5 c3 = 2 c4 = 3 assert.are_same(utils.stosamps(c1, 44100), 44100) assert.are_same(utils.stosamps(c1, 48000), 48000) assert.are_same(utils.stosamps(c2, 44100), 66150) assert.are_same(utils.stosamps(c3, 44100), 88200) assert.are_same(utils.stosamps(c4, 44100), 132300) end) end) describe("Get the base dir", function() it("Return only the base dir", function() c1 = "/home/james/path/foo.lua" c2 = "/home/james/path/" c3 = "/home/james/path" c4 = "/home/james/path/foo" assert.are_same(utils.dir_parent(c1), "/home/james/path/") assert.are_same(utils.dir_parent(c2), "/home/james/path/") assert.are_same(utils.dir_parent(c3), "/home/james/") assert.are_same(utils.dir_parent(c4), "/home/james/path/") end) end) describe("Get the base name", function() it("Return only the name of the file", function() c1 = "/home/james/path/foo.lua" c2 = "/home/james/path/" c3 = "/home/james/path" c4 = "/home/james/path/foo" assert.are_same(utils.basename(c1), "/home/james/path/foo") assert.are_same(utils.basename(c2), nil) assert.are_same(utils.basename(c3), nil) assert.are_same(utils.basename(c4), nil) end) end) describe("Remove trailing slash", function() it("Removes a trailing slash from a path", function() c1 = "/home/james/path/foo.lua/" c2 = "/home/james/path/" assert.are_same(utils.rm_trailing_slash(c1), "/home/james/path/foo.lua") assert.are_same(utils.rm_trailing_slash(c2), "/home/james/path") end) end) describe("Check comma splitting is predictable", function() it("Split them commas", function() c1 = "param1,param2,param3,param5" test_case = { "param1", "param2", "param3", "param5" } assert.are_same(utils.split_comma(c1), test_case) end) end) describe("Check space splitting is predictable", function() it("Split them spaces", function() c1 = "param1 param2 param3 param5" test_case = { "param1", "param2", "param3", "param5" } assert.are_same(utils.split_space(c1), test_case) end) end) describe("Lacing tables is predictable", function() it("Lace them together", function() c1 = "param1 param2 param3 param5" left = {0.0, 100.0, 300.1} right = {78.0, 299.0} expected = {0.0, 78.0, 100.0, 299.0, 300.1} assert.are_same(utils.lace_tables(left, right), expected) end) end) describe("Remove delimiters", function() it("Should have no delimiters in the string", function() delimited = "foo.bar is the best.worst" expected = "foobaristhebestworst" assert.are_same(utils.rmdelim(delimited), expected) end) end) describe("wrap_quotes a string for CLI", function() it("Should return something that is double quoted", function() c1 = '/home/james/Documents/Max 8/Packages/Worst Path Ever' c2 = "/home/james/Documents/Max 8/Packages/Worst Path Ever" expected = '"/home/james/Documents/Max 8/Packages/Worst Path Ever"' assert.are_same(utils.wrap_quotes(c1), expected) assert.are_same(utils.wrap_quotes(c2), expected) end) end) -- describe("Check line splitting is predictable", function() -- it("Split them commas", function() -- c1 = "param1\rparam2\rparam3\rparam5 " -- c2 = "param1\nparam2\nparam3\nparam5" -- c3 = "param1\rparam2\nparam3\rparam5" -- test_case = { -- [1] = "param1", -- "param2", -- "param3", -- "param5" -- } -- assert.are.equals(utils.split_line(c1), test_case) -- assert.are.equals(utils.split_line(c2), test_case) -- assert.are.equals(utils.split_line(c3), test_case) -- end) -- end)
package("libgpg-error") set_homepage("https://www.gnupg.org/related_software/libgpg-error/") set_description("Libgpg-error is a small library that originally defined common error values for all GnuPG components.") set_license("GPL-2.0") add_urls("https://www.gnupg.org/ftp/gcrypt/libgpg-error/libgpg-error-$(version).tar.bz2") add_versions("1.44", "8e3d2da7a8b9a104dd8e9212ebe8e0daf86aa838cc1314ba6bc4de8f2d8a1ff9") if is_plat("macosx") then add_deps("libintl") end on_install("linux", "macosx", function (package) local configs = {"--disable-doc", "--disable-tests"} table.insert(configs, "--enable-static=" .. (package:config("shared") and "no" or "yes")) table.insert(configs, "--enable-shared=" .. (package:config("shared") and "yes" or "no")) if package:config("pic") ~= false then table.insert(configs, "--with-pic") end import("package.tools.autoconf").install(package, configs) end) on_test(function (package) assert(package:has_cfuncs("gpgrt_strdup", {includes = "gpgrt.h"})) end)
local math = require("math") local Rope = {} Rope.__index = Rope setmetatable(Rope, { __call = function(cls, ...) return cls.new(...) end, }) -- Non-leaf nodes are represented by empty strings in the `string` field. local RopeNode = {} RopeNode.__index = RopeNode setmetatable(RopeNode, { __call = function(cls, ...) return cls.new(...) end, }) function RopeNode.new(string, left, right) local self = setmetatable({}, RopeNode) self.string = string self.weight = #string self.sum_weights = RopeNode.sum_weights self.concat = RopeNode.concat if left then self.left = left self.left.parent = self self.weight = self.weight + self.left:sum_weights() end if right then self.right = right self.right.parent = self end return self end function RopeNode:sum_weights() local sum = #self.string if sum == 0 then if self.left.right then sum = sum + self.left.weight + self.left.right:sum_weights() else sum = sum + self.left.weight end if self.right.right then sum = sum + self.right.weight + self.right.right:sum_weights() else sum = sum + self.right.weight end end return sum end function RopeNode.concat(left, right) return RopeNode.new("", left, right) end function Rope.new(initial) local self = setmetatable({}, Rope) if type(initial) == "string" then self.root = RopeNode.new(initial) else self.root = initial end self.get_node_and_index = Rope.get_node_and_index self.concat = Rope.concat self.append = Rope.append self.split = Rope.split self.insert = Rope.insert self.delete = Rope.delete self.report_until = Rope.report_until self.report = Rope.report return self end function Rope:get_node_and_index(i) local function index_node(node, i) if node.weight <= i then return index_node(node.right, i - node.weight) elseif node.left then return index_node(node.left, i) else return node, i end end local node, i = index_node(self.root, i - 1) return node, i + 1 end function Rope:__len() return self.root:sum_weights() end function Rope:__index(i) local node, i = self:get_node_and_index(i) return node.string:sub(i, i) end function Rope.concat(left, right) return Rope.new(RopeNode.concat(left.root, right.root)) -- TODO: rebalance tree end function Rope:append(s) if s == "" then return end self.root = RopeNode.concat(self.root, RopeNode.new(s)) end function Rope:split(i) local node, i = self:get_node_and_index(i) local detatched_nodes = {} local sub_weight if i ~= #node.string then local left = RopeNode.new(node.string:sub(1, i)) detatched_nodes[#detatched_nodes+1] = RopeNode.new(node.string:sub(i + 1)) sub_weight = detatched_nodes[1].weight node.string = left.string node.weight = left.weight end local last = node node = node.parent while node do if node.left == last then local detatch = node.right detatched_nodes[#detatched_nodes+1] = detatch node.string = last.string node.weight = last.weight node.left = last.left node.right = last.right if node.string == "" then -- non-leaf node --node.weight = node.weight - sub_weight -- TODO: optimize this if possible node.weight = node.left:sum_weights() end end last = node node = node.parent end -- Processes in reverse order because our list of nodes is reversed local function balanced_bst(nodes, start, end_) if start == end_ then return nodes[start] else return RopeNode.concat( balanced_bst(nodes, start, end_ - math.floor((end_ - start) / 2) - 1), balanced_bst(nodes, end_ - math.floor((end_ - start) / 2), end_) ) end end if #detatched_nodes == 0 then return Rope.new("") else return Rope.new(balanced_bst(detatched_nodes, 1, #detatched_nodes)) end -- TODO: rebalance tree end function Rope:insert(i, s) if s == "" then return end if i == 0 then self.root = RopeNode.concat(RopeNode.new(s), self.root) elseif i == #self then self.root = RopeNode.concat(self.root, RopeNode.new(s)) else local t = self:split(i) t = RopeNode.concat(RopeNode.new(s), t.root) self.root = RopeNode.concat(self.root, t) end end function Rope:delete(i, j) if i == 1 then local t = self:split(j) self.root = t.root elseif j == #self then self:split(i - 1) else local t = self:split(j) self:split(i - 1) self.root = RopeNode.concat(self.root, t.root) end end -- `term` is a function that takes two parameters: The current index, and the -- full reported string (it can find the most recent character by just doing -- `s.sub(i, i)`). The returned string excludes the last element (e.g. the one -- that was added on the round that `term` returned true) function Rope:report_until(start, term) local node, i = self:get_node_and_index(start) local current_index = 1 local res = "" local function process_node(node, start) start = start or 1 for i = start, #node.string do res = res .. node.string:sub(i, i) if term(current_index, res) then res = res:sub(1, #res - 1) return true end current_index = current_index + 1 end return false end if process_node(node, i) then return res end local function traverse_in_order(node) if node.string ~= "" then if process_node(node) then return true end else if traverse_in_order(left) then return true end if traverse_in_order(right) then return true end end return false end -- Remarkably similar to the loop in split() -- Maybe extract these out into functions...? local last = node local node = node.parent while node do if node.left == last then if traverse_in_order(node.right) then return res end end last = node node = node.parent end return res end function Rope:report(start, end_) return self:report_until(start, function(i, _) return i == (end_ - start + 2) end) end return { Rope = Rope, RopeNode = RopeNode }
print("twat")
-- Apartment 1: -787.78050000 334.92320000 215.83840000 exports('GetExecApartment1Object', function() return ExecApartment1 end) ExecApartment1 = { currentInteriorId = -1, Style = { Theme = { modern = {interiorId = 227329, ipl = "apa_v_mp_h_01_a"}, moody = {interiorId = 228097, ipl = "apa_v_mp_h_02_a"}, vibrant = {interiorId = 228865, ipl = "apa_v_mp_h_03_a"}, sharp = {interiorId = 229633, ipl = "apa_v_mp_h_04_a"}, monochrome = {interiorId = 230401, ipl = "apa_v_mp_h_05_a"}, seductive = {interiorId = 231169, ipl = "apa_v_mp_h_06_a"}, regal = {interiorId = 231937, ipl = "apa_v_mp_h_07_a"}, aqua = {interiorId = 232705, ipl = "apa_v_mp_h_08_a"} }, Set = function(style, refresh) if (IsTable(style)) then ExecApartment1.Style.Clear() ExecApartment1.currentInteriorId = style.interiorId EnableIpl(style.ipl, true) if (refresh) then RefreshInterior(style.interiorId) end end end, Clear = function() for key, value in pairs(ExecApartment1.Style.Theme) do SetIplPropState(value.interiorId, {"Apart_Hi_Strip_A", "Apart_Hi_Strip_B", "Apart_Hi_Strip_C"}, false) SetIplPropState(value.interiorId, {"Apart_Hi_Booze_A", "Apart_Hi_Booze_B", "Apart_Hi_Booze_C"}, false) SetIplPropState(value.interiorId, {"Apart_Hi_Smokes_A", "Apart_Hi_Smokes_B", "Apart_Hi_Smokes_C"}, false, true) EnableIpl(value.ipl, false) end end }, Strip = { A = "Apart_Hi_Strip_A", B = "Apart_Hi_Strip_B", C = "Apart_Hi_Strip_C", Enable = function (details, state, refresh) SetIplPropState(ExecApartment1.currentInteriorId, details, state, refresh) end }, Booze = { A = "Apart_Hi_Booze_A", B = "Apart_Hi_Booze_B", C = "Apart_Hi_Booze_C", Enable = function (details, state, refresh) SetIplPropState(ExecApartment1.currentInteriorId, details, state, refresh) end }, Smoke = { none = "", stage1 = "Apart_Hi_Smokes_A", stage2 = "Apart_Hi_Smokes_B", stage3 = "Apart_Hi_Smokes_C", Set = function(smoke, refresh) ExecApartment1.Smoke.Clear(false) if (smoke ~= nil) then SetIplPropState(ExecApartment1.currentInteriorId, smoke, true, refresh) else if (refresh) then RefreshInterior(ExecApartment1.currentInteriorId) end end end, Clear = function(refresh) SetIplPropState(ExecApartment1.currentInteriorId, {ExecApartment1.Smoke.stage1, ExecApartment1.Smoke.stage2, ExecApartment1.Smoke.stage3}, false, refresh) end }, LoadDefault = function() ExecApartment1.Style.Set(ExecApartment1.Style.Theme.modern, true) ExecApartment1.Strip.Enable({ExecApartment1.Strip.A, ExecApartment1.Strip.B, ExecApartment1.Strip.C}, false) ExecApartment1.Booze.Enable({ExecApartment1.Booze.A, ExecApartment1.Booze.B, ExecApartment1.Booze.C}, false) ExecApartment1.Smoke.Set(ExecApartment1.Smoke.none) end }
--====================================================================-- -- dmc_ui/dmc_widget/widget_scrollview/axis_motion.lua -- -- Documentation: --====================================================================-- --[[ The MIT License (MIT) Copyright (C) 2015 David McCuskey. All Rights Reserved. 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. --]] --====================================================================-- --== DMC Corona UI : Axis Motion --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== DMC Corona UI Setup --====================================================================-- local dmc_ui_data = _G.__dmc_ui local dmc_ui_func = dmc_ui_data.func local ui_find = dmc_ui_func.find --====================================================================-- --== DMC UI : --====================================================================-- --====================================================================-- --== Imports local Objects = require 'dmc_objects' local StatesMixModule = require 'dmc_states_mix' local Utils = require 'dmc_utils' local uiConst = require( ui_find( 'ui_constants' ) ) local easingx = require( ui_find( 'dmc_widget.lib.easingx' ) ) --====================================================================-- --== Setup, Constants local newClass = Objects.newClass local ObjectBase = Objects.ObjectBase local mabs = math.abs local mfloor = math.floor local sfmt = string.format local tinsert = table.insert local tremove = table.remove local tstr = tostring --====================================================================-- --== Axis Motion Class --====================================================================-- local AxisMotion = newClass( ObjectBase, {name="Axis Motion"} ) StatesMixModule.patch( AxisMotion ) --== Class Constants AxisMotion.HIT_UPPER_LIMIT = 'upper-limit-hit' AxisMotion.HIT_LOWER_LIMIT = 'lower-limit-hit' AxisMotion.HIT_SIZE_LIMIT = 'size-limit-hit' AxisMotion.SCROLLBACK_FACTOR = 1/3 AxisMotion.VELOCITY_STACK_LENGTH = uiConst.AXIS_VELOCITY_STACK_LENGTH AxisMotion.VELOCITY_LIMIT = uiConst.AXIS_VELOCITY_LIMIT AxisMotion.UPPER = 'upper-alignment' AxisMotion.MIDDLE = 'middle-aligment' AxisMotion.LOWER = 'lower-alignment' AxisMotion._VALID_ALIGNMENT = { AxisMotion.UPPER, AxisMotion.MIDDLE, AxisMotion.LOWER } --== State Constants AxisMotion.STATE_CREATE = 'state_create' AxisMotion.STATE_AT_REST = 'state_at_rest' AxisMotion.STATE_DECELERATE = 'state_decelerate' AxisMotion.STATE_RESTORE = 'state_restore' AxisMotion.STATE_RESTRAINT = 'state_restraint' AxisMotion.STATE_TOUCH = 'state_touch' --== Event Constants AxisMotion.SCROLLING = 'scrolling' AxisMotion.SCROLLED = 'scrolled' --======================================================-- -- Start: Setup DMC Objects function AxisMotion:__init__( params ) -- print( "AxisMotion:__init__" ) params = params or {} if params.bounceIsActive==nil then params.bounceIsActive=true end if params.autoAlign==nil then params.autoAlign=AxisMotion.MIDDLE end if params.decelerateTransitionTime==nil then params.decelerateTransitionTime=uiConst.AXIS_DECELERATE_TIME end if params.restoreTransitionTime==nil then params.restoreTransitionTime=uiConst.AXIS_RESTORE_TIME end if params.restraintTransitionTime==nil then params.restraintTransitionTime=uiConst.AXIS_RESTRAINT_TIME end if params.scrollToTransitionTime==nil then params.scrollToTransitionTime=uiConst.AXIS_SCROLLTO_TIME end if params.length==nil then params.length=0 end if params.lowerOffset==nil then params.lowerOffset=0 end if params.scrollbackFactor==nil then params.scrollbackFactor=AxisMotion.SCROLLBACK_FACTOR end if params.scrollIsEnabled==nil then params.scrollIsEnabled=true end if params.scrollLength==nil then params.scrollLength=0 end if params.upperOffset==nil then params.upperOffset=0 end self:superCall( '__init__', params ) --==-- -- save params for later self._ax_tmp_params = params -- tmp assert( params.callback ) --== Create Properties ==-- self._id = params.id self._callback = params.callback self._autoAlign = nil self._decelTransTime = 0 self._restoreTransTime = 0 self._restraintTransTime = 0 self._scrollToTransTime = 0 -- value is current position, eg x/y self._value = 0 -- view port size self._length = 0 -- actual scroller size (at 1.0) self._scrollLength = 0 -- current scale self._scale = 1.0 -- scroller size at scale self._scaledScrollLength = 0 -- reference point at scale 1.0 (eg, x,y) self._refPoint = nil self._location = 0 -- x/y position, used for offset self._lowerOffset = 0 self._upperOffset = 0 self._scrollbackFactor = 0 self._scrollbackLimit = 0 -- block to make sure had a proper start -- to touch events, eg 'began' self._didBegin = false --== Internal Properties -- eg, HIT_UPPER_LIMIT, HIT_LOWER_LIMIT, etc self._scrollLimit = nil -- previous Touch Event, used for calculating deltas self._tmpTouchEvt = nil -- previous enterFrame event, used for calculating deltas self._tmpFrameEvent = nil self._velocityStack = {0,0} self._velocity = { value=0, vector=0 } self._enterFrameIterator = nil self._bounceIsActive = false self._alwaysBounce = false self._scrollEnabled = false self:setState( AxisMotion.STATE_CREATE ) end --== createView function AxisMotion:__initComplete__() -- print( "AxisMotion:__initComplete__" ) self:superCall( '__initComplete__' ) --==-- local tmp = self._ax_tmp_params --== Use Setters self.alignment = tmp.alignment self.autoAlign = tmp.autoAlign self.bounceIsActive = tmp.bounceIsActive self.decelerateTransitionTime = tmp.decelerateTransitionTime self.length = tmp.length self.lowerOffset = tmp.lowerOffset self.restoreTransitionTime = tmp.restoreTransitionTime self.restraintTransitionTime = tmp.restraintTransitionTime self.scrollbackFactor = tmp.scrollbackFactor self.scrollIsEnabled = tmp.scrollIsEnabled self.scrollLength = tmp.scrollLength self.scrollToTransitionTime = tmp.scrollToTransitionTime self.upperOffset = tmp.upperOffset self._ax_tmp_params = nil self:gotoState( AxisMotion.STATE_AT_REST ) end function AxisMotion:__undoInitComplete__() -- print( "AxisMotion:__undoInitComplete__" ) --==-- self:superCall( '__undoInitComplete__' ) end -- END: Setup DMC Objects --======================================================-- --====================================================================-- --== Public Methods -- whether to bounce on constraint function AxisMotion.__getters:autoAlign() return self._autoAlign end function AxisMotion.__setters:autoAlign( value ) assert( value==nil or type(value)=='string' ) if value~=nil then if not Utils.propertyIn( AxisMotion._VALID_ALIGNMENT, value ) then error( "AxisMotion.alignment expected a valid value" ) end end --==-- self._autoAlign = value end -- whether to bounce on constraint function AxisMotion.__getters:bounceIsActive() return self._bounceIsActive end function AxisMotion.__setters:bounceIsActive( value ) assert( type(value)=='boolean' ) --==-- self._bounceIsActive = value end function AxisMotion.__getters:decelerateTransitionTime() return self._decelTransTime end function AxisMotion.__setters:decelerateTransitionTime( value ) assert( type(value)=='number' and value > 0, "ERROR: AxisMotion.decelerateTransitionTime expected number", value ) --==-- self._decelTransTime = value end -- this is the length of the view port function AxisMotion.__getters:length() return self._length end function AxisMotion.__setters:length( value ) assert( type(value)=='number' and value > 0 ) --==-- self._length = value self:_setScrollbackLimit() end function AxisMotion.__setters:location( value ) assert( type(value)=='number' ) --==-- self._location = value end function AxisMotion.__getters:lowerOffset() return self._lowerOffset end function AxisMotion.__setters:lowerOffset( value ) assert( type(value)=='number' ) --==-- self._lowerOffset = value end function AxisMotion.__getters:restoreTransitionTime() return self._restoreTransTime end function AxisMotion.__setters:restoreTransitionTime( value ) assert( type(value)=='number' and value > 0, "ERROR: AxisMotion.restoreTransitionTime expected number", value ) --==-- self._restoreTransTime = value end function AxisMotion.__getters:restraintTransitionTime() return self._restraintTransTime end function AxisMotion.__setters:restraintTransitionTime( value ) assert( type(value)=='number' and value > 0, "ERROR: AxisMotion.restraintTransitionTime expected number", value ) --==-- self._restraintTransTime = value end function AxisMotion.__setters:scale( value ) -- print("AxisMotion.__setters:scale", value ) self._scale = value local refPoint = self._refPoint self:_setScaledScrollLength() if refPoint~=nil then self._value = self._tmpTouchEvt.value - refPoint*value end self:_checkScaledPosition() end -- decimal fraction (1/3) function AxisMotion.__setters:scrollbackFactor( value ) self._scrollbackFactor = value self:_setScrollbackLimit() end function AxisMotion.__getters:scrollIsEnabled() return self._scrollEnabled end function AxisMotion.__setters:scrollIsEnabled( value ) assert( type(value)=='boolean' ) --==-- self._scrollEnabled = value end function AxisMotion.__getters:scrollToTransitionTime() return self._scrollToTransTime end function AxisMotion.__setters:scrollToTransitionTime( value ) assert( type(value)=='number' and value > 0, "ERROR: AxisMotion.scrollToTransitionTime expected number", value ) --==-- self._scrollToTransTime = value end -- this is the maximum dimension of the scroller function AxisMotion.__getters:scaledScrollLength() return self._scaledScrollLength end function AxisMotion:_setScaledScrollLength() self._scaledScrollLength = mfloor( self._scrollLength * self._scale ) end -- this is the maximum dimension of the scroller function AxisMotion.__getters:scrollLength() return self._scrollLength end function AxisMotion.__setters:scrollLength( value ) assert( type(value)=='number' and value >= 0 ) --==-- self._scrollLength = value self:_setScaledScrollLength() end function AxisMotion.__getters:upperOffset() return self._upperOffset end function AxisMotion.__setters:upperOffset( value ) assert( type(value)=='number' ) --==-- self._upperOffset = value end -- current position/location function AxisMotion.__getters:value() return self._value end function AxisMotion:scrollToPosition( pos, params ) -- print( "AxisMotion:scrollToPosition", pos ) params = params or {} -- params.onComplete=params.onComplete if params.time==nil then params.time=self._scrollToTransTime end if params.limitIsActive==nil then params.limitIsActive=false end --==-- local eFI if params.time==0 then eFI = function() self._value = pos self._isMoving=false self._hasMoved=true self._enterFrameIterator=nil if params.onComplete then params.onComplete() end end else local time = params.time local ease_f = easingx.easeOut local val = self._value local startEvt = { time=system.getTimer() } self._isMoving = true local delta = self._value + pos if params.limitIsActive then local velocity = mabs( delta/time ) if velocity > AxisMotion.VELOCITY_LIMIT then time = mfloor( mabs(delta/AxisMotion.VELOCITY_LIMIT) ) end end eFI = function( e ) local deltaT = e.time - startEvt.time local deltaV = ease_f( deltaT, time, val, delta ) if deltaT < time then self._value = deltaV else self._isMoving = false self._hasMoved = true self._value = delta self._enterFrameIterator=nil if params.onComplete then params.onComplete() end end end end self._enterFrameIterator = eFI Runtime:addEventListener( 'enterFrame', self ) end --====================================================================-- --== Private Methods -- set how far table can be scrolled against a boundary limit -- function AxisMotion:_setScrollbackLimit() self._scrollbackLimit = self._length * self._scrollbackFactor end function AxisMotion:_checkScaledPosition() -- print( "AxisMotion:_checkScaledPosition" ) if self:getState() ~= AxisMotion.STATE_AT_REST then return end local value = self._value if value==nil then return end local newVal = self:_constrainPosition( value, 0 ) if value==newVal then return end if newVal==nil then return end self:scrollToPosition( newVal, {time=0} ) end -- check if position is at a limit -- function AxisMotion:_checkScrollBounds( value ) -- print( "AxisMotion:_checkScrollBounds", value ) local calcs = { min=0, max=0 } if self._scrollEnabled and value then local upper = 0 + self._upperOffset local lower = (self._length-self._scaledScrollLength) - self._lowerOffset calcs.min=upper calcs.max=lower if self._scaledScrollLength < self._length then self._scrollLimit = AxisMotion.HIT_SIZE_LIMIT elseif value > upper then self._scrollLimit = AxisMotion.HIT_UPPER_LIMIT elseif value < lower then self._scrollLimit = AxisMotion.HIT_LOWER_LIMIT else self._scrollLimit = nil end end return calcs end -- ensure position stays within boundaries -- function AxisMotion:_constrainPosition( value, delta ) if self._id=='y' then -- print( "AxisMotion:_constrainPosition", value, delta ) end local isBounceActive = self._bounceIsActive local LIMIT = self._scrollbackLimit local scrollLimit, newVal, calcs, s, factor newVal = value + delta calcs = self:_checkScrollBounds( newVal ) scrollLimit = self._scrollLimit -- after check bounds if scrollLimit==AxisMotion.HIT_SIZE_LIMIT then local align = self._autoAlign if align==nil then newVal = newValue elseif align==AxisMotion.MIDDLE then newVal = self._length*0.5 - self._scaledScrollLength*0.5 elseif align==AxisMotion.LOWER then newVal = self._length - self._scaledScrollLength else newVal = 0 end elseif scrollLimit==AxisMotion.HIT_UPPER_LIMIT then if not isBounceActive then newVal=calcs.min else s = newVal-self._upperOffset factor = 1 - (s/LIMIT) if factor < 0 then factor = 0 end newVal = value + ( delta * factor ) -- check bounds again self:_checkScrollBounds( newVal ) end elseif scrollLimit==AxisMotion.HIT_LOWER_LIMIT then if not isBounceActive then newVal=calcs.max else s = (self._length - self._scaledScrollLength) - newVal - self._lowerOffset factor = 1 - (s/LIMIT) if factor < 0 then factor = 0 end newVal = value + ( delta * factor ) -- check bounds again self:_checkScrollBounds( newVal ) end end if self._id=='y' then -- print( "constain", self._scrollLimit ) end return newVal end -- clamp max velocity, calculate average velocity -- function AxisMotion:_updateVelocity( value ) -- print( "AxisMotion:_updateVelocity", value ) local VEL_STACK_LENGTH = AxisMotion.VELOCITY_STACK_LENGTH local LIMIT = AxisMotion.VELOCITY_LIMIT local _mabs = mabs local velStack = self._velocityStack local vel = self._velocity local vector, aveVel = 0,0 if _mabs(value) > LIMIT then -- clamp velocity vector = (value>=0) and 1 or -1 value = LIMIT*vector end tinsert( velStack, 1, value ) for i = #velStack, 1, -1 do -- calculate average velocity and -- clean off velocity stack at same time if i > VEL_STACK_LENGTH then tremove( velStack, i ) else aveVel = aveVel + velStack[i] end end aveVel = aveVel / #velStack vel.value = _mabs( aveVel ) if aveVel~=0 then vel.vector = (aveVel>0) and -1 or 1 else vel.vector = 0 end end --====================================================================-- --== Event Handlers function AxisMotion:enterFrame( event ) -- print( "AxisMotion:enterFrame" ) local f = self._enterFrameIterator if not f then Runtime:removeEventListener( 'enterFrame', self ) else f( event ) self._tmpFrameEvent = event if self._isMoving then local vel = self._velocity self._callback{ id=self._id, state=AxisMotion.SCROLLING, value=self._value, velocity = vel.value * vel.vector, } self._hasMoved = true end -- look at "full" 'enterFrameIterator' in case value -- was changed during last call to interator if not self._enterFrameIterator and self._hasMoved then self._callback{ id=self._id, state = AxisMotion.SCROLLED, value = self._value, velocity = 0 } self._hasMoved = false end end end function AxisMotion:touch( event ) -- print( "AxisMotion:touch", event.phase, event.value ) local phase = event.phase if not self._scrollEnabled then return end local evt = { -- make a "copy" of the event time=event.time, start=event.start, -- make relative position, without using globalToContent value=event.value-self._location } if phase=='began' then local vel = self._velocity local velStack = self._velocityStack -- @TODO, probably check to see state we're in vel.value, vel.vector = 0, 0 -- get our initial reference point self._refPoint = (evt.value - self._value)/self._scale if #velStack==0 then tinsert( velStack, 1, 0 ) end self._tmpTouchEvt = evt self._didBegin = true self:gotoState( AxisMotion.STATE_TOUCH ) end if not self._didBegin then return end if phase == 'moved' then local tmpTouchEvt = self._tmpTouchEvt local constrain = AxisMotion._constrainPosition local deltaVal = evt.value - tmpTouchEvt.value local deltaT = evt.time - tmpTouchEvt.time local oldVal, newVal self._isMoving = true --== Calculate new position/velocity oldVal = self._value newVal = constrain( self, oldVal, deltaVal ) self:_updateVelocity( (oldVal-newVal)/deltaT ) self._value = newVal self._tmpTouchEvt = evt elseif phase=='ended' or phase=='cancelled' then self._tmpTouchEvt = evt self._didBegin = false self._refPoint = nil local next_state, next_params = self:_getNextState{ event=evt } self:gotoState( next_state, next_params ) end end --====================================================================-- --== State Machine function AxisMotion:_getNextState( params ) -- print( "AxisMotion:_getNextState" ) params = params or {} --==-- local scrollLimit = self._scrollLimit local velocity = self._velocity local isBounceActive = self._bounceIsActive local s, p -- state, params -- print( "gNS>>", velocity.value, scrollLimit, isBounceActive ) if velocity.value > 0 and not scrollLimit then s = AxisMotion.STATE_DECELERATE p = { event=params.event } elseif velocity.value <= 0 and scrollLimit and isBounceActive then s = AxisMotion.STATE_RESTORE p = { event=params.event } elseif velocity.value > 0 and scrollLimit and isBounceActive then s = AxisMotion.STATE_RESTRAINT p = { event=params.event } else s = AxisMotion.STATE_AT_REST p = { event=params.event } end return s, p end --== State Create function AxisMotion:state_create( next_state, params ) -- print( "AxisMotion:state_create: >> ", next_state ) if next_state == AxisMotion.STATE_AT_REST then self:do_state_at_rest( params ) else pwarn( sfmt( "AxisMotion:state_create unknown transition '%s'", tstr( next_state ))) end end --== State At-Rest function AxisMotion:do_state_at_rest( params ) -- print( "AxisMotion:do_state_at_rest", params ) params = params or {} --==-- local vel = self._velocity vel.value, vel.vector = 0, 0 self._isMoving = false self._enterFrameIterator = nil Runtime:removeEventListener( 'enterFrame', self ) self:setState( AxisMotion.STATE_AT_REST ) end function AxisMotion:state_at_rest( next_state, params ) -- print( "AxisMotion:state_at_rest: >> ", next_state ) if next_state == AxisMotion.STATE_TOUCH then self:do_state_touch( params ) else pwarn( sfmt( "AxisMotion:state_at_rest unknown transition '%s'", tstr( next_state ))) end end --== State Touch function AxisMotion:do_state_touch( params ) -- print( "AxisMotion:do_state_touch" ) -- params = params or {} -- --==-- local enterFrameFunc1 = function( e ) -- print( "enterFrameFunc: enterFrameFunc1 state touch " ) self:_updateVelocity( 0 ) end -- start animation if self._enterFrameIterator == nil then Runtime:addEventListener( 'enterFrame', self ) end self._enterFrameIterator = enterFrameFunc1 -- set current state self:setState( AxisMotion.STATE_TOUCH ) end function AxisMotion:state_touch( next_state, params ) -- print( "AxisMotion:state_touch: >> ", next_state ) if next_state == AxisMotion.STATE_RESTORE then self:do_state_restore( params ) elseif next_state == AxisMotion.STATE_RESTRAINT then self:do_state_restraint( params ) elseif next_state == AxisMotion.STATE_AT_REST then self:do_state_at_rest( params ) elseif next_state == AxisMotion.STATE_DECELERATE then self:do_state_decelerate( params ) else pwarn( sfmt( "AxisMotion:state_touch unknown state transition '%s'", tstr( next_state ))) end end --== State Decelerate function AxisMotion:do_state_decelerate( params ) -- print( "AxisMotion:do_state_decelerate" ) params = params or {} --==-- local TIME = self._decelTransTime local constrain = AxisMotion._constrainPosition local ease_f = easingx.easeOutQuad local _mabs = mabs local startEvt = params.event local vel = self._velocity local velocity = vel.value local deltaVel = -velocity self._isMoving = true local enterFrameFunc = function( e ) -- print( "AxisMotion: enterFrameFunc: do_state_decelerate" ) local frameEvt = self._tmpFrameEvent local scrollLimit = self._scrollLimit local deltaStart = e.time - startEvt.time local deltaFrame = e.time - frameEvt.time local deltaVal, oldVal, newVal --== Calculation vel.value = ease_f( deltaStart, TIME, velocity, deltaVel ) deltaVal = vel.value * vel.vector * deltaFrame --== Action oldVal = self._value newVal = constrain( self, oldVal, deltaVal ) self._value = newVal if vel.value > 0 and scrollLimit then -- hit edge while moving self:gotoState( AxisMotion.STATE_RESTRAINT, { event=e } ) elseif deltaStart >= TIME or _mabs( newVal-oldVal ) < 1 then -- over time or movement too small to see (pixel) self:gotoState( AxisMotion.STATE_AT_REST ) end end -- start animation if self._enterFrameIterator == nil then Runtime:addEventListener( 'enterFrame', self ) end self._enterFrameIterator = enterFrameFunc -- set current state self:setState( AxisMotion.STATE_DECELERATE ) end function AxisMotion:state_decelerate( next_state, params ) -- print( "AxisMotion:state_decelerate: >> ", next_state ) if next_state == self.STATE_TOUCH then self:do_state_touch( params ) elseif next_state == self.STATE_AT_REST then self:do_state_at_rest( params ) elseif next_state == self.STATE_RESTRAINT then self:do_state_restraint( params ) else pwarn( sfmt( "AxisMotion:state_decelerate unknown state transition '%s'", tstr( next_state ))) end end --== State Restore function AxisMotion:do_state_restore( params ) -- print( "AxisMotion:do_state_restore" ) params = params or {} --==-- local TIME = self._restoreTransTime local constrain = AxisMotion._constrainPosition local ease_f = easingx.easeOut local startEvt = params.event local val = self._value local vel = self._velocity local delta, offset -- calculate restore distance local scrollLimit = self._scrollLimit if scrollLimit == AxisMotion.HIT_SIZE_LIMIT then offset = constrain( self, val, 0 ) elseif scrollLimit == AxisMotion.HIT_UPPER_LIMIT then offset = self._upperOffset else offset = (self._length - self._scaledScrollLength - self._lowerOffset) end delta = offset-val self._isMoving = true local enterFrameFunc = function( e ) -- print( "AxisMotion: enterFrameFunc: do_state_restore " ) --== Calculation local deltaT = e.time - startEvt.time local deltaV = ease_f( deltaT, TIME, val, delta ) --== Action if deltaT < TIME then self._value = deltaV else self._value = offset self:gotoState( AxisMotion.STATE_AT_REST ) end end -- start animation if self._enterFrameIterator == nil then Runtime:addEventListener( 'enterFrame', self ) end self._enterFrameIterator = enterFrameFunc -- set current state self:setState( AxisMotion.STATE_RESTORE ) end function AxisMotion:state_restore( next_state, params ) -- print( "AxisMotion:state_restore: >> ", next_state ) if next_state == AxisMotion.STATE_TOUCH then self:do_state_touch( params ) elseif next_state == AxisMotion.STATE_AT_REST then self:do_state_at_rest( params ) else pwarn( sfmt( "AxisMotion:state_restore unknown state transition '%s'", tstr( next_state ))) end end --== State Restraint -- when object has velocity and hit limit -- we constrain its motion away from limit -- function AxisMotion:do_state_restraint( params ) -- print( "AxisMotion:do_state_restraint" ) params = params or {} --==-- local TIME = self._restraintTransTime local constrain = AxisMotion._constrainPosition local ease_f = easingx.easeOut local _mabs = mabs -- startEvt could be Touch or enterFrame event -- of importance is the 'time' param local startEvt = params.event local vel = self._velocity local velocity = vel.value * vel.vector local deltaVel = -velocity self._isMoving = true local enterFrameFunc = function( e ) -- print( "AxisMotion: enterFrameFunc: do_state_restraint" ) local frameEvt = self._tmpFrameEvent local deltaStart = e.time - startEvt.time -- total local deltaFrame = e.time - frameEvt.time local deltaVal, oldVal, newVal --== Calculation vel.value = ease_f( deltaStart, TIME, velocity, deltaVel ) deltaVal = vel.value * deltaFrame --== Action oldVal = self._value newVal = constrain( self, oldVal, deltaVal ) self._value = newVal if deltaStart >= TIME or _mabs( newVal-oldVal ) < 1 then vel.value, vel.vector = 0, 0 self:gotoState( AxisMotion.STATE_RESTORE, { event=e } ) end end -- start animation if self._enterFrameIterator == nil then Runtime:addEventListener( 'enterFrame', self ) end self._enterFrameIterator = enterFrameFunc -- set current state self:setState( AxisMotion.STATE_RESTRAINT ) end function AxisMotion:state_restraint( next_state, params ) -- print( "AxisMotion:state_restraint: >> ", next_state ) if next_state == self.STATE_TOUCH then self:do_state_touch( params ) elseif next_state == self.STATE_RESTORE then self:do_state_restore( params ) else pwarn( sfmt( "AxisMotion:state_restraint unknown state transition '%s'", tstr( next_state ))) end end return AxisMotion
return { include = function() includedirs "../vendor/cpprestsdk/Release/include/" defines { '_NO_PPLXIMP', '_NO_ASYNCRTIMP', '_PPLTASK_ASYNC_LOGGING=0' } if _OPTIONS['with-asan'] then defines { 'CPPREST_FORCE_PPLX' } end end, run = function() language "C++" kind "StaticLib" includedirs "../vendor/cpprestsdk/Release/src/pch/" files_project '../vendor/cpprestsdk/Release/src/' { 'pplx/pplx.cpp', 'pplx/threadpool.cpp', 'pch/stdafx.cpp', 'utilities/asyncrt_utils.cpp' } filter 'system:linux' files_project '../vendor/cpprestsdk/Release/src/' { 'pplx/pplxlinux.cpp' } filter 'system:windows' files_project '../vendor/cpprestsdk/Release/src/' { 'pplx/pplxwin.cpp' } end }
object_building_player_player_guildhall_corellia_style_04 = object_building_player_shared_player_guildhall_corellia_style_04:new { } ObjectTemplates:addTemplate(object_building_player_player_guildhall_corellia_style_04, "object/building/player/player_guildhall_corellia_style_04.iff")
module(..., package.seeall) local constants = require("apps.lwaftr.constants") local bit = require("bit") local ffi = require("ffi") local band, rshift, bswap = bit.band, bit.rshift, bit.bswap local cast = ffi.cast local uint16_ptr_t = ffi.typeof("uint16_t*") local uint32_ptr_t = ffi.typeof("uint32_t*") function get_ihl_from_offset(pkt, offset) local ver_and_ihl = pkt.data[offset] return band(ver_and_ihl, 0xf) * 4 end -- The rd16/wr16/rd32/wr32 functions are provided for convenience. -- They do NO conversion of byte order; that is the caller's responsibility. function rd16(offset) return cast(uint16_ptr_t, offset)[0] end function wr16(offset, val) cast(uint16_ptr_t, offset)[0] = val end function rd32(offset) return cast(uint32_ptr_t, offset)[0] end function wr32(offset, val) cast(uint32_ptr_t, offset)[0] = val end local to_uint32_buf = ffi.new('uint32_t[1]') local function to_uint32(x) to_uint32_buf[0] = x return to_uint32_buf[0] end function htons(s) return rshift(bswap(s), 16) end function htonl(s) return to_uint32(bswap(s)) end function keys(t) local result = {} for k,_ in pairs(t) do table.insert(result, k) end return result end local uint64_ptr_t = ffi.typeof('uint64_t*') function ipv6_equals(a, b) local a, b = ffi.cast(uint64_ptr_t, a), ffi.cast(uint64_ptr_t, b) return a[0] == b[0] and a[1] == b[1] end -- Local bindings for constants that are used in the hot path of the -- data plane. Not having them here is a 1-2% performance penalty. local o_ethernet_ethertype = constants.o_ethernet_ethertype local n_ethertype_ipv4 = constants.n_ethertype_ipv4 local n_ethertype_ipv6 = constants.n_ethertype_ipv6 function is_ipv6(pkt) return rd16(pkt.data + o_ethernet_ethertype) == n_ethertype_ipv6 end function is_ipv4(pkt) return rd16(pkt.data + o_ethernet_ethertype) == n_ethertype_ipv4 end
local Bot={}; function Bot.initialize(agent) local agentId=agent:getAgentId(); Bot[agentId]={}; local PredatorBrainFactory=dofile(agent:getScriptClassPath() .. "\\TransformerBrain.lua"); Bot[agentId].brain=PredatorBrainFactory.create(agent); --attack any type of bots end function Bot.think(agent) local agentId=agent:getAgentId(); Bot[agentId].brain:think(); end function Bot.train(agent) alert("Training not supported", "This bot does not have training algorithm embeded in it"); end function Bot.uploadConfig(agent) alert("Method not implemented", "Method not implemented"); end return Bot;
-- Make lldb available in global lldb = require('lldb') -- Global assertion functions function assertTrue(x) if not x then error('assertTrue failure') end end function assertFalse(x) if x then error('assertNotNil failure') end end function assertNotNil(x) if x == nil then error('assertNotNil failure') end end function assertEquals(x, y) if type(x) == 'table' and type(y) == 'table' then for k, _ in pairs(x) do assertEquals(x[k], y[k]) end elseif type(x) ~= type(y) then error('assertEquals failure') elseif x ~= y then error('assertEquals failure') end end function assertStrContains(x, y) if not string.find(x, y, 1, true) then error('assertStrContains failure') end end -- Global helper functions function read_file_non_empty_lines(f) local lines = {} while true do local line = f:read('*l') if not line then break end if line ~= '\n' then table.insert(lines, line) end end return lines end function split_lines(str) local lines = {} for line in str:gmatch("[^\r\n]+") do table.insert(lines, line) end return lines end function get_stopped_threads(process, reason) local threads = {} for i = 0, process:GetNumThreads() - 1 do local t = process:GetThreadAtIndex(i) if t:IsValid() and t:GetStopReason() == reason then table.insert(threads, t) end end return threads end function get_stopped_thread(process, reason) local threads = get_stopped_threads(process, reason) if #threads ~= 0 then return threads[1] else return nil end end -- Test helper local _M = {} local _m = {} local _mt = { __index = _m } function _M.create_test(name, exe, output, input) print('[lldb/lua] Create test ' .. name) exe = exe or os.getenv('TEST_EXE') output = output or os.getenv('TEST_OUTPUT') input = input or os.getenv('TEST_INPUT') lldb.SBDebugger.Initialize() local debugger = lldb.SBDebugger.Create() -- Ensure that debugger is created assertNotNil(debugger) assertTrue(debugger:IsValid()) debugger:SetAsync(false) local lua_language = debugger:GetScriptingLanguage('lua') assertNotNil(lua_language) debugger:SetScriptLanguage(lua_language) local test = setmetatable({ output = output, input = input, name = name, exe = exe, debugger = debugger }, _mt) _G[name] = test return test end function _m:create_target(exe) local target if not exe then exe = self.exe end target = self.debugger:CreateTarget(exe) -- Ensure that target is created assertNotNil(target) assertTrue(target:IsValid()) return target end function _m:handle_command(command, collect) if collect == nil then collect = true end if collect then local ret = lldb.SBCommandReturnObject() local interpreter = self.debugger:GetCommandInterpreter() assertTrue(interpreter:IsValid()) interpreter:HandleCommand(command, ret) self.debugger:GetOutputFile():Flush() self.debugger:GetErrorFile():Flush() assertTrue(ret:Succeeded()) return ret:GetOutput() else self.debugger:HandleCommand(command) self.debugger:GetOutputFile():Flush() self.debugger:GetErrorFile():Flush() end end function _m:run() local tests = {} for k, v in pairs(self) do if string.sub(k, 1, 4) == 'Test' then table.insert(tests, k) end end table.sort(tests) for _, t in ipairs(tests) do print('[lldb/lua] Doing test ' .. self.name .. ' - ' .. t) local success = xpcall(self[t], function(e) print(debug.traceback()) end, self) if not success then print('[lldb/lua] Failure in test ' .. self.name .. ' - ' .. t) return 1 end end return 0 end return _M
function onCreate() -- background shit makeLuaSprite('back2', 'back2', -250, 0); setScrollFactor('back2', 0.9, 0.9); addLuaSprite('back2', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
local prefix = '{' .. KEYS[1] .. '}' .. '::' local id = ARGV[1] local key = prefix .. id local updateHasChildenCache = function (target, hasChild) local parentKey = prefix .. target .. '::P' local parents = redis.call('smembers', parentKey) for _, parent in ipairs(parents) do if parent then local parentValue = redis.call('get', prefix .. parent); if parentValue then local list = cmsgpack.unpack(parentValue) for _, v in ipairs(list) do if v[1] == target then v[2] = hasChild end end redis.call('set', prefix .. parent, cmsgpack.pack(list)); else -- REMEDY redis.call('srem', parentKey, parent) end end end end
 minetest.register_craftitem("technic_diamond:diamond_dust", { description="Diamond Dust", inventory_image = "technic_diamond_dust.png"}) technic.register_grinder_recipe({ input = {"default:diamond"}, output = {"technic_diamond:diamond_dust 2"}}) technic.register_compressor_recipe({ input = {"technic_diamond:diamond_dust"}, output = {"default:diamond"}}) technic.register_compressor_recipe({ input = {"technic:coal 10"}, output = {"default:diamond"}}) technic.register_compressor_recipe({ input = {"technic:coal_dust"}, input = {"default:coal_lump"}})
-- Collection of utility functions for the ConstructBot library -- Runs func untill it returns either true or nil function tillDone(func) local r = {func()} while(next(r) ~= nil and r[1] ~= true) do r = {func()} end end -- Runs tillDone(func) num times -- This means func will be ran until it returns nil or true a total of num times -- at wich point this method will return function runMany(func, num) local toMove = num while(toMove > 0) do tillDone(func) toMove = toMove-1 end end
require "utils" utils.dofile("wifi") require "am2302" am2302.start()
-- Multi-threading -- referenced (https://github.com/soumith/dcgan.torch/blob/master/data) -- Copyright (c) 2017, Minchul Shin [See LICENSE file for details] require 'os' local Threads = require 'threads' Threads.serialization('threads.sharedserialize') local data = {} local result = {} local unpack = unpack and unpack or table.unpack -- option list -- 'threads', 'batchSize', 'manualSeed' function data.new(_params) local _params = _params or {} local self = {} for k,v in pairs(data) do self[k] = v end -- get params or set default value. local nthreads = _params.nthreads or 1 -- default thread num is 1. local manualSeed = _params.manualSeed or os.time() -- random seed. self.batchSize = _params.batchSize --local donkey_file = 'donkey.lua' if nthreads > 0 then self.threads = Threads( nthreads, function() require 'torch' end, function(thread_id) opt = _params local seed = (manualSeed and manualSeed or 0) + thread_id torch.manualSeed(seed) torch.setnumthreads(1) print(string.format('Starting donkey with id: %d, seed: %d', thread_id, seed)) assert(opt, 'option parameters not given') require('dataloader') loader=DataLoader(opt) end ) end local nTrainSamples = 0 local nTestSamples = 0 self.threads:addjob( function() return loader:size('train') end, function(c) nTrainSamples = c end) self.threads:addjob( function() return loader:size('test') end, function(c) nTestSamples = c end) self.threads:synchronize() self._trainlen = nTrainSamples self._testlen = nTestSamples return self end function data._getFromTrainThreads() assert(opt.batchSize, 'batchSize not found.') return loader:getSample('train') end function data._getFromTestThreads() assert(opt.batchSize, 'batchSize not found.') return loader:getSample('test') end function data._pushResult(...) local res = {...} if res == nil then self.threads:synchronize() end table.insert(result, res) end function data.table2Tensor(table) assert( table[1]:size(1)==3 or table[1]:size(1)==1, 'the tensor channel should be 1(gray) or 3(rgb).') assert( table[1]~=nil, 'no elements were found in batch table.') local len = #table local res = torch.Tensor(len, table[1]:size(1), table[1]:size(2), table[1]:size(3)):zero() for i = 1, len do res[{{i},{},{},{}}]:copy(table[i]) end return res end function data.getBatch(self, target) assert(target=='train' or target=='test') assert(self.batchSize, 'batchSize not found.') local dataTable = {} ---queue another job if target == 'train' then for i = 1, self.batchSize do self.threads:addjob(self._getFromTrainThreads, function(c) table.insert(dataTable, c) end) end elseif target == 'test' then for i = 1, opt.batchSize do self.threads:addjob(self._getFromTestThreads, self._pushResult) self.threads:dojob() end end self.threads:synchronize() collectgarbage() local res = self.table2Tensor(dataTable) return res end function data.getSample(self, target) assert(target=='train' or target=='test') assert(self.batchSize, 'batchSize not found.') local dataTable = {} if target == 'train' then self.threads:addjob(self._getFromTrainThreads, function(c) table.insert(dataTable, c) end) self.threads:dojob() elseif target == 'test' then self.threads:addjob(self._getFromTestThreads, function(c) table.insert(dataTable, c) end) self.threads:dojob() end return unpack(dataTable) end function data:size(target) if target == 'train' then return self._trainlen elseif target == 'test' then return self._testlen elseif target == 'all' or target == nil then return (self._trainlen + self._testlen) end end return data
--[[ Global scope variables ]]-- local WinWidth, WinHeight = love.graphics.getDimensions() -- Global scope objects local Ball local Enemy local Player -- This basic object will hold the score info local Score = {} function Score.increase() Score.score = Score.score + 1 end function Score.draw() love.graphics.setColor({1, 1, 1}) love.graphics.print( 'Score: ' .. Score.score, WinWidth/2-20, 50) end --[[ love.load ]]-- function love.load() -- Reset the global score Score.score = 0 -- To create Player and Enemy at same class -- we can use the metatable of lua (https://www.lua.org/pil/13.html). -- First create a simple table local Rect = {} -- __index will access the methods shared between -- objects, working like inherit (https://www.lua.org/pil/13.4.1.html). Rect.__index = Rect -- Properties and methods shared between all rects Rect.width = 10 Rect.height = 100 Rect.move = function(self, y) -- Here we will first move the rect self.y = self.y + y -- then check if still inside the screen if self.y + self.height >= WinHeight or self.y <= 0 then -- and if is off screen the rect go back. self.y = self.y - y end end -- Just a monotone draw function Rect.draw = function(self, color) love.graphics.setColor(color) love.graphics.rectangle( 'fill', self.x, self.y, self.width, self.height ) end -- Here we will pay some extra attention Rect.coll = function(self, x, y, callback) -- this is a way to put an default value on var -- and dont catch an error callback = callback or function() end -- Then an intersection check that -- test if x and y are inside the rect if x <= self.x + self.width and x >= self.x and y >= self.y and y <= self.y + self.height then -- This callback function will score -- on ball-player collision callback() -- after the collision has been -- confirmed then return true return true end end -- Initialized the Enemy object Enemy = {} -- Here we simulate inherit of enemy object as a rect setmetatable(Enemy, Rect) -- These properties arent shared with anyone -- x and y will be the position of enemy on screen Enemy.x = WinWidth - 20 Enemy.y = math.floor(WinHeight/2) - 25 -- Initialized the Player object Player = {} -- Here we simulate inherit of player object as a rect too setmetatable(Player, Rect) -- These properties are the same from enemy but -- are inside the player Player.x = 10 Player.y = math.floor(WinHeight/2) - 25 -- vecY will be the player "velocity" Player.vecY = 0 -- at the update method, the position of player will -- be calculated with dt and vecY Player.update = function(self, dt) self:move(self.vecY * dt) end -- Ball object initialized Ball = {} -- same as in player but moves in two dimensions Ball.x = math.floor(WinWidth/2) Ball.y = math.floor(WinHeight/2) Ball.vecX = 250 Ball.vecY = 50 -- Here the code gets a little confused Ball.update = function(self, dt) -- First of all, we need to update -- the balls position self.x = self.x + self.vecX*dt self.y = self.y + self.vecY*dt -- Then we check if has collision with -- someone and if has collided with -- player, the score increase if Player:coll(self.x, self.y, Score.increase) or Enemy:coll(self.x, self.y) then -- When the ball collides, we need get back -- the ball and invert his "velocity" to get -- a bounce effect self.x = self.x - self.vecX*dt self.vecX = self.vecX * -1 -- and increase the speed of the ball to get harder self.vecX = self.vecX*(1+dt) self.vecY = self.vecY*(1+dt) end -- So if the ball didnt collided with anyone -- we check if is beyond the limits of screen -- first bouncing against the walls if self.y >= WinHeight - 10 or self.y <= 10 then self.y = self.y - self.vecY*dt self.vecY = self.vecY * -1 end -- and then verifying if has a game over -- here we just quit the game to simplify if self.x >= WinWidth - 10 or self.x <= 10 then love.load() end -- This is a way to the enemy -- follow the ball and (probaly) dont lose Enemy:move(self.vecY*dt) -- You can activate the samething -- to the player, but this will be a cheat -- or an I.A. battle... --Player:move(self.vecY*dt) end -- Simple draw function Ball.draw = function(self) love.graphics.setColor({0.9, 0.4, 0.4}) love.graphics.circle("line", self.x, self.y, 10) end end --[[ love.update ]]-- function love.update(dt) Player:update(dt) Ball:update(dt) end --[[ love.draw ]]-- function love.draw() Score.draw() Ball:draw() Player:draw({0.5, 0.5, 0.6}) Enemy:draw({0.6, 0.5, 0.5}) -- Here we render big buttons to separate the -- two touch buttons on the screen love.graphics.setColor({1,1,1,0.05}) -- this has x and y at 0, 0 and goes at the -- middle of screen width ocuppying full height love.graphics.rectangle('fill', 0, 0, WinWidth/2-1, WinHeight) -- and this has x at the middle of screen but -- goes until the end, symmetric with the other button love.graphics.rectangle('fill', WinWidth/2+2, 0, WinWidth/2-1, WinHeight) -- these "+2" and "=1" are calculated to get a little gap -- between the buttons end --[[ Functions that handles the touch ]]-- function touchpressHandle(id, x, y) -- Exactly as in ball collision test -- here we check the intersection of touch -- on the buttons and then set the player "velocity" -- where the negative indicates up and positive down -- Left button if x >= 0 and x <= WinWidth/2-1 and y >= 0 and y <= WinHeight then -- To Infinity and Beyond Player.vecY = -500 end -- Right button if x >= WinWidth/2+2 and x <= WinWidth and y >= 0 and y <= WinHeight then -- On the highway to hell Player.vecY = 500 end end function touchreleaseHandle() -- When the button is released -- we need to reset the player "velocity" Player.vecY = 0 end --[[ Mouse will simule the touch on computer ]]-- love.mousepressed = function(x, y) touchpressHandle(nil, x, y) end love.mousereleased = touchreleaseHandle --[[ Love touch events ]]-- love.touchpressed = touchpressHandle love.mousereleased = touchreleaseHandle --[[ end :) ]]--
-- Sector A2: Destroy the Enemy Ship obj_prim_newobj_id = 0 enemy_ping = 0 function OnInit() Rule_Add("Rule_Init") end function Rule_Init() StartMission() if (questsStatus.a2_ShipHasBeenDestroyed ~= 1) then Event_Start( "IntelEvent_Intro" ) enemy_ping = Ping_AddSobGroup("Enemy Ship", "anomaly", "EnyGroup") Rule_AddInterval( "Rule_PlayerWins", 2 ) else objectivesClear[currentSectorRow][currentSectorCol] = 1 Event_Start( "IntelEvent_AlreadyDone" ) end Rule_Remove( "Rule_Init" ) end function Rule_PlayerWins() if (SobGroup_Empty("EnyGroup") == 1) then Ping_Remove(enemy_ping) questsStatus.a2_ShipHasBeenDestroyed = 1 Objective_SetState(obj_prim_newobj_id, OS_Complete) objectivesClear[currentSectorRow][currentSectorCol] = 1 Event_Start( "IntelEvent_Finale" ) Rule_Remove("Rule_PlayerWins") end end Events = {} Events.IntelEvent_Intro = { { { [[Sound_EnableAllSpeech( 1 )]], [[]] }, { [[Sound_EnterIntelEvent()]], [[]] }, { [[Universe_EnableSkip(1)]], [[]] }, HW2_LocationCardEvent( mission_text_card, 5 ), }, { -- HW2_Letterbox( 1 ), HW2_Wait( 2 ), }, { { [[obj_prim_newobj_id = Objective_Add( mission_text_short, OT_Primary )]], [[]] }, { [[Objective_AddDescription( obj_prim_newobj_id, mission_text_long)]], [[]] }, HW2_SubTitleEvent( Actor_FleetIntel, mission_text_long, 4 ), }, { HW2_Wait( 1 ), }, { HW2_Letterbox( 0 ), HW2_Wait( 2 ), { [[Universe_EnableSkip(0)]], [[]] }, { [[Sound_ExitIntelEvent()]], [[]] }, }, } Events.IntelEvent_Finale = { { {"Sound_EnterIntelEvent()",""}, {"Universe_EnableSkip(1)",""}, }, { HW2_Wait( 2 ), HW2_Letterbox( 1 ), HW2_Wait( 2 ), }, { HW2_SubTitleEvent( Actor_FleetCommand, mission_text_success, 5 ), }, { HW2_Wait( 1 ), }, { HW2_Letterbox( 0 ), HW2_Wait( 2 ), {"Universe_EnableSkip(0)",""}, {"Sound_ExitIntelEvent()",""}, }, } Events.IntelEvent_AlreadyDone = { { {"Sound_EnterIntelEvent()",""}, {"Universe_EnableSkip(1)",""}, }, { HW2_Wait( 2 ), HW2_Letterbox( 1 ), HW2_Wait( 2 ), }, { {"obj_prim_newobj_id = Objective_Add( mission_text_short, OT_Primary )",""}, {"Objective_AddDescription( obj_prim_newobj_id, mission_text_clear)",""}, {"Objective_SetState( obj_prim_newobj_id, OS_Complete )",""}, HW2_SubTitleEvent( Actor_FleetCommand, mission_text_clear, 5 ), }, { HW2_Wait( 1 ), }, { HW2_Letterbox( 0 ), HW2_Wait( 2 ), {"Universe_EnableSkip(0)",""}, {"Sound_ExitIntelEvent()",""}, }, }
generator_list["json"] = { os.projectdir().."/tools/codegen/serialize_json.py", os.projectdir().."/tools/codegen/json_reader.h.mako", os.projectdir().."/tools/codegen/json_reader.cpp.mako", os.projectdir().."/tools/codegen/json_writer.h.mako", os.projectdir().."/tools/codegen/json_writer.cpp.mako" }; generator_list["serialize"] = { os.projectdir().."/tools/codegen/serialize.py", os.projectdir().."/tools/codegen/serialize.h.mako", }; generator_list["typeid"] = { os.projectdir().."/tools/codegen/typeid.py", os.projectdir().."/tools/codegen/typeid.hpp.mako", }; generator_list["config"] = { os.projectdir().."/tools/codegen/config_resource.py", os.projectdir().."/tools/codegen/config_resource.cpp.mako", }; generator_list["rtti"] = { os.projectdir().."/tools/codegen/rtti.py", os.projectdir().."/tools/codegen/rtti.cpp.mako", os.projectdir().."/tools/codegen/rtti.hpp.mako", }; generator_list["config_asset"] = { os.projectdir().."/tools/codegen/config_asset.py", os.projectdir().."/tools/codegen/config_asset.cpp.mako", gendir = toolgendir }; generator_list["importer"] = { os.projectdir().."/tools/codegen/importer.py", os.projectdir().."/tools/codegen/importer.cpp.mako", };
--- --- Copyright (c) GoGo Easy Team & Jacobs Lei --- Author: Jacobs Lei --- Date: 2018/4/7 --- Time: 上午10:44 local utils = require("core.utils.utils") local tonumber = tonumber local global_cache = require("core.cache.local.global_cache_util") local global_cache_prefix = require("core.cache.local.global_cache_prefix") local base_handler = require("plugins.base_handler") local plugin_config = require("plugins.global_rate_limit.config") local error_utils = require("core.utils.error_utils") local rate_limit_utils = require("core.utils.local_rate_limit_utils") local resp_utils = require("core.resp.resp_utils") local err_resp_template_utils = require("core.utils.err_resp_template_utils") local error_type_sys = error_utils.types.ERROR_SYSTEM.name local error_type_biz = error_utils.types.ERROR_BIZ.name local PRIORITY = require("plugins.handler_priority") local base_dao = require("core.dao.base_dao") local req_var_extractor = require("core.req.req_var_extractor") local log_config = require("core.utils.log_config") local plugin_name = plugin_config.name local ERR = ngx.ERR local ngx_log = ngx.log local str_format = string.format local function check_rate_limit_period(rate_limit_period) if not rate_limit_period then return nil end local period = tonumber(rate_limit_period) if not period then return nil end if period ~= 1 and period ~= 60 and period ~= 3600 and period ~= 86400 then return nil end ngx.log(ngx.DEBUG, "[global_rate_limit] period valid:", period) return period end local function check_rate_limit_count(rate_limit_value) if not rate_limit_value then return nil end local total = tonumber(rate_limit_value) if not total or total == 0 then return nil end ngx.log(ngx.DEBUG, "[global_rate_limit] total count valid:", total) return total end local function get_limit_type(period) if not period then return nil end if period == 1 then return "Second" elseif period == 60 then return "Minute" elseif period == 3600 then return "Hour" elseif period == 86400 then return "Day" else return nil end end -- 限速处理 local function rate_limit_handler(rate_limit_code,limit_count,limit_period,p_name,biz_id,cache_client) limit_period = check_rate_limit_period(limit_period) limit_count = check_rate_limit_count(limit_count) if not limit_period or not limit_count then ngx_log(ERR,str_format(log_config.sys_error_format,"[global_rate_limit] period or total count configuration error.")) error_utils.add_error_2_ctx(error_type_sys,plugin_config.small_error_types.sys.type_plugin_conf) return end local limit_type = get_limit_type(limit_period) if not limit_type then ngx_log(ERR,str_format(log_config.sys_error_format,log_config.ERROR,"[global_rate_limit] period configuration error,only support 1 second/minute/hour/day")) error_utils.add_error_2_ctx(error_type_sys,plugin_config.small_error_types.sys.type_plugin_conf) return end if limit_type then local current_timetable = utils.current_timetable() local rate_limit_key = plugin_name .. rate_limit_code .. current_timetable[limit_type] local pass = rate_limit_utils:check_rate_limit(rate_limit_key,limit_count,limit_type) if not pass then local msg = "ngr " .. rate_limit_code .." rate limit: ".. limit_count .. " remaining:".. 0; ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,msg)) error_utils.add_error_2_ctx(error_type_biz,plugin_config.small_error_types.biz.type_rate_control) resp_utils.say_customized_response_by_template(p_name,biz_id,resp_utils.status_codes.HTTP_GATEWAY_REJECTED,cache_client) return end end end local global_rate_limit_handler = base_handler:extend() global_rate_limit_handler.PRIORITY = PRIORITY.global_rate_limit function global_rate_limit_handler:new(app_context) global_rate_limit_handler.super.new(self, plugin_name) self.app_context = app_context end local function execute(cache_client) local http_host = req_var_extractor.extract_http_host() if not http_host then return end local rate_limit_table = global_cache.get_json(global_cache_prefix.rate_limit .. http_host) if not rate_limit_table then ngx_log(ERR,str_format(log_config.sys_error_format,log_config.ERROR,"can not get [" .. http_host .."] rate limit info from cache ")) error_utils.add_error_2_ctx(error_type_sys,plugin_config.small_error_types.sys.type_plugin_conf) return end local gateway_limit_period = rate_limit_table.gateway_limit_period; -- 网关限速 rate_limit_handler("gateway_" .. rate_limit_table.gateway_code, rate_limit_table.gateway_limit_count, gateway_limit_period, "gateway",rate_limit_table.gateway_id,cache_client) local host_limit_period = rate_limit_table.host_limit_period; -- 主机限速 rate_limit_handler("host_" .. http_host, rate_limit_table.host_limit_count, host_limit_period, "host",rate_limit_table.host_id,cache_client) end function global_rate_limit_handler:access() global_rate_limit_handler.super.access(self) local cache_client = self.app_context.cache_client xpcall(function () execute(cache_client) end, function (err) ngx.log(ngx.ERR, "global_rate_limit_handler access error: ", debug.traceback(err)) end) end function global_rate_limit_handler:init_worker_ext_timer() global_rate_limit_handler.super.init_worker_ext_timer(self) local app_context = self.app_context base_dao.init_rate_limit(app_context.store,app_context.config.application_conf.hosts) -- init gateway error massage err_resp_template_utils.init_2_redis("gateway",self.app_context.store,self.app_context.cache_client) -- init host error massage err_resp_template_utils.init_2_redis("host",self.app_context.store,self.app_context.cache_client) end return global_rate_limit_handler
require "util.class" require "util.event" require "system.system" local tt = require "util.table" class("Font") function Font:Font(font, size) self.font = font or nil self.size = size or 16 end local DefaultFont = Font() class("Noder") function Noder:Noder(font, justify, color, hoffset) self.font = font or DefaultFont self.justify = justify or "left" self.color = color or vec4(1, 0, 0, 1) self.hoffset = hoffset or 125 end local function txtnd(n, tag, fn) local f = n.font if f.font ~= nil then return am.text(n.font, fn(), n.color, n.justify) end return am.text(fn(), n.color, n.justify):tag(tag) end local function getValue(n, tag, x, y, fn) return am.translate(x,y):tag(string.format("%s", tag)) ^txtnd(n, tag, fn) end local function getValueUpdating(n, tag, x, y, fn) local s = string.format("%s-updatable", tag) local txt = txtnd(n, s, function() return "-" end) local act = function() while true do txt(s).text = fn() coroutine.yield() end end return am.translate(x,y):tag(string.format("%s", tag)) ^txt:action(coroutine.create(act)) end function Noder.Value(self) return function(tag, fn) return getValue(self, tag, 0, 0, fn) end end function Noder.UpdatingValue(self) return function(tag, fn) return getValueUpdating(self, tag, 0, 0, fn) end end function Noder.KeyValue(self) return function(tag, fn) local kt = string.format("%s-key", tag) local vt = string.format("%s-value", tag) local v = string.format("%s:", tag) return am.translate(0,0):tag(tag) ^am.group{ getValue(self, kt, 0, 0, function() return v end), getValue(self, vt, self.hoffset, 0, fn), } end end function Noder.UpdatingKeyValue(self) return function(tag, fn) local kt = string.format("%s-key", tag) local vt = string.format("%s-value", tag) local v = string.format("%s:", tag) return am.translate(0, 0):tag(tag) ^am.group{ getValue(self, kt, 0, 0, function() return v end), getValueUpdating(self, vt, self.hoffset, 0, fn), } end end function Noder:LineHeight() return self.font.size end function Noder:Function(k) local action = { ["Value"] = self.Value, ["UpdatingValue"] = self.UpdatingValue, ["KeyValue"] = self.KeyValue, ["UpdatingKeyValue"] = self.UpdatingKeyValue, } local function act(k) local fn = action[k] return fn(self) end return act(k) end class("Item") function Item:Item(tag, noder, ofk, ifn) self.tag = tag or "NO-ITEM-TAG" self.noder = noder or Noder() self.ofk = ofk or "Value" self.ifn = ifn or function() return "NOTHING" end end function Item:execute() local n = self.noder local ofn = n:Function(self.ofk) return ofn(self.tag, self.ifn) end class("Block") function Block:Block(tag, button, ...) self.tag = tag or "BLOCK" self.button = button or "" self.has = {...} self.active = false end function Block:count() return table.getn(self.has) end function Block:height() local c = 0 for _, v in ipairs(self.has) do c = c + v.noder:LineHeight() end return c end function Block:nodeGroup() local current = 0 local g = am.translate(0,0) for _,v in ipairs(self.has) do g:append(am.translate(0,current)^v:execute()) current = current - v.noder:LineHeight() end return g end class("Blocker") function Blocker:Blocker(tag, origin) self.tag = tag or "BLOCKER" self.Origin = origin or {X=0,Y=0} self.Current = {X=0,Y=0} self.attached = false self.active = {} end local function base(tag, x, y) local bt = string.format("%s-blocks", tag) local ni = am.translate(x,y):tag(bt) return ni end function Blocker:root() self.rootNode = base(self.tag, self.Origin.X, self.Origin.Y) return self.rootNode end function Blocker:Attach(to) to:append(self:root()) self.attached = true end function Blocker:Detach(from) local ni = from:remove(self.tag) ni = nil self.Current.X = 0 self.Current.Y = 0 self.rootNode = nil self.attached = false end function Blocker:ActiveCount() return table.getn(self.active) end function Blocker:setActive(block) for _,v in ipairs(self.active) do if v.tag == block.tag then return end end table.insert(self.active, block) block.active = true end function Blocker:Add(...) if self.attached and self.rootNode ~= nil then local nbs = {} local y = self.Current.Y for _,v in ipairs({...}) do local a = am.translate(0,y):tag(v.tag) ^v:nodeGroup() table.insert(nbs, a) self:setActive(v) y = y - v:height() end for _,v in pairs(nbs) do self.rootNode:append(v) end self.Current.Y = y end end local function removal(n, t) for i, v in ipairs(t) do if n.tag == v.tag then n.active = false table.remove(t, i) end end end function Blocker:Remove(...) if self.attached and self.rootNode ~= nil then for _,v in ipairs({...}) do removal(v, self.active) end self.rootNode:remove_all() self.Current.X = 0 self.Current.Y = 0 self:Add(unpack(self.active)) end end class"OSDI" ("system") local defaultBlocks = { Block( "AM_BLOCK", "t", Item("am_version", noder, "KeyValue", function() return am.version end), Item("am_platform", noder,"KeyValue", function() return am.platform end), Item("am_language", noder, "KeyValue", function() return am.language() end) ), --Block( -- "TIME_BLOCK", -- "", -- Item("os_clock", noder, "KeyValue", function() return os.clock() end), -- Item("os_time", noder, "KeyValue", function() return os.time() end), -- Item("date", noder, "KeyValue", function() return os.date() end), -- Item("window_time", noder, "KeyValue", function() return am.current_time() end) --), Block( "TIME_BLOCK_UPDATING", "t", Item("os_clock", noder, "UpdatingKeyValue", function() return os.clock() end), Item("os_time", noder, "UpdatingKeyValue", function() return os.time() end), Item("date", noder, "UpdatingKeyValue", function() return os.date() end), Item("window_time", noder, "UpdatingKeyValue", function() return am.current_time() end) ), --Block( -- "FRAME", -- "", -- Item("frame_time", noder, "KeyValue", function() return am.frame_time end), -- Item("delta_time", noder, "KeyValue", function() return am.delta_time end) --), Block( "FRAME_UPDATING", "t", Item("frame_time", noder, "UpdatingKeyValue", function() return am.frame_time end), Item("delta_time", noder, "UpdatingKeyValue", function() return am.delta_time end) ), --Block( -- "FPS", -- "", -- Item("avg_fps", noder, "KeyValue", function() local p = am.perf_stats();return p.avg_fps end), -- Item("min_fps", noder, "KeyValue", function() local p = am.perf_stats();return p.min_fps end) --), Block( "FPS_UPDATING", "t", Item("avg_fps", noder, "UpdatingKeyValue", function() local p = am.perf_stats();return p.avg_fps end), Item("min_fps", noder, "UpdatingKeyValue", function() local p = am.perf_stats();return p.min_fps end) ), } function OSDI:OSDI() system.system(self) self.ui = true self.widgets = true self.noder = Noder() self.blocks = defaultBlocks self.root = am.translate(0,0):tag("on-screen-debugging-display") end local function blockFn(root, blocker, block) local function blkrAttach(root, blocker) if not blocker.attached then blocker:Attach(root) end end local function blkrDetach(root, blocker) if blocker.attached and blocker:ActiveCount() < 1 then blocker:Detach(root) end end return function() blkrAttach(root, blocker) if not block.active then blocker:Add(block) return end if block.active then blocker:Remove(block) blkrDetach(root, blocker) return end end end function OSDI:Init(world, broker) local ev = Eventer() self.eventer = ev local events = {} local subscriptions = {} local blocker = Blocker("debugger", {X=0, Y=0}) -- Blocker("debugger", {X=w.left+10, Y=w.top-10}) for i, v in ipairs(self.blocks) do table.insert(subscriptions, "KEYBOARD_PRESSED_" .. v.button) table.insert(events, Event(v.button, blockFn(self.root, blocker, v))) end ev:Set(events) broker:Subscribe(self, subscriptions) end function OSDI:process(dt, mouse, left, right) local evs = self:GetBulk() for k, v in pairs(evs) do self.eventer:Execute(v) end end
-- include useful files u_execDependencyScript("ohvrvanilla", "base", "vittorio romeo", "utils.lua") u_execDependencyScript("ohvrvanilla", "base", "vittorio romeo", "common.lua") u_execDependencyScript("ohvrvanilla", "base", "vittorio romeo", "commonpatterns.lua") u_execDependencyScript("ohvrvanilla", "base", "vittorio romeo", "nextpatterns.lua") u_execDependencyScript("ohvrvanilla", "base", "vittorio romeo", "evolutionpatterns.lua") -- this function adds a pattern to the timeline based on a key function addPattern(mKey) if mKey == 0 then pAltBarrage(u_rndInt(1, 3), 2) elseif mKey == 1 then pMirrorSpiral(u_rndInt(2, 4), 0) elseif mKey == 2 then pBarrageSpiral(u_rndInt(0, 3), 1, 1) elseif mKey == 3 then pBarrageSpiral(u_rndInt(0, 2), 1.2, 2) elseif mKey == 4 then pBarrageSpiral(2, 0.7, 1) elseif mKey == 5 then pInverseBarrage(0) elseif mKey == 6 then hmcDefBarrageSpiral() elseif mKey == 7 then pMirrorWallStrip(1, 0) elseif mKey == 8 then hmcDefSpinner() elseif mKey == 9 then hmcDefBarrage() elseif mKey == 10 then hmcDef2Cage() elseif mKey == 11 then hmcDefBarrageSpiralSpin() end end -- shuffle the keys, and then call them to add all the patterns -- shuffling is better than randomizing - it guarantees all the patterns will be called keys = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 10, 8, 8, 9, 9, 9, 9, 6, 11, 11, 10, 10 } shuffle(keys) index = 0 achievementUnlocked = false specials = { "cage", "spinner", "barrage" } special = "none" -- onInit is an hardcoded function that is called when the level is first loaded function onInit() l_setSpeedMult(1.7) l_setSpeedInc(0.15) l_setSpeedMax(2.9) l_setRotationSpeed(0.1) l_setRotationSpeedMax(0.415) l_setRotationSpeedInc(0.035) l_setDelayMult(1.2) l_setDelayInc(0.0) l_setFastSpin(0.0) l_setSides(6) l_setSidesMin(6) l_setSidesMax(6) l_setIncTime(15) l_setPulseMin(77) l_setPulseMax(95) l_setPulseSpeed(1.937) l_setPulseSpeedR(0.524) l_setPulseDelayMax(13.05) l_setPulseInitialDelay(28.346) -- skip a beat to match with the clap l_setBeatPulseMax(17) l_setBeatPulseDelayMax(28.346) l_setSwapEnabled(true) l_addTracked("special", "special") end -- onLoad is an hardcoded function that is called when the level is started/restarted function onLoad() end -- onStep is an hardcoded function that is called when the level timeline is empty -- onStep should contain your pattern spawning logic function onStep() if special == "none" then addPattern(keys[index]) index = index + 1 if index - 1 == #keys then index = 1 shuffle(keys) end elseif special == "cage" then addPattern(10) elseif special == "spinner" then addPattern(8) elseif special == "barrage" then addPattern(9) end end -- onIncrement is an hardcoded function that is called when the level difficulty is incremented function onIncrement() shuffle(specials) if special == "none" then special = specials[1] e_messageAddImportant("Special: "..special, 120) else special = "none" end end -- onUnload is an hardcoded function that is called when the level is closed/restarted function onUnload() end -- onUpdate is an hardcoded function that is called every frame function onUpdate(mFrameTime) if not achievementUnlocked and l_getLevelTime() > 90 and u_getDifficultyMult() >= 1 then steam_unlockAchievement("a12_disco") achievementUnlocked = true end end
function lt.constant(value) function f(iter) return value end return f end --[[ Used to decay the learning rate. This schedule is advocated by Leon Bottou in "Stochastic Gradient Descent Tricks". --]] function lt.gentle_decay(init, decay) function f(iter) return init / (1 + iter * decay) end return f end --[[ Used to decay momentum. See "On the importance of initialization and momentum in deep learning", by Sutskever et al., for the reasoning behind why this schedule is used. --]] function lt.sutskever_blend(max, stretch) stretch = stretch or 250 function f(iter) return math.min(1 - math.pow(2, -1 - math.log( math.floor(iter / stretch) + 1, 2)), max) end return f end
ENT.Type = "brush" function ENT:Initialize() -- ParticleEffectAttach("portal_cleanser",PATTACH_ABSORIGIN,self,1) self:SetTrigger(true) end function ENT:Touch( ent ) end function ENT:StartTouch( ent ) if ent:IsPlayer() and ent:Alive() then plyweap = ent:GetActiveWeapon() if IsValid( plyweap ) and plyweap:GetClass() == "weapon_portalgun" and plyweap.CleanPortals then plyweap:CleanPortals() end elseif ent and ent:IsValid() then if ent:GetClass()=="projectile_portal_ball" then //portal ball projectile. local ang = ent:GetAngles() ang:RotateAroundAxis(ent:GetForward(),90) ang.y = self:GetAngles().y+90 ParticleEffect("portal_"..ent:GetNWInt("Kind",1).."_cleanser",ent:GetPos(),ang) ent:Remove() else if ent:GetName() != "dissolveme" then local vel = ent:GetVelocity() local fakebox = ents.Create( "prop_physics" ) fakebox:SetModel(ent:GetModel()) fakebox:SetPos(ent:GetPos()) fakebox:SetAngles(ent:GetAngles()) fakebox:Spawn() fakebox:Activate() fakebox:SetSkin(ent:GetSkin()) fakebox:SetName("dissolveme") local phys = fakebox:GetPhysicsObject() if phys:IsValid() then phys:EnableGravity(false) phys:Wake() phys:SetVelocity(vel/10) end ent:Remove() local dissolver = ents.Create( "env_entity_dissolver" ) dissolver:SetKeyValue( "dissolvetype", 0 ) dissolver:SetKeyValue( "magnitude", 0 ) dissolver:Spawn() dissolver:Activate() dissolver:Fire("Dissolve","dissolveme",0) dissolver:Fire("kill","",0.1) end end end end function ENT:EndTouch( ent ) end
local SCREEN_WIDTH = 640 local SCREEN_HEIGHT = 480 local BLUE = "blue" local RED = "red" local GREEN = "green" local COLOR_COUNT = 3 local TO_RIGHT = 1 local TO_LEFT = -1 local CORRECT = "correct" local WRONG = "wrong" local CODES_IN_PROD_DISPLAY_SIZE = 5 local TILE_DIMENSION = 32 local MARGIN = 10 local PLAYER_BASELINE = SCREEN_HEIGHT - 170 local SPAWN_SEQUENCE_DELAY_SEC= 1 local player1 = { specs = { red = {}, green = {}, blue = {} }, codes = {}, codingDirection = TO_RIGHT, spawnTimer = 0 } local player2 = { specs = { red = {}, green = {}, blue = {} }, codes = {}, codingDirection = TO_LEFT, spawnTimer = 0 } local codesInProd = {} local specImages = {} local codeImages = {} local scores = { implemented = 0, bugs = 0 } function love.load() math.randomseed(os.time()) love.window.setMode(SCREEN_WIDTH, SCREEN_HEIGHT) love.window.setTitle("ⓒⓞⓓⓔⓣⓡⓘⓢ") specImages[RED] = love.graphics.newImage("images/rosso.png") specImages[GREEN] = love.graphics.newImage("images/bene.png") specImages[BLUE] = love.graphics.newImage("images/azzurro.png") codeImages[CORRECT] = love.graphics.newImage("images/bene.png") codeImages[WRONG] = love.graphics.newImage("images/antibene.png") playerImage = love.graphics.newImage("images/sviluppatore.png") end function love.draw() drawInstructions() drawScoreboard(scores) drawProd(codesInProd, codeImages) drawThings(combineTables(player1.specs[RED], player1.specs[GREEN], player1.specs[BLUE], player2.specs[RED], player2.specs[GREEN], player2.specs[BLUE]), specImages) drawThings(combineTables(player1.codes, player2.codes), codeImages) drawImage(playerImage, 26, PLAYER_BASELINE) drawImage(playerImage, SCREEN_WIDTH - 26, PLAYER_BASELINE, 0, -1) end function love.update(dt) moveSpecs(player1, player2, dt) moveSpecs(player2, player1, dt) moveCodes(player1, dt) moveCodes(player2, dt) spawnSpecIfTimeIsRight(player1, MARGIN, dt) spawnSpecIfTimeIsRight(player2, SCREEN_WIDTH - (3 * TILE_DIMENSION) - MARGIN, dt) end function love.keypressed(key) if key == "z" then handleCoding(RED, player1, player2) end if key == "x" then handleCoding(GREEN, player1, player2) end if key == "c" then handleCoding(BLUE, player1, player2) end if key == "lshift" then handleReject(player1) end if key == "b" then handleCoding(RED, player2, player1) end if key == "n" then handleCoding(GREEN, player2, player1) end if key == "m" then handleCoding(BLUE, player2, player1) end if key == "rshift" then handleReject(player2) end end function drawThings(things, thingImages) for _, thing in ipairs(things) do drawImage(thingImages[thing.image], thing.xPos, thing.yPos) end end function drawImage(image, x, y, r, sx, sy) r = r or 0 sx = sx or 1 sy = sy or 1 love.graphics.draw(image, x, y, r, sx, sy) end function moveSpecs(coder, reviewer, dt) for key, coloredSpecs in pairs(coder.specs) do for index, spec in ipairs(coloredSpecs) do updateLocation(spec, dt) if isNoMoreCodable(spec) then table.remove(coloredSpecs, index) table.insert(reviewer.codes, createCode(false, coder.codingDirection)) end end end -- for i=1, COLOR_COUNT, 1 do -- indexColor = getColorFromNumber(i) -- for index, spec in ipairs(coder.specs[indexColor]) do -- updateLocation(spec, dt) -- if isNoMoreCodable(spec) then -- table.remove(coder.specs[indexColor], index) -- table.insert(reviewer.codes, createCode(false, coder.codingDirection)) -- end -- end -- end end function moveCodes(coder, dt) for index, code in ipairs(coder.codes) do updateLocation(code, dt) if isRejectable(code) then publishtoProd(code.image, codesInProd, scores) table.remove(coder.codes, index) end end end function spawnSpecIfTimeIsRight(player, location, dt) if player.spawnTimer > 0 then player.spawnTimer = player.spawnTimer - dt else createSpec(player, location) player.spawnTimer = SPAWN_SEQUENCE_DELAY_SEC end end function updateLocation(thing, dt) thing.yPos = thing.yPos + dt * thing.speedY thing.xPos = thing.xPos + dt * thing.speedX end function createSpec(player, xPos) colorIndex = math.random(COLOR_COUNT) color = getColorFromNumber(colorIndex) spec = { xPos = xPos + colorIndex * TILE_DIMENSION - TILE_DIMENSION, yPos = -10, speedY = 100, speedX = 0, image = color, width = TILE_DIMENSION, height = TILE_DIMENSION } table.insert(player.specs[color], spec) end function getColorFromNumber(num) if num == 1 then return RED elseif num == 2 then return GREEN else return BLUE end end function createCode(isCorrect, direction) local correctness = WRONG if isCorrect then correctness = CORRECT end if direction == TO_RIGHT then xPos = MARGIN + TILE_DIMENSION yPos = PLAYER_BASELINE else xPos = SCREEN_WIDTH - MARGIN - 2 * TILE_DIMENSION yPos = PLAYER_BASELINE + TILE_DIMENSION end return { xPos = xPos, yPos = yPos, speedY = 0, speedX = 100 * direction, image = correctness, width = TILE_DIMENSION, height = TILE_DIMENSION } end function isNoMoreCodable(thing) return thing.yPos > PLAYER_BASELINE end function isRejectable(thing) return thing.xPos < MARGIN + TILE_DIMENSION or thing.xPos > SCREEN_WIDTH - MARGIN - 2 * TILE_DIMENSION end function handleCoding(color, coder, reviewer) if noSpecsToCode(coder) then return end if table.getn(coder.specs[color]) > 0 and color == coder.specs[color][1].image then table.insert(reviewer.codes, createCode(true, coder.codingDirection)) else table.insert(reviewer.codes, createCode(false, coder.codingDirection)) end table.remove(coder.specs[color], 1) coder.spawnTimer = SPAWN_SEQUENCE_DELAY_SEC / 3 end function noSpecsToCode(coder) return table.getn(coder.specs[BLUE]) == 0 and table.getn(coder.specs[RED]) == 0 and table.getn(coder.specs[GREEN]) == 0 end function handleReject(player) if table.getn(player.codes) > 0 then table.remove(player.codes, 1) end end function combineTables(...) combined = {} for i, t in pairs{...} do for _, value in ipairs(t) do table.insert(combined, value) end end return combined end function drawInstructions() local leftPadding = 200 love.graphics.print('player 1', leftPadding, 20) love.graphics.print('z = red, x = greeb, c = blue', leftPadding, 40) love.graphics.print('lshift = reject', leftPadding, 60) love.graphics.print('player 2', leftPadding, 100) love.graphics.print('b = red, n = green, m = blue', leftPadding, 120) love.graphics.print('rshift = reject', leftPadding, 140) end function drawScoreboard(scores) love.graphics.print('Implemented ' .. scores.implemented, 200, 180) love.graphics.print('Bugs ' .. scores.bugs, 200, 200) end function publishtoProd(isCorrect, codesInProd, scores) if isCorrect == CORRECT then scores.implemented = scores.implemented + 1 else scores.bugs = scores.bugs + 1 end table.insert(codesInProd, isCorrect) if #codesInProd > CODES_IN_PROD_DISPLAY_SIZE then table.remove(codesInProd, 1) end end function drawProd(codesInProd, images) for i = #codesInProd, 1, -1 do xPos = 450 - i * (TILE_DIMENSION + MARGIN) drawImage(images[codesInProd[i]], xPos, SCREEN_HEIGHT - 40) end end
function ISatyr_OnEnterCombat(Unit,Event) if Unit:GetHealthPct() == 97 then Unit:FullCastSpellOnTarget(38048,Unit:GetClosestPlayer()) end end RegisterUnitEvent(21656, 1, "ISatyr_OnEnterCombat")
---@class Ability Ability = {} ---@class AbilityBlueprint AbilityBlueprint = {} ---@class ActorID ActorID = {} ---@class Ai Ai = {} ---@class AIEncounter AIEncounter = {} ---@class AITacticType AITacticType = {} ---@class AllianceResult AllianceResult = {} ---@class Availability Availability = {} ---@class blipID blipID = {} ---@class Blueprint Blueprint = {} ---@class BuildingFireState BuildingFireState = {} ---@class ButtonIconStyle ButtonIconStyle = {} ---@class CamouflageStanceID CamouflageStanceID = {} ---@class CapType CapType = {} ---@class CheckHiddenType CheckHiddenType = {} ---@class checkID checkID = {} ---@class CriticalID CriticalID = {} ---@class CrushMode CrushMode = {} ---@class CueStyleID CueStyleID = {} ---@class DialogResult DialogResult = {} ---@class EGroup EGroup = {} ---@class ElementID ElementID = {} ---@class encID encID = {} ---@class Encounter Encounter = {} ---@class EncounterData EncounterData = {} ---@class Entity Entity = {} ---@class ErrorMessage ErrorMessage = {} ---@class event event = {} ---@class EVENT EVENT = {} ---@class EventCueID EventCueID = {} ---@class EventID EventID = {} ---@class FactionID FactionID = {} ---@class filtertype filtertype = {} ---@class GameEventType GameEventType = {} ---@class GD GD = {} ---@class GoalData GoalData = {} ---@class HintPointActionType HintPointActionType = {} ---@class HintPointID HintPointID = {} ---@class HPAT HPAT = {} ---@class HUDFeatureType HUDFeatureType = {} ---@class ID ID = {} ---@class Item Item = {} ---@class LabelAlignHorizontal LabelAlignHorizontal = {} ---@class LabelAlignVertical LabelAlignVertical = {} ---@class LocString LocString = {} ---@class Lua Lua = {} ---@class Marker Marker = {} ---@class ModID ModID = {} ---@class Modifier Modifier = {} ---@class ModifierApplicationType ModifierApplicationType = {} ---@class ModifierUsageType ModifierUsageType = {} ---@class MoveTypeBlueprint MoveTypeBlueprint = {} ---@class ObjectiveID ObjectiveID = {} ---@class ObjectiveState ObjectiveState = {} ---@class ObjectiveType ObjectiveType = {} ---@class Offset Offset = {} ---@class OpportunityID OpportunityID = {} ---@class OwnerType OwnerType = {} ---@class PingID PingID = {} ---@class Player Player = {} ---@class PrintOnScreenID PrintOnScreenID = {} ---@class ProductionItemType ProductionItemType = {} ---@class PropertyBagGroup PropertyBagGroup = {} ---@class ProximityType ProximityType = {} ---@class ProxType ProxType = {} ---@class RaceID RaceID = {} ---@class ResourceAmount ResourceAmount = {} ---@class ResourceType ResourceType = {} ---@class ScarAbilityPBG ScarAbilityPBG = {} ---@class ScarCamouflageStancePBG ScarCamouflageStancePBG = {} ---@class ScarCriticalPBG ScarCriticalPBG = {} ---@class ScarEntityPBG ScarEntityPBG = {} ---@class ScarMarker ScarMarker = {} ---@class ScarMoveTypePBG ScarMoveTypePBG = {} ---@class ScarPosition ---@field public x number ---@field public y number ---@field public z number ScarPosition = {} ---@class ScarRacePBG ScarRacePBG = {} ---@class ScarSlotItemPBG ScarSlotItemPBG = {} ---@class ScarSquadPBG ScarSquadPBG = {} ---@class ScarType ScarType = {} ---@class ScarUpgradePBG ScarUpgradePBG = {} ---@class ScarWeaponPBG ScarWeaponPBG = {} ---@class SectorID SectorID = {} ---@class SGroup SGroup = {} ---@class SlotItemID SlotItemID = {} ---@class Squad Squad = {} ---@class SquadBlueprint SquadBlueprint = {} ---@class SyncWeaponID SyncWeaponID = {} ---@class TargetPreference TargetPreference = {} ---@class TuningValue TuningValue = {} ---@class Type Type = {} ---@class UIEventType UIEventType = {} ---@class UIMode UIMode = {} ---@class UpgradeBlueprint UpgradeBlueprint = {} ---@class UpgradeID UpgradeID = {} ---@class world world = {} --- E-mails a warning out with logfiles at the end of the game. ---@param errormessage ErrorMessage function bug(errormessage) end --- Clears the direct draw frame. ---@param frame string function dr_clear(frame) end --- Draws a 2D circle on the screen. ---@param frame string ---@param x number ---@param y number ---@param z number ---@param radius number ---@param red integer ---@param green integer ---@param blue integer function dr_drawCircle(frame, x, y, z, radius, red, green, blue) end --- Draws a 2D line on the screen. ---@param start ScarPosition ---@param _end ScarPosition ---@param red integer ---@param green integer ---@param blue integer ---@param frame string function dr_drawline(start, _end, red, green, blue, frame) end --- Sets the auto-clear interval of a frame. 0 is infinite. ---@param frame string ---@param interval number function dr_setautoclear(frame, interval) end --- Sets the visibility of a frame. ---@param frame string ---@param isVisible boolean function dr_setdisplay(frame, isVisible) end --- Draws a circle on the terrain. Accuracy controls number of points on the circle perimeter. Minimum is 3, which results in a triangle. ---@param origin ScarPosition ---@param radius number ---@param red integer ---@param green integer ---@param blue integer ---@param accuracy integer ---@param frame string function dr_terraincircle(origin, radius, red, green, blue, accuracy, frame) end --- Unknown functionality because of lack of frame argument. ---@param origin ScarPosition ---@param unknown_1 number ---@param unknown_2 number ---@param red integer ---@param green integer ---@param blue integer ---@param unknown_3 number function dr_terrainrect(origin, unknown_1, unknown_2, red, green, blue, unknown_3) end --- Draws text on the screen. ---@param frame string ---@param x number ---@param y number ---@param text string ---@param red integer ---@param green integer ---@param blue integer function dr_text2d(frame, x, y, text, red, green, blue) end --- Draws text on the screen (3D). ---@param frame string ---@param x number ---@param y number ---@param z number ---@param text string ---@param red integer ---@param green integer ---@param blue integer function dr_text3d(frame, x, y, z, text, red, green, blue) end --- Throws an error to lua and print out the error message ---@param state any ---@return integer function fatal(state) end --- Imports a script file ---@param file string function import(file) end --- Dump content of inventory to a file function inv_dump() end --- Loads a nis file for playing. ---@param nisFile string function nis_load(nisFile) end --- Pauses the NIS animation. function nis_pause() end --- function nis_play() end --- Sets the number of seconds it takes to transition from game to nis, 0 is instantaneous ---@param numSeconds number function nis_setintransitiontime(numSeconds) end --- function nis_setnextnis() end --- Lets the nis system know which nis will be transitioned to when the first one ends. ---@param filename string function nis_setouttransitionnis(filename) end --- Sets the number of seconds it takes to transition from nis back to game, 0 is instantaneous ---@param numSeconds number function nis_setouttransitiontime(numSeconds) end --- function nis_settime() end --- function nis_skip() end --- function nis_skipone() end --- Stops playing the NIS animation. function nis_stop() end --- function nis_synchelp() end --- Returns the ScarType of the value. ---@param value any ---@return ScarType function scartype(value) end --- Returns the string representation of the ScarType of the value. ---@param value any ---@return string function scartype_tostring(value) end --- ?? function statgraph() end --- ?? ---@param channel string function statgraph_channel(channel) end --- ?? ---@param channel string ---@return boolean function statgraph_channel_get_enabled(channel) end --- ?? ---@param channel string ---@param enable boolean function statgraph_channel_set_enabled(channel, enable) end --- ?? function statgraph_clear() end --- ?? function statgraph_list() end --- ?? function statgraph_pause() end --- ---@param message string function warning(message) end --- Plays the next intel event in the debug queue. IntelEvents are played sequentially as they are defined in a mission's .events file. ---@param UnknownType any function _IntelDebugNext(UnknownType) end --- Plays the next intel event in the debug queue. IntelEvents are played sequentially as they are defined in a mission's .events file. ---@param UnknownType any function _IntelDebugPrev(UnknownType) end --- Replays the last intel event that was debugged. ---@param UnknownType any function _IntelDebugReplay(UnknownType) end --- Clear ties between an actor and any units ---@param actor table function Actor_Clear(actor) end --- Plays a speech event for a given actor WITH a portrait and subtitle ---@param actor table ---@param locID integer ---@param continueButton boolean ---@param stickySubtitle boolean ---@param blockInput boolean ---@overload fun(actor: table, locID: integer) ---@overload fun(actor: table, locID: integer, continueButton: boolean) ---@overload fun(actor: table, locID: integer, continueButton: boolean, stickySubtitle: boolean) function Actor_PlaySpeech(actor, locID, continueButton, stickySubtitle, blockInput) end --- Plays a speech event for a given actor WITHOUT a portrait or subtitle. See Actor_PlaySpeech for more details ---@param actor table ---@param locID integer ---@param continueButton boolean ---@param stickySubtitle boolean ---@param blockInput boolean ---@overload fun(actor: table, locID: integer) ---@overload fun(actor: table, locID: integer, continueButton: boolean) ---@overload fun(actor: table, locID: integer, continueButton: boolean, stickySubtitle: boolean) function Actor_PlaySpeechWithoutPortrait(actor, locID, continueButton, stickySubtitle, blockInput) end --- Tie an entire sgroup to an actor, so audio comes from a squad member ---@param actor table ---@param sgroup SGroup function Actor_SetFromSGroup(actor, sgroup) end --- Tie a single squad to an actor, so audio comes from a squad member ---@param actor table ---@param squad Squad function Actor_SetFromSquad(actor, squad) end --- Finds all encounters that contain ANY or ALL squads within the given sgroup. ---@param sgroup SGroup ---@param all any|boolean ---@return table function Ai:GetEncountersBySGroup(sgroup, all) end --- Finds all encounters that contain ANY or ALL squads within the given sgroup. ---@param sgroup SGroup ---@param all any|boolean ---@return table function Ai:GetEncountersBySquad(sgroup, all) end --- This clears the importance bonus on this capture point ---@param pPlayer Player ---@param pEntity Entity function AI_ClearCaptureImportanceBonus(pPlayer, pEntity) end --- This clears the importance override on this military point ---@param pPlayer Player ---@param pEntity Entity function AI_ClearImportance(pPlayer, pEntity) end --- Create a new objective for player ---@param pPlayer Player ---@param objectiveType integer ---@return table function AI_CreateObjective(pPlayer, objectiveType) end --- Enables/disables debugging of AI Attack Objective Encounter Position Scoring ---@param enable boolean function AI_DebugAttackEncounterPositionScoringEnable(enable) end --- Returns true if AI Attack Objective Encounter Position Scoring is enabled ---@return boolean function AI_DebugAttackEncounterPositionScoringIsEnabled() end --- Enables/disables AI Lua Debugging ---@param enable boolean function AI_DebugLuaEnable(enable) end --- Returns true if AI Lua Debugging is enabled ---@return boolean function AI_DebugLuaIsEnabled() end --- Enables/disables AI Construction Debugging ---@param enable boolean function AI_DebugRatingEnable(enable) end --- Returns true if AI Construction Debugging is enabled ---@return boolean function AI_DebugRatingIsEnabled() end --- Enables/disables AI Rendering of All Task Children ---@param enable boolean function AI_DebugRenderAllTaskChildrenEnable(enable) end --- Returns true if AI Rendering of All Task Children is enabled ---@return boolean function AI_DebugRenderAllTaskChildrenIsEnabled() end --- Enables/disables AI Skirmish Capture Debugging ---@param enable boolean function AI_DebugSkirmishCaptureEnable(enable) end --- Returns true if AI Skirmish Capture Debugging is enabled ---@return boolean function AI_DebugSkirmishCaptureIsEnabled() end --- Enables/disables AI Skirmish Combat Target Debugging ---@param enable boolean function AI_DebugSkirmishCombatTargetEnable(enable) end --- Returns true if AI Skirmish Combat Target Debugging is enabled ---@return boolean function AI_DebugSkirmishCombatTargetIsEnabled() end --- Enables/disables AI Skirmish Objective Debugging ---@param enable boolean function AI_DebugSkirmishObjectiveEnable(enable) end --- Returns true if AI Skirmish Objective Debugging is enabled ---@return boolean function AI_DebugSkirmishObjectiveIsEnabled() end --- Disable all of the economy overrides for the AI player ---@param pPlayer Player function AI_DisableAllEconomyOverrides(pPlayer) end --- Disables all encounters function AI_DisableAllEncounters() end --- Enables or Disables an AI player ---@param pPlayer Player ---@param enable boolean function AI_Enable(pPlayer, enable) end --- Enables or Disables all AI players ---@param enable boolean function AI_EnableAll(enable) end --- Enables all encounters function AI_EnableAllEncounters() end --- Enable or disable the economy override for the AI player ---@param pPlayer Player ---@param overrideName string ---@param enable boolean function AI_EnableEconomyOverride(pPlayer, overrideName, enable) end --- Returns a table with all active (not dead) encounters. ---@return table function AI_GetActiveEncounters() end --- Gets the difficulty level of this AI player ---@param pPlayer Player ---@return integer function AI_GetDifficulty(pPlayer) end --- Returns the number of alive encounters currently managed by the AI manager. ---@return integer function AI_GetNumEncounters() end --- Get the personality name of this AI player ---@param pPlayer Player ---@return string function AI_GetPersonality(pPlayer) end --- Get the personality lua file name of this AI player ---@param pPlayer Player ---@return string function AI_GetPersonalityLuaFileName(pPlayer) end --- Returns true if player is an AI player ---@param pPlayer Player ---@return boolean function AI_IsAIPlayer(pPlayer) end --- Returns true if player is a AIPlayer and is enabled ---@param pPlayer Player ---@return boolean function AI_IsEnabled(pPlayer) end --- Returns True if the current AI_Manager difficulty matches any in a given list. ---@param difficultyList integer|table ---@return boolean function AI_IsMatchingDifficulty(difficultyList) end --- Locks the entity and disables its tactics (if any) and the AI will no longer use this object ---@param pPlayer Player ---@param pEntity Entity function AI_LockEntity(pPlayer, pEntity) end --- Locks the squad and disables its tactics (if any) and the AI will no longer use this object ---@param pPlayer Player ---@param pSquad Squad function AI_LockSquad(pPlayer, pSquad) end --- Locks the squads and disables its tactics (if any) and the AI will no longer use these objects ---@param pPlayer Player ---@param squads SGroup function AI_LockSquads(pPlayer, squads) end --- Overrides the current difficulty setting (only for the AI Manager). Pass 'nil' to reset to Game_GetSPDifficulty() value ---@param level integer function AI_OverrideDifficulty(level) end --- Disables all encounters, then clears out the encounter list function AI_RemoveAllEncounters() end --- Restores the default personality and difficulty settings of this AI player ---@param pPlayer Player function AI_RestoreDefaultPersonalitySettings(pPlayer) end --- This sets importance bonus of the given capture point ---@param pPlayer Player ---@param pEntity Entity ---@param importanceBonus number function AI_SetCaptureImportanceBonus(pPlayer, pEntity, importanceBonus) end --- Set the level of debug information shown but Ai:Print(). function AI_SetDebugLevel() end --- Set the difficulty level of this AI player ---@param pPlayer Player ---@param difficultyLevel integer function AI_SetDifficulty(pPlayer, difficultyLevel) end --- This overrides the default importance of the given military point ---@param pPlayer Player ---@param pEntity Entity ---@param importance number function AI_SetImportance(pPlayer, pEntity, importance) end --- Set the personality name of this AI player ---@param pPlayer Player ---@param personalityName string function AI_SetPersonality(pPlayer, personalityName) end --- Sets the delay to use when using staggeredSpawn for encounters. The new interval will take effect immediately. ---@param delay number function AI_SetStaggeredSpawnDelay(delay) end --- Toggle encounter/goal debug information on screen. function AI_ToggleDebugData() end --- Toggle printing console debug information for encounters. function AI_ToggleDebugPrint() end --- Unlocks all designer locked squads for player ---@param pPlayer Player function AI_UnlockAll(pPlayer) end --- Unlocks this entity so that AI can use it again ---@param pPlayer Player ---@param pEntity Entity function AI_UnlockEntity(pPlayer, pEntity) end --- Unlocks the given squad so the AI can use it again ---@param pPlayer Player ---@param pSquad Squad function AI_UnlockSquad(pPlayer, pSquad) end --- Locks the squads and disables its tactics (if any) and the AI will no longer use these objects ---@param pPlayer Player ---@param squads SGroup function AI_UnlockSquads(pPlayer, squads) end --- Re-updates the AI in regards to all the static objects in the world (if SCAR creates new strategic points dynamically this will need to be called) ---@param pPlayer Player function AI_UpdateStatics(pPlayer) end --- Adjust default goal data for ability goals. Sets the default GoalData to the current defaults plus additionalDefaultGoalData; any values specified are used for unspecified encounter ability goal values. ---@param additionalDefaultGoalData table function AIAbilityGoal_AdjustDefaultGoalData(additionalDefaultGoalData) end --- Set default goal data for ability goals. defaultGoalData is cloned; any values specified are used for unspecified encounter ability goal values. ---@param defaultGoalData table function AIAbilityGoal_SetDefaultGoalData(defaultGoalData) end --- Set modify goal data for ability goals. modifyGoalData is cloned; values specified via keyname_Multiplier are used for the numeric keyname encounter ability goal value. ---@param modifyGoalData table function AIAbilityGoal_SetModifyGoalData(modifyGoalData) end --- Set override goal data for ability goals. overrideGoalData is cloned; any values specified are used for encounter ability goal values. ---@param overrideGoalData table function AIAbilityGoal_SetOverrideGoalData(overrideGoalData) end --- Set ability for ability objective ---@param pObjective table ---@param abilityPBG PropertyBagGroup function AIAbilityObjective_AbilityGuidance_SetAbilityPBG(pObjective, abilityPBG) end --- Adjust default goal data for attack goals. Sets the default GoalData to the current defaults plus additionalDefaultGoalData; any values specified are used for unspecified encounter attack goal values. ---@param additionalDefaultGoalData table function AIAttackGoal_AdjustDefaultGoalData(additionalDefaultGoalData) end --- Set default goal data for attack goals. defaultGoalData is cloned; any values specified are used for unspecified encounter attack goal values. ---@param defaultGoalData table function AIAttackGoal_SetDefaultGoalData(defaultGoalData) end --- Set modify goal data for attack goals. modifyGoalData is cloned; values specified via keyname_Multiplier are used for the numeric keyname encounter attack goal value. ---@param modifyGoalData table function AIAttackGoal_SetModifyGoalData(modifyGoalData) end --- Set override goal data for attack goals. overrideGoalData is cloned; any values specified are used for encounter attack goal values. ---@param overrideGoalData table function AIAttackGoal_SetOverrideGoalData(overrideGoalData) end --- Adjust default goal data. Sets the default GoalData to the current defaults plus additionalDefaultGoalData; any values specified are used for unspecified encounter goal values. ---@param additionalDefaultGoalData table function AIBaseGoal_AdjustDefaultGoalData(additionalDefaultGoalData) end --- Set default goal data. defaultGoalData is cloned; any values specified are used for unspecified encounter goal values. ---@param defaultGoalData table function AIBaseGoal_SetDefaultGoalData(defaultGoalData) end --- Set modify goal data. modifyGoalData is cloned; values specified via keyname_Multiplier are used for the numeric keyname encounter goal value. ---@param modifyGoalData table function AIBaseGoal_SetModifyGoalData(modifyGoalData) end --- Set override goal data. overrideGoalData is cloned; any values specified are used for encounter goal values. ---@param overrideGoalData table function AIBaseGoal_SetOverrideGoalData(overrideGoalData) end --- Adjust default goal data for defend goals. Sets the default GoalData to the current defaults plus additionalDefaultGoalData; any values specified are used for unspecified encounter defend goal values. ---@param additionalDefaultGoalData table function AIDefendGoal_AdjustDefaultGoalData(additionalDefaultGoalData) end --- Set default goal data for defend goals. defaultGoalData is cloned; any values specified are used for unspecified encounter defend goal values. ---@param defaultGoalData table function AIDefendGoal_SetDefaultGoalData(defaultGoalData) end --- Set modify goal data for defend goals. modifyGoalData is cloned; values specified via keyname_Multiply are used for the numeric keyname encounter defend goal value. ---@param modifyGoalData table function AIDefendGoal_SetModifyGoalData(modifyGoalData) end --- Set override goal data for defend goals. overrideGoalData is cloned; any values specified are used for encounter defend goal values. ---@param overrideGoalData table function AIDefendGoal_SetOverrideGoalData(overrideGoalData) end --- Adjust default goal data for move goals. Sets the default GoalData to the current defaults plus additionalDefaultGoalData; any values specified are used for unspecified encounter move goal values. ---@param additionalDefaultGoalData table function AIMoveGoal_AdjustDefaultGoalData(additionalDefaultGoalData) end --- Set default goal data for move goals. defaultGoalData is cloned; any values specified are used for unspecified encounter move goal values. ---@param defaultGoalData table function AIMoveGoal_SetDefaultGoalData(defaultGoalData) end --- Set modify goal data for move goals. modifyGoalData is cloned; values specified via keyname_Multiply are used for the numeric keyname encounter move goal value. ---@param modifyGoalData table function AIMoveGoal_SetModifyGoalData(modifyGoalData) end --- Set override goal data for move goals. overrideGoalData is cloned; any values specified are used for encounter move goal values. ---@param overrideGoalData table function AIMoveGoal_SetOverrideGoalData(overrideGoalData) end --- Ends the objective and deletes it. ---@param pObjective table function AIObjective_Cancel(pObjective) end --- Enables/disables squads in combat garrisoning. ---@param pObjective table ---@param enable boolean function AIObjective_CombatGuidance_EnableCombatGarrison(pObjective, enable) end --- Enables/disables allowing squads to retaliate against attacking enemies outside the allowed leash area ---@param pObjective table ---@param enable boolean function AIObjective_CombatGuidance_EnableRetaliateAttacks(pObjective, enable) end --- Sets the target area radius for the maximum range an enemy can be for a retaliate attack ---@param pObjective table ---@param radius number function AIObjective_CombatGuidance_SetRetaliateAttackTargetAreaRadius(pObjective, radius) end --- Add facing position to objective; used to determine good defensive setup positions. ---@param pObjective table ---@param pos ScarPosition function AIObjective_DefenseGuidance_AddFacingPosition(pObjective, pos) end --- Enables/disables idle squads garrisoning. ---@param pObjective table ---@param enable boolean function AIObjective_DefenseGuidance_EnableIdleGarrison(pObjective, enable) end --- Remove all facing positions from objective. ---@param pObjective table function AIObjective_DefenseGuidance_ResetFacingPositions(pObjective) end --- Enable / disable aggressive move into engagement area ---@param pObjective table ---@param enable boolean function AIObjective_EngagementGuidance_EnableAggressiveEngagementMove(pObjective, enable) end --- Enable objective to return to previous stages if they fail to meet conditions for current stage. ---@param pObjective table ---@param enable boolean function AIObjective_EngagementGuidance_SetAllowReturnToPreviousStages(pObjective, enable) end --- Enable coordinated arrival or setup of squads at engagement area. ---@param pObjective table ---@param enable boolean function AIObjective_EngagementGuidance_SetCoordinatedSetup(pObjective, enable) end --- Sets max time, in seconds, to accomplish objective, once the target is engaged. ---@param pObjective table ---@param seconds number function AIObjective_EngagementGuidance_SetMaxEngagementTime(pObjective, seconds) end --- Sets max time, in seconds, to remain idle at objective target, once engaged. ---@param pObjective table ---@param seconds number function AIObjective_EngagementGuidance_SetMaxIdleTime(pObjective, seconds) end --- Enable retreat to break supression. ---@param pObjective table ---@param enable boolean function AIObjective_FallbackGuidance_EnableRetreatOnPinned(pObjective, enable) end --- Enable retreat to break supression. ---@param pObjective table ---@param enable boolean function AIObjective_FallbackGuidance_EnableRetreatOnSuppression(pObjective, enable) end --- Set entities remaining threshold of encounter [0-N] to fallback at. ---@param pObjective table ---@param value number function AIObjective_FallbackGuidance_SetEntitiesRemainingThreshold(pObjective, value) end --- Set health threshold [0-1] to fallback at. ---@param pObjective table ---@param value number function AIObjective_FallbackGuidance_SetFallbackCapacityPercentage(pObjective, value) end --- Set health threshold [0-1] to fallback at. ---@param pObjective table ---@param value number function AIObjective_FallbackGuidance_SetFallbackCombatRatingPercentage(pObjective, value) end --- Set combat rating threshold of area [0-1] to fallback at. ---@param pObjective table ---@param value number function AIObjective_FallbackGuidance_SetFallbackSquadHealthPercentage(pObjective, value) end --- Set health threshold [0-1] to fallback at. ---@param pObjective table ---@param value number function AIObjective_FallbackGuidance_SetFallbackVehicleHealthPercentage(pObjective, value) end --- Set global fallback threshold (0.0f for individual squad). ---@param pObjective table ---@param value number function AIObjective_FallbackGuidance_SetGlobalFallbackPercentage(pObjective, value) end --- Set global retreat type (true for retreat; false for fallback). ---@param pObjective table ---@param value boolean function AIObjective_FallbackGuidance_SetGlobalFallbackRetreat(pObjective, value) end --- Set combat rating threshold of area [0-1] to fallback at. ---@param pObjective table ---@param value number function AIObjective_FallbackGuidance_SetRetreatCapacityPercentage(pObjective, value) end --- Set combat rating threshold of area [0-1] to fallback at. ---@param pObjective table ---@param value number function AIObjective_FallbackGuidance_SetRetreatCombatRatingPercentage(pObjective, value) end --- Set combat rating threshold of area [0-1] to fallback at. ---@param pObjective table ---@param value number function AIObjective_FallbackGuidance_SetRetreatHealthPercentage(pObjective, value) end --- Set fallback target. ---@param pObjective table ---@param pos ScarPosition function AIObjective_FallbackGuidance_SetTargetPosition(pObjective, pos) end --- Determines if objective is still valid. Must be true before calling any other of the AIObjective_* function. Return true if valid, false otherwise. ---@param pObjective table ---@return boolean function AIObjective_IsValid(pObjective) end --- Enable / disable aggressive movements on way to engagement targets ---@param pObjective table ---@param enable boolean function AIObjective_MoveGuidance_EnableAggressiveMove(pObjective, enable) end --- Reset preference for shorter paths on way to engagement targets, to defaults ---@param pObjective table function AIObjective_MoveGuidance_ResetPathingLengthFactor(pObjective) end --- Reset preference for safe movements on way to engagement targets, to defaults ---@param pObjective table function AIObjective_MoveGuidance_ResetSafePathingWeight(pObjective) end --- Set preference for shorter paths on way to engagement targets ---@param pObjective table ---@param weight number function AIObjective_MoveGuidance_SetPathingLengthFactor(pObjective, weight) end --- Set preference for safe movements on way to engagement targets ---@param pObjective table ---@param weight number function AIObjective_MoveGuidance_SetSafePathingWeight(pObjective, weight) end --- Set radius (follow distance) for coordinated move phase (<= 0 disables coordinated movement) ---@param pObjective table ---@param radius number function AIObjective_MoveGuidance_SetSquadCoherenceRadius(pObjective, radius) end --- Clears all notification callbacks for objective ---@param pObjective table function AIObjective_Notify_ClearCallbacks(pObjective) end --- Sets the failure notification callback for objective. ---@param pObjective table ---@param f function function AIObjective_Notify_SetFailureCallback(pObjective, f) end --- Sets the transition notification callback for objective. ---@param pObjective table ---@param f function function AIObjective_Notify_SetOnTransitionCallback(pObjective, f) end --- Sets the ID for the notification event sent out by objective ---@param pObjective table ---@param id integer function AIObjective_Notify_SetPlayerEventObjectiveID(pObjective, id) end
local api = trinium.api local DataMesh = api.DataMesh function api.initialize_inventory(inv, def) for k, v in pairs(def) do inv:set_size(k, v) end end function api.initializer(def0) return function(pos) local def = table.copy(def0) local meta = minetest.get_meta(pos) if def.formspec then meta:set_string("formspec", def.formspec) def.formspec = nil end api.initialize_inventory(meta:get_inventory(), def) end end function api.inv_to_itemmap(...) local map, inv = {}, {...} for _, v in pairs(inv) do for _, v1 in pairs(v) do local name, count = v1:get_name(), v1:get_count() if not map[name] then map[name] = 0 end map[name] = map[name] + count end end map[""] = nil return map end function api.get_item_identifier(stack) local s = stack:to_string():split(" ") if not s[1] then return nil end return s[1] .. (s[3] and " " .. table.concat(table.multi_tail(s, 2), " ") or "") end function api.count_stacks(inv, list, disallow_multi_stacks) local dm = DataMesh:new():data(inv:get_list(list)):filter(function(v) return not v:is_empty() end) if not disallow_multi_stacks then dm = dm:map(function(v) return v:get_name() end):unique() end return dm:count() end function api.formspec_escape_reverse(text) text = text:gsub("\\%[", "["):gsub("\\%]", "]"):gsub("\\\\", "\\"):gsub("\\,", ","):gsub("\\;", ";") return text end function api.merge_itemmaps(a, b) for k, v in pairs(b) do a[k] = (a[k] or 0) + v end end
-- Commands interface. A simple way to handle dispatching commands and parse -- arguments. -- -- This file is licensed under the BSD 2-Clause license. -- -- Copyright (c) 2016 Aaron Bolyard. local function perform_dispatch(self, ...) local command = select(1, ...) if command and #command > 1 then local func = self[string.lower(command)] if func then return pcall(func, select(2, ...)) end end return false, "command not found" end local M = {} -- Creates a command object. -- -- This object is callable, like a function. The first argument will be treated -- as the command name. The dispatch method will return a boolean value -- indicating success and any values returned by the invoked command. On error, -- the boolean value will be false and an error message will be returned. -- -- 't' should be a table that maps commands, represented as lower-case strings, -- to commands. These commands should be callable. -- -- Returns the command object. function M.create(t) return setmetatable(t or {}, { __call = perform_dispatch }) end -- Parses 'line' into separate arguments. -- -- Arguments are separated by whitespace. A quote character ('"') at the -- beginning of an argument will include all characters, including whitespace, -- until the next quote. -- -- Returns the arguments individually. function M.parse_arguments(line) local quoted_argument = '^%s*"(.-)"' local plain_argument = '^%s*([^%s]+)' local args = {} local is_done = false repeat local s, e, c -- Advances the position to 'e + 1' and adds the match, 'c', to the -- argument list. local function add_argument() table.insert(args, c) line = string.sub(line, e + 1) end -- Attempt quoted arguments first. -- -- The plain argument pattern can match quoted arguments, but quoted -- arguments cannot match plain arguments. s, e, c = string.find(line, quoted_argument) if s then add_argument() else s, e, c = string.find(line, plain_argument) if s then add_argument() end end is_done = not e until is_done return unpack(args) end return M
local api = vim.api local custom_options = { noremap = true, silent = true } local M = {} M.map = function(mode, target, source, opts) api.nvim_set_keymap(mode, target, source, opts or custom_options) end for _, mode in ipairs({ "n", "o", "i", "x", "t" }) do M[mode .. "map"] = function(...) M.map(mode, ...) end end M.buf_map = function(bufnr, mode, target, source, opts) api.nvim_buf_set_keymap(bufnr or 0, mode, target, source, opts or custom_options) end M.command = function(name, fn) vim.cmd(string.format("command! %s %s", name, fn)) end M.lua_command = function(name, fn) M.command(name, "lua " .. fn) end M.input = function(keys, mode) api.nvim_feedkeys(M.t(keys), mode or "m", true) end return M
BASE_DIR = path.getabsolute("..") THIRD_PARTY_DIR = path.join(BASE_DIR, "3rdparty") TUTORIAL_BUILD_DIR = path.join(BASE_DIR, "build") BGFX_DIR = path.join(THIRD_PARTY_DIR, "bgfx") BX_DIR = path.join(THIRD_PARTY_DIR, "bx") BIMG_DIR = path.join(THIRD_PARTY_DIR, "bimg") SRC_DIR = path.join(BASE_DIR, "src") function copyLib() end newoption { trigger = "with-tools", description = "Build with tools." } solution "isosurface-tutorial-genie" configurations { "debug", "development", "release", } if _ACTION:match "xcode*" then platforms { "Universal", } else platforms { "x32", "x64", -- "Xbox360", "Native", -- for targets where bitness is not specified } end language "C++" --flags { "NoRTTI", "NoExceptions" } configuration {} dofile("toolchain.lua") toolchain(TUTORIAL_BUILD_DIR, THIRD_PARTY_DIR) project ("marching_squares") kind "ConsoleApp" includedirs { path.join(BGFX_DIR, "include"), path.join(BX_DIR, "include"), path.join(BIMG_DIR, "include"), } files { path.join(SRC_DIR, "marching_squares/*.cpp"), path.join(SRC_DIR, "marching_squares/*.h"), } links { "glfw", "bgfx", "bimg", "bx", } configuration { "linux-*" } links { "X11", "Xrandr", "pthread", "GL", } configuration {} group "libs" dofile(path.join(BGFX_DIR, "scripts/bgfx.lua")) bgfxProject("", "StaticLib") dofile (path.join(BX_DIR, "scripts/bx.lua")) dofile (path.join(BIMG_DIR, "scripts/bimg.lua")) dofile (path.join(BIMG_DIR, "scripts/bimg_encode.lua")) dofile (path.join(BIMG_DIR, "scripts/bimg_decode.lua")) if _OPTIONS["with-tools"] then group "tools" dofile(path.join(BGFX_DIR, "scripts/shaderc.lua")) dofile(path.join(BGFX_DIR, "scripts/texturec.lua")) end dofile("tests.lua")
project "BenchLib" kind "StaticLib" if zpm.option( "ProfileMemory" ) then zpm.export [[ defines "BENCHLIB_ENABLE_MEMPROFILE" ]] end zpm.export [[ includedirs "benchmark/include/" flags "C++11" ]]
--[[ Name: cl_init.lua For: SantosRP By: TalosLife ]]-- include "shared.lua" ENT.RenderGroup = RENDERGROUP_BOTH function ENT:Initialize() self.m_sndBurnSound = CreateSound( self, "weapons/flaregun/burn.wav" ) end function ENT:OnRemove() if self.m_sndBurnSound then self.m_sndBurnSound:Stop() end end function ENT:Think() if not self:GetLit() then return end if not self.m_sndBurnSound:IsPlaying() then self.m_sndBurnSound:SetSoundLevel( 65 ) self.m_sndBurnSound:Play() end end
--[[ Copyright (c) 2019 dgw * Part of the Warehousing mod * * See License.txt in the project directory for license information. --]] -- migrate from old single logistic research to the new pair of techs -- relies on JSON migration to rename the old tech to level 2 first for index, force in pairs(game.forces) do local technologies = force.technologies local recipes = force.recipes if technologies["warehouse-logistics-research-2"].researched then technologies["warehouse-logistics-research-1"].researched = true end end
local function map(list, mapper) local listType = type(list) assert(listType == "table", "expected a table for first argument, got " .. listType) local mapperType = type(mapper) assert(mapperType == "function", "expected a function for second argument, got " .. mapperType) local new = {} local index = 1 for i = 1, #list do local value = mapper(list[i], i) if value ~= nil then new[index] = value index = index + 1 end end return new end return map
return setmetatable({},{ __index = function(_, key: string) return function(duration: number?) return TweenInfo.new(duration or 0, Enum.EasingStyle[key]) end end, })
-- Copyright (C) Miracle -- Copyright (C) OpenWAF local _M = { _VERSION = "0.0.3" } local ffi = require "ffi" local cjson = require "cjson.safe" local twaf_action = require "lib.twaf.inc.action" local ngx_ERR = ngx.ERR local ngx_log = ngx.log local ngx_exit = ngx.exit local ngx_header = ngx.header local timer = ngx.timer.at local ngx_re_find = ngx.re.find local ngx_var = ngx.var local ngx_get_phase = ngx.get_phase local ngx_socket_tcp = ngx.socket.tcp local ngx_req_get_uri_args = ngx.req.get_uri_args function _M.ffi_copy(value, len) local buf = ffi.new(ffi.typeof("char[?]"), len + 1) ffi.copy(buf, value) return buf end function _M.ffi_str(value, len) return ffi.string(value, len) end function _M.load_lib(cpath, lib_name) for k, v in (cpath or ""):gmatch("[^;]+") do local lib_path = k:match("(.*/)") if lib_path then -- "lib_path" could be nil. e.g, the dir path component is "." lib_path = lib_path .. (lib_name or "") local f = io.open(lib_path) if f ~= nil then f:close() return ffi.load(lib_path) end end end ngx.log(ngx.WARN, "load lib failed - ", lib_name) end function _M.string_trim(self, str) return (str:gsub("^%s*(.-)%s*$", "%1")) end --Only the first character to take effect in separator. function _M.string_split(self, str, sep) local fields = {} local pattern = string.format("([^%s]+)", sep) str:gsub(pattern, function(c) fields[#fields + 1] = c end) return fields end -- If the separator with '-', '*', '+', '?', '%', '.', '[', ']', '^', it should add escape character function _M.string_ssplit(self, str, sep) if not str or not sep then return str end local result = {} for m in (str..sep):gmatch("(.-)"..sep) do table.insert(result, m) end return result end -- When processing the request message, it is recommended to use this function -- no object request pahse,this function does't work function _M.string_split_re(self, str, sep) if not str or not sep then return str end local result = {} repeat local len = #str if len <= 0 then break end local from, to, err = ngx.re.find(str, sep, "oij") if not from then table.insert(result, str) break else table.insert(result, str:sub(1, from - 1)) str = str:sub(to + 1) end until false return result end function _M.get_cookie_table(self, text_cookie) local text_cookie = ngx_var.http_cookie if not text_cookie then return {} end local cookie_table = {} local cookie_string = _M:string_split(text_cookie, ";") for _, value in ipairs(cookie_string) do value = _M:string_trim(value) local result = _M:string_split(value, "=") if result[1] then cookie_table[result[1]] = result[2] end end return cookie_table end function _M.get_cookie(self, _twaf, key) local cookie = ngx_var.http_cookie if cookie == nil then return nil, "no any cookie found in the current request" end local cookie_table = _twaf:ctx().cookie_table if cookie_table == nil then cookie_table = _M:get_cookie_table(cookie) _twaf:ctx().cookie_table = cookie_table end return cookie_table[key] end local function _bake_cookie(cookie) if not cookie.name or not cookie.value then return nil, 'missing cookie field "name" or "value"' end if cookie["max-age"] then cookie.max_age = cookie["max-age"] end local str = cookie.name .. "=" .. cookie.value .. (cookie.expires and "; Expires=" .. cookie.expires or "") .. (cookie.max_age and "; Max-Age=" .. cookie.max_age or "") .. (cookie.domain and "; Domain=" .. cookie.domain or "") .. (cookie.path and "; Path=" .. cookie.path or "") .. (cookie.secure and "; Secure" or "") .. (cookie.httponly and "; HttpOnly" or "") .. (cookie.extension and "; " .. cookie.extension or "") return str end function _M.set_cookie(self, cookie) local cookie_str, err if type(cookie) == "table" then cookie_str, err = _bake_cookie(cookie) else cookie_str = cookie end if cookie_str == nil then ngx_log(ngx_ERR, err) return end local Set_Cookie = ngx_header['Set-Cookie'] local set_cookie_type = type(Set_Cookie) local t = {} if set_cookie_type == "string" then -- only one cookie has been setted if Set_Cookie ~= cookie_str then t[1] = Set_Cookie t[2] = cookie_str ngx_header['Set-Cookie'] = t end elseif set_cookie_type == "table" then -- more than one cookies has been setted local size = #Set_Cookie -- we can not set cookie like ngx.header['Set-Cookie'][3] = val -- so create a new table, copy all the values, and then set it back for i=1, size do t[i] = ngx_header['Set-Cookie'][i] if t[i] == cookie_str then -- new cookie is duplicated return true end end t[size + 1] = cookie_str ngx_header['Set-Cookie'] = t else -- no cookie has been setted ngx_header['Set-Cookie'] = cookie_str end end --time ip agent key time function _M.set_cookie_value(self, request, key) if type(key) ~= "string" then ngx.log(ngx.WARN, "the cookie key not string in set_cookie_value") return "" end local time = request.TIME_EPOCH or ngx.time() local addr = request.REMOTE_ADDR or ngx.var.remote_addr local agent = request.http_user_agent or ngx.var.http_user_agent or "" local crc32_buf = time..addr..agent..key..time local crc32 = ngx.crc32_long(crc32_buf) return time..":"..crc32.."; path=/" end function _M.check_cookie_value(self, cookie, request, key, timeout) if not cookie or type(key) ~= "string" then ngx.log(ngx.WARN, "not cookie or key not a string in check_cookie_value") return false end local from = cookie:find(":") if not from or from == 1 or from == #cookie then return false end local time = tonumber(cookie:sub(1, from - 1)) or 0 local crc = tonumber(cookie:sub(from + 1)) or 0 local now = request.TIME_EPOCH or ngx.time() local addr = request.REMOTE_ADDR or ngx.var.remote_addr local agent = request.http_user_agent or ngx.var.http_user_agent or "" local crc32_buf = time..addr..agent..key..time local crc32 = ngx.crc32_long(crc32_buf) if crc == crc32 then if timeout and (now - time) > timeout then return ngx.AGAIN end return true end return false end function _M.flush_expired(premature, _twaf, dict, delay) dict:flush_expired() if not dict:get("add_timer") then return nil, "twaf_func:flush_expired - don't have key \"add_timer\"" end local ok, err = timer(delay, _M.flush_expired, _twaf, dict, delay) if not ok then dict:set("add_timer", nil) end return ok, err end function _M.dict_flush_expired(self, _twaf, dict, delay) local add_timer = dict:get("add_timer") if not add_timer then dict:add("add_timer", 1) local ok, err = timer(delay, _M.flush_expired, _twaf, dict, delay) if not ok then ngx_log(ngx_ERR, "twaf_func:dict_flush_expired - failed to create timer: ", err) dict:set("add_timer", nil) return end end end function _M.match(self, subject, complex, options) if complex == nil then return false end local res if type(complex) == "string" then res = ngx.re.find(subject, complex, options) if res then return true end elseif type(complex) == "table" then for _, v in pairs(complex) do res = ngx.re.find(subject, v, options) if res then return true end end end return false end function _M.state(self, state) if state == nil then return false end -- dynamic state if type(state) == "string" then state = state:sub(2) local ds_state = ngx_var[state] if ds_state == "1" then return true elseif ds_state == "0" then return false end return false end if type(state) == "boolean" then return state end return false end function _M.get_variable(self, key) local str = nil local request = twaf:ctx().request if type(request[key]) == "function" then str = _M:table_to_string(request[key]()) elseif key:sub(1,1) == "%" then str = _M:parse_dynamic_value(key ,request) else str = _M:table_to_string(request[key]) end if str == nil then return "-" end return str end function _M.key(self, key_var) local key if type(key_var) == "string" then key = self:get_variable(key_var) elseif type(key_var) == "table" then if type(key_var[1]) == "string" then key = self:get_variable(key_var[1]) for i = 2, #key_var do key = key .. self:get_variable(key_var[i]) end elseif type(key_var[1]) == "table" then for _, key_m in ipairs(key_var) do local key_n = self:get_variable(key_m[1]) for i = 2, #key_m do key_n = key_n .. self:get_variable(key_m[i]) end key[#key+1] = key_n end end end return key end function _M.get_dict_info(self, dict, key) return dict:get(key) or 0 end function _M.content_length_operation(self, num, operator) local phase = ngx_get_phase() if phase ~= "header_filter" then return nil end local content_length = ngx_header['Content-Length'] if content_length ~= nil then if operator == "add" then ngx_header['Content-Length'] = content_length + num elseif operator == "sub" then ngx_header['Content-Length'] = content_length - num end end return nil end function _M.tcp_connect(self, host, port, timeout) local sock, err = ngx_socket_tcp() if not sock then ngx_log(ngx_ERR, err) return nil end if timeout then sock:settimeout(timeout) end local ok, err = sock:connect(host, port) if not ok then ngx_log(ngx_ERR, err) return nil end return sock end function _M.random_id(self, max_len) local s0 = "1234567890" local s1 = "abcdefghijklmnopqrstuvwxyz" local s2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" local seed = tostring(os.time())..tostring(ngx.var.stat_requests) math.randomseed(tonumber(seed)) local srt = "" local str = s0 .. s1 .. s2 for i = 1, max_len, 1 do local index = math.random(1, #str) srt = srt .. str:sub(index, index) end return srt end function _M.copy_table(self, st) local new_tab = {} for k, v in pairs(st or {}) do if k == "lua" then new_tab[k] = tostring(v) else if type(v) ~= "table" then new_tab[k] = v else new_tab[k] = _M:copy_table(v) end end end return new_tab end function _M.copy_value(self, val) if type(val) == "table" then return _M:copy_table(val) end return val end function _M.table_has_value(self, tb, value) if type(tb) ~= "table" or type(value) == "table" then return false end for _, v in pairs(tb) do if type(v) == "table" then return _M:table_has_value(v, value) else if type(v) == type(value) and v == value then return true end end end return false end function _M.table_keys(self, tb) if type(tb) ~= "table" then ngx.log(ngx.WARN, type(tb) .. " was given to table_keys") return tb end local t = {} for key, _ in pairs(tb) do table.insert(t, key) end return t end function _M.table_values(self, tb) if type(tb) ~= "table" then ngx.log(ngx.WARN, type(tb) .. " was given to table_values") return tb end local t = {} for _, value in pairs(tb) do if type(value) == "table" then local tab = _M:table_values(value) for _, v in pairs(tab) do table.insert(t, v) end else table.insert(t, value) end end return t end function _M.multi_table_values(self, ...) local t = {} for _, tb in ipairs({...}) do local t1 = _M:table_values(tb) for _, v in ipairs(t1) do table.insert(t, v) end end return t end function _M.check_rules(self, conf, rule) local log = {} -- id if type(rule.id) ~= "string" then table.insert(log, "ID("..tostring(rule.id).."): string expected, got "..type(rule.id)) rule.id = tostring(rule.id) end if conf.rules_id[rule.id] then table.insert(log, "ID: "..rule.id.." is duplicate") end -- phase local phase_arr = {access = 1, header_filter = 1, body_filter = 1} local p_func = function(phase) local t = type(phase) if t == "string" then if not phase_arr[phase] then table.insert(log, "phase: 'access', 'header_filter' or ".. "'body_filter' expected, got ".. phase.." in rule ID: "..rule.id) end else table.insert(log, "phase: 'string' or 'table' expected, got ".. t.." in rule ID: "..rule.id) end end if type(rule.phase) ~= "table" then p_func(rule.phase) else for _, v in ipairs(rule.phase) do p_func(v) end end if #log > 0 then ngx.log(ngx.WARN, cjson.encode(log)) return false, log end return true end local function sanitise_request_line(ctx, request) local s local func = function(m) local str = "" for i = 1, #m - 1 do str = str.."*" end str = s.."="..str..m:sub(-1, -1) return str end local r_line = request.REQUEST_LINE if r_line and ctx.sanitise_uri_args then for _, arg in pairs(ctx.sanitise_uri_args) do s = arg r_line = string.gsub(r_line, arg.."=(.-[& ])", func) end end ctx.sanitise_uri_args = nil return r_line or "" end local function table_value_to_string(tb) if type(tb) ~= "table" then return tb end for k, v in pairs(tb) do if type(v) == "table" then tb[k] = table_value_to_string(v) elseif type(v) =="function" then tb[k] = string.dump(v) elseif type(v) == "userdata" then tb[k] = 1 end end return tb end function _M.table_to_string(self, tb) if type(tb) ~= "table" then return tb end local tbl = _M:copy_table(tb) local t = table_value_to_string(tbl) return cjson.encode(t) end function _M.syn_config_process(self, _twaf, worker_config) if type(worker_config) ~= "table" then return nil end local phase = {"access", "header_filter", "body_filter"} -- system rules if worker_config.rules then for phase, rules in pairs(worker_config.rules) do for _, rule in ipairs(rules) do if not rule.match then for _, p in ipairs(phase) do if rule[p] then rule[p] = load(rule[p]) end end end end end end -- user defined rules if worker_config.twaf_policy and worker_config.twaf_policy.policy_uuids then for uuid, _ in pairs(worker_config.twaf_policy.policy_uuids) do local policy = worker_config.twaf_policy[uuid] if policy and policy.twaf_secrules then local rules = policy.twaf_secrules.user_defined_rules for _, rule in ipairs(rules or {}) do if not rule.match then for _, p in ipairs(phase) do if rule[p] then rule[p] = load(rule[p]) end end end end end end end for k, v in pairs(worker_config) do if type(_twaf.config[k]) == "userdata" then worker_config[k] = _twaf.config[k] end end return worker_config end function _M.syn_config(self, _twaf) local gcf = _twaf:get_config_param("twaf_global") local dict = ngx.shared[gcf.dict_name] local wid = ngx.worker.id() local wpid = ngx.worker.pid() local res = dict:get("worker_process_"..wid) if res and res ~= true and res ~= wpid then res = true end if res == true then ngx.log(ngx.ERR, "config synchronization ing..") local worker_config = dict:get("worker_config") worker_config = cjson.decode(worker_config) _twaf.config = _M:syn_config_process(_twaf, worker_config) or _twaf.config dict:set("worker_process_"..wid, wpid) end end function _M.parse_dynamic_value(self, key, request) local lookup = function(m) local val = request[m[1]:upper()] local specific = m[2] if (not val) then --logger.fatal_fail("Bad dynamic parse, no collection key " .. m[1]) return "-" end if (type(val) == "table") then if (specific) then return tostring(val[specific]) else return _M:table_to_string(val) --return tostring(m[1]) end elseif (type(val) == "function") then return tostring(val(twaf)) else return tostring(val) end end -- grab something that looks like -- %{VAL} or %{VAL.foo} -- and find it in the lookup table local str = ngx.re.gsub(key, [[%{([^\.]+?)(?:\.([^}]+))?}]], lookup, "oij") --logger.log(_twaf, "Parsed dynamic value is " .. str) if (ngx.re.find(str, [=[^\d+$]=], "oij")) then return tonumber(str) else return str end end function _M.conf_log(self, _twaf, request, ctx) local log = {} local lcf = _twaf:get_config_param("twaf_log") or {} local sef = lcf.safe_event_format if not sef then return false end for _, v in pairs(sef.ctx or {}) do log[v] = _M:table_to_string(ctx[v]) or "-" end for _, v in pairs(sef.vars or {}) do local value = request[v:upper()] if type(value) == "function" then value = _M:table_to_string(value()) else value = _M:table_to_string(value) end log[v] = value or "-" end return log end function _M.rule_category(self, _twaf, rule_name) for k, v in pairs(_twaf.config.category_map or {}) do if ngx.re.find(rule_name, v.rule_name) then return k end end return "UNKNOWN" end function _M.rule_log(self, _twaf, info) local ctx = _twaf:ctx() local request = ctx.request info.category = _M:rule_category(_twaf, info.rule_name) -- reqstat ctx.events.stat[info.category] = (info.action or "PASS"):upper() -- attack response if info.action == "DENY" then ngx_var.twaf_attack_info = ngx_var.twaf_attack_info .. info.rule_name .. ";" end -- log if info.log_state == true then ctx.events.log[info.rule_name] = _M:conf_log(_twaf, ctx.request, info) end request.MATCHED_VARS = {} request.MATCHED_VAR_NAMES = {} -- action return twaf_action:do_action(_twaf, info.action, info.action_meta) end function _M:print_G(_twaf) local gcf = _twaf:get_config_param("twaf_global") local shm = gcf.dict_name if not shm then return end local dict = ngx.shared[shm] if not dict then return end local path = dict:get("twaf_print_G") if not path then return end dict:delete("twaf_print_G") local data = {} local tablePrinted = {} local printTableItem = function(tb, k, v, printTableItem) k = tostring(k) if type(v) == "table" then if not tablePrinted[v] then tb[k] = {} tablePrinted[v] = true for m, n in pairs(v) do printTableItem(tb[k], m, n, printTableItem) end else tb[k] = "'"..k.."' have existed" end else tb[k] = tostring(v) end end printTableItem(data, "_G", _G, printTableItem) local f = io.open(path, "a+") f:write(cjson.encode(data)) f:close() return end function _M:print_ctx(_twaf) local gcf = _twaf:get_config_param("twaf_global") local shm = gcf.dict_name if not shm then return end local dict = ngx.shared[shm] if not dict then return end local path = dict:get("twaf_print_ctx") if not path then return end dict:delete("twaf_print_ctx") local func = function(tb, func, data, tablePrinted) data = data or {} tablePrinted = tablePrinted or {} if type(tb) ~= "table" then return tostring(tb) end for k, v in pairs(tb) do if type(v) == "table" then if not tablePrinted[v] then tablePrinted[v] = true data[k] = func(v, func, data[k], tablePrinted) else data[k] = "'"..k.."' have existed" end else data[k] = tostring(v) end end return data end local data = func(_twaf:ctx(), func) local f = io.open(path, "a+") f:write(cjson.encode(data)) f:close() end function _M.table_merge(tb1, tb2) if type(tb1) ~= "table" or type(tb2) ~= "table" then return tb1 end for k, v in pairs(tb2) do tb1[k] = v end return tb1 end -- check json body function _M.api_check_json_body(log) ngx.req.read_body() local body = ngx.req.get_body_data() local res, data = pcall(cjson.decode, body) if not res or type(data) ~= "table" then log.success = 0 log.reason = "request body: json expected, got " .. (body or "nil") return nil end return data end return _M
FACTION.name = "Hauptamt SS-Gericht" FACTION.desc = "SS Court Main Office" FACTION.color = Color(255, 0, 0) FACTION.isDefault = false FACTION.pay = 125 FACTION.payTime = 900 FACTION.isGloballyRecognized = true FACTION_GERICH = FACTION.index
return function(args) local weblit = require 'weblit-app' weblit.use(require 'weblit-auto-headers') local web_hook_server = require './src/WebHookServer'(weblit) weblit.start() local build_manager = require './src/BuildManager'() build_manager.add_builder(require './src/SshBuilder'({ server = 'ryan@192.168.1.15', port = 22, labels = { 'ubuntu', 'lenv' } })) build_manager.add_builder(require './src/SshBuilder'({ server = 'ryan@192.168.1.1', port = 22, labels = { 'ubuntu', 'lenv' } })) local configamajig = require './src/Configamajig'( 'sample/mach.lua-config.lua', 'sample/webhook-test-config.lua' ) local build_scheduler = require './src/BuildScheduler'( web_hook_server, build_manager, configamajig ) end
-- neovim_helpers.lua -- Set of wrappers to ease interaction with the neovim api local cmd = vim.cmd local global = vim.o local map_key = vim.api.nvim_set_keymap -- Set an option to a value -- If no scopes specified then use global local function opt(option, value, scopes) scopes = scopes or {global} for _, s in ipairs(scopes) do s[option] = value end end -- Create an autocommand local function autocmd(group, cmds, clear) clear = clear == nil and false or clear if type(cmds) == 'string' then cmds = {cmds} end cmd('augroup ' .. group) if clear then cmd [[au!]] end for _, c in ipairs(cmds) do cmd('autocmd ' .. c) end cmd [[augroup END]] end -- Create a key binding local function map(modes, lhs, rhs, opts) opts = opts or {} opts.noremap = opts.noremap == nil and true or opts.noremap if type(modes) == 'string' then modes = {modes} end for _, mode in ipairs(modes) do map_key(mode, lhs, rhs, opts) end end return {opt = opt, autocmd = autocmd, map = map}
if not modules then modules = { } end modules ['attr-col'] = { version = 1.001, comment = "companion to attr-col.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- this module is being reconstructed and code will move to other places -- we can also do the nsnone via a metatable and then also se index 0 -- list could as well refer to the tables (instead of numbers that -- index into another table) .. depends on what we need local type, tonumber = type, tonumber local concat = table.concat local min, max, floor, mod = math.min, math.max, math.floor, math.mod local attributes = attributes local nodes = nodes local utilities = utilities local logs = logs local backends = backends local storage = storage local context = context local tex = tex local variables = interfaces.variables local v_yes = variables.yes local v_no = variables.no local p_split_comma = lpeg.tsplitat(",") local p_split_colon = lpeg.splitat(":") local lpegmatch = lpeg.match local allocate = utilities.storage.allocate local setmetatableindex = table.setmetatableindex local report_attributes = logs.reporter("attributes","colors") local report_colors = logs.reporter("colors","support") local report_transparencies = logs.reporter("transparencies","support") -- todo: document this but first reimplement this as it reflects the early -- days of luatex / mkiv and we have better ways now -- nb: attributes: color etc is much slower than normal (marks + literals) but ... -- nb. too many "0 g"s local states = attributes.states local nodeinjections = backends.nodeinjections local registrations = backends.registrations local unsetvalue = attributes.unsetvalue local enableaction = nodes.tasks.enableaction local setaction = nodes.tasks.setaction local registerstorage = storage.register local formatters = string.formatters local interfaces = interfaces local implement = interfaces.implement local texgetattribute = tex.getattribute -- We can distinguish between rules and glyphs but it's not worth the trouble. A -- first implementation did that and while it saves a bit for glyphs and rules, it -- costs more resourses for transparencies. So why bother. -- -- colors -- -- we can also collapse the two attributes: n, n+1, n+2 and then -- at the tex end add 0, 1, 2, but this is not faster and less -- flexible (since sometimes we freeze color attribute values at -- the lua end of the game) -- -- we also need to store the colorvalues because we need then in mp -- -- This is a compromis between speed and simplicity. We used to store the -- values and data in one array, which made in neccessary to store the -- converters that need node constructor into strings and evaluate them -- at runtime (after reading from storage). Think of: -- -- colors.strings = colors.strings or { } -- -- if environment.initex then -- colors.strings[color] = "return colors." .. colorspace .. "(" .. concat({...},",") .. ")" -- end -- -- registerstorage("attributes/colors/data", colors.strings, "attributes.colors.data") -- evaluated -- -- We assume that only processcolors are defined in the format. attributes.colors = attributes.colors or { } local colors = attributes.colors local a_color = attributes.private('color') local a_selector = attributes.private('colormodel') colors.data = allocate() colors.values = colors.values or { } colors.registered = colors.registered or { } colors.weightgray = true colors.attribute = a_color colors.selector = a_selector colors.default = 1 colors.main = nil colors.triggering = true colors.supported = true colors.model = "all" local data = colors.data local values = colors.values local registered = colors.registered local numbers = attributes.numbers local list = attributes.list registerstorage("attributes/colors/values", values, "attributes.colors.values") registerstorage("attributes/colors/registered", registered, "attributes.colors.registered") local f_colors = { rgb = formatters["r:%s:%s:%s"], cmyk = formatters["c:%s:%s:%s:%s"], gray = formatters["s:%s"], spot = formatters["p:%s:%s:%s:%s"], } local models = { [interfaces.variables.none] = unsetvalue, black = unsetvalue, bw = unsetvalue, all = 1, gray = 2, rgb = 3, cmyk = 4, } local function rgbtocmyk(r,g,b) -- we could reduce if not r then return 0, 0, 0 else return 1-r, 1-g, 1-b, 0 end end local function cmyktorgb(c,m,y,k) if not c then return 0, 0, 0, 1 else return 1.0 - min(1.0,c+k), 1.0 - min(1.0,m+k), 1.0 - min(1.0,y+k) end end local function rgbtogray(r,g,b) if not r then return 0 end local w = colors.weightgray if w == true then return .30*r + .59*g + .11*b elseif not w then return r/3 + g/3 + b/3 else return w[1]*r + w[2]*g + w[3]*b end end local function cmyktogray(c,m,y,k) return rgbtogray(cmyktorgb(c,m,y,k)) end -- http://en.wikipedia.org/wiki/HSI_color_space -- http://nl.wikipedia.org/wiki/HSV_(kleurruimte) -- h /= 60; // sector 0 to 5 -- i = floor( h ); -- f = h - i; // factorial part of h local function hsvtorgb(h,s,v) if s > 1 then s = 1 elseif s < 0 then s = 0 elseif s == 0 then return v, v, v end if v > 1 then s = 1 elseif v < 0 then v = 0 end if h < 0 then h = 0 elseif h >= 360 then h = mod(h,360) end local hd = h / 60 local hi = floor(hd) local f = hd - hi local p = v * (1 - s) local q = v * (1 - f * s) local t = v * (1 - (1 - f) * s) if hi == 0 then return v, t, p elseif hi == 1 then return q, v, p elseif hi == 2 then return p, v, t elseif hi == 3 then return p, q, v elseif hi == 4 then return t, p, v elseif hi == 5 then return v, p, q else print("error in hsv -> rgb",h,s,v) return 0, 0, 0 end end local function rgbtohsv(r,g,b) local offset, maximum, other_1, other_2 if r >= g and r >= b then offset, maximum, other_1, other_2 = 0, r, g, b elseif g >= r and g >= b then offset, maximum, other_1, other_2 = 2, g, b, r else offset, maximum, other_1, other_2 = 4, b, r, g end if maximum == 0 then return 0, 0, 0 end local minimum = other_1 < other_2 and other_1 or other_2 if maximum == minimum then return 0, 0, maximum end local delta = maximum - minimum return (offset + (other_1-other_2)/delta)*60, delta/maximum, maximum end local function graytorgb(s) -- unweighted return 1-s, 1-s, 1-s end local function hsvtogray(h,s,v) return rgb_to_gray(hsv_to_rgb(h,s,v)) end local function graytohsv(s) return 0, 0, s end colors.rgbtocmyk = rgbtocmyk colors.rgbtogray = rgbtogray colors.cmyktorgb = cmyktorgb colors.cmyktogray = cmyktogray colors.rgbtohsv = rgbtohsv colors.hsvtorgb = hsvtorgb colors.hsvtogray = hsvtogray colors.graytohsv = graytohsv -- we can share some *data by using s, rgb and cmyk hashes, but -- normally the amount of colors is not that large; storing the -- components costs a bit of extra runtime, but we expect to gain -- some back because we have them at hand; the number indicates the -- default color space function colors.gray(s) return { 2, s, s, s, s, 0, 0, 0, 1-s } end function colors.rgb(r,g,b) local s = rgbtogray(r,g,b) local c, m, y, k = rgbtocmyk(r,g,b) return { 3, s, r, g, b, c, m, y, k } end function colors.cmyk(c,m,y,k) local s = cmyktogray(c,m,y,k) local r, g, b = cmyktorgb(c,m,y,k) return { 4, s, r, g, b, c, m, y, k } end --~ function colors.spot(parent,f,d,p) --~ return { 5, .5, .5, .5, .5, 0, 0, 0, .5, parent, f, d, p } --~ end function colors.spot(parent,f,d,p) -- inspect(parent) inspect(f) inspect(d) inspect(p) if type(p) == "number" then local n = list[numbers.color][parent] -- hard coded ref to color number if n then local v = values[n] if v then -- the via cmyk hack is dirty, but it scales better local c, m, y, k = p*v[6], p*v[7], p*v[8], p*v[8] local r, g, b = cmyktorgb(c,m,y,k) local s = cmyktogray(c,m,y,k) return { 5, s, r, g, b, c, m, y, k, parent, f, d, p } end end else -- todo, multitone (maybe p should be a table) local ps = lpegmatch(p_split_comma,p) local ds = lpegmatch(p_split_comma,d) local c, m, y, k = 0, 0, 0, 0 local done = false for i=1,#ps do local p = tonumber(ps[i]) local d = ds[i] if p and d then local n = list[numbers.color][d] -- hard coded ref to color number if n then local v = values[n] if v then c = c + p*v[6] m = m + p*v[7] y = y + p*v[8] k = k + p*v[8] done = true end end end end if done then local r, g, b = cmyktorgb(c,m,y,k) local s = cmyktogray(c,m,y,k) local f = tonumber(f) return { 5, s, r, g, b, c, m, y, k, parent, f, d, p } end end return { 5, .5, .5, .5, .5, 0, 0, 0, .5, parent, f, d, p } end local function graycolor(...) graycolor = nodeinjections.graycolor return graycolor(...) end local function rgbcolor (...) rgbcolor = nodeinjections.rgbcolor return rgbcolor (...) end local function cmykcolor(...) cmykcolor = nodeinjections.cmykcolor return cmykcolor(...) end local function spotcolor(...) spotcolor = nodeinjections.spotcolor return spotcolor(...) end local function extender(colors,key) if colors.supported and key == "none" then local d = graycolor(0) colors.none = d return d end end local function reviver(data,n) if colors.supported then local v = values[n] local d if not v then local gray = graycolor(0) d = { gray, gray, gray, gray } report_attributes("unable to revive color %a",n) else local model = colors.forcedmodel(v[1]) if model == 2 then local gray = graycolor(v[2]) d = { gray, gray, gray, gray } elseif model == 3 then local gray, rgb, cmyk = graycolor(v[2]), rgbcolor(v[3],v[4],v[5]), cmykcolor(v[6],v[7],v[8],v[9]) d = { rgb, gray, rgb, cmyk } elseif model == 4 then local gray, rgb, cmyk = graycolor(v[2]), rgbcolor(v[3],v[4],v[5]), cmykcolor(v[6],v[7],v[8],v[9]) d = { cmyk, gray, rgb, cmyk } elseif model == 5 then local spot = spotcolor(v[10],v[11],v[12],v[13]) -- d = { spot, gray, rgb, cmyk } d = { spot, spot, spot, spot } end end data[n] = d return d end end setmetatableindex(colors, extender) setmetatableindex(colors.data, reviver) function colors.filter(n) return concat(data[n],":",5) end -- unweighted (flat) gray could be another model but a bit work as we need to check: -- -- attr-col colo-ini colo-run -- grph-inc grph-wnd -- lpdf-col lpdf-fmt lpdf-fld lpdf-grp -- meta-pdf meta-pdh mlib-pps -- -- but as we never needed it we happily delay that. function colors.setmodel(name,weightgray) if weightgray == true or weightgray == v_yes then weightgray = true elseif weightgray == false or weightgray == v_no then weightgray = false else local r, g, b = lpegmatch(p_split_colon,weightgray) if r and g and b then weightgray = { r, g, b } else weightgray = true end end colors.model = name -- global, not useful that way colors.default = models[name] or 1 -- global colors.weightgray = weightgray -- global return colors.default end function colors.register(name, colorspace, ...) -- passing 9 vars is faster (but not called that often) local stamp = f_colors[colorspace](...) local color = registered[stamp] if not color then color = #values + 1 values[color] = colors[colorspace](...) registered[stamp] = color -- colors.reviver(color) end if name then list[a_color][name] = color -- not grouped, so only global colors end return registered[stamp] end function colors.value(id) return values[id] end attributes.colors.handler = nodes.installattributehandler { name = "color", namespace = colors, initializer = states.initialize, finalizer = states.finalize, processor = states.selective, resolver = function() return colors.main end, } function colors.enable(value) setaction("shipouts","attributes.colors.handler",not (value == false or not colors.supported)) end function colors.forcesupport(value) -- can move to attr-div colors.supported = value report_colors("color is %ssupported",value and "" or "not ") colors.enable(value) end function colors.toattributes(name) local mc = list[a_color][name] local mm = texgetattribute(a_selector) return (mm == unsetvalue and 1) or mm or 1, mc or list[a_color][1] or unsetvalue end -- transparencies local a_transparency = attributes.private('transparency') attributes.transparencies = attributes.transparencies or { } local transparencies = attributes.transparencies transparencies.registered = transparencies.registered or { } transparencies.data = allocate() transparencies.values = transparencies.values or { } transparencies.triggering = true transparencies.attribute = a_transparency transparencies.supported = true local registered = transparencies.registered -- we could use a 2 dimensional table instead local data = transparencies.data local values = transparencies.values local f_transparency = formatters["%s:%s"] registerstorage("attributes/transparencies/registered", registered, "attributes.transparencies.registered") registerstorage("attributes/transparencies/values", values, "attributes.transparencies.values") local function inject_transparency(...) inject_transparency = nodeinjections.transparency return inject_transparency(...) end local function register_transparency(...) register_transparency = registrations.transparency return register_transparency(...) end function transparencies.register(name,a,t,force) -- name is irrelevant here (can even be nil) -- Force needed here for metapost converter. We could always force -- but then we'd end up with transparencies resources even if we -- would not use transparencies (but define them only). This is -- somewhat messy. local stamp = f_transparency(a,t) local n = registered[stamp] if not n then n = #values + 1 values[n] = { a, t } registered[stamp] = n if force then register_transparency(n,a,t) end elseif force and not data[n] then register_transparency(n,a,t) end if name then list[a_transparency][name] = n -- not grouped, so only global transparencies end return registered[stamp] end local function extender(transparencies,key) if colors.supported and key == "none" then local d = inject_transparency(0) transparencies.none = d return d end end local function reviver(data,n) if transparencies.supported then local v = values[n] local d if not v then d = inject_transparency(0) else d = inject_transparency(n) register_transparency(n,v[1],v[2]) end data[n] = d return d else return "" end end setmetatableindex(transparencies,extender) setmetatableindex(transparencies.data,reviver) -- register if used -- check if there is an identity function transparencies.value(id) return values[id] end attributes.transparencies.handler = nodes.installattributehandler { name = "transparency", namespace = transparencies, initializer = states.initialize, finalizer = states.finalize, processor = states.process, } function transparencies.enable(value) -- nil is enable setaction("shipouts","attributes.transparencies.handler",not (value == false or not transparencies.supported)) end function transparencies.forcesupport(value) -- can move to attr-div transparencies.supported = value report_transparencies("transparency is %ssupported",value and "" or "not ") transparencies.enable(value) end function transparencies.toattribute(name) return list[a_transparency][name] or unsetvalue end --- colorintents: overprint / knockout attributes.colorintents = attributes.colorintents or { } local colorintents = attributes.colorintents colorintents.data = allocate() -- colorintents.data or { } colorintents.attribute = attributes.private('colorintent') colorintents.registered = allocate { overprint = 1, knockout = 2, } local data, registered = colorintents.data, colorintents.registered local function extender(colorintents,key) if key == "none" then local d = data[2] colorintents.none = d return d end end local function reviver(data,n) if n == 1 then local d = nodeinjections.overprint() -- called once data[1] = d return d elseif n == 2 then local d = nodeinjections.knockout() -- called once data[2] = d return d end end setmetatableindex(colorintents, extender) setmetatableindex(colorintents.data, reviver) function colorintents.register(stamp) return registered[stamp] or registered.overprint end colorintents.handler = nodes.installattributehandler { name = "colorintent", namespace = colorintents, initializer = states.initialize, finalizer = states.finalize, processor = states.process, } function colorintents.enable() enableaction("shipouts","attributes.colorintents.handler") end -- interface implement { name = "enablecolor", onlyonce = true, actions = colors.enable } implement { name = "enabletransparency", onlyonce = true, actions = transparencies.enable } implement { name = "enablecolorintents", onlyonce = true, actions = colorintents.enable } --------- { name = "registercolor", actions = { colors .register, context }, arguments = "string" } --------- { name = "registertransparency", actions = { transparencies.register, context }, arguments = "string" } implement { name = "registercolorintent", actions = { colorintents .register, context }, arguments = "string" }
require('stdlib/string') local tools = {} function tools.protect_entity(entity) entity.minable = false entity.destructible = false end function tools.link_in_spawn(pos) local link_in = game.surfaces[GAME_SURFACE_NAME].create_entity { name = "linked-belt", position = pos, force = game.forces["neutral"] } link_in.linked_belt_type = "input" return link_in end function tools.link_out_spawn(pos) local link_out = game.surfaces[GAME_SURFACE_NAME].create_entity { name = "linked-belt", position = pos, force = game.forces["neutral"] } link_out.linked_belt_type = "output" return link_out end function tools.link_belts(player, inp, outp) local p = player.print if inp.valid and outp.valid then inp.connect_linked_belts(outp) if inp.linked_belt_neighbour == out then p("Success") tools.protect_entity(inp) tools.protect_entity(outp) elseif inp.linked_belt_neighbour ~= outp then p("Couldn't make link") return end else p("Invalid") end end commands.add_command("make", "magic", function(command) local player = game.players[command.player_index] local args = string.split(command.parameter, " ") if not args[1] then args[1] = false end if not args[2] then args[2] = false end tools.make(player, args[1], args[2]) end) commands.add_command("replace", "attempts to replace entities in the held blueprint", function(command) local player = game.players[command.player_index] local args = string.split(command.parameter, " ") args[1], args[2] = args[1] or false, args[2] or false if not args[1] or not args[2] then player.print("No source and/or replacement entity given.") return end tools.replace(player, args[1], args[2]) end) --[[ commands.add_command("layout", "save entity layout to file", function(command) local player = game.players[command.player_index] local area = command.parameter tools.save_layout(player, area) end) function tools.save_layout(player, area) local p = player.print if not player.admin then p("[ERROR] You're not admin!") return end local surface = player.surface game.write_file('layout.lua', '', false, player.index) if not area.left_top then local l_t = {x = area[1].x or area[1][1], y = area[1].y or area[1][2]} end if not area.right_bottom then local r_b = {x = area[2].x or area[2][1], y = area[2].y or area[2][2]} end local area = area or {left_top = l_t, right_bottom = r_b} local entities = surface.find_entities_filtered {area = area} local data = {position = {}, name = {}, direction = {}, force = {}} for _, e in pairs(entities) do if e.name ~= 'character' then table.insert(data.position, e.position) table.insert(data.name, e.name) table.insert(data.direction, tostring(e.direction)) table.insert(data.force, player.force.name) end end game.write_file('layout.lua', "layout = " .. serpent.block(data) .. '\n', false, player.index) p("Done.\n" .. data.name.count() .. " entities logged to \\script-output\\layout.lua") end --]] function tools.make(player, sharedobject, flow) local p = player.print if not player.admin then p("[ERROR] You're not admin!") return end if sharedobject == "link" then local link_in = global.oarc_players[player.name].link_in or nil local link_out = global.oarc_players[player.name].link_out or nil if link_in == link_out then p( "[ERROR] Last logged input belt is the same as last logged output belt. Specify a new belt with /make mode <in/out>") return false end tools.link_belts(player, link_in, link_out) end if sharedobject == "mode" then local sel = player.selected if not sel then p("[ERROR] Place your cursor over the target linked belt.") return false end if sel.name == "linked-belt" then if flow == "in" then global.oarc_players[player.name].link_in = sel local link_in = global.oarc_players[player.name].link_in if link_in.linked_belt_type == "input" then p( "MODE already set to INPUT. '/make mode output' to link an OUTPUT belt. '/make link' to connect.") return link_in else link_in.linked_belt_type = "input" p( "MODE set to INPUT. '/make mode output' to link an OUTPUT belt. '/make link' to connect.") return link_in end elseif flow == "out" then global.oarc_players[player.name].link_out = sel local link_out = global.oarc_players[player.name].link_out if link_out.linked_belt_type == "output" then p( "MODE already set to OUTPUT. '/make mode input' to link an INPUT belt. '/make link' to connect.") return link_out else link_out.linked_belt_type = "output" p( "MODE set to OUTPUT. '/make mode input' to link an INPUT belt. '/make link' to connect.") return link_out end else p("[ERROR] Invalid argument. Looking for 'in' or 'out'") return false end else p("[ERROR] Not a linked belt type.") return false end else local pos = GetWoodenChestFromCursor(player) pos = pos or FindClosestWoodenChestAndDestroy(player) if pos then if sharedobject == "chest" then if flow == "in" then SharedChestsSpawnInput(player, pos) return true end if flow == "out" then SharedChestsSpawnOutput(player, pos) return true end end if sharedobject == "belt" or "belts" then if flow == "in" then local link_in = tools.link_in_spawn(pos) global.oarc_players[player.name].link_in = link_in return link_in end if flow == "out" then local link_out = tools.link_out_spawn(pos) global.oarc_players[player.name].link_out = link_out return link_out end end if sharedobject == "power" or "energy" or "accumulator" then if flow == "in" then if (player.surface.can_place_entity { name = "electric-energy-interface", position = pos }) and (player.surface.can_place_entity { name = "constant-combinator", position = {x = pos.x + 1, y = pos.y} }) then SharedEnergySpawnInput(player, pos) return true end end if flow == "out" then if (player.surface.can_place_entity { name = "electric-energy-interface", position = pos }) and (player.surface.can_place_entity { name = "constant-combinator", position = {x = pos.x + 1, y = pos.y} }) then SharedEnergySpawnOutput(player, pos) return true end end end if sharedobject == "combinator" or sharedobject == "combinators" then if (player.surface.can_place_entity { name = "constant-combinator", position = {pos.x, pos.y - 1} }) and (player.surface.can_place_entity { name = "constant-combinator", position = {pos.x, pos.y + 1} }) then SharedChestsSpawnCombinators(player, {x = pos.x, y = pos.y - 1}, {x = pos.x, y = pos.y + 1}) return true else p( "Failed to place the special combinators. Please check there is enough space in the surrounding tiles!") end end if sharedobject == "water" then if (getDistance(pos, player.position) > 2) then player.surface.set_tiles({ [1] = {name = "water", position = pos} }) return true else p("Failed to place waterfill. Don't stand so close FOOL!") end end end end end function tools.run_tests(player, cursor_stack) local p = player.print local log = print local tests = { parent = { "[cursor stack]", "[cursor stack]", "[cursor stack]", "[cursor stack] ", "[player]", "[cursor stack]", "[cursor stack]", "[cursor stack]", "[cursor stack]", "[cursor stack]", "[cursor stack]" }, name = { "oName:", "valid:", "is_blueprint:", "is_blueprint_book:", "is_cursor_blueprint:", "[cursor stack] is_module:", "is_tool:", "[cursor stack] is_mining_tool:", "is_armor:", "[cursor stack] is_repair_tool:", "is_item_with_label:", "is_item_with_inventory:", "is_item_with_entity_data:", "is_upgrade_item:" }, funcs = { cursor_stack.object_name, cursor_stack.valid, cursor_stack.is_blueprint, cursor_stack.is_blueprint_book, player.is_cursor_blueprint(), cursor_stack.is_module, cursor_stack.is_tool, cursor_stack.is_mining_tool, cursor_stack.is_armor, cursor_stack.is_repair_tool, cursor_stack.is_item_with_label, cursor_stack.is_item_with_inventory, cursor_stack.is_item_with_entity_data, cursor_stack.is_upgrade_item }, truthy = { parent = "[color=blue]", name = "[color=green]", funcs = "[color=orange]", close = "[/color]" } } for index, test in pairs(tests.funcs) do if test then local msg = tests.truthy.parent .. tests.parent[index] .. tests.truthy.close .. " " .. tests.truthy.name .. tests.name[index] .. tests.truthy.close .. " " .. tests.truthy.funcs .. tostring(test) .. tests.truthy.close p(msg) msg = tests.parent[index] .. " " .. tests.name[index] .. " " .. tostring(test) log(msg) end end end function tools.replace(player, e1, e2) if not player.admin then player.print("[ERROR] You're not admin!") return end local p, cs, bp_ent_count, bp_tile_count = player.print, player.cursor_stack, 0, 0 tools.run_tests(player, cs) if game.entity_prototypes[e1] or game.tile_prototypes[e1] then local bp, bp_ents, bp_tiles = {}, {}, {} if not player.is_cursor_blueprint() then bp_ents = cs.get_blueprint_entities() bp_tiles = cs.get_blueprint_tiles() else bp_ents = player.get_blueprint_entities() bp_tiles = player.cursor_stack.import_stack(tostring( player.cursor_stack .export_stack())) .get_blueprint_tiles() end if game.entity_prototypes[e1] then p(e1 .. " is an entity prototype.") for each, ent in pairs(bp_ents) do if ent.name == e1 then ent.name = e2 bp_ent_count = bp_ent_count + 1 end end elseif game.tile_prototypes[e1] then p(e1 .. " is a tile prototype.") for each, tile in pairs(bp_tiles) do if tile.name == e1 then tile.name = e2 bp_tile_count = bp_tile_count + 1 end end end cs.clear() cs.set_stack {name = "blueprint"} bp = cs bp.set_blueprint_entities(bp_ents) bp.set_blueprint_tiles(bp_tiles) -- bp.clear() -- bp. -- if not player.is_cursor_blueprint() then -- else -- end -- bp.clear_blueprint() end p("entity replacements: " .. bp_ent_count) p("tile replacements: " .. bp_tile_count) -- else -- player.print("Not a valid blueprint") end
local utils = require "../sel/utils" local stringSplit = utils.stringSplit local stringTrim = utils.stringTrim return { populateContextByDefaultHandlers = function(context) context:registerHandler('not', function(arg) arg = tostring(arg) arg = arg:lower(); local args = stringSplit(arg, ","); --assert(table.getn(args) == 1, "SEL: not handler accepts only one argument") arg = stringTrim(args[1]); return not (arg == "true") end) context:registerHandler('allOf', function(arg) arg = tostring(arg) local args = stringSplit(arg, ","); for k, v in pairs(args) do if stringTrim(v) ~= "true" then return false; end end return true; end) context:registerHandler('anyOf', function(arg) arg = tostring(arg) local args = stringSplit(arg, ","); for k, v in pairs(args) do if stringTrim(v) == "true" then return true; end end return false; end) return context end }