content stringlengths 5 1.05M |
|---|
---@meta
---@class cc.AtlasNode :cc.Node@all parent class: Node,TextureProtocol
local AtlasNode={ }
cc.AtlasNode=AtlasNode
---* lua NA
---@return cc.BlendFunc
function AtlasNode:getBlendFunc () end
---* Initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to render
---@param tile string
---@param tileWidth int
---@param tileHeight int
---@param itemsToRender int
---@return boolean
function AtlasNode:initWithTileFile (tile,tileWidth,tileHeight,itemsToRender) end
---* code<br>
---* When this function bound into js or lua,the parameter will be changed<br>
---* In js: var setBlendFunc(var src, var dst)<br>
---* endcode<br>
---* lua NA
---@param blendFunc cc.BlendFunc
---@return self
function AtlasNode:setBlendFunc (blendFunc) end
---* Set an buffer manager of the texture vertex.
---@param textureAtlas cc.TextureAtlas
---@return self
function AtlasNode:setTextureAtlas (textureAtlas) end
---*
---@return cc.Texture2D
function AtlasNode:getTexture () end
---* Return the buffer manager of the texture vertex. <br>
---* return Return A TextureAtlas.
---@return cc.TextureAtlas
function AtlasNode:getTextureAtlas () end
---* updates the Atlas (indexed vertex array).<br>
---* Shall be overridden in subclasses.
---@return self
function AtlasNode:updateAtlasValues () end
---*
---@param texture cc.Texture2D
---@return self
function AtlasNode:setTexture (texture) end
---* Initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity of items to render
---@param texture cc.Texture2D
---@param tileWidth int
---@param tileHeight int
---@param itemsToRender int
---@return boolean
function AtlasNode:initWithTexture (texture,tileWidth,tileHeight,itemsToRender) end
---*
---@return unsigned_int
function AtlasNode:getQuadsToDraw () end
---*
---@param quadsToDraw int
---@return self
function AtlasNode:setQuadsToDraw (quadsToDraw) end
---* creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render.<br>
---* param filename The path of Atlas file.<br>
---* param tileWidth The width of the item.<br>
---* param tileHeight The height of the item.<br>
---* param itemsToRender The quantity of items to render.
---@param filename string
---@param tileWidth int
---@param tileHeight int
---@param itemsToRender int
---@return self
function AtlasNode:create (filename,tileWidth,tileHeight,itemsToRender) end
---*
---@param renderer cc.Renderer
---@param transform mat4_table
---@param flags unsigned_int
---@return self
function AtlasNode:draw (renderer,transform,flags) end
---*
---@return boolean
function AtlasNode:isOpacityModifyRGB () end
---*
---@param color color3b_table
---@return self
function AtlasNode:setColor (color) end
---*
---@return color3b_table
function AtlasNode:getColor () end
---*
---@param isOpacityModifyRGB boolean
---@return self
function AtlasNode:setOpacityModifyRGB (isOpacityModifyRGB) end
---*
---@param opacity unsigned_char
---@return self
function AtlasNode:setOpacity (opacity) end
---*
---@return self
function AtlasNode:AtlasNode () end |
-- hop.nvim config
require('hop').setup {
-- keys default: 'asdghklqwertyuiopzxcvbnmfj'
-- use colemak equivalent
keys = 'arstdhneioqwfpgjluyzxcvbkm',
}
vim.api.nvim_set_keymap('n', '<Leader><Leader>/', "<cmd>lua require'hop'.hint_patterns()<cr>", {})
vim.api.nvim_set_keymap('n', '<Leader><Leader>f', "<cmd>lua require'hop'.hint_char1()<cr>", {})
vim.api.nvim_set_keymap('n', '<Leader><Leader>l', "<cmd>lua require'hop'.hint_lines()<cr>", {})
vim.api.nvim_set_keymap('n', '<Leader><Leader>w', "<cmd>lua require'hop'.hint_words()<cr>", {})
|
local M = {}
M.new = function(title, buttons, listener, dog)
if not M.group then
ALERT = false
M.listener = listener
M.timer = timer.performWithDelay(0, function() M.group:toFront() end, 0)
M.group, M.buttons = display.newGroup(), {}
M.bg = display.newRoundedRect(CENTER_X, CENTER_Y - 100, DISPLAY_WIDTH - 100, 110, 20)
M.bg:setFillColor(0.2, 0.2, 0.22)
M.group:insert(M.bg)
M.title = display.newText({
text = title, width = DISPLAY_WIDTH - 150, x = CENTER_X,
y = CENTER_Y, font = 'ubuntu', fontSize = 30
}) M.title.anchorY = 0
M.group:insert(M.title)
M.title.height = M.title.height > DISPLAY_HEIGHT - 300 and DISPLAY_HEIGHT - 300 or M.title.height
M.bg.height = M.bg.height + M.title.height
M.title.y = M.bg.y - M.bg.height / 2 + 15
M.dog = display.newImage('Sprites/ccdog' .. dog .. '.png', CENTER_X, M.bg.y - M.bg.height / 2 - 75)
M.dog.width = 250
M.dog.height = 250
M.group:insert(M.dog)
M.dog:addEventListener('touch', function(e)
if e.phase == 'began' then
display.getCurrentStage():setFocus(e.target)
e.target.fill = {type = 'image', filename = 'Sprites/ccdog0.png'}
e.target.click = true
elseif e.phase == 'ended' or e.phase == 'cancelled' then
display.getCurrentStage():setFocus(nil)
e.target.fill = {type = 'image', filename = 'Sprites/ccdog' .. dog .. '.png'}
if e.target.click then e.target.click = false end
end
return true
end)
for i = 1, #buttons do
M.buttons[i] = display.newRect(M.bg.x - M.bg.width / 4 + 5, M.bg.y + M.bg.height / 2 - 10, M.bg.width / 2 - 30, 60)
M.buttons[i].x = i == 2 and M.bg.x + M.bg.width / 4 - 5 or M.buttons[i].x
M.buttons[i]:setFillColor(0.2, 0.2, 0.22)
M.buttons[i].anchorY = 1
M.buttons[i].id = i
M.group:insert(M.buttons[i])
M.buttons[i].text = display.newText({
text = buttons[i], width = M.buttons[i].width - 10, align = 'center',
x = M.buttons[i].x, y = M.buttons[i].y - M.buttons[i].height / 2, font = 'ubuntu', fontSize = 22
}) M.buttons[i].text.height = M.buttons[i].text.height > M.buttons[i].height - 10 and M.buttons[i].height - 10 or M.buttons[i].text.height
M.group:insert(M.buttons[i].text)
M.buttons[i]:addEventListener('touch', function(e)
if e.phase == 'began' then
display.getCurrentStage():setFocus(e.target)
e.target:setFillColor(0.24, 0.24, 0.26)
e.target.click = true
elseif e.phase == 'moved' and (math.abs(e.x - e.xStart) > 30 or math.abs(e.y - e.yStart) > 30) then
display.getCurrentStage():setFocus(nil)
e.target:setFillColor(0.2, 0.2, 0.22)
e.target.click = false
elseif e.phase == 'ended' or e.phase == 'cancelled' then
display.getCurrentStage():setFocus(nil)
e.target:setFillColor(0.2, 0.2, 0.22)
if e.target.click then
e.target.click = false
M.remove(e.target.id)
end
end
return true
end)
end
EXITS.add(M.remove, 0)
end
end
M.remove = function(index)
if M and M.group then
ALERT = true
M.listener({index = index})
timer.cancel(M.timer)
M.group:removeSelf()
M.group = nil
end
end
return M
|
--[[ Copyright (c) 2021 npc_strider, ickputzdirwech
* Original mod by npc_strider.
* For direct use of code or graphics, credit is appreciated and encouraged. See LICENSE.txt for more information.
* This mod may contain modified code sourced from base/core Factorio.
* This mod has been modified by ickputzdirwech.
]]
--[[ Overview of shortcuts-basic.lua:
* Character Lamp shortcut.
* Emergency locator beacon shortcut.
* Grid shortcut.
* Show rail block visualization shortcut.
* Toggle Personal logistics requests shortcut.
* Zoom out of world shortcut.
* MaxRateCalculator shortcut.
]]
if settings.startup["flashlight-toggle"].value then
data:extend(
{
{
type = "shortcut",
name = "flashlight-toggle",
localised_name = {"", {"Shortcuts-ick.basic"}, {"Shortcuts-ick.flashlight-toggle"}},
order = "a[basic]-b[flashlight-toggle]",
--associated_control_input = "flashlight-toggle",
action = "lua",
toggleable = true,
icon =
{
filename = "__Shortcuts-ick__/graphics/flashlight-toggle-x32.png",
priority = "extra-high-no-scale",
size = 32,
scale = 0.5,
flags = {"gui-icon"}
},
small_icon =
{
filename = "__Shortcuts-ick__/graphics/flashlight-toggle-x24.png",
priority = "extra-high-no-scale",
size = 24,
scale = 0.5,
flags = {"gui-icon"}
},
disabled_icon =
{
filename = "__Shortcuts-ick__/graphics/flashlight-toggle-x32-white.png",
priority = "extra-high-no-scale",
size = 32,
scale = 0.5,
flags = {"gui-icon"}
},
disabled_small_icon =
{
filename = "__Shortcuts-ick__/graphics/flashlight-toggle-x24-white.png",
priority = "extra-high-no-scale",
size = 24,
scale = 0.5,
flags = {"gui-icon"}
}
}
})
end
if settings.startup["signal-flare"].value then
data:extend(
{
{
type = "shortcut",
name = "signal-flare",
localised_name = {"", {"Shortcuts-ick.basic"}, {"Shortcuts-ick.signal-flare"}},
order = "a[basic]-c[signal-flare]",
--associated_control_input = "signal-flare",
action = "lua",
toggleable = true,
style = "red",
icon =
{
filename = "__Shortcuts-ick__/graphics/signal-flare-x32-white.png",
priority = "extra-high-no-scale",
size = 32,
scale = 0.5,
flags = {"gui-icon"}
},
small_icon =
{
filename = "__Shortcuts-ick__/graphics/signal-flare-x24-white.png",
priority = "extra-high-no-scale",
size = 24,
scale = 0.5,
flags = {"gui-icon"}
}
}
})
end
if settings.startup["draw-grid"].value then
data:extend(
{
{
type = "shortcut",
name = "draw-grid",
localised_name = {"", {"Shortcuts-ick.basic"}, {"gui.grid"}},
order = "a[basic]-d[draw-grid]",
--associated_control_input = "draw-grid",
action = "lua",
toggleable = true,
style = "blue",
icon =
{
filename = "__Shortcuts-ick__/graphics/grid-x32-white.png",
priority = "extra-high-no-scale",
size = 32,
scale = 0.5,
flags = {"gui-icon"}
},
small_icon =
{
filename = "__Shortcuts-ick__/graphics/grid-x24-white.png",
priority = "extra-high-no-scale",
size = 24,
scale = 0.5,
flags = {"gui-icon"}
}
}
})
end
if settings.startup["rail-block-visualization-toggle"].value then
data:extend(
{
{
type = "shortcut",
name = "rail-block-visualization-toggle",
localised_name = {"", {"Shortcuts-ick.basic"}, {"gui-interface-settings.show-rail-block-visualization"}},
order = "a[basic]-e[rail-block-visualization-toggle]",
--associated_control_input = "rail-block-visualization-toggle",
action = "lua",
toggleable = true,
icon =
{
filename = "__Shortcuts-ick__/graphics/rail-block-visualization-toggle-x32-2.png",
priority = "extra-high-no-scale",
size = 32,
mipmap_count = 2,
scale = 0.5,
flags = {"gui-icon"}
},
small_icon =
{
filename = "__Shortcuts-ick__/graphics/rail-block-visualization-toggle-x32-2.png",
priority = "extra-high-no-scale",
size = 32,
mipmap_count = 2,
scale = 0.5,
flags = {"gui-icon"}
},
disabled_icon =
{
filename = "__Shortcuts-ick__/graphics/rail-block-visualization-toggle-x32-2-white.png",
priority = "extra-high-no-scale",
size = 32,
mipmap_count = 2,
scale = 0.5,
flags = {"gui-icon"}
},
disabled_small_icon =
{
filename = "__Shortcuts-ick__/graphics/rail-block-visualization-toggle-x32-2-white.png",
priority = "extra-high-no-scale",
size = 32,
mipmap_count = 2,
scale = 0.5,
flags = {"gui-icon"}
}
}
})
end
if settings.startup["toggle-personal-logistic-requests"] and settings.startup["toggle-personal-logistic-requests"].value then
-- taken from mods.factorio.com/mod/PersonalLogisticsShortcut from Haxtorio, modified by ickputzdirwech
data:extend(
{
{
type = "shortcut",
name = "toggle-personal-logistic-requests",
localised_name = {"", {"Shortcuts-ick.basic"}, {"shortcut.toggle-personal-logistic-requests"}},
order = "a[basic]-f[toggle-personal-logistic-requests]",
action = "toggle-personal-logistic-requests",
associated_control_input = "toggle-personal-logistic-requests",
technology_to_unlock = "logistic-robotics",
icon =
{
filename = "__base__/graphics/icons/shortcut-toolbar/mip/toggle-personal-logistics-x32.png",
priority = "extra-high-no-scale",
size = 32,
scale = 0.5,
mipmap_count = 2,
flags = {"gui-icon"}
},
small_icon =
{
filename = "__base__/graphics/icons/shortcut-toolbar/mip/toggle-personal-logistics-x24.png",
priority = "extra-high-no-scale",
size = 24,
scale = 0.5,
mipmap_count = 2,
flags = {"gui-icon"}
},
disabled_icon =
{
filename = "__base__/graphics/icons/shortcut-toolbar/mip/toggle-personal-logistics-x32-white.png",
priority = "extra-high-no-scale",
size = 32,
scale = 0.5,
mipmap_count = 2,
flags = {"gui-icon"}
},
disabled_small_icon =
{
filename = "__base__/graphics/icons/shortcut-toolbar/mip/toggle-personal-logistics-x24-white.png",
priority = "extra-high-no-scale",
size = 24,
scale = 0.5,
mipmap_count = 2,
flags = {"gui-icon"}
}
}
})
-- end Haxtorio
end
if settings.startup["big-zoom"].value then
data:extend(
{
{
type = "shortcut",
name = "big-zoom",
localised_name = {"", {"Shortcuts-ick.basic"}, {"controls.alt-zoom-out"}},
order = "a[basic]-g[big-zoom]",
--associated_control_input = "big-zoom",
action = "lua",
toggleable = true,
style = "blue",
icon =
{
filename = "__Shortcuts-ick__/graphics/big-zoom-x32-white.png",
priority = "extra-high-no-scale",
size = 32,
scale = 0.5,
flags = {"gui-icon"}
},
small_icon =
{
filename = "__Shortcuts-ick__/graphics/big-zoom-x24-white.png",
priority = "extra-high-no-scale",
size = 24,
scale = 0.5,
flags = {"gui-icon"}
}
}
})
end
if mods["MaxRateCalculator"] and data.raw["selection-tool"]["max-rate-calculator"] and settings.startup["max-rate-calculator"].value then
data.raw["selection-tool"]["max-rate-calculator"].icon = "__MaxRateCalculator__/graphics/calculator.png"
data.raw["selection-tool"]["max-rate-calculator"].icon_size = 64
table.insert(data.raw["selection-tool"]["max-rate-calculator"].flags, "spawnable")
data:extend(
{
{
type = "shortcut",
name = "max-rate-shortcut",
localised_name = {"", {"Shortcuts-ick.basic"}, {"item-name.max-rate-calculator"}, " ", {"Shortcuts-ick.control", "marc_hotkey"}},
order = "a[basic]-h[max-rate-shortcut]",
--associated_control_input = "marc_hotkey",
action = "spawn-item",
item_to_spawn = "max-rate-calculator",
style = "blue",
icon =
{
filename = "__Shortcuts-ick__/graphics/max-rate-calculator-x32-white.png",
priority = "extra-high-no-scale",
size = 32,
scale = 0.5,
flags = {"gui-icon"}
},
small_icon =
{
filename = "__Shortcuts-ick__/graphics/max-rate-calculator-x24-white.png",
priority = "extra-high-no-scale",
size = 24,
scale = 0.5,
flags = {"gui-icon"}
}
}
})
end
|
--
-- I never tread... lightly.
-- Author: Dubpub
-- Date: 9/15/2015
-- Time: 8:00 PM
-- Use as you please, it's LUA for christ's sake.
--
-- Spawns a single inmate, obviously. I mean, look at the code dude.
function Create()
local prisoner = Object.Spawn("Prisoner", this.Pos.x, this.Pos.y);
this.Delete();
end
|
puck_dream_coil_lua = class({})
LinkLuaModifier( "modifier_generic_stunned_lua", "lua_abilities/generic/modifier_generic_stunned_lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( "modifier_puck_dream_coil_lua", "lua_abilities/puck_dream_coil_lua/modifier_puck_dream_coil_lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( "modifier_puck_dream_coil_lua_thinker", "lua_abilities/puck_dream_coil_lua/modifier_puck_dream_coil_lua_thinker", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
-- Custom KV
-- AOE Radius
function puck_dream_coil_lua:GetAOERadius()
return self:GetSpecialValueFor( "coil_radius" )
end
--------------------------------------------------------------------------------
-- Ability Start
function puck_dream_coil_lua:OnSpellStart()
-- unit identifier
local caster = self:GetCaster()
local point = self:GetCursorPosition()
-- load data
local radius = self:GetSpecialValueFor("coil_radius")
local duration = self:GetSpecialValueFor("coil_duration")
local stun_duration = self:GetSpecialValueFor("stun_duration")
if caster:HasScepter() then
duration = self:GetSpecialValueFor("coil_duration_scepter")
end
-- center point
local center = CreateModifierThinker(
self:GetCaster(),
self,
"modifier_puck_dream_coil_lua_thinker",
{ duration = duration },
point,
self:GetCaster():GetTeamNumber(),
false
)
-- find enemies
local enemies = FindUnitsInRadius(
caster:GetTeamNumber(), -- int, your team number
point, -- point, center point
nil, -- handle, cacheUnit. (not known)
radius, -- float, radius. or use FIND_UNITS_EVERYWHERE
DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter
DOTA_UNIT_TARGET_HERO, -- int, type filter
DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, -- int, flag filter
0, -- int, order filter
false -- bool, can grow cache
)
for _,enemy in pairs(enemies) do
enemy:AddNewModifier(
caster, -- player source
self, -- ability source
"modifier_generic_stunned_lua", -- modifier name
{ duration = stun_duration } -- kv
)
local modifier = enemy:AddNewModifier(
caster, -- player source
self, -- ability source
"modifier_puck_dream_coil_lua", -- modifier name
{
duration = duration,
coil_x = point.x,
coil_y = point.y,
coil_z = point.z,
} -- kv
)
end
-- play effects
self:PlayEffects( point, duration )
end
--------------------------------------------------------------------------------
function puck_dream_coil_lua:PlayEffects( point, duration )
-- Get Resources
local sound_cast = "Hero_Puck.Dream_Coil"
EmitSoundOnLocationWithCaster( point, sound_cast, self:GetCaster() )
end |
local awful = require("awful")
local interval = 10
awful.widget.watch('sh -c "top -bn1 | grep \"Cpu\""', interval, function(_, stdout)
local us = tonumber(string.match(stdout, ' (.*) us'))
local sy = tonumber(string.match(stdout, ', *(.*) sy'))
local usage = us + sy
awesome.emit_signal("status::cpu", usage)
end)
|
-- module will not return anything, only register assertions with the main assert engine
-- assertions take 2 parameters;
-- 1) state
-- 2) arguments list. The list has a member 'n' with the argument count to check for trailing nils
-- 3) level The level of the error position relative to the called function
-- returns; boolean; whether assertion passed
local assert = require('luassert.assert')
local astate = require ('luassert.state')
local util = require ('luassert.util')
local s = require('say')
local function set_failure_message(state, message)
if message ~= nil then
state.failure_message = message
end
end
local function tensor_comp(t1, t2)
local th1 = torch.type(t1)
local th2 = torch.type(t2)
if (th1 == "table") then
t1 = torch.Tensor(t1):type(t2:type())
elseif (th2 == "table") then
t2 = torch.Tensor(t2):type(t1:type())
elseif (th1 ~= th2) then
t1 = t1:type("torch.DoubleTensor")
t2 = t2:type("torch.DoubleTensor")
end
return torch.all(t1:eq(t2))
end
local function tds_comp(t1, t2)
if (table.exact_length(t1) ~=
table.exact_length(t2)) then
return false
end
for pos,val in pairs(t1) do
if (t2[pos] ~= val) then
return false
end
end
return true
end
local function format(val)
return astate.format_argument(val) or tostring(val)
end
local isnan = function(val)
return val ~= val
end
local function deepcompare(t1,t2,ignore_mt,cycles,thresh1,thresh2)
local ty1 = torch.type(t1)
local ty2 = torch.type(t2)
-- non-table types can be directly compared
if (ty1:match("^tds") and ty1:match("^tds")) then
return tds_comp(t1, t2)
elseif (ty1:match("^torch.*Tensor") and ty1:match("^torch.*Tensor")) then
return tensor_comp(t1, t2)
elseif (ty1 ~= 'table' or ty2 ~= 'table') then
if (isnan(t1)) then
return isnan(t2)
end
return t1 == t2
end
local mt1 = debug.getmetatable(t1)
local mt2 = debug.getmetatable(t2)
-- would equality be determined by metatable __eq?
if mt1 and mt1 == mt2 and mt1.__eq then
-- then use that unless asked not to
if not ignore_mt then
return t1 == t2 end
else -- we can skip the deep comparison below if t1 and t2 share identity
if rawequal(t1, t2) then return true end
end
-- handle recursive tables
cycles = cycles or {{},{}}
thresh1, thresh2 = (thresh1 or 1), (thresh2 or 1)
cycles[1][t1] = (cycles[1][t1] or 0)
cycles[2][t2] = (cycles[2][t2] or 0)
if cycles[1][t1] == 1 or cycles[2][t2] == 1 then
thresh1 = cycles[1][t1] + 1
thresh2 = cycles[2][t2] + 1
end
if cycles[1][t1] > thresh1 and cycles[2][t2] > thresh2 then
return true
end
cycles[1][t1] = cycles[1][t1] + 1
cycles[2][t2] = cycles[2][t2] + 1
for k1,v1 in next, t1 do
local v2 = t2[k1]
if v2 == nil then
return false, {k1}
end
local same, crumbs = deepcompare(v1,v2,nil,cycles,thresh1,thresh2)
if not same then
crumbs = crumbs or {}
table.insert(crumbs, k1)
return false, crumbs
end
end
for k2,_ in next, t2 do
-- only check wether each element has a t1 counterpart, actual comparison
-- has been done in first loop above
if t1[k2] == nil then return false, {k2} end
end
cycles[1][t1] = cycles[1][t1] - 1
cycles[2][t2] = cycles[2][t2] - 1
return true
end
local function check_if_nan(state, arguments, level)
local level = (level or 1) + 1
local argcnt = arguments.n
assert(argcnt > 0, s("assertion.internal.argtolittle", { "same", 1, tostring(argcnt) }), level)
set_failure_message(state, arguments[2])
return arguments[1] ~= arguments[1]
end
-- Adapation of the original same function for torch and Dataframe compatibility
local function torch_same(state, arguments, level)
local level = (level or 1) + 1
local argcnt = arguments.n
assert(argcnt > 1, s("assertion.internal.argtolittle", { "same", 2, tostring(argcnt) }), level)
for i=1,2 do
if (torch.type(arguments[i]):match("Dataseries")) then
arguments[i] = arguments[i]:to_table()
end
end
if torch.type(arguments[1]) == 'table' and
torch.type(arguments[2]) == 'table' then
local result, crumbs = deepcompare(arguments[1], arguments[2], true)
-- switch arguments for proper output message
-- util.tinsert(arguments, 1, util.tremove(arguments, 2))
arguments.fmtargs = arguments.fmtargs or {}
arguments.fmtargs[1] = { crumbs = crumbs }
arguments.fmtargs[2] = { crumbs = crumbs }
set_failure_message(state, arguments[3])
return result
end
if (torch.type(arguments[1]):match("torch.*Tensor") or
torch.type(arguments[2]):match("torch.*Tensor")) then
set_failure_message(state, arguments[3])
return tensor_comp(arguments[1], arguments[2])
end
if(torch.type(arguments[1]):match("^tds.") or
torch.type(arguments[2]):match("^tds.")) then
set_failure_message(state, arguments[3])
return tds_comp(arguments[1], arguments[2])
end
local result = arguments[1] == arguments[2]
-- switch arguments for proper output message
-- skip the flip: util.tinsert(arguments, 1, util.tremove(arguments, 2))
set_failure_message(state, arguments[3])
return result
end
local function torch_same_elements(state, arguments, level)
local level = (level or 1) + 1
local argcnt = arguments.n
assert(argcnt > 1, s("assertion.internal.argtolittle", { "same", 2, tostring(argcnt) }), level)
for i=1,2 do
if (torch.type(arguments[i]):match("Dataseries") or
torch.type(arguments[i]):match("torch.*Tensor")) then
arguments[i] = arguments[i]:to_table()
end
end
set_failure_message(state, arguments[3])
for _,needle in ipairs(arguments[1]) do
found = false
for _,hay in ipairs(arguments[2]) do
if (needle == hay) then
found = true
break
end
end
if (not found) then
return false
end
end
return true
end
local function torch_same_keys(state, arguments, level)
local level = (level or 1) + 1
local argcnt = arguments.n
assert(argcnt > 1, s("assertion.internal.argtolittle", { "same", 2, tostring(argcnt) }), level)
for i=1,2 do
if (torch.type(arguments[i]):match("Dataseries") or
torch.type(arguments[i]):match("torch.*Tensor")) then
arguments[i] = arguments[i]:to_table()
end
end
set_failure_message(state, arguments[3])
for needle,_ in pairs(arguments[1]) do
found = false
for hay,_ in pairs(arguments[2]) do
if (needle == hay) then
found = true
break
end
end
if (not found) then
return false
end
end
return true
end
-- Override the original "same" with our own method
assert:register("assertion", "same",
torch_same,
"assertion.same.positive", "assertion.same.negative")
-- Register custom helperes
assert:register("assertion", "same_keys",
torch_same_keys,
"assertion.same.positive", "assertion.same.negative")
assert:register("assertion", "same_elements",
torch_same_elements,
"assertion.same.positive", "assertion.same.negative")
assert:register("assertion", "nan",
check_if_nan,
"assertion.same.positive", "assertion.same.negative")
|
--- 导入需要的模块
local modbus_master = require 'modbus.master.skynet'
local modbus_pdu = require 'modbus.pdu.init'
local data_pack = require 'modbus.data.pack'
local data_unpack = require 'modbus.data.unpack'
local queue = require 'skynet.queue'
local csv_tpl = require 'csv_tpl'
local packet_split = require 'packet_split'
local valid_value = require 'valid_value'
local conf_helper = require 'app.conf_helper'
local base_app = require 'app.base'
local basexx = require 'basexx'
--- 注册对象(请尽量使用唯一的标识字符串)
local app = base_app:subclass("MODBUS_LUA_MASTER_APP")
--- 设定应用最小运行接口版本
app.static.API_VER = 5
--- 应用启动函数
function app:on_start()
csv_tpl.init(self._sys:app_dir())
---获取设备序列号和应用配置
local sys_id = self._sys:id()
local config = self._conf or {}
--[[
config.devs = config.devs or {
{ unit = 1, name = 'bms01', sn = 'xxx-xx-1', tpl = 'bms' },
{ unit = 2, name = 'bms02', sn = 'xxx-xx-2', tpl = 'bms2' }
}
]]--
--- 获取云配置
if not config.devs and config.cnf and conf.ver then
config = config.cnf .. '.' .. config.ver
end
--[[ test
if not config.cnf then
config = 'CNF000000003.1' -- loading cloud configuration CNF000000002 version 1
end
]]--
local helper = conf_helper:new(self._sys, config)
helper:fetch()
self._pdu = modbus_pdu:new()
self._data_pack = data_pack:new()
self._data_unpack = data_unpack:new()
self._split = packet_split:new(self._data_pack, self._data_unpack)
local dev_sn_prefix = config.dev_sn_prefix ~= nil and config.dev_sn_prefix or true
self._devs = {}
for _, v in ipairs(helper:devices()) do
assert(v.sn and v.name and v.unit and v.tpl)
--- 生成设备的序列号
local dev_sn = dev_sn_prefix and sys_id.."."..v.sn or v.sn
self._log:debug("Loading template file", v.tpl)
local tpl, err = csv_tpl.load_tpl(v.tpl, function(...) self._log:error(...) end)
if not tpl then
self._log:error("loading csv tpl failed", err)
else
local meta = self._api:default_meta()
meta.name = tpl.meta.name or "Modbus"
meta.description = tpl.meta.desc or "Modbus Device"
meta.series = tpl.meta.series or "XXX"
meta.inst = v.name
local inputs = {}
local outputs = {}
local tpl_inputs = {}
local tpl_outputs = {}
for _, v in ipairs(tpl.props) do
if string.find(v.rw, '[Rr]') then
inputs[#inputs + 1] = {
name = v.name,
desc = v.desc,
vt = v.vt,
unit = v.unit,
}
tpl_inputs[#tpl_inputs + 1] = v
end
if string.find(v.rw, '[Ww]') then
outputs[#outputs + 1] = {
name = v.name,
desc = v.desc,
unit = v.unit,
}
tpl_outputs[#tpl_outputs + 1] = v
end
end
local packets = self._split:split(tpl_inputs, v.pack_opt)
--- 生成设备对象
local dev = self._api:add_device(dev_sn, meta, inputs, outputs)
--- 生成设备通讯口统计对象
local stat = dev:stat('port')
table.insert(self._devs, {
unit = tonumber(v.unit) or 0,
sn = dev_sn,
dev = dev,
tpl = tpl,
stat = stat,
packets = packets,
inputs = tpl_inputs,
outputs = tpl_outputs,
})
end
end
--- 获取配置
local conf = helper:config()
conf.channel_type = conf.channel_type or 'socket'
if conf.channel_type == 'socket' then
conf.opt = conf.socket_opt or {
host = "127.0.0.1",
port = 1503,
nodelay = true
}
else
conf.opt = conf.serial_opt or {
port = "/tmp/ttyS1",
baudrate = 19200
}
end
self._loop_gap = conf.loop_gap or self._conf.loop_gap
if conf.channel_type == 'socket' then
self._modbus = modbus_master(string.lower(conf.apdu_type or 'tcp'), {link='tcp', tcp=conf.opt})
self._block = string.lower(conf.apdu_type or 'tcp') ~= 'tcp'
else
self._modbus = modbus_master(string.lower(conf.apdu_type or 'rtu'), {link='serial', serial=conf.opt})
self._block = true
end
if self._block then
self._queue = queue()
else
-- fake queue
self._queue = function(f, ...)
return f(...)
end
end
--- 设定通讯口数据回调
self._modbus:set_io_cb(function(io, unit, msg)
--[[
if string.lower(conf.apdu_type) == 'ascii' then
self._log:trace(io, msg)
else
self._log:trace(io, basexx.to_hex(msg))
end
]]--
local dev = nil
for _, v in ipairs(self._devs) do
if v.unit == tonumber(unit) then
dev = v
break
end
end
--- 输出通讯报文
if dev then
dev.dev:dump_comm(io, msg)
--- 计算统计信息
if io == 'IN' then
dev.stat:inc('bytes_in', string.len(msg))
else
dev.stat:inc('bytes_out', string.len(msg))
end
else
self._sys:dump_comm(sys_id, io, msg)
end
end)
return self._modbus:start()
end
--- 应用退出函数
function app:on_close(reason)
local close_modbus = function()
if self._modbus then
self._modbus:stop()
self._modbus = nil
end
end
if self._queue then
self._log:debug("Wait for reading queue finished")
self._queue(function()
self._log:debug("Reading queue finished!")
close_modbus()
end)
else
close_modbus()
end
end
function app:on_output(app_src, sn, output, prop, value, timestamp)
if prop ~= 'value' then
return false, "Cannot write property which is not value"
end
local dev = nil
for _, v in ipairs(self._devs) do
if v.sn == sn then
dev = v
break
end
end
if not dev then
return false, "Cannot find device sn "..sn
end
local tpl_output = nil
for _, v in ipairs(dev.outputs or {}) do
if v.name == output then
tpl_output = v
break
end
end
if not tpl_output then
return false, "Cannot find output "..sn.."."..output
end
local val = value
if tpl_output.rate and tpl_output.rate ~= 1 then
val = val / tpl_output.rate
end
local val, err = valid_value(tpl_output.dt, val)
if not val then
self._log:error("Write value validation", err)
return false, err
end
--- UINT8, INT8 hacks
if tpl_output.dt == 'int8' or tpl_output.dt == 'uint8' then
local link_val = 0
local link_offset = tpl_output.offset == 1 and 0 or 1
for _, v in ipairs(dev.inputs) do
--- Check function code and addr and offset
if v.fc == tpl_output.fc and v.addr == tpl_output.addr and v.offset == link_offset then
-- check data type
if v.dt == 'uint8' or v.dt == 'int8' then
link_val = dev.dev:get_input_prop(v.name, 'value')
if v.rate ~= 1 then
link_val = link_val / v.rate
end
if tpl_output.dt ~= v.dt then
if tpl_output.dt == 'uint8' then
link_val = (link_val + 256) % 256
else
link_val = (link_val - 128) % 256 - 128
end
end
end
end
end
--- TODO: Take care about little endian stuff?????
if link_offset == 1 then
val = (val << 8 ) + link_val
else
val = (link_val << 8) + val
end
end
--- hacks end
if tpl_output.dt == 'bit' and tpl_output.wfc == 0x06 then
return nil, "Bit value readed from 0x03/0x04 cannot be write to device"
end
local r, err = self._queue(self.write_packet, self, dev.dev, dev.stat, dev.unit, tpl_output, val)
--[[
if not r then
local info = "Write output failure!"
local data = { sn=sn, output=output, prop=prop, value=value, err=err }
self._dev:fire_event(event.LEVEL_ERROR, event.EVENT_DEV, info, data)
end
]]--
return r, err or "Done"
end
function app:write_packet(dev, stat, unit, output, value)
--- 设定写数据的地址
local func = tonumber(output.wfc) or 0x06
local addr = output.addr
if not self._modbus then
return
end
local timeout = output.timeout or 5000
local req = nil
local err = nil
if output.wfc == 0x06 or output.wfc == 0x05 then
req, err = self._pdu:make_request(func, addr, value)
else
local dpack = self._data_pack
local data = dpack[output.dt](dpack, value)
req, err = self._pdu:make_request(func, addr, data)
end
if not req then
self._log:warning("Failed to build modbus request, error:", err)
return self:invalid_dev(dev, pack)
end
--- 写入数据
stat:inc('packets_out', 1)
local pdu, err = self._modbus:request(unit, req, timeout)
if not pdu then
self._log:warning("write failed: " .. err)
return nil, err
end
--- 统计数据
stat:inc('packets_in', 1)
return true, "Write Done!"
end
function app:read_packet(dev, stat, unit, pack, tpl)
assert(dev and stat and unit)
--- 设定读取的起始地址和读取的长度
local func = pack.fc or 0x03 -- 03指令
local addr = pack.start or 0x00
local len = pack.len or 10 -- 长度
if not self._modbus then
return
end
--- 读取数据
local timeout = pack.timeout or 5000
local req, err = self._pdu:make_request(func, addr, len)
if not req then
self._log:warning("Failed to build modbus request, error:", err)
return self:invalid_dev(dev, pack)
end
--- 统计数据
stat:inc('packets_out', 1)
--self._log:debug("Before request", unit, func, addr, len, timeout)
local pdu, err = self._modbus:request(unit, req, timeout)
if not pdu then
self._log:warning("read failed: " .. (err or "Timeout"))
stat:set('status', -1)
return self:invalid_dev(dev, pack)
end
--self._log:trace("read input registers done!", unit)
--- 统计数据
stat:inc('packets_in', 1)
stat:set('status', 0)
--- 解析数据
local d = self._data_unpack
if d:uint8(pdu, 1) == (0x80 + func) then
local basexx = require 'basexx'
self._log:warning("read package failed 0x"..basexx.to_hex(string.sub(pdu, 1, 1)))
return
end
local len = d:uint8(pdu, 2)
--assert(len >= pack.len * 2)
local pdu_data = string.sub(pdu, 3)
for _, input in ipairs(pack.inputs) do
local val, err = pack.unpack(input, pdu_data)
if val == nil then
assert(false, err or 'val is nil')
end
--- AI Calc
if tpl.ai_calc_list[input.name] then
local ac = tpl.ai_calc_list[input.name]
val = ((val - ac.in_min) * (ac.out_max - ac.out_min))/(ac.in_max - ac.in_min)
val = val + ac.out_min
end
--- Data Rate
if input.rate and input.rate ~= 1 then
val = val * input.rate
end
dev:set_input_prop(input.name, "value", val)
end
end
function app:invalid_dev(dev, pack)
for _, input in ipairs(pack.inputs) do
dev:set_input_prop(input.name, "value", 0, nil, 1)
end
end
function app:read_dev(dev, stat, unit, packets, tpl)
for _, pack in ipairs(packets) do
self._queue(self.read_packet, self, dev, stat, unit, pack, tpl)
end
end
--- 应用运行入口
function app:on_run(tms)
if not self._modbus then
return
end
local begin_time = self._sys:time()
local gap = self._loop_gap or 5000
for _, dev in ipairs(self._devs) do
if not self._modbus then
break
end
self:read_dev(dev.dev, dev.stat, dev.unit, dev.packets, dev.tpl)
end
local next_tms = gap - ((self._sys:time() - begin_time) * 1000)
return next_tms > 0 and next_tms or 0
end
--- 返回应用对象
return app
|
local constants = require('d2info.constants')
local utils = {}
function utils.friendlyVersion(ver)
return table.concat({ver.major, ver.minor, ver.build, ver.revision}, '.')
end
function utils.tableMerge(a, b)
local merged = {}
for k,v in pairs(b) do
merged[k] = v
end
-- a overwrites any duplicates in b
for k,v in pairs(a) do
merged[k] = v
end
return merged
end
function utils.friendlyNumber(num)
local abs = math.abs(num)
if abs >= 1000000000 then
return string.format("%0.1fb", num / 1000000000)
elseif abs >= 1000000 then
return string.format("%0.1fm", num / 1000000)
elseif abs >= 1000 then
return string.format("%0.1fk", num / 1000)
end
return string.format("%d", num)
end
local secondsPerMin = 60
local secondsPerHour = secondsPerMin * 60
local secondsPerDay = secondsPerHour * 24
function utils.friendlyTime(seconds, showDays)
if seconds == nil or seconds < 0 then
return "-"
elseif showDays and seconds >= secondsPerDay then
return string.format("%ud%02uh", math.floor(seconds / secondsPerDay), (seconds % secondsPerDay) / secondsPerHour)
elseif seconds >= secondsPerHour*10 then
return string.format("%uh", math.floor(seconds / secondsPerHour))
elseif seconds >= secondsPerHour then
return string.format("%uh%um", math.floor(seconds / secondsPerHour), (seconds % secondsPerHour) / secondsPerMin)
elseif seconds >= secondsPerMin then
return string.format("%um%02us", math.floor(seconds / secondsPerMin), seconds % secondsPerMin)
else
return string.format("%02usec", seconds)
end
end
function utils.printf(...)
print(string.format(...))
end
function utils.toFile(filename, txt)
local f = assert(io.open(filename, "w"))
f:write(txt)
f:close()
end
function utils.expToPercentLeveled(exp, level)
if level == 99 then return 0 end
local expRange = constants.experience[level+1] - constants.experience[level]
local expGotten = exp - constants.experience[level]
return expGotten / expRange
end
-- Converts exp to GUI 'ticks' of the experience bar
function utils.expToTicks(exp, level)
if level == 99 then return 0 end
local maxTicks = constants.gui.expBar.ticks
local percentLeveled = utils.expToPercentLeveled(exp, level)
return percentLeveled * maxTicks
end
-- The GUI bar is full at 119 ticks rather than the full 120
-- (i.e. with the XP bar totally full there is still 1 tick left to gain)
-- so this can be used to determine whether or not a tick has actually
-- appeared on the XP bar GUI
function utils.expToVisualTicks(exp, level)
if level == 99 then return 0 end
local maxVisualTicks = constants.gui.expBar.ticks - 1
local percentLeveled = utils.expToPercentLeveled(exp, level)
return percentLeveled * maxVisualTicks
end
function utils.expToNextVisualTick(exp, level)
if level == 99 then return 0 end
local maxVisualTicks = constants.gui.expBar.ticks - 1
local expRange = constants.experience[level+1] - constants.experience[level]
local expGotten = exp - constants.experience[level]
local expPerVisualTick = math.floor(expRange / maxVisualTicks)
return expPerVisualTick - (expGotten % expPerVisualTick)
end
local underLevel25 = {
[10] = 0.02, [9] = 0.15, [8] = 0.36, [7] = 0.68, [6] = 0.88, [-6] = 0.81, [-7] = 0.62, [-8] = 0.43, [-9] = 0.24, [-10] = 0.05
}
local level25Plus = {
[-6] = 0.81, [-7] = 0.62, [-8] = 0.43, [-9] = 0.24, [-10] = 0.05
}
function utils.expLevelDifference(mlvl, clvl)
local diff = mlvl-clvl
if clvl < 25 then
if underLevel25[diff] then
return underLevel25[diff]
elseif diff > 10 then
return 0.02
elseif diff < -10 then
return 0.05
else
return 1.0
end
else
-- For any monster above your level, you get EXP*(Player Level / Monster Level).
if diff > 0 then
return clvl / mlvl
elseif level25Plus[diff] then
return level25Plus[diff]
elseif diff <= -10 then
return 0.05
else
return 1.0
end
end
end
function utils.expLevelPenalty(clvl)
return constants.experienceLevelPenalties[clvl] or 1
end
function utils.expGain(mlvl, clvl)
return utils.expLevelDifference(mlvl, clvl) * utils.expLevelPenalty(clvl)
end
-- replace all non-whitespace characters with space characters
-- e.g. "ab\n \t c" should become " \n \t "
function utils.makeWhitespace(str)
return str:gsub("[^\n\r\t ]", " ")
end
-- add space characters to a buf in order to
-- make it completely overwrite the previous buf
function utils.padBuf(cur, last)
if not last then return cur end
local padded = {}
for i,v in ipairs(cur) do
padded[i] = v
end
for i,v in ipairs(last) do
if not cur[i] then
padded[i] = utils.makeWhitespace(v)
elseif #cur[i] < #v then
local remainder = v:sub(#cur[i])
padded[i] = cur[i] .. utils.makeWhitespace(remainder)
end
end
return padded
end
return utils
|
-- scaffolding entry point for zopfli
return dofile("zopfli.lua")
|
---
-- DICOM library
--
-- This library implements (partially) the DICOM protocol. This protocol is used to
-- capture, store and distribute medical images.
--
-- From Wikipedia:
-- The core application of the DICOM standard is to capture, store and distribute
-- medical images. The standard also provides services related to imaging such as
-- managing imaging procedure worklists, printing images on film or digital media
-- like DVDs, reporting procedure status like completion of an imaging acquisition,
-- confirming successful archiving of images, encrypting datasets, removing patient
-- identifying information from datasets, organizing layouts of images for review,
-- saving image manipulations and annotations, calibrating image displays, encoding
-- ECGs, encoding CAD results, encoding structured measurement data, and storing
-- acquisition protocols.
--
-- OPTIONS:
-- *<code>called_aet</code> - If set it changes the called Application Entity Title
-- used in the requests. Default: ANY-SCP
-- *<code>calling_aet</code> - If set it changes the calling Application Entity Title
-- used in the requests. Default: ECHOSCU
--
-- @args dicom.called_aet Called Application Entity Title. Default: ANY-SCP
-- @args dicom.calling_aet Calling Application Entity Title. Default: ECHOSCU
--
-- @author Paulino Calderon <paulino@calderonpale.com>
-- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html
---
local nmap = require "nmap"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
_ENV = stdnse.module("dicom", stdnse.seeall)
local MIN_SIZE_ASSOC_REQ = 68
local MAX_SIZE_PDU = 128000
local MIN_HEADER_LEN = 6
local PDU_NAMES = {}
local PDU_CODES = {}
PDU_CODES =
{
ASSOCIATE_REQUEST = 0x01,
ASSOCIATE_ACCEPT = 0x02,
ASSOCIATE_REJECT = 0x03,
DATA = 0x04,
RELEASE_REQUEST = 0x05,
RELEASE_RESPONSE = 0x06,
ABORT = 0x07
}
for i, v in pairs(PDU_CODES) do
PDU_NAMES[v] = i
end
---
-- start_connection(host, port) starts socket to DICOM service
--
-- @param host Host object
-- @param port Port table
-- @return (status, socket) If status is true, socket of DICOM object is set.
-- If status is false, socket is the error message.
---
function start_connection(host, port)
local dcm = {}
local status, err
dcm['socket'] = nmap.new_socket()
status, err = dcm['socket']:connect(host, port, "tcp")
if(status == false) then
return false, "DICOM: Failed to connect to host: " .. err
end
return true, dcm
end
---
-- send(dcm, data) Sends DICOM packet over established socket
--
-- @param dcm DICOM object
-- @param data Data to send
-- @return status True if data was sent correctly, otherwise false and error message is returned.
---
function send(dcm, data)
local status, err
stdnse.debug2("DICOM: Sending DICOM packet (%d)", #data)
if dcm['socket'] then
status, err = dcm['socket']:send(data)
if status == false then
return false, err
end
else
return false, "No socket found. Check your DICOM object"
end
return true
end
---
-- receive(dcm) Reads DICOM packets over an established socket
--
-- @param dcm DICOM object
-- @return (status, data) Returns data if status true, otherwise data is the error message.
---
function receive(dcm)
local status, data = dcm['socket']:receive()
if status == false then
return false, data
end
stdnse.debug1("DICOM: receive() read %d bytes", #data)
return true, data
end
---
-- pdu_header_encode(pdu_type, length) encodes the DICOM PDU header
--
-- @param pdu_type PDU type as ann unsigned integer
-- @param length Length of the DICOM message
-- @return (status, dcm) If status is true, the DICOM object with the header set is returned.
-- If status is false, dcm is the error message.
---
function pdu_header_encode(pdu_type, length)
-- Some simple sanity checks, we do not check ranges to allow users to create malformed packets.
if not(type(pdu_type)) == "number" then
return false, "PDU Type must be an unsigned integer. Range:0-7"
end
if not(type(length)) == "number" then
return false, "Length must be an unsigned integer."
end
local header = string.pack("<B >B I4",
pdu_type, -- PDU Type ( 1 byte - unsigned integer in Big Endian )
0, -- Reserved section ( 1 byte that should be set to 0x0 )
length) -- PDU Length ( 4 bytes - unsigned integer in Little Endian)
if #header < MIN_HEADER_LEN then
return false, "Header must be at least 6 bytes. Something went wrong."
end
return true, header
end
---
-- associate(host, port) Attempts to associate to a DICOM Service Provider by sending an A-ASSOCIATE request.
--
-- @param host Host object
-- @param port Port object
-- @return (status, dcm) If status is true, the DICOM object is returned.
-- If status is false, dcm is the error message.
---
function associate(host, port, calling_aet, called_aet)
local application_context = ""
local presentation_context = ""
local userinfo_context = ""
local status, dcm = start_connection(host, port)
if status == false then
return false, dcm
end
local application_context_name = "1.2.840.10008.3.1.1.1"
application_context = string.pack(">B B I2 c" .. #application_context_name,
0x10,
0x0,
#application_context_name,
application_context_name)
local abstract_syntax_name = "1.2.840.10008.1.1"
local transfer_syntax_name = "1.2.840.10008.1.2"
presentation_context = string.pack(">B B I2 B B B B B B I2 c" .. #abstract_syntax_name .. "B B I2 c".. #transfer_syntax_name,
0x20, -- Presentation context type ( 1 byte )
0x0, -- Reserved ( 1 byte )
0x2e, -- Item Length ( 2 bytes )
0x1, -- Presentation context id ( 1 byte )
0x0,0x0,0x0, -- Reserved ( 3 bytes )
0x30, -- Abstract Syntax Tree ( 1 byte )
0x0, -- Reserved ( 1 byte )
0x11, -- Item Length ( 2 bytes )
abstract_syntax_name,
0x40, -- Transfer Syntax ( 1 byte )
0x0, -- Reserved ( 1 byte )
0x11, -- Item Length ( 2 bytes )
transfer_syntax_name)
local implementation_id = "1.2.276.0.7230010.3.0.3.6.2"
local implementation_version = "OFFIS_DCMTK_362"
userinfo_context = string.pack(">B B I2 B B I2 I4 B B I2 c" .. #implementation_id .. " B B I2 c".. #implementation_version,
0x50, -- Type 0x50 (1 byte)
0x0, -- Reserved ( 1 byte )
0x3a, -- Length ( 2 bytes )
0x51, -- Type 0x51 ( 1 byte)
0x0, -- Reserved ( 1 byte)
0x04, -- Length ( 2 bytes )
0x4000, -- DATA ( 4 bytes )
0x52, -- Type 0x52 (1 byte)
0x0,
0x1b,
implementation_id,
0x55,
0x0,
0x0f,
implementation_version)
local called_ae_title = called_aet or stdnse.get_script_args("dicom.called_aet") or "ANY-SCP"
local calling_ae_title = calling_aet or stdnse.get_script_args("dicom.calling_aet") or "ECHOSCU"
if #called_ae_title > 16 or #calling_ae_title > 16 then
return false, "Calling/Called Application Entity Title must be less than 16 bytes"
end
called_ae_title = called_ae_title .. string.rep(" ", 16 - #called_ae_title)
calling_ae_title = calling_ae_title .. string.rep(" ", 16 - #calling_ae_title)
-- ASSOCIATE request
local assoc_request = string.pack(">I2 I2 c16 c16 c32 c" .. application_context:len() .. " c" .. presentation_context:len() .. " c" .. userinfo_context:len(),
0x1, -- Protocol version ( 2 bytes )
0x0, -- Reserved section ( 2 bytes that should be set to 0x0 )
called_ae_title, -- Called AE title ( 16 bytes)
calling_ae_title, -- Calling AE title ( 16 bytes)
0x0, -- Reserved section ( 32 bytes set to 0x0 )
application_context,
presentation_context,
userinfo_context)
local status, header = pdu_header_encode(PDU_CODES["ASSOCIATE_REQUEST"], #assoc_request)
-- Something might be wrong with our header
if status == false then
return false, header
end
assoc_request = header .. assoc_request
stdnse.debug2("PDU len minus header:%d", #assoc_request-#header)
if #assoc_request < MIN_SIZE_ASSOC_REQ then
return false, string.format("ASSOCIATE request PDU must be at least %d bytes and we tried to send %d.", MIN_SIZE_ASSOC_REQ, #assoc_request)
end
local status, err = send(dcm, assoc_request)
if status == false then
return false, string.format("Couldn't send ASSOCIATE request:%s", err)
end
status, err = receive(dcm)
if status == false then
return false, string.format("Couldn't read ASSOCIATE response:%s", err)
end
local resp_type, _, resp_length = string.unpack(">B B I4", err)
stdnse.debug1("PDU Type:%d Length:%d", resp_type, resp_length)
if resp_type == PDU_CODES["ASSOCIATE_ACCEPT"] then
stdnse.debug1("ASSOCIATE ACCEPT message found!")
return true, dcm
elseif resp_type == PDU_CODES["ASSOCIATE_REJECT"] then
stdnse.debug1("ASSOCIATE REJECT message found!")
return false, "ASSOCIATE REJECT received"
else
return false, "Received unknown response"
end
end
function send_pdata(dicom, data)
local status, header = pdu_header_encode(PDU_CODES["DATA"], #data)
if status == false then
return false, header
end
local err
status, err = send(dicom, header .. data)
if status == false then
return false, err
end
end
return _ENV
|
local lib, oldminor = LibStub:NewLibrary("tekKonfig-AboutPanel", 5)
if not lib then return end
function lib.new(parent, addonname)
local frame = CreateFrame("Frame", nil, InterfaceOptionsFramePanelContainer)
frame.name, frame.parent, frame.addonname = parent and "About" or addonname, parent, addonname
frame:Hide()
frame:SetScript("OnShow", lib.OnShow)
InterfaceOptions_AddCategory(frame)
return frame
end
local editbox = CreateFrame('EditBox', nil, UIParent)
editbox:Hide()
editbox:SetAutoFocus(true)
editbox:SetHeight(32)
editbox:SetFontObject('GameFontHighlightSmall')
lib.editbox = editbox
local left = editbox:CreateTexture(nil, "BACKGROUND")
left:SetWidth(8) left:SetHeight(20)
left:SetPoint("LEFT", -5, 0)
left:SetTexture("Interface\\Common\\Common-Input-Border")
left:SetTexCoord(0, 0.0625, 0, 0.625)
local right = editbox:CreateTexture(nil, "BACKGROUND")
right:SetWidth(8) right:SetHeight(20)
right:SetPoint("RIGHT", 0, 0)
right:SetTexture("Interface\\Common\\Common-Input-Border")
right:SetTexCoord(0.9375, 1, 0, 0.625)
local center = editbox:CreateTexture(nil, "BACKGROUND")
center:SetHeight(20)
center:SetPoint("RIGHT", right, "LEFT", 0, 0)
center:SetPoint("LEFT", left, "RIGHT", 0, 0)
center:SetTexture("Interface\\Common\\Common-Input-Border")
center:SetTexCoord(0.0625, 0.9375, 0, 0.625)
editbox:SetScript("OnEscapePressed", editbox.ClearFocus)
editbox:SetScript("OnEnterPressed", editbox.ClearFocus)
editbox:SetScript("OnEditFocusLost", editbox.Hide)
editbox:SetScript("OnEditFocusGained", editbox.HighlightText)
editbox:SetScript("OnTextChanged", function(self)
self:SetText(self:GetParent().val)
self:HighlightText()
end)
function lib.OpenEditbox(self)
editbox:SetText(self.val)
editbox:SetParent(self)
editbox:SetPoint("LEFT", self)
editbox:SetPoint("RIGHT", self)
editbox:Show()
end
local fields = {"Version", "Author", "X-Category", "X-License", "X-Email", "X-Website", "X-Credits"}
local haseditbox = {["Version"] = true, ["X-Website"] = true, ["X-Email"] = true}
local function HideTooltip() GameTooltip:Hide() end
local function ShowTooltip(self)
GameTooltip:SetOwner(self, "ANCHOR_TOPRIGHT")
GameTooltip:SetText("Click and press Ctrl-C to copy")
end
function lib.OnShow(frame)
local notes = GetAddOnMetadata(frame.addonname, "Notes")
local title = frame:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
title:SetPoint("TOPLEFT", 16, -16)
title:SetText((frame.parent or frame.addonname).." - About")
local subtitle = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
subtitle:SetHeight(32)
subtitle:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -8)
subtitle:SetPoint("RIGHT", parent, -32, 0)
subtitle:SetNonSpaceWrap(true)
subtitle:SetJustifyH("LEFT")
subtitle:SetJustifyV("TOP")
subtitle:SetText(notes)
local anchor
for _,field in pairs(fields) do
local val = GetAddOnMetadata(frame.addonname, field)
if val then
local title = frame:CreateFontString(nil, "ARTWORK", "GameFontNormalSmall")
title:SetWidth(75)
if not anchor then title:SetPoint("TOPLEFT", subtitle, "BOTTOMLEFT", -2, -8)
else title:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 0, -6) end
title:SetJustifyH("RIGHT")
title:SetText(field:gsub("X%-", ""))
local detail = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
detail:SetPoint("LEFT", title, "RIGHT", 4, 0)
detail:SetPoint("RIGHT", -16, 0)
detail:SetJustifyH("LEFT")
detail:SetText((haseditbox[field] and "|cff9999ff" or "").. val)
if haseditbox[field] then
local button = CreateFrame("Button", nil, frame)
button:SetAllPoints(detail)
button.val = val
button:SetScript("OnClick", lib.OpenEditbox)
button:SetScript("OnEnter", ShowTooltip)
button:SetScript("OnLeave", HideTooltip)
end
anchor = title
end
end
frame:SetScript("OnShow", nil)
end
|
require 'nn'
local models = {}
models.basic_parallel = function()
local m = nn.Sequential()
local prl = nn.ParallelTable()
prl:add(nn.Linear(2,2))
prl:add(nn.Sequential():add(nn.Linear(2,1)):add(nn.Sigmoid()):add(nn.Linear(1,1)))
m:add(prl)
m:add(nn.JoinTable(2))
m:add(nn.Linear(3,2))
m:add(nn.ReLU(true))
local input = {torch.rand(2,2), torch.rand(2,2)}
return m, input
end
models.basic_conv = function()
local m = nn.Sequential()
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
-- m:add(nn.ReLU(true))
-- m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
-- m:add(nn.ReLU(true))
m:add(nn.View(32*32):setNumInputDims(3))
m:add(nn.Linear(32*32,100))
-- m:add(nn.ReLU(true))
-- m:add(nn.Linear(100,10))
local input = torch.rand(1,1,32,32)
return m, input
end
models.basic_deep_conv = function()
local inplace = true
local m = nn.Sequential()
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
m:add(nn.ReLU(inplace))
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
m:add(nn.ReLU(inplace))
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
m:add(nn.ReLU(inplace))
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
m:add(nn.ReLU(inplace))
m:add(nn.View(32*32):setNumInputDims(3))
m:add(nn.Linear(32*32,100))
m:add(nn.ReLU(inplace))
m:add(nn.Linear(100,10))
local input = torch.rand(1,1,32,32)
return m, input
end
models.basic_unpooling = function()
local inplace = true
local m = nn.Sequential()
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
m:add(nn.ReLU(inplace))
local mp1 = nn.SpatialMaxPooling(2,2,2,2)
m:add(mp1)
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
m:add(nn.ReLU(inplace))
local mp2 = nn.SpatialMaxPooling(2,2,2,2)
m:add(mp2)
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
m:add(nn.ReLU(inplace))
m:add(nn.SpatialMaxUnpooling(mp2))
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
m:add(nn.ReLU(inplace))
m:add(nn.SpatialMaxUnpooling(mp1))
m:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
local input = torch.rand(1,1,32,32)
return m, input
end
models.siamese = function()
local inplace = false
local b1 = nn.Sequential()
b1:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
b1:add(nn.ReLU(inplace))
b1:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
b1:add(nn.ReLU(inplace))
b1:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
b1:add(nn.ReLU(inplace))
b1:add(nn.SpatialConvolution(1,1,3,3,1,1,1,1))
b1:add(nn.ReLU(inplace))
b1:add(nn.View(-1):setNumInputDims(3))
local b2 = b1:clone('weight','bias','gradWeight','gradBias')
local prl = nn.ParallelTable()
prl:add(b1)
prl:add(b2)
m = nn.Sequential()
m:add(prl)
m:add(nn.PairwiseDistance(2))
local input = {torch.rand(1,1,32,32), torch.rand(1,1,32,32)}
return m, input
end
models.basic_concat = function()
local m = nn.Sequential()
local cat = nn.ConcatTable()
local b1 = nn.Sequential():add(nn.Linear(2,1)):add(nn.ReLU(true)):add(nn.Linear(1,1))
local b2 = nn.Sequential():add(nn.Linear(2,2)):add(nn.ReLU())
local b3 = nn.Sequential():add(nn.Linear(2,3)):add(nn.ReLU(true)):add(nn.Linear(3,2))
cat:add(b1):add(b2):add(b3)
local cat2 = nn.ConcatTable()
local bb1 = nn.SelectTable(1)
local bb2 = nn.NarrowTable(2,2)
cat2:add(bb1):add(bb2)
local prl = nn.ParallelTable()
local bbb1 = nn.Sequential():add(nn.Linear(1,2))
local bbb2 = nn.CAddTable()
prl:add(bbb1):add(bbb2)
local final = nn.CMulTable()
m:add(cat):add(cat2):add(prl):add(final)
local input = torch.rand(2,2)
return m, input
end
models.basic_multiOutput = function()
local m = nn.Sequential()
m:add(nn.Linear(2,2))
m:add(nn.ReLU())
m:add(nn.Linear(2,2))
m:add(nn.ReLU())
m:add(nn.Linear(2,2))
m:add(nn.ReLU())
local p = nn.ConcatTable()
p:add(nn.Linear(2,2))
p:add(nn.Linear(2,2))
p:add(nn.Linear(2,2))
m:add(p)
local input = torch.rand(2,2)
return m, input
end
models.alexnet = function()
-- taken from soumith's imagenet-multiGPU
-- https://github.com/soumith/imagenet-multiGPU.torch/blob/master/models/alexnet.lua
local features = nn.Concat(2)
local fb1 = nn.Sequential() -- branch 1
fb1:add(nn.SpatialConvolution(3,48,11,11,4,4,2,2)) -- 224 -> 55
fb1:add(nn.ReLU(true))
fb1:add(nn.SpatialMaxPooling(3,3,2,2)) -- 55 -> 27
fb1:add(nn.SpatialConvolution(48,128,5,5,1,1,2,2)) -- 27 -> 27
fb1:add(nn.ReLU(true))
fb1:add(nn.SpatialMaxPooling(3,3,2,2)) -- 27 -> 13
fb1:add(nn.SpatialConvolution(128,192,3,3,1,1,1,1)) -- 13 -> 13
fb1:add(nn.ReLU(true))
fb1:add(nn.SpatialConvolution(192,192,3,3,1,1,1,1)) -- 13 -> 13
fb1:add(nn.ReLU(true))
fb1:add(nn.SpatialConvolution(192,128,3,3,1,1,1,1)) -- 13 -> 13
fb1:add(nn.ReLU(true))
fb1:add(nn.SpatialMaxPooling(3,3,2,2)) -- 13 -> 6
local fb2 = fb1:clone() -- branch 2
for k,v in ipairs(fb2:findModules('nn.SpatialConvolution')) do
v:reset() -- reset branch 2's weights
end
features:add(fb1)
features:add(fb2)
-- 1.3. Create Classifier (fully connected layers)
local classifier = nn.Sequential()
classifier:add(nn.View(256*6*6))
--classifier:add(nn.Dropout(0.5))
classifier:add(nn.Linear(256*6*6, 4096))
classifier:add(nn.Threshold(0, 1e-6))
--classifier:add(nn.Dropout(0.5))
classifier:add(nn.Linear(4096, 4096))
classifier:add(nn.Threshold(0, 1e-6))
classifier:add(nn.Linear(4096, 1000))
classifier:add(nn.LogSoftMax())
-- 1.4. Combine 1.1 and 1.3 to produce final model
local model = nn.Sequential():add(features):add(classifier)
model.imageSize = 256
model.imageCrop = 224
local input = torch.rand(1,3,model.imageCrop,model.imageCrop)
return model, input
end
models.googlenet = function()
-- taken from soumith's imagenet-multiGPU
-- https://github.com/soumith/imagenet-multiGPU.torch/blob/master/models/googlenet.lua
local function inception(input_size, config)
local concat = nn.Concat(2)
if config[1][1] ~= 0 then
local conv1 = nn.Sequential()
conv1:add(nn.SpatialConvolution(input_size, config[1][1],1,1,1,1)):add(nn.ReLU(true))
concat:add(conv1)
end
local conv3 = nn.Sequential()
conv3:add(nn.SpatialConvolution( input_size, config[2][1],1,1,1,1)):add(nn.ReLU(true))
conv3:add(nn.SpatialConvolution(config[2][1], config[2][2],3,3,1,1,1,1)):add(nn.ReLU(true))
concat:add(conv3)
local conv3xx = nn.Sequential()
conv3xx:add(nn.SpatialConvolution( input_size, config[3][1],1,1,1,1)):add(nn.ReLU(true))
conv3xx:add(nn.SpatialConvolution(config[3][1], config[3][2],3,3,1,1,1,1)):add(nn.ReLU(true))
conv3xx:add(nn.SpatialConvolution(config[3][2], config[3][2],3,3,1,1,1,1)):add(nn.ReLU(true))
concat:add(conv3xx)
local pool = nn.Sequential()
pool:add(nn.SpatialZeroPadding(1,1,1,1)) -- remove after getting nn R2 into fbcode
if config[4][1] == 'max' then
pool:add(nn.SpatialMaxPooling(3,3,1,1):ceil())
elseif config[4][1] == 'avg' then
pool:add(nn.SpatialAveragePooling(3,3,1,1):ceil())
else
error('Unknown pooling')
end
if config[4][2] ~= 0 then
pool:add(nn.SpatialConvolution(input_size, config[4][2],1,1,1,1)):add(nn.ReLU(true))
end
concat:add(pool)
return concat
end
local nClasses = 1000
local features = nn.Sequential()
features:add(nn.SpatialConvolution(3,64,7,7,2,2,3,3)):add(nn.ReLU(true))
features:add(nn.SpatialMaxPooling(3,3,2,2):ceil())
features:add(nn.SpatialConvolution(64,64,1,1)):add(nn.ReLU(true))
features:add(nn.SpatialConvolution(64,192,3,3,1,1,1,1)):add(nn.ReLU(true))
features:add(nn.SpatialMaxPooling(3,3,2,2):ceil())
features:add(inception( 192, {{ 64},{ 64, 64},{ 64, 96},{'avg', 32}})) -- 3(a)
features:add(inception( 256, {{ 64},{ 64, 96},{ 64, 96},{'avg', 64}})) -- 3(b)
features:add(inception( 320, {{ 0},{128,160},{ 64, 96},{'max', 0}})) -- 3(c)
features:add(nn.SpatialConvolution(576,576,2,2,2,2))
features:add(inception( 576, {{224},{ 64, 96},{ 96,128},{'avg',128}})) -- 4(a)
features:add(inception( 576, {{192},{ 96,128},{ 96,128},{'avg',128}})) -- 4(b)
features:add(inception( 576, {{160},{128,160},{128,160},{'avg', 96}})) -- 4(c)
features:add(inception( 576, {{ 96},{128,192},{160,192},{'avg', 96}})) -- 4(d)
local main_branch = nn.Sequential()
main_branch:add(inception( 576, {{ 0},{128,192},{192,256},{'max', 0}})) -- 4(e)
main_branch:add(nn.SpatialConvolution(1024,1024,2,2,2,2))
main_branch:add(inception(1024, {{352},{192,320},{160,224},{'avg',128}})) -- 5(a)
main_branch:add(inception(1024, {{352},{192,320},{192,224},{'max',128}})) -- 5(b)
main_branch:add(nn.SpatialAveragePooling(7,7,1,1))
main_branch:add(nn.View(1024):setNumInputDims(3))
main_branch:add(nn.Linear(1024,nClasses))
main_branch:add(nn.LogSoftMax())
-- add auxillary classifier here (thanks to Christian Szegedy for the details)
local aux_classifier = nn.Sequential()
aux_classifier:add(nn.SpatialAveragePooling(5,5,3,3):ceil())
aux_classifier:add(nn.SpatialConvolution(576,128,1,1,1,1))
aux_classifier:add(nn.View(128*4*4):setNumInputDims(3))
aux_classifier:add(nn.Linear(128*4*4,768))
aux_classifier:add(nn.ReLU())
aux_classifier:add(nn.Linear(768,nClasses))
aux_classifier:add(nn.LogSoftMax())
local splitter = nn.Concat(2)
splitter:add(main_branch):add(aux_classifier)
local model = nn.Sequential():add(features):add(splitter)
model.imageSize = 256
model.imageCrop = 224
local input = torch.rand(1,3,model.imageCrop,model.imageCrop)
return model, input
end
models.vgg = function(modelType)
-- taken from soumith's imagenet-multiGPU
-- https://github.com/soumith/imagenet-multiGPU.torch/blob/master/models/vgg.lua
local nClasses = 1000
local modelType = modelType or 'A' -- on a titan black, B/D/E run out of memory even for batch-size 32
-- Create tables describing VGG configurations A, B, D, E
local cfg = {}
if modelType == 'A' then
cfg = {64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'}
elseif modelType == 'B' then
cfg = {64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'}
elseif modelType == 'D' then
cfg = {64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'}
elseif modelType == 'E' then
cfg = {64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'}
else
error('Unknown model type: ' .. modelType .. ' | Please specify a modelType A or B or D or E')
end
local features = nn.Sequential()
do
local iChannels = 3;
for k,v in ipairs(cfg) do
if v == 'M' then
features:add(nn.SpatialMaxPooling(2,2,2,2))
else
local oChannels = v;
local conv3 = nn.SpatialConvolution(iChannels,oChannels,3,3,1,1,1,1);
features:add(conv3)
features:add(nn.ReLU(true))
iChannels = oChannels;
end
end
end
local classifier = nn.Sequential()
classifier:add(nn.View(512*7*7))
classifier:add(nn.Linear(512*7*7, 4096))
classifier:add(nn.Threshold(0, 1e-6))
-- classifier:add(nn.Dropout(0.5))
classifier:add(nn.Linear(4096, 4096))
classifier:add(nn.Threshold(0, 1e-6))
-- classifier:add(nn.Dropout(0.5))
classifier:add(nn.Linear(4096, nClasses))
classifier:add(nn.LogSoftMax())
local model = nn.Sequential()
model:add(features):add(classifier)
model.imageSize = 256
model.imageCrop = 224
local input = torch.rand(1,3,model.imageCrop,model.imageCrop)
return model, input
end
models.resnet = function(opt)
-- taken from https://github.com/facebook/fb.resnet.torch
local Convolution = nn.SpatialConvolution
local Avg = nn.SpatialAveragePooling
local ReLU = nn.ReLU
local Max = nn.SpatialMaxPooling
local SBatchNorm = function(n)
local m = nn.MulConstant(1)
m.inplace = nil
return m
end--nn.SpatialBatchNormalization
local function createModel(opt)
local depth = opt.depth
local shortcutType = opt.shortcutType or 'B'
local iChannels
-- The shortcut layer is either identity or 1x1 convolution
local function shortcut(nInputPlane, nOutputPlane, stride)
local useConv = shortcutType == 'C' or
(shortcutType == 'B' and nInputPlane ~= nOutputPlane)
if useConv then
-- 1x1 convolution
return nn.Sequential()
:add(Convolution(nInputPlane, nOutputPlane, 1, 1, stride, stride))
:add(SBatchNorm(nOutputPlane))
elseif nInputPlane ~= nOutputPlane then
-- Strided, zero-padded identity shortcut
return nn.Sequential()
:add(nn.SpatialAveragePooling(1, 1, stride, stride))
:add(nn.Concat(2)
:add(nn.Identity())
:add(nn.MulConstant(0)))
else
return nn.Identity()
end
end
-- The basic residual layer block for 18 and 34 layer network, and the
-- CIFAR networks
local function basicblock(n, stride)
local nInputPlane = iChannels
iChannels = n
local s = nn.Sequential()
s:add(Convolution(nInputPlane,n,3,3,stride,stride,1,1))
s:add(SBatchNorm(n))
s:add(ReLU(true))
s:add(Convolution(n,n,3,3,1,1,1,1))
s:add(SBatchNorm(n))
return nn.Sequential()
:add(nn.ConcatTable()
:add(s)
:add(shortcut(nInputPlane, n, stride)))
:add(nn.CAddTable(true))
:add(ReLU(true))
end
-- The bottleneck residual layer for 50, 101, and 152 layer networks
local function bottleneck(n, stride)
local nInputPlane = iChannels
iChannels = n * 4
local s = nn.Sequential()
s:add(Convolution(nInputPlane,n,1,1,1,1,0,0))
s:add(SBatchNorm(n))
s:add(ReLU(true))
s:add(Convolution(n,n,3,3,stride,stride,1,1))
s:add(SBatchNorm(n))
s:add(ReLU(true))
s:add(Convolution(n,n*4,1,1,1,1,0,0))
s:add(SBatchNorm(n * 4))
return nn.Sequential()
:add(nn.ConcatTable()
:add(s)
:add(shortcut(nInputPlane, n * 4, stride)))
:add(nn.CAddTable(true))
:add(ReLU(true))
end
-- Creates count residual blocks with specified number of features
local function layer(block, features, count, stride)
local s = nn.Sequential()
for i=1,count do
s:add(block(features, i == 1 and stride or 1))
end
return s
end
local model = nn.Sequential()
local input
if opt.dataset == 'imagenet' then
-- Configurations for ResNet:
-- num. residual blocks, num features, residual block function
local cfg = {
[18] = {{2, 2, 2, 2}, 512, basicblock},
[34] = {{3, 4, 6, 3}, 512, basicblock},
[50] = {{3, 4, 6, 3}, 2048, bottleneck},
[101] = {{3, 4, 23, 3}, 2048, bottleneck},
[152] = {{3, 8, 36, 3}, 2048, bottleneck},
}
assert(cfg[depth], 'Invalid depth: ' .. tostring(depth))
local def, nFeatures, block = table.unpack(cfg[depth])
iChannels = 64
--print(' | ResNet-' .. depth .. ' ImageNet')
-- The ResNet ImageNet model
model:add(Convolution(3,64,7,7,2,2,3,3))
model:add(SBatchNorm(64))
model:add(ReLU(true))
model:add(Max(3,3,2,2,1,1))
model:add(layer(block, 64, def[1]))
model:add(layer(block, 128, def[2], 2))
model:add(layer(block, 256, def[3], 2))
model:add(layer(block, 512, def[4], 2))
model:add(Avg(7, 7, 1, 1))
model:add(nn.View(nFeatures):setNumInputDims(3))
model:add(nn.Linear(nFeatures, 1000))
input = torch.rand(1,3,224,224)
elseif opt.dataset == 'cifar10' then
-- Model type specifies number of layers for CIFAR-10 model
assert((depth - 2) % 6 == 0, 'depth should be one of 20, 32, 44, 56, 110, 1202')
local n = (depth - 2) / 6
iChannels = 16
--print(' | ResNet-' .. depth .. ' CIFAR-10')
-- The ResNet CIFAR-10 model
model:add(Convolution(3,16,3,3,1,1,1,1))
model:add(SBatchNorm(16))
model:add(ReLU(true))
model:add(layer(basicblock, 16, n))
model:add(layer(basicblock, 32, n, 2))
model:add(layer(basicblock, 64, n, 2))
model:add(Avg(8, 8, 1, 1))
model:add(nn.View(64):setNumInputDims(3))
model:add(nn.Linear(64, 10))
input = torch.rand(1,3,32,32)
else
error('invalid dataset: ' .. opt.dataset)
end
local function ConvInit(name)
for k,v in pairs(model:findModules(name)) do
local n = v.kW*v.kH*v.nOutputPlane
v.weight:normal(0,math.sqrt(2/n))
if false and cudnn.version >= 4000 then
v.bias = nil
v.gradBias = nil
else
v.bias:zero()
end
end
end
local function BNInit(name)
for k,v in pairs(model:findModules(name)) do
v.weight:fill(1)
v.bias:zero()
end
end
ConvInit('cudnn.SpatialConvolution')
ConvInit('nn.SpatialConvolution')
BNInit('fbnn.SpatialBatchNormalization')
BNInit('cudnn.SpatialBatchNormalization')
BNInit('nn.SpatialBatchNormalization')
for k,v in pairs(model:findModules('nn.Linear')) do
v.bias:zero()
end
if opt.cudnn == 'deterministic' then
model:apply(function(m)
if m.setMode then m:setMode(1,1,1) end
end)
end
return model, input
end
return createModel(opt)
end
models.preresnet = function(opt)
local Convolution = nn.SpatialConvolution
local Avg = nn.SpatialAveragePooling
local ReLU = nn.ReLU
local Max = nn.SpatialMaxPooling
local SBatchNorm = function(n)
local m = nn.MulConstant(1)
m.inplace = nil
return m
end--nn.SpatialBatchNormalization
local function createModel(opt)
local depth = opt.depth
local shortcutType = opt.shortcutType or 'B'
local iChannels
-- The shortcut layer is either identity or 1x1 convolution
local function shortcut(nInputPlane, nOutputPlane, stride)
local useConv = shortcutType == 'C' or
(shortcutType == 'B' and nInputPlane ~= nOutputPlane)
if useConv then
-- 1x1 convolution
return nn.Sequential()
:add(Convolution(nInputPlane, nOutputPlane, 1, 1, stride, stride))
elseif nInputPlane ~= nOutputPlane then
-- Strided, zero-padded identity shortcut
return nn.Sequential()
:add(nn.SpatialAveragePooling(1, 1, stride, stride))
:add(nn.Concat(2)
:add(nn.Identity())
:add(nn.MulConstant(0)))
else
return nn.Identity()
end
end
-- The basic residual layer block for 18 and 34 layer network, and the
-- CIFAR networks
local function basicblock(n, stride, type)
local nInputPlane = iChannels
iChannels = n
local block = nn.Sequential()
local s = nn.Sequential()
if type == 'both_preact' then
block:add(SBatchNorm(nInputPlane))
block:add(ReLU(true))
elseif type ~= 'no_preact' then
s:add(SBatchNorm(nInputPlane))
s:add(ReLU(true))
end
s:add(Convolution(nInputPlane,n,3,3,stride,stride,1,1))
s:add(SBatchNorm(n))
s:add(ReLU(true))
s:add(Convolution(n,n,3,3,1,1,1,1))
return block
:add(nn.ConcatTable()
:add(s)
:add(shortcut(nInputPlane, n, stride)))
:add(nn.CAddTable(true))
end
-- The bottleneck residual layer for 50, 101, and 152 layer networks
local function bottleneck(n, stride, type)
local nInputPlane = iChannels
iChannels = n * 4
local block = nn.Sequential()
local s = nn.Sequential()
if type == 'both_preact' then
block:add(SBatchNorm(nInputPlane))
block:add(ReLU(true))
elseif type ~= 'no_preact' then
s:add(SBatchNorm(nInputPlane))
s:add(ReLU(true))
end
s:add(Convolution(nInputPlane,n,1,1,1,1,0,0))
s:add(SBatchNorm(n))
s:add(ReLU(true))
s:add(Convolution(n,n,3,3,stride,stride,1,1))
s:add(SBatchNorm(n))
s:add(ReLU(true))
s:add(Convolution(n,n*4,1,1,1,1,0,0))
return block
:add(nn.ConcatTable()
:add(s)
:add(shortcut(nInputPlane, n * 4, stride)))
:add(nn.CAddTable(true))
end
-- Creates count residual blocks with specified number of features
local function layer(block, features, count, stride, type)
local s = nn.Sequential()
if count < 1 then
return s
end
s:add(block(features, stride,
type == 'first' and 'no_preact' or 'both_preact'))
for i=2,count do
s:add(block(features, 1))
end
return s
end
local model = nn.Sequential()
local input
if opt.dataset == 'imagenet' then
-- Configurations for ResNet:
-- num. residual blocks, num features, residual block function
local cfg = {
[18] = {{2, 2, 2, 2}, 512, basicblock},
[34] = {{3, 4, 6, 3}, 512, basicblock},
[50] = {{3, 4, 6, 3}, 2048, bottleneck},
[101] = {{3, 4, 23, 3}, 2048, bottleneck},
[152] = {{3, 8, 36, 3}, 2048, bottleneck},
[200] = {{3, 24, 36, 3}, 2048, bottleneck},
}
assert(cfg[depth], 'Invalid depth: ' .. tostring(depth))
local def, nFeatures, block = table.unpack(cfg[depth])
iChannels = 64
--print(' | ResNet-' .. depth .. ' ImageNet')
-- The ResNet ImageNet model
model:add(Convolution(3,64,7,7,2,2,3,3))
model:add(SBatchNorm(64))
model:add(ReLU(true))
model:add(Max(3,3,2,2,1,1))
model:add(layer(block, 64, def[1], 1, 'first'))
model:add(layer(block, 128, def[2], 2))
model:add(layer(block, 256, def[3], 2))
model:add(layer(block, 512, def[4], 2))
model:add(nn.Copy(nil, nil, true))
model:add(SBatchNorm(iChannels))
model:add(ReLU(true))
model:add(Avg(7, 7, 1, 1))
model:add(nn.View(nFeatures):setNumInputDims(3))
model:add(nn.Linear(nFeatures, 1000))
input = torch.rand(1,3,224,224)
elseif opt.dataset == 'cifar10' then
-- Model type specifies number of layers for CIFAR-10 model
assert((depth - 2) % 6 == 0, 'depth should be one of 20, 32, 44, 56, 110, 1202')
local n = (depth - 2) / 6
iChannels = 16
--print(' | ResNet-' .. depth .. ' CIFAR-10')
-- The ResNet CIFAR-10 model
model:add(Convolution(3,16,3,3,1,1,1,1))
model:add(layer(basicblock, 16, n, 1))
model:add(layer(basicblock, 32, n, 2))
model:add(layer(basicblock, 64, n, 2))
model:add(nn.Copy(nil, nil, true))
model:add(SBatchNorm(iChannels))
model:add(ReLU(true))
model:add(Avg(8, 8, 1, 1))
model:add(nn.View(64):setNumInputDims(3))
model:add(nn.Linear(64, 10))
input = torch.rand(1,3,32,32)
else
error('invalid dataset: ' .. opt.dataset)
end
local function ConvInit(name)
for k,v in pairs(model:findModules(name)) do
local n = v.kW*v.kH*v.nOutputPlane
v.weight:normal(0,math.sqrt(2/n))
if false and cudnn.version >= 4000 then
v.bias = nil
v.gradBias = nil
else
v.bias:zero()
end
end
end
local function BNInit(name)
for k,v in pairs(model:findModules(name)) do
v.weight:fill(1)
v.bias:zero()
end
end
--ConvInit('cudnn.SpatialConvolution')
ConvInit('nn.SpatialConvolution')
--BNInit('fbnn.SpatialBatchNormalization')
--BNInit('cudnn.SpatialBatchNormalization')
BNInit('nn.SpatialBatchNormalization')
for k,v in pairs(model:findModules('nn.Linear')) do
v.bias:zero()
end
--model:cuda()
if opt.cudnn == 'deterministic' then
model:apply(function(m)
if m.setMode then m:setMode(1,1,1) end
end)
end
--model:get(1).gradInput = nil
return model, input
end
return createModel(opt)
end
return models
|
local _, core = ...
local function GameTooltip_OnTooltipSetItem(tooltip)
local itemName, itemLink = tooltip:GetItem()
if not itemName or not itemLink then
return
end
local _, _, _, _, _, itemType = GetItemInfo(itemLink)
local _,
itemId,
enchantId,
jewelId1,
jewelId2,
jewelId3,
jewelId4,
suffixId,
uniqueId,
linkLevel,
specializationID,
reforgeId,
unknown1,
unknown2 = strsplit(":", itemLink)
if
itemType ~= "Armor" and itemType ~= "Weapon" and itemType ~= "Quest" and itemType ~= "Miscellaneous" and
itemType ~= "Trade Goods"
then
return
end
itemId = tonumber(itemId)
if core.lootDb[itemId] then
local itemInfo = core.lootDb[itemId]
tooltip:AddLine(" ")
tooltip:AddLine("|cFF00FF00SU Loot Info|r")
if itemInfo.role ~= nil and itemInfo.role ~= "" then
tooltip:AddLine("Prio: " .. core.colorizeTextByRole(itemInfo.role))
end
if itemInfo.dkp ~= nil and itemInfo.dkp ~= "" and itemInfo.dkp ~= "NA" then
tooltip:AddLine("Min Bid: |cFFA330C9" .. itemInfo.dkp .. " DKP|r")
end
if (itemInfo.note ~= nil and itemInfo.note ~= "") then
tooltip:AddLine("Notes: " .. itemInfo.note)
end
end
end
GameTooltip:HookScript("OnTooltipSetItem", GameTooltip_OnTooltipSetItem)
ItemRefTooltip:HookScript("OnTooltipSetItem", GameTooltip_OnTooltipSetItem)
|
local BaseMotor = require(script.Parent.BaseMotor)
local SingleMotor = require(script.Parent.SingleMotor)
local isMotor = require(script.Parent.isMotor)
local Ser = require(script.Parent.Serializer)
local GroupMotor = setmetatable({}, BaseMotor)
GroupMotor.__index = GroupMotor
local function serializeGoal(goalClass, goal)
local data = Ser.serialize(goal._targetValue)
for property, value in pairs(data) do
data[property] = goalClass.new(value, goal._options)
end
return data
end
local function toMotor(value)
if isMotor(value) then
return value
end
local valueType = typeof(value)
if valueType == "number" then
return SingleMotor.new(value, false)
elseif valueType == "table" then
return GroupMotor.new(value, false, true)
elseif Ser.has(valueType) then
return GroupMotor.new(
Ser.serialize(value),
false,
true,
valueType
)
end
error(("Unable to convert %q to motor; type %s is unsupported"):format(value, valueType), 2)
end
function GroupMotor.new(initialValues, useImplicitConnections, notTopSuper, dataType)
local valueType = typeof(initialValues)
if Ser.has(valueType) then
return GroupMotor.new(
Ser.serialize(initialValues),
nil,
nil,
valueType
)
end
assert(valueType == "table", "initialValues must be a table or data type!")
local self = setmetatable(BaseMotor.new(), GroupMotor)
if useImplicitConnections ~= nil then
self._useImplicitConnections = useImplicitConnections
else
self._useImplicitConnections = true
end
self._isTopSuper = not notTopSuper
self._dataType = dataType
self._complete = true
self._motors = {}
for key, value in pairs(initialValues) do
self._motors[key] = toMotor(value)
end
return self
end
function GroupMotor:step(deltaTime)
if self._complete then
return true
end
local allMotorsComplete = true
for _, motor in pairs(self._motors) do
local complete = motor:step(deltaTime)
if not complete then
-- If any of the sub-motors are incomplete, the group motor will not be complete either
allMotorsComplete = false
end
end
self._onStep:fire(self:getValue())
if allMotorsComplete then
if self._useImplicitConnections then
self:stop()
end
self._complete = true
self._onComplete:fire()
end
return allMotorsComplete
end
function GroupMotor:setGoal(goals)
self._complete = false
if self._isTopSuper then -- if the goal is a direct data type
local isGoal = getmetatable(goals)
if isGoal then
goals = serializeGoal(isGoal, goals)
end
end
for key, goal in pairs(goals) do
local motor = assert(self._motors[key], ("Unknown motor for key %s"):format(key))
if motor._dataType then
local goalClass = getmetatable(goal)
motor:setGoal(serializeGoal(goalClass, goal))
else
motor:setGoal(goal)
end
end
if self._useImplicitConnections then
self:start()
end
end
function GroupMotor:getValue(noDeserializing) -- param for nested data types
local values = {}
for key, motor in pairs(self._motors) do
values[key] = motor:getValue(self._dataType and true)
end
if not noDeserializing and self._dataType then
return Ser.deserialize(values, self._dataType)
else
return values
end
end
function GroupMotor:__tostring()
return "Motor(Group)"
end
return GroupMotor
|
------------------------------------------------------------------------------------------------------------------------
-- Proposal:
-- https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0192-button_subscription_response_from_hmi.md
------------------------------------------------------------------------------------------------------------------------
-- Description: Check that App is still subscribed on <button> if HMI does not respond to SubscribeButton request
-- from SDL once default timeout expires
------------------------------------------------------------------------------------------------------------------------
-- In case:
-- 1. Mobile app is subscribed for <button>
-- 2. Mobile app requests UnsubscribeButton(<button>)
-- 3. SDL sends Buttons.UnsubscribeButton(<button>, appId) to HMI
-- 4. HMI does not respond during default timeout
-- 5. SDL responds UnsubscribeButton(GENERIC_ERROR) to mobile app
-- 6. HMI sends Buttons.UnsubscribeButton(SUCCESS) to SDL
-- SDL does:
-- - sends Buttons.SubscribeButton(<button>, appId) to HMI
-- In case:
-- 7. HMI doesn't respond for a `Buttons.SubscribeButton` request from SDL
-- 8. HMI sends OnButtonEvent and OnButtonPress notifications for <button>
-- SDL does:
-- - transfer OnButtonEvent and OnButtonPress to App
------------------------------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local common = require('test_scripts/API/ButtonSubscription/commonButtonSubscription')
--[[ Local Variables ]]
local appSessionId1 = 1
local buttonName = "PRESET_0"
--[[ Local function ]]
local function rpcGenericError(pButtonName)
local hmiCID
local cid = common.getMobileSession():SendRPC("UnsubscribeButton", { buttonName = pButtonName })
local appIdVariable = common.getHMIAppId()
common.getHMIConnection():ExpectRequest("Buttons.UnsubscribeButton",
{ appID = appIdVariable, buttonName = pButtonName })
:Do(function(_, data)
-- HMI did not response
hmiCID = data.id
end)
common.getMobileSession():ExpectResponse(cid, { success = false, resultCode = "GENERIC_ERROR" })
:Do(function()
common.getHMIConnection():SendResponse( hmiCID, "Buttons.UnsubscribeButton", "SUCCESS", { })
common.getHMIConnection():ExpectRequest("Buttons.SubscribeButton",
{ appID = appIdVariable, buttonName = pButtonName })
:Do(function(_, data)
-- HMI did not response
end)
end)
local event = common.createEvent()
event.matches = function(_, data)
return data.rpcType == 1 and
data.rpcFunctionId == 18
end
common.getMobileSession():ExpectEvent(event, "SubscribeButtonResponse")
:Times(0)
end
--[[ Scenario ]]
common.runner.Title("Preconditions")
common.runner.Step("Clean environment", common.preconditions)
common.runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
common.runner.Step("App registration", common.registerAppWOPTU)
common.runner.Step("App activation", common.activateApp)
common.runner.Title("Test")
common.runner.Title("ButtonName parameter: " .. buttonName)
common.runner.Step("Subscribe on " .. buttonName, common.rpcSuccess, { appSessionId1, "SubscribeButton", buttonName })
common.runner.Step("On Button Press " .. buttonName, common.buttonPress, { appSessionId1, buttonName })
common.runner.Step("Unsubscribe on " .. buttonName .. " button in timeout case", rpcGenericError, { buttonName })
common.runner.Step("On Button Press " .. buttonName, common.buttonPress, { appSessionId1, buttonName })
common.runner.Title("Postconditions")
common.runner.Step("Stop SDL", common.postconditions)
|
local VEHICLE = FindMetaTable("Vehicle")
function VEHICLE:IsOverturned()
// Tweak this number to adjust what's considered "overturned"
return vector_up:Dot(self:GetAngles():Up()) < 0
end
|
function onCreate()
makeLuaSprite('bg', 'assets/halloween_bg_low', -200, 0);
setLuaSpriteScrollFactor(0.9, 0.9);
setProperty('bg.scale.x', getProperty('bg.scale.x') + 0.4);
setProperty('bg.scale.y', getProperty('bg.scale.y') + 0.4);
setProperty('dad.alpha', 0.5);
setProperty('iconP2.alpha', 0.5);
addLuaSprite('bg', false);
end |
function plugindef()
-- This function and the 'finaleplugin' namespace
-- are both reserved for the plug-in definition.
finaleplugin.RequireSelection = true
finaleplugin.Author = "Robert Patterson"
finaleplugin.Copyright = "CC0 https://creativecommons.org/publicdomain/zero/1.0/"
finaleplugin.Version = "1.0.1"
finaleplugin.Date = "June 12, 2020"
finaleplugin.CategoryTags = "Note"
finaleplugin.Notes = [[
This script beams together any notes or rests in the selected region that can
be beamed together and breaks beams that cross into or out of the selected
region at the boundaries of the selected region. The beam options in Finale’s
Document Settings determine whether rests can be included at the start or end of a beam.
If you select multiple staves vertically, you can create the same beaming pattern
across all the staves with a single invocation of the script.
It does *not* create beams over barlines.
This script could be particularly useful if you assign it a keystroke using a keyboard macro utility.
]]
return "Beam Selected Region", "Beam Selected Region", "Beam Selected Region"
end
local note_entry = require("library.note_entry")
function beam_selected_region()
local first_in_beam = true
local first_in_beam_v2 = false
local curr_staff = 0
local curr_layer = -1
for entry in eachentrysaved(finenv.Region()) do
if (curr_staff ~= entry:GetStaff()) or (curr_layer ~= entry:GetLayerNumber()) then
first_in_beam = true
first_in_beam_v2 = true
curr_staff = entry:GetStaff()
curr_layer = entry:GetLayerNumber()
end
local isV2 = entry:GetVoice2()
if not isV2 then
first_in_beam_v2 = true
end
if entry:GetDuration() < 1024 then -- less than quarter note duration
if (not isV2 and first_in_beam) or (isV2 and first_in_beam_v2) then
entry:SetBeamBeat(true)
if not isV2 then
first_in_beam = false
else
first_in_beam_v2 = false
end
else
entry:SetBeamBeat(false)
end
local next_entry = note_entry.get_next_same_v(entry)
if (nil ~= next_entry) and (next_entry:GetDuration() < 1024) and
not finenv.Region():IsEntryPosWithin(next_entry) then
next_entry:SetBeamBeat(true)
end
end
end
end
beam_selected_region()
|
-- --------------------
-- TellMeWhen
-- Originally by Nephthys of Hyjal <lieandswell@yahoo.com>
-- Other contributions by:
-- Sweetmms of Blackrock, Oozebull of Twisting Nether, Oodyboo of Mug'thol,
-- Banjankri of Blackrock, Predeter of Proudmoore, Xenyr of Aszune
-- Currently maintained by
-- Cybeloras of Aerie Peak
-- --------------------
if not TMW then return end
local TMW = TMW
local L = TMW.L
local print = TMW.print
local Module = TMW:NewClass("IconModule_RecieveSpellDrags", "IconModule")
Module:SetScriptHandler("OnClick", function(Module, icon, button)
if not TMW.Locked and TMW.IE and button == "LeftButton" then
TMW.IE:SpellItemToIcon(icon)
end
end)
Module:SetScriptHandler("OnReceiveDrag", function(Module, icon, button)
if not TMW.Locked and TMW.IE then
TMW.IE:SpellItemToIcon(icon)
end
end)
|
--[[
MIT LICENSE
Copyright (c) 2018 Denys Almaral
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.
]]
--- Our main game stuff,
-- try to keep it simple... oh well..
--aliases and modules
--api
local apiG = love.graphics
local api = love
if api.system.getOS()=='Android' or api.system.getOS()=='iOS' then CURRENT_PLATFORM = 'mobile' else CURRENT_PLATFORM = 'desktop' end
--application
local sim = require('code.simulation')
local map = require('code.map')
local cam = require('code.camview')
local cfg = require('code.simconfig')
local ui = require('code.gui')
-- doing a global scaling for basic adaptation to different screens/windows sizes
local contentScaling
local function screenSizeUpdated()
contentScaling = apiG.getHeight() / cfg.idealContentHeight
ui.setContentScale( contentScaling, contentScaling )
cam.contentScale = contentScaling
end
screenSizeUpdated()
--- We init the application defining the load event
function api.load()
TIME_start = os.clock()
print('Initializing...')
--if arg[#arg] == "-debug" then require("mobdebug").start() end
sim.init()
cam.translation = {x = 500, y = 300 }
cam.scale = { x = 2, y = 2 }
cam.zoomOrigin = { x = apiG.getWidth() / 2, y = apiG.getHeight() / 2 }
apiG.setBackgroundColor(cfg.colorBk)
apiG.setDefaultFilter("nearest", "nearest")
apiG.setLineStyle( 'rough' )
end
function api.update()
ui.numAnts = map.ants.count
ui.mainUpdate()
sim.update()
end
function api.draw()
--gameworld
if cfg.simFrameNumber == 1 then print( (os.clock() - TIME_start)..'secs' ) end
apiG.push()
apiG.translate( cam.translation.x, cam.translation.y )
apiG.scale( cam.scale.x * contentScaling, cam.scale.y * contentScaling )
sim.draw()
--ui stuff
apiG.pop()
--ui
apiG.scale(contentScaling, contentScaling)
ui.draw()
end
function api.keypressed(key)
if key=='1' then
elseif key=='2' then
cfg.antComEveryFrame = not cfg.antComEveryFrame
print('cfg.antComEveryFrame = ',cfg.antComEveryFrame)
elseif key=='3' then
cfg.debugGrid = not cfg.debugGrid
print('cfg.debugGrid =',cfg.debugGrid)
elseif key=='4' then
cfg.antComAlgorithm = cfg.antComAlgorithm + 1
if cfg.antComAlgorithm > 1 then cfg.antComAlgorithm = 0 end
print('cfg.antComAlgorithm = ', cfg.antComAlgorithm )
elseif key=='5' then
cfg.debugPheromones = not cfg.debugPheromones
print('cfg.debugPheromones =',cfg.debugPheromones)
elseif key=='m' then
print('Memory: '..math.floor( collectgarbage ('count'))..'kb')
elseif key=='escape' then
api.event.quit()
elseif key=='6' then
cfg.antObjectAvoidance = not cfg.antObjectAvoidance
print('cfg.antObjectAvoidance = ', cfg.antObjectAvoidance )
elseif key=='0'then
cfg.debugHideAnts = not cfg.debugHideAnts
print('cfg.debugHideAnts = ', cfg.debugHideAnts )
elseif key=='f11' then
api.window.setFullscreen( not api.window.getFullscreen() )
screenSizeUpdated()
end
end
local function dragmoved(x, y, dx, dy)
local tool = ui.radioBtns_cells.selectedCaption
if api.mouse.isDown(1) and (x > ui.leftPanelWidth) then
if (tool ~= 'cave') and (tool ~= 'portal') and (tool~='pan view') then
sim.setCell(ui.radioBtns_cells.selectedCaption, cam.screenToWorld(x, y) )
end
end
if (x > ui.leftPanelWidth) then
if api.mouse.isDown(3) or api.mouse.isDown(2) or ( api.mouse.isDown(1) and tool =='pan view' ) then
cam.translation.x = cam.translation.x + dx
cam.translation.y = cam.translation.y + dy
end
end
end
--needed to do this because mousemoved makes big dx,dy jumps on mobile
if CURRENT_PLATFORM == 'desktop' then
function api.mousemoved(x,y,dx,dy, istouch)
dragmoved(x,y,dx,dy)
end
else
function api.touchmoved(id, x,y,dx,dy, pressure)
dragmoved(x,y,dx,dy)
end
end
function api.mousepressed(x, y, button, istouch)
if button == 1 and (x > ui.leftPanelWidth) then
sim.setCell(ui.radioBtns_cells.selectedCaption, cam.screenToWorld(x, y) )
end
end
function api.wheelmoved( x, y)
local inc = y * 0.5
cam.zoomOrigin.x, cam.zoomOrigin.y = api.mouse.getX(), api.mouse.getY()
cam.zoom(inc)
end
function ui.onZoomInOut( inc )
cam.zoomOrigin = { x = apiG.getWidth() / 2, y = apiG.getHeight() / 2 }
cam.zoom(inc)
end
|
-- import
local ComponentModule = require 'candy.Component'
local RenderComponent = require 'candy.gfx.RenderComponent'
local getBuiltinShader = MOAIShaderMgr.getShader
local DECK2D_TEX_ONLY_SHADER = MOAIShaderMgr.DECK2D_TEX_ONLY_SHADER
local DECK2D_SHADER = MOAIShaderMgr.DECK2D_SHADER
local FONT_SHADER = MOAIShaderMgr.FONT_SHADER
local OVERRUN_MOVE_WORD = MOAITextLabel.OVERRUN_MOVE_WORD
local OVERRUN_SPLIT_WORD = MOAITextLabel.OVERRUN_SPLIT_WORD
local OVERRUN_TRUNCATE_WORD = MOAITextLabel.OVERRUN_TRUNCATE_WORD
local OVERRUN_ABORT_LAYOUT = MOAITextLabel.OVERRUN_ABORT_LAYOUT
---@class TextLabel : RenderComponent
local TextLabel = CLASS: TextLabel ( RenderComponent )
:MODEL {
"----";
Field "text" :string():set("setText"):widget("textbox");
"----";
Field "stylesheet" :asset_pre("stylesheet"):getset("StyleSheet");
Field "defaultStyle" :string():label("default"):set("setDefaultStyle"):selection("getStyleNames");
"----";
Field "italic" :number():set("setItalic");
"----";
Field "rectLimit" :boolean():set("setRectLimit");
Field "size" :type("vec2"):getset("Size");
Field "alignment" :enum(EnumTextAlignment):set("setAlignment"):label("align H");
Field "alignmentV" :enum(EnumTextAlignmentV):set("setAlignmentV"):label("align V");
Field "lineSpacing" :set("setLineSpacing"):label("line spacing");
Field "wordBreak" :boolean():set("setWordBreak"):label("break word");
}
function TextLabel:__init ()
local box = markRenderNode ( MOAITextBox.new () )
box:setStyle ( getFallbackTextStyle () )
box:setYFlip ( true )
self.box = box
self.text = "Sample Text"
self.alignment = "left"
self.alignmentV = "top"
self:setSize ( 100, 100 )
self.defaultStyle = "default"
self.styleSheet = false
self.rectLimit = true
self:useDeckShader ()
self.wordBreak = false
self.lineSpacing = 0
self.fitAlignment = true
self.italic = 0
self.prop = box
end
function TextLabel:onAttach ( entity )
entity:_attachProp ( self.box, "render" )
end
function TextLabel:onDetach ( entity )
entity:_detachProp ( self.box )
self.box:stop ()
end
function TextLabel:getMoaiProp ()
return self.box
end
function TextLabel:setBlend ( b )
self.blend = b
setPropBlend ( self.box, b )
end
function TextLabel:setWordBreak ( wbreak )
if wbreak then
self.box:setOverrunRules ( OVERRUN_SPLIT_WORD, OVERRUN_SPLIT_WORD )
else
self.box:setOverrunRules ( OVERRUN_ABORT_LAYOUT, OVERRUN_MOVE_WORD )
end
end
function TextLabel:setOverrunRules ( first, common )
self.box:setOverrunRules ( first, common )
end
function TextLabel:setItalic ( italic )
-- TODO: MOAITextLabel::setItalic not impl.
local tt = type ( italic )
if tt == "number" then
self.italic = italic
-- self.box:setItalic ( italic )
else
self.italic = italic and 0.25 or 0
-- self.box:setItalic ( self.italic )
end
end
function TextLabel:setLineSpacing ( spacing )
self.lineSpacing = spacing
self.box:setLineSpacing ( spacing or 0 )
end
local defaultShader = MOAIShaderMgr.getShader ( MOAIShaderMgr.DECK2D_SHADER )
function TextLabel:setShader ( shaderPath )
self.shader = shaderPath
if shaderPath then
local shader = candy.loadAsset ( shaderPath )
if shader then
local moaiShader = shader:getMoaiShader ()
return self.prop:setShader ( moaiShader )
end
end
self.prop:setShader ( defaultShader )
end
function TextLabel:setDefaultStyle ( styleName )
self.defaultStyle = styleName or "default"
self:updateStyles ()
end
function TextLabel:setStyleSheet ( sheetPath )
local box = self.box
self.styleSheetPath = sheetPath
self.styleSheet = candy.loadAsset ( sheetPath )
self:updateStyles ()
end
function TextLabel:updateStyles ()
if self.styleSheet then
self.styleSheet:applyToTextBox ( self.box, self.defaultStyle )
end
end
function TextLabel:getStyleSheet ()
return self.styleSheetPath
end
function TextLabel:getStyleNames ()
local sheet = candy.loadAsset ( self.styleSheetPath )
if not sheet then
return nil
end
local result = {}
for i, name in pairs ( sheet:getStyleNames () ) do
table.insert ( result, { name, name } )
end
return result
end
function TextLabel:setRectLimit ( limit )
self.rectLimit = limit
self:updateRect ()
end
function TextLabel:setRect ( x0, y0, x1, y1 )
local w = x1 - x0
local h = y1 - y0
self:setLoc ( x0, y0 )
self:setSize ( w, h )
end
function TextLabel:getSize ()
return self.w, self.h
end
function TextLabel:setSize ( w, h )
if w == false then
self.rectLimit = false
else
self.w = w or 100
self.h = h or 100
end
self:updateRect ()
end
function TextLabel:updateRect ()
if not self.rectLimit then
self.box:setRectLimits ( false, false )
else
local w = self.w
local h = self.h
local sx, sy = self.box:getScl ()
w = w * sx
h = h * sy
if self.fitAlignment then
local alignH = self.alignment
local alignV = self.alignmentV
local x, y = nil
if alignH == "left" then
x = 0
elseif alignH == "center" then
x = -w / 2
else
x = -w
end
if alignV == "top" then
y = -h
elseif alignV == "center" then
y = -h / 2
else
y = 0
end
self.box:setRect ( x, y, x + w, y + h )
else
self.box:setRect ( 0, 0, w, h )
end
end
self.box:setString ( self.text )
end
function TextLabel:setText ( text )
text = tostring ( text )
self.text = text
self.box:setString ( text )
end
function TextLabel:setTextf ( pattern, ... )
return self:setText ( string.format ( pattern, ... ) )
end
function TextLabel:getText ()
return self.text
end
function TextLabel:appendText ( text )
return self.text .. text
end
function TextLabel:appendTextf ( pattern, ... )
return self:appendText ( string.format ( pattern, ... ) )
end
local textAlignments = {
center = MOAITextLabel.CENTER_JUSTIFY,
left = MOAITextLabel.LEFT_JUSTIFY,
right = MOAITextLabel.RIGHT_JUSTIFY,
top = MOAITextLabel.TOP_JUSTIFY,
bottom = MOAITextLabel.BOTTOM_JUSTIFY,
baseline = MOAITextLabel.BASELINE_JUSTIFY
}
function TextLabel:setAlignment ( align )
align = align or "left"
self.alignment = align
return self:_updateAlignment ()
end
function TextLabel:setAlignmentV ( align )
align = align or "top"
self.alignmentV = align
return self:_updateAlignment ()
end
function TextLabel:_updateAlignment ()
self.box:setAlignment ( textAlignments[self.alignment], textAlignments[self.alignmentV] )
return self:updateRect ()
end
function TextLabel:getBounds ()
return self.box:getBounds ()
end
function TextLabel:getTextBounds ( ... )
return self.box:getTextBounds ( ... )
end
function TextLabel:getLineBounds ( line )
return self.box:getLineBounds ( line )
end
function TextLabel:getLineCount ()
return self.box:getLineCount ()
end
function TextLabel:testTextSize ( ... )
return self.box:testTextSize ( ... )
end
function TextLabel:getTextSize ( ... )
local x0, y0, x1, y1 = self:getTextBounds ( ... )
if x0 then
return x1 - x0, y1 - y0
else
return 0, 0
end
end
function TextLabel:drawBounds ()
if not self._entity then
return
end
-- GIIHelper.setVertexTransform ( self._entity:getProp () )
if self.rectLimit then
local x1, y1, x2, y2 = self.box:getRect ()
MOAIDraw.drawRect ( x1, y1, x2, y2 )
else
local x1, y1, x2, y2 = self.box:getTextBounds ()
MOAIDraw.drawRect ( x1, y1, x2, y2 )
end
end
function TextLabel:getPickingProp ()
return self.box
end
function TextLabel:inside ( x, y, z, pad )
return self.box:inside ( x, y, z, pad )
end
local FontShaderMaterialBatch = MOAIMaterialBatch.new ()
FontShaderMaterialBatch:setShader ( 1, getBuiltinShader ( FONT_SHADER ) )
local DeckShaderMaterialBatch = MOAIMaterialBatch.new ()
DeckShaderMaterialBatch:setShader ( 1, getBuiltinShader ( DECK2D_SHADER ) )
function TextLabel:useFontShader ()
self.box:setParentMaterialBatch ( FontShaderMaterialBatch )
end
function TextLabel:useDeckShader ()
-- self.box:setParentMaterialBatch ( DeckShaderMaterialBatch )
self.box:setMaterialBatch ( DeckShaderMaterialBatch )
end
function TextLabel:more ()
return self.box:more ()
end
function TextLabel:nextPage ( reveal )
return self.box:nextPage ( reveal )
end
function TextLabel:setSpeed ( spd )
self.box:setSpeed ( spd )
end
function TextLabel:spool ( spooled )
return self.box:spool ( spooled )
end
function TextLabel:stopSpool ()
return self.box:stop ()
end
local defaultShader = MOAIShaderMgr.getShader ( MOAIShaderMgr.DECK2D_SHADER )
function TextLabel:setShader ( shaderPath )
self.shader = shaderPath
if shaderPath then
local shader = candy.loadAsset ( shaderPath )
if shader then
local moaiShader = shader:getMoaiShader ()
return self.box:setShader ( moaiShader )
end
end
self.box:setShader ( defaultShader )
end
function TextLabel:applyMaterial ( material )
material:applyToMoaiProp ( self.box )
if not material.shader then
self.box:setShader ( defaultShader )
end
end
function TextLabel:onEditorInit ()
local sheet = getDefaultStyleSheet ()
self:setStyleSheet ( sheet )
end
ComponentModule.registerComponent ( "TextLabel", TextLabel )
ComponentModule.registerEntityWithComponent ( "TextLabel", TextLabel )
wrapWithMoaiPropMethods ( TextLabel, "box" )
return TextLabel |
local mod = foundation_stdlib
local m = foundation.com
local Luna = assert(m.Luna)
local case = Luna:new("foundation_stdlib")
case:describe("is_blank/1", function (t2)
t2:test("nil is blank", function (t3)
t3:assert(m.is_blank(nil))
end)
t2:test("an empty string is blank", function (t3)
t3:assert(m.is_blank(""))
end)
t2:test("a string with only whitespaces is not blank, though it should be", function (t3)
t3:refute(m.is_blank(" "))
t3:refute(m.is_blank(" "))
end)
t2:test("booleans are not blank", function (t3)
t3:refute(m.is_blank(false))
t3:refute(m.is_blank(true))
end)
end)
case:describe("iodata_to_string/0", function (t2)
t2:test("can convert a table to a string", function (t3)
local result = m.iodata_to_string({"Hello", ", ", "World"})
t3:assert_eq(result, "Hello, World")
end)
t2:test("can handle nested tables", function (t3)
local result = m.iodata_to_string({"(", {"24", ",", "26", ",", "01"}, ")"})
t3:assert_eq(result, "(24,26,01)")
end)
end)
case:describe("random_string/1", function (t2)
t2:test("can generate random strings of specified length", function (t3)
local s = m.random_string(16)
t3:assert_eq(#s, 16)
end)
end)
case:describe("format_pretty_time/1", function (t2)
t2:test("can format a value greater than an hour", function (t3)
local result = m.format_pretty_time(3 * 60 * 60 + 60 * 5 + 32)
t3:assert_eq(result, "03:05:32")
result = m.format_pretty_time(12 * 60 * 60 + 60 * 11 + 9)
t3:assert_eq(result, "12:11:09")
end)
t2:test("can format a value greater than a minute", function (t3)
local result = m.format_pretty_time(60 * 5 + 7)
t3:assert_eq(result, "05:07")
result = m.format_pretty_time(60 * 5 + 32)
t3:assert_eq(result, "05:32")
result = m.format_pretty_time(60 * 32 + 32)
t3:assert_eq(result, "32:32")
end)
t2:test("can format a value less than a minute", function (t3)
local result = m.format_pretty_time(32)
t3:assert_eq(result, "32")
result = m.format_pretty_time(5)
t3:assert_eq(result, "05")
end)
end)
case:execute()
case:display_stats()
case:maybe_error()
mod:require("/tests/color_test.lua")
mod:require("/tests/direction_test.lua")
mod:require("/tests/iodata_test.lua")
mod:require("/tests/list_test.lua")
mod:require("/tests/number_test.lua")
mod:require("/tests/path_test.lua")
mod:require("/tests/rect_test.lua")
mod:require("/tests/string_test.lua")
mod:require("/tests/table_test.lua")
mod:require("/tests/value_test.lua")
mod:require("/tests/waves_test.lua")
|
local dpdk = require "dpdk"
local memory = require "memory"
local device = require "device"
local dpdkc = require "dpdkc"
local filter = require "filter"
local ffi = require "ffi"
ffi.cdef[[
uint32_t rte_mempool_count(void* mp);
]]
memory.enableCache()
local C = ffi.C
local PORT = 0
function master(...)
local dev = device.config(PORT)
local queue = dev:getTxQueue(0)
dev:wait()
local poolId = dpdk.launchLua("task", queue):wait()
dpdk.launchLua("reclaimTask", poolId):wait()
end
function task(queue)
local mempool = memory.createMemPool(function(buf)
local pkt = buf:getUdpPacket()
pkt.payload.uint32[0] = 0x1234
end)
local bufs = mempool:bufArray()
bufs:alloc(60)
queue:send(bufs)
dpdk.sleepMillis(50)
queue:stop()
queue:start()
assert(C.rte_mempool_count(mempool) == 2047)
queue.dev:getTxQueue(5)
local bufs = {}
for i = 1, 2047 do
bufs[#bufs + 1] = mempool:alloc(60)
end
assert(bufs[2047] ~= nil)
for i = 1, 2047 do
dpdkc.rte_pktmbuf_free_export(bufs[i])
end
-- important: pass this as a string as a future version will disable caching
-- for pools that are serialized (i.e. used by multiple cores)
return tostring(mempool)
end
function reclaimTask(poolAddr)
local numBufs = 0
local mempool = memory.createMemPool(function(buf)
local pkt = buf:getUdpPacket()
assert(pkt.payload.uint32[0] == 0)
numBufs = numBufs + 1
end)
assert(numBufs == 2047)
assert(C.rte_mempool_count(mempool) == 2047)
assert(poolAddr == tostring(mempool))
end
|
-- FUNCTIONAL
local Q = require 'Q'
require 'Q/UTILS/lua/strict'
local qconsts = require 'Q/UTILS/lua/qconsts'
local Scalar = require 'libsclr'
local qmem = require 'Q/UTILS/lua/qmem'
local chunk_size = qmem.chunk_size
local tests = {}
tests.t1 = function()
local val = (2048*1048576)-1
local len = chunk_size * 2 + 3
local qtype = "I4"
local c1 = Q.const( {val = val, qtype = qtype, len = len }):memo(true)
c1:eval()
for i = 1, len do
assert(c1:get1(i-1):to_num() == val)
end
assert(c1:num_elements() == len)
local status = pcall(c1.get1, len) -- deliberate error
assert(not status)
assert(c1:qtype() == qtype)
print("Test t1 succeeded")
end
tests.t2 = function()
local len = chunk_size * 3 + 1941;
local vals = { true, false }
local qtype = "B1"
for _, val in pairs(vals) do
local c1 = Q.const( {val = val, qtype = qtype, len = len })
c1:eval()
for i = 1, len do
assert(c1:get1(i-1) == Scalar.new(val, "B1"))
end
assert(c1:num_elements() == len)
local status = pcall(c1.get1, len) -- deliberate error
assert(c1:qtype() == qtype)
end
print("Test t2 succeeded")
end
tests.t3 = function() -- this is a stress test
local val = 1
local num_chunks = 1000 -- set this very large for a stress test
local len = num_chunks * chunk_size
local qtype = "I4"
local c1 = Q.const( {val = val, qtype = qtype, len = len }):memo(false)
for i = 1, num_chunks do
local chunk_len = c1:get_chunk(i-1)
assert(chunk_len == chunk_size)
if ( ( i % 1000000 ) == 0 ) then print("i = ", i) end
c1:unget_chunk(i-1)
local n1, n2 = c1:num_elements()
assert(not n2)
assert(n1 == i * chunk_size)
collectgarbage()
end
c1:get_chunk(num_chunks)
assert(c1:is_eov())
assert(c1:eval())
print("Test t3 succeeded")
end
--[[
tests.t1()
tests.t3()
tests.t2()
os.exit()
--]]
return tests
|
require("firecast.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
require("locale.lua");
local __o_Utils = require("utils.lua");
local function constructNew_templateKata()
local obj = GUI.fromHandle(_obj_newObject("form"));
local self = obj;
local sheet = nil;
rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));
function obj:setNodeObject(nodeObject)
sheet = nodeObject;
self.sheet = nodeObject;
self:_oldSetNodeObjectFunction(nodeObject);
end;
function obj:setNodeDatabase(nodeObject)
self:setNodeObject(nodeObject);
end;
_gui_assignInitialParentForForm(obj.handle);
obj:beginUpdate();
obj:setName("templateKata");
obj:setHeight(70);
obj.layout1 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout1:setParent(obj);
obj.layout1:setAlign("top");
obj.layout1:setHeight(30);
obj.layout1:setName("layout1");
obj.edit1 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit1:setParent(obj.layout1);
obj.edit1:setAlign("left");
obj.edit1:setField("aaa");
obj.edit1:setWidth(188);
obj.edit1:setMargins({right=2});
lfm_setPropAsString(obj.edit1, "fontStyle", "bold");
obj.edit1:setFontColor("white");
obj.edit1:setName("edit1");
obj.edit1:setFontFamily("Cambria");
obj.edit1:setTransparent(true);
obj.dataLink1 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink1:setParent(obj.layout1);
obj.dataLink1:setDefaultValue("—");
obj.dataLink1:setField("aaa");
obj.dataLink1:setName("dataLink1");
obj.btnKK = GUI.fromHandle(_obj_newObject("button"));
obj.btnKK:setParent(obj.layout1);
obj.btnKK:setAlign("right");
obj.btnKK:setName("btnKK");
obj.btnKK:setText("𝐢");
obj.btnKK:setWidth(30);
obj.btnKK:setMargins({right=2});
obj.button1 = GUI.fromHandle(_obj_newObject("button"));
obj.button1:setParent(obj.layout1);
obj.button1:setAlign("right");
obj.button1:setText("🞭");
obj.button1:setWidth(30);
obj.button1:setName("button1");
obj.edit2 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit2:setParent(obj.layout1);
obj.edit2:setAlign("client");
obj.edit2:setField("abb");
obj.edit2:setHorzTextAlign("center");
obj.edit2:setType("number");
obj.edit2:setMargins({right=2});
obj.edit2:setName("edit2");
obj.edit2:setFontFamily("Cambria");
obj.edit2:setTransparent(true);
obj.edit2:setFontColor("#cdcdcd");
obj.dataLink2 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink2:setParent(obj.layout1);
obj.dataLink2:setDefaultValue("1");
obj.dataLink2:setField("abb");
obj.dataLink2:setName("dataLink2");
obj.horzLine1 = GUI.fromHandle(_obj_newObject("horzLine"));
obj.horzLine1:setParent(obj);
obj.horzLine1:setAlign("top");
obj.horzLine1:setMargins({top=2, bottom=2});
obj.horzLine1:setStrokeColor("#424242");
obj.horzLine1:setName("horzLine1");
obj.layout2 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout2:setParent(obj);
obj.layout2:setAlign("top");
obj.layout2:setHeight(30);
obj.layout2:setName("layout2");
obj.comboBox1 = GUI.fromHandle(_obj_newObject("comboBox"));
obj.comboBox1:setParent(obj.layout2);
obj.comboBox1:setWidth(113);
obj.comboBox1:setAlign("left");
obj.comboBox1:setMargins({right=2});
obj.comboBox1:setItems({'Kata', 'Kiho Interno', 'Kiho Kármico', 'Kiho Marcial', 'Kiho Místico'});
obj.comboBox1:setField("tipoKata");
obj.comboBox1:setValues({'Kata', 'Kiho Interno', 'Kiho Kármico', 'Kiho Marcial', 'Kiho Místico'});
obj.comboBox1:setName("comboBox1");
obj.comboBox1:setFontFamily("Cambria");
obj.comboBox1:setTransparent(true);
obj.comboBox1:setFontColor("#cdcdcd");
obj.comboBox2 = GUI.fromHandle(_obj_newObject("comboBox"));
obj.comboBox2:setParent(obj.layout2);
obj.comboBox2:setWidth(113);
obj.comboBox2:setAlign("left");
obj.comboBox2:setMargins({right=2});
obj.comboBox2:setItems({'Água', 'Ar', 'Fogo', 'Terra', 'Vazio'});
obj.comboBox2:setField("elementoKata");
obj.comboBox2:setValues({'Água', 'Ar', 'Fogo', 'Terra', 'Vazio'});
obj.comboBox2:setName("comboBox2");
obj.comboBox2:setFontFamily("Cambria");
obj.comboBox2:setTransparent(true);
obj.comboBox2:setFontColor("#cdcdcd");
obj.popKK = GUI.fromHandle(_obj_newObject("popup"));
obj.popKK:setParent(obj.layout2);
obj.popKK:setName("popKK");
obj.popKK:setWidth(440);
obj.popKK:setHeight(200);
obj.popKK:setBackOpacity(0);
obj.popKK:setDrawContainer(false);
lfm_setPropAsString(obj.popKK, "autoScopeNode", "true");
obj.rectangle1 = GUI.fromHandle(_obj_newObject("rectangle"));
obj.rectangle1:setParent(obj.popKK);
obj.rectangle1:setAlign("client");
obj.rectangle1:setColor("#0e0e0e");
obj.rectangle1:setPadding({top=10, left=10, bottom=10, right=10});
obj.rectangle1:setXradius(10);
obj.rectangle1:setYradius(10);
obj.rectangle1:setCornerType("bevel");
obj.rectangle1:setName("rectangle1");
obj.label1 = GUI.fromHandle(_obj_newObject("label"));
obj.label1:setParent(obj.rectangle1);
obj.label1:setFontColor("white");
obj.label1:setAlign("top");
obj.label1:setField("aaa");
obj.label1:setMargins({bottom=5});
lfm_setPropAsString(obj.label1, "fontStyle", "bold");
obj.label1:setFontFamily("Constantia");
obj.label1:setFontSize(26);
obj.label1:setHeight(30);
obj.label1:setName("label1");
obj.horzLine2 = GUI.fromHandle(_obj_newObject("horzLine"));
obj.horzLine2:setParent(obj.rectangle1);
obj.horzLine2:setAlign("top");
obj.horzLine2:setMargins({bottom=5});
obj.horzLine2:setStrokeColor("#424242");
obj.horzLine2:setName("horzLine2");
obj.textEditor1 = GUI.fromHandle(_obj_newObject("textEditor"));
obj.textEditor1:setParent(obj.rectangle1);
obj.textEditor1:setField("descriKata");
obj.textEditor1:setAlign("client");
obj.textEditor1:setFontFamily("Cambria");
obj.textEditor1:setTransparent(true);
obj.textEditor1:setName("textEditor1");
obj.dataLink3 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink3:setParent(obj.rectangle1);
obj.dataLink3:setField("descriKata");
obj.dataLink3:setDefaultValue("—");
obj.dataLink3:setName("dataLink3");
obj._e_event0 = obj.btnKK:addEventListener("onClick",
function (_)
local pop = self:findControlByName("popKK");
if pop ~= nil then
pop:setNodeObject(self.sheet);
pop:showPopupEx("left", self.btnKK);
else
showMessage("Ops, bug... Nao encontrei o popup para exibir");
end;
end, obj);
obj._e_event1 = obj.button1:addEventListener("onClick",
function (_)
NDB.deleteNode(sheet);
end, obj);
function obj:_releaseEvents()
__o_rrpgObjs.removeEventListenerById(self._e_event1);
__o_rrpgObjs.removeEventListenerById(self._e_event0);
end;
obj._oldLFMDestroy = obj.destroy;
function obj:destroy()
self:_releaseEvents();
if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
self:setNodeDatabase(nil);
end;
if self.dataLink3 ~= nil then self.dataLink3:destroy(); self.dataLink3 = nil; end;
if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end;
if self.label1 ~= nil then self.label1:destroy(); self.label1 = nil; end;
if self.textEditor1 ~= nil then self.textEditor1:destroy(); self.textEditor1 = nil; end;
if self.popKK ~= nil then self.popKK:destroy(); self.popKK = nil; end;
if self.btnKK ~= nil then self.btnKK:destroy(); self.btnKK = nil; end;
if self.edit2 ~= nil then self.edit2:destroy(); self.edit2 = nil; end;
if self.dataLink2 ~= nil then self.dataLink2:destroy(); self.dataLink2 = nil; end;
if self.horzLine1 ~= nil then self.horzLine1:destroy(); self.horzLine1 = nil; end;
if self.layout1 ~= nil then self.layout1:destroy(); self.layout1 = nil; end;
if self.comboBox1 ~= nil then self.comboBox1:destroy(); self.comboBox1 = nil; end;
if self.edit1 ~= nil then self.edit1:destroy(); self.edit1 = nil; end;
if self.layout2 ~= nil then self.layout2:destroy(); self.layout2 = nil; end;
if self.comboBox2 ~= nil then self.comboBox2:destroy(); self.comboBox2 = nil; end;
if self.rectangle1 ~= nil then self.rectangle1:destroy(); self.rectangle1 = nil; end;
if self.horzLine2 ~= nil then self.horzLine2:destroy(); self.horzLine2 = nil; end;
if self.dataLink1 ~= nil then self.dataLink1:destroy(); self.dataLink1 = nil; end;
self:_oldLFMDestroy();
end;
obj:endUpdate();
return obj;
end;
function newtemplateKata()
local retObj = nil;
__o_rrpgObjs.beginObjectsLoading();
__o_Utils.tryFinally(
function()
retObj = constructNew_templateKata();
end,
function()
__o_rrpgObjs.endObjectsLoading();
end);
assert(retObj ~= nil);
return retObj;
end;
local _templateKata = {
newEditor = newtemplateKata,
new = newtemplateKata,
name = "templateKata",
dataType = "",
formType = "undefined",
formComponentName = "form",
title = "",
description=""};
templateKata = _templateKata;
Firecast.registrarForm(_templateKata);
return _templateKata;
|
object_intangible_vehicle_pod_racer_ipg_longtail_pcd = object_intangible_vehicle_shared_pod_racer_ipg_longtail_pcd:new {
}
ObjectTemplates:addTemplate(object_intangible_vehicle_pod_racer_ipg_longtail_pcd, "object/intangible/vehicle/pod_racer_ipg_longtail_pcd.iff")
|
-- @Author:pandayu
-- @Version:1.0
-- @DateTime:2018-09-09
-- @Project:pandaCardServer CardGame
-- @Contact: QQ:815099602
local _M = function(role,data)
if not data.id or type(data.id) ~= "number" then return 2 end
local pass = role.both:can_stage(data.id)
if not pass then return 2402 end
role.both:set_begin_stage(data.id)
return 0
end
return _M
|
-- TODO: sacar el seeall
module(..., package.seeall)
-- Query String Utilities
--var QueryString = exports;
--var urlDecode = process.binding("http_parser").urlDecode;
--// a safe fast alternative to decodeURIComponent
--QueryString.unescape = urlDecode;
--QueryString.escape = function (str) {
-- return encodeURIComponent(str);
--};
--var stringifyPrimitive = function(v) {
-- switch (typeof v) {
-- case "string":
-- return v;
--
-- case "boolean":
-- return v ? "true" : "false";
--
-- case "number":
-- return isFinite(v) ? v : "";
--
-- default:
-- return "";
-- }
--};
--[[
/**
* <p>Converts an arbitrary value to a Query String representation.</p>
*
* <p>Objects with cyclical references will trigger an exception.</p>
*
* @method stringify
* @param obj {Variant} any arbitrary value to convert to query string
* @param sep {String} (optional) Character that should join param k=v pairs together. Default: "&"
* @param eq {String} (optional) Character that should join keys to their values. Default: "="
* @param name {String} (optional) Name of the current key, for handling children recursively.
* @static
*/
QueryString.stringify = QueryString.encode = function (obj, sep, eq, name) {
sep = sep || "&";
eq = eq || "=";
obj = (obj === null) ? undefined : obj;
switch (typeof obj) {
case "object":
return Object.keys(obj).map(function(k) {
if (Array.isArray(obj[k])) {
return obj[k].map(function(v) {
return QueryString.escape(stringifyPrimitive(k)) +
eq +
QueryString.escape(stringifyPrimitive(v));
}).join(sep);
} else {
return QueryString.escape(stringifyPrimitive(k)) +
eq +
QueryString.escape(stringifyPrimitive(obj[k]));
}
}).join(sep);
default:
return (name) ?
QueryString.escape(stringifyPrimitive(name)) + eq +
QueryString.escape(stringifyPrimitive(obj)) :
"";
}
};
// Parse a key=val string.
QueryString.parse = QueryString.decode = function (qs, sep, eq) {
sep = sep || "&";
eq = eq || "=";
var obj = {};
if (typeof qs !== 'string') {
return obj;
}
qs.split(sep).forEach(function(kvp) {
var x = kvp.split(eq);
var k = QueryString.unescape(x[0], true);
var v = QueryString.unescape(x.slice(1).join(eq), true);
if (!(k in obj)) {
obj[k] = v;
} else if (!Array.isArray(obj[k])) {
obj[k] = [obj[k], v];
} else {
obj[k].push(v);
}
});
return obj;
};
--]]
--
-- Encodes the key-value pairs of a table according the application/x-www-form-urlencoded content type.
function url_encode_arguments(arguments)
local body = {}
for k,v in pairs(arguments) do
body[#body + 1] = Url.escape(tostring(k)) .. "=" .. Url.escape(tostring(v))
end
return table.concat(body, "&")
end
-- Taken from wsapi (TODO: add proper attribution)
----------------------------------------------------------------------------
-- Decode an URL-encoded string (see RFC 2396)
----------------------------------------------------------------------------
function url_decode(str)
if not str then return nil end
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end)
str = string.gsub (str, "\r\n", "\n")
return str
end
-- Taken from wsapi (TODO: add proper attribution)
----------------------------------------------------------------------------
-- URL-encode a string (see RFC 2396)
----------------------------------------------------------------------------
function url_encode(str)
if not str then return nil end
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w ])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
return str
end
-- Taken from wsapi (TODO: add proper attribution)
local function insert_field (tab, name, value, overwrite)
if overwrite or not tab[name] then
tab[name] = value
else
local t = type (tab[name])
if t == "table" then
table.insert (tab[name], value)
else
tab[name] = { tab[name], value }
end
end
end
function parse(qs, tab, overwrite)
tab = tab or {}
if type(qs) == "string" then
local url_decode = url_decode
for key, val in string.gmatch(qs, "([^&=]+)=([^&=]*)&?") do
insert_field(tab, url_decode(key), url_decode(val), overwrite)
end
elseif qs then
error("WSAPI Request error: invalid query string")
end
return tab
end |
function ApplyParticleToIllusions(keys)
local caster = keys.caster
local target = keys.target
if target:IsIllusion() and caster:IsRealHero() then
target.GemOfClearMindIllusionParticle = ParticleManager:CreateParticleForTeam("particles/arena/items_fx/gem_of_clear_mind_illusion.vpcf", PATTACH_ABSORIGIN_FOLLOW, target, caster:GetTeamNumber())
end
end
function RemoveParticleFromIllusions(keys)
local target = keys.target
if target.GemOfClearMindIllusionParticle then
ParticleManager:DestroyParticle(target.GemOfClearMindIllusionParticle, false)
target.GemOfClearMindIllusionParticle = nil
end
end |
local api = require("fromage")
local client = api()
local enumerations = client.enumerations()
coroutine.wrap(function()
client.connect("Username#0000", "password")
if client.isConnected() then
print("Members:")
local members, err = client.getTribeMembers() -- Gets the list of members of the tribe
if members then
p(members)
else
print(err)
end
print("Tribe ranks:")
local ranks
ranks, err = client.getTribeRanks() -- Gets the list of rank names of the tribe
if ranks then
p(ranks)
else
print(err)
end
print("Tribe history:")
local history
history, err = client.getTribeHistory() -- Gets the list of history logs of the tribe
if history then
p(history)
else
print(err)
end
print("Tribe forum sections:")
local sections
sections, err = client.getTribeForum() -- Gets the data of the tribe forum
if sections then
p(sections)
else
print(err)
end
end
client.disconnect()
os.execute("pause >nul")
end)() |
--[[
File: src/level/layer.lua
Author: Daniel "lytedev" Flanagan
Website: http://dmf.me
Defines a layer of tiles and methods for manipulating/managing them.
]]--
local Tile = require("src.level.tile")
local Layer = Class{function(self, size, tileset, tileSize)
self.tiles = {}
self.size = vector(20, 20)
self.objects = {}
self.level = nil
for i = 1, self.size.x * self.size.y do
self.tiles[i] = 0
end
self.tileset = tileset or {Tile()}
self.tileSize = tileSize or vector(16, 16)
self.lastObjectId = 0
end}
-- Object Methods
function Layer:getNextObjectId()
if self.lastObjectId >= 99999999999999 then
self.lastObjectId = 0
end
repeat
self.lastObjectId = self.lastObjectId + 1
until self.layers[self.lastObjectId] == nil
return self.lastObjectId
end
function Layer:getObject(id)
return self.objects[id]
end
function Layer:addObject(g)
g.level = self.level
g.layer = self
g.id = self:getNextObjectId()
self.objects[g.id] = g
end
function Layer:removeObject(id)
table.remove(self.objects, id)
end
function Layer:coordsToId(x, y)
x = math.floor(x)
y = math.floor(y)
if self:tileExists(x, y) then
return ((y * self.size.x) + x) + 1;
else
return nil
end
end
function Layer:idToCoords(id)
return vector(math.floor((id - 1) % self.size.x), math.floor((id - 1) / self.size.x))
end
function Layer:setTile(x, y, type)
x = math.floor(x)
y = math.floor(y)
if self:tileExists(x, y) then
self.tiles[self:coordsToId(x, y)] = type
end
end
function Layer:setTileById(id, type)
if id <= #self.tiles and id > 0 then
self.tiles[id] = type
end
end
function Layer:getTileType(x, y)
x = math.floor(x)
y = math.floor(y)
if self:tileExists(x, y) then
return self.tiles[self:coordsToId(x, y)]
else
return 0
end
end
function Layer:getTileTypeById(id)
if id <= #self.tiles and id > 0 then
return self.tiles[id]
end
end
function Layer:getTile(x, y)
x = math.floor(x)
y = math.floor(y)
if self:tileExists(x, y) then
return self.tileset[self:getTileType(x, y)]
else
return self.blankTile
end
end
function Layer:getTileById(id)
local tileTypeId = self:getTileTypeById(id)
if tileTypeId ~= 0 then
return self.tileset[tileTypeId]
else
return self.blankTile
end
end
function Layer:selectTileSection(position, size, noclamp)
local noclamp = noclamp or false
noclamp = false
local x1, y1, x2, y2 = selectRectangles(position, size, vector(self.tileSize, self.tileSize))
if not noclamp then
x1 = math.clamp(0, x1, self.size.x - 1)
y1 = math.clamp(0, y1, self.size.y - 1)
x2 = math.clamp(0, x2, self.size.x - 1)
y2 = math.clamp(0, y2, self.size.y - 1)
-- print(TileGrid.numofclamps .. "HEY!")
end
return x1, y1, x2, y2
end
function Layer:tileExists(x, y)
return x >= 0 and x < self.size.x and y >= 0 and y < self.size.y
end
function Layer:tileExistsById(i)
return self:tileExists(self:idToCoords(i))
end
function Layer:collideObjectWithTiles(g, dt)
local pos, size = g:getVelocityAABB(g.velocity * dt)
local x1, y1, x2, y2 = self:selectTileSection(pos, size)
if not x1 or not y1 or not x2 or not y2 then
return nil
end
local tsize = vector(self.tileSize, self.tileSize)
for x = x1, x2 do
for y = y1, y2 do
local t = self:getTile(x, y)
if t then
local p = vector(x, y) * tsize
g:collide(p, tsize)
end
end
end
end
function Layer:update(dt)
for i = 1, #self.tileset do
self.tileset[i]:update(dt)
end
for k, v in pairs(self.objects) do
v:update(dt)
for k2, v2 in pairs(self.objects) do
if v2 ~= v then
v:collideWithObject(v2, dt)
end
end
self:collideObjectWithTiles(v, dt)
end
end
function Layer:getNextObjectId()
if self.lastObjectId >= 99999999999999 then
self.lastObjectId = 0
end
repeat
self.lastObjectId = self.lastObjectId + 1
until self.objects[self.lastObjectId] == nil
return self.lastObjectId
end
function Layer:addObject(g)
g.layer = self
g.lid = self.id
g.id = self:getNextObjectId()
self.objects[g.id] = g
end
function Layer:draw()
local max = self.size.x * self.size.y
for i = 1, max do
local c = self:idToCoords(i)
local tile = self:getTileById(i)
local c2 = vector(c.x * self.tileSize.x, c.y, c.y * self.tileSize.y)
if tile then
tile:draw(c2)
end
-- love.graphics.rectangle("line", c.x * self.tileSize, c.y * self.tileSize, self.tileSize, self.tileSize)
end
for k, v in pairs(self.objects) do
v:draw()
end
end
return Layer
|
-- TUI acceptance tests.
-- Uses :terminal as a way to send keys and assert screen state.
--
-- "bracketed paste" terminal feature:
-- http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Bracketed-Paste-Mode
local helpers = require('test.functional.helpers')(after_each)
local uname = helpers.uname
local thelpers = require('test.functional.terminal.helpers')
local Screen = require('test.functional.ui.screen')
local assert_alive = helpers.assert_alive
local eq = helpers.eq
local feed_command = helpers.feed_command
local feed_data = thelpers.feed_data
local clear = helpers.clear
local command = helpers.command
local nvim_dir = helpers.nvim_dir
local retry = helpers.retry
local nvim_prog = helpers.nvim_prog
local nvim_set = helpers.nvim_set
local ok = helpers.ok
local read_file = helpers.read_file
if helpers.pending_win32(pending) then return end
describe('TUI', function()
local screen
local child_session
before_each(function()
clear()
local child_server = helpers.new_pipename()
screen = thelpers.screen_setup(0,
string.format([=[["%s", "--listen", "%s", "-u", "NONE", "-i", "NONE", "--cmd", "%s laststatus=2 background=dark"]]=],
nvim_prog, child_server, nvim_set))
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
|
{3:-- TERMINAL --} |
]])
child_session = helpers.connect(child_server)
end)
-- Wait for mode in the child Nvim (avoid "typeahead race" #10826).
local function wait_for_mode(mode)
retry(nil, nil, function()
local _, m = child_session:request('nvim_get_mode')
eq(mode, m.mode)
end)
end
-- Assert buffer contents in the child Nvim.
local function expect_child_buf_lines(expected)
assert(type({}) == type(expected))
retry(nil, nil, function()
local _, buflines = child_session:request(
'nvim_buf_get_lines', 0, 0, -1, false)
eq(expected, buflines)
end)
end
it('rapid resize #7572 #7628', function()
-- Need buffer rows to provoke the behavior.
feed_data(":edit test/functional/fixtures/bigfile.txt:")
command('call jobresize(b:terminal_job_id, 58, 9)')
command('call jobresize(b:terminal_job_id, 62, 13)')
command('call jobresize(b:terminal_job_id, 100, 42)')
command('call jobresize(b:terminal_job_id, 37, 1000)')
-- Resize to <5 columns.
screen:try_resize(4, 44)
command('call jobresize(b:terminal_job_id, 4, 1000)')
-- Resize to 1 row, then to 1 column, then increase rows to 4.
screen:try_resize(44, 1)
command('call jobresize(b:terminal_job_id, 44, 1)')
screen:try_resize(1, 1)
command('call jobresize(b:terminal_job_id, 1, 1)')
screen:try_resize(1, 4)
command('call jobresize(b:terminal_job_id, 1, 4)')
screen:try_resize(57, 17)
command('call jobresize(b:terminal_job_id, 57, 17)')
assert_alive()
end)
it('accepts resize while pager is active', function()
child_session:request("nvim_command", [[
set more
func! ManyErr()
for i in range(10)
echoerr "FAIL ".i
endfor
endfunc
]])
feed_data(':call ManyErr()\r')
screen:expect{grid=[[
{8:Error detected while processing function ManyErr:} |
{11:line 2:} |
{8:FAIL 0} |
{8:FAIL 1} |
{8:FAIL 2} |
{10:-- More --}{1: } |
{3:-- TERMINAL --} |
]]}
feed_data('d')
screen:expect{grid=[[
{8:FAIL 1} |
{8:FAIL 2} |
{8:FAIL 3} |
{8:FAIL 4} |
{8:FAIL 5} |
{10:-- More --}{1: } |
{3:-- TERMINAL --} |
]]}
screen:try_resize(50,5)
screen:expect{grid=[[
{8:FAIL 3} |
{8:FAIL 4} |
{8:FAIL 5} |
{10:-- More --}{1: } |
{3:-- TERMINAL --} |
]]}
-- TODO(bfredl): messes up the output (just like vim does).
feed_data('g')
screen:expect{grid=[[
) |
{8:Error detected while processing function ManyErr:} |
{11:line 2:} |
{10:-- More --}{1: } |
{3:-- TERMINAL --} |
]]}
screen:try_resize(50,10)
screen:expect{grid=[[
) |
{8:Error detected while processing function ManyErr:} |
{11:line 2:} |
{8:FAIL 0} |
{8:FAIL 1} |
{8:FAIL 2} |
{8:FAIL 3} |
{8:FAIL 4} |
{10:-- More --}{1: } |
{3:-- TERMINAL --} |
]]}
feed_data('\003')
screen:expect{grid=[[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
|
{3:-- TERMINAL --} |
]]}
end)
it('accepts basic utf-8 input', function()
feed_data('iabc\ntest1\ntest2')
screen:expect([[
abc |
test1 |
test2{1: } |
{4:~ }|
{5:[No Name] [+] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
feed_data('\027')
screen:expect([[
abc |
test1 |
test{1:2} |
{4:~ }|
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]])
end)
it('interprets leading <Esc> byte as ALT modifier in normal-mode', function()
local keys = 'dfghjkl'
for c in keys:gmatch('.') do
feed_command('nnoremap <a-'..c..'> ialt-'..c..'<cr><esc>')
feed_data('\027'..c)
end
screen:expect([[
alt-j |
alt-k |
alt-l |
{1: } |
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]])
feed_data('gg')
screen:expect([[
{1:a}lt-d |
alt-f |
alt-g |
alt-h |
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]])
end)
it('interprets ESC+key as ALT chord', function()
-- Vim represents ALT/META by setting the "high bit" of the modified key:
-- ALT+j inserts "ê". Nvim does not (#3982).
feed_data('i\022\027j')
screen:expect([[
<M-j>{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
end)
it('accepts ASCII control sequences', function()
feed_data('i')
feed_data('\022\007') -- ctrl+g
feed_data('\022\022') -- ctrl+v
feed_data('\022\013') -- ctrl+m
local attrs = screen:get_default_attr_ids()
attrs[11] = {foreground = 81}
screen:expect([[
{11:^G^V^M}{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]], attrs)
end)
it('paste: Insert mode', function()
-- "bracketed paste"
feed_data('i""\027i\027[200~')
screen:expect([[
"{1:"} |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
feed_data('pasted from terminal')
expect_child_buf_lines({'"pasted from terminal"'})
screen:expect([[
"pasted from terminal{1:"} |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
feed_data('\027[201~') -- End paste.
feed_data('\027\000') -- ESC: go to Normal mode.
wait_for_mode('n')
screen:expect([[
"pasted from termina{1:l}" |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]])
-- Dot-repeat/redo.
feed_data('2.')
expect_child_buf_lines(
{'"pasted from terminapasted from terminalpasted from terminall"'})
screen:expect([[
"pasted from terminapasted from terminalpasted fro|
m termina{1:l}l" |
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]])
-- Undo.
feed_data('u')
expect_child_buf_lines({'"pasted from terminal"'})
feed_data('u')
expect_child_buf_lines({'""'})
feed_data('u')
expect_child_buf_lines({''})
end)
it('paste: select-mode', function()
feed_data('ithis is line 1\nthis is line 2\nline 3 is here\n\027')
wait_for_mode('n')
screen:expect{grid=[[
this is line 1 |
this is line 2 |
line 3 is here |
{1: } |
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]]}
-- Select-mode. Use <C-n> to move down.
feed_data('gg04lgh\14\14')
wait_for_mode('s')
feed_data('\027[200~')
feed_data('just paste it™')
feed_data('\027[201~')
screen:expect{grid=[[
thisjust paste it™{1:3} is here |
|
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]]}
-- Undo.
feed_data('u')
expect_child_buf_lines{
'this is line 1',
'this is line 2',
'line 3 is here',
'',
}
-- Redo.
feed_data('\18') -- <C-r>
expect_child_buf_lines{
'thisjust paste it™3 is here',
'',
}
end)
it('paste: terminal mode', function()
if os.getenv('GITHUB_ACTIONS') ~= nil then
pending("tty-test complains about not owning the terminal -- actions/runner#241")
return
end
feed_data(':set statusline=^^^^^^^\n')
feed_data(':terminal '..nvim_dir..'/tty-test\n')
feed_data('i')
screen:expect{grid=[[
tty ready |
{1: } |
|
|
{5:^^^^^^^ }|
{3:-- TERMINAL --} |
{3:-- TERMINAL --} |
]]}
feed_data('\027[200~')
feed_data('hallo')
feed_data('\027[201~')
screen:expect{grid=[[
tty ready |
hallo{1: } |
|
|
{5:^^^^^^^ }|
{3:-- TERMINAL --} |
{3:-- TERMINAL --} |
]]}
end)
it('paste: normal-mode (+CRLF #10872)', function()
feed_data(':set ruler')
wait_for_mode('c')
feed_data('\n')
wait_for_mode('n')
local expected_lf = {'line 1', 'ESC:\027 / CR: \rx'}
local expected_crlf = {'line 1', 'ESC:\027 / CR: ', 'x'}
local expected_grid1 = [[
line 1 |
ESC:{11:^[} / CR: |
{1:x} |
{4:~ }|
{5:[No Name] [+] 3,1 All}|
|
{3:-- TERMINAL --} |
]]
local expected_attr = {
[1] = {reverse = true},
[3] = {bold = true},
[4] = {foreground = tonumber('0x00000c')},
[5] = {bold = true, reverse = true},
[11] = {foreground = tonumber('0x000051')},
[12] = {reverse = true, foreground = tonumber('0x000051')},
}
-- "bracketed paste"
feed_data('\027[200~'..table.concat(expected_lf,'\n')..'\027[201~')
screen:expect{grid=expected_grid1, attr_ids=expected_attr}
-- Dot-repeat/redo.
feed_data('.')
screen:expect{
grid=[[
ESC:{11:^[} / CR: |
xline 1 |
ESC:{11:^[} / CR: |
{1:x} |
{5:[No Name] [+] 5,1 Bot}|
|
{3:-- TERMINAL --} |
]],
attr_ids=expected_attr}
-- Undo.
feed_data('u')
expect_child_buf_lines(expected_crlf)
feed_data('u')
expect_child_buf_lines({''})
-- CRLF input
feed_data('\027[200~'..table.concat(expected_lf,'\r\n')..'\027[201~')
screen:expect{
grid=expected_grid1:gsub(
':set ruler *',
'3 fewer lines; before #1 0 seconds ago '),
attr_ids=expected_attr}
expect_child_buf_lines(expected_crlf)
end)
it('paste: cmdline-mode inserts 1 line', function()
feed_data('ifoo\n') -- Insert some text (for dot-repeat later).
feed_data('\027:""') -- Enter Cmdline-mode.
feed_data('\027[D') -- <Left> to place cursor between quotes.
wait_for_mode('c')
-- "bracketed paste"
feed_data('\027[200~line 1\nline 2\n')
wait_for_mode('c')
feed_data('line 3\nline 4\n\027[201~')
wait_for_mode('c')
screen:expect{grid=[[
foo |
|
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
:"line 1{1:"} |
{3:-- TERMINAL --} |
]]}
-- Dot-repeat/redo.
feed_data('\027\000')
wait_for_mode('n')
feed_data('.')
screen:expect{grid=[[
foo |
foo |
{1: } |
{4:~ }|
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]]}
end)
it('paste: cmdline-mode collects chunks of unfinished line', function()
local function expect_cmdline(expected)
retry(nil, nil, function()
local _, cmdline = child_session:request(
'nvim_call_function', 'getcmdline', {})
eq(expected, cmdline)
end)
end
feed_data('\027:""') -- Enter Cmdline-mode.
feed_data('\027[D') -- <Left> to place cursor between quotes.
wait_for_mode('c')
feed_data('\027[200~stuff 1 ')
expect_cmdline('"stuff 1 "')
-- Discards everything after the first line.
feed_data('more\nstuff 2\nstuff 3\n')
expect_cmdline('"stuff 1 more"')
feed_data('stuff 3')
expect_cmdline('"stuff 1 more"')
-- End the paste sequence.
feed_data('\027[201~')
feed_data(' typed')
expect_cmdline('"stuff 1 more typed"')
end)
it('paste: recovers from vim.paste() failure', function()
child_session:request('nvim_exec_lua', [[
_G.save_paste_fn = vim.paste
-- Stack traces for this test are non-deterministic, so disable them
_G.debug.traceback = function(msg) return msg end
vim.paste = function(lines, phase) error("fake fail") end
]], {})
-- Prepare something for dot-repeat/redo.
feed_data('ifoo\n\027\000')
wait_for_mode('n')
screen:expect{grid=[[
foo |
{1: } |
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]]}
-- Start pasting...
feed_data('\027[200~line 1\nline 2\n')
screen:expect{grid=[[
foo |
|
{5: }|
{8:paste: Error executing lua: [string "<nvim>"]:4: f}|
{8:ake fail} |
{10:Press ENTER or type command to continue}{1: } |
{3:-- TERMINAL --} |
]]}
-- Remaining chunks are discarded after vim.paste() failure.
feed_data('line 3\nline 4\n')
feed_data('line 5\nline 6\n')
feed_data('line 7\nline 8\n')
-- Stop paste.
feed_data('\027[201~')
feed_data('\n') -- <CR>
expect_child_buf_lines({'foo',''})
--Dot-repeat/redo is not modified by failed paste.
feed_data('.')
screen:expect{grid=[[
foo |
foo |
{1: } |
{4:~ }|
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]]}
-- Editor should still work after failed/drained paste.
feed_data('ityped input...\027\000')
screen:expect{grid=[[
foo |
foo |
typed input..{1:.} |
{4:~ }|
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]]}
-- Paste works if vim.paste() succeeds.
child_session:request('nvim_exec_lua', [[
vim.paste = _G.save_paste_fn
]], {})
feed_data('\027[200~line A\nline B\n\027[201~')
feed_data('\n') -- <CR>
screen:expect{grid=[[
foo |
typed input...line A |
line B |
{1: } |
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]]}
end)
it('paste: vim.paste() cancel (retval=false) #10865', function()
-- This test only exercises the "cancel" case. Use-case would be "dangling
-- paste", but that is not implemented yet. #10865
child_session:request('nvim_exec_lua', [[
vim.paste = function(lines, phase) return false end
]], {})
feed_data('\027[200~line A\nline B\n\027[201~')
feed_data('ifoo\n\027\000')
expect_child_buf_lines({'foo',''})
end)
it("paste: 'nomodifiable' buffer", function()
child_session:request('nvim_command', 'set nomodifiable')
child_session:request('nvim_exec_lua', [[
-- Stack traces for this test are non-deterministic, so disable them
_G.debug.traceback = function(msg) return msg end
]], {})
feed_data('\027[200~fail 1\nfail 2\n\027[201~')
screen:expect{grid=[[
|
{4:~ }|
{5: }|
{8:paste: Error executing lua: vim.lua:243: Vim:E21: }|
{8:Cannot make changes, 'modifiable' is off} |
{10:Press ENTER or type command to continue}{1: } |
{3:-- TERMINAL --} |
]]}
feed_data('\n') -- <Enter>
child_session:request('nvim_command', 'set modifiable')
feed_data('\027[200~success 1\nsuccess 2\n\027[201~')
screen:expect{grid=[[
success 1 |
success 2 |
{1: } |
{4:~ }|
{5:[No Name] [+] }|
|
{3:-- TERMINAL --} |
]]}
end)
it('paste: exactly 64 bytes #10311', function()
local expected = string.rep('z', 64)
feed_data('i')
wait_for_mode('i')
-- "bracketed paste"
feed_data('\027[200~'..expected..'\027[201~')
-- FIXME: Data race between the two feeds
if uname() == 'freebsd' then screen:sleep(1) end
feed_data(' end')
expected = expected..' end'
screen:expect([[
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz|
zzzzzzzzzzzzzz end{1: } |
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
expect_child_buf_lines({expected})
end)
it('paste: less-than sign in cmdline #11088', function()
local expected = '<'
feed_data(':')
wait_for_mode('c')
-- "bracketed paste"
feed_data('\027[200~'..expected..'\027[201~')
screen:expect{grid=[[
|
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
:<{1: } |
{3:-- TERMINAL --} |
]]}
end)
it('paste: big burst of input', function()
feed_data(':set ruler\n')
local t = {}
for i = 1, 3000 do
t[i] = 'item ' .. tostring(i)
end
feed_data('i')
wait_for_mode('i')
-- "bracketed paste"
feed_data('\027[200~'..table.concat(t, '\n')..'\027[201~')
expect_child_buf_lines(t)
feed_data(' end')
screen:expect([[
item 2997 |
item 2998 |
item 2999 |
item 3000 end{1: } |
{5:[No Name] [+] 3000,14 Bot}|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
feed_data('\027\000') -- ESC: go to Normal mode.
wait_for_mode('n')
-- Dot-repeat/redo.
feed_data('.')
screen:expect([[
item 2997 |
item 2998 |
item 2999 |
item 3000 en{1:d} |
{5:[No Name] [+] 3000,13 Bot}|
|
{3:-- TERMINAL --} |
]])
end)
it('paste: forwards spurious "start paste" code', function()
-- If multiple "start paste" sequences are sent without a corresponding
-- "stop paste" sequence, only the first occurrence should be consumed.
-- Send the "start paste" sequence.
feed_data('i\027[200~')
feed_data('\npasted from terminal (1)\n')
-- Send spurious "start paste" sequence.
feed_data('\027[200~')
feed_data('\n')
-- Send the "stop paste" sequence.
feed_data('\027[201~')
screen:expect{grid=[[
|
pasted from terminal (1) |
{6:^[}[200~ |
{1: } |
{5:[No Name] [+] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]],
attr_ids={
[1] = {reverse = true},
[2] = {background = tonumber('0x00000b')},
[3] = {bold = true},
[4] = {foreground = tonumber('0x00000c')},
[5] = {bold = true, reverse = true},
[6] = {foreground = tonumber('0x000051')},
}}
end)
it('paste: ignores spurious "stop paste" code', function()
-- If "stop paste" sequence is received without a preceding "start paste"
-- sequence, it should be ignored.
feed_data('i')
-- Send "stop paste" sequence.
feed_data('\027[201~')
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
end)
it('paste: split "start paste" code', function()
feed_data('i')
-- Send split "start paste" sequence.
feed_data('\027[2')
feed_data('00~pasted from terminal\027[201~')
screen:expect([[
pasted from terminal{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
end)
it('paste: split "stop paste" code', function()
feed_data('i')
-- Send split "stop paste" sequence.
feed_data('\027[200~pasted from terminal\027[20')
feed_data('1~')
screen:expect([[
pasted from terminal{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] [+] }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
end)
it('allows termguicolors to be set at runtime', function()
screen:set_option('rgb', true)
screen:set_default_attr_ids({
[1] = {reverse = true},
[2] = {foreground = tonumber('0x4040ff'), fg_indexed=true},
[3] = {bold = true, reverse = true},
[4] = {bold = true},
[5] = {reverse = true, foreground = tonumber('0xe0e000'), fg_indexed=true},
[6] = {foreground = tonumber('0xe0e000'), fg_indexed=true},
[7] = {reverse = true, foreground = Screen.colors.SeaGreen4},
[8] = {foreground = Screen.colors.SeaGreen4},
[9] = {bold = true, foreground = Screen.colors.Blue1},
})
feed_data(':hi SpecialKey ctermfg=3 guifg=SeaGreen\n')
feed_data('i')
feed_data('\022\007') -- ctrl+g
feed_data('\028\014') -- crtl+\ ctrl+N
feed_data(':set termguicolors?\n')
screen:expect([[
{5:^}{6:G} |
{2:~ }|
{2:~ }|
{2:~ }|
{3:[No Name] [+] }|
notermguicolors |
{4:-- TERMINAL --} |
]])
feed_data(':set termguicolors\n')
screen:expect([[
{7:^}{8:G} |
{9:~ }|
{9:~ }|
{9:~ }|
{3:[No Name] [+] }|
:set termguicolors |
{4:-- TERMINAL --} |
]])
feed_data(':set notermguicolors\n')
screen:expect([[
{5:^}{6:G} |
{2:~ }|
{2:~ }|
{2:~ }|
{3:[No Name] [+] }|
:set notermguicolors |
{4:-- TERMINAL --} |
]])
end)
it('forwards :term palette colors with termguicolors', function()
if os.getenv('GITHUB_ACTIONS') ~= nil then
pending("tty-test complains about not owning the terminal -- actions/runner#241")
return
end
screen:set_rgb_cterm(true)
screen:set_default_attr_ids({
[1] = {{reverse = true}, {reverse = true}},
[2] = {{bold = true, reverse = true}, {bold = true, reverse = true}},
[3] = {{bold = true}, {bold = true}},
[4] = {{fg_indexed = true, foreground = tonumber('0xe0e000')}, {foreground = 3}},
[5] = {{foreground = tonumber('0xff8000')}, {}},
})
feed_data(':set statusline=^^^^^^^\n')
feed_data(':set termguicolors\n')
feed_data(':terminal '..nvim_dir..'/tty-test\n')
-- Depending on platform the above might or might not fit in the cmdline
-- so clear it for consistent behavior.
feed_data(':\027')
screen:expect{grid=[[
{1:t}ty ready |
|
|
|
{2:^^^^^^^ }|
|
{3:-- TERMINAL --} |
]]}
feed_data(':call chansend(&channel, "\\033[38;5;3mtext\\033[38:2:255:128:0mcolor\\033[0;10mtext")\n')
screen:expect{grid=[[
{1:t}ty ready |
{4:text}{5:color}text |
|
|
{2:^^^^^^^ }|
|
{3:-- TERMINAL --} |
]]}
feed_data(':set notermguicolors\n')
screen:expect{grid=[[
{1:t}ty ready |
{4:text}colortext |
|
|
{2:^^^^^^^ }|
:set notermguicolors |
{3:-- TERMINAL --} |
]]}
end)
it('is included in nvim_list_uis()', function()
feed_data(':echo map(nvim_list_uis(), {k,v -> sort(items(filter(v, {k,v -> k[:3] !=# "ext_" })))})\r')
screen:expect([=[
|
{4:~ }|
{5: }|
[[['chan', 0], ['height', 6], ['override', v:false|
], ['rgb', v:false], ['width', 50]]] |
{10:Press ENTER or type command to continue}{1: } |
{3:-- TERMINAL --} |
]=])
end)
end)
describe('TUI', function()
before_each(clear)
after_each(function()
os.remove('testF')
end)
it('with non-tty (pipe) stdout/stderr', function()
local screen = thelpers.screen_setup(0, '"'..nvim_prog
..' -u NONE -i NONE --cmd \'set noswapfile noshowcmd noruler\' --cmd \'normal iabc\' > /dev/null 2>&1 && cat testF && rm testF"')
feed_data(':w testF\n:q\n')
screen:expect([[
:w testF |
:q |
abc |
|
[Process exited 0]{1: } |
|
{3:-- TERMINAL --} |
]])
end)
it('<C-h> #10134', function()
local screen = thelpers.screen_setup(0, '["'..nvim_prog
..[[", "-u", "NONE", "-i", "NONE", "--cmd", "set noruler", "--cmd", ':nnoremap <C-h> :echomsg "\<C-h\>"<CR>']]..']')
command([[call chansend(b:terminal_job_id, "\<C-h>")]])
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
<C-h> |
{3:-- TERMINAL --} |
]])
end)
end)
describe('TUI UIEnter/UILeave', function()
it('fires exactly once, after VimEnter', function()
clear()
local screen = thelpers.screen_setup(0,
'["'..nvim_prog..'", "-u", "NONE", "-i", "NONE"'
..[[, "--cmd", "set noswapfile noshowcmd noruler"]]
..[[, "--cmd", "let g:evs = []"]]
..[[, "--cmd", "autocmd UIEnter * :call add(g:evs, 'UIEnter')"]]
..[[, "--cmd", "autocmd UILeave * :call add(g:evs, 'UILeave')"]]
..[[, "--cmd", "autocmd VimEnter * :call add(g:evs, 'VimEnter')"]]
..']'
)
feed_data(":echo g:evs\n")
screen:expect{grid=[[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
['VimEnter', 'UIEnter'] |
{3:-- TERMINAL --} |
]]}
end)
end)
describe('TUI FocusGained/FocusLost', function()
local screen
before_each(function()
clear()
screen = thelpers.screen_setup(0, '["'..nvim_prog
..'", "-u", "NONE", "-i", "NONE", "--cmd", "set noswapfile noshowcmd noruler"]')
feed_data(":autocmd FocusGained * echo 'gained'\n")
feed_data(":autocmd FocusLost * echo 'lost'\n")
feed_data("\034\016") -- CTRL-\ CTRL-N
end)
it('in normal-mode', function()
retry(2, 3 * screen.timeout, function()
feed_data('\027[I')
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
gained |
{3:-- TERMINAL --} |
]])
feed_data('\027[O')
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
lost |
{3:-- TERMINAL --} |
]])
end)
end)
it('in insert-mode', function()
feed_command('set noshowmode')
feed_data('i')
retry(2, 3 * screen.timeout, function()
feed_data('\027[I')
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
gained |
{3:-- TERMINAL --} |
]])
feed_data('\027[O')
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
lost |
{3:-- TERMINAL --} |
]])
end)
end)
-- During cmdline-mode we ignore :echo invoked by timers/events.
-- See commit: 5cc87d4dabd02167117be7a978b5c8faaa975419.
it('in cmdline-mode does NOT :echo', function()
feed_data(':')
feed_data('\027[I')
screen:expect([[
|
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
:{1: } |
{3:-- TERMINAL --} |
]])
feed_data('\027[O')
screen:expect{grid=[[
|
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] }|
:{1: } |
{3:-- TERMINAL --} |
]], unchanged=true}
end)
it('in cmdline-mode', function()
-- Set up autocmds that modify the buffer, instead of just calling :echo.
-- This is how we can test handling of focus gained/lost during cmdline-mode.
-- See commit: 5cc87d4dabd02167117be7a978b5c8faaa975419.
feed_data(":autocmd!\n")
feed_data(":autocmd FocusLost * call append(line('$'), 'lost')\n")
feed_data(":autocmd FocusGained * call append(line('$'), 'gained')\n")
retry(2, 3 * screen.timeout, function()
-- Enter cmdline-mode.
feed_data(':')
screen:sleep(1)
-- Send focus lost/gained termcodes.
feed_data('\027[O')
feed_data('\027[I')
screen:sleep(1)
-- Exit cmdline-mode. Redraws from timers/events are blocked during
-- cmdline-mode, so the buffer won't be updated until we exit cmdline-mode.
feed_data('\n')
screen:expect{any='lost'..(' '):rep(46)..'|\ngained'}
end)
end)
it('in terminal-mode', function()
feed_data(':set shell='..nvim_dir..'/shell-test\n')
feed_data(':set noshowmode laststatus=0\n')
feed_data(':terminal\n')
-- Wait for terminal to be ready.
screen:expect{grid=[[
{1:r}eady $ |
[Process exited 0] |
|
|
|
:terminal |
{3:-- TERMINAL --} |
]]}
feed_data('\027[I')
screen:expect{grid=[[
{1:r}eady $ |
[Process exited 0] |
|
|
|
gained |
{3:-- TERMINAL --} |
]], timeout=(4 * screen.timeout)}
feed_data('\027[O')
screen:expect([[
{1:r}eady $ |
[Process exited 0] |
|
|
|
lost |
{3:-- TERMINAL --} |
]])
end)
it('in press-enter prompt', function()
feed_data(":echom 'msg1'|echom 'msg2'|echom 'msg3'|echom 'msg4'|echom 'msg5'\n")
-- Execute :messages to provoke the press-enter prompt.
feed_data(":messages\n")
feed_data('\027[I')
feed_data('\027[I')
screen:expect([[
msg1 |
msg2 |
msg3 |
msg4 |
msg5 |
{10:Press ENTER or type command to continue}{1: } |
{3:-- TERMINAL --} |
]])
end)
end)
-- These tests require `thelpers` because --headless/--embed
-- does not initialize the TUI.
describe("TUI 't_Co' (terminal colors)", function()
local screen
local is_freebsd = (uname() == 'freebsd')
local function assert_term_colors(term, colorterm, maxcolors)
helpers.clear({env={TERM=term}, args={}})
-- This is ugly because :term/termopen() forces TERM=xterm-256color.
-- TODO: Revisit this after jobstart/termopen accept `env` dict.
screen = thelpers.screen_setup(0, string.format(
[=[['sh', '-c', 'LANG=C TERM=%s %s %s -u NONE -i NONE --cmd "%s"']]=],
term or "",
(colorterm ~= nil and "COLORTERM="..colorterm or ""),
nvim_prog,
nvim_set))
local tline
if maxcolors == 8 or maxcolors == 16 then
tline = "~ "
else
tline = "{4:~ }"
end
screen:expect(string.format([[
{1: } |
%s|
%s|
%s|
%s|
|
{3:-- TERMINAL --} |
]], tline, tline, tline, tline))
feed_data(":echo &t_Co\n")
screen:expect(string.format([[
{1: } |
%s|
%s|
%s|
%s|
%-3s |
{3:-- TERMINAL --} |
]], tline, tline, tline, tline, tostring(maxcolors and maxcolors or "")))
end
-- ansi and no terminal type at all:
it("no TERM uses 8 colors", function()
assert_term_colors(nil, nil, 8)
end)
it("TERM=ansi no COLORTERM uses 8 colors", function()
assert_term_colors("ansi", nil, 8)
end)
it("TERM=ansi with COLORTERM=anything-no-number uses 16 colors", function()
assert_term_colors("ansi", "yet-another-term", 16)
end)
it("unknown TERM COLORTERM with 256 in name uses 256 colors", function()
assert_term_colors("ansi", "yet-another-term-256color", 256)
end)
it("TERM=ansi-256color sets 256 colours", function()
assert_term_colors("ansi-256color", nil, 256)
end)
-- Unknown terminal types:
it("unknown TERM no COLORTERM sets 8 colours", function()
assert_term_colors("yet-another-term", nil, 8)
end)
it("unknown TERM with COLORTERM=anything-no-number uses 16 colors", function()
assert_term_colors("yet-another-term", "yet-another-term", 16)
end)
it("unknown TERM with 256 in name sets 256 colours", function()
assert_term_colors("yet-another-term-256color", nil, 256)
end)
it("unknown TERM COLORTERM with 256 in name uses 256 colors", function()
assert_term_colors("yet-another-term", "yet-another-term-256color", 256)
end)
-- Linux kernel terminal emulator:
it("TERM=linux uses 256 colors", function()
assert_term_colors("linux", nil, 256)
end)
it("TERM=linux-16color uses 256 colors", function()
assert_term_colors("linux-16color", nil, 256)
end)
it("TERM=linux-256color uses 256 colors", function()
assert_term_colors("linux-256color", nil, 256)
end)
-- screen:
--
-- FreeBSD falls back to the built-in screen-256colour entry.
-- Linux and MacOS have a screen entry in external terminfo with 8 colours,
-- which is raised to 16 by COLORTERM.
it("TERM=screen no COLORTERM uses 8/256 colors", function()
if is_freebsd then
assert_term_colors("screen", nil, 256)
else
assert_term_colors("screen", nil, 8)
end
end)
it("TERM=screen COLORTERM=screen uses 16/256 colors", function()
if is_freebsd then
assert_term_colors("screen", "screen", 256)
else
assert_term_colors("screen", "screen", 16)
end
end)
it("TERM=screen COLORTERM=screen-256color uses 256 colors", function()
assert_term_colors("screen", "screen-256color", 256)
end)
it("TERM=screen-256color no COLORTERM uses 256 colors", function()
assert_term_colors("screen-256color", nil, 256)
end)
-- tmux:
--
-- FreeBSD and MacOS fall back to the built-in tmux-256colour entry.
-- Linux has a tmux entry in external terminfo with 8 colours,
-- which is raised to 256.
it("TERM=tmux no COLORTERM uses 256 colors", function()
assert_term_colors("tmux", nil, 256)
end)
it("TERM=tmux COLORTERM=tmux uses 256 colors", function()
assert_term_colors("tmux", "tmux", 256)
end)
it("TERM=tmux COLORTERM=tmux-256color uses 256 colors", function()
assert_term_colors("tmux", "tmux-256color", 256)
end)
it("TERM=tmux-256color no COLORTERM uses 256 colors", function()
assert_term_colors("tmux-256color", nil, 256)
end)
-- xterm and imitators:
it("TERM=xterm uses 256 colors", function()
assert_term_colors("xterm", nil, 256)
end)
it("TERM=xterm COLORTERM=gnome-terminal uses 256 colors", function()
assert_term_colors("xterm", "gnome-terminal", 256)
end)
it("TERM=xterm COLORTERM=mate-terminal uses 256 colors", function()
assert_term_colors("xterm", "mate-terminal", 256)
end)
it("TERM=xterm-256color uses 256 colors", function()
assert_term_colors("xterm-256color", nil, 256)
end)
-- rxvt and stterm:
--
-- FreeBSD and MacOS fall back to the built-in rxvt-256color and
-- st-256colour entries.
-- Linux has an rxvt, an st, and an st-16color entry in external terminfo
-- with 8, 8, and 16 colours respectively, which are raised to 256.
it("TERM=rxvt no COLORTERM uses 256 colors", function()
assert_term_colors("rxvt", nil, 256)
end)
it("TERM=rxvt COLORTERM=rxvt uses 256 colors", function()
assert_term_colors("rxvt", "rxvt", 256)
end)
it("TERM=rxvt-256color uses 256 colors", function()
assert_term_colors("rxvt-256color", nil, 256)
end)
it("TERM=st no COLORTERM uses 256 colors", function()
assert_term_colors("st", nil, 256)
end)
it("TERM=st COLORTERM=st uses 256 colors", function()
assert_term_colors("st", "st", 256)
end)
it("TERM=st COLORTERM=st-256color uses 256 colors", function()
assert_term_colors("st", "st-256color", 256)
end)
it("TERM=st-16color no COLORTERM uses 8/256 colors", function()
assert_term_colors("st", nil, 256)
end)
it("TERM=st-16color COLORTERM=st uses 16/256 colors", function()
assert_term_colors("st", "st", 256)
end)
it("TERM=st-16color COLORTERM=st-256color uses 256 colors", function()
assert_term_colors("st", "st-256color", 256)
end)
it("TERM=st-256color uses 256 colors", function()
assert_term_colors("st-256color", nil, 256)
end)
-- gnome and vte:
--
-- FreeBSD and MacOS fall back to the built-in vte-256color entry.
-- Linux has a gnome, a vte, a gnome-256color, and a vte-256color entry in
-- external terminfo with 8, 8, 256, and 256 colours respectively, which are
-- raised to 256.
it("TERM=gnome no COLORTERM uses 256 colors", function()
assert_term_colors("gnome", nil, 256)
end)
it("TERM=gnome COLORTERM=gnome uses 256 colors", function()
assert_term_colors("gnome", "gnome", 256)
end)
it("TERM=gnome COLORTERM=gnome-256color uses 256 colors", function()
assert_term_colors("gnome", "gnome-256color", 256)
end)
it("TERM=gnome-256color uses 256 colors", function()
assert_term_colors("gnome-256color", nil, 256)
end)
it("TERM=vte no COLORTERM uses 256 colors", function()
assert_term_colors("vte", nil, 256)
end)
it("TERM=vte COLORTERM=vte uses 256 colors", function()
assert_term_colors("vte", "vte", 256)
end)
it("TERM=vte COLORTERM=vte-256color uses 256 colors", function()
assert_term_colors("vte", "vte-256color", 256)
end)
it("TERM=vte-256color uses 256 colors", function()
assert_term_colors("vte-256color", nil, 256)
end)
-- others:
-- TODO(blueyed): this is made pending, since it causes failure + later hang
-- when using non-compatible libvterm (#9494/#10179).
pending("TERM=interix uses 8 colors", function()
assert_term_colors("interix", nil, 8)
end)
it("TERM=iTerm.app uses 256 colors", function()
assert_term_colors("iTerm.app", nil, 256)
end)
it("TERM=iterm uses 256 colors", function()
assert_term_colors("iterm", nil, 256)
end)
end)
-- These tests require `thelpers` because --headless/--embed
-- does not initialize the TUI.
describe("TUI 'term' option", function()
local screen
local is_bsd = not not string.find(uname(), 'bsd')
local is_macos = not not string.find(uname(), 'darwin')
local function assert_term(term_envvar, term_expected)
clear()
-- This is ugly because :term/termopen() forces TERM=xterm-256color.
-- TODO: Revisit this after jobstart/termopen accept `env` dict.
local cmd = string.format(
[=[['sh', '-c', 'LANG=C TERM=%s %s -u NONE -i NONE --cmd "%s"']]=],
term_envvar or "",
nvim_prog,
nvim_set)
screen = thelpers.screen_setup(0, cmd)
local full_timeout = screen.timeout
screen.timeout = 250 -- We want screen:expect() to fail quickly.
retry(nil, 2 * full_timeout, function() -- Wait for TUI thread to set 'term'.
feed_data(":echo 'term='.(&term)\n")
screen:expect{any='term='..term_expected}
end)
end
it('gets builtin term if $TERM is invalid', function()
assert_term("foo", "builtin_ansi")
end)
it('gets system-provided term if $TERM is valid', function()
if uname() == "openbsd" then
assert_term("xterm", "xterm")
elseif is_bsd then -- BSD lacks terminfo, builtin is always used.
assert_term("xterm", "builtin_xterm")
elseif is_macos then
local status, _ = pcall(assert_term, "xterm", "xterm")
if not status then
pending("macOS: unibilium could not find terminfo")
end
else
assert_term("xterm", "xterm")
end
end)
it('builtin terms', function()
-- These non-standard terminfos are always builtin.
assert_term('win32con', 'builtin_win32con')
assert_term('conemu', 'builtin_conemu')
assert_term('vtpcon', 'builtin_vtpcon')
end)
end)
-- These tests require `thelpers` because --headless/--embed
-- does not initialize the TUI.
describe("TUI", function()
local screen
local logfile = 'Xtest_tui_verbose_log'
after_each(function()
os.remove(logfile)
end)
-- Runs (child) `nvim` in a TTY (:terminal), to start the builtin TUI.
local function nvim_tui(extra_args)
clear()
-- This is ugly because :term/termopen() forces TERM=xterm-256color.
-- TODO: Revisit this after jobstart/termopen accept `env` dict.
local cmd = string.format(
[=[['sh', '-c', 'LANG=C %s -u NONE -i NONE %s --cmd "%s"']]=],
nvim_prog,
extra_args or "",
nvim_set)
screen = thelpers.screen_setup(0, cmd)
end
it('-V3log logs terminfo values', function()
nvim_tui('-V3'..logfile)
-- Wait for TUI to start.
feed_data('Gitext')
screen:expect([[
text{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{4:~ }|
{3:-- INSERT --} |
{3:-- TERMINAL --} |
]])
retry(nil, 3000, function() -- Wait for log file to be flushed.
local log = read_file('Xtest_tui_verbose_log') or ''
eq('--- Terminal info --- {{{\n', string.match(log, '%-%-%- Terminal.-\n'))
ok(#log > 50)
end)
end)
end)
describe('TUI bg color', function()
local screen
local function setup()
-- Only single integration test.
-- See test/unit/tui_spec.lua for unit tests.
clear()
screen = thelpers.screen_setup(0, '["'..nvim_prog
..'", "-u", "NONE", "-i", "NONE", "--cmd", "set noswapfile", '
..'"-c", "autocmd OptionSet background echo \\"did OptionSet, yay!\\""]')
end
before_each(setup)
it('triggers OptionSet event on unsplit terminal-response', function()
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] 0,0-1 All}|
|
{3:-- TERMINAL --} |
]])
feed_data('\027]11;rgb:ffff/ffff/ffff\007')
screen:expect{any='did OptionSet, yay!'}
feed_data(':echo "new_bg=".&background\n')
screen:expect{any='new_bg=light'}
setup()
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] 0,0-1 All}|
|
{3:-- TERMINAL --} |
]])
feed_data('\027]11;rgba:ffff/ffff/ffff/8000\027\\')
screen:expect{any='did OptionSet, yay!'}
feed_data(':echo "new_bg=".&background\n')
screen:expect{any='new_bg=light'}
end)
it('triggers OptionSet event with split terminal-response', function()
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] 0,0-1 All}|
|
{3:-- TERMINAL --} |
]])
-- Send a background response with the OSC command part split.
feed_data('\027]11;rgb')
feed_data(':ffff/ffff/ffff\027\\')
screen:expect{any='did OptionSet, yay!'}
feed_data(':echo "new_bg=".&background\n')
screen:expect{any='new_bg=light'}
setup()
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] 0,0-1 All}|
|
{3:-- TERMINAL --} |
]])
-- Send a background response with the Pt portion split.
feed_data('\027]11;rgba:ffff/fff')
feed_data('f/ffff/8000\007')
screen:expect{any='did OptionSet, yay!'}
feed_data(':echo "new_bg=".&background\n')
screen:expect{any='new_bg=light'}
end)
it('not triggers OptionSet event with invalid terminal-response', function()
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] 0,0-1 All}|
|
{3:-- TERMINAL --} |
]])
feed_data('\027]11;rgb:ffff/ffff/ffff/8000\027\\')
screen:expect_unchanged()
feed_data(':echo "new_bg=".&background\n')
screen:expect{any='new_bg=dark'}
setup()
screen:expect([[
{1: } |
{4:~ }|
{4:~ }|
{4:~ }|
{5:[No Name] 0,0-1 All}|
|
{3:-- TERMINAL --} |
]])
feed_data('\027]11;rgba:ffff/foo/ffff/8000\007')
screen:expect_unchanged()
feed_data(':echo "new_bg=".&background\n')
screen:expect{any='new_bg=dark'}
end)
end)
|
vim.g.everforest_better_performance = 1
vim.g.everforest_background = 'hard'
vim.g.everforest_enable_italic = 1
vim.cmd [[
try
colorscheme everforest
catch /^Vim\%((\a\+)\)\=:E185/
colorscheme default
set background=dark
endtry
]]
|
local xx = 510;
local yy = 450;
local xx1 = 810;
local yy1 = 450;
local ofs = 60;
local followchars = true;
local del = 0;
local del1 = 0;
function onUpdate()
if del > 0 then
del = del - 1
end
if del1 > 0 then
del1 = del1 - 1
end
if followchars == true then
if mustHitSection == false then
if getProperty('dad.animation.curAnim.name') == 'singLEFT' then
triggerEvent('Camera Follow Pos',xx-ofs,yy)
end
if getProperty('dad.animation.curAnim.name') == 'singRIGHT' then
triggerEvent('Camera Follow Pos',xx+ofs,yy)
end
if getProperty('dad.animation.curAnim.name') == 'singUP' then
triggerEvent('Camera Follow Pos',xx,yy-ofs)
end
if getProperty('dad.animation.curAnim.name') == 'singDOWN' then
triggerEvent('Camera Follow Pos',xx,yy+ofs)
end
if getProperty('dad.animation.curAnim.name') == 'singLEFT-alt' then
triggerEvent('Camera Follow Pos',xx-ofs,yy)
end
if getProperty('dad.animation.curAnim.name') == 'singRIGHT-alt' then
triggerEvent('Camera Follow Pos',xx+ofs,yy)
end
if getProperty('dad.animation.curAnim.name') == 'singUP-alt' then
triggerEvent('Camera Follow Pos',xx,yy-ofs)
end
if getProperty('dad.animation.curAnim.name') == 'singDOWN-alt' then
triggerEvent('Camera Follow Pos',xx,yy+ofs)
end
if getProperty('dad.animation.curAnim.name') == 'idle-alt' then
triggerEvent('Camera Follow Pos',xx,yy)
end
if getProperty('dad.animation.curAnim.name') == 'idle' then
triggerEvent('Camera Follow Pos',xx,yy)
end
else
if getProperty('boyfriend.animation.curAnim.name') == 'singLEFT' then
triggerEvent('Camera Follow Pos',xx1-ofs,yy1)
end
if getProperty('boyfriend.animation.curAnim.name') == 'singRIGHT' then
triggerEvent('Camera Follow Pos',xx1+ofs,yy1)
end
if getProperty('boyfriend.animation.curAnim.name') == 'singUP' then
triggerEvent('Camera Follow Pos',xx1,yy1-ofs)
end
if getProperty('boyfriend.animation.curAnim.name') == 'singDOWN' then
triggerEvent('Camera Follow Pos',xx1,yy1+ofs)
end
if getProperty('boyfriend.animation.curAnim.name') == 'idle' then
triggerEvent('Camera Follow Pos',xx1,yy1)
end
end
else
triggerEvent('Camera Follow Pos','','')
end
end |
local map = require("utils").map
vim.g.spotify_show_status = 1
vim.g.spotify_status_format = ' {status} {song} - {artists} {decorator}'
vim.g.spotify_wait_time = 0.5
map("n", [[\sn]], "<cmd>Spotify next<CR>")
map("n", [[\sp]], ":Spotify prev<CR>")
map("n", [[\ss]], ":Spotify play/pause<CR>")
map("n", [[\so]], ":Spotify show<CR>")
map("n", [[\sc]], ":Spotify status<CR>")
|
--
-- Created by IntelliJ IDEA.
-- User: jarlene
-- Date: 2018/2/24
-- Time: 下午6:22
-- To change this template use File | Settings | File Templates.
--
local User = {}
local returncode = require "conf.returncode"
local http = require "comm.http"
local function test()
local res = { code = returncode.SUCCESS.code, msg = returncode.SUCCESS.msg }
return res
end
local function ipsearch()
local ip = http.getParam("ip")
if not ip then
return returncode.BUSINESS.ParamError
end
local url = "/ipsearch?format=json&ip=" .. ip
local r = http.getCapture(url)
if not r or type(r) ~= 'table' or not r.ret or r.ret ~= 1 then
return returncode.BUSINESS.UriError
end
local result = {}
result.country = r.country
result.province = r.province
result.city = r.city
result.district = r.district
result.isp = r.isp
local res = { code = returncode.SUCCESS.code, msg = returncode.SUCCESS.msg, data = result }
return res
end
User.test = test
User.ipsearch = ipsearch
return User
|
ClassicLFGCheckBox= {}
ClassicLFGCheckBox.__index = ClassicLFGCheckBox
setmetatable(ClassicLFGCheckBox, {
__call = function (cls, ...)
return cls.new(...)
end,
})
function ClassicLFGCheckBox.new(text, parent, text)
local self = setmetatable({}, ClassicLFGCheckBox)
self.Frame = CreateFrame("Frame", nil, parent, nil)
self.Selected = false
self.Frame:SetBackdrop({
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", tile = true, tileSize = 8
})
self.Frame:SetBackdropColor(ClassicLFG.Config.PrimaryColor.Red,
ClassicLFG.Config.PrimaryColor.Green,
ClassicLFG.Config.PrimaryColor.Blue,
ClassicLFG.Config.PrimaryColor.Alpha)
self.Frame:SetBackdropBorderColor(1,1,1,1)
self.Frame.Thumb = self.Frame:CreateTexture(nil, "ARTWORK")
self.Frame.Thumb:SetTexture("Interface\\Button\\UI-Checkbox-Check")
self.Frame.Thumb:SetWidth(15)
self.Frame.Thumb:SetHeight(15)
self.Frame.Thumb:SetColorTexture(
ClassicLFG.Config.BackgroundColor.Red,
ClassicLFG.Config.BackgroundColor.Green,
ClassicLFG.Config.BackgroundColor.Blue,
ClassicLFG.Config.BackgroundColor.Alpha
)
self.Frame.Thumb:SetPoint("LEFT", self.Frame, "LEFT", 5, 0)
self.Frame.Title = self.Frame:CreateFontString(nil, "OVERLAY", "GameFontHighlight");
self.Frame.Title:SetFont(ClassicLFG.Config.Font, 12, "NONE");
self.Frame.Title:SetPoint("LEFT", self.Frame.Thumb, "RIGHT", 8, 0)
self.Frame.Title:SetText(text)
self.Frame:SetScript("OnEnter", function()
self.Frame.Thumb:SetColorTexture(
ClassicLFG.Config.SecondaryColor.Red,
ClassicLFG.Config.SecondaryColor.Green,
ClassicLFG.Config.SecondaryColor.Blue,
ClassicLFG.Config.SecondaryColor.Alpha
)
end)
self.Frame:SetScript("OnLeave", function()
if (self.Selected == true) then
self:Select()
else
self:Deselect()
end
end)
self.Frame:SetScript("OnMouseUp", function()
self:SetState(not self.Selected)
end)
self.Frame:SetScript("OnMouseDown", function()
PlaySound(SOUNDKIT.U_CHAT_SCROLL_BUTTON)
self:OnMouseDown()
end)
return self
end
function ClassicLFGCheckBox:SetState(selected)
self.Selected = selected
if (selected == true) then
self:Select()
else
self:Deselect()
end
self:OnValueChanged(self.Selected)
end
function ClassicLFGCheckBox:Select()
self.Frame.Thumb:SetColorTexture(
ClassicLFG.Config.PrimaryColor.Red,
ClassicLFG.Config.PrimaryColor.Green,
ClassicLFG.Config.PrimaryColor.Blue,
ClassicLFG.Config.PrimaryColor.Alpha
)
end
function ClassicLFGCheckBox:Deselect()
self.Frame.Thumb:SetColorTexture(
ClassicLFG.Config.BackgroundColor.Red,
ClassicLFG.Config.BackgroundColor.Green,
ClassicLFG.Config.BackgroundColor.Blue,
ClassicLFG.Config.BackgroundColor.Alpha
)
end
function ClassicLFGCheckBox:OnValueChanged(selected)
end
function ClassicLFGCheckBox:OnMouseDown()
end |
require "classes.constants.screen"
FacebookMessenger={}
function FacebookMessenger:new()
local this = {}
local public = this
local private={}
local facebook = require("plugin.facebook.v4")
local json = require("json")
local fbAppID = "XXXXXXXXXXXXXXX" -- Your FB App ID from facebook developer's panel
local userFB_ID
local nameFB
local descriptionFB
local fbCommand -- Facebook Commands
local SHOW_FEED_DIALOG = 2
local POST_MSG = 4
local GET_PHOTO = 8
local GET_FRIENDS = 9
local POST_SCORE = 10
local GET_USERSSCORE = 11
local postMessage = ""
local postScore = 6
local controller
local users
local currentAccessToken
local alreadyLogin = false
function private.FacebookMessenger()
end
function public.setResponseObjects(newController, newUsers)
controller = newController
users = newUsers
end
function public.login()
private.enforceFacebookLogin()
end
function public.logout()
facebook.logout()
end
function public.postMessage(newPostMessage)
postMessage = newPostMessage
private.postMsg_onRelease()
end
function public.inviteFriends()
private.showFeedDialog_onRelease()
end
function public.postScore(newPostScore)
postScore = newPostScore
private.postScore()
end
function public.getUsersScore()
private.getUsersScore()
end
function private.listener(event) -- New Facebook Connection listener
if event.type == "session" then
if event.phase ~= "login" then
return -- Exit if login error
else
currentAccessToken = event.token
alreadyLogin = true
end
elseif event.type == "request" then
local response = event.response -- event.response is a JSON object from the FB server
if not event.isError then
response = json.decode( event.response )
if fbCommand == POST_MSG then
elseif fbCommand == GET_PHOTO then
users[1].userName = ""..response.first_name.." "..response.last_name
users[1].points = hudModel.getScoreValue()
controller.showList(users)
local function fbNetworkImageDownload( event )
users[1].imgUser = "fbPic.png" --event.response.filename
controller.showList(users)
end
network.download(response.picture.data.url,
"GET",
fbNetworkImageDownload,
{},
"fbPic.png",
system.DocumentDirectory
)
elseif fbCommand == GET_FRIENDS then
for i=1, #response.data do
if users[i] then
users[i].userName = ""..response.data[i].name
users[i].points = hudModel.getScoreValue()
else
users[i]= {imgUser = "img/userdefault.png", userName = response.data[i].name, points = 23}
end
local function fbNetworkImageDownload( event )
users[i].imgUser = "fbPic"..response.data[i].id..".png" --event.response.filename
controller.showList(users)
end
network.download(response.data[i].picture.data.url,
"GET",
fbNetworkImageDownload,
{},
"fbPic"..response.data[i].id..".png",
system.DocumentDirectory
)
end
controller.showList(users)
elseif fbCommand == GET_USERSSCORE then
for i=1, #response.data do
if users[i] then
users[i].userName = ""..response.data[i].user.name
users[i].points = response.data[i].score
else
users[i]= {imgUser = "img/userdefault.png", userName = response.data[i].user.name, points = response.data[i].score}
end
local function fbNetworkImageDownload( event )
users[i].imgUser = "fbPic"..response.data[i].user.id..".png" --event.response.filename
controller.showList(users)
end
network.download(
"https://graph.facebook.com/"..response.data[i].user.id.."/picture",
"GET",
fbNetworkImageDownload,
{},
"fbPic"..response.data[i].user.id..".png",
system.DocumentDirectory
)
end
controller.showList(users)
elseif fbCommand == POST_SCORE then
--print("Post Score")
else
-- Unknown command response
end
else
-- Post Failed
end
elseif ( "dialog" == event.type ) then
-- showDialog response
--print( "dialog response:", event.response )
end
end
function private.processFBCommand(event) -- Runs the desired facebook command
if fbCommand == SHOW_FEED_DIALOG then -- The following displays a Facebook dialog box for posting to your Facebook Wall -- "feed" is the standard "post status message" dialog
facebook.showDialog("requests", {message = "You should download this game!", filter = "APP_NON_USERS"})
end
if fbCommand == POST_MSG then -- This code posts a message to your Facebook Wall
local faceMessage = {
name = "OOP Samples for Corona SDK",
link = "https://play.google.com/store/apps/details?id=com.gmail.lis.a.sebastian.oopsamplesforcoronasdk",
message = postMessage --"Got ".. hudModel.getScoreValue().." points how about you?",
--picture =pictureFB
}
local response = facebook.request( "me/feed", "POST", faceMessage )
end
if fbCommand == GET_PHOTO then -- This code gets a photo image from your Facebook Wall
facebook.request("me","GET",{fields="name,first_name, last_name, id, picture"})
end
if fbCommand == GET_USERSSCORE then -- This code gets a friends invited by you
local response = facebook.request("/"..fbAppID.."/scores","GET");
end
if fbCommand == POST_SCORE then
local params = {
score=tostring(postScore), --hudModel.getScoreValue()
access_token=currentAccessToken--accessToken--event.token
}
facebook.request("me/scores" , "POST", params)
end
if fbCommand == GET_FRIENDS then -- This code gets a friends invited by you
local response = facebook.request("/me/taggable_friends", "GET")
end
end
function private.enforceFacebookLogin()
if facebook.isActive then
local accessToken = facebook.getCurrentAccessToken()
if accessToken == nil then
facebook.login( private.listener ) --print( "Need to log in" )
elseif not private.inTable( accessToken.grantedPermissions, "publish_actions" ) then
facebook.login( private.listener, {"publish_actions"} ) --print( "Logged in, but need permissions" )
else
--print( "Already logged in with needed permissions" )
private.processFBCommand()
end
else
--print( "Please wait for facebook to finish initializing before checking the current access token" );
end
end
function private.inTable( table, item ) -- Check for an item inside the provided table -- Based on implementation at: https://www.omnimaga.org/other-computer-languages-help/(lua)-check-if-array-contains-given-value/
for k,v in pairs(table) do
if v == item then
return true
end
end
return false
end
function private.postMsg_onRelease(event)
fbCommand = POST_MSG
private.enforceFacebookLogin()
end
function private.showFeedDialog_onRelease(event)
fbCommand = SHOW_FEED_DIALOG
private.enforceFacebookLogin()
end
function private.getPhoto(event)
fbCommand = GET_PHOTO
private.enforceFacebookLogin()
end
function private.getFriends(event)
fbCommand = GET_FRIENDS
private.enforceFacebookLogin()
end
function private.getUsersScore(event)
fbCommand = GET_USERSSCORE
private.enforceFacebookLogin()
end
function private.postScore(event)
fbCommand = POST_SCORE
private.enforceFacebookLogin()
end
function public.alreadyLogin()
return alreadyLogin
end
private.FacebookMessenger()
return this
end
return FacebookMessenger
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('./base').HostInfo
local misc = require('./misc')
local Transform = require('stream').Transform
local json = require('json')
local async = require('async')
local path = require('path')
--------------------------------------------------------------------------------------------------------------------
local Reader = Transform:extend()
function Reader:initialize()
Transform.initialize(self, {objectMode = true})
self._pushed = false
end
local ApacheOutputReader = Reader:extend()
function ApacheOutputReader:_transform(line, cb)
if line:find('-D HTTPD_ROOT=') then
self:push({config_path = line:sub(17, line:len()-1)})
elseif line:find('Server version:') then
self:push({version = line:sub(17)})
elseif line:find('Server MPM:') then
self:push({mpm = line:sub(17)})
elseif line:find('-D SERVER_CONFIG_FILE=') then
self:push({config_file = line:sub(25, line:len()-1)})
elseif line:find('WARNING: Require MaxClients > 0, setting to') then
self:push({max_clients = line:sub(45):match('%d+')})
elseif line:find('Syntax OK') then
self:push({syntax_ok = true})
elseif line:find('Syntax error') then
local errs = line:match('%: (.+)')
self:push({
syntax_ok = false,
syntax_errors = errs
})
end
cb()
end
local VhostOutputReader = Reader:extend()
function VhostOutputReader:_transform(line, cb)
local dataTable = {}
if line:find('is a NameVirtualHost') then
self:push({current_vhost = line:match('%S+')})
elseif line:find('^(%s*)User:') then
self:push({user = line:match('%"(.*)%"')})
else
line:gsub("%S+", function(c) table.insert(dataTable, c) end)
-- does the line start with default?
if line:find('^(%s*)default(%s)') then
self:push({
vhost = dataTable[3],
conf = dataTable[4]:match('%((.*)%)') -- strip brackets
})
-- does the line start with port?
elseif line:find('^(%s*)port(%s)') then
line:gsub("%S+", function(c) table.insert(dataTable, c) end)
self:push({
vhost = dataTable[4],
port = dataTable[2],
conf = dataTable[5]:match('%((.*)%)') -- strip brackets
})
end
end
cb()
end
local VhostConfigReader = Reader:extend()
function VhostConfigReader:_transform(line, cb)
-- '%s+%S+%s+(%S+)' will get the second word in line
if line:find('^(%s*)DocumentRoot(%s)') then
self:push({docroot = line:match('%s+%S+%s+(%S+)')})
elseif line:find('^(%s*)ErrorLog(%s)') then
self:push({error_log = line:match('%s+%S+%s+(%S+)')})
elseif line:find('^(%s*)CustomLog(%s)') then
self:push({access_log = line:match('%s+%S+%s+(%S+)')})
end
cb()
end
local PerforkReader = Reader:extend()
function PerforkReader:_transform(line, cb)
if line:find('<IfModule') and line:find('prefork') then
-- We do this to check if we're inside the right block for the next block
self._pushed = true
end
if self._pushed and line:find('^(%s*)MaxClients') then
self:push({max_clients = line:match('%s+%S+%s+(%S+)')})
end
cb()
end
local RamPerPreforkChildReader = Reader:extend()
-- 'mapped: 121504K writeable/private: 2228K shared: 4K' -> 2.175
-- Ohai gives you ram in mb, though it isnt specified in the output, well do the same
function RamPerPreforkChildReader:_transform(line, cb)
local dataTable = {}
line:gsub("%S+", function(c) table.insert(dataTable, c) end)
self:push(dataTable[4]:match('%d+')/1024) -- Strip K at the end for kilobytes and convert to mb
cb()
end
--------------------------------------------------------------------------------------------------------------------
--[[ Packages ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:_run(callback)
local errTable, outTable = {}, {}
local deb = {apacheCmd = '/usr/sbin/apache2ctl', apacheArgs = {'-V'},
vhostCmd = '/usr/sbin/apache2ctl', vhostArgs = {'-S'}}
local rhel = {apacheCmd = '/usr/sbin/httpd', apacheArgs = {'-V'},
vhostCmd = '/usr/sbin/httpd', vhostArgs = {'-S'}}
local options = {
ubuntu = deb,
debian = deb,
rhel = rhel,
centos = rhel,
default = nil
}
local spawnConfig = misc.getInfoByVendor(options)
if not spawnConfig.apacheCmd then
self:_pushError(string.format("Couldn't decipher linux distro for check %s", self:getType()))
return callback()
end
local function finalCb()
self:_pushParams(errTable, outTable)
return callback()
end
local function streamToBuffer(stream, cb)
local outTable, errTable = {}, {}
stream:on('data', function(data)
if type(data) == 'table' then
misc.safeMerge(outTable, data)
else
table.insert(outTable, data)
end
end)
stream:on('error', function(err)
if type(err) == 'table' then
misc.safeMerge(errTable, err)
else
table.insert(errTable, err)
end
end)
stream:once('end', function() cb(outTable, errTable) end)
end
local function getApacheOutput(cmd, args, cb)
local apacheChild = misc.run(cmd, args, {})
local reader = ApacheOutputReader:new()
-- We want to capture both stderr and stdout and pass it through the same reader
apacheChild:on('data', function(data) reader:write(data) end)
apacheChild:on('error', function(err) reader:write(err) end)
apacheChild:once('end', function() reader:emit('end') end)
streamToBuffer(reader, cb)
end
local function getApacheClients(cmd, user, cb)
local cmd = string.format('ps -u %s -o cmd | grep -c %s', user, cmd)
local child = misc.run('sh', {'-c', cmd})
streamToBuffer(child, cb)
end
local function getVhostsConfig(file, line_number, cb)
local readStream = misc.read(file)
-- Catch no file found errors
readStream:on('error', function(err)
table.insert(errTable, err)
return cb()
end)
local reader = VhostConfigReader:new()
local iterCount = 1
readStream:on('data', function(data)
iterCount = iterCount + 1
if iterCount >= tonumber(line_number) then
reader:write(data)
end
end)
readStream:once('end', function()
reader:emit('end')
end)
streamToBuffer(reader, cb)
end
local function getVhostsOutput(cmd, args, cb)
local outTable, errTable, current_vhost = {}, {}, ''
local child = misc.run(cmd, args)
local reader = VhostOutputReader:new()
local waitCount = 1 -- we wish to wait for the end of the reader stream
local function await()
waitCount = waitCount - 1
if waitCount == 0 then cb(outTable, errTable) end
end
child:pipe(reader)
reader:on('data', function(data)
-- Handleline: *:80 is a NameVirtualHost
if data.current_vhost then
current_vhost = data.current_vhost
outTable.vhosts = {}
outTable.vhosts[current_vhost] = {}
end
if data.user then misc.safeMerge(outTable, data) end
if data.conf then
local file, lineNum = data.conf:match("(.+)%:(.+)")
if not data.port then
-- Handleline: default server 2001:4800:7812:514:be76:4eff:fe05:678d (/etc/apache2/sites-enabled/000-default.conf:1)
waitCount = waitCount + 1
getVhostsConfig(file, lineNum, function(out, err)
if err then table.insert(errTable, err) end
outTable.vhosts[current_vhost]['default'] = {
vhost = data.vhost,
conf = data.conf,
docroot = out['docroot'] or '',
accesslogs = out['access_logs'] or '',
errorlog = out['error_log'] or ''
}
await()
end)
else
-- Handleline: port 80 namevhost example.com (/etc/apache2/sites-enabled/example.com.conf:1)
waitCount = waitCount + 1
getVhostsConfig(file, lineNum, function(out, err)
if err then table.insert(errTable, err) end
outTable.vhosts[current_vhost][data.vhost] = {
vhost = data.vhost,
conf = data.conf,
port = data.port,
docroot = out['docroot'] or '',
accesslogs = out['access_log'] or '',
errorlog = out['error_log'] or ''
}
await()
end)
end
end
end)
reader:once('end', function() await() end)
end
local function getRamPerPreforkChild(user, cb)
local cmd = "ps -u " .. user .. " -o pid= | xargs pmap -d | awk '/private/'"
local stream = misc.run('sh', {'-c', cmd}, {})
local reader = RamPerPreforkChildReader:new()
stream:pipe(reader)
streamToBuffer(reader, function(out, err)
-- Get Average
local sum = 0
table.foreach(out, function(k, v)
sum = sum + v
end)
sum = sum / #out
cb(sum, err)
end)
end
outTable.bin = spawnConfig.apacheCmd
async.parallel({
function(cb)
getApacheOutput(spawnConfig.apacheCmd, spawnConfig.apacheArgs, function(out, err)
misc.safeMerge(outTable, out)
misc.safeMerge(errTable, err)
if not outTable.syntax_ok then outTable.syntax_ok = true end
cb()
end)
end,
function(cb)
getVhostsOutput(spawnConfig.vhostCmd, spawnConfig.vhostArgs, function(out, err)
misc.safeMerge(outTable, out)
misc.safeMerge(errTable, err)
getApacheClients(spawnConfig.apacheConfig, outTable.user, function(out, err)
outTable.cients = out and table.concat(out) or ''
misc.safeMerge(errTable, err)
cb()
end)
end)
end
}, function()
if outTable.config_file then
outTable.config_file = path.join(outTable.config_path, outTable.config_file)
end
if outTable.mpm == 'prefork' and outTable.user then
if #outTable.user ~= 0 then
getRamPerPreforkChild(outTable.user, function(out, err)
outTable.estimatedRAMperpreforkchild = type(out) == 'table' and json.stringify(out) or out
misc.safeMerge(errTable, err)
local readStream = misc.read(outTable.config_file)
readStream:on('error', function(err)
table.insert(errTable, err)
return finalCb()
end)
local reader = PerforkReader:new()
readStream:pipe(reader)
streamToBuffer(reader, function(out, err)
misc.safeMerge(errTable, err)
if out.max_clients then outTable.max_clients = out.max_clients end
return finalCb()
end)
end)
end
end
return finalCb()
end)
end
function Info:getPlatforms()
return {'linux', 'darwin'}
end
function Info:getType()
return 'APACHE2'
end
exports.Info = Info
exports.ApacheOutputReader = ApacheOutputReader
exports.VhostConfigReader = VhostConfigReader
exports.VhostOutputReader = VhostOutputReader
exports.RamPerPreforkChildReader = RamPerPreforkChildReader
exports.PerforkReader = PerforkReader -- untested
|
-- Fp Integer Arithmetic
local unpack = table.unpack
local n = 0xffff
local m = 0x10000
local p = {3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65533}
local p2 = {21845, 21845, 21845, 21845, 21845, 21845, 21845, 21845, 21845, 21845, 21845, 43690}
local r2 = {44014, 58358, 19452, 6484, 45852, 58974, 63348, 64806, 65292, 65454, 65508, 21512}
local function eq(a, b)
for i = 1, 12 do
if a[i] ~= b[i] then
return false
end
end
return true
end
local function reduce(a)
local r1 = a[1]
local r2 = a[2]
local r3 = a[3]
local r4 = a[4]
local r5 = a[5]
local r6 = a[6]
local r7 = a[7]
local r8 = a[8]
local r9 = a[9]
local r10 = a[10]
local r11 = a[11]
local r12 = a[12]
if r12 < 65533 or r12 == 65533 and r1 < 3 then
return {unpack(a)}
end
r1 = r1 - 3
r12 = r12 - 65533
if r1 < 0 then
r2 = r2 - 1
r1 = r1 + m
end
if r2 < 0 then
r3 = r3 - 1
r2 = r2 + m
end
if r3 < 0 then
r4 = r4 - 1
r3 = r3 + m
end
if r4 < 0 then
r5 = r5 - 1
r4 = r4 + m
end
if r5 < 0 then
r6 = r6 - 1
r5 = r5 + m
end
if r6 < 0 then
r7 = r7 - 1
r6 = r6 + m
end
if r7 < 0 then
r8 = r8 - 1
r7 = r7 + m
end
if r8 < 0 then
r9 = r9 - 1
r8 = r8 + m
end
if r9 < 0 then
r10 = r10 - 1
r9 = r9 + m
end
if r10 < 0 then
r11 = r11 - 1
r10 = r10 + m
end
if r11 < 0 then
r12 = r12 - 1
r11 = r11 + m
end
return {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12}
end
local function add(a, b)
local r1 = a[1] + b[1]
local r2 = a[2] + b[2]
local r3 = a[3] + b[3]
local r4 = a[4] + b[4]
local r5 = a[5] + b[5]
local r6 = a[6] + b[6]
local r7 = a[7] + b[7]
local r8 = a[8] + b[8]
local r9 = a[9] + b[9]
local r10 = a[10] + b[10]
local r11 = a[11] + b[11]
local r12 = a[12] + b[12]
if r1 > n then
r2 = r2 + 1
r1 = r1 - m
end
if r2 > n then
r3 = r3 + 1
r2 = r2 - m
end
if r3 > n then
r4 = r4 + 1
r3 = r3 - m
end
if r4 > n then
r5 = r5 + 1
r4 = r4 - m
end
if r5 > n then
r6 = r6 + 1
r5 = r5 - m
end
if r6 > n then
r7 = r7 + 1
r6 = r6 - m
end
if r7 > n then
r8 = r8 + 1
r7 = r7 - m
end
if r8 > n then
r9 = r9 + 1
r8 = r8 - m
end
if r9 > n then
r10 = r10 + 1
r9 = r9 - m
end
if r10 > n then
r11 = r11 + 1
r10 = r10 - m
end
if r11 > n then
r12 = r12 + 1
r11 = r11 - m
end
local result = {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12}
return reduce(result)
end
local function shr(a)
local r1 = a[1]
local r2 = a[2]
local r3 = a[3]
local r4 = a[4]
local r5 = a[5]
local r6 = a[6]
local r7 = a[7]
local r8 = a[8]
local r9 = a[9]
local r10 = a[10]
local r11 = a[11]
local r12 = a[12]
r1 = r1 / 2
r1 = r1 - r1 % 1
r1 = r1 + (r2 % 2) * 0x8000
r2 = r2 / 2
r2 = r2 - r2 % 1
r2 = r2 + (r3 % 2) * 0x8000
r3 = r3 / 2
r3 = r3 - r3 % 1
r3 = r3 + (r4 % 2) * 0x8000
r4 = r4 / 2
r4 = r4 - r4 % 1
r4 = r4 + (r5 % 2) * 0x8000
r5 = r5 / 2
r5 = r5 - r5 % 1
r5 = r5 + (r6 % 2) * 0x8000
r6 = r6 / 2
r6 = r6 - r6 % 1
r6 = r6 + (r7 % 2) * 0x8000
r7 = r7 / 2
r7 = r7 - r7 % 1
r7 = r7 + (r8 % 2) * 0x8000
r8 = r8 / 2
r8 = r8 - r8 % 1
r8 = r8 + (r9 % 2) * 0x8000
r9 = r9 / 2
r9 = r9 - r9 % 1
r9 = r9 + (r10 % 2) * 0x8000
r10 = r10 / 2
r10 = r10 - r10 % 1
r10 = r10 + (r11 % 2) * 0x8000
r11 = r11 / 2
r11 = r11 - r11 % 1
r11 = r11 + (r12 % 2) * 0x8000
r12 = r12 / 2
r12 = r12 - r12 % 1
local result = {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12}
return result
end
local function sub192(a, b)
local r1 = a[1] - b[1]
local r2 = a[2] - b[2]
local r3 = a[3] - b[3]
local r4 = a[4] - b[4]
local r5 = a[5] - b[5]
local r6 = a[6] - b[6]
local r7 = a[7] - b[7]
local r8 = a[8] - b[8]
local r9 = a[9] - b[9]
local r10 = a[10] - b[10]
local r11 = a[11] - b[11]
local r12 = a[12] - b[12]
if r1 < 0 then
r2 = r2 - 1
r1 = r1 + m
end
if r2 < 0 then
r3 = r3 - 1
r2 = r2 + m
end
if r3 < 0 then
r4 = r4 - 1
r3 = r3 + m
end
if r4 < 0 then
r5 = r5 - 1
r4 = r4 + m
end
if r5 < 0 then
r6 = r6 - 1
r5 = r5 + m
end
if r6 < 0 then
r7 = r7 - 1
r6 = r6 + m
end
if r7 < 0 then
r8 = r8 - 1
r7 = r7 + m
end
if r8 < 0 then
r9 = r9 - 1
r8 = r8 + m
end
if r9 < 0 then
r10 = r10 - 1
r9 = r9 + m
end
if r10 < 0 then
r11 = r11 - 1
r10 = r10 + m
end
if r11 < 0 then
r12 = r12 - 1
r11 = r11 + m
end
local result = {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12}
return result
end
local function sub(a, b)
local r1 = a[1] - b[1]
local r2 = a[2] - b[2]
local r3 = a[3] - b[3]
local r4 = a[4] - b[4]
local r5 = a[5] - b[5]
local r6 = a[6] - b[6]
local r7 = a[7] - b[7]
local r8 = a[8] - b[8]
local r9 = a[9] - b[9]
local r10 = a[10] - b[10]
local r11 = a[11] - b[11]
local r12 = a[12] - b[12]
if r1 < 0 then
r2 = r2 - 1
r1 = r1 + m
end
if r2 < 0 then
r3 = r3 - 1
r2 = r2 + m
end
if r3 < 0 then
r4 = r4 - 1
r3 = r3 + m
end
if r4 < 0 then
r5 = r5 - 1
r4 = r4 + m
end
if r5 < 0 then
r6 = r6 - 1
r5 = r5 + m
end
if r6 < 0 then
r7 = r7 - 1
r6 = r6 + m
end
if r7 < 0 then
r8 = r8 - 1
r7 = r7 + m
end
if r8 < 0 then
r9 = r9 - 1
r8 = r8 + m
end
if r9 < 0 then
r10 = r10 - 1
r9 = r9 + m
end
if r10 < 0 then
r11 = r11 - 1
r10 = r10 + m
end
if r11 < 0 then
r12 = r12 - 1
r11 = r11 + m
end
local result = {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12}
if r12 < 0 then
result = add(result, p)
end
return result
end
local function add384(a, b)
local r1 = a[1] + b[1]
local r2 = a[2] + b[2]
local r3 = a[3] + b[3]
local r4 = a[4] + b[4]
local r5 = a[5] + b[5]
local r6 = a[6] + b[6]
local r7 = a[7] + b[7]
local r8 = a[8] + b[8]
local r9 = a[9] + b[9]
local r10 = a[10] + b[10]
local r11 = a[11] + b[11]
local r12 = a[12] + b[12]
local r13 = a[13] + b[13]
local r14 = a[14] + b[14]
local r15 = a[15] + b[15]
local r16 = a[16] + b[16]
local r17 = a[17] + b[17]
local r18 = a[18] + b[18]
local r19 = a[19] + b[19]
local r20 = a[20] + b[20]
local r21 = a[21] + b[21]
local r22 = a[22] + b[22]
local r23 = a[23] + b[23]
local r24 = a[24] + b[24]
if r1 > n then
r2 = r2 + 1
r1 = r1 - m
end
if r2 > n then
r3 = r3 + 1
r2 = r2 - m
end
if r3 > n then
r4 = r4 + 1
r3 = r3 - m
end
if r4 > n then
r5 = r5 + 1
r4 = r4 - m
end
if r5 > n then
r6 = r6 + 1
r5 = r5 - m
end
if r6 > n then
r7 = r7 + 1
r6 = r6 - m
end
if r7 > n then
r8 = r8 + 1
r7 = r7 - m
end
if r8 > n then
r9 = r9 + 1
r8 = r8 - m
end
if r9 > n then
r10 = r10 + 1
r9 = r9 - m
end
if r10 > n then
r11 = r11 + 1
r10 = r10 - m
end
if r11 > n then
r12 = r12 + 1
r11 = r11 - m
end
if r12 > n then
r13 = r13 + 1
r12 = r12 - m
end
if r13 > n then
r14 = r14 + 1
r13 = r13 - m
end
if r14 > n then
r15 = r15 + 1
r14 = r14 - m
end
if r15 > n then
r16 = r16 + 1
r15 = r15 - m
end
if r16 > n then
r17 = r17 + 1
r16 = r16 - m
end
if r17 > n then
r18 = r18 + 1
r17 = r17 - m
end
if r18 > n then
r19 = r19 + 1
r18 = r18 - m
end
if r19 > n then
r20 = r20 + 1
r19 = r19 - m
end
if r20 > n then
r21 = r21 + 1
r20 = r20 - m
end
if r21 > n then
r22 = r22 + 1
r21 = r21 - m
end
if r22 > n then
r23 = r23 + 1
r22 = r22 - m
end
if r23 > n then
r24 = r24 + 1
r23 = r23 - m
end
local result = {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19, r20, r21, r22, r23, r24}
return result
end
local function mul384(a, b)
local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = unpack(a)
local b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12 = unpack(b)
local r1 = a1 * b1
local r2 = a1 * b2
r2 = r2 + a2 * b1
local r3 = a1 * b3
r3 = r3 + a2 * b2
r3 = r3 + a3 * b1
local r4 = a1 * b4
r4 = r4 + a2 * b3
r4 = r4 + a3 * b2
r4 = r4 + a4 * b1
local r5 = a1 * b5
r5 = r5 + a2 * b4
r5 = r5 + a3 * b3
r5 = r5 + a4 * b2
r5 = r5 + a5 * b1
local r6 = a1 * b6
r6 = r6 + a2 * b5
r6 = r6 + a3 * b4
r6 = r6 + a4 * b3
r6 = r6 + a5 * b2
r6 = r6 + a6 * b1
local r7 = a1 * b7
r7 = r7 + a2 * b6
r7 = r7 + a3 * b5
r7 = r7 + a4 * b4
r7 = r7 + a5 * b3
r7 = r7 + a6 * b2
r7 = r7 + a7 * b1
local r8 = a1 * b8
r8 = r8 + a2 * b7
r8 = r8 + a3 * b6
r8 = r8 + a4 * b5
r8 = r8 + a5 * b4
r8 = r8 + a6 * b3
r8 = r8 + a7 * b2
r8 = r8 + a8 * b1
local r9 = a1 * b9
r9 = r9 + a2 * b8
r9 = r9 + a3 * b7
r9 = r9 + a4 * b6
r9 = r9 + a5 * b5
r9 = r9 + a6 * b4
r9 = r9 + a7 * b3
r9 = r9 + a8 * b2
r9 = r9 + a9 * b1
local r10 = a1 * b10
r10 = r10 + a2 * b9
r10 = r10 + a3 * b8
r10 = r10 + a4 * b7
r10 = r10 + a5 * b6
r10 = r10 + a6 * b5
r10 = r10 + a7 * b4
r10 = r10 + a8 * b3
r10 = r10 + a9 * b2
r10 = r10 + a10 * b1
local r11 = a1 * b11
r11 = r11 + a2 * b10
r11 = r11 + a3 * b9
r11 = r11 + a4 * b8
r11 = r11 + a5 * b7
r11 = r11 + a6 * b6
r11 = r11 + a7 * b5
r11 = r11 + a8 * b4
r11 = r11 + a9 * b3
r11 = r11 + a10 * b2
r11 = r11 + a11 * b1
local r12 = a1 * b12
r12 = r12 + a2 * b11
r12 = r12 + a3 * b10
r12 = r12 + a4 * b9
r12 = r12 + a5 * b8
r12 = r12 + a6 * b7
r12 = r12 + a7 * b6
r12 = r12 + a8 * b5
r12 = r12 + a9 * b4
r12 = r12 + a10 * b3
r12 = r12 + a11 * b2
r12 = r12 + a12 * b1
local r13 = a2 * b12
r13 = r13 + a3 * b11
r13 = r13 + a4 * b10
r13 = r13 + a5 * b9
r13 = r13 + a6 * b8
r13 = r13 + a7 * b7
r13 = r13 + a8 * b6
r13 = r13 + a9 * b5
r13 = r13 + a10 * b4
r13 = r13 + a11 * b3
r13 = r13 + a12 * b2
local r14 = a3 * b12
r14 = r14 + a4 * b11
r14 = r14 + a5 * b10
r14 = r14 + a6 * b9
r14 = r14 + a7 * b8
r14 = r14 + a8 * b7
r14 = r14 + a9 * b6
r14 = r14 + a10 * b5
r14 = r14 + a11 * b4
r14 = r14 + a12 * b3
local r15 = a4 * b12
r15 = r15 + a5 * b11
r15 = r15 + a6 * b10
r15 = r15 + a7 * b9
r15 = r15 + a8 * b8
r15 = r15 + a9 * b7
r15 = r15 + a10 * b6
r15 = r15 + a11 * b5
r15 = r15 + a12 * b4
local r16 = a5 * b12
r16 = r16 + a6 * b11
r16 = r16 + a7 * b10
r16 = r16 + a8 * b9
r16 = r16 + a9 * b8
r16 = r16 + a10 * b7
r16 = r16 + a11 * b6
r16 = r16 + a12 * b5
local r17 = a6 * b12
r17 = r17 + a7 * b11
r17 = r17 + a8 * b10
r17 = r17 + a9 * b9
r17 = r17 + a10 * b8
r17 = r17 + a11 * b7
r17 = r17 + a12 * b6
local r18 = a7 * b12
r18 = r18 + a8 * b11
r18 = r18 + a9 * b10
r18 = r18 + a10 * b9
r18 = r18 + a11 * b8
r18 = r18 + a12 * b7
local r19 = a8 * b12
r19 = r19 + a9 * b11
r19 = r19 + a10 * b10
r19 = r19 + a11 * b9
r19 = r19 + a12 * b8
local r20 = a9 * b12
r20 = r20 + a10 * b11
r20 = r20 + a11 * b10
r20 = r20 + a12 * b9
local r21 = a10 * b12
r21 = r21 + a11 * b11
r21 = r21 + a12 * b10
local r22 = a11 * b12
r22 = r22 + a12 * b11
local r23 = a12 * b12
local r24 = 0
r2 = r2 + (r1 / m)
r2 = r2 - r2 % 1
r1 = r1 % m
r3 = r3 + (r2 / m)
r3 = r3 - r3 % 1
r2 = r2 % m
r4 = r4 + (r3 / m)
r4 = r4 - r4 % 1
r3 = r3 % m
r5 = r5 + (r4 / m)
r5 = r5 - r5 % 1
r4 = r4 % m
r6 = r6 + (r5 / m)
r6 = r6 - r6 % 1
r5 = r5 % m
r7 = r7 + (r6 / m)
r7 = r7 - r7 % 1
r6 = r6 % m
r8 = r8 + (r7 / m)
r8 = r8 - r8 % 1
r7 = r7 % m
r9 = r9 + (r8 / m)
r9 = r9 - r9 % 1
r8 = r8 % m
r10 = r10 + (r9 / m)
r10 = r10 - r10 % 1
r9 = r9 % m
r11 = r11 + (r10 / m)
r11 = r11 - r11 % 1
r10 = r10 % m
r12 = r12 + (r11 / m)
r12 = r12 - r12 % 1
r11 = r11 % m
r13 = r13 + (r12 / m)
r13 = r13 - r13 % 1
r12 = r12 % m
r14 = r14 + (r13 / m)
r14 = r14 - r14 % 1
r13 = r13 % m
r15 = r15 + (r14 / m)
r15 = r15 - r15 % 1
r14 = r14 % m
r16 = r16 + (r15 / m)
r16 = r16 - r16 % 1
r15 = r15 % m
r17 = r17 + (r16 / m)
r17 = r17 - r17 % 1
r16 = r16 % m
r18 = r18 + (r17 / m)
r18 = r18 - r18 % 1
r17 = r17 % m
r19 = r19 + (r18 / m)
r19 = r19 - r19 % 1
r18 = r18 % m
r20 = r20 + (r19 / m)
r20 = r20 - r20 % 1
r19 = r19 % m
r21 = r21 + (r20 / m)
r21 = r21 - r21 % 1
r20 = r20 % m
r22 = r22 + (r21 / m)
r22 = r22 - r22 % 1
r21 = r21 % m
r23 = r23 + (r22 / m)
r23 = r23 - r23 % 1
r22 = r22 % m
r24 = r24 + (r23 / m)
r24 = r24 - r24 % 1
r23 = r23 % m
local result = {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19, r20, r21, r22, r23, r24}
return result
end
local function REDC(T)
local m = {unpack(mul384({unpack(T, 1, 12)}, p2), 1, 12)}
local t = {unpack(add384(T, mul384(m, p)), 13, 24)}
return reduce(t)
end
local function mul(a, b)
return REDC(mul384(a, b))
end
local function sqr(a)
local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = unpack(a)
local r1 = a1 * a1
local r2 = a1 * a2 * 2
local r3 = a1 * a3 * 2
r3 = r3 + a2 * a2
local r4 = a1 * a4 * 2
r4 = r4 + a2 * a3 * 2
local r5 = a1 * a5 * 2
r5 = r5 + a2 * a4 * 2
r5 = r5 + a3 * a3
local r6 = a1 * a6 * 2
r6 = r6 + a2 * a5 * 2
r6 = r6 + a3 * a4 * 2
local r7 = a1 * a7 * 2
r7 = r7 + a2 * a6 * 2
r7 = r7 + a3 * a5 * 2
r7 = r7 + a4 * a4
local r8 = a1 * a8 * 2
r8 = r8 + a2 * a7 * 2
r8 = r8 + a3 * a6 * 2
r8 = r8 + a4 * a5 * 2
local r9 = a1 * a9 * 2
r9 = r9 + a2 * a8 * 2
r9 = r9 + a3 * a7 * 2
r9 = r9 + a4 * a6 * 2
r9 = r9 + a5 * a5
local r10 = a1 * a10 * 2
r10 = r10 + a2 * a9 * 2
r10 = r10 + a3 * a8 * 2
r10 = r10 + a4 * a7 * 2
r10 = r10 + a5 * a6 * 2
local r11 = a1 * a11 * 2
r11 = r11 + a2 * a10 * 2
r11 = r11 + a3 * a9 * 2
r11 = r11 + a4 * a8 * 2
r11 = r11 + a5 * a7 * 2
r11 = r11 + a6 * a6
local r12 = a1 * a12 * 2
r12 = r12 + a2 * a11 * 2
r12 = r12 + a3 * a10 * 2
r12 = r12 + a4 * a9 * 2
r12 = r12 + a5 * a8 * 2
r12 = r12 + a6 * a7 * 2
local r13 = a2 * a12 * 2
r13 = r13 + a3 * a11 * 2
r13 = r13 + a4 * a10 * 2
r13 = r13 + a5 * a9 * 2
r13 = r13 + a6 * a8 * 2
r13 = r13 + a7 * a7
local r14 = a3 * a12 * 2
r14 = r14 + a4 * a11 * 2
r14 = r14 + a5 * a10 * 2
r14 = r14 + a6 * a9 * 2
r14 = r14 + a7 * a8 * 2
local r15 = a4 * a12 * 2
r15 = r15 + a5 * a11 * 2
r15 = r15 + a6 * a10 * 2
r15 = r15 + a7 * a9 * 2
r15 = r15 + a8 * a8
local r16 = a5 * a12 * 2
r16 = r16 + a6 * a11 * 2
r16 = r16 + a7 * a10 * 2
r16 = r16 + a8 * a9 * 2
local r17 = a6 * a12 * 2
r17 = r17 + a7 * a11 * 2
r17 = r17 + a8 * a10 * 2
r17 = r17 + a9 * a9
local r18 = a7 * a12 * 2
r18 = r18 + a8 * a11 * 2
r18 = r18 + a9 * a10 * 2
local r19 = a8 * a12 * 2
r19 = r19 + a9 * a11 * 2
r19 = r19 + a10 * a10
local r20 = a9 * a12 * 2
r20 = r20 + a10 * a11 * 2
local r21 = a10 * a12 * 2
r21 = r21 + a11 * a11
local r22 = a11 * a12 * 2
local r23 = a12 * a12
local r24 = 0
r2 = r2 + (r1 / m)
r2 = r2 - r2 % 1
r1 = r1 % m
r3 = r3 + (r2 / m)
r3 = r3 - r3 % 1
r2 = r2 % m
r4 = r4 + (r3 / m)
r4 = r4 - r4 % 1
r3 = r3 % m
r5 = r5 + (r4 / m)
r5 = r5 - r5 % 1
r4 = r4 % m
r6 = r6 + (r5 / m)
r6 = r6 - r6 % 1
r5 = r5 % m
r7 = r7 + (r6 / m)
r7 = r7 - r7 % 1
r6 = r6 % m
r8 = r8 + (r7 / m)
r8 = r8 - r8 % 1
r7 = r7 % m
r9 = r9 + (r8 / m)
r9 = r9 - r9 % 1
r8 = r8 % m
r10 = r10 + (r9 / m)
r10 = r10 - r10 % 1
r9 = r9 % m
r11 = r11 + (r10 / m)
r11 = r11 - r11 % 1
r10 = r10 % m
r12 = r12 + (r11 / m)
r12 = r12 - r12 % 1
r11 = r11 % m
r13 = r13 + (r12 / m)
r13 = r13 - r13 % 1
r12 = r12 % m
r14 = r14 + (r13 / m)
r14 = r14 - r14 % 1
r13 = r13 % m
r15 = r15 + (r14 / m)
r15 = r15 - r15 % 1
r14 = r14 % m
r16 = r16 + (r15 / m)
r16 = r16 - r16 % 1
r15 = r15 % m
r17 = r17 + (r16 / m)
r17 = r17 - r17 % 1
r16 = r16 % m
r18 = r18 + (r17 / m)
r18 = r18 - r18 % 1
r17 = r17 % m
r19 = r19 + (r18 / m)
r19 = r19 - r19 % 1
r18 = r18 % m
r20 = r20 + (r19 / m)
r20 = r20 - r20 % 1
r19 = r19 % m
r21 = r21 + (r20 / m)
r21 = r21 - r21 % 1
r20 = r20 % m
r22 = r22 + (r21 / m)
r22 = r22 - r22 % 1
r21 = r21 % m
r23 = r23 + (r22 / m)
r23 = r23 - r23 % 1
r22 = r22 % m
r24 = r24 + (r23 / m)
r24 = r24 - r24 % 1
r23 = r23 % m
local result = {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19, r20, r21, r22, r23, r24}
return REDC(result)
end
local function mont(a)
return mul(a, r2)
end
local function invMont(a)
local a = {unpack(a)}
for i = 13, 24 do
a[i] = 0
end
return REDC(a)
end
return {
eq = eq,
add = add,
shr = shr,
sub192 = sub192,
sub = sub,
mul = mul,
sqr = sqr,
mont = mont,
invMont = invMont,
}
|
return {
["93ee8c86-b883-46f2-ad22-2c270376bd07"] = "hanxi",
}
|
-- got it from here
-- credits to ruilov
-- http://twolivesleft.com/Codify/Talk/discussion/20/my-first-app-pigs-in-clover
-- https://gist.github.com/1330422
if dofile ~= nil then
dofile ("loveCodify.lua")
end
backgroundC = color(0, 0, 0, 255)
time = 0
won = false
-- open is the angle of the openning. top is where the hole is (top or bottom)
circles = {
{ radius = 75, top = true },
{ radius = 150, top = false },
{ radius = 225, top = true },
--{ radius = 300, top = false },
}
balls = {
{ x = 300, y = 300, speedX = 0, speedY = 0, radius = 10 },
{ x = -300, y = -300, speedX = 0, speedY = 0, radius = 10 },
{ x = -300, y = 300, speedX = 0, speedY = 0, radius = 10 },
{ x = 300, y = -300, speedX = 0, speedY = 0, radius = 10 }
}
function setup()
watch("time")
end
-- This function gets called once every frame
function draw()
if not won then
-- check if won now
time = ElapsedTime
allBallsIn = true
for i,ball in ipairs(balls) do
if math.sqrt(ball.x^2+ball.y^2) > 75 then
allBallsIn = false
end
end
if allBallsIn then
print("YOU WON!")
won = true
end
end
ellipseMode(RADIUS)
pushMatrix()
translate(WIDTH/2, HEIGHT/2)
background(backgroundC)
drawWalls()
fill(70, 111, 75, 255)
stroke(168, 165, 165, 255)
strokeWidth(1)
collideStuff()
-- update ball speeds
for i,ball in ipairs(balls) do
if not ball.collided then
ball.speedX = ball.speedX + Gravity.x/2
ball.speedY = ball.speedY + Gravity.y/2
end
end
-- collide after updating speeds so for example we dont go through walls
collideStuff()
for i, ball in ipairs(balls) do
-- friction
ball.speedX = ball.speedX * .98
ball.speedY = ball.speedY * .98
--print(ball.speedY)
-- move and pain
ball.x = ball.x + ball.speedX
ball.y = ball.y + ball.speedY
ellipse(ball.x, ball.y, ball.radius, ball.radius)
end
-- hacks to make sure things dont cross boundaries
for i,ball in ipairs(balls) do
dc = math.sqrt(ball.x^2+ball.y^2)
for ci, circle in ipairs(circles) do
if dc > circle.radius-ball.radius+2
and dc < circle.radius+ball.radius-2 and math.abs(ball.x)>20 then
if ball.x > 0 then ball.x = 20
else ball.x = -20 end
end
end
end
popMatrix()
end
-- collides each ball with other balls, circles and outter walls.
-- roughly works but still bugs abound
function collideStuff()
nballs = table.maxn(balls)
for i = 1,nballs do
b = balls[i]
b.collided = false
newX = b.x + b.speedX
newY = b.y + b.speedY
-- collide with other balls
for j = i+1,nballs do
b2 = balls[j]
newX2 = b2.x + b2.speedX
newY2 = b2.y + b2.speedY
newD = math.sqrt((newX-newX2)^2 + (newY-newY2)^2)
if newD+1<b.radius+b2.radius then
-- b1 and b2 collide
b.speedX,b2.speedX = b2.speedX,b.speedX
b.speedY,b2.speedY = b2.speedY,b.speedY
newX = b.x + b.speedX
newY = b.y + b.speedY
b.collided = true
b2.collided = true
if math.sqrt(b.speedX^2+b.speedY^2) > 2 then
sound(SOUND_HIT, 5)
end
end
end
-- collide with outter walls
minX = -WIDTH/2+b.radius-2
maxX = -minX
if newX<minX or newX>maxX then
b.speedX = -b.speedX
b.collided = true
if math.sqrt(b.speedX^2+b.speedY^2) > 2 then
sound(SOUND_HIT,8)
end
end
minY = -HEIGHT/2+b.radius-2
maxY = -minY
if newY<minY or newY>maxY then
b.speedY = -b.speedY
b.collided = true
if math.sqrt(b.speedX^2+b.speedY^2) > 2 then
sound(SOUND_HIT,8)
end
end
-- collide with circles
for ci,circle in ipairs(circles) do
oldInside = b.x^2+b.y^2<circle.radius^2
if oldInside then
collision = newX^2+newY^2>(circle.radius-b.radius+2)^2
else
collision = newX^2+newY^2<(circle.radius+b.radius-2)^2
end
if collision then
-- this ball might be colliding with the circle , unless it's at the openning
if math.abs(b.x)>25-b.radius/2 or
not ( (circle.top and b.y>0) or ((not circle.top) and b.y<0) ) then
-- reflect the speed vector around the position vector
posv = vec2(b.x,b.y)
speedv = vec2(b.speedX,b.speedY)
speedvNew = reflect(speedv,posv)
if math.sqrt(b.speedX^2+b.speedY^2) > 2 then
sound(SOUND_HIT,8)
end
b.speedX = -speedvNew.x
b.speedY = -speedvNew.y
b.collided = true
end
end
end
end
end
-- reflects vec1 around vec2
function reflect(vec1, vec2)
-- (ans-vec1) dot vec2 = 0 and ans+vec1 = scalar * p
-- solve these equations
scalar = vec1:dot(vec2)*2 / vec2:dot(vec2)
answer = vec2 * scalar - vec1
return(answer)
end
function drawWalls()
noFill()
stroke(255, 255, 255, 255)
strokeWidth(1)
for i, circle in ipairs(circles) do
ellipse(0, 0, circle.radius, circle.radius)
end
-- make the opennings
fill(backgroundC)
stroke(backgroundC)
strokeWidth(0)
for i, circle in ipairs(circles) do
if circle.top then
ellipse(0, circle.radius-13, 25, 25)
else
ellipse(0, -circle.radius+13, 25, 25)
end
end
end
|
require("telescope").load_extension("notify")
|
object_building_kashyyyk_kash_swamp_reed_s02 = object_building_kashyyyk_shared_kash_swamp_reed_s02:new {
}
ObjectTemplates:addTemplate(object_building_kashyyyk_kash_swamp_reed_s02, "object/building/kashyyyk/kash_swamp_reed_s02.iff")
|
-----------------------------------
-- Area: Newton Movalpolos
-- NPC: Furnace_Hatch
-----------------------------------
local ID = require("scripts/zones/Newton_Movalpolos/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/status")
-----------------------------------
function onTrade(player, npc, trade)
if npcUtil.tradeHas(trade, 947) then
local offset = npc:getID() - ID.npc.FURNACE_HATCH_OFFSET
player:confirmTrade()
player:startEvent(21 + offset) -- THUD!
-- toggle open/closed the four doors related to this hatch
local doorOffset = ID.npc.DOOR_OFFSET + math.min(offset, 2) * 4
for i = doorOffset, doorOffset + 3 do
local door = GetNPCByID(i)
door:setAnimation((door:getAnimation() == tpz.anim.OPEN_DOOR) and tpz.anim.CLOSE_DOOR or tpz.anim.OPEN_DOOR)
end
else
player:startEvent(20) -- no firesand message
end
end
function onTrigger(player, npc)
player:startEvent(20) -- no firesand message
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
local require = using("BodyEditor.Script")
local CCLayer = require("CCLayer")
local CCDrawNode = require("CCDrawNode")
local oVec2 = require("oVec2")
local ccColor4 = require("ccColor4")
local oLine = require("oLine")
local once = require("once")
local wait = require("wait")
local seconds = require("seconds")
local function oPointControl()
local oEditor = require("oEditor")
local control = CCLayer()
control.visible = false
local circle = CCDrawNode()
circle:drawDot(oVec2.zero,20,ccColor4(0xff00ffff))
circle:addChild(oLine({oVec2(-10,0),oVec2(10,0)},ccColor4()))
circle:addChild(oLine({oVec2(0,10),oVec2(0,-10)},ccColor4()))
circle.opacity = 0.5
control:addChild(circle)
local target = nil
local targetPos = oVec2.zero
local totalDelta = oVec2.zero
local posChanged = nil
local jump = false
local jumpNow = false
control.touchPriority = oEditor.touchPriorityEditControl
control.swallowTouches = true
control:slot("TouchBegan",function(touch)
if not jump then
jump = true
jumpNow = true
control:schedule(once(function()
wait(seconds(0.4))
jump = false
jumpNow = false
end))
elseif jumpNow then
jump = false
control:unschedule()
targetPos = target:convertToNodeSpace(touch.location)
if oEditor.isFixed then
targetPos = oEditor:round(targetPos)
end
circle.position = targetPos
if posChanged then
posChanged(targetPos)
end
end
return true
end)
control:slot("TouchMoved",function(touch)
local delta = target:convertToNodeSpace(touch.location) - target:convertToNodeSpace(touch.preLocation)
if oEditor.isFixed then
totalDelta = totalDelta + delta
if totalDelta.x > 1 or totalDelta.x < -1 then
local posX = targetPos.x+totalDelta.x
targetPos.x = oEditor:round(posX)
totalDelta.x = 0
end
if totalDelta.y > 1 or totalDelta.y < -1 then
local posY = targetPos.y+totalDelta.y
targetPos.y = oEditor:round(posY)
totalDelta.y = 0
end
else
targetPos = targetPos + delta
end
circle.position = targetPos
if posChanged then
posChanged(targetPos)
end
end)
control.show = function(self,pos,callback,controlTarget)
control.visible = true
control.touchEnabled = true
target = nil
if controlTarget then
target = controlTarget
else
target = oEditor.world
end
circle.transformTarget = target
circle.position = pos
targetPos = pos
totalDelta = oVec2.zero
posChanged = callback
jump = false
jumpNow = false
end
control.hide = function(self)
if not control.visible then return end
control.visible = false
control.touchEnabled = false
posChanged = nil
target = nil
end
return control
end
return oPointControl
|
local ffi = require('ffi')
local kdns = require('dns')
local utils, rrparser = require('dns.utils'), require('dns.rrparser')
-- Compile query string/table into filter function
-- e.g. 'TXT' => filter matching TXT records
-- 'rdata~=A(1.2.3.4)' => match all except A RDATA==1.2.3.4'
-- See examples/zq.lua
local function makefilter(query)
if type(query) == 'string' then query = {query} end
local filters, farg = {}, {}
for _,t in ipairs(query) do
local k,op,v = t:match('(%w+)([~!=><]+)(%S+)')
if not v then
local tstr = t:match('%w+')
if tstr and kdns.type[tstr] then
k = (#tstr == #t) and 'type' or 'rdata'
v = t
op = '=='
else -- Owner filter
k = 'owner'
op = '=='
v = t
end
end
-- Normalize operator
if op == '=' or op == 'is' then op = '=='
elseif op == '!=' then op = '~='
end
-- Normalize inversion
local opref = ''
if op == '~=' then opref = 'not ' op = '==' end
-- Select left operand
if k == 'owner' then
local owner, _ = v:match('([^~]+)~?(%d*)')
local meta = 'equals'
if owner:sub(1,1) == '*' then
owner = owner:sub(3)
meta = 'parentof'
end
owner = kdns.dname.parse(owner)
-- TODO(marek): fuzzy search with N allowed edit distance
-- fuzzy = tonumber(fuzzy)
table.insert(farg, owner)
table.insert(filters, string.format('(%sargs[%d]:%s(owner))', opref, #farg, meta))
elseif k == 'ttl' then
table.insert(filters, string.format('%s(%s%s%s)', opref, k, op, v))
elseif k == 'type' then
table.insert(filters, string.format('%s(rtype%s%d)', opref, op, kdns.type[v]))
elseif k == 'rdata' then
-- Parse type and text format and attempt to parse it into wire format
local rt, rv, rwire = v:match('(%w+)%(([^)]+)%)$')
-- Raw hex-encoded RDATA is not prefixed with type
if not rt then
rwire = v:gsub("\\x(%x%x)",function (x) return string.char(tonumber(x,16)) end)
-- Type-specific RDATA, attempt to parse
elseif rt and rv then
rt = string.upper(rt)
rwire = kdns.rdata.parse(string.format('%s %s', rt, rv))
table.insert(filters, string.format('(rtype==%d)', kdns.type[rt]))
end
if not rwire then error(string.format('invalid rdata: "%s"', v)) end
table.insert(farg, rwire)
table.insert(filters, string.format('(%sstring.find(rdata,args[%d],1,true))', opref, #farg))
else
return nil, string.format('unknown filter "%s"', t)
end
end
-- Compile filter function
local fdecl = table.concat(filters, ' and ')
if #fdecl == 0 then fdecl = 'true' end
local ok, filter = pcall(loadstring(
string.format('return function(owner, rtype, ttl, rdata, args) return %s end', fdecl)))
if not ok or filter == nil then
return nil, string.format('bad filter function "%s"', fdecl)
end
-- Clear temporary data and return closure
fdecl, filters, query = nil, nil, nil -- luacheck: ignore
return function(owner, rtype, ttl, rdata)
return filter(owner, rtype, ttl, rdata, farg)
end
end
local function sink_print()
local count = 0
return function (owner, type, ttl, rdata)
if not owner then return count end
io.write(kdns.rrset(owner, type):add(rdata, ttl):tostring())
count = count + 1
return true
end
end
local function sink_table()
local capture = {}
return function (owner, type, ttl, rdata)
if not owner then return capture end
table.insert(capture, kdns.rrset(owner, type):add(rdata, ttl))
return true
end
end
local function sink_set()
local capture = rrparser.set()
local inserted = 0
return function (owner, type, ttl, rdata)
if not owner then
return capture, inserted
end
-- We'll initialize pre-allocated block to save some ticks
local rrset = capture:newrr(true)
rrset._owner = nil
rrset.rrs.rdata = nil
rrset:init(owner, type):add(rdata, ttl)
inserted = inserted + 1
return true
end
end
local function sink_nameset()
local capture = rrparser.nameset()
local inserted = 0
return function (owner, _, _, _)
if not owner then
capture:sort()
return capture, inserted
end
capture:put(owner)
inserted = inserted + 1
return true
end
end
local lmdb_ok, lmdb = pcall(require, 'dns.lmdb')
local function sink_lmdb(env, db, txn)
if not lmdb_ok then return nil, 'lmdb sink not supported' end
if not db then txn, db = assert(env:open()) end
local key, val = lmdb.val_t(), lmdb.val_t()
local ttlbuf = ffi.new('uint32_t [1]')
local inserted = 0
return function (owner, type, ttl, rdata)
if not owner then
txn:commit()
return env, inserted, db
end
-- Create search key
key.data, key.size = utils.searchkey(owner, type)
-- Insert into LMDB
local rdlen = #rdata
val.data, val.size = nil, ffi.sizeof(ttlbuf) + rdlen
assert(txn:put(key, val, 'reserve'))
-- Serialize RR set
ttlbuf[0] = ttl
ffi.copy(val.data, ttlbuf, ffi.sizeof(ttlbuf))
ffi.copy(ffi.cast('char *', val.data) + ffi.sizeof(ttlbuf), rdata, rdlen)
inserted = inserted + 1
return true
end
end
local function sink_json()
local capture = {}
local rr = ffi.gc(kdns.rrset(nil, 0), kdns.rrset.clear)
local fmt = '{ "name": "%s", "type": %d, "TTL": %d, "data": %s }'
return function (owner, type, ttl, rdata)
if not owner then
return string.format('[%s]', table.concat(capture, ','))
end
-- Set data for RR set for printing
rr.raw_type = type
rr:add(rdata, ttl)
-- Convert to JSON entry
local rdata_text = rr:tostring(0)
if rdata_text:byte() ~= 34 then
rdata_text = '"'..rdata_text..'"'
end
table.insert(capture, string.format(fmt, owner, type, ttl, rdata_text))
rr:clear()
return true
end
end
local function zone(zonefile, sink, filter, limit)
if not zonefile then return false end
-- Create sink and parser instance
if not sink then sink = sink_print() end
local parser = assert(rrparser.new())
local ok, err = parser:open(zonefile)
if not ok then
return ok, err
end
-- Process all records
local last_name = nil
while parser:parse() do
local owner_dname = kdns.todname(parser.r_owner)
local rdata = ffi.string(parser.r_data, parser.r_data_length)
-- When limit is placed on the number of results, continue matching
-- results only as long as owner doesn't change, after that, stop
if last_name then
if not last_name:equals(owner_dname) then break end
end
-- Match current record against filter
if not filter or filter(owner_dname, parser.r_type, parser.r_ttl, rdata) then
-- When limit is placed on the number of results, continue matching
-- results only as long as owner doesn't change, after that, stop
if not last_name and limit then
limit = limit - 1
if limit <= 0 then last_name = owner_dname:copy() end
end
if not sink(owner_dname, parser.r_type, parser.r_ttl, rdata) then
break
end
end
end
return sink(nil)
end
local function domains(zonefile, sink, filter, limit)
if not zonefile then return false end
-- Create sink and parser instance
if not sink then sink = sink_print() end
local last_name = nil
-- read the lines in table 'lines'
for line in io.lines(zonefile) do
local owner_dname = kdns.dname.parse(line:sub(1, #line-1))
-- When limit is placed on the number of results, continue matching
-- results only as long as owner doesn't change, after that, stop
if last_name then
if not last_name:equals(owner_dname) then break end
end
-- Match current record against filter
if not filter or filter(owner_dname, kdns.type.A, 0, '\0\0\0\0') then
-- When limit is placed on the number of results, continue matching
-- results only as long as owner doesn't change, after that, stop
if not last_name and limit then
limit = limit - 1
if limit <= 0 then last_name = owner_dname:copy() end
end
if not sink(owner_dname, kdns.type.A, 0, '\0\0\0\0') then
break
end
end
end
return sink(nil)
end
return {
zone = zone,
domains = domains,
makefilter = makefilter,
printer = sink_print,
jsonify = sink_json,
table = sink_table,
set = sink_set,
lmdb = sink_lmdb,
nameset = sink_nameset,
} |
package.path = string.format("?.lua;%s",package.path)
local spell = require "spell"
spell.init("big.txt")
while true do
io.write("Enter a word (ctrl+d exits): ")
io.stdout:flush()
local w = io.read()
if not w then break end
print("Sugestion:", assert( spell.correct(w) ))
end
print()
|
if settings.startup["Noxys_Trees-tree_dying_factor"].value > 0.00001 then
data.raw.fire["fire-flame-on-tree"].tree_dying_factor = settings.startup["Noxys_Trees-tree_dying_factor"].value
end
local mul = settings.startup["Noxys_Trees-emission_multiplier"].value
if mul ~= 1 then
for _,v in pairs(data.raw.tree) do
if v.emissions_per_second then
v.emissions_per_second = v.emissions_per_second * mul
end
end
end |
if GetBot():IsInvulnerable() or not GetBot():IsHero() or not string.find(GetBot():GetUnitName(), "hero") or GetBot():IsIllusion() then
return;
end
local ability_item_usage_generic = dofile( GetScriptDirectory().."/ability_item_usage_generic" )
local utils = require(GetScriptDirectory() .. "/util")
local mutil = require(GetScriptDirectory() .. "/MyUtility")
if GetBot():IsInvulnerable() then
return;
end
function AbilityLevelUpThink()
ability_item_usage_generic.AbilityLevelUpThink();
end
function BuybackUsageThink()
ability_item_usage_generic.BuybackUsageThink();
end
function CourierUsageThink()
ability_item_usage_generic.CourierUsageThink();
end
function ItemUsageThink()
ability_item_usage_generic.ItemUsageThink()
end
local castBSDesire = 0;
local castTDDesire = 0;
local castPSDesire = 0;
local castPSEDesire = 0;
local castMCDesire = 0;
local castUTDesire = 0;
local castWCDesire = 0;
local abilityBS = nil;
local abilityTD = nil;
local abilityPS = nil;
local abilityPSE = nil;
local abilityMC = nil;
local abilityUT = nil;
local abilityWC = nil;
local PSLoc = {0, 0, 0};
local Ancient = GetAncient(GetTeam());
local npcBot = nil;
function AbilityUsageThink()
if npcBot == nil then npcBot = GetBot(); end
if abilityPSE == nil then abilityPSE = npcBot:GetAbilityByName( "monkey_king_primal_spring_early" ) end
castPSEDesire = ConsiderPrimalSpringEarly();
if ( castPSEDesire > 0 )
then
npcBot:Action_UseAbility( abilityPSE );
return;
end
-- Check if we're already using an ability
if mutil.CanNotUseAbility(npcBot) then return end
if abilityBS == nil then abilityBS = npcBot:GetAbilityByName( "monkey_king_boundless_strike" ) end
if abilityTD == nil then abilityTD = npcBot:GetAbilityByName( "monkey_king_tree_dance" ) end
if abilityPS == nil then abilityPS = npcBot:GetAbilityByName( "monkey_king_primal_spring" ) end
if abilityMC == nil then abilityMC = npcBot:GetAbilityByName( "monkey_king_mischief" ) end
if abilityUT == nil then abilityUT = npcBot:GetAbilityByName( "monkey_king_untransform" ) end
if abilityWC == nil then abilityWC = npcBot:GetAbilityByName( "monkey_king_wukongs_command" ) end
-- Consider using each ability
castWCDesire, castWCLocation = ConsiderWukongCommand();
castBSDesire, castBSLocation = ConsiderBoundlessStrike();
castTDDesire, castTDTarget = ConsiderTreeDance();
castMCDesire = ConsiderMischief();
castUTDesire = ConsiderUntransform();
castPSDesire, castPSLocation = ConsiderPrimalSpring();
if ( castMCDesire > 0 )
then
npcBot:Action_UseAbility( abilityMC );
return;
end
if ( castUTDesire > 0 )
then
npcBot:Action_UseAbility( abilityUT );
return;
end
if ( castWCDesire > 0 )
then
npcBot:Action_UseAbilityOnLocation( abilityWC, castWCLocation );
return;
end
if ( castBSDesire > 0 )
then
npcBot:Action_UseAbilityOnLocation( abilityBS, castBSLocation );
return;
end
if ( castTDDesire > 0 )
then
npcBot:Action_UseAbilityOnTree( abilityTD, castTDTarget );
return;
end
if ( castPSDesire > 0 )
then
PSLoc = castPSLocation;
npcBot:Action_UseAbilityOnLocation( abilityPS, castPSLocation );
return;
end
end
function GetFurthestTree(trees)
if Ancient == nil then return nil end;
local furthest = nil;
local fDist = 10000;
for _,tree in pairs(trees)
do
local dist = GetUnitToLocationDistance(Ancient, GetTreeLocation(tree));
if dist < fDist then
furthest = tree;
fDist = dist;
end
end
return furthest;
end
function ConsiderBoundlessStrike()
-- Make sure it's castable
if ( not abilityBS:IsFullyCastable() )
then
return BOT_ACTION_DESIRE_NONE, 0;
end
-- Get some of its values
local nCastRange = abilityBS:GetCastRange();
local nCastPoint = abilityBS:GetCastPoint( );
-- Check for a channeling enemy
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE );
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if ( npcEnemy:IsChanneling() )
then
--return BOT_ACTION_DESIRE_HIGH, npcEnemy:GetLocation();
return BOT_ACTION_DESIRE_MODERATE, npcEnemy:GetExtrapolatedLocation( nCastPoint );
end
end
if npcBot:HasModifier('modifier_monkey_king_jingu_mastery') then
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nCastRange , true, BOT_MODE_NONE );
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if (mutil.CanCastOnNonMagicImmune(npcEnemy) and mutil.IsInRange(npcEnemy, npcBot, nCastRange-200))
then
--return BOT_ACTION_DESIRE_HIGH, npcEnemy:GetLocation( );
return BOT_ACTION_DESIRE_MODERATE, npcEnemy:GetExtrapolatedLocation( nCastPoint );
end
end
end
--------------------------------------
-- Mode based usage
--------------------------------------
-- If we're seriously retreating, see if we can land a stun on someone who's damaged us recently
if mutil.IsRetreating(npcBot)
then
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( 1200, true, BOT_MODE_NONE );
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) )
then
return BOT_ACTION_DESIRE_MODERATE, npcEnemy:GetLocation( );
end
end
end
if mutil.IsInTeamFight(npcBot, 1200)
then
local locationAoE = npcBot:FindAoELocation( true, true, npcBot:GetLocation(), nCastRange, 200, 0, 0 );
if ( locationAoE.count >= 2 )
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc;
end
end
-- If we're going after someone
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if ( mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, nCastRange-200) )
then
return BOT_ACTION_DESIRE_MODERATE, npcTarget:GetExtrapolatedLocation( nCastPoint );
end
end
--
return BOT_ACTION_DESIRE_NONE, 0;
end
function ConsiderTreeDance()
-- Make sure it's castable
if ( not abilityTD:IsFullyCastable() or not abilityPS:IsFullyCastable() or npcBot:IsRooted() )
then
return BOT_ACTION_DESIRE_NONE, 0;
end
local nCastRange = abilityTD:GetCastRange();
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE );
if tableNearbyEnemyHeroes == nil then
return BOT_ACTION_DESIRE_NONE, 0;
end
if ( not abilityPS:IsFullyCastable() and not abilityPS:IsHidden() )
then
return BOT_ACTION_DESIRE_NONE, 0;
end
if mutil.IsRetreating(npcBot) and abilityPS:IsFullyCastable() and npcBot:DistanceFromFountain() > 1000 and #tableNearbyEnemyHeroes >= 1
then
local tableNearbyTrees = npcBot:GetNearbyTrees( nCastRange );
local furthest = GetFurthestTree(tableNearbyTrees);
if furthest ~= nil then
return BOT_ACTION_DESIRE_MODERATE, furthest;
end
end
if mutil.IsInTeamFight(npcBot, 1200)
then
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE );
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if ( mutil.IsInRange(npcEnemy, npcBot, nCastRange) )
then
local tableNearbyTrees = npcEnemy:GetNearbyTrees( nCastRange );
if tableNearbyTrees ~= nil and #tableNearbyTrees >= 1 then
return BOT_ACTION_DESIRE_MODERATE, tableNearbyTrees[1];
end
end
end
end
-- If we're going after someone
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if ( mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, nCastRange) )
then
local tableNearbyTrees = npcTarget:GetNearbyTrees( nCastRange );
if tableNearbyTrees ~= nil and #tableNearbyTrees >= 1 then
return BOT_ACTION_DESIRE_MODERATE, tableNearbyTrees[1];
end
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function ConsiderPrimalSpring()
if ( not abilityPS:IsFullyCastable() or abilityPS:IsHidden() or abilityPS:IsActivated() == false )
then
return BOT_ACTION_DESIRE_NONE, 0;
end
-- Get some of its values
local nCastRange = abilityPS:GetSpecialValueInt("max_distance");
local nRadius = abilityPS:GetSpecialValueInt("impact_radius");
local nCastPoint = abilityPS:GetChannelTime( );
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( 1000, true, BOT_MODE_NONE );
if tableNearbyEnemyHeroes == nil then
return BOT_ACTION_DESIRE_NONE, 0;
end
--------------------------------------
-- Mode based usage
--------------------------------------
if mutil.IsRetreating(npcBot) and #tableNearbyEnemyHeroes >= 1
then
local location = npcBot:GetXUnitsTowardsLocation( GetAncient(GetTeam()):GetLocation(), nCastRange );
return BOT_ACTION_DESIRE_MODERATE, location;
end
if mutil.IsInTeamFight(npcBot, 1200)
then
local locationAoE = npcBot:FindAoELocation( true, true, npcBot:GetLocation(), nCastRange, nRadius, 0, 0 );
if ( locationAoE.count >= 2 )
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc;
end
end
-- If we're going after someone
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, nCastRange)
then
if mutil.IsDisabled(true, npcTarget) or npcTarget:GetMovementDirectionStability() < 1.0 then
return BOT_ACTION_DESIRE_HIGH, npcTarget:GetLocation( );
else
return BOT_ACTION_DESIRE_MODERATE, npcTarget:GetExtrapolatedLocation( nCastPoint );
end
end
end
--
return BOT_ACTION_DESIRE_NONE, 0;
end
function ConsiderPrimalSpringEarly()
if ( not abilityPSE:IsFullyCastable() or abilityPSE:IsHidden() )
then
return BOT_ACTION_DESIRE_NONE;
end
local trees = npcBot:GetNearbyTrees(50);
if trees == nil or #trees == 0 then
return BOT_ACTION_DESIRE_NONE;
end
local nRadius = 375;
if mutil.IsRetreating(npcBot)
then
return BOT_ACTION_DESIRE_MODERATE
end
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and
( GetUnitToLocationDistance(npcTarget, PSLoc) >= ( 375 - 125 ) or npcTarget:GetHealth() <= 175 )
then
return BOT_ACTION_DESIRE_MODERATE;
end
end
return BOT_ACTION_DESIRE_NONE;
end
function ConsiderMischief()
if ( not abilityMC:IsFullyCastable() or abilityMC:IsHidden() )
then
return BOT_ACTION_DESIRE_NONE;
end
if mutil.IsRetreating(npcBot)
then
local tableNearbyEnemy = npcBot:GetNearbyHeroes( 1200, true, BOT_MODE_NONE );
if #tableNearbyEnemy >= 1 then
return BOT_ACTION_DESIRE_MODERATE
end
end
if mutil.IsDefending(npcBot) then
local tableNearbyAlly = npcBot:GetNearbyHeroes( 1000, false, BOT_MODE_NONE );
local tower = npcBot:GetNearbyTowers(1000, false);
if tower ~= nil and tableNearbyAlly ~= nil and #tower >= 1 and #tableNearbyAlly >= 2 then
return BOT_ACTION_DESIRE_MODERATE
end
end
return BOT_ACTION_DESIRE_NONE;
end
function ConsiderUntransform()
if ( not abilityUT:IsFullyCastable() or abilityUT:IsHidden() )
then
return BOT_ACTION_DESIRE_NONE;
end
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if mutil.IsValidTarget(npcTarget) and not mutil.IsInRange(npcTarget, npcBot, 1200)
then
return BOT_ACTION_DESIRE_MODERATE
end
end
if mutil.IsRetreating(npcBot) and not npcBot:WasRecentlyDamagedByAnyHero(4.0)
then
return BOT_ACTION_DESIRE_MODERATE
end
return BOT_ACTION_DESIRE_NONE;
end
function ConsiderWukongCommand()
-- Make sure it's castable
if ( not abilityWC:IsFullyCastable() )
then
return BOT_ACTION_DESIRE_NONE, 0;
end
--
-- Get some of its values
local nCastRange = abilityWC:GetSpecialValueInt("cast_range");
local nRadius = abilityWC:GetSpecialValueInt("second_radius");
--------------------------------------
-- Mode based usage
--------------------------------------
if mutil.IsInTeamFight(npcBot, 1200)
then
local locationAoE = npcBot:FindAoELocation( true, true, npcBot:GetLocation(), nCastRange, nRadius/2, 0, 0 );
if ( locationAoE.count >= 2 )
then
return BOT_ACTION_DESIRE_MODERATE, locationAoE.targetloc;
end
end
-- If we're going after someone
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if mutil.IsValidTarget(npcTarget) and mutil.IsInRange(npcTarget, npcBot, nCastRange+(nRadius/2))
then
local tableNearbyEnemyHeroes = npcTarget:GetNearbyHeroes( 1000, false, BOT_MODE_NONE );
if tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes >= 2 then
return BOT_ACTION_DESIRE_MODERATE, npcTarget:GetExtrapolatedLocation(0.5);
end
end
end
--
return BOT_ACTION_DESIRE_NONE, 0;
end
|
--[[
// BigInteger.js
// Available under Public Domain
// https://github.com/Yaffle/BigInteger/
// For implementation details, see "The Handbook of Applied Cryptography"
// http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
]]
--[[
-- BigInteger.lua
-- Available under Public Domain
-- https://github.com/romdotdog/BigInteger.lua
]]
--
local createArray = table.create
local byte = string.byte
local sub = string.sub
local floor = math.floor
--
local epsilon = 2 / (9007199254740991 + 1)
while 1 + epsilon / 2 ~= 1 do
epsilon /= 2
end
local BASE = 2 / epsilon
local s = 134217728
while s * s < 2 / epsilon do
s *= 2
end
local SPLIT = s + 1
local function fma(a, b, product)
local at = SPLIT * a
local ahi = at - (at - a)
local alo = a - ahi
local bt = SPLIT * b
local bhi = bt - (bt - b)
local blo = b - bhi
return ((ahi * bhi + product) + ahi * blo + alo * bhi) + alo * blo
end
local function fastTrunc(x)
local v = (x - BASE) + BASE
return v > x and v - 1 or v
end
local function performMultiplication(carry, a, b)
local product = a * b
local err = fma(a, b, -product)
local hi = (product / BASE) - BASE + BASE
local lo = product - hi * BASE + err
if lo >= 0 then
lo -= BASE
hi += 1
end
lo += carry
if lo < 0 then
lo += BASE
hi -= 1
end
return lo, hi
end
local function performDivision(a, b, divisor)
if a >= divisor then
error()
end
local p = a * BASE
local q = fastTrunc(p / divisor)
local r = 0 - fma(q, divisor, -p)
if r < 0 then
q -= 1
r += divisor
end
r += b - divisor
if r < 0 then
r += divisor
else
q += 1
end
local y = fastTrunc(r / divisor)
r -= y * divisor
q += y
return q, r
end
local mt = {}
mt.__index = mt
local function createBigInteger(sign, magnitude, length)
local t = createArray(3)
t[1] = sign
t[2] = magnitude
t[3] = length
setmetatable(t, mt)
return t
end
local function fromNumber(n)
if n >= BASE or 0 - n >= BASE then
error("Cannot store number, it is too inaccurate. Please represent in string.")
end
local a = createArray(1, 0)
a[1] = n < 0 and 0 - n or 0 + n
return createBigInteger(n < 0 and 1 or 0, a, n == 0 and 0 or 1)
end
local function fromString(s: string)
local length = #s
if length == 0 then
error("Blank string passed to `new`")
end
local sign = 0
local signCharCode = byte(s, 1)
local from = 0
if signCharCode == 43 then -- +
from = 1
end
if signCharCode == 45 then -- -
from = 1
sign = 1
end
local radix = 10
if from == 0 and length >= 2 and byte(s, 1) == 48 then -- 0
local cha = byte(s, 2)
if cha == 98 then -- b
from = 2
elseif cha == 111 then -- o
radix = 8
from = 2
elseif cha == 88 or cha == 120 then -- Xx
radix = 16
from = 2
end
end
length -= from
if length == 0 then
error("Blank string passed to `new`")
end
local groupLength = 0
local groupRadix = 1
local limit = fastTrunc(BASE / radix)
while groupRadix <= limit do
groupLength += 1
groupRadix *= radix
end
local size = floor((length - 1) / groupLength) + 1
local magnitude = createArray(size, 0)
local start = from + 1 + (length - 1 - (size - 1) * groupLength) - groupLength
for j = 0, size - 1 do
local groupStart = start + j * groupLength
local c = tonumber(sub(s, (groupStart >= from and groupStart or from) + 1, groupStart + groupLength), radix)
for l = 1, j do
magnitude[l], c = performMultiplication(c, magnitude[l], groupRadix)
end
magnitude[j + 1] = c
end
while size > 0 and magnitude[size] == 0 do
size -= 1
end
return createBigInteger(size == 0 and 0 or sign, magnitude, size)
end
function mt.new(x)
if type(x) == "number" then
return fromNumber(x)
end
if type(x) == "string" then
return fromString(x)
end
error("Invalid type passed to `new`, expected number or string")
end
function mt.toNumber(a)
local size = a[3]
if size == 0 then
return 0
end
local mag = a[2]
if size == 1 then
return a[1] == 1 and 0 - mag[1] or mag[1]
end
if BASE + 1 ~= BASE then
error("BaseError")
end
local x = mag[size]
local y = mag[size - 1]
local i = size - 2
while i > 0 and mag[i] == 0 do
i -= 1
end
if i > 0 and y % 2 == 1 then
y += 1
end
local z = (x * BASE + y) * BASE ^ (size - 2)
return a[1] == 1 and 0 - z or z
end
-- Find some way to compare tables fast?
-- I removed the initial magnitude equality.
local function compareMagnitude(a, b)
local al, bl = a[3], b[3]
if al ~= bl then
return al < bl and -1 or 1
end
local am, bm = a[2], b[2]
for i = al, 1, -1 do
local ai, bi = am[i], bm[i]
if ai ~= bi then
return ai < bi and -1 or 1
end
end
return 0
end
local function compareTo(a, b)
local as = a[1]
local c = as == b[1] and compareMagnitude(a, b) or 1
return as == 1 and 0 - c or c
end
function mt.__lt(a, b)
return compareTo(a, b) < 0
end
function mt.__le(a, b)
return compareTo(a, b) <= 0
end
function mt.__eq(a, b)
return compareTo(a, b) == 0
end
local function addAndSubtract(a, b, isSubtraction)
local z = compareMagnitude(a, b)
local resultSign = z < 0 and (isSubtraction ~= 0 and 1 - b[1] or b[1]) or a[1]
local min = z < 0 and a or b
local max = z < 0 and b or a
local nm, xm = min[2], max[2]
if min[3] == 0 then
return createBigInteger(resultSign, xm, max[3])
end
local subtract = 0
local resultLength = max[3]
if a[1] ~= (isSubtraction ~= 0 and 1 - b[1] or b[1]) then
subtract = 1
if min[3] == resultLength then
while resultLength > 0 and nm[resultLength] == xm[resultLength] do
resultLength -= 1
end
end
if resultLength == 0 then -- a == -b
return createBigInteger(0, {}, 0)
end
end
-- result ~= 0
local result = createArray(resultLength + (1 - subtract), 0)
local c = 0
for i = 1, min[3] do
local aDigit = nm[i]
c += xm[i] + (subtract ~= 0 and 0 - aDigit or aDigit - BASE)
if c < 0 then
result[i] = BASE + c
c = 0 - subtract
else
result[i] = c
c = 1 - subtract
end
end
for i = min[3] + 1, resultLength do
c += xm[i]
if subtract == 0 then
c += 0 - BASE
end
if c < 0 then
result[i] = BASE + c
c = 0 - subtract
else
result[i] = c
c = 1 - subtract
end
end
if subtract == 0 then
result[resultLength + 1] = c
if c ~= 0 then
resultLength += 1
end
else
while resultLength > 0 and result[resultLength] == 0 do
resultLength -= 1
end
end
return createBigInteger(resultSign, result, resultLength)
end
function mt.__add(a, b)
return addAndSubtract(a, b, 0)
end
function mt.__sub(a, b)
return addAndSubtract(a, b, 1)
end
function mt.__mul(a, b)
local alength = a[3]
local blength = b[3]
local am = a[2]
local bm = b[2]
local asign = a[1]
local bsign = b[1]
if alength == 0 or blength == 0 then
return createBigInteger(0, {}, 0)
end
if alength == 1 and am[1] == 1 then
return createBigInteger(asign == 1 and 1 - bsign or bsign, bm, blength)
end
if blength == 1 and bm[1] == 1 then
return createBigInteger(asign == 1 and 1 - bsign or bsign, am, alength)
end
local astart = 1
while am[astart] == 0 do
astart += 1
end
local resultSign = asign == 1 and 1 - bsign or bsign
local resultLength = alength + blength
local result = createArray(resultLength, 0)
for i = 1, blength do
local digit = bm[i]
if digit ~= 0 then
local c = 0
for j = astart, alength do
local ij = j + i - 1
local carry = 1
c += result[ij] - BASE
if c < 0 then
c += BASE
carry = 0
end
local lo, hi = performMultiplication(c, am[j], digit)
result[ij] = lo
c = hi + carry
end
result[alength + i] = c
end
end
if result[resultLength] == 0 then
resultLength -= 1
end
return createBigInteger(resultSign, result, resultLength)
end
local function divideAndRemainder(a, b, isDivision)
local alength = a[3]
local blength = b[3]
local am = a[2]
local bm = b[2]
local asign = a[1]
local bsign = b[1]
if blength == 0 then
error("Attempt to divide by zero")
end
if alength == 0 then
return createBigInteger(0, {}, 0)
end
local quotientSign = asign == 1 and 1 - bsign or bsign
if blength == 1 and bm[1] == 1 then
if isDivision ~= 0 then
return createBigInteger(quotientSign, am, alength)
end
return createBigInteger(0, {}, 0)
end
local divisorOffset = alength + 1
local divisorAndRemainder = createArray(divisorOffset + blength + 1, 0)
local divisor = divisorAndRemainder
local remainder = divisorAndRemainder
for n = 1, alength do
remainder[n] = am[n]
end
for m = 1, blength do
divisor[divisorOffset + m] = bm[m]
end
local top = divisor[divisorOffset + blength]
-- normalization
local lambda = 1
if blength > 1 then
lambda = fastTrunc(BASE / (top + 1))
if lambda > 1 then
local carry = 0
for l = 1, divisorOffset + blength do
local lo, hi = performMultiplication(carry, divisorAndRemainder[l], lambda)
divisorAndRemainder[l] = lo
carry = hi
end
divisorAndRemainder[divisorOffset + blength + 1] = carry
top = divisor[divisorOffset + blength]
end
if top < fastTrunc(BASE / 2) then
error()
end
end
local shift = alength - blength
if shift < 0 then
shift = 0
end
local quotient
local quotientLength = 0
local lastNonZero = 1
while divisor[divisorOffset + lastNonZero] == 0 do
lastNonZero += 1
end
for i = shift, 0, -1 do
local t = blength + i
local t1 = t + 1
local q = BASE - 1
if remainder[t1] ~= top then
q = performDivision(remainder[t1], remainder[t], top)
end
local ax = 0
local bx = 0
local z = i + lastNonZero
for j = z, t1 do
local lo, hi = performMultiplication(bx, q, divisor[divisorOffset + j - i])
bx = hi
ax += remainder[j] - lo
if ax < 0 then
remainder[j] = BASE + ax
ax = -1
else
remainder[j] = ax
ax = 0
end
end
while ax ~= 0 do
q -= 1
local c = 0
for k = z, t1 do
c += remainder[k] - BASE + divisor[divisorOffset + k - i]
if c < 0 then
remainder[k] = BASE + c
c = 0
else
remainder[k] = c
c = 1
end
end
ax += c
end
if isDivision ~= 0 and q ~= 0 then
if quotientLength == 0 then
quotientLength = i + 1
quotient = createArray(quotientLength, 0)
end
quotient[i + 1] = q
end
end
if isDivision ~= 0 then
if quotientLength == 0 then
return createBigInteger(0, {}, 0)
end
return createBigInteger(quotientSign, quotient, quotientLength)
end
local remainderLength = alength + 1
if lambda > 1 then
local r = 0
for p = remainderLength, 1, -1 do
local q
q, r = performDivision(r, remainder[p], lambda)
remainder[p] = q
end
if r ~= 0 then
error()
end
end
while remainderLength > 0 and remainder[remainderLength] == 0 do
remainderLength -= 1
end
if remainderLength == 0 then
return createBigInteger(0, {}, 0)
end
local result = createArray(remainderLength, 0)
for o = 1, remainderLength do
result[o] = remainder[o]
end
return createBigInteger(asign, result, remainderLength)
end
function mt.__div(a, b)
return divideAndRemainder(a, b, 1)
end
function mt.__mod(a, b)
local fa = divideAndRemainder(a, b, 0)
if a[1] + b[1] == 0 then -- a > 0 and b > 0
return fa
end
return divideAndRemainder(
fa + b,
b, 0
)
end
function mt.__unm(a)
return createBigInteger(a[3] == 0 and a[1] or 1 - a[1], a[2], a[3])
end
local two = mt.new(2)
local log = math.log
function mt.__pow(a, b)
local n = b:toNumber()
if n < 0 then
error()
end
if n > 9007199254740991 then
local y = a:toNumber()
if y == 0 or y == -1 or y == 1 then
return y == -1 and (b % 2):toNumber() == 0 and -a or a
end
error()
end
if n == 0 then
return mt.new(1)
end
local am = a[2]
local af = am[1]
if a[3] == 1 and (af == 2 or af == 16) then
local log2 = log(2)
local bits = floor(log(BASE) / log2 + 0.5)
local abits = floor(log(af) / log2 + 0.5)
local nn = abits * n
local q = floor(nn / bits)
local q1 = q + 1
local r = nn - q * bits
local array = createArray(q1, 0)
array[q1] = 2 ^ r
return createBigInteger((af == 0 or n % 2 == 0) and 0 or 1, array, q1)
end
local x = a
while n % 2 == 0 do
n = floor(n / 2)
x *= x
end
local accumulator = x
n -= 1
if n >= 2 then
while n >= 2 do
local t = floor(n / 2)
if t * 2 ~= n then
accumulator *= x
end
n = t
x *= x
end
accumulator *= x
end
return accumulator
end
local new = mt.new
local rep = string.rep
local format = string.format
local insert = table.insert
local concat = table.concat
local formatBases = {
[8] = "o",
[10] = "d",
[16] = "x"
}
local digits = "0123456789abcdefghijklmnopqrstuvwxyz"
local abs = math.abs
local function basen(n, b)
local fb = formatBases[b or 10]
if fb then
return format("%.0"..fb, n)
end
n = floor(abs(n))
local t = {}
repeat
local d = (n % b) + 1
n = floor(n / b)
insert(t, 1, sub(digits, d, d))
until n == 0
return concat(t)
end
local function toString(this, radix)
if radix == nil then radix = 10 end
if radix ~= 10 and (radix < 2 or radix > 36 or radix ~= floor(radix)) then
error("radix argument must be an integer between 2 and 36")
end
local thisl = this[3]
if thisl > 8 then
if this[1] == 1 then
return "-" .. toString(-this, radix)
end
local e = floor(thisl * log(BASE) / log(radix) / 2 + 0.5 - 1)
local split = new(radix) ^ new(e)
local q = this / split
local r = this - q * split
local a = toString(r, radix)
return toString(q, radix) .. rep("0", e - #a) .. a
end
local remainderLength = thisl
if remainderLength == 0 then
return "0"
end
local a = this
local result = {a[1] == 1 and "-" or ""}
if remainderLength == 1 then
insert(result, basen(a[2][1], radix))
return concat(result)
end
local groupLength = 0
local groupRadix = 1
local limit = fastTrunc(BASE / radix)
while groupRadix <= limit do
groupLength += 1
groupRadix *= radix
end
if groupRadix * radix <= BASE then
error()
end
local size = remainderLength + floor((remainderLength - 1) / groupLength) + 1
local remainder = createArray(size, 0)
local am = a[2]
for n = 1, remainderLength do
remainder[n] = am[n]
end
local k = size
while remainderLength ~= 0 do
local groupDigit = 0
for i = remainderLength, 1, -1 do
remainder[i], groupDigit = performDivision(groupDigit, remainder[i], groupRadix)
end
while remainderLength > 0 and remainder[remainderLength] == 0 do
remainderLength -= 1
end
remainder[k] = groupDigit
k -= 1
end
k += 1
insert(result, basen(remainder[k], radix))
for i = k + 1, size do
local t = basen(remainder[i], radix)
insert(result, rep("0", groupLength - #t))
insert(result, t)
end
return concat(result)
end
mt.__tostring = toString
mt.toString = toString
return mt |
local AddonName, AddonTable = ...
-- WoD Toys
AddonTable.toys = {
-- Misc
109739, -- Star Chart
111476, -- Stolen Breath
113375, -- Vindicator's Armor Polish Kit
113540, -- Ba'ruun's Bountiful Bloom
113543, -- Spirit of Shinri
116120, -- Tasty Talador Lunch
117550, -- Angry Beehive
118244, -- Iron Buccaneer's Hat
118938, -- Manastorms Duplicator
127394, -- Podling Camouflage
-- Pepe
127870, -- A Tiny Pirate Hat
}
|
-- The player class
local player = {}
player.__index = player
-- Constants
local PLAYER_MAXSPEED = 450
local PLAYER_ACCEL = 1500
local PLAYER_FRICTION = 400
local PLAYER_BULLET_COOLDOWN = 0.25
function player.new()
local self = setmetatable({}, player)
-- Constants
self.IFRAME_LENGTH = 1
-- Variables
self.x = ARENA_WIDTH / 2
self.y = ARENA_HEIGHT * (4 / 5)
self.radius = 8
self.xspeed = 0
self.yspeed = 0
self.angle = 0
self.timeSinceLastShot = 0
self.health = 3
self.iframeTime = 0
self.markForDeletion = false
return self
end
function player:update(dt)
-- Update player values
self.angle = math.atan2(relMouse.y - self.y, relMouse.x - self.x)
self.timeSinceLastShot = self.timeSinceLastShot + dt
-- Move player
local accelVector = {x = 0, y = 0}
if love.keyboard.isDown("d") then
accelVector.x = accelVector.x + 1
end
if love.keyboard.isDown("a") then
accelVector.x = accelVector.x - 1
end
if love.keyboard.isDown("s") then
accelVector.y = accelVector.y + 1
end
if love.keyboard.isDown("w") then
accelVector.y = accelVector.y - 1
end
if accelVector.x ~= 0 or accelVector.y ~= 0 then
-- Normalize vector
local accelMag, accelAng = toPolar(accelVector.x, accelVector.y)
accelMag = PLAYER_ACCEL
accelVector.x, accelVector.y = toCartesian(accelMag, accelAng)
self.xspeed = self.xspeed + accelVector.x * dt
self.yspeed = self.yspeed + accelVector.y * dt
end
local speed, ang = toPolar(self.xspeed, self.yspeed)
if speed > PLAYER_MAXSPEED then
speed = PLAYER_MAXSPEED
self.xspeed = PLAYER_MAXSPEED * math.cos(ang)
self.yspeed = PLAYER_MAXSPEED * math.sin(ang)
end
self.x = self.x + self.xspeed * dt
self.y = self.y + self.yspeed * dt
-- Apply friction
if speed > 0 then
speed = speed - PLAYER_FRICTION * dt
if speed < 0 then speed = 0 end
self.xspeed, self.yspeed = toCartesian(speed, ang)
end
-- Collide with walls
if self.x < self.radius then
self.x = self.radius
self.xspeed = 0
end
if self.x > ARENA_WIDTH - self.radius then
self.x = ARENA_WIDTH - self.radius
self.xspeed = 0
end
if self.y < self.radius then
self.y = self.radius
self.yspeed = 0
end
if self.y > ARENA_HEIGHT - self.radius then
self.y = ARENA_HEIGHT - self.radius
self.yspeed = 0
end
-- Check for hurt
if self.iframeTime > 0 then
self.iframeTime = self.iframeTime - dt
if self.iframeTime < 0 then self.iframeTime = 0 end
else
if state.opponent and not state.opponent.intangible then
if calcDist(self.x, self.y, state.opponent.x, state.opponent.y) <= (self.radius + state.opponent.radius)
then
self:damage()
end
end
for i, bullet in ipairs(state.bullets) do
if self.iframeTime > 0 then break end
if not bullet.friendly and not (getmetatable(bullet) == classes.bulletPortal) then
if calcDist(self.x, self.y, bullet.x, bullet.y) <= (self.radius + bullet.radius) then
self:damage()
bullet.markForDeletion = true
end
end
end
if state.opponent and state.opponent.ducks then
for i, duck in ipairs(state.opponent.ducks) do
if self.iframeTime > 0 then break end
if calcDist(self.x, self.y, duck.x, duck.y) <= (self.radius + duck.radius) then
self:damage()
end
end
end
end
if self.portaled then
self.portaled = self.portaled - dt
if self.portaled <= 0 then self.portaled = nil end
end
-- Create bullets
if love.mouse.isDown(1) and self.timeSinceLastShot > PLAYER_BULLET_COOLDOWN then
table.insert(state.bullets, classes.bullet.new(self.x, self.y, self.angle, true))
self.timeSinceLastShot = 0
sounds.bulletFiringFriendly:stop()
sounds.bulletFiringFriendly:play()
end
end
local playerPolygon =
{
30, 0,
-20, 15,
-12, 0,
-20, -15,
30, 0,
}
local playerPolygonTri = love.math.triangulate(playerPolygon)
function player:draw()
-- Draw the player
love.graphics.push()
love.graphics.translate(self.x, self.y)
love.graphics.rotate(self.angle)
if self.iframeTime > 0.5 then
love.graphics.setColor(0.8, 0.2, 0.2, 1-self.iframeTime)
else
love.graphics.setColor(1, 1, 1, 1-self.iframeTime)
end
for _, tri in ipairs(playerPolygonTri) do
love.graphics.polygon("fill", tri)
end
local width = love.graphics.getLineWidth()
love.graphics.setLineWidth(3)
love.graphics.setColor(0, 0, 0)
love.graphics.line(playerPolygon)
love.graphics.setLineWidth(width)
love.graphics.pop()
-- Debug player hitbox
if debug then
love.graphics.setColor(1, 0, 0)
love.graphics.circle("line", self.x, self.y, self.radius)
-- Print current music time in seconds
-- Also print the checkpoint time the song will go to if you die
local currentMusic = musicGetPlaying()
if currentMusic then
love.graphics.setFont(fonts.medium)
local currentSeek = currentMusic:tell()
local lastCheckpoint = musicCalculateCheckpoint(currentMusic)
love.graphics.print(string.format("%.2f\n%.2f", currentSeek, lastCheckpoint), 10, 400)
end
end
end
function player:onDestroy()
state.gameOverTimer = classes.gameOverTimer.new()
for i, bullet in ipairs(state.bullets) do
if bullet.friendly then
bullet.markForDeletion = true
end
end
end
function player:damage()
self.health = self.health - 1
if self.health <= 0 then
self.markForDeletion = true
sounds.playerDeath:stop()
sounds.playerDeath:play()
musicPauseAndCheckpoint()
state:screenShake(0.75, 15)
else
self.iframeTime = self.IFRAME_LENGTH
sounds.playerHit:stop()
sounds.playerHit:play()
state:screenShake()
end
end
-- Register class
classes.player = player
|
project "ImGui"
kind "StaticLib"
staticruntime "on"
language "C++"
cppdialect "C++17"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-obj/" .. outputdir .. "/%{prj.name}")
files
{
"include/imgui/imconfig.h",
"include/imgui/imgui.h",
"src/imgui.cpp",
"src/imgui_draw.cpp",
"include/imgui/imgui_internal.h",
"src/imgui_tables.cpp",
"src/imgui_widgets.cpp",
"include/imgui/imstb_rectpack.h",
"include/imgui/imstb_textedit.h",
"include/imgui/imstb_truetype.h",
"src/imgui_demo.cpp"
}
includedirs "include"
filter "system:windows"
systemversion "latest"
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
|
local _, TRB = ...
local _, _, classIndexId = UnitClass("player")
if classIndexId == 1 then --Only do this if we're on a Warrior!
local barContainerFrame = TRB.Frames.barContainerFrame
local resourceFrame = TRB.Frames.resourceFrame
local castingFrame = TRB.Frames.castingFrame
local passiveFrame = TRB.Frames.passiveFrame
local barBorderFrame = TRB.Frames.barBorderFrame
local leftTextFrame = TRB.Frames.leftTextFrame
local middleTextFrame = TRB.Frames.middleTextFrame
local rightTextFrame = TRB.Frames.rightTextFrame
local resourceFrame = TRB.Frames.resourceFrame
local passiveFrame = TRB.Frames.passiveFrame
local targetsTimerFrame = TRB.Frames.targetsTimerFrame
local timerFrame = TRB.Frames.timerFrame
local combatFrame = TRB.Frames.combatFrame
TRB.Options.Warrior = {}
TRB.Options.Warrior.Arms = {}
TRB.Options.Warrior.Fury = {}
TRB.Options.Warrior.Protection = {}
TRB.Frames.interfaceSettingsFrameContainer.controls.arms = {}
TRB.Frames.interfaceSettingsFrameContainer.controls.fury = {}
TRB.Frames.interfaceSettingsFrameContainer.controls.protection = {}
--[[
Arms Defaults
]]
local function ArmsLoadDefaultBarTextSimpleSettings()
local textSettings = {
fontSizeLock=true,
fontFaceLock=true,
left={
text="",
fontFace="Fonts\\FRIZQT__.TTF",
fontFaceName="Friz Quadrata TT",
fontSize=18
},
middle={
text="",
fontFace="Fonts\\FRIZQT__.TTF",
fontFaceName="Friz Quadrata TT",
fontSize=18
},
right={
text="{$passive}[$passive+]{$casting}[$casting + ]{$passive}[$passive + ]$rage",
fontFace="Fonts\\FRIZQT__.TTF",
fontFaceName="Friz Quadrata TT",
fontSize=18
}
}
return textSettings
end
local function ArmsLoadDefaultBarTextAdvancedSettings()
local textSettings = {
fontSizeLock = false,
fontFaceLock = true,
left = {
text = "#deepWounds $deepWoundsCount $haste% ($gcd)||n{$rend}[#rend $rendCount ][ ]{$ttd}[TTD: $ttd][ ]",
fontFace = "Fonts\\FRIZQT__.TTF",
fontFaceName = "Friz Quadrata TT",
fontSize = 13
},
middle = {
text="{$suddenDeathTime}[#suddenDeath $suddenDeathTime #suddenDeath]",
fontFace = "Fonts\\FRIZQT__.TTF",
fontFaceName = "Friz Quadrata TT",
fontSize = 13
},
right = {
text = "{$ravagerRage}[#ravager$ravagerRage+]{$covenantRage}[#covenantAbility$covenantRage+]{$casting}[#casting$casting+]$rage",
fontFace = "Fonts\\FRIZQT__.TTF",
fontFaceName = "Friz Quadrata TT",
fontSize = 22
}
}
return textSettings
end
local function ArmsLoadDefaultSettings()
local settings = {
hastePrecision=2,
ragePrecision=0,
overcapThreshold=100,
thresholds = {
width = 2,
overlapBorder=true,
icons = {
border=2,
relativeTo = "TOP",
relativeToName = "Above",
enabled=true,
xPos=0,
yPos=-12,
width=24,
height=24
},
execute = {
enabled = true, -- 1
},
ignorePain = {
enabled = true, -- 2
},
shieldBlock = {
enabled = false, -- 3
},
slam = {
enabled = true, -- 4
},
whirlwind = {
enabled = true, -- 5
},
mortalStrike = {
enabled = true, -- 6
},
impendingVictory = {
enabled = true, -- 7
},
rend = {
enabled = true, -- 8
},
cleave = {
enabled = true, -- 9
},
condemn = {
enabled = true, -- 10
},
},
displayBar = {
alwaysShow=false,
notZeroShow=true,
neverShow=false
},
bar = {
width=555,
height=34,
xPos=0,
yPos=-200,
border=4,
dragAndDrop=false,
pinToPersonalResourceDisplay=false,
showPassive=true,
showCasting=true
},
colors = {
text = {
current="FFFF0000",
casting="FFFFFFFF",
spending="FF555555",
passive="FFEA3C53",
overcap="FF800000",
overThreshold="FF00FF00",
overThresholdEnabled=false,
overcapEnabled=true,
left="FFFFFFFF",
middle="FFFFFFFF",
right="FFFFFFFF",
dots={
enabled=true,
up="FFFFFFFF",
down="FFFF0000",
pandemic="FFFFFF00"
}
},
bar = {
border="FFC21807",
borderOvercap="FF800000",
background="66000000",
base="FFFF0000",
casting="FFFFFFFF",
spending="FF555555",
passive="FFEA3C53",
overcapEnabled=true,
},
threshold = {
under="FFFFFFFF",
over="FF00FF00",
unusable="FFFF0000"
}
},
displayText = {},
audio = {
overcap={
name = "Overcap",
enabled=false,
sound="Interface\\Addons\\TwintopInsanityBar\\AirHorn.ogg",
soundName="TRB: Air Horn"
},
suddenDeath={
name = "Sudden Death Proc",
enabled=false,
sound="Interface\\Addons\\TwintopInsanityBar\\AirHorn.ogg",
soundName="TRB: Air Horn"
},
},
textures = {
background="Interface\\Tooltips\\UI-Tooltip-Background",
backgroundName="Blizzard Tooltip",
border="Interface\\Buttons\\WHITE8X8",
borderName="1 Pixel",
resourceBar="Interface\\TargetingFrame\\UI-StatusBar",
resourceBarName="Blizzard",
passiveBar="Interface\\TargetingFrame\\UI-StatusBar",
passiveBarName="Blizzard",
castingBar="Interface\\TargetingFrame\\UI-StatusBar",
castingBarName="Blizzard",
textureLock=true
}
}
settings.displayText = ArmsLoadDefaultBarTextSimpleSettings()
return settings
end
local function ArmsResetSettings()
local settings = ArmsLoadDefaultSettings()
return settings
end
--[[
Fury Defaults
]]
local function FuryLoadDefaultBarTextSimpleSettings()
local textSettings = {
fontSizeLock=true,
fontFaceLock=true,
left={
text="",
fontFace="Fonts\\FRIZQT__.TTF",
fontFaceName="Friz Quadrata TT",
fontSize=18
},
middle={
text="{$enrageTime}[$enrageTime sec]",
fontFace="Fonts\\FRIZQT__.TTF",
fontFaceName="Friz Quadrata TT",
fontSize=18
},
right={
text="{$passive}[$passive+]{$casting}[$casting + ]{$passive}[$passive + ]$rage",
fontFace="Fonts\\FRIZQT__.TTF",
fontFaceName="Friz Quadrata TT",
fontSize=18
}
}
return textSettings
end
local function FuryLoadDefaultBarTextAdvancedSettings()
local textSettings = {
fontSizeLock = false,
fontFaceLock = true,
left = {
text = "$haste% ($gcd)||n{$ttd}[TTD: $ttd][ ]",
fontFace = "Fonts\\FRIZQT__.TTF",
fontFaceName = "Friz Quadrata TT",
fontSize = 13
},
middle = {
text="{$enrageTime}[#enrage $enrageTime #enrage][ ]||n{$whirlwindStacks}[#whirlwind $whirlwindTime ($whirlwindStacks) #whirlwind]",
fontFace = "Fonts\\FRIZQT__.TTF",
fontFaceName = "Friz Quadrata TT",
fontSize = 13
},
right = {
text = "{$covenantRage}[#covenantAbility$covenantRage+]{$casting}[#casting$casting+]$rage",
fontFace = "Fonts\\FRIZQT__.TTF",
fontFaceName = "Friz Quadrata TT",
fontSize = 22
}
}
return textSettings
end
local function FuryLoadDefaultSettings()
local settings = {
hastePrecision=2,
ragePrecision=0,
overcapThreshold=100,
thresholds = {
width = 2,
overlapBorder=true,
icons = {
border=2,
relativeTo = "TOP",
relativeToName = "Above",
enabled=true,
xPos=0,
yPos=-12,
width=24,
height=24
},
ignorePain = {
enabled = true, -- 1
},
shieldBlock = {
enabled = false, -- 2
},
slam = {
enabled = true, -- 3
},
whirlwind = {
enabled = true, -- 4
},
rampage = {
enabled = true, -- 5
},
impendingVictory = {
enabled = true, -- 6
},
},
displayBar = {
alwaysShow=false,
notZeroShow=true,
neverShow=false
},
bar = {
width=555,
height=34,
xPos=0,
yPos=-200,
border=4,
dragAndDrop=false,
pinToPersonalResourceDisplay=false,
showPassive=true,
showCasting=true
},
colors = {
text = {
current="FFFF0000",
casting="FFFFFFFF",
spending="FF555555",
passive="FFEA3C53",
overcap="FF800000",
overThreshold="FF00FF00",
overThresholdEnabled=false,
overcapEnabled=true,
left="FFFFFFFF",
middle="FFFFFFFF",
right="FFFFFFFF",
dots={
enabled=true,
up="FFFFFFFF",
down="FFFF0000",
pandemic="FFFFFF00"
}
},
bar = {
border="FFC21807",
borderOvercap="FF800000",
background="66000000",
base="FFFF0000",
casting="FFFFFFFF",
spending="FF555555",
passive="FFEA3C53",
enrage="FFFFCC55",
overcapEnabled=true,
},
threshold = {
under="FFFFFFFF",
over="FF00FF00",
unusable="FFFF0000"
}
},
displayText = {},
audio = {
overcap={
name = "Overcap",
enabled=false,
sound="Interface\\Addons\\TwintopInsanityBar\\AirHorn.ogg",
soundName="TRB: Air Horn"
},
},
textures = {
background="Interface\\Tooltips\\UI-Tooltip-Background",
backgroundName="Blizzard Tooltip",
border="Interface\\Buttons\\WHITE8X8",
borderName="1 Pixel",
resourceBar="Interface\\TargetingFrame\\UI-StatusBar",
resourceBarName="Blizzard",
passiveBar="Interface\\TargetingFrame\\UI-StatusBar",
passiveBarName="Blizzard",
castingBar="Interface\\TargetingFrame\\UI-StatusBar",
castingBarName="Blizzard",
textureLock=true
}
}
settings.displayText = FuryLoadDefaultBarTextSimpleSettings()
return settings
end
local function FuryResetSettings()
local settings = FuryLoadDefaultSettings()
return settings
end
local function LoadDefaultSettings()
local settings = TRB.Options.LoadDefaultSettings()
settings.warrior.arms = ArmsLoadDefaultSettings()
settings.warrior.fury = FuryLoadDefaultSettings()
return settings
end
TRB.Options.Warrior.LoadDefaultSettings = LoadDefaultSettings
--[[
Arms Option Menus
]]
local function ArmsConstructResetDefaultsPanel(parent)
if parent == nil then
return
end
local controls = TRB.Frames.interfaceSettingsFrameContainer.controls.arms
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
local title = ""
local dropdownWidth = 225
local sliderWidth = 260
local sliderHeight = 20
StaticPopupDialogs["TwintopResourceBar_Warrior_Arms_Reset"] = {
text = "Do you want to reset the Twintop's Resource Bar back to its default configuration? Only the Arms Warrior settings will be changed. This will cause your UI to be reloaded!",
button1 = "Yes",
button2 = "No",
OnAccept = function()
TRB.Data.settings.warrior.arms = ArmsResetSettings()
ReloadUI()
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3
}
StaticPopupDialogs["TwintopResourceBar_Warrior_Arms_ResetBarTextSimple"] = {
text = "Do you want to reset Twintop's Resource Bar's text (including font size, font style, and text information) back to its default (simple) configuration? Only the Arms Warrior settings will be changed. This will cause your UI to be reloaded!",
button1 = "Yes",
button2 = "No",
OnAccept = function()
TRB.Data.settings.warrior.arms.displayText = ArmsLoadDefaultBarTextSimpleSettings()
ReloadUI()
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3
}
StaticPopupDialogs["TwintopResourceBar_Warrior_Arms_ResetBarTextAdvanced"] = {
text = "Do you want to reset Twintop's Resource Bar's text (including font size, font style, and text information) back to its default (advanced) configuration? Only the Arms Warrior settings will be changed. This will cause your UI to be reloaded!",
button1 = "Yes",
button2 = "No",
OnAccept = function()
TRB.Data.settings.warrior.arms.displayText = ArmsLoadDefaultBarTextAdvancedSettings()
ReloadUI()
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3
}
--[[StaticPopupDialogs["TwintopResourceBar_Warrior_Arms_ResetBarTextNarrowAdvanced"] = {
text = "Do you want to reset Twintop's Resource Bar's text (including font size, font style, and text information) back to its default (narrow advanced) configuration? Only the Arms Warrior settings will be changed. This will cause your UI to be reloaded!",
button1 = "Yes",
button2 = "No",
OnAccept = function()
TRB.Data.settings.warrior.arms.displayText = ArmsLoadDefaultBarTextNarrowAdvancedSettings()
ReloadUI()
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3
}]]
controls.textCustomSection = TRB.UiFunctions.BuildSectionHeader(parent, "Reset Resource Bar to Defaults", 0, yCoord)
yCoord = yCoord - 30
controls.resetButton = TRB.UiFunctions.BuildButton(parent, "Reset to Defaults", xCoord, yCoord, 150, 30)
controls.resetButton:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Warrior_Arms_Reset")
end)
yCoord = yCoord - 40
controls.textCustomSection = TRB.UiFunctions.BuildSectionHeader(parent, "Reset Resource Bar Text", 0, yCoord)
yCoord = yCoord - 30
controls.resetButton1 = TRB.UiFunctions.BuildButton(parent, "Reset Bar Text (Simple)", xCoord, yCoord, 250, 30)
controls.resetButton1:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Warrior_Arms_ResetBarTextSimple")
end)
yCoord = yCoord - 40
--[[
controls.resetButton2 = TRB.UiFunctions.BuildButton(parent, "Reset Bar Text (Narrow Advanced)", xCoord, yCoord, 250, 30)
controls.resetButton2:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Warrior_Arms_ResetBarTextNarrowAdvanced")
end)
]]
controls.resetButton3 = TRB.UiFunctions.BuildButton(parent, "Reset Bar Text (Full Advanced)", xCoord, yCoord, 250, 30)
controls.resetButton3:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Warrior_Arms_ResetBarTextAdvanced")
end)
TRB.Frames.interfaceSettingsFrameContainer.controls.arms = controls
end
local function ArmsConstructBarColorsAndBehaviorPanel(parent)
if parent == nil then
return
end
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local controls = interfaceSettingsFrame.controls.arms
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
local title = ""
local dropdownWidth = 225
local sliderWidth = 260
local sliderHeight = 20
local maxBorderHeight = math.min(math.floor(TRB.Data.settings.warrior.arms.bar.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.arms.bar.width / TRB.Data.constants.borderWidthFactor))
local sanityCheckValues = TRB.Functions.GetSanityCheckValues(TRB.Data.settings.warrior.arms)
controls.buttons.exportButton_Warrior_Arms_BarDisplay = TRB.UiFunctions.BuildButton(parent, "Export Bar Display", 325, yCoord-5, 225, 20)
controls.buttons.exportButton_Warrior_Arms_BarDisplay:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Arms Warrior (Bar Display).", 1, 1, true, false, false, false, false)
end)
controls.barPositionSection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Position and Size", 0, yCoord)
yCoord = yCoord - 40
title = "Bar Width"
controls.width = TRB.UiFunctions.BuildSlider(parent, title, sanityCheckValues.barMinWidth, sanityCheckValues.barMaxWidth, TRB.Data.settings.warrior.arms.bar.width, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.width:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.bar.width = value
if GetSpecialization() == 1 then
barContainerFrame:SetWidth(value-(TRB.Data.settings.warrior.arms.bar.border*2))
barBorderFrame:SetWidth(TRB.Data.settings.warrior.arms.bar.width)
resourceFrame:SetWidth(value-(TRB.Data.settings.warrior.arms.bar.border*2))
castingFrame:SetWidth(value-(TRB.Data.settings.warrior.arms.bar.border*2))
passiveFrame:SetWidth(value-(TRB.Data.settings.warrior.arms.bar.border*2))
TRB.Functions.SetBarMinMaxValues(TRB.Data.settings.warrior.arms)
for k, v in pairs(TRB.Data.spells) do
if TRB.Data.spells[k] ~= nil and TRB.Data.spells[k]["id"] ~= nil and TRB.Data.spells[k]["rage"] ~= nil and TRB.Data.spells[k]["rage"] < 0 and TRB.Data.spells[k]["thresholdId"] ~= nil then
TRB.Functions.RepositionThreshold(TRB.Data.settings.warrior.arms, resourceFrame.thresholds[TRB.Data.spells[k]["thresholdId"]], resourceFrame, TRB.Data.settings.warrior.arms.thresholds.width, -TRB.Data.spells[k]["rage"], TRB.Data.character.maxResource)
TRB.Frames.resourceFrame.thresholds[TRB.Data.spells[k]["thresholdId"]]:Show()
end
end
end
local maxBorderSize = math.min(math.floor(TRB.Data.settings.warrior.arms.bar.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.arms.bar.width / TRB.Data.constants.borderWidthFactor))
local borderSize = TRB.Data.settings.warrior.arms.bar.border
if maxBorderSize < borderSize then
maxBorderSize = borderSize
end
controls.borderWidth:SetMinMaxValues(0, maxBorderSize)
controls.borderWidth.MaxLabel:SetText(maxBorderSize)
controls.borderWidth.EditBox:SetText(borderSize)
TRB.Functions.UpdateBarWidth(TRB.Data.settings.warrior.arms)
end)
title = "Bar Height"
controls.height = TRB.UiFunctions.BuildSlider(parent, title, sanityCheckValues.barMinHeight, sanityCheckValues.barMaxHeight, TRB.Data.settings.warrior.arms.bar.height, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.height:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.bar.height = value
if GetSpecialization() == 1 then
barContainerFrame:SetHeight(value-(TRB.Data.settings.warrior.arms.bar.border*2))
barBorderFrame:SetHeight(TRB.Data.settings.warrior.arms.bar.height)
resourceFrame:SetHeight(value-(TRB.Data.settings.warrior.arms.bar.border*2))
for x = 1, TRB.Functions.TableLength(resourceFrame.thresholds) do
resourceFrame.thresholds[x]:SetHeight(value)
end
castingFrame:SetHeight(value-(TRB.Data.settings.warrior.arms.bar.border*2))
passiveFrame:SetHeight(value-(TRB.Data.settings.warrior.arms.bar.border*2))
leftTextFrame:SetHeight(TRB.Data.settings.warrior.arms.bar.height * 3.5)
middleTextFrame:SetHeight(TRB.Data.settings.warrior.arms.bar.height * 3.5)
rightTextFrame:SetHeight(TRB.Data.settings.warrior.arms.bar.height * 3.5)
end
local maxBorderSize = math.min(math.floor(TRB.Data.settings.warrior.arms.bar.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.arms.bar.width / TRB.Data.constants.borderWidthFactor))
local borderSize = TRB.Data.settings.warrior.arms.bar.border
if maxBorderSize < borderSize then
maxBorderSize = borderSize
end
controls.borderWidth:SetMinMaxValues(0, maxBorderSize)
controls.borderWidth.MaxLabel:SetText(maxBorderSize)
controls.borderWidth.EditBox:SetText(borderSize)
TRB.Functions.UpdateBarHeight(TRB.Data.settings.warrior.arms)
end)
title = "Bar Horizontal Position"
yCoord = yCoord - 60
controls.horizontal = TRB.UiFunctions.BuildSlider(parent, title, math.ceil(-sanityCheckValues.barMaxWidth/2), math.floor(sanityCheckValues.barMaxWidth/2), TRB.Data.settings.warrior.arms.bar.xPos, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.horizontal:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.bar.xPos = value
if GetSpecialization() == 1 then
barContainerFrame:ClearAllPoints()
barContainerFrame:SetPoint("CENTER", UIParent)
barContainerFrame:SetPoint("CENTER", TRB.Data.settings.warrior.arms.bar.xPos, TRB.Data.settings.warrior.arms.bar.yPos)
end
end)
title = "Bar Vertical Position"
controls.vertical = TRB.UiFunctions.BuildSlider(parent, title, math.ceil(-sanityCheckValues.barMaxHeight/2), math.floor(sanityCheckValues.barMaxHeight/2), TRB.Data.settings.warrior.arms.bar.yPos, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.vertical:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.bar.yPos = value
if GetSpecialization() == 1 then
barContainerFrame:ClearAllPoints()
barContainerFrame:SetPoint("CENTER", UIParent)
barContainerFrame:SetPoint("CENTER", TRB.Data.settings.warrior.arms.bar.xPos, TRB.Data.settings.warrior.arms.bar.yPos)
end
end)
title = "Bar Border Width"
yCoord = yCoord - 60
controls.borderWidth = TRB.UiFunctions.BuildSlider(parent, title, 0, maxBorderHeight, TRB.Data.settings.warrior.arms.bar.border, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.borderWidth:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.bar.border = value
if GetSpecialization() == 1 then
barContainerFrame:SetWidth(TRB.Data.settings.warrior.arms.bar.width-(TRB.Data.settings.warrior.arms.bar.border*2))
barContainerFrame:SetHeight(TRB.Data.settings.warrior.arms.bar.height-(TRB.Data.settings.warrior.arms.bar.border*2))
barBorderFrame:SetWidth(TRB.Data.settings.warrior.arms.bar.width)
barBorderFrame:SetHeight(TRB.Data.settings.warrior.arms.bar.height)
if TRB.Data.settings.warrior.arms.bar.border < 1 then
barBorderFrame:SetBackdrop({
edgeFile = TRB.Data.settings.warrior.arms.textures.border,
tile = true,
tileSize = 4,
edgeSize = 1,
insets = {0, 0, 0, 0}
})
barBorderFrame:Hide()
else
barBorderFrame:SetBackdrop({
edgeFile = TRB.Data.settings.warrior.arms.textures.border,
tile = true,
tileSize=4,
edgeSize=TRB.Data.settings.warrior.arms.bar.border,
insets = {0, 0, 0, 0}
})
barBorderFrame:Show()
end
barBorderFrame:SetBackdropColor(0, 0, 0, 0)
barBorderFrame:SetBackdropBorderColor (TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.bar.border, true))
TRB.Functions.SetBarMinMaxValues(TRB.Data.settings.warrior.arms)
for k, v in pairs(TRB.Data.spells) do
if TRB.Data.spells[k] ~= nil and TRB.Data.spells[k]["id"] ~= nil and TRB.Data.spells[k]["rage"] ~= nil and TRB.Data.spells[k]["rage"] < 0 and TRB.Data.spells[k]["thresholdId"] ~= nil then
TRB.Functions.RepositionThreshold(TRB.Data.settings.warrior.arms, resourceFrame.thresholds[TRB.Data.spells[k]["thresholdId"]], resourceFrame, TRB.Data.settings.warrior.arms.thresholds.width, -TRB.Data.spells[k]["rage"], TRB.Data.character.maxResource)
TRB.Frames.resourceFrame.thresholds[TRB.Data.spells[k]["thresholdId"]]:Show()
end
end
end
local minsliderWidth = math.max(TRB.Data.settings.warrior.arms.bar.border*2, 120)
local minsliderHeight = math.max(TRB.Data.settings.warrior.arms.bar.border*2, 1)
local scValues = TRB.Functions.GetSanityCheckValues(TRB.Data.settings.warrior.arms)
controls.height:SetMinMaxValues(minsliderHeight, scValues.barMaxHeight)
controls.height.MinLabel:SetText(minsliderHeight)
controls.width:SetMinMaxValues(minsliderWidth, scValues.barMaxWidth)
controls.width.MinLabel:SetText(minsliderWidth)
end)
title = "Threshold Line Width"
controls.thresholdWidth = TRB.UiFunctions.BuildSlider(parent, title, 1, 10, TRB.Data.settings.warrior.arms.thresholds.width, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.thresholdWidth:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.thresholds.width = value
if GetSpecialization() == 1 then
for x = 1, TRB.Functions.TableLength(resourceFrame.thresholds) do
resourceFrame.thresholds[x]:SetWidth(TRB.Data.settings.warrior.arms.thresholds.width)
end
end
end)
yCoord = yCoord - 40
--NOTE: the order of these checkboxes is reversed!
controls.checkBoxes.lockPosition = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_dragAndDrop", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.lockPosition
f:SetPoint("TOPLEFT", xCoord2+xPadding, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Drag & Drop Movement Enabled")
f.tooltip = "Disable Drag & Drop functionality of the bar to keep it from accidentally being moved.\n\nWhen 'Pin to Personal Resource Display' is checked, this value is ignored and cannot be changed."
f:SetChecked(TRB.Data.settings.warrior.arms.bar.dragAndDrop)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.bar.dragAndDrop = self:GetChecked()
barContainerFrame:SetMovable((not TRB.Data.settings.warrior.arms.bar.pinToPersonalResourceDisplay) and TRB.Data.settings.warrior.arms.bar.dragAndDrop)
barContainerFrame:EnableMouse((not TRB.Data.settings.warrior.arms.bar.pinToPersonalResourceDisplay) and TRB.Data.settings.warrior.arms.bar.dragAndDrop)
end)
TRB.UiFunctions.ToggleCheckboxEnabled(controls.checkBoxes.lockPosition, not TRB.Data.settings.warrior.arms.bar.pinToPersonalResourceDisplay)
controls.checkBoxes.pinToPRD = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_pinToPRD", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.pinToPRD
f:SetPoint("TOPLEFT", xCoord+xPadding, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Pin to Personal Resource Display")
f.tooltip = "Pins the bar to the Blizzard Personal Resource Display. Adjust the Horizontal and Vertical positions above to offset it from PRD. When enabled, Drag & Drop positioning is not allowed. If PRD is not enabled, will behave as if you didn't have this enabled.\n\nNOTE: This will also be the position (relative to the center of the screen, NOT the PRD) that it shows when out of combat/the PRD is not displayed! It is recommended you set 'Bar Display' to 'Only show bar in combat' if you plan to pin it to your PRD."
f:SetChecked(TRB.Data.settings.warrior.arms.bar.pinToPersonalResourceDisplay)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.bar.pinToPersonalResourceDisplay = self:GetChecked()
TRB.UiFunctions.ToggleCheckboxEnabled(controls.checkBoxes.lockPosition, not TRB.Data.settings.warrior.arms.bar.pinToPersonalResourceDisplay)
barContainerFrame:SetMovable((not TRB.Data.settings.warrior.arms.bar.pinToPersonalResourceDisplay) and TRB.Data.settings.warrior.arms.bar.dragAndDrop)
barContainerFrame:EnableMouse((not TRB.Data.settings.warrior.arms.bar.pinToPersonalResourceDisplay) and TRB.Data.settings.warrior.arms.bar.dragAndDrop)
TRB.Functions.RepositionBar(TRB.Data.settings.warrior.arms, TRB.Frames.barContainerFrame)
end)
yCoord = yCoord - 30
controls.textBarTexturesSection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Textures", 0, yCoord)
yCoord = yCoord - 30
-- Create the dropdown, and configure its appearance
controls.dropDown.resourceBarTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_RageBarTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.resourceBarTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Main Bar Texture", xCoord, yCoord)
controls.dropDown.resourceBarTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.resourceBarTexture:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.resourceBarTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, TRB.Data.settings.warrior.arms.textures.resourceBarName)
UIDropDownMenu_JustifyText(controls.dropDown.resourceBarTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.resourceBarTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("statusbar")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("statusbar")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Status Bar Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.arms.textures.resourceBar
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.resourceBarTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.textures.resourceBar = newValue
TRB.Data.settings.warrior.arms.textures.resourceBarName = newName
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, newName)
if TRB.Data.settings.warrior.arms.textures.textureLock then
TRB.Data.settings.warrior.arms.textures.castingBar = newValue
TRB.Data.settings.warrior.arms.textures.castingBarName = newName
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, newName)
TRB.Data.settings.warrior.arms.textures.passiveBar = newValue
TRB.Data.settings.warrior.arms.textures.passiveBarName = newName
UIDropDownMenu_SetText(controls.dropDown.passiveBarTexture, newName)
end
if GetSpecialization() == 1 then
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.resourceBar)
if TRB.Data.settings.warrior.arms.textures.textureLock then
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.castingBar)
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.passiveBar)
end
end
CloseDropDownMenus()
end
-- Create the dropdown, and configure its appearance
controls.dropDown.castingBarTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_CastBarTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.castingBarTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Casting Bar Texture", xCoord2, yCoord)
controls.dropDown.castingBarTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.castingBarTexture:SetPoint("TOPLEFT", xCoord2, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.castingBarTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, TRB.Data.settings.warrior.arms.textures.castingBarName)
UIDropDownMenu_JustifyText(controls.dropDown.castingBarTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.castingBarTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("statusbar")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("statusbar")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Status Bar Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.arms.textures.castingBar
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.castingBarTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.textures.castingBar = newValue
TRB.Data.settings.warrior.arms.textures.castingBarName = newName
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.castingBar)
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, newName)
if TRB.Data.settings.warrior.arms.textures.textureLock then
TRB.Data.settings.warrior.arms.textures.resourceBar = newValue
TRB.Data.settings.warrior.arms.textures.resourceBarName = newName
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.resourceBar)
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, newName)
TRB.Data.settings.warrior.arms.textures.passiveBar = newValue
TRB.Data.settings.warrior.arms.textures.passiveBarName = newName
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.passiveBar)
UIDropDownMenu_SetText(controls.dropDown.passiveBarTexture, newName)
end
if GetSpecialization() == 1 then
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.castingBar)
if TRB.Data.settings.warrior.arms.textures.textureLock then
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.resourceBar)
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.passiveBar)
end
end
CloseDropDownMenus()
end
yCoord = yCoord - 60
-- Create the dropdown, and configure its appearance
controls.dropDown.passiveBarTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_PassiveBarTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.passiveBarTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Passive Bar Texture", xCoord, yCoord)
controls.dropDown.passiveBarTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.passiveBarTexture:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.passiveBarTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.passiveBarTexture, TRB.Data.settings.warrior.arms.textures.passiveBarName)
UIDropDownMenu_JustifyText(controls.dropDown.passiveBarTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.passiveBarTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("statusbar")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("statusbar")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Status Bar Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.arms.textures.passiveBar
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.passiveBarTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.textures.passiveBar = newValue
TRB.Data.settings.warrior.arms.textures.passiveBarName = newName
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.passiveBar)
UIDropDownMenu_SetText(controls.dropDown.passiveBarTexture, newName)
if TRB.Data.settings.warrior.arms.textures.textureLock then
TRB.Data.settings.warrior.arms.textures.resourceBar = newValue
TRB.Data.settings.warrior.arms.textures.resourceBarName = newName
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.resourceBar)
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, newName)
TRB.Data.settings.warrior.arms.textures.castingBar = newValue
TRB.Data.settings.warrior.arms.textures.castingBarName = newName
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.castingBar)
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, newName)
end
if GetSpecialization() == 1 then
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.passiveBar)
if TRB.Data.settings.warrior.arms.textures.textureLock then
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.resourceBar)
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.castingBar)
end
end
CloseDropDownMenus()
end
controls.checkBoxes.textureLock = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_CB1_TEXTURE1", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.textureLock
f:SetPoint("TOPLEFT", xCoord2, yCoord-30)
getglobal(f:GetName() .. 'Text'):SetText("Use the same texture for all bars")
f.tooltip = "This will lock the texture for each part of the bar to be the same."
f:SetChecked(TRB.Data.settings.warrior.arms.textures.textureLock)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.textures.textureLock = self:GetChecked()
if TRB.Data.settings.warrior.arms.textures.textureLock then
TRB.Data.settings.warrior.arms.textures.passiveBar = TRB.Data.settings.warrior.arms.textures.resourceBar
TRB.Data.settings.warrior.arms.textures.passiveBarName = TRB.Data.settings.warrior.arms.textures.resourceBarName
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, TRB.Data.settings.warrior.arms.textures.passiveBarName)
TRB.Data.settings.warrior.arms.textures.castingBar = TRB.Data.settings.warrior.arms.textures.resourceBar
TRB.Data.settings.warrior.arms.textures.castingBarName = TRB.Data.settings.warrior.arms.textures.resourceBarName
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, TRB.Data.settings.warrior.arms.textures.castingBarName)
if GetSpecialization() == 1 then
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.passiveBar)
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.arms.textures.castingBar)
end
end
end)
yCoord = yCoord - 60
-- Create the dropdown, and configure its appearance
controls.dropDown.borderTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_BorderTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.borderTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Border Texture", xCoord, yCoord)
controls.dropDown.borderTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.borderTexture:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.borderTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.borderTexture, TRB.Data.settings.warrior.arms.textures.borderName)
UIDropDownMenu_JustifyText(controls.dropDown.borderTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.borderTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("border")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("border")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Border Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.arms.textures.border
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.borderTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.textures.border = newValue
TRB.Data.settings.warrior.arms.textures.borderName = newName
if GetSpecialization() == 1 then
if TRB.Data.settings.warrior.arms.bar.border < 1 then
barBorderFrame:SetBackdrop({ })
else
barBorderFrame:SetBackdrop({ edgeFile = TRB.Data.settings.warrior.arms.textures.border,
tile = true,
tileSize=4,
edgeSize=TRB.Data.settings.warrior.arms.bar.border,
insets = {0, 0, 0, 0}
})
end
barBorderFrame:SetBackdropColor(0, 0, 0, 0)
barBorderFrame:SetBackdropBorderColor (TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.bar.border, true))
end
UIDropDownMenu_SetText(controls.dropDown.borderTexture, newName)
CloseDropDownMenus()
end
-- Create the dropdown, and configure its appearance
controls.dropDown.backgroundTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_BackgroundTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.backgroundTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Background (Empty Bar) Texture", xCoord2, yCoord)
controls.dropDown.backgroundTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.backgroundTexture:SetPoint("TOPLEFT", xCoord2, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.backgroundTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.backgroundTexture, TRB.Data.settings.warrior.arms.textures.backgroundName)
UIDropDownMenu_JustifyText(controls.dropDown.backgroundTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.backgroundTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("background")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("background")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Background Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.arms.textures.background
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.backgroundTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.textures.background = newValue
TRB.Data.settings.warrior.arms.textures.backgroundName = newName
if GetSpecialization() == 1 then
barContainerFrame:SetBackdrop({
bgFile = TRB.Data.settings.warrior.arms.textures.background,
tile = true,
tileSize = TRB.Data.settings.warrior.arms.bar.width,
edgeSize = 1,
insets = {0, 0, 0, 0}
})
barContainerFrame:SetBackdropColor (TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.bar.background, true))
end
UIDropDownMenu_SetText(controls.dropDown.backgroundTexture, newName)
CloseDropDownMenus()
end
yCoord = yCoord - 70
controls.barDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Display", 0, yCoord)
yCoord = yCoord - 30
controls.checkBoxes.alwaysShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_RB1_2", parent, "UIRadioButtonTemplate")
f = controls.checkBoxes.alwaysShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Always show Resource Bar")
getglobal(f:GetName() .. 'Text'):SetFontObject(GameFontHighlight)
f.tooltip = "This will make the Resource Bar always visible on your UI, even when out of combat."
f:SetChecked(TRB.Data.settings.warrior.arms.displayBar.alwaysShow)
f:SetScript("OnClick", function(self, ...)
controls.checkBoxes.alwaysShow:SetChecked(true)
controls.checkBoxes.notZeroShow:SetChecked(false)
controls.checkBoxes.combatShow:SetChecked(false)
controls.checkBoxes.neverShow:SetChecked(false)
TRB.Data.settings.warrior.arms.displayBar.alwaysShow = true
TRB.Data.settings.warrior.arms.displayBar.notZeroShow = false
TRB.Data.settings.warrior.arms.displayBar.neverShow = false
TRB.Functions.HideResourceBar()
end)
controls.checkBoxes.notZeroShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_RB1_3", parent, "UIRadioButtonTemplate")
f = controls.checkBoxes.notZeroShow
f:SetPoint("TOPLEFT", xCoord, yCoord-15)
getglobal(f:GetName() .. 'Text'):SetText("Show Resource Bar when Rage > 0")
getglobal(f:GetName() .. 'Text'):SetFontObject(GameFontHighlight)
f.tooltip = "This will make the Resource Bar show out of combat only if Rage > 0, hidden otherwise when out of combat."
f:SetChecked(TRB.Data.settings.warrior.arms.displayBar.notZeroShow)
f:SetScript("OnClick", function(self, ...)
controls.checkBoxes.alwaysShow:SetChecked(false)
controls.checkBoxes.notZeroShow:SetChecked(true)
controls.checkBoxes.combatShow:SetChecked(false)
controls.checkBoxes.neverShow:SetChecked(false)
TRB.Data.settings.warrior.arms.displayBar.alwaysShow = false
TRB.Data.settings.warrior.arms.displayBar.notZeroShow = true
TRB.Data.settings.warrior.arms.displayBar.neverShow = false
TRB.Functions.HideResourceBar()
end)
controls.checkBoxes.combatShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_RB1_4", parent, "UIRadioButtonTemplate")
f = controls.checkBoxes.combatShow
f:SetPoint("TOPLEFT", xCoord, yCoord-30)
getglobal(f:GetName() .. 'Text'):SetText("Only show Resource Bar in combat")
getglobal(f:GetName() .. 'Text'):SetFontObject(GameFontHighlight)
f.tooltip = "This will make the Resource Bar only be visible on your UI when in combat."
f:SetChecked((not TRB.Data.settings.warrior.arms.displayBar.alwaysShow) and (not TRB.Data.settings.warrior.arms.displayBar.notZeroShow))
f:SetScript("OnClick", function(self, ...)
controls.checkBoxes.alwaysShow:SetChecked(false)
controls.checkBoxes.notZeroShow:SetChecked(false)
controls.checkBoxes.combatShow:SetChecked(true)
controls.checkBoxes.neverShow:SetChecked(false)
TRB.Data.settings.warrior.arms.displayBar.alwaysShow = false
TRB.Data.settings.warrior.arms.displayBar.notZeroShow = false
TRB.Data.settings.warrior.arms.displayBar.neverShow = false
TRB.Functions.HideResourceBar()
end)
controls.checkBoxes.neverShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_RB1_5", parent, "UIRadioButtonTemplate")
f = controls.checkBoxes.neverShow
f:SetPoint("TOPLEFT", xCoord, yCoord-45)
getglobal(f:GetName() .. 'Text'):SetText("Never show Resource Bar (run in background)")
getglobal(f:GetName() .. 'Text'):SetFontObject(GameFontHighlight)
f.tooltip = "This will make the Resource Bar never display but still run in the background to update the global variable."
f:SetChecked(TRB.Data.settings.warrior.arms.displayBar.neverShow)
f:SetScript("OnClick", function(self, ...)
controls.checkBoxes.alwaysShow:SetChecked(false)
controls.checkBoxes.notZeroShow:SetChecked(false)
controls.checkBoxes.combatShow:SetChecked(false)
controls.checkBoxes.neverShow:SetChecked(true)
TRB.Data.settings.warrior.arms.displayBar.alwaysShow = false
TRB.Data.settings.warrior.arms.displayBar.notZeroShow = false
TRB.Data.settings.warrior.arms.displayBar.neverShow = true
TRB.Functions.HideResourceBar()
end)
controls.checkBoxes.showCastingBar = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_showCastingBar", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.showCastingBar
f:SetPoint("TOPLEFT", xCoord2, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Show casting bar")
f.tooltip = "This will show the casting bar when Bladestorm is being channeled. Uncheck to hide this bar."
f:SetChecked(TRB.Data.settings.warrior.fury.bar.showCasting)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.bar.showCasting = self:GetChecked()
end)
controls.checkBoxes.showPassiveBar = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_showPassiveBar", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.showPassiveBar
f:SetPoint("TOPLEFT", xCoord2, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Show passive bar")
f.tooltip = "This will show the passive bar. Uncheck to hide this bar. This setting supercedes any other passive tracking options!"
f:SetChecked(TRB.Data.settings.warrior.arms.bar.showPassive)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.bar.showPassive = self:GetChecked()
end)
yCoord = yCoord - 60
controls.barColorsSection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Colors", 0, yCoord)
yCoord = yCoord - 30
controls.colors.base = TRB.UiFunctions.BuildColorPicker(parent, "Rage", TRB.Data.settings.warrior.arms.colors.bar.base, 300, 25, xCoord, yCoord)
f = controls.colors.base
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.bar.base, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.base.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.bar.base = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.border = TRB.UiFunctions.BuildColorPicker(parent, "Resource Bar's border", TRB.Data.settings.warrior.arms.colors.bar.border, 225, 25, xCoord2, yCoord)
f = controls.colors.border
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.bar.border, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.border.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.bar.border = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
barBorderFrame:SetBackdropBorderColor(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 30
controls.colors.passive = TRB.UiFunctions.BuildColorPicker(parent, "Rage gain from Passive Sources", TRB.Data.settings.warrior.arms.colors.bar.passive, 275, 25, xCoord, yCoord)
f = controls.colors.passive
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.bar.passive, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.passive.Texture:SetColorTexture(r, g, b, 1-a)
passiveFrame:SetStatusBarColor(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.bar.passive = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.borderOvercap = TRB.UiFunctions.BuildColorPicker(parent, "Bar border color when you are overcapping Rage", TRB.Data.settings.warrior.arms.colors.bar.borderOvercap, 275, 25, xCoord2, yCoord)
f = controls.colors.borderOvercap
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.bar.borderOvercap, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.borderOvercap.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.bar.borderOvercap = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 30
controls.colors.background = TRB.UiFunctions.BuildColorPicker(parent, "Unfilled bar background", TRB.Data.settings.warrior.arms.colors.bar.background, 275, 25, xCoord2, yCoord)
f = controls.colors.background
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.bar.background, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.background.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.bar.background = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
barContainerFrame:SetBackdropColor(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 40
controls.barColorsSection = TRB.UiFunctions.BuildSectionHeader(parent, "Ability Threshold Lines", 0, yCoord)
yCoord = yCoord - 25
controls.colors.thresholdUnder = TRB.UiFunctions.BuildColorPicker(parent, "Under minimum required Rage threshold line", TRB.Data.settings.warrior.arms.colors.threshold.under, 275, 25, xCoord2, yCoord)
f = controls.colors.thresholdUnder
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.threshold.under, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.thresholdUnder.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.threshold.under = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.thresholdOver = TRB.UiFunctions.BuildColorPicker(parent, "Over minimum required Rage threshold line", TRB.Data.settings.warrior.arms.colors.threshold.over, 275, 25, xCoord2, yCoord-30)
f = controls.colors.thresholdOver
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.threshold.over, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.thresholdOver.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.threshold.over = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.thresholdUnusable = TRB.UiFunctions.BuildColorPicker(parent, "Ability is unusable threshold line", TRB.Data.settings.warrior.arms.colors.threshold.unusable, 275, 25, xCoord2, yCoord-60)
f = controls.colors.thresholdUnusable
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.threshold.unusable, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.thresholdUnusable.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.threshold.unusable = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.checkBoxes.thresholdOverlapBorder = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_thresholdOverlapBorder", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.thresholdOverlapBorder
f:SetPoint("TOPLEFT", xCoord2, yCoord-90)
getglobal(f:GetName() .. 'Text'):SetText("Threshold lines overlap bar border?")
f.tooltip = "When checked, threshold lines will span the full height of the bar and overlap the bar border."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.overlapBorder)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.overlapBorder = self:GetChecked()
TRB.Functions.RedrawThresholdLines(TRB.Data.settings.warrior.arms)
end)
controls.checkBoxes.cleaveThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_Threshold_Option_cleave", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.cleaveThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Cleave (if talented)")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Cleave. Only visible if talented."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.cleave.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.cleave.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.executeThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_Threshold_Option_execute", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.executeThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Execute / Condemn (if |cFFFF4040Venthyr|r)")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Execute or Condemn (if |cFFFF4040Venthyr|r). Only visible when the current target is in Execute health range or available from a Sudden Death proc. Will move along the bar between the current minimum and maximum Rage cost amounts."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.execute.enabled or TRB.Data.settings.warrior.arms.thresholds.condemn.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.execute.enabled = self:GetChecked()
TRB.Data.settings.warrior.arms.thresholds.condemn.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.ignorePainThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_Threshold_Option_ignorePain", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.ignorePainThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Ignore Pain")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Ignore Pain."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.ignorePain.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.ignorePain.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.impendingVictoryThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_Threshold_Option_impendingVictory", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.impendingVictoryThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Impending Victory (if talented)")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Impending Victory. Only visible if talented."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.impendingVictory.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.impendingVictory.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.mortalStrikeThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_Threshold_Option_mortalStrike", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.mortalStrikeThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Mortal Strike")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Mortal Strike."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.mortalStrike.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.mortalStrike.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.rendThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_Threshold_Option_rend", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.rendThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Rend (if talented)")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Rend. Only visible if talented."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.rend.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.rend.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.shieldBlockThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_Threshold_Option_shieldBlock", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.shieldBlockThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Shield Block")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Shield Block. This does not check to see if you have a shield equipped!"
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.shieldBlock.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.shieldBlock.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.slamThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_Threshold_Option_slam", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.slamThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Slam")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Slam."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.slam.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.slam.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.whirlwindThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_Threshold_Option_whirlwind", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.whirlwindThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Whirlwind")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Whirlwind."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.whirlwind.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.whirlwind.enabled = self:GetChecked()
end)
yCoord = yCoord - 40
-- Create the dropdown, and configure its appearance
controls.dropDown.thresholdIconRelativeTo = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_thresholdIconRelativeTo", parent, "UIDropDownMenuTemplate")
controls.dropDown.thresholdIconRelativeTo.label = TRB.UiFunctions.BuildSectionHeader(parent, "Relative Position of Threshold Line Icons", xCoord, yCoord)
controls.dropDown.thresholdIconRelativeTo.label.font:SetFontObject(GameFontNormal)
controls.dropDown.thresholdIconRelativeTo:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.thresholdIconRelativeTo, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.thresholdIconRelativeTo, TRB.Data.settings.warrior.arms.thresholds.icons.relativeToName)
UIDropDownMenu_JustifyText(controls.dropDown.thresholdIconRelativeTo, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.thresholdIconRelativeTo, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local relativeTo = {}
relativeTo["Above"] = "TOP"
relativeTo["Middle"] = "CENTER"
relativeTo["Below"] = "BOTTOM"
local relativeToList = {
"Above",
"Middle",
"Below"
}
for k, v in pairs(relativeToList) do
info.text = v
info.value = relativeTo[v]
info.checked = relativeTo[v] == TRB.Data.settings.warrior.arms.thresholds.icons.relativeTo
info.func = self.SetValue
info.arg1 = relativeTo[v]
info.arg2 = v
UIDropDownMenu_AddButton(info, level)
end
end)
function controls.dropDown.thresholdIconRelativeTo:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.thresholds.icons.relativeTo = newValue
TRB.Data.settings.warrior.arms.thresholds.icons.relativeToName = newName
if GetSpecialization() == 1 then
TRB.Functions.RedrawThresholdLines(TRB.Data.settings.warrior.arms)
end
UIDropDownMenu_SetText(controls.dropDown.thresholdIconRelativeTo, newName)
CloseDropDownMenus()
end
controls.checkBoxes.thresholdIconEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_thresholdIconEnabled", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.thresholdIconEnabled
f:SetPoint("TOPLEFT", xCoord2, yCoord-30)
getglobal(f:GetName() .. 'Text'):SetText("Show ability icons for threshold lines?")
f.tooltip = "When checked, icons for the threshold each line represents will be displayed. Configuration of size and location of these icons is below."
f:SetChecked(TRB.Data.settings.warrior.arms.thresholds.icons.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.thresholds.icons.enabled = self:GetChecked()
if GetSpecialization() == 1 then
TRB.Functions.RedrawThresholdLines(TRB.Data.settings.warrior.arms)
end
end)
yCoord = yCoord - 80
title = "Threshold Icon Width"
controls.thresholdIconWidth = TRB.UiFunctions.BuildSlider(parent, title, 1, 128, TRB.Data.settings.warrior.arms.thresholds.icons.width, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.thresholdIconWidth:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.thresholds.icons.width = value
local maxBorderSize = math.min(math.floor(TRB.Data.settings.warrior.arms.thresholds.icons.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.arms.thresholds.icons.width / TRB.Data.constants.borderWidthFactor))
local borderSize = TRB.Data.settings.warrior.arms.thresholds.icons.border
if maxBorderSize < borderSize then
maxBorderSize = borderSize
end
controls.thresholdIconBorderWidth:SetMinMaxValues(0, maxBorderSize)
controls.thresholdIconBorderWidth.MaxLabel:SetText(maxBorderSize)
controls.thresholdIconBorderWidth.EditBox:SetText(borderSize)
end)
title = "Threshold Icon Height"
controls.thresholdIconHeight = TRB.UiFunctions.BuildSlider(parent, title, 1, 128, TRB.Data.settings.warrior.arms.thresholds.icons.height, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.thresholdIconHeight:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.thresholds.icons.height = value
local maxBorderSize = math.min(math.floor(TRB.Data.settings.warrior.arms.thresholds.icons.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.arms.thresholds.icons.width / TRB.Data.constants.borderWidthFactor))
local borderSize = TRB.Data.settings.warrior.arms.thresholds.icons.border
if maxBorderSize < borderSize then
maxBorderSize = borderSize
end
controls.thresholdIconBorderWidth:SetMinMaxValues(0, maxBorderSize)
controls.thresholdIconBorderWidth.MaxLabel:SetText(maxBorderSize)
controls.thresholdIconBorderWidth.EditBox:SetText(borderSize)
end)
title = "Threshold Icon Horizontal Position (Relative)"
yCoord = yCoord - 60
controls.thresholdIconHorizontal = TRB.UiFunctions.BuildSlider(parent, title, math.ceil(-sanityCheckValues.barMaxWidth/2), math.floor(sanityCheckValues.barMaxWidth/2), TRB.Data.settings.warrior.arms.thresholds.icons.xPos, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.thresholdIconHorizontal:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.thresholds.icons.xPos = value
if GetSpecialization() == 1 then
TRB.Functions.RepositionBar(TRB.Data.settings.warrior.arms, TRB.Frames.barContainerFrame)
end
end)
title = "Threshold Icon Vertical Position (Relative)"
controls.thresholdIconVertical = TRB.UiFunctions.BuildSlider(parent, title, math.ceil(-sanityCheckValues.barMaxHeight/2), math.floor(sanityCheckValues.barMaxHeight/2), TRB.Data.settings.warrior.arms.thresholds.icons.yPos, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.thresholdIconVertical:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.thresholds.icons.yPos = value
end)
local maxIconBorderHeight = math.min(math.floor(TRB.Data.settings.warrior.arms.thresholds.icons.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.arms.thresholds.icons.width / TRB.Data.constants.borderWidthFactor))
title = "Threshold Icon Border Width"
yCoord = yCoord - 60
controls.thresholdIconBorderWidth = TRB.UiFunctions.BuildSlider(parent, title, 0, maxIconBorderHeight, TRB.Data.settings.warrior.arms.thresholds.icons.border, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.thresholdIconBorderWidth:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.thresholds.icons.border = value
local minsliderWidth = math.max(TRB.Data.settings.warrior.arms.thresholds.icons.border*2, 1)
local minsliderHeight = math.max(TRB.Data.settings.warrior.arms.thresholds.icons.border*2, 1)
controls.thresholdIconHeight:SetMinMaxValues(minsliderHeight, 128)
controls.thresholdIconHeight.MinLabel:SetText(minsliderHeight)
controls.thresholdIconWidth:SetMinMaxValues(minsliderWidth, 128)
controls.thresholdIconWidth.MinLabel:SetText(minsliderWidth)
if GetSpecialization() == 1 then
TRB.Functions.RedrawThresholdLines(TRB.Data.settings.warrior.arms)
end
end)
yCoord = yCoord - 60
controls.textSection = TRB.UiFunctions.BuildSectionHeader(parent, "Overcapping Configuration", 0, yCoord)
yCoord = yCoord - 30
controls.checkBoxes.overcapEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_CB1_8", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.overcapEnabled
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Change border color when overcapping")
f.tooltip = "This will change the bar's border color when your current hardcast spell will result in overcapping maximum Rage. Setting accepts values up to 130 to accomidate the Deadly Calm talent."
f:SetChecked(TRB.Data.settings.warrior.arms.colors.bar.overcapEnabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.colors.bar.overcapEnabled = self:GetChecked()
end)
yCoord = yCoord - 40
title = "Show Overcap Notification Above"
controls.overcapAt = TRB.UiFunctions.BuildSlider(parent, title, 0, 130, TRB.Data.settings.warrior.arms.overcapThreshold, 1, 1,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.overcapAt:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
value = TRB.Functions.RoundTo(value, 1)
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.overcapThreshold = value
end)
TRB.Frames.interfaceSettingsFrameContainer.controls.arms = controls
end
local function ArmsConstructFontAndTextPanel(parent)
if parent == nil then
return
end
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local controls = interfaceSettingsFrame.controls.arms
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
local title = ""
local dropdownWidth = 225
local sliderWidth = 260
local sliderHeight = 20
controls.buttons.exportButton_Warrior_Arms_FontAndText = TRB.UiFunctions.BuildButton(parent, "Export Font & Text", 325, yCoord-5, 225, 20)
controls.buttons.exportButton_Warrior_Arms_FontAndText:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Arms Warrior (Font & Text).", 1, 1, false, true, false, false, false)
end)
controls.textDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Font Face", 0, yCoord)
yCoord = yCoord - 30
-- Create the dropdown, and configure its appearance
controls.dropDown.fontLeft = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_FontLeft", parent, "UIDropDownMenuTemplate")
controls.dropDown.fontLeft.label = TRB.UiFunctions.BuildSectionHeader(parent, "Left Bar Font Face", xCoord, yCoord)
controls.dropDown.fontLeft.label.font:SetFontObject(GameFontNormal)
controls.dropDown.fontLeft:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.fontLeft, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.fontLeft, TRB.Data.settings.warrior.arms.displayText.left.fontFaceName)
UIDropDownMenu_JustifyText(controls.dropDown.fontLeft, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.fontLeft, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local fonts = TRB.Details.addonData.libs.SharedMedia:HashTable("font")
local fontsList = TRB.Details.addonData.libs.SharedMedia:List("font")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(fonts) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Fonts " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(fontsList) do
if k > start and k <= start + entries then
info.text = v
info.value = fonts[v]
info.checked = fonts[v] == TRB.Data.settings.warrior.arms.displayText.left.fontFace
info.func = self.SetValue
info.arg1 = fonts[v]
info.arg2 = v
info.fontObject = CreateFont(v)
info.fontObject:SetFont(fonts[v], 12, "OUTLINE")
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
function controls.dropDown.fontLeft:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.displayText.left.fontFace = newValue
TRB.Data.settings.warrior.arms.displayText.left.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontLeft, newName)
if TRB.Data.settings.warrior.arms.displayText.fontFaceLock then
TRB.Data.settings.warrior.arms.displayText.middle.fontFace = newValue
TRB.Data.settings.warrior.arms.displayText.middle.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, newName)
TRB.Data.settings.warrior.arms.displayText.right.fontFace = newValue
TRB.Data.settings.warrior.arms.displayText.right.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontRight, newName)
end
if GetSpecialization() == 1 then
leftTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.left.fontFace, TRB.Data.settings.warrior.arms.displayText.left.fontSize, "OUTLINE")
if TRB.Data.settings.warrior.arms.displayText.fontFaceLock then
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.middle.fontFace, TRB.Data.settings.warrior.arms.displayText.middle.fontSize, "OUTLINE")
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.right.fontFace, TRB.Data.settings.warrior.arms.displayText.right.fontSize, "OUTLINE")
end
end
CloseDropDownMenus()
end
-- Create the dropdown, and configure its appearance
controls.dropDown.fontMiddle = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_FontMiddle", parent, "UIDropDownMenuTemplate")
controls.dropDown.fontMiddle.label = TRB.UiFunctions.BuildSectionHeader(parent, "Middle Bar Font Face", xCoord2, yCoord)
controls.dropDown.fontMiddle.label.font:SetFontObject(GameFontNormal)
controls.dropDown.fontMiddle:SetPoint("TOPLEFT", xCoord2, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.fontMiddle, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, TRB.Data.settings.warrior.arms.displayText.middle.fontFaceName)
UIDropDownMenu_JustifyText(controls.dropDown.fontMiddle, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.fontMiddle, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local fonts = TRB.Details.addonData.libs.SharedMedia:HashTable("font")
local fontsList = TRB.Details.addonData.libs.SharedMedia:List("font")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(fonts) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Fonts " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(fontsList) do
if k > start and k <= start + entries then
info.text = v
info.value = fonts[v]
info.checked = fonts[v] == TRB.Data.settings.warrior.arms.displayText.middle.fontFace
info.func = self.SetValue
info.arg1 = fonts[v]
info.arg2 = v
info.fontObject = CreateFont(v)
info.fontObject:SetFont(fonts[v], 12, "OUTLINE")
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
function controls.dropDown.fontMiddle:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.displayText.middle.fontFace = newValue
TRB.Data.settings.warrior.arms.displayText.middle.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, newName)
if TRB.Data.settings.warrior.arms.displayText.fontFaceLock then
TRB.Data.settings.warrior.arms.displayText.left.fontFace = newValue
TRB.Data.settings.warrior.arms.displayText.left.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontLeft, newName)
TRB.Data.settings.warrior.arms.displayText.right.fontFace = newValue
TRB.Data.settings.warrior.arms.displayText.right.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontRight, newName)
end
if GetSpecialization() == 1 then
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.middle.fontFace, TRB.Data.settings.warrior.arms.displayText.middle.fontSize, "OUTLINE")
if TRB.Data.settings.warrior.arms.displayText.fontFaceLock then
leftTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.left.fontFace, TRB.Data.settings.warrior.arms.displayText.left.fontSize, "OUTLINE")
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.right.fontFace, TRB.Data.settings.warrior.arms.displayText.right.fontSize, "OUTLINE")
end
end
CloseDropDownMenus()
end
yCoord = yCoord - 40 - 20
-- Create the dropdown, and configure its appearance
controls.dropDown.fontRight = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_FontRight", parent, "UIDropDownMenuTemplate")
controls.dropDown.fontRight.label = TRB.UiFunctions.BuildSectionHeader(parent, "Right Bar Font Face", xCoord, yCoord)
controls.dropDown.fontRight.label.font:SetFontObject(GameFontNormal)
controls.dropDown.fontRight:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.fontRight, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.fontRight, TRB.Data.settings.warrior.arms.displayText.right.fontFaceName)
UIDropDownMenu_JustifyText(controls.dropDown.fontRight, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.fontRight, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local fonts = TRB.Details.addonData.libs.SharedMedia:HashTable("font")
local fontsList = TRB.Details.addonData.libs.SharedMedia:List("font")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(fonts) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Fonts " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(fontsList) do
if k > start and k <= start + entries then
info.text = v
info.value = fonts[v]
info.checked = fonts[v] == TRB.Data.settings.warrior.arms.displayText.right.fontFace
info.func = self.SetValue
info.arg1 = fonts[v]
info.arg2 = v
info.fontObject = CreateFont(v)
info.fontObject:SetFont(fonts[v], 12, "OUTLINE")
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
function controls.dropDown.fontRight:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.displayText.right.fontFace = newValue
TRB.Data.settings.warrior.arms.displayText.right.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontRight, newName)
if TRB.Data.settings.warrior.arms.displayText.fontFaceLock then
TRB.Data.settings.warrior.arms.displayText.left.fontFace = newValue
TRB.Data.settings.warrior.arms.displayText.left.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontLeft, newName)
TRB.Data.settings.warrior.arms.displayText.middle.fontFace = newValue
TRB.Data.settings.warrior.arms.displayText.middle.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, newName)
end
if GetSpecialization() == 1 then
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.right.fontFace, TRB.Data.settings.warrior.arms.displayText.right.fontSize, "OUTLINE")
if TRB.Data.settings.warrior.arms.displayText.fontFaceLock then
leftTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.left.fontFace, TRB.Data.settings.warrior.arms.displayText.left.fontSize, "OUTLINE")
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.middle.fontFace, TRB.Data.settings.warrior.arms.displayText.middle.fontSize, "OUTLINE")
end
end
CloseDropDownMenus()
end
controls.checkBoxes.fontFaceLock = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_CB1_FONTFACE1", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.fontFaceLock
f:SetPoint("TOPLEFT", xCoord2, yCoord-30)
getglobal(f:GetName() .. 'Text'):SetText("Use the same font face for all text")
f.tooltip = "This will lock the font face for text for each part of the bar to be the same."
f:SetChecked(TRB.Data.settings.warrior.arms.displayText.fontFaceLock)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.displayText.fontFaceLock = self:GetChecked()
if TRB.Data.settings.warrior.arms.displayText.fontFaceLock then
TRB.Data.settings.warrior.arms.displayText.middle.fontFace = TRB.Data.settings.warrior.arms.displayText.left.fontFace
TRB.Data.settings.warrior.arms.displayText.middle.fontFaceName = TRB.Data.settings.warrior.arms.displayText.left.fontFaceName
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, TRB.Data.settings.warrior.arms.displayText.middle.fontFaceName)
TRB.Data.settings.warrior.arms.displayText.right.fontFace = TRB.Data.settings.warrior.arms.displayText.left.fontFace
TRB.Data.settings.warrior.arms.displayText.right.fontFaceName = TRB.Data.settings.warrior.arms.displayText.left.fontFaceName
UIDropDownMenu_SetText(controls.dropDown.fontRight, TRB.Data.settings.warrior.arms.displayText.right.fontFaceName)
if GetSpecialization() == 1 then
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.middle.fontFace, TRB.Data.settings.warrior.arms.displayText.middle.fontSize, "OUTLINE")
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.right.fontFace, TRB.Data.settings.warrior.arms.displayText.right.fontSize, "OUTLINE")
end
end
end)
yCoord = yCoord - 70
controls.textDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Font Size and Colors", 0, yCoord)
title = "Left Bar Text Font Size"
yCoord = yCoord - 50
controls.fontSizeLeft = TRB.UiFunctions.BuildSlider(parent, title, 6, 72, TRB.Data.settings.warrior.arms.displayText.left.fontSize, 1, 0,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.fontSizeLeft:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.displayText.left.fontSize = value
if GetSpecialization() == 1 then
leftTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.left.fontFace, TRB.Data.settings.warrior.arms.displayText.left.fontSize, "OUTLINE")
end
if TRB.Data.settings.warrior.arms.displayText.fontSizeLock then
controls.fontSizeMiddle:SetValue(value)
controls.fontSizeRight:SetValue(value)
end
end)
controls.checkBoxes.fontSizeLock = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_CB2_F1", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.fontSizeLock
f:SetPoint("TOPLEFT", xCoord2, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Use the same font size for all text")
f.tooltip = "This will lock the font sizes for each part of the bar to be the same size."
f:SetChecked(TRB.Data.settings.warrior.arms.displayText.fontSizeLock)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.displayText.fontSizeLock = self:GetChecked()
if TRB.Data.settings.warrior.arms.displayText.fontSizeLock then
controls.fontSizeMiddle:SetValue(TRB.Data.settings.warrior.arms.displayText.left.fontSize)
controls.fontSizeRight:SetValue(TRB.Data.settings.warrior.arms.displayText.left.fontSize)
end
end)
controls.colors.leftText = TRB.UiFunctions.BuildColorPicker(parent, "Left Text", TRB.Data.settings.warrior.arms.colors.text.left,
250, 25, xCoord2, yCoord-30)
f = controls.colors.leftText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.left, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.leftText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.left = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.middleText = TRB.UiFunctions.BuildColorPicker(parent, "Middle Text", TRB.Data.settings.warrior.arms.colors.text.middle,
225, 25, xCoord2, yCoord-70)
f = controls.colors.middleText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.middle, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.middleText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.middle = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.rightText = TRB.UiFunctions.BuildColorPicker(parent, "Right Text", TRB.Data.settings.warrior.arms.colors.text.right,
225, 25, xCoord2, yCoord-110)
f = controls.colors.rightText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.right, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.rightText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.right = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
title = "Middle Bar Text Font Size"
yCoord = yCoord - 60
controls.fontSizeMiddle = TRB.UiFunctions.BuildSlider(parent, title, 6, 72, TRB.Data.settings.warrior.arms.displayText.middle.fontSize, 1, 0,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.fontSizeMiddle:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.displayText.middle.fontSize = value
if GetSpecialization() == 1 then
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.middle.fontFace, TRB.Data.settings.warrior.arms.displayText.middle.fontSize, "OUTLINE")
end
if TRB.Data.settings.warrior.arms.displayText.fontSizeLock then
controls.fontSizeLeft:SetValue(value)
controls.fontSizeRight:SetValue(value)
end
end)
title = "Right Bar Text Font Size"
yCoord = yCoord - 60
controls.fontSizeRight = TRB.UiFunctions.BuildSlider(parent, title, 6, 72, TRB.Data.settings.warrior.arms.displayText.right.fontSize, 1, 0,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.fontSizeRight:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.displayText.right.fontSize = value
if GetSpecialization() == 1 then
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.arms.displayText.right.fontFace, TRB.Data.settings.warrior.arms.displayText.right.fontSize, "OUTLINE")
end
if TRB.Data.settings.warrior.arms.displayText.fontSizeLock then
controls.fontSizeLeft:SetValue(value)
controls.fontSizeMiddle:SetValue(value)
end
end)
yCoord = yCoord - 40
controls.textDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Rage Text Colors", 0, yCoord)
yCoord = yCoord - 30
controls.colors.currentRageText = TRB.UiFunctions.BuildColorPicker(parent, "Current Rage", TRB.Data.settings.warrior.arms.colors.text.current, 300, 25, xCoord, yCoord)
f = controls.colors.currentRageText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.current, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.currentRageText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.current = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.passiveRageText = TRB.UiFunctions.BuildColorPicker(parent, "Passive Rage", TRB.Data.settings.warrior.arms.colors.text.passive, 275, 25, xCoord2, yCoord)
f = controls.colors.passiveRageText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.passive, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.passiveRageText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.passive = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 30
controls.colors.thresholdrageText = TRB.UiFunctions.BuildColorPicker(parent, "Have enough Rage to use any enabled threshold ability", TRB.Data.settings.warrior.arms.colors.text.overThreshold, 300, 25, xCoord, yCoord)
f = controls.colors.thresholdrageText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.overThreshold, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.thresholdrageText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.overThreshold = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.overcaprageText = TRB.UiFunctions.BuildColorPicker(parent, "Overcapping Rage", TRB.Data.settings.warrior.arms.colors.text.overcap, 300, 25, xCoord2, yCoord)
f = controls.colors.overcaprageText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.overcap, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.overcaprageText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.overcap = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 30
controls.checkBoxes.overThresholdEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_OverThresholdTextEnable", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.overThresholdEnabled
f:SetPoint("TOPLEFT", xCoord+xPadding, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Enabled?")
f.tooltip = "This will change the Rage text color when you are able to use an ability whose threshold you have enabled under 'Bar Display'."
f:SetChecked(TRB.Data.settings.warrior.arms.colors.text.overThresholdEnabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.colors.text.overThresholdEnabled = self:GetChecked()
end)
controls.checkBoxes.overcapTextEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_OvercapTextEnable", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.overcapTextEnabled
f:SetPoint("TOPLEFT", xCoord2+xPadding, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Enabled?")
f.tooltip = "This will change the Rage text color when your current hardcast spell will result in overcapping maximum Rage."
f:SetChecked(TRB.Data.settings.warrior.arms.colors.text.overcapEnabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.colors.text.overcapEnabled = self:GetChecked()
end)
yCoord = yCoord - 30
controls.dotColorSection = TRB.UiFunctions.BuildSectionHeader(parent, "DoT Count and Time Remaining Tracking", 0, yCoord)
yCoord = yCoord - 25
controls.checkBoxes.dotColor = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_dotColor", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.dotColor
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Change total DoT counter and DoT timer color based on DoT status?")
f.tooltip = "When checked, the color of total DoTs up counters and DoT timers ($deepWoundsCount, $rendCount) will change based on whether or not the DoT is on the current target."
f:SetChecked(TRB.Data.settings.warrior.arms.colors.text.dots.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.colors.text.dots.enabled = self:GetChecked()
end)
controls.colors.dotUp = TRB.UiFunctions.BuildColorPicker(parent, "DoT is active on current target", TRB.Data.settings.warrior.arms.colors.text.dots.up, 550, 25, xCoord, yCoord-30)
f = controls.colors.dotUp
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.dots.up, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.dotUp.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.dots.up = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.dotPandemic = TRB.UiFunctions.BuildColorPicker(parent, "DoT is active on current target but within Pandemic refresh range", TRB.Data.settings.warrior.arms.colors.text.dots.pandemic, 550, 25, xCoord, yCoord-60)
f = controls.colors.dotPandemic
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.dots.pandemic, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.dotPandemic.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.dots.pandemic = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.dotDown = TRB.UiFunctions.BuildColorPicker(parent, "DoT is not active on current target", TRB.Data.settings.warrior.arms.colors.text.dots.down, 550, 25, xCoord, yCoord-90)
f = controls.colors.dotDown
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.arms.colors.text.dots.down, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.dotDown.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.arms.colors.text.dots.down = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 130
controls.textDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Decimal Precision", 0, yCoord)
yCoord = yCoord - 50
title = "Haste / Crit / Mastery / Vers Decimal Precision"
controls.hastePrecision = TRB.UiFunctions.BuildSlider(parent, title, 0, 10, TRB.Data.settings.warrior.arms.hastePrecision, 1, 0,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.hastePrecision:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
value = TRB.Functions.RoundTo(value, 0)
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.hastePrecision = value
end)
title = "Rage Decimal Precision"
controls.astralPowerPrecision = TRB.UiFunctions.BuildSlider(parent, title, 0, 1, TRB.Data.settings.warrior.arms.ragePrecision, 1, 0,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.astralPowerPrecision:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
value = TRB.Functions.RoundTo(value, 0)
self.EditBox:SetText(value)
TRB.Data.settings.warrior.arms.ragePrecision = value
end)
TRB.Frames.interfaceSettingsFrameContainer.controls.arms = controls
end
local function ArmsConstructAudioAndTrackingPanel(parent)
if parent == nil then
return
end
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local controls = interfaceSettingsFrame.controls.arms
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
local title = ""
local dropdownWidth = 225
local sliderWidth = 260
local sliderHeight = 20
controls.buttons.exportButton_Warrior_Arms_AudioAndTracking = TRB.UiFunctions.BuildButton(parent, "Export Audio & Tracking", 325, yCoord-5, 225, 20)
controls.buttons.exportButton_Warrior_Arms_AudioAndTracking:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Arms Warrior (Audio & Tracking).", 1, 1, false, false, true, false, false)
end)
controls.textSection = TRB.UiFunctions.BuildSectionHeader(parent, "Audio Options", 0, yCoord)
yCoord = yCoord - 30
controls.checkBoxes.overcapAudio = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_CB3_OC_Sound", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.overcapAudio
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Play audio cue when you will overcap Rage")
f.tooltip = "Play an audio cue when your hardcast spell will overcap Rage."
f:SetChecked(TRB.Data.settings.warrior.arms.audio.overcap.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.audio.overcap.enabled = self:GetChecked()
if TRB.Data.settings.warrior.arms.audio.overcap.enabled then
PlaySoundFile(TRB.Data.settings.warrior.arms.audio.overcap.sound, TRB.Data.settings.core.audio.channel.channel)
end
end)
-- Create the dropdown, and configure its appearance
controls.dropDown.overcapAudio = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_overcapAudio", parent, "UIDropDownMenuTemplate")
controls.dropDown.overcapAudio:SetPoint("TOPLEFT", xCoord, yCoord-20)
UIDropDownMenu_SetWidth(controls.dropDown.overcapAudio, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.overcapAudio, TRB.Data.settings.warrior.arms.audio.overcap.soundName)
UIDropDownMenu_JustifyText(controls.dropDown.overcapAudio, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.overcapAudio, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local sounds = TRB.Details.addonData.libs.SharedMedia:HashTable("sound")
local soundsList = TRB.Details.addonData.libs.SharedMedia:List("sound")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(sounds) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Sounds " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(soundsList) do
if k > start and k <= start + entries then
info.text = v
info.value = sounds[v]
info.checked = sounds[v] == TRB.Data.settings.warrior.arms.audio.overcap.sound
info.func = self.SetValue
info.arg1 = sounds[v]
info.arg2 = v
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the audio
function controls.dropDown.overcapAudio:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.audio.overcap.sound = newValue
TRB.Data.settings.warrior.arms.audio.overcap.soundName = newName
UIDropDownMenu_SetText(controls.dropDown.overcapAudio, newName)
CloseDropDownMenus()
PlaySoundFile(TRB.Data.settings.warrior.arms.audio.overcap.sound, TRB.Data.settings.core.audio.channel.channel)
end
yCoord = yCoord - 60
controls.checkBoxes.suddenDeathAudio = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_suddenDeath_Sound_Checkbox", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.suddenDeathAudio
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Play audio cue when you get a Sudden Death proc (if talented)")
f.tooltip = "Play an audio cue when you get a Sudden Death proc that allows you to use Execute/Condemn for 0 Rage and above normal execute range enemy health."
f:SetChecked(TRB.Data.settings.warrior.arms.audio.suddenDeath.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.arms.audio.suddenDeath.enabled = self:GetChecked()
if TRB.Data.settings.warrior.arms.audio.suddenDeath.enabled then
PlaySoundFile(TRB.Data.settings.warrior.arms.audio.suddenDeath.sound, TRB.Data.settings.core.audio.channel.channel)
end
end)
-- Create the dropdown, and configure its appearance
controls.dropDown.suddenDeathAudio = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Arms_suddenDeath_Audio", parent, "UIDropDownMenuTemplate")
controls.dropDown.suddenDeathAudio:SetPoint("TOPLEFT", xCoord, yCoord-20)
UIDropDownMenu_SetWidth(controls.dropDown.suddenDeathAudio, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.suddenDeathAudio, TRB.Data.settings.warrior.arms.audio.suddenDeath.soundName)
UIDropDownMenu_JustifyText(controls.dropDown.suddenDeathAudio, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.suddenDeathAudio, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local sounds = TRB.Details.addonData.libs.SharedMedia:HashTable("sound")
local soundsList = TRB.Details.addonData.libs.SharedMedia:List("sound")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(sounds) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Sounds " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(soundsList) do
if k > start and k <= start + entries then
info.text = v
info.value = sounds[v]
info.checked = sounds[v] == TRB.Data.settings.warrior.arms.audio.suddenDeath.sound
info.func = self.SetValue
info.arg1 = sounds[v]
info.arg2 = v
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the audio
function controls.dropDown.overcapAudio:SetValue(newValue, newName)
TRB.Data.settings.warrior.arms.audio.suddenDeath.sound = newValue
TRB.Data.settings.warrior.arms.audio.suddenDeath.soundName = newName
UIDropDownMenu_SetText(controls.dropDown.overcapAudio, newName)
CloseDropDownMenus()
PlaySoundFile(TRB.Data.settings.warrior.arms.audio.suddenDeath.sound, TRB.Data.settings.core.audio.channel.channel)
end
TRB.Frames.interfaceSettingsFrameContainer.controls.arms = controls
end
local function ArmsConstructBarTextDisplayPanel(parent, cache)
if parent == nil then
return
end
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local controls = interfaceSettingsFrame.controls.arms
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
controls.buttons.exportButton_Warrior_Arms_BarText = TRB.UiFunctions.BuildButton(parent, "Export Bar Text", 325, yCoord-5, 225, 20)
controls.buttons.exportButton_Warrior_Arms_BarText:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Arms Warrior (Bar Text).", 1, 1, false, false, false, true, false)
end)
controls.textCustomSection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Display Text Customization", 0, yCoord)
yCoord = yCoord - 30
controls.labels.leftText = TRB.UiFunctions.BuildLabel(parent, "Left Text", xCoord, yCoord, 90, 20, nil, "RIGHT")
controls.textbox.left = TRB.UiFunctions.BuildTextBox(parent, TRB.Data.settings.warrior.arms.displayText.left.text,
500, 440, 24, xCoord+100, yCoord)
f = controls.textbox.left
f:SetScript("OnTextChanged", function(self, input)
TRB.Data.settings.warrior.arms.displayText.left.text = self:GetText()
TRB.Data.barTextCache = {}
TRB.Functions.IsTtdActive(TRB.Data.settings.warrior.arms)
end)
yCoord = yCoord - 30
controls.labels.middleText = TRB.UiFunctions.BuildLabel(parent, "Middle Text", xCoord, yCoord, 90, 20, nil, "RIGHT")
controls.textbox.middle = TRB.UiFunctions.BuildTextBox(parent, TRB.Data.settings.warrior.arms.displayText.middle.text,
500, 440, 24, xCoord+100, yCoord)
f = controls.textbox.middle
f:SetScript("OnTextChanged", function(self, input)
TRB.Data.settings.warrior.arms.displayText.middle.text = self:GetText()
TRB.Data.barTextCache = {}
TRB.Functions.IsTtdActive(TRB.Data.settings.warrior.arms)
end)
yCoord = yCoord - 30
controls.labels.rightText = TRB.UiFunctions.BuildLabel(parent, "Right Text", xCoord, yCoord, 90, 20, nil, "RIGHT")
controls.textbox.right = TRB.UiFunctions.BuildTextBox(parent, TRB.Data.settings.warrior.arms.displayText.right.text,
500, 440, 24, xCoord+100, yCoord)
f = controls.textbox.right
f:SetScript("OnTextChanged", function(self, input)
TRB.Data.settings.warrior.arms.displayText.right.text = self:GetText()
TRB.Data.barTextCache = {}
TRB.Functions.IsTtdActive(TRB.Data.settings.warrior.arms)
end)
yCoord = yCoord - 30
TRB.Options.CreateBarTextInstructions(cache, parent, xCoord, yCoord)
end
local function ArmsConstructOptionsPanel(cache)
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local parent = interfaceSettingsFrame.panel
local controls = interfaceSettingsFrame.controls.arms or {}
local yCoord = 0
local f = nil
local xPadding = 10
local xPadding2 = 30
local xMax = 550
local xCoord = 0
local xCoord2 = 325
local xOffset1 = 50
local xOffset2 = 275
controls.colors = {}
controls.labels = {}
controls.textbox = {}
controls.checkBoxes = {}
controls.dropDown = {}
interfaceSettingsFrame.armsDisplayPanel = CreateFrame("Frame", "TwintopResourceBar_Options_Warrior_Arms", UIParent)
interfaceSettingsFrame.armsDisplayPanel.name = "Arms Warrior"
---@diagnostic disable-next-line: undefined-field
interfaceSettingsFrame.armsDisplayPanel.parent = parent.name
InterfaceOptions_AddCategory(interfaceSettingsFrame.armsDisplayPanel)
parent = interfaceSettingsFrame.armsDisplayPanel
controls.buttons = controls.buttons or {}
controls.textSection = TRB.UiFunctions.BuildSectionHeader(parent, "Arms Warrior", xCoord+xPadding, yCoord-5)
controls.checkBoxes.armsWarriorEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Arms_armsWarriorEnabled", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.armsWarriorEnabled
f:SetPoint("TOPLEFT", 250, yCoord-10)
getglobal(f:GetName() .. 'Text'):SetText("Enabled")
f.tooltip = "Is Twintop's Resource Bar enabled for the Arms Warrior specialization? If unchecked, the bar will not function (including the population of global variables!)."
f:SetChecked(TRB.Data.settings.core.enabled.warrior.arms)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.core.enabled.warrior.arms = self:GetChecked()
TRB.Functions.EventRegistration()
TRB.UiFunctions.ToggleCheckboxOnOff(controls.checkBoxes.armsWarriorEnabled, TRB.Data.settings.core.enabled.warrior.arms, true)
end)
TRB.UiFunctions.ToggleCheckboxOnOff(controls.checkBoxes.armsWarriorEnabled, TRB.Data.settings.core.enabled.warrior.arms, true)
controls.buttons.importButton = TRB.UiFunctions.BuildButton(parent, "Import", 345, yCoord-10, 90, 20)
controls.buttons.importButton:SetFrameLevel(10000)
controls.buttons.importButton:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Import")
end)
controls.buttons.exportButton_Warrior_Arms_All = TRB.UiFunctions.BuildButton(parent, "Export Specialization", 440, yCoord-10, 150, 20)
controls.buttons.exportButton_Warrior_Arms_All:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Arms Warrior (All).", 1, 1, true, true, true, true, false)
end)
yCoord = yCoord - 42
local tabs = {}
local tabsheets = {}
tabs[1] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Arms_Tab2", "Bar Display", 1, parent, 85)
tabs[1]:SetPoint("TOPLEFT", 15, yCoord)
tabs[2] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Arms_Tab3", "Font & Text", 2, parent, 85, tabs[1])
tabs[3] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Arms_Tab4", "Audio & Tracking", 3, parent, 120, tabs[2])
tabs[4] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Arms_Tab5", "Bar Text", 4, parent, 60, tabs[3])
tabs[5] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Arms_Tab1", "Reset Defaults", 5, parent, 100, tabs[4])
PanelTemplates_TabResize(tabs[1], 0)
PanelTemplates_TabResize(tabs[2], 0)
PanelTemplates_TabResize(tabs[3], 0)
PanelTemplates_TabResize(tabs[4], 0)
PanelTemplates_TabResize(tabs[5], 0)
yCoord = yCoord - 15
for i = 1, 5 do
tabsheets[i] = TRB.UiFunctions.CreateTabFrameContainer("TwintopResourceBar_Warrior_Arms_LayoutPanel" .. i, parent)
tabsheets[i]:Hide()
tabsheets[i]:SetPoint("TOPLEFT", 10, yCoord)
end
tabsheets[1]:Show()
tabsheets[1].selected = true
tabs[1]:SetNormalFontObject(TRB.Options.fonts.options.tabHighlightSmall)
parent.tabs = tabs
parent.tabsheets = tabsheets
parent.lastTab = tabsheets[1]
parent.lastTabId = 1
TRB.Frames.interfaceSettingsFrameContainer = interfaceSettingsFrame
TRB.Frames.interfaceSettingsFrameContainer.controls.arms = controls
ArmsConstructBarColorsAndBehaviorPanel(tabsheets[1].scrollFrame.scrollChild)
ArmsConstructFontAndTextPanel(tabsheets[2].scrollFrame.scrollChild)
ArmsConstructAudioAndTrackingPanel(tabsheets[3].scrollFrame.scrollChild)
ArmsConstructBarTextDisplayPanel(tabsheets[4].scrollFrame.scrollChild, cache)
ArmsConstructResetDefaultsPanel(tabsheets[5].scrollFrame.scrollChild)
end
--[[
Fury Option Menus
]]
local function FuryConstructResetDefaultsPanel(parent)
if parent == nil then
return
end
local controls = TRB.Frames.interfaceSettingsFrameContainer.controls.fury
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
local title = ""
local dropdownWidth = 225
local sliderWidth = 260
local sliderHeight = 20
StaticPopupDialogs["TwintopResourceBar_Warrior_Fury_Reset"] = {
text = "Do you want to reset the Twintop's Resource Bar back to its default configuration? Only the Fury Warrior settings will be changed. This will cause your UI to be reloaded!",
button1 = "Yes",
button2 = "No",
OnAccept = function()
TRB.Data.settings.warrior.fury = FuryResetSettings()
ReloadUI()
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3
}
StaticPopupDialogs["TwintopResourceBar_Warrior_Fury_ResetBarTextSimple"] = {
text = "Do you want to reset Twintop's Resource Bar's text (including font size, font style, and text information) back to its default (simple) configuration? Only the Fury Warrior settings will be changed. This will cause your UI to be reloaded!",
button1 = "Yes",
button2 = "No",
OnAccept = function()
TRB.Data.settings.warrior.fury.displayText = FuryLoadDefaultBarTextSimpleSettings()
ReloadUI()
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3
}
StaticPopupDialogs["TwintopResourceBar_Warrior_Fury_ResetBarTextAdvanced"] = {
text = "Do you want to reset Twintop's Resource Bar's text (including font size, font style, and text information) back to its default (advanced) configuration? Only the Fury Warrior settings will be changed. This will cause your UI to be reloaded!",
button1 = "Yes",
button2 = "No",
OnAccept = function()
TRB.Data.settings.warrior.fury.displayText = FuryLoadDefaultBarTextAdvancedSettings()
ReloadUI()
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3
}
--[[StaticPopupDialogs["TwintopResourceBar_Warrior_Fury_ResetBarTextNarrowAdvanced"] = {
text = "Do you want to reset Twintop's Resource Bar's text (including font size, font style, and text information) back to its default (narrow advanced) configuration? Only the Fury Warrior settings will be changed. This will cause your UI to be reloaded!",
button1 = "Yes",
button2 = "No",
OnAccept = function()
TRB.Data.settings.warrior.fury.displayText = FuryLoadDefaultBarTextNarrowAdvancedSettings()
ReloadUI()
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3
}]]
controls.textCustomSection = TRB.UiFunctions.BuildSectionHeader(parent, "Reset Resource Bar to Defaults", 0, yCoord)
yCoord = yCoord - 30
controls.resetButton = TRB.UiFunctions.BuildButton(parent, "Reset to Defaults", xCoord, yCoord, 150, 30)
controls.resetButton:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Warrior_Fury_Reset")
end)
yCoord = yCoord - 40
controls.textCustomSection = TRB.UiFunctions.BuildSectionHeader(parent, "Reset Resource Bar Text", 0, yCoord)
yCoord = yCoord - 30
controls.resetButton1 = TRB.UiFunctions.BuildButton(parent, "Reset Bar Text (Simple)", xCoord, yCoord, 250, 30)
controls.resetButton1:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Warrior_Fury_ResetBarTextSimple")
end)
yCoord = yCoord - 40
--[[
controls.resetButton2 = TRB.UiFunctions.BuildButton(parent, "Reset Bar Text (Narrow Advanced)", xCoord, yCoord, 250, 30)
controls.resetButton2:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Warrior_Fury_ResetBarTextNarrowAdvanced")
end)
]]
controls.resetButton3 = TRB.UiFunctions.BuildButton(parent, "Reset Bar Text (Full Advanced)", xCoord, yCoord, 250, 30)
controls.resetButton3:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Warrior_Fury_ResetBarTextAdvanced")
end)
TRB.Frames.interfaceSettingsFrameContainer.controls.fury = controls
end
local function FuryConstructBarColorsAndBehaviorPanel(parent)
if parent == nil then
return
end
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local controls = interfaceSettingsFrame.controls.fury
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
local title = ""
local dropdownWidth = 225
local sliderWidth = 260
local sliderHeight = 20
local maxBorderHeight = math.min(math.floor(TRB.Data.settings.warrior.fury.bar.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.fury.bar.width / TRB.Data.constants.borderWidthFactor))
local sanityCheckValues = TRB.Functions.GetSanityCheckValues(TRB.Data.settings.warrior.fury)
controls.buttons.exportButton_Warrior_Fury_BarDisplay = TRB.UiFunctions.BuildButton(parent, "Export Bar Display", 325, yCoord-5, 225, 20)
controls.buttons.exportButton_Warrior_Fury_BarDisplay:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Fury Warrior (Bar Display).", 1, 2, true, false, false, false, false)
end)
controls.barPositionSection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Position and Size", 0, yCoord)
yCoord = yCoord - 40
title = "Bar Width"
controls.width = TRB.UiFunctions.BuildSlider(parent, title, sanityCheckValues.barMinWidth, sanityCheckValues.barMaxWidth, TRB.Data.settings.warrior.fury.bar.width, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.width:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.bar.width = value
if GetSpecialization() == 2 then
barContainerFrame:SetWidth(value-(TRB.Data.settings.warrior.fury.bar.border*2))
barBorderFrame:SetWidth(TRB.Data.settings.warrior.fury.bar.width)
resourceFrame:SetWidth(value-(TRB.Data.settings.warrior.fury.bar.border*2))
castingFrame:SetWidth(value-(TRB.Data.settings.warrior.fury.bar.border*2))
passiveFrame:SetWidth(value-(TRB.Data.settings.warrior.fury.bar.border*2))
TRB.Functions.SetBarMinMaxValues(TRB.Data.settings.warrior.fury)
for k, v in pairs(TRB.Data.spells) do
if TRB.Data.spells[k] ~= nil and TRB.Data.spells[k]["id"] ~= nil and TRB.Data.spells[k]["rage"] ~= nil and TRB.Data.spells[k]["rage"] < 0 and TRB.Data.spells[k]["thresholdId"] ~= nil then
TRB.Functions.RepositionThreshold(TRB.Data.settings.warrior.fury, resourceFrame.thresholds[TRB.Data.spells[k]["thresholdId"]], resourceFrame, TRB.Data.settings.warrior.fury.thresholds.width, -TRB.Data.spells[k]["rage"], TRB.Data.character.maxResource)
TRB.Frames.resourceFrame.thresholds[TRB.Data.spells[k]["thresholdId"]]:Show()
end
end
end
local maxBorderSize = math.min(math.floor(TRB.Data.settings.warrior.fury.bar.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.fury.bar.width / TRB.Data.constants.borderWidthFactor))
local borderSize = TRB.Data.settings.warrior.fury.bar.border
if maxBorderSize < borderSize then
maxBorderSize = borderSize
end
controls.borderWidth:SetMinMaxValues(0, maxBorderSize)
controls.borderWidth.MaxLabel:SetText(maxBorderSize)
controls.borderWidth.EditBox:SetText(borderSize)
TRB.Functions.UpdateBarWidth(TRB.Data.settings.warrior.fury)
end)
title = "Bar Height"
controls.height = TRB.UiFunctions.BuildSlider(parent, title, sanityCheckValues.barMinHeight, sanityCheckValues.barMaxHeight, TRB.Data.settings.warrior.fury.bar.height, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.height:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.bar.height = value
if GetSpecialization() == 2 then
barContainerFrame:SetHeight(value-(TRB.Data.settings.warrior.fury.bar.border*2))
barBorderFrame:SetHeight(TRB.Data.settings.warrior.fury.bar.height)
resourceFrame:SetHeight(value-(TRB.Data.settings.warrior.fury.bar.border*2))
for x = 1, TRB.Functions.TableLength(resourceFrame.thresholds) do
resourceFrame.thresholds[x]:SetHeight(value)
end
castingFrame:SetHeight(value-(TRB.Data.settings.warrior.fury.bar.border*2))
passiveFrame:SetHeight(value-(TRB.Data.settings.warrior.fury.bar.border*2))
leftTextFrame:SetHeight(TRB.Data.settings.warrior.fury.bar.height * 3.5)
middleTextFrame:SetHeight(TRB.Data.settings.warrior.fury.bar.height * 3.5)
rightTextFrame:SetHeight(TRB.Data.settings.warrior.fury.bar.height * 3.5)
end
local maxBorderSize = math.min(math.floor(TRB.Data.settings.warrior.fury.bar.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.fury.bar.width / TRB.Data.constants.borderWidthFactor))
local borderSize = TRB.Data.settings.warrior.fury.bar.border
if maxBorderSize < borderSize then
maxBorderSize = borderSize
end
controls.borderWidth:SetMinMaxValues(0, maxBorderSize)
controls.borderWidth.MaxLabel:SetText(maxBorderSize)
controls.borderWidth.EditBox:SetText(borderSize)
TRB.Functions.UpdateBarHeight(TRB.Data.settings.warrior.fury)
end)
title = "Bar Horizontal Position"
yCoord = yCoord - 60
controls.horizontal = TRB.UiFunctions.BuildSlider(parent, title, math.ceil(-sanityCheckValues.barMaxWidth/2), math.floor(sanityCheckValues.barMaxWidth/2), TRB.Data.settings.warrior.fury.bar.xPos, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.horizontal:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.bar.xPos = value
if GetSpecialization() == 2 then
barContainerFrame:ClearAllPoints()
barContainerFrame:SetPoint("CENTER", UIParent)
barContainerFrame:SetPoint("CENTER", TRB.Data.settings.warrior.fury.bar.xPos, TRB.Data.settings.warrior.fury.bar.yPos)
end
end)
title = "Bar Vertical Position"
controls.vertical = TRB.UiFunctions.BuildSlider(parent, title, math.ceil(-sanityCheckValues.barMaxHeight/2), math.floor(sanityCheckValues.barMaxHeight/2), TRB.Data.settings.warrior.fury.bar.yPos, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.vertical:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.bar.yPos = value
if GetSpecialization() == 2 then
barContainerFrame:ClearAllPoints()
barContainerFrame:SetPoint("CENTER", UIParent)
barContainerFrame:SetPoint("CENTER", TRB.Data.settings.warrior.fury.bar.xPos, TRB.Data.settings.warrior.fury.bar.yPos)
end
end)
title = "Bar Border Width"
yCoord = yCoord - 60
controls.borderWidth = TRB.UiFunctions.BuildSlider(parent, title, 0, maxBorderHeight, TRB.Data.settings.warrior.fury.bar.border, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.borderWidth:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.bar.border = value
if GetSpecialization() == 2 then
barContainerFrame:SetWidth(TRB.Data.settings.warrior.fury.bar.width-(TRB.Data.settings.warrior.fury.bar.border*2))
barContainerFrame:SetHeight(TRB.Data.settings.warrior.fury.bar.height-(TRB.Data.settings.warrior.fury.bar.border*2))
barBorderFrame:SetWidth(TRB.Data.settings.warrior.fury.bar.width)
barBorderFrame:SetHeight(TRB.Data.settings.warrior.fury.bar.height)
if TRB.Data.settings.warrior.fury.bar.border < 1 then
barBorderFrame:SetBackdrop({
edgeFile = TRB.Data.settings.warrior.fury.textures.border,
tile = true,
tileSize = 4,
edgeSize = 1,
insets = {0, 0, 0, 0}
})
barBorderFrame:Hide()
else
barBorderFrame:SetBackdrop({
edgeFile = TRB.Data.settings.warrior.fury.textures.border,
tile = true,
tileSize=4,
edgeSize=TRB.Data.settings.warrior.fury.bar.border,
insets = {0, 0, 0, 0}
})
barBorderFrame:Show()
end
barBorderFrame:SetBackdropColor(0, 0, 0, 0)
barBorderFrame:SetBackdropBorderColor (TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.bar.border, true))
TRB.Functions.SetBarMinMaxValues(TRB.Data.settings.warrior.fury)
for k, v in pairs(TRB.Data.spells) do
if TRB.Data.spells[k] ~= nil and TRB.Data.spells[k]["id"] ~= nil and TRB.Data.spells[k]["rage"] ~= nil and TRB.Data.spells[k]["rage"] < 0 and TRB.Data.spells[k]["thresholdId"] ~= nil then
TRB.Functions.RepositionThreshold(TRB.Data.settings.warrior.fury, resourceFrame.thresholds[TRB.Data.spells[k]["thresholdId"]], resourceFrame, TRB.Data.settings.warrior.fury.thresholds.width, -TRB.Data.spells[k]["rage"], TRB.Data.character.maxResource)
TRB.Frames.resourceFrame.thresholds[TRB.Data.spells[k]["thresholdId"]]:Show()
end
end
end
local minsliderWidth = math.max(TRB.Data.settings.warrior.fury.bar.border*2, 120)
local minsliderHeight = math.max(TRB.Data.settings.warrior.fury.bar.border*2, 1)
local scValues = TRB.Functions.GetSanityCheckValues(TRB.Data.settings.warrior.fury)
controls.height:SetMinMaxValues(minsliderHeight, scValues.barMaxHeight)
controls.height.MinLabel:SetText(minsliderHeight)
controls.width:SetMinMaxValues(minsliderWidth, scValues.barMaxWidth)
controls.width.MinLabel:SetText(minsliderWidth)
end)
title = "Threshold Line Width"
controls.thresholdWidth = TRB.UiFunctions.BuildSlider(parent, title, 1, 10, TRB.Data.settings.warrior.fury.thresholds.width, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.thresholdWidth:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.thresholds.width = value
if GetSpecialization() == 2 then
for x = 1, TRB.Functions.TableLength(resourceFrame.thresholds) do
resourceFrame.thresholds[x]:SetWidth(TRB.Data.settings.warrior.fury.thresholds.width)
end
end
end)
yCoord = yCoord - 40
--NOTE: the order of these checkboxes is reversed!
controls.checkBoxes.lockPosition = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_dragAndDrop", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.lockPosition
f:SetPoint("TOPLEFT", xCoord2+xPadding, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Drag & Drop Movement Enabled")
f.tooltip = "Disable Drag & Drop functionality of the bar to keep it from accidentally being moved.\n\nWhen 'Pin to Personal Resource Display' is checked, this value is ignored and cannot be changed."
f:SetChecked(TRB.Data.settings.warrior.fury.bar.dragAndDrop)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.bar.dragAndDrop = self:GetChecked()
barContainerFrame:SetMovable((not TRB.Data.settings.warrior.fury.bar.pinToPersonalResourceDisplay) and TRB.Data.settings.warrior.fury.bar.dragAndDrop)
barContainerFrame:EnableMouse((not TRB.Data.settings.warrior.fury.bar.pinToPersonalResourceDisplay) and TRB.Data.settings.warrior.fury.bar.dragAndDrop)
end)
TRB.UiFunctions.ToggleCheckboxEnabled(controls.checkBoxes.lockPosition, not TRB.Data.settings.warrior.fury.bar.pinToPersonalResourceDisplay)
controls.checkBoxes.pinToPRD = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_pinToPRD", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.pinToPRD
f:SetPoint("TOPLEFT", xCoord+xPadding, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Pin to Personal Resource Display")
f.tooltip = "Pins the bar to the Blizzard Personal Resource Display. Adjust the Horizontal and Vertical positions above to offset it from PRD. When enabled, Drag & Drop positioning is not allowed. If PRD is not enabled, will behave as if you didn't have this enabled.\n\nNOTE: This will also be the position (relative to the center of the screen, NOT the PRD) that it shows when out of combat/the PRD is not displayed! It is recommended you set 'Bar Display' to 'Only show bar in combat' if you plan to pin it to your PRD."
f:SetChecked(TRB.Data.settings.warrior.fury.bar.pinToPersonalResourceDisplay)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.bar.pinToPersonalResourceDisplay = self:GetChecked()
TRB.UiFunctions.ToggleCheckboxEnabled(controls.checkBoxes.lockPosition, not TRB.Data.settings.warrior.fury.bar.pinToPersonalResourceDisplay)
barContainerFrame:SetMovable((not TRB.Data.settings.warrior.fury.bar.pinToPersonalResourceDisplay) and TRB.Data.settings.warrior.fury.bar.dragAndDrop)
barContainerFrame:EnableMouse((not TRB.Data.settings.warrior.fury.bar.pinToPersonalResourceDisplay) and TRB.Data.settings.warrior.fury.bar.dragAndDrop)
TRB.Functions.RepositionBar(TRB.Data.settings.warrior.fury, TRB.Frames.barContainerFrame)
end)
yCoord = yCoord - 30
controls.textBarTexturesSection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Textures", 0, yCoord)
yCoord = yCoord - 30
-- Create the dropdown, and configure its appearance
controls.dropDown.resourceBarTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_RageBarTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.resourceBarTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Main Bar Texture", xCoord, yCoord)
controls.dropDown.resourceBarTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.resourceBarTexture:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.resourceBarTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, TRB.Data.settings.warrior.fury.textures.resourceBarName)
UIDropDownMenu_JustifyText(controls.dropDown.resourceBarTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.resourceBarTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("statusbar")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("statusbar")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Status Bar Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.fury.textures.resourceBar
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.resourceBarTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.textures.resourceBar = newValue
TRB.Data.settings.warrior.fury.textures.resourceBarName = newName
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, newName)
if TRB.Data.settings.warrior.fury.textures.textureLock then
TRB.Data.settings.warrior.fury.textures.castingBar = newValue
TRB.Data.settings.warrior.fury.textures.castingBarName = newName
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, newName)
TRB.Data.settings.warrior.fury.textures.passiveBar = newValue
TRB.Data.settings.warrior.fury.textures.passiveBarName = newName
UIDropDownMenu_SetText(controls.dropDown.passiveBarTexture, newName)
end
if GetSpecialization() == 2 then
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.resourceBar)
if TRB.Data.settings.warrior.fury.textures.textureLock then
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.castingBar)
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.passiveBar)
end
end
CloseDropDownMenus()
end
-- Create the dropdown, and configure its appearance
controls.dropDown.castingBarTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_CastBarTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.castingBarTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Casting Bar Texture", xCoord2, yCoord)
controls.dropDown.castingBarTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.castingBarTexture:SetPoint("TOPLEFT", xCoord2, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.castingBarTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, TRB.Data.settings.warrior.fury.textures.castingBarName)
UIDropDownMenu_JustifyText(controls.dropDown.castingBarTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.castingBarTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("statusbar")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("statusbar")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Status Bar Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.fury.textures.castingBar
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.castingBarTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.textures.castingBar = newValue
TRB.Data.settings.warrior.fury.textures.castingBarName = newName
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.castingBar)
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, newName)
if TRB.Data.settings.warrior.fury.textures.textureLock then
TRB.Data.settings.warrior.fury.textures.resourceBar = newValue
TRB.Data.settings.warrior.fury.textures.resourceBarName = newName
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.resourceBar)
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, newName)
TRB.Data.settings.warrior.fury.textures.passiveBar = newValue
TRB.Data.settings.warrior.fury.textures.passiveBarName = newName
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.passiveBar)
UIDropDownMenu_SetText(controls.dropDown.passiveBarTexture, newName)
end
if GetSpecialization() == 2 then
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.castingBar)
if TRB.Data.settings.warrior.fury.textures.textureLock then
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.resourceBar)
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.passiveBar)
end
end
CloseDropDownMenus()
end
yCoord = yCoord - 60
-- Create the dropdown, and configure its appearance
controls.dropDown.passiveBarTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_PassiveBarTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.passiveBarTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Passive Bar Texture", xCoord, yCoord)
controls.dropDown.passiveBarTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.passiveBarTexture:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.passiveBarTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.passiveBarTexture, TRB.Data.settings.warrior.fury.textures.passiveBarName)
UIDropDownMenu_JustifyText(controls.dropDown.passiveBarTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.passiveBarTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("statusbar")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("statusbar")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Status Bar Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.fury.textures.passiveBar
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.passiveBarTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.textures.passiveBar = newValue
TRB.Data.settings.warrior.fury.textures.passiveBarName = newName
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.passiveBar)
UIDropDownMenu_SetText(controls.dropDown.passiveBarTexture, newName)
if TRB.Data.settings.warrior.fury.textures.textureLock then
TRB.Data.settings.warrior.fury.textures.resourceBar = newValue
TRB.Data.settings.warrior.fury.textures.resourceBarName = newName
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.resourceBar)
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, newName)
TRB.Data.settings.warrior.fury.textures.castingBar = newValue
TRB.Data.settings.warrior.fury.textures.castingBarName = newName
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.castingBar)
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, newName)
end
if GetSpecialization() == 2 then
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.passiveBar)
if TRB.Data.settings.warrior.fury.textures.textureLock then
resourceFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.resourceBar)
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.castingBar)
end
end
CloseDropDownMenus()
end
controls.checkBoxes.textureLock = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_CB1_TEXTURE1", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.textureLock
f:SetPoint("TOPLEFT", xCoord2, yCoord-30)
getglobal(f:GetName() .. 'Text'):SetText("Use the same texture for all bars")
f.tooltip = "This will lock the texture for each part of the bar to be the same."
f:SetChecked(TRB.Data.settings.warrior.fury.textures.textureLock)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.textures.textureLock = self:GetChecked()
if TRB.Data.settings.warrior.fury.textures.textureLock then
TRB.Data.settings.warrior.fury.textures.passiveBar = TRB.Data.settings.warrior.fury.textures.resourceBar
TRB.Data.settings.warrior.fury.textures.passiveBarName = TRB.Data.settings.warrior.fury.textures.resourceBarName
UIDropDownMenu_SetText(controls.dropDown.resourceBarTexture, TRB.Data.settings.warrior.fury.textures.passiveBarName)
TRB.Data.settings.warrior.fury.textures.castingBar = TRB.Data.settings.warrior.fury.textures.resourceBar
TRB.Data.settings.warrior.fury.textures.castingBarName = TRB.Data.settings.warrior.fury.textures.resourceBarName
UIDropDownMenu_SetText(controls.dropDown.castingBarTexture, TRB.Data.settings.warrior.fury.textures.castingBarName)
if GetSpecialization() == 2 then
passiveFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.passiveBar)
castingFrame:SetStatusBarTexture(TRB.Data.settings.warrior.fury.textures.castingBar)
end
end
end)
yCoord = yCoord - 60
-- Create the dropdown, and configure its appearance
controls.dropDown.borderTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_BorderTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.borderTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Border Texture", xCoord, yCoord)
controls.dropDown.borderTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.borderTexture:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.borderTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.borderTexture, TRB.Data.settings.warrior.fury.textures.borderName)
UIDropDownMenu_JustifyText(controls.dropDown.borderTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.borderTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("border")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("border")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Border Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.fury.textures.border
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.borderTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.textures.border = newValue
TRB.Data.settings.warrior.fury.textures.borderName = newName
if GetSpecialization() == 2 then
if TRB.Data.settings.warrior.fury.bar.border < 1 then
barBorderFrame:SetBackdrop({ })
else
barBorderFrame:SetBackdrop({ edgeFile = TRB.Data.settings.warrior.fury.textures.border,
tile = true,
tileSize=4,
edgeSize=TRB.Data.settings.warrior.fury.bar.border,
insets = {0, 0, 0, 0}
})
end
barBorderFrame:SetBackdropColor(0, 0, 0, 0)
barBorderFrame:SetBackdropBorderColor (TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.bar.border, true))
end
UIDropDownMenu_SetText(controls.dropDown.borderTexture, newName)
CloseDropDownMenus()
end
-- Create the dropdown, and configure its appearance
controls.dropDown.backgroundTexture = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_BackgroundTexture", parent, "UIDropDownMenuTemplate")
controls.dropDown.backgroundTexture.label = TRB.UiFunctions.BuildSectionHeader(parent, "Background (Empty Bar) Texture", xCoord2, yCoord)
controls.dropDown.backgroundTexture.label.font:SetFontObject(GameFontNormal)
controls.dropDown.backgroundTexture:SetPoint("TOPLEFT", xCoord2, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.backgroundTexture, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.backgroundTexture, TRB.Data.settings.warrior.fury.textures.backgroundName)
UIDropDownMenu_JustifyText(controls.dropDown.backgroundTexture, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.backgroundTexture, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local textures = TRB.Details.addonData.libs.SharedMedia:HashTable("background")
local texturesList = TRB.Details.addonData.libs.SharedMedia:List("background")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(textures) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Background Textures " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(texturesList) do
if k > start and k <= start + entries then
info.text = v
info.value = textures[v]
info.checked = textures[v] == TRB.Data.settings.warrior.fury.textures.background
info.func = self.SetValue
info.arg1 = textures[v]
info.arg2 = v
info.icon = textures[v]
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the texture
function controls.dropDown.backgroundTexture:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.textures.background = newValue
TRB.Data.settings.warrior.fury.textures.backgroundName = newName
if GetSpecialization() == 2 then
barContainerFrame:SetBackdrop({
bgFile = TRB.Data.settings.warrior.fury.textures.background,
tile = true,
tileSize = TRB.Data.settings.warrior.fury.bar.width,
edgeSize = 1,
insets = {0, 0, 0, 0}
})
barContainerFrame:SetBackdropColor (TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.bar.background, true))
end
UIDropDownMenu_SetText(controls.dropDown.backgroundTexture, newName)
CloseDropDownMenus()
end
yCoord = yCoord - 70
controls.barDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Display", 0, yCoord)
yCoord = yCoord - 30
controls.checkBoxes.alwaysShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_RB1_2", parent, "UIRadioButtonTemplate")
f = controls.checkBoxes.alwaysShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Always show Resource Bar")
getglobal(f:GetName() .. 'Text'):SetFontObject(GameFontHighlight)
f.tooltip = "This will make the Resource Bar always visible on your UI, even when out of combat."
f:SetChecked(TRB.Data.settings.warrior.fury.displayBar.alwaysShow)
f:SetScript("OnClick", function(self, ...)
controls.checkBoxes.alwaysShow:SetChecked(true)
controls.checkBoxes.notZeroShow:SetChecked(false)
controls.checkBoxes.combatShow:SetChecked(false)
controls.checkBoxes.neverShow:SetChecked(false)
TRB.Data.settings.warrior.fury.displayBar.alwaysShow = true
TRB.Data.settings.warrior.fury.displayBar.notZeroShow = false
TRB.Data.settings.warrior.fury.displayBar.neverShow = false
TRB.Functions.HideResourceBar()
end)
controls.checkBoxes.notZeroShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_RB1_3", parent, "UIRadioButtonTemplate")
f = controls.checkBoxes.notZeroShow
f:SetPoint("TOPLEFT", xCoord, yCoord-15)
getglobal(f:GetName() .. 'Text'):SetText("Show Resource Bar when Rage > 0")
getglobal(f:GetName() .. 'Text'):SetFontObject(GameFontHighlight)
f.tooltip = "This will make the Resource Bar show out of combat only if Rage > 0, hidden otherwise when out of combat."
f:SetChecked(TRB.Data.settings.warrior.fury.displayBar.notZeroShow)
f:SetScript("OnClick", function(self, ...)
controls.checkBoxes.alwaysShow:SetChecked(false)
controls.checkBoxes.notZeroShow:SetChecked(true)
controls.checkBoxes.combatShow:SetChecked(false)
controls.checkBoxes.neverShow:SetChecked(false)
TRB.Data.settings.warrior.fury.displayBar.alwaysShow = false
TRB.Data.settings.warrior.fury.displayBar.notZeroShow = true
TRB.Data.settings.warrior.fury.displayBar.neverShow = false
TRB.Functions.HideResourceBar()
end)
controls.checkBoxes.combatShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_RB1_4", parent, "UIRadioButtonTemplate")
f = controls.checkBoxes.combatShow
f:SetPoint("TOPLEFT", xCoord, yCoord-30)
getglobal(f:GetName() .. 'Text'):SetText("Only show Resource Bar in combat")
getglobal(f:GetName() .. 'Text'):SetFontObject(GameFontHighlight)
f.tooltip = "This will make the Resource Bar only be visible on your UI when in combat."
f:SetChecked((not TRB.Data.settings.warrior.fury.displayBar.alwaysShow) and (not TRB.Data.settings.warrior.fury.displayBar.notZeroShow))
f:SetScript("OnClick", function(self, ...)
controls.checkBoxes.alwaysShow:SetChecked(false)
controls.checkBoxes.notZeroShow:SetChecked(false)
controls.checkBoxes.combatShow:SetChecked(true)
controls.checkBoxes.neverShow:SetChecked(false)
TRB.Data.settings.warrior.fury.displayBar.alwaysShow = false
TRB.Data.settings.warrior.fury.displayBar.notZeroShow = false
TRB.Data.settings.warrior.fury.displayBar.neverShow = false
TRB.Functions.HideResourceBar()
end)
controls.checkBoxes.neverShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_RB1_5", parent, "UIRadioButtonTemplate")
f = controls.checkBoxes.neverShow
f:SetPoint("TOPLEFT", xCoord, yCoord-45)
getglobal(f:GetName() .. 'Text'):SetText("Never show Resource Bar (run in background)")
getglobal(f:GetName() .. 'Text'):SetFontObject(GameFontHighlight)
f.tooltip = "This will make the Resource Bar never display but still run in the background to update the global variable."
f:SetChecked(TRB.Data.settings.warrior.fury.displayBar.neverShow)
f:SetScript("OnClick", function(self, ...)
controls.checkBoxes.alwaysShow:SetChecked(false)
controls.checkBoxes.notZeroShow:SetChecked(false)
controls.checkBoxes.combatShow:SetChecked(false)
controls.checkBoxes.neverShow:SetChecked(true)
TRB.Data.settings.warrior.fury.displayBar.alwaysShow = false
TRB.Data.settings.warrior.fury.displayBar.notZeroShow = false
TRB.Data.settings.warrior.fury.displayBar.neverShow = true
TRB.Functions.HideResourceBar()
end)
controls.checkBoxes.showPassiveBar = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_showPassiveBar", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.showPassiveBar
f:SetPoint("TOPLEFT", xCoord2, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Show passive bar")
f.tooltip = "This will show the passive bar. Uncheck to hide this bar. This setting supercedes any other passive tracking options!"
f:SetChecked(TRB.Data.settings.warrior.fury.bar.showPassive)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.bar.showPassive = self:GetChecked()
end)
yCoord = yCoord - 60
controls.barColorsSection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Colors", 0, yCoord)
yCoord = yCoord - 30
controls.colors.base = TRB.UiFunctions.BuildColorPicker(parent, "Rage", TRB.Data.settings.warrior.fury.colors.bar.base, 300, 25, xCoord, yCoord)
f = controls.colors.base
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.bar.base, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.base.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.bar.base = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.border = TRB.UiFunctions.BuildColorPicker(parent, "Resource Bar's border", TRB.Data.settings.warrior.fury.colors.bar.border, 225, 25, xCoord2, yCoord)
f = controls.colors.border
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.bar.border, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.border.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.bar.border = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
barBorderFrame:SetBackdropBorderColor(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 30
controls.colors.passive = TRB.UiFunctions.BuildColorPicker(parent, "Rage gain from Passive Sources", TRB.Data.settings.warrior.fury.colors.bar.passive, 275, 25, xCoord, yCoord)
f = controls.colors.passive
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.bar.passive, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.passive.Texture:SetColorTexture(r, g, b, 1-a)
passiveFrame:SetStatusBarColor(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.bar.passive = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.borderOvercap = TRB.UiFunctions.BuildColorPicker(parent, "Bar border color when you are overcapping Rage", TRB.Data.settings.warrior.fury.colors.bar.borderOvercap, 275, 25, xCoord2, yCoord)
f = controls.colors.borderOvercap
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.bar.borderOvercap, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.borderOvercap.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.bar.borderOvercap = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 30
controls.colors.background = TRB.UiFunctions.BuildColorPicker(parent, "Unfilled bar background", TRB.Data.settings.warrior.fury.colors.bar.background, 275, 25, xCoord, yCoord)
f = controls.colors.background
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.bar.background, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.background.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.bar.background = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
barContainerFrame:SetBackdropColor(r, g, b, 1-a)
end)
end
end)
controls.colors.enrage = TRB.UiFunctions.BuildColorPicker(parent, "Fury while Enrage is active", TRB.Data.settings.warrior.fury.colors.bar.enrage, 250, 25, xCoord2, yCoord)
f = controls.colors.enrage
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.bar.enrage, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.enrage.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.bar.enrage = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 40
controls.barColorsSection = TRB.UiFunctions.BuildSectionHeader(parent, "Ability Threshold Lines", 0, yCoord)
yCoord = yCoord - 25
controls.colors.thresholdUnder = TRB.UiFunctions.BuildColorPicker(parent, "Under minimum required Rage threshold line", TRB.Data.settings.warrior.fury.colors.threshold.under, 275, 25, xCoord2, yCoord)
f = controls.colors.thresholdUnder
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.threshold.under, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.thresholdUnder.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.threshold.under = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.thresholdOver = TRB.UiFunctions.BuildColorPicker(parent, "Over minimum required Rage threshold line", TRB.Data.settings.warrior.fury.colors.threshold.over, 275, 25, xCoord2, yCoord-30)
f = controls.colors.thresholdOver
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.threshold.over, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.thresholdOver.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.threshold.over = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.thresholdUnusable = TRB.UiFunctions.BuildColorPicker(parent, "Ability is unusable threshold line", TRB.Data.settings.warrior.fury.colors.threshold.unusable, 275, 25, xCoord2, yCoord-60)
f = controls.colors.thresholdUnusable
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.threshold.unusable, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.thresholdUnusable.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.threshold.unusable = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.checkBoxes.thresholdOverlapBorder = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_thresholdOverlapBorder", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.thresholdOverlapBorder
f:SetPoint("TOPLEFT", xCoord2, yCoord-90)
getglobal(f:GetName() .. 'Text'):SetText("Threshold lines overlap bar border?")
f.tooltip = "When checked, threshold lines will span the full height of the bar and overlap the bar border."
f:SetChecked(TRB.Data.settings.warrior.fury.thresholds.overlapBorder)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.thresholds.overlapBorder = self:GetChecked()
TRB.Functions.RedrawThresholdLines(TRB.Data.settings.warrior.fury)
end)
controls.checkBoxes.ignorePainThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_Threshold_Option_ignorePain", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.ignorePainThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Ignore Pain")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Ignore Pain."
f:SetChecked(TRB.Data.settings.warrior.fury.thresholds.ignorePain.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.thresholds.ignorePain.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.impendingVictoryThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_Threshold_Option_impendingVictory", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.impendingVictoryThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Impending Victory (if talented)")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Impending Victory. Only visible if talented."
f:SetChecked(TRB.Data.settings.warrior.fury.thresholds.impendingVictory.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.thresholds.impendingVictory.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.rampageThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_Threshold_Option_rampage", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.rampageThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Rampage (if talented)")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Rampage."
f:SetChecked(TRB.Data.settings.warrior.fury.thresholds.rampage.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.thresholds.rampage.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.shieldBlockThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_Threshold_Option_shieldBlock", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.shieldBlockThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Shield Block")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Shield Block. This does not check to see if you have a shield equipped!"
f:SetChecked(TRB.Data.settings.warrior.fury.thresholds.shieldBlock.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.thresholds.shieldBlock.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.slamThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_Threshold_Option_slam", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.slamThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Slam")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Slam."
f:SetChecked(TRB.Data.settings.warrior.fury.thresholds.slam.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.thresholds.slam.enabled = self:GetChecked()
end)
yCoord = yCoord - 25
controls.checkBoxes.whirlwindThresholdShow = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_Threshold_Option_whirlwind", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.whirlwindThresholdShow
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Whirlwind")
f.tooltip = "This will show the vertical line on the bar denoting how much Rage is required to use Whirlwind."
f:SetChecked(TRB.Data.settings.warrior.fury.thresholds.whirlwind.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.thresholds.whirlwind.enabled = self:GetChecked()
end)
yCoord = yCoord - 40
-- Create the dropdown, and configure its appearance
controls.dropDown.thresholdIconRelativeTo = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_thresholdIconRelativeTo", parent, "UIDropDownMenuTemplate")
controls.dropDown.thresholdIconRelativeTo.label = TRB.UiFunctions.BuildSectionHeader(parent, "Relative Position of Threshold Line Icons", xCoord, yCoord)
controls.dropDown.thresholdIconRelativeTo.label.font:SetFontObject(GameFontNormal)
controls.dropDown.thresholdIconRelativeTo:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.thresholdIconRelativeTo, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.thresholdIconRelativeTo, TRB.Data.settings.warrior.fury.thresholds.icons.relativeToName)
UIDropDownMenu_JustifyText(controls.dropDown.thresholdIconRelativeTo, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.thresholdIconRelativeTo, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local relativeTo = {}
relativeTo["Above"] = "TOP"
relativeTo["Middle"] = "CENTER"
relativeTo["Below"] = "BOTTOM"
local relativeToList = {
"Above",
"Middle",
"Below"
}
for k, v in pairs(relativeToList) do
info.text = v
info.value = relativeTo[v]
info.checked = relativeTo[v] == TRB.Data.settings.warrior.fury.thresholds.icons.relativeTo
info.func = self.SetValue
info.arg1 = relativeTo[v]
info.arg2 = v
UIDropDownMenu_AddButton(info, level)
end
end)
function controls.dropDown.thresholdIconRelativeTo:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.thresholds.icons.relativeTo = newValue
TRB.Data.settings.warrior.fury.thresholds.icons.relativeToName = newName
if GetSpecialization() == 2 then
TRB.Functions.RedrawThresholdLines(TRB.Data.settings.warrior.fury)
end
UIDropDownMenu_SetText(controls.dropDown.thresholdIconRelativeTo, newName)
CloseDropDownMenus()
end
controls.checkBoxes.thresholdIconEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_thresholdIconEnabled", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.thresholdIconEnabled
f:SetPoint("TOPLEFT", xCoord2, yCoord-30)
getglobal(f:GetName() .. 'Text'):SetText("Show ability icons for threshold lines?")
f.tooltip = "When checked, icons for the threshold each line represents will be displayed. Configuration of size and location of these icons is below."
f:SetChecked(TRB.Data.settings.warrior.fury.thresholds.icons.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.thresholds.icons.enabled = self:GetChecked()
if GetSpecialization() == 2 then
TRB.Functions.RedrawThresholdLines(TRB.Data.settings.warrior.fury)
end
end)
yCoord = yCoord - 80
title = "Threshold Icon Width"
controls.thresholdIconWidth = TRB.UiFunctions.BuildSlider(parent, title, 1, 128, TRB.Data.settings.warrior.fury.thresholds.icons.width, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.thresholdIconWidth:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.thresholds.icons.width = value
local maxBorderSize = math.min(math.floor(TRB.Data.settings.warrior.fury.thresholds.icons.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.fury.thresholds.icons.width / TRB.Data.constants.borderWidthFactor))
local borderSize = TRB.Data.settings.warrior.fury.thresholds.icons.border
if maxBorderSize < borderSize then
maxBorderSize = borderSize
end
controls.thresholdIconBorderWidth:SetMinMaxValues(0, maxBorderSize)
controls.thresholdIconBorderWidth.MaxLabel:SetText(maxBorderSize)
controls.thresholdIconBorderWidth.EditBox:SetText(borderSize)
end)
title = "Threshold Icon Height"
controls.thresholdIconHeight = TRB.UiFunctions.BuildSlider(parent, title, 1, 128, TRB.Data.settings.warrior.fury.thresholds.icons.height, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.thresholdIconHeight:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.thresholds.icons.height = value
local maxBorderSize = math.min(math.floor(TRB.Data.settings.warrior.fury.thresholds.icons.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.fury.thresholds.icons.width / TRB.Data.constants.borderWidthFactor))
local borderSize = TRB.Data.settings.warrior.fury.thresholds.icons.border
if maxBorderSize < borderSize then
maxBorderSize = borderSize
end
controls.thresholdIconBorderWidth:SetMinMaxValues(0, maxBorderSize)
controls.thresholdIconBorderWidth.MaxLabel:SetText(maxBorderSize)
controls.thresholdIconBorderWidth.EditBox:SetText(borderSize)
end)
title = "Threshold Icon Horizontal Position (Relative)"
yCoord = yCoord - 60
controls.thresholdIconHorizontal = TRB.UiFunctions.BuildSlider(parent, title, math.ceil(-sanityCheckValues.barMaxWidth/2), math.floor(sanityCheckValues.barMaxWidth/2), TRB.Data.settings.warrior.fury.thresholds.icons.xPos, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.thresholdIconHorizontal:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.thresholds.icons.xPos = value
if GetSpecialization() == 2 then
TRB.Functions.RepositionBar(TRB.Data.settings.warrior.fury, TRB.Frames.barContainerFrame)
end
end)
title = "Threshold Icon Vertical Position (Relative)"
controls.thresholdIconVertical = TRB.UiFunctions.BuildSlider(parent, title, math.ceil(-sanityCheckValues.barMaxHeight/2), math.floor(sanityCheckValues.barMaxHeight/2), TRB.Data.settings.warrior.fury.thresholds.icons.yPos, 1, 2,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.thresholdIconVertical:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.thresholds.icons.yPos = value
end)
local maxIconBorderHeight = math.min(math.floor(TRB.Data.settings.warrior.fury.thresholds.icons.height / TRB.Data.constants.borderWidthFactor), math.floor(TRB.Data.settings.warrior.fury.thresholds.icons.width / TRB.Data.constants.borderWidthFactor))
title = "Threshold Icon Border Width"
yCoord = yCoord - 60
controls.thresholdIconBorderWidth = TRB.UiFunctions.BuildSlider(parent, title, 0, maxIconBorderHeight, TRB.Data.settings.warrior.fury.thresholds.icons.border, 1, 2,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.thresholdIconBorderWidth:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.thresholds.icons.border = value
local minsliderWidth = math.max(TRB.Data.settings.warrior.fury.thresholds.icons.border*2, 1)
local minsliderHeight = math.max(TRB.Data.settings.warrior.fury.thresholds.icons.border*2, 1)
controls.thresholdIconHeight:SetMinMaxValues(minsliderHeight, 128)
controls.thresholdIconHeight.MinLabel:SetText(minsliderHeight)
controls.thresholdIconWidth:SetMinMaxValues(minsliderWidth, 128)
controls.thresholdIconWidth.MinLabel:SetText(minsliderWidth)
if GetSpecialization() == 2 then
TRB.Functions.RedrawThresholdLines(TRB.Data.settings.warrior.fury)
end
end)
yCoord = yCoord - 60
controls.textSection = TRB.UiFunctions.BuildSectionHeader(parent, "Overcapping Configuration", 0, yCoord)
yCoord = yCoord - 30
controls.checkBoxes.overcapEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_CB1_8", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.overcapEnabled
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Change border color when overcapping")
f.tooltip = "This will change the bar's border color when your current hardcast spell will result in overcapping maximum Rage. Setting accepts values up to 130 to accomidate the Deadly Calm talent."
f:SetChecked(TRB.Data.settings.warrior.fury.colors.bar.overcapEnabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.colors.bar.overcapEnabled = self:GetChecked()
end)
yCoord = yCoord - 40
title = "Show Overcap Notification Above"
controls.overcapAt = TRB.UiFunctions.BuildSlider(parent, title, 0, 100, TRB.Data.settings.warrior.fury.overcapThreshold, 1, 1,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.overcapAt:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
value = TRB.Functions.RoundTo(value, 1)
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.overcapThreshold = value
end)
TRB.Frames.interfaceSettingsFrameContainer.controls.fury = controls
end
local function FuryConstructFontAndTextPanel(parent)
if parent == nil then
return
end
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local controls = interfaceSettingsFrame.controls.fury
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
local title = ""
local dropdownWidth = 225
local sliderWidth = 260
local sliderHeight = 20
controls.buttons.exportButton_Warrior_Fury_FontAndText = TRB.UiFunctions.BuildButton(parent, "Export Font & Text", 325, yCoord-5, 225, 20)
controls.buttons.exportButton_Warrior_Fury_FontAndText:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Fury Warrior (Font & Text).", 1, 2, false, true, false, false, false)
end)
controls.textDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Font Face", 0, yCoord)
yCoord = yCoord - 30
-- Create the dropdown, and configure its appearance
controls.dropDown.fontLeft = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_FontLeft", parent, "UIDropDownMenuTemplate")
controls.dropDown.fontLeft.label = TRB.UiFunctions.BuildSectionHeader(parent, "Left Bar Font Face", xCoord, yCoord)
controls.dropDown.fontLeft.label.font:SetFontObject(GameFontNormal)
controls.dropDown.fontLeft:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.fontLeft, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.fontLeft, TRB.Data.settings.warrior.fury.displayText.left.fontFaceName)
UIDropDownMenu_JustifyText(controls.dropDown.fontLeft, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.fontLeft, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local fonts = TRB.Details.addonData.libs.SharedMedia:HashTable("font")
local fontsList = TRB.Details.addonData.libs.SharedMedia:List("font")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(fonts) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Fonts " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(fontsList) do
if k > start and k <= start + entries then
info.text = v
info.value = fonts[v]
info.checked = fonts[v] == TRB.Data.settings.warrior.fury.displayText.left.fontFace
info.func = self.SetValue
info.arg1 = fonts[v]
info.arg2 = v
info.fontObject = CreateFont(v)
info.fontObject:SetFont(fonts[v], 12, "OUTLINE")
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
function controls.dropDown.fontLeft:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.displayText.left.fontFace = newValue
TRB.Data.settings.warrior.fury.displayText.left.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontLeft, newName)
if TRB.Data.settings.warrior.fury.displayText.fontFaceLock then
TRB.Data.settings.warrior.fury.displayText.middle.fontFace = newValue
TRB.Data.settings.warrior.fury.displayText.middle.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, newName)
TRB.Data.settings.warrior.fury.displayText.right.fontFace = newValue
TRB.Data.settings.warrior.fury.displayText.right.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontRight, newName)
end
if GetSpecialization() == 2 then
leftTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.left.fontFace, TRB.Data.settings.warrior.fury.displayText.left.fontSize, "OUTLINE")
if TRB.Data.settings.warrior.fury.displayText.fontFaceLock then
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.middle.fontFace, TRB.Data.settings.warrior.fury.displayText.middle.fontSize, "OUTLINE")
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.right.fontFace, TRB.Data.settings.warrior.fury.displayText.right.fontSize, "OUTLINE")
end
end
CloseDropDownMenus()
end
-- Create the dropdown, and configure its appearance
controls.dropDown.fontMiddle = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_FontMiddle", parent, "UIDropDownMenuTemplate")
controls.dropDown.fontMiddle.label = TRB.UiFunctions.BuildSectionHeader(parent, "Middle Bar Font Face", xCoord2, yCoord)
controls.dropDown.fontMiddle.label.font:SetFontObject(GameFontNormal)
controls.dropDown.fontMiddle:SetPoint("TOPLEFT", xCoord2, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.fontMiddle, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, TRB.Data.settings.warrior.fury.displayText.middle.fontFaceName)
UIDropDownMenu_JustifyText(controls.dropDown.fontMiddle, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.fontMiddle, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local fonts = TRB.Details.addonData.libs.SharedMedia:HashTable("font")
local fontsList = TRB.Details.addonData.libs.SharedMedia:List("font")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(fonts) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Fonts " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(fontsList) do
if k > start and k <= start + entries then
info.text = v
info.value = fonts[v]
info.checked = fonts[v] == TRB.Data.settings.warrior.fury.displayText.middle.fontFace
info.func = self.SetValue
info.arg1 = fonts[v]
info.arg2 = v
info.fontObject = CreateFont(v)
info.fontObject:SetFont(fonts[v], 12, "OUTLINE")
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
function controls.dropDown.fontMiddle:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.displayText.middle.fontFace = newValue
TRB.Data.settings.warrior.fury.displayText.middle.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, newName)
if TRB.Data.settings.warrior.fury.displayText.fontFaceLock then
TRB.Data.settings.warrior.fury.displayText.left.fontFace = newValue
TRB.Data.settings.warrior.fury.displayText.left.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontLeft, newName)
TRB.Data.settings.warrior.fury.displayText.right.fontFace = newValue
TRB.Data.settings.warrior.fury.displayText.right.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontRight, newName)
end
if GetSpecialization() == 2 then
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.middle.fontFace, TRB.Data.settings.warrior.fury.displayText.middle.fontSize, "OUTLINE")
if TRB.Data.settings.warrior.fury.displayText.fontFaceLock then
leftTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.left.fontFace, TRB.Data.settings.warrior.fury.displayText.left.fontSize, "OUTLINE")
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.right.fontFace, TRB.Data.settings.warrior.fury.displayText.right.fontSize, "OUTLINE")
end
end
CloseDropDownMenus()
end
yCoord = yCoord - 40 - 20
-- Create the dropdown, and configure its appearance
controls.dropDown.fontRight = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_FontRight", parent, "UIDropDownMenuTemplate")
controls.dropDown.fontRight.label = TRB.UiFunctions.BuildSectionHeader(parent, "Right Bar Font Face", xCoord, yCoord)
controls.dropDown.fontRight.label.font:SetFontObject(GameFontNormal)
controls.dropDown.fontRight:SetPoint("TOPLEFT", xCoord, yCoord-30)
UIDropDownMenu_SetWidth(controls.dropDown.fontRight, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.fontRight, TRB.Data.settings.warrior.fury.displayText.right.fontFaceName)
UIDropDownMenu_JustifyText(controls.dropDown.fontRight, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.fontRight, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local fonts = TRB.Details.addonData.libs.SharedMedia:HashTable("font")
local fontsList = TRB.Details.addonData.libs.SharedMedia:List("font")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(fonts) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Fonts " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(fontsList) do
if k > start and k <= start + entries then
info.text = v
info.value = fonts[v]
info.checked = fonts[v] == TRB.Data.settings.warrior.fury.displayText.right.fontFace
info.func = self.SetValue
info.arg1 = fonts[v]
info.arg2 = v
info.fontObject = CreateFont(v)
info.fontObject:SetFont(fonts[v], 12, "OUTLINE")
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
function controls.dropDown.fontRight:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.displayText.right.fontFace = newValue
TRB.Data.settings.warrior.fury.displayText.right.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontRight, newName)
if TRB.Data.settings.warrior.fury.displayText.fontFaceLock then
TRB.Data.settings.warrior.fury.displayText.left.fontFace = newValue
TRB.Data.settings.warrior.fury.displayText.left.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontLeft, newName)
TRB.Data.settings.warrior.fury.displayText.middle.fontFace = newValue
TRB.Data.settings.warrior.fury.displayText.middle.fontFaceName = newName
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, newName)
end
if GetSpecialization() == 2 then
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.right.fontFace, TRB.Data.settings.warrior.fury.displayText.right.fontSize, "OUTLINE")
if TRB.Data.settings.warrior.fury.displayText.fontFaceLock then
leftTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.left.fontFace, TRB.Data.settings.warrior.fury.displayText.left.fontSize, "OUTLINE")
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.middle.fontFace, TRB.Data.settings.warrior.fury.displayText.middle.fontSize, "OUTLINE")
end
end
CloseDropDownMenus()
end
controls.checkBoxes.fontFaceLock = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_CB1_FONTFACE1", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.fontFaceLock
f:SetPoint("TOPLEFT", xCoord2, yCoord-30)
getglobal(f:GetName() .. 'Text'):SetText("Use the same font face for all text")
f.tooltip = "This will lock the font face for text for each part of the bar to be the same."
f:SetChecked(TRB.Data.settings.warrior.fury.displayText.fontFaceLock)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.displayText.fontFaceLock = self:GetChecked()
if TRB.Data.settings.warrior.fury.displayText.fontFaceLock then
TRB.Data.settings.warrior.fury.displayText.middle.fontFace = TRB.Data.settings.warrior.fury.displayText.left.fontFace
TRB.Data.settings.warrior.fury.displayText.middle.fontFaceName = TRB.Data.settings.warrior.fury.displayText.left.fontFaceName
UIDropDownMenu_SetText(controls.dropDown.fontMiddle, TRB.Data.settings.warrior.fury.displayText.middle.fontFaceName)
TRB.Data.settings.warrior.fury.displayText.right.fontFace = TRB.Data.settings.warrior.fury.displayText.left.fontFace
TRB.Data.settings.warrior.fury.displayText.right.fontFaceName = TRB.Data.settings.warrior.fury.displayText.left.fontFaceName
UIDropDownMenu_SetText(controls.dropDown.fontRight, TRB.Data.settings.warrior.fury.displayText.right.fontFaceName)
if GetSpecialization() == 2 then
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.middle.fontFace, TRB.Data.settings.warrior.fury.displayText.middle.fontSize, "OUTLINE")
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.right.fontFace, TRB.Data.settings.warrior.fury.displayText.right.fontSize, "OUTLINE")
end
end
end)
yCoord = yCoord - 70
controls.textDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Font Size and Colors", 0, yCoord)
title = "Left Bar Text Font Size"
yCoord = yCoord - 50
controls.fontSizeLeft = TRB.UiFunctions.BuildSlider(parent, title, 6, 72, TRB.Data.settings.warrior.fury.displayText.left.fontSize, 1, 0,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.fontSizeLeft:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.displayText.left.fontSize = value
if GetSpecialization() == 2 then
leftTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.left.fontFace, TRB.Data.settings.warrior.fury.displayText.left.fontSize, "OUTLINE")
end
if TRB.Data.settings.warrior.fury.displayText.fontSizeLock then
controls.fontSizeMiddle:SetValue(value)
controls.fontSizeRight:SetValue(value)
end
end)
controls.checkBoxes.fontSizeLock = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_CB2_F1", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.fontSizeLock
f:SetPoint("TOPLEFT", xCoord2, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Use the same font size for all text")
f.tooltip = "This will lock the font sizes for each part of the bar to be the same size."
f:SetChecked(TRB.Data.settings.warrior.fury.displayText.fontSizeLock)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.displayText.fontSizeLock = self:GetChecked()
if TRB.Data.settings.warrior.fury.displayText.fontSizeLock then
controls.fontSizeMiddle:SetValue(TRB.Data.settings.warrior.fury.displayText.left.fontSize)
controls.fontSizeRight:SetValue(TRB.Data.settings.warrior.fury.displayText.left.fontSize)
end
end)
controls.colors.leftText = TRB.UiFunctions.BuildColorPicker(parent, "Left Text", TRB.Data.settings.warrior.fury.colors.text.left,
250, 25, xCoord2, yCoord-30)
f = controls.colors.leftText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.left, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.leftText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.left = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.middleText = TRB.UiFunctions.BuildColorPicker(parent, "Middle Text", TRB.Data.settings.warrior.fury.colors.text.middle,
225, 25, xCoord2, yCoord-70)
f = controls.colors.middleText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.middle, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.middleText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.middle = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.rightText = TRB.UiFunctions.BuildColorPicker(parent, "Right Text", TRB.Data.settings.warrior.fury.colors.text.right,
225, 25, xCoord2, yCoord-110)
f = controls.colors.rightText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.right, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.rightText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.right = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
title = "Middle Bar Text Font Size"
yCoord = yCoord - 60
controls.fontSizeMiddle = TRB.UiFunctions.BuildSlider(parent, title, 6, 72, TRB.Data.settings.warrior.fury.displayText.middle.fontSize, 1, 0,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.fontSizeMiddle:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.displayText.middle.fontSize = value
if GetSpecialization() == 2 then
middleTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.middle.fontFace, TRB.Data.settings.warrior.fury.displayText.middle.fontSize, "OUTLINE")
end
if TRB.Data.settings.warrior.fury.displayText.fontSizeLock then
controls.fontSizeLeft:SetValue(value)
controls.fontSizeRight:SetValue(value)
end
end)
title = "Right Bar Text Font Size"
yCoord = yCoord - 60
controls.fontSizeRight = TRB.UiFunctions.BuildSlider(parent, title, 6, 72, TRB.Data.settings.warrior.fury.displayText.right.fontSize, 1, 0,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.fontSizeRight:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.displayText.right.fontSize = value
if GetSpecialization() == 2 then
rightTextFrame.font:SetFont(TRB.Data.settings.warrior.fury.displayText.right.fontFace, TRB.Data.settings.warrior.fury.displayText.right.fontSize, "OUTLINE")
end
if TRB.Data.settings.warrior.fury.displayText.fontSizeLock then
controls.fontSizeLeft:SetValue(value)
controls.fontSizeMiddle:SetValue(value)
end
end)
yCoord = yCoord - 40
controls.textDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Rage Text Colors", 0, yCoord)
yCoord = yCoord - 30
controls.colors.currentRageText = TRB.UiFunctions.BuildColorPicker(parent, "Current Rage", TRB.Data.settings.warrior.fury.colors.text.current, 300, 25, xCoord, yCoord)
f = controls.colors.currentRageText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.current, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.currentRageText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.current = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.passiveRageText = TRB.UiFunctions.BuildColorPicker(parent, "Passive Rage", TRB.Data.settings.warrior.fury.colors.text.passive, 275, 25, xCoord2, yCoord)
f = controls.colors.passiveRageText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.passive, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.passiveRageText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.passive = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 30
controls.colors.thresholdrageText = TRB.UiFunctions.BuildColorPicker(parent, "Have enough Rage to use any enabled threshold ability", TRB.Data.settings.warrior.fury.colors.text.overThreshold, 300, 25, xCoord, yCoord)
f = controls.colors.thresholdrageText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.overThreshold, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.thresholdrageText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.overThreshold = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.overcaprageText = TRB.UiFunctions.BuildColorPicker(parent, "Overcapping Rage", TRB.Data.settings.warrior.fury.colors.text.overcap, 300, 25, xCoord2, yCoord)
f = controls.colors.overcaprageText
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.overcap, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
--Text doesn't care about Alpha, but the color picker does!
a = 0.0
controls.colors.overcaprageText.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.overcap = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
yCoord = yCoord - 30
controls.checkBoxes.overThresholdEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_OverThresholdTextEnable", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.overThresholdEnabled
f:SetPoint("TOPLEFT", xCoord+xPadding, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Enabled?")
f.tooltip = "This will change the Rage text color when you are able to use an ability whose threshold you have enabled under 'Bar Display'."
f:SetChecked(TRB.Data.settings.warrior.fury.colors.text.overThresholdEnabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.colors.text.overThresholdEnabled = self:GetChecked()
end)
controls.checkBoxes.overcapTextEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_OvercapTextEnable", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.overcapTextEnabled
f:SetPoint("TOPLEFT", xCoord2+xPadding, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Enabled?")
f.tooltip = "This will change the Rage text color when your current hardcast spell will result in overcapping maximum Rage."
f:SetChecked(TRB.Data.settings.warrior.fury.colors.text.overcapEnabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.colors.text.overcapEnabled = self:GetChecked()
end)
--[[
yCoord = yCoord - 30
controls.dotColorSection = TRB.UiFunctions.BuildSectionHeader(parent, "DoT Count and Time Remaining Tracking", 0, yCoord)
yCoord = yCoord - 25
controls.checkBoxes.dotColor = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_dotColor", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.dotColor
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Change total DoT counter and DoT timer color based on DoT status?")
f.tooltip = "When checked, the color of total DoTs up counters and DoT timers ($deepWoundsCount, $rendCount) will change based on whether or not the DoT is on the current target."
f:SetChecked(TRB.Data.settings.warrior.fury.colors.text.dots.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.colors.text.dots.enabled = self:GetChecked()
end)
controls.colors.dotUp = TRB.UiFunctions.BuildColorPicker(parent, "DoT is active on current target", TRB.Data.settings.warrior.fury.colors.text.dots.up, 550, 25, xCoord, yCoord-30)
f = controls.colors.dotUp
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.dots.up, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.dotUp.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.dots.up = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.dotPandemic = TRB.UiFunctions.BuildColorPicker(parent, "DoT is active on current target but within Pandemic refresh range", TRB.Data.settings.warrior.fury.colors.text.dots.pandemic, 550, 25, xCoord, yCoord-60)
f = controls.colors.dotPandemic
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.dots.pandemic, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.dotPandemic.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.dots.pandemic = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
controls.colors.dotDown = TRB.UiFunctions.BuildColorPicker(parent, "DoT is not active on current target", TRB.Data.settings.warrior.fury.colors.text.dots.down, 550, 25, xCoord, yCoord-90)
f = controls.colors.dotDown
f:SetScript("OnMouseDown", function(self, button, ...)
if button == "LeftButton" then
local r, g, b, a = TRB.Functions.GetRGBAFromString(TRB.Data.settings.warrior.fury.colors.text.dots.down, true)
TRB.UiFunctions.ShowColorPicker(r, g, b, 1-a, function(color)
local r, g, b, a
if color then
r, g, b, a = unpack(color)
else
r, g, b = ColorPickerFrame:GetColorRGB()
a = OpacitySliderFrame:GetValue()
end
controls.colors.dotDown.Texture:SetColorTexture(r, g, b, 1-a)
TRB.Data.settings.warrior.fury.colors.text.dots.down = TRB.Functions.ConvertColorDecimalToHex(r, g, b, 1-a)
end)
end
end)
]]
yCoord = yCoord - 130
controls.textDisplaySection = TRB.UiFunctions.BuildSectionHeader(parent, "Decimal Precision", 0, yCoord)
yCoord = yCoord - 50
title = "Haste / Crit / Mastery / Vers Decimal Precision"
controls.hastePrecision = TRB.UiFunctions.BuildSlider(parent, title, 0, 10, TRB.Data.settings.warrior.fury.hastePrecision, 1, 0,
sliderWidth, sliderHeight, xCoord, yCoord)
controls.hastePrecision:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
value = TRB.Functions.RoundTo(value, 0)
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.hastePrecision = value
end)
title = "Rage Decimal Precision"
controls.astralPowerPrecision = TRB.UiFunctions.BuildSlider(parent, title, 0, 1, TRB.Data.settings.warrior.fury.ragePrecision, 1, 0,
sliderWidth, sliderHeight, xCoord2, yCoord)
controls.astralPowerPrecision:SetScript("OnValueChanged", function(self, value)
local min, max = self:GetMinMaxValues()
if value > max then
value = max
elseif value < min then
value = min
end
value = TRB.Functions.RoundTo(value, 0)
self.EditBox:SetText(value)
TRB.Data.settings.warrior.fury.ragePrecision = value
end)
TRB.Frames.interfaceSettingsFrameContainer.controls.fury = controls
end
local function FuryConstructAudioAndTrackingPanel(parent)
if parent == nil then
return
end
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local controls = interfaceSettingsFrame.controls.fury
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
local title = ""
local dropdownWidth = 225
local sliderWidth = 260
local sliderHeight = 20
controls.buttons.exportButton_Warrior_Fury_AudioAndTracking = TRB.UiFunctions.BuildButton(parent, "Export Audio & Tracking", 325, yCoord-5, 225, 20)
controls.buttons.exportButton_Warrior_Fury_AudioAndTracking:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Fury Warrior (Audio & Tracking).", 1, 2, false, false, true, false, false)
end)
controls.textSection = TRB.UiFunctions.BuildSectionHeader(parent, "Audio Options", 0, yCoord)
yCoord = yCoord - 30
controls.checkBoxes.overcapAudio = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_CB3_OC_Sound", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.overcapAudio
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Play audio cue when you will overcap Rage")
f.tooltip = "Play an audio cue when your hardcast spell will overcap Rage."
f:SetChecked(TRB.Data.settings.warrior.fury.audio.overcap.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.audio.overcap.enabled = self:GetChecked()
if TRB.Data.settings.warrior.fury.audio.overcap.enabled then
PlaySoundFile(TRB.Data.settings.warrior.fury.audio.overcap.sound, TRB.Data.settings.core.audio.channel.channel)
end
end)
-- Create the dropdown, and configure its appearance
controls.dropDown.overcapAudio = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_overcapAudio", parent, "UIDropDownMenuTemplate")
controls.dropDown.overcapAudio:SetPoint("TOPLEFT", xCoord, yCoord-20)
UIDropDownMenu_SetWidth(controls.dropDown.overcapAudio, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.overcapAudio, TRB.Data.settings.warrior.fury.audio.overcap.soundName)
UIDropDownMenu_JustifyText(controls.dropDown.overcapAudio, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.overcapAudio, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local sounds = TRB.Details.addonData.libs.SharedMedia:HashTable("sound")
local soundsList = TRB.Details.addonData.libs.SharedMedia:List("sound")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(sounds) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Sounds " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(soundsList) do
if k > start and k <= start + entries then
info.text = v
info.value = sounds[v]
info.checked = sounds[v] == TRB.Data.settings.warrior.fury.audio.overcap.sound
info.func = self.SetValue
info.arg1 = sounds[v]
info.arg2 = v
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the audio
function controls.dropDown.overcapAudio:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.audio.overcap.sound = newValue
TRB.Data.settings.warrior.fury.audio.overcap.soundName = newName
UIDropDownMenu_SetText(controls.dropDown.overcapAudio, newName)
CloseDropDownMenus()
PlaySoundFile(TRB.Data.settings.warrior.fury.audio.overcap.sound, TRB.Data.settings.core.audio.channel.channel)
end
--[[
yCoord = yCoord - 60
controls.checkBoxes.suddenDeathAudio = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_suddenDeath_Sound_Checkbox", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.suddenDeathAudio
f:SetPoint("TOPLEFT", xCoord, yCoord)
getglobal(f:GetName() .. 'Text'):SetText("Play audio cue when you get a Sudden Death proc (if talented)")
f.tooltip = "Play an audio cue when you get a Sudden Death proc that allows you to use Execute/Condemn for 0 Rage and above normal execute range enemy health."
f:SetChecked(TRB.Data.settings.warrior.fury.audio.suddenDeath.enabled)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.warrior.fury.audio.suddenDeath.enabled = self:GetChecked()
if TRB.Data.settings.warrior.fury.audio.suddenDeath.enabled then
PlaySoundFile(TRB.Data.settings.warrior.fury.audio.suddenDeath.sound, TRB.Data.settings.core.audio.channel.channel)
end
end)
-- Create the dropdown, and configure its appearance
controls.dropDown.suddenDeathAudio = CreateFrame("FRAME", "TwintopResourceBar_Warrior_Fury_suddenDeath_Audio", parent, "UIDropDownMenuTemplate")
controls.dropDown.suddenDeathAudio:SetPoint("TOPLEFT", xCoord, yCoord-20)
UIDropDownMenu_SetWidth(controls.dropDown.suddenDeathAudio, dropdownWidth)
UIDropDownMenu_SetText(controls.dropDown.suddenDeathAudio, TRB.Data.settings.warrior.fury.audio.suddenDeath.soundName)
UIDropDownMenu_JustifyText(controls.dropDown.suddenDeathAudio, "LEFT")
-- Create and bind the initialization function to the dropdown menu
UIDropDownMenu_Initialize(controls.dropDown.suddenDeathAudio, function(self, level, menuList)
local entries = 25
local info = UIDropDownMenu_CreateInfo()
local sounds = TRB.Details.addonData.libs.SharedMedia:HashTable("sound")
local soundsList = TRB.Details.addonData.libs.SharedMedia:List("sound")
if (level or 1) == 1 or menuList == nil then
local menus = math.ceil(TRB.Functions.TableLength(sounds) / entries)
for i=0, menus-1 do
info.hasArrow = true
info.notCheckable = true
info.text = "Sounds " .. i+1
info.menuList = i
UIDropDownMenu_AddButton(info)
end
else
local start = entries * menuList
for k, v in pairs(soundsList) do
if k > start and k <= start + entries then
info.text = v
info.value = sounds[v]
info.checked = sounds[v] == TRB.Data.settings.warrior.fury.audio.suddenDeath.sound
info.func = self.SetValue
info.arg1 = sounds[v]
info.arg2 = v
UIDropDownMenu_AddButton(info, level)
end
end
end
end)
-- Implement the function to change the audio
function controls.dropDown.overcapAudio:SetValue(newValue, newName)
TRB.Data.settings.warrior.fury.audio.suddenDeath.sound = newValue
TRB.Data.settings.warrior.fury.audio.suddenDeath.soundName = newName
UIDropDownMenu_SetText(controls.dropDown.overcapAudio, newName)
CloseDropDownMenus()
PlaySoundFile(TRB.Data.settings.warrior.fury.audio.suddenDeath.sound, TRB.Data.settings.core.audio.channel.channel)
end
]]
TRB.Frames.interfaceSettingsFrameContainer.controls.fury = controls
end
local function FuryConstructBarTextDisplayPanel(parent, cache)
if parent == nil then
return
end
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local controls = interfaceSettingsFrame.controls.fury
local yCoord = 5
local f = nil
local maxOptionsWidth = 580
local xPadding = 10
local xPadding2 = 30
local xCoord = 5
local xCoord2 = 290
local xOffset1 = 50
local xOffset2 = xCoord2 + xOffset1
controls.buttons.exportButton_Warrior_Fury_BarText = TRB.UiFunctions.BuildButton(parent, "Export Bar Text", 325, yCoord-5, 225, 20)
controls.buttons.exportButton_Warrior_Fury_BarText:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Fury Warrior (Bar Text).", 1, 2, false, false, false, true, false)
end)
controls.textCustomSection = TRB.UiFunctions.BuildSectionHeader(parent, "Bar Display Text Customization", 0, yCoord)
yCoord = yCoord - 30
controls.labels.leftText = TRB.UiFunctions.BuildLabel(parent, "Left Text", xCoord, yCoord, 90, 20, nil, "RIGHT")
controls.textbox.left = TRB.UiFunctions.BuildTextBox(parent, TRB.Data.settings.warrior.fury.displayText.left.text,
500, 440, 24, xCoord+100, yCoord)
f = controls.textbox.left
f:SetScript("OnTextChanged", function(self, input)
TRB.Data.settings.warrior.fury.displayText.left.text = self:GetText()
TRB.Data.barTextCache = {}
TRB.Functions.IsTtdActive(TRB.Data.settings.warrior.fury)
end)
yCoord = yCoord - 30
controls.labels.middleText = TRB.UiFunctions.BuildLabel(parent, "Middle Text", xCoord, yCoord, 90, 20, nil, "RIGHT")
controls.textbox.middle = TRB.UiFunctions.BuildTextBox(parent, TRB.Data.settings.warrior.fury.displayText.middle.text,
500, 440, 24, xCoord+100, yCoord)
f = controls.textbox.middle
f:SetScript("OnTextChanged", function(self, input)
TRB.Data.settings.warrior.fury.displayText.middle.text = self:GetText()
TRB.Data.barTextCache = {}
TRB.Functions.IsTtdActive(TRB.Data.settings.warrior.fury)
end)
yCoord = yCoord - 30
controls.labels.rightText = TRB.UiFunctions.BuildLabel(parent, "Right Text", xCoord, yCoord, 90, 20, nil, "RIGHT")
controls.textbox.right = TRB.UiFunctions.BuildTextBox(parent, TRB.Data.settings.warrior.fury.displayText.right.text,
500, 440, 24, xCoord+100, yCoord)
f = controls.textbox.right
f:SetScript("OnTextChanged", function(self, input)
TRB.Data.settings.warrior.fury.displayText.right.text = self:GetText()
TRB.Data.barTextCache = {}
TRB.Functions.IsTtdActive(TRB.Data.settings.warrior.fury)
end)
yCoord = yCoord - 30
TRB.Options.CreateBarTextInstructions(cache, parent, xCoord, yCoord)
end
local function FuryConstructOptionsPanel(cache)
local interfaceSettingsFrame = TRB.Frames.interfaceSettingsFrameContainer
local parent = interfaceSettingsFrame.panel
local controls = interfaceSettingsFrame.controls.fury or {}
local yCoord = 0
local f = nil
local xPadding = 10
local xPadding2 = 30
local xMax = 550
local xCoord = 0
local xCoord2 = 325
local xOffset1 = 50
local xOffset2 = 275
controls.colors = {}
controls.labels = {}
controls.textbox = {}
controls.checkBoxes = {}
controls.dropDown = {}
interfaceSettingsFrame.furyDisplayPanel = CreateFrame("Frame", "TwintopResourceBar_Options_Warrior_Fury", UIParent)
interfaceSettingsFrame.furyDisplayPanel.name = "Fury Warrior"
---@diagnostic disable-next-line: undefined-field
interfaceSettingsFrame.furyDisplayPanel.parent = parent.name
InterfaceOptions_AddCategory(interfaceSettingsFrame.furyDisplayPanel)
parent = interfaceSettingsFrame.furyDisplayPanel
controls.buttons = controls.buttons or {}
controls.textSection = TRB.UiFunctions.BuildSectionHeader(parent, "Fury Warrior", xCoord+xPadding, yCoord-5)
controls.checkBoxes.furyWarriorEnabled = CreateFrame("CheckButton", "TwintopResourceBar_Warrior_Fury_furyWarriorEnabled", parent, "ChatConfigCheckButtonTemplate")
f = controls.checkBoxes.furyWarriorEnabled
f:SetPoint("TOPLEFT", 250, yCoord-10)
getglobal(f:GetName() .. 'Text'):SetText("Enabled")
f.tooltip = "Is Twintop's Resource Bar enabled for the Fury Warrior specialization? If unchecked, the bar will not function (including the population of global variables!)."
f:SetChecked(TRB.Data.settings.core.enabled.warrior.fury)
f:SetScript("OnClick", function(self, ...)
TRB.Data.settings.core.enabled.warrior.fury = self:GetChecked()
TRB.Functions.EventRegistration()
TRB.UiFunctions.ToggleCheckboxOnOff(controls.checkBoxes.furyWarriorEnabled, TRB.Data.settings.core.enabled.warrior.fury, true)
end)
TRB.UiFunctions.ToggleCheckboxOnOff(controls.checkBoxes.furyWarriorEnabled, TRB.Data.settings.core.enabled.warrior.fury, true)
controls.buttons.importButton = TRB.UiFunctions.BuildButton(parent, "Import", 345, yCoord-10, 90, 20)
controls.buttons.importButton:SetFrameLevel(10000)
controls.buttons.importButton:SetScript("OnClick", function(self, ...)
StaticPopup_Show("TwintopResourceBar_Import")
end)
controls.buttons.exportButton_Warrior_Fury_All = TRB.UiFunctions.BuildButton(parent, "Export Specialization", 440, yCoord-10, 150, 20)
controls.buttons.exportButton_Warrior_Fury_All:SetScript("OnClick", function(self, ...)
TRB.Functions.ExportPopup("Copy the string below to share your Twintop's Resource Bar configuration for Fury Warrior (All).", 1, 2, true, true, true, true, false)
end)
yCoord = yCoord - 42
local tabs = {}
local tabsheets = {}
tabs[1] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Fury_Tab2", "Bar Display", 1, parent, 85)
tabs[1]:SetPoint("TOPLEFT", 15, yCoord)
tabs[2] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Fury_Tab3", "Font & Text", 2, parent, 85, tabs[1])
tabs[3] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Fury_Tab4", "Audio & Tracking", 3, parent, 120, tabs[2])
tabs[4] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Fury_Tab5", "Bar Text", 4, parent, 60, tabs[3])
tabs[5] = TRB.UiFunctions.CreateTab("TwintopResourceBar_Options_Warrior_Fury_Tab1", "Reset Defaults", 5, parent, 100, tabs[4])
PanelTemplates_TabResize(tabs[1], 0)
PanelTemplates_TabResize(tabs[2], 0)
PanelTemplates_TabResize(tabs[3], 0)
PanelTemplates_TabResize(tabs[4], 0)
PanelTemplates_TabResize(tabs[5], 0)
yCoord = yCoord - 15
for i = 1, 5 do
tabsheets[i] = TRB.UiFunctions.CreateTabFrameContainer("TwintopResourceBar_Warrior_Fury_LayoutPanel" .. i, parent)
tabsheets[i]:Hide()
tabsheets[i]:SetPoint("TOPLEFT", 10, yCoord)
end
tabsheets[1]:Show()
tabsheets[1].selected = true
tabs[1]:SetNormalFontObject(TRB.Options.fonts.options.tabHighlightSmall)
parent.tabs = tabs
parent.tabsheets = tabsheets
parent.lastTab = tabsheets[1]
parent.lastTabId = 1
TRB.Frames.interfaceSettingsFrameContainer = interfaceSettingsFrame
TRB.Frames.interfaceSettingsFrameContainer.controls.fury = controls
FuryConstructBarColorsAndBehaviorPanel(tabsheets[1].scrollFrame.scrollChild)
FuryConstructFontAndTextPanel(tabsheets[2].scrollFrame.scrollChild)
FuryConstructAudioAndTrackingPanel(tabsheets[3].scrollFrame.scrollChild)
FuryConstructBarTextDisplayPanel(tabsheets[4].scrollFrame.scrollChild, cache)
FuryConstructResetDefaultsPanel(tabsheets[5].scrollFrame.scrollChild)
end
local function ConstructOptionsPanel(specCache)
TRB.Options.ConstructOptionsPanel()
ArmsConstructOptionsPanel(specCache.arms)
FuryConstructOptionsPanel(specCache.fury)
end
TRB.Options.Warrior.ConstructOptionsPanel = ConstructOptionsPanel
end |
local pluginv = require(script.Parent.Parent.Parent.Library.Plugin)
local Selection = game:GetService("Selection")
local waypointModule = {
{
-- "WaypointPositionText" 1
{
{ "Name", "WaypointPositionText" },
{ "AnchorPoint", Vector2.new(1, 1) },
{ "BackgroundTransparency", 1 },
{ "BorderSizePixel", 0 },
{ "Font", Enum.Font.Code },
{ "Position", UDim2.new(0.87, 0, 0.14, 0) },
{ "Size", UDim2.new(0.05, 0, 0.05, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "Position" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 10 },
{ "TextXAlignment", Enum.TextXAlignment.Right },
{ "ZIndex", 10 },
},
-- "WaypointRotationText" 2
{
{ "Name", "WaypointRotationText" },
{ "AnchorPoint", Vector2.new(1, 1) },
{ "BackgroundTransparency", 1 },
{ "BorderSizePixel", 0 },
{ "Font", Enum.Font.Code },
{ "Position", UDim2.new(0.87, 0, 0.22, 0) },
{ "Size", UDim2.new(0.05, 0, 0.05, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "Rotation" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 10 },
{ "TextXAlignment", Enum.TextXAlignment.Right },
{ "ZIndex", 10 },
},
},
{
-- "WaypointMenu" 1
{
{ "Name", "WaypointMenu" },
{ "AnchorPoint", Vector2.new(0, 0) },
{ "BackgroundColor3", Color3.new(46 / 255, 46 / 255, 46 / 255) },
{ "BorderSizePixel", 0 },
{ "Position", UDim2.new(0, 0, 0, 0) },
{ "Size", UDim2.new(1, 0, 1, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "ZIndex", 1 },
},
},
{
-- "GetCurrentTransform" 1
{
{ "Name", "GetCurrentTransform" },
{ "AnchorPoint", Vector2.new(0.5, 0) },
{ "BackgroundColor3", Color3.new(35 / 255, 35 / 255, 35 / 255) },
{ "BorderSizePixel", 1 },
{ "BorderColor3", Color3.new(0 / 255, 0 / 255, 0 / 255) },
{ "Font", Enum.Font.Code },
{ "Position", UDim2.new(0.65, 0, 0.27, 0) },
{ "Size", UDim2.new(0.45, 0, 0.03, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "Get current transform" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 8 },
{ "ZIndex", 3 },
},
-- "SaveWaypoint" 2
{
{ "Name", "SaveWaypoint" },
{ "AnchorPoint", Vector2.new(0.5, 0) },
{ "BackgroundColor3", Color3.new(35 / 255, 35 / 255, 35 / 255) },
{ "BorderSizePixel", 1 },
{ "BorderColor3", Color3.new(0 / 255, 0 / 255, 0 / 255) },
{ "Font", Enum.Font.Code },
{ "Position", UDim2.new(0.5, 0, 0.32, 0) },
{ "Size", UDim2.new(0.75, 0, 0.06, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "Save transform" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 13 },
{ "ZIndex", 3 },
},
},
{},
{
-- "WaypointPositionInputX" 1
{
{ "Name", "WaypointPositionInputX" },
{ "AnchorPoint", Vector2.new(0.5, 0) },
{ "BackgroundColor3", Color3.new(46 / 255, 46 / 255, 46 / 255) },
{ "BorderSizePixel", 1 },
{ "BorderColor3", Color3.new(180 / 255, 0 / 255, 0 / 255) },
{ "Font", Enum.Font.Code },
{ "PlaceholderText", "X" },
{ "PlaceholderColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "Position", UDim2.new(0.22, 0, 0.13, 0) },
{ "Size", UDim2.new(0.2, 0, 0.04, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 11 },
{ "ZIndex", 3 },
},
-- "WaypointPositionInputY" 2
{
{ "Name", "WaypointPositionInputY" },
{ "AnchorPoint", Vector2.new(0.5, 0) },
{ "BackgroundColor3", Color3.new(46 / 255, 46 / 255, 46 / 255) },
{ "BorderSizePixel", 1 },
{ "BorderColor3", Color3.new(0 / 255, 180 / 255, 0 / 255) },
{ "Font", Enum.Font.Code },
{ "PlaceholderText", "Y" },
{ "PlaceholderColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "Position", UDim2.new(0.5, 0, 0.13, 0) },
{ "Size", UDim2.new(0.2, 0, 0.04, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 11 },
{ "ZIndex", 3 },
},
-- "WaypointPositionInputZ" 3
{
{ "Name", "WaypointPositionInputZ" },
{ "AnchorPoint", Vector2.new(0.5, 0) },
{ "BackgroundColor3", Color3.new(46 / 255, 46 / 255, 46 / 255) },
{ "BorderSizePixel", 1 },
{ "BorderColor3", Color3.new(0 / 255, 0 / 255, 180 / 255) },
{ "Font", Enum.Font.Code },
{ "PlaceholderText", "Z" },
{ "PlaceholderColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "Position", UDim2.new(0.78, 0, 0.13, 0) },
{ "Size", UDim2.new(0.2, 0, 0.04, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 11 },
{ "ZIndex", 3 },
},
-- "WaypointRotationInputX" 4
{
{ "Name", "WaypointRotationInputX" },
{ "AnchorPoint", Vector2.new(0.5, 0) },
{ "BackgroundColor3", Color3.new(46 / 255, 46 / 255, 46 / 255) },
{ "BorderSizePixel", 1 },
{ "BorderColor3", Color3.new(180 / 255, 0 / 255, 0 / 255) },
{ "Font", Enum.Font.Code },
{ "PlaceholderText", "X" },
{ "PlaceholderColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "Position", UDim2.new(0.22, 0, 0.21, 0) },
{ "Size", UDim2.new(0.2, 0, 0.04, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 11 },
{ "ZIndex", 3 },
},
-- "WaypointRotationInputY" 5
{
{ "Name", "WaypointRotationInputY" },
{ "AnchorPoint", Vector2.new(0.5, 0) },
{ "BackgroundColor3", Color3.new(46 / 255, 46 / 255, 46 / 255) },
{ "BorderSizePixel", 1 },
{ "BorderColor3", Color3.new(0 / 255, 180 / 255, 0 / 255) },
{ "Font", Enum.Font.Code },
{ "PlaceholderText", "Y" },
{ "PlaceholderColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "Position", UDim2.new(0.5, 0, 0.21, 0) },
{ "Size", UDim2.new(0.2, 0, 0.04, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 11 },
{ "ZIndex", 3 },
},
-- "WaypointRotationInputZ" 6
{
{ "Name", "WaypointRotationInputZ" },
{ "AnchorPoint", Vector2.new(0.5, 0) },
{ "BackgroundColor3", Color3.new(46 / 255, 46 / 255, 46 / 255) },
{ "BorderSizePixel", 1 },
{ "BorderColor3", Color3.new(0 / 255, 0 / 255, 180 / 255) },
{ "Font", Enum.Font.Code },
{ "PlaceholderText", "Z" },
{ "PlaceholderColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "Position", UDim2.new(0.78, 0, 0.21, 0) },
{ "Size", UDim2.new(0.2, 0, 0.04, 0) },
{ "SizeConstraint", Enum.SizeConstraint.RelativeXY },
{ "Text", "" },
{ "TextColor3", Color3.new(255 / 255, 255 / 255, 255 / 255) },
{ "TextSize", 11 },
{ "ZIndex", 3 },
},
},
}
function waypointModule:GetCurrentTransform(a, b, c, d, e, f)
return function()
local function RoundNumber(n, dp)
return math.floor(n * 10 ^ dp) / 10 ^ dp
end
local dp = 5
local cf = workspace.CurrentCamera.CFrame
local p1, p2, p3, r1, r2, r3 = cf.Position.X, cf.Position.Y, cf.Position.Z, cf:ToEulerAnglesXYZ()
local t1 = table.pack(a, b, c, d, e, f)
local t2 = table.pack(p1, p2, p3, math.deg(r1), math.deg(r2), math.deg(r3))
for i = 1, t1["n"], 1 do
t1[i].Text = RoundNumber(t2[i], dp)
end
end
end
function waypointModule:SaveTransform(a, b, c, d, e, f, module)
return function()
local function CleanString(a)
return string.gsub(a, "%.", "")
end
local check = false
local str = "("
.. a.Text
.. ", "
.. b.Text
.. ", "
.. c.Text
.. "), ("
.. d.Text
.. ", "
.. e.Text
.. ", "
.. f.Text
.. ")"
local t = {}
local t1 = table.pack(a, b, c, d, e, f)
local key = ""
for i1, i2 in ipairs(t1) do
key = key .. CleanString(i2.Text)
table.insert(t, #t + 1, i2.Text)
end
table.insert(t, 1, key)
for i1, i2 in ipairs(module.Saved) do
if i2[1] == key then
check = true
end
end
if check == true then
warn("Transform already exists, save unsuccessful")
else
table.insert(module.Saved, #module.Saved + 1, t)
warn("Saved transform " .. #module.Saved .. " at " .. str)
end
end
end
return waypointModule
|
require "Client.Scripts.Modulus.RootUI.Data.SkillItemData" |
-----------------------------------
-- Area: Windurst Waters
-- NPC: Chamama
-- Involved In Quest: Inspector's Gadget
-- Starts Quest: In a Pickle
-----------------------------------
local ID = require("scripts/zones/Windurst_Waters/IDs");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/titles");
-----------------------------------
function onTrade(player,npc,trade)
local FakeMoustache = player:hasKeyItem(tpz.ki.FAKE_MOUSTACHE);
local InvisibleManSticker = player:hasKeyItem(tpz.ki.INVISIBLE_MAN_STICKER);
local InAPickle = player:getQuestStatus(WINDURST,tpz.quest.id.windurst.IN_A_PICKLE);
local count = trade:getItemCount();
local gil = trade:getGil();
if ((InAPickle == QUEST_ACCEPTED or InAPickle == QUEST_COMPLETED) and trade:hasItemQty(583,1) == true and count == 1 and gil == 0) then
local rand = math.random(1,4);
if (rand <= 2) then
if (InAPickle == QUEST_ACCEPTED) then
player:startEvent(659); -- IN A PICKLE: Quest Turn In (1st Time)
elseif (InAPickle == QUEST_COMPLETED) then
player:startEvent(662,200);
end
elseif (rand == 3) then
player:startEvent(657); -- IN A PICKLE: Too Light
player:tradeComplete(trade);
elseif (rand == 4) then
player:startEvent(658); -- IN A PICKLE: Too Small
player:tradeComplete(trade);
end
elseif (FakeMoustache == false) then
local InspectorsGadget = player:getQuestStatus(WINDURST,tpz.quest.id.windurst.INSPECTOR_S_GADGET);
if (InspectorsGadget == QUEST_ACCEPTED) then
local SarutaCotton = trade:hasItemQty(834,4);
if (SarutaCotton == true and count == 4) then
player:startEvent(552);
end
end
elseif (InvisibleManSticker == false) then
local ThePromise = player:getQuestStatus(WINDURST,tpz.quest.id.windurst.THE_PROMISE);
if (ThePromise == QUEST_ACCEPTED) then
local ShoalWeed = trade:hasItemQty(1148,1);
if (ShoalWeed == true and count == 1) then
player:startEvent(799,0,0,tpz.ki.INVISIBLE_MAN_STICKER);
end
end
end
end;
function onTrigger(player,npc)
local InspectorsGadget = player:getQuestStatus(WINDURST,tpz.quest.id.windurst.INSPECTOR_S_GADGET);
local ThePromise = player:getQuestStatus(WINDURST,tpz.quest.id.windurst.THE_PROMISE);
local InAPickle = player:getQuestStatus(WINDURST,tpz.quest.id.windurst.IN_A_PICKLE);
local NeedToZone = player:needToZone();
if (ThePromise == QUEST_ACCEPTED) then
local InvisibleManSticker = player:hasKeyItem(tpz.ki.INVISIBLE_MAN_STICKER);
if (InvisibleManSticker == true) then
player:startEvent(800);
else
local ThePromiseVar = player:getCharVar("ThePromise");
if (ThePromiseVar == 1) then
player:startEvent(798,0,1148,tpz.ki.INVISIBLE_MAN_STICKER);
else
player:startEvent(797,0,1148,tpz.ki.INVISIBLE_MAN_STICKER);
end
end
elseif (InspectorsGadget == QUEST_ACCEPTED) then
local FakeMoustache = player:hasKeyItem(tpz.ki.FAKE_MOUSTACHE);
-- printf("mustach check");
if (FakeMoustache == true) then
player:startEvent(553);
else
player:startEvent(551,0,tpz.ki.FAKE_MOUSTACHE);
end
elseif (InAPickle == QUEST_AVAILABLE and NeedToZone == false) then
local rand = math.random(1,2);
if (rand == 1) then
player:startEvent(654,0,4444); -- IN A PICKLE + RARAB TAIL: Quest Begin
else
player:startEvent(651); -- Standard Conversation
end
elseif (InAPickle == QUEST_ACCEPTED or player:getCharVar("QuestInAPickle_var") == 1) then
player:startEvent(655,0,4444); -- IN A PICKLE + RARAB TAIL: Quest Objective Reminder
elseif (InAPickle == QUEST_COMPLETED and NeedToZone) then
player:startEvent(660); -- IN A PICKLE: After Quest
elseif (InAPickle == QUEST_COMPLETED and NeedToZone == false and player:getCharVar("QuestInAPickle_var") ~= 1) then
local rand = math.random(1,2)
if (rand == 1) then
player:startEvent(661); -- IN A PICKLE: Repeatable Quest Begin
else
player:startEvent(651); -- Standard Conversation
end
else
player:startEvent(651); -- Standard Conversation
end
-- player:delQuest(WINDURST,tpz.quest.id.windurst.IN_A_PICKLE); [[[[[[[[[[[[[ FOR TESTING ONLY ]]]]]]]]]]]]]
end;
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
function onEventFinish(player,csid,option)
if (csid == 552) then
player:tradeComplete();
player:addKeyItem(tpz.ki.FAKE_MOUSTACHE);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.FAKE_MOUSTACHE);
elseif (csid == 797) then
player:setCharVar("ThePromise",1);
elseif (csid == 799) then
player:tradeComplete();
player:addKeyItem(tpz.ki.INVISIBLE_MAN_STICKER);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.INVISIBLE_MAN_STICKER);
elseif (csid == 654 and option == 1) then -- IN A PICKLE + RARAB TAIL: Quest Begin
player:addQuest(WINDURST,tpz.quest.id.windurst.IN_A_PICKLE);
elseif (csid == 659) then -- IN A PICKLE: Quest Turn In (1st Time)
player:tradeComplete(trade);
player:completeQuest(WINDURST,tpz.quest.id.windurst.IN_A_PICKLE);
player:needToZone(true);
player:addItem(12505);
player:messageSpecial(ID.text.ITEM_OBTAINED,12505);
player:addGil(GIL_RATE*200);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*200);
player:addFame(WINDURST,75);
elseif (csid == 661 and option == 1) then
player:setCharVar("QuestInAPickle_var",1)
elseif (csid == 662) then -- IN A PICKLE + 200 GIL: Repeatable Quest Turn In
player:tradeComplete(trade);
player:needToZone(true);
player:addGil(GIL_RATE*200);
player:addFame(WINDURST,8);
player:setCharVar("QuestInAPickle_var",0)
end
end;
|
--[[
Renamer.lua
--]]
local Renamer, dbg, dbgf = Object:newClass{ className = "Renamer", register = true } -- jre debug, and fmt debug funcs, as you prefer.
--- Constructor for extending class.
--
function Renamer:newClass( t )
return Object.newClass( self, t )
end
--- Constructor for new instance.
--
function Renamer:new( t )
return Object.new( self, t )
end
function Renamer:init()
if not app:isPluginEnabled() then
app:show{ info="Plugin must be enabled in order for '^1' to function (via 'Library Menu -> Plugin Extras').",
subs = app:getPluginName(),
actionPrefKey = "plugin must be enabled"
}
return -- return uninitialized.
else
-- proceed to attempt initialization.
-- Note: non-nil filenamePreset member indicates initialization was done OK.
end
local filename = str:fmtx( "^1.lrtemplate", app:getPluginName() )
local template = LrPathUtils.child( _PLUGIN.path, filename )
-- Note: although original method for finding filename-preset dir will work here, since it's writing to *both* places if appropriate,
-- then reading back in *either* place, this hap-hazard method is deprecated in favor of it's version 2.
--[[ this until 19/May/2014 4:36:
local withCat, dir, altDir = lightroom:getFilenamePresetDir() -- whacky, but worky... ### get-preset-dir?
local dirs
if withCat ~= nil then
if withCat then
app:log( "There are filename presets stored with catalog in '^1'", dir ) -- but that does not necessarily mean they are currently being used there.
Debug.pauseIf( not str:is( dir ) or not str:is( altDir ), dir, altDir )
dirs = { dir, altDir }
else -- I think if there are none stored with catalog, then the proper target can not possibly be with catalog.
app:log( "Filename presets are stored in Lightroom app-data (not with catalog) in '^1'", dir )
dirs = { dir } -- Note: I just checked - as soon as ya say: "store presets with catalog", it creates the dir in catalog, which remains even if you then uncheck it.
end
else
app:logWarning( "Not clear where filename presets are stored just yet, hopefully after template copy / Lr restart it will become clear." )
dirs = { dir, altDir }
end
--]]
-- this after 19/May/2014 4:37: (###2: keep eye on it).
local dir, oops = lightroom:getPresetDir( "Filename Templates" )
if not dir then app:error( oops ) end
local dirs = { dir }
-------------------------------
local presets = LrApplication.filenamePresets()
local pluginName = app:getPluginName()
app:logv( "Looking for filename preset named '^1'", pluginName )
for k, v in pairs( presets ) do
if str:isEqualIgnoringCase( k, pluginName ) then
app:log( "Got requisite filename preset." )
self.filenamePreset = v -- UUID on win7/64-Lr4, but doc says could be path - hmmm......
break
else
app:logv( "'^1' is not it...", k )
end
end
if not self.filenamePreset then
if #dirs > 1 then
app:logWarning( "Not clear if presets are stored with catalog or not, attempting to cover all bases..." )
end
local goodNuff = false
for i, tDir in ipairs( dirs ) do
-- Debug.pause( tDir, fso:existsAsDir( tDir ) )
if fso:existsAsDir( tDir ) then
local destPath = LrPathUtils.child( tDir, filename )
local s, m = fso:copyFile( template, destPath, true, true ) -- do not create dir - it's existence has been pre-validated - do overwrite file though, even if it already exists.
if s then
app:log( "Copied requisite filename template '^1' to '^2'.", template, destPath )
goodNuff = true
else
app:logWarning( "Unable to copy requisite filenameing template (^1) to Lightroom preset folder: '^2'.", template, tDir )
app:show{ warning="Unable to copy requisite filenameing template (^1) to Lightroom's filename presets folder: '^2'.",
subs = { filename, tDir },
}
end
else
app:logv( "No filename preset dir here: ^1", tDir )
end
end
if goodNuff then
local f, qual = lightroom:prepareForRestart() -- restart with active catalog.
if f then
local typ = 'confirm'
local msg = "Requisite filenaming template was just copied to Lightroom's filenaming templates folder - Lightroom must be restarted.\n \nClick 'OK' to restart Lightroom now, or 'Cancel' if you prefer to restart manually."
if not qual then
-- msg = "Restart Lightroom?"
--typ = 'confirm'
else
msg = msg .. "\n \n" .. qual
--typ = 'warning'
end
local button = app:show{ [typ]=msg }
if button == 'ok' then
f() -- execute restart function.
end
else
app:log( "Unable to initiate restart programmatically, restart will have to be manual - ^1", qual )
app:show{ warning="Requisite filenaming template was just copied to Lightroom's filenaming templates folder. You must restart Lightroom, before you can rename files using ^1",
subs = app:getPluginName(),
}
end
else
app:error( "Unable to setup requisite filename preset." )
end
-- else hunky-dory.
end
end
-- common things called in service finale method.
function Renamer:_wrapOp( call )
if call.testMode then
app:log( "*** TEST MODE ONLY - NO CHANGES WERE BE MADE TO CATALOG (EXCEPT RENAME COLLECTION) OR PHOTO FILES" )
else
app:log( "*** REAL MODE - CHANGES MAY HAVE BEEN MADE TO CATALOG AS INDICATED ABOVE" )
end
end
-- called first off upon service method entry.
function Renamer:_initOp( call )
local s, m = background:waitForInit( 30, 10 ) -- initial delay, retry interval - only requires such a long wait when reloading upon re-export is checked.
if not s then
app:error( m )
end
call.testMode = app:getPref( 'testMode' )
if call.testMode == true then
app:log( "*** TEST MODE ONLY - NO CHANGES WILL BE MADE TO CATALOG (EXCEPT RENAME COLLECTION) OR PHOTO FILES" )
--app:logVerbose( "If wasn't test mode, collection for renamed files would have been created or validated." )
elseif call.testMode == false then
app:log( "*** REAL MODE - CHANGES MAY BE MADE TO CATALOG AS INDICATED BELOW" )
else
error( "invalid test mode" )
end
-- now regardless of test mode
call.renameColl = cat:assurePluginCollection( "Renamed" ) -- throws error if no can do.
app:logVerbose( "Collection for renamed files created or validated: ^1/^2", app:getPluginName(), call.renameColl:getName() )
end
-- init for run, after clear for takeoff...
-- props only used for part-1 of rename sequence.
-- return true or nil, errm.
function Renamer:_initRun( call, photos, props )
if props then -- rename-start
local init = app:getPref( 'init' )
if init ~= nil then
if type( init ) ~= 'function' then
app:error( "bad init - must be function" )
end
local errm = init{ call=call, photos=photos, props=props }
if str:is( errm ) then
return nil, "error message returned by init function: " .. errm
else -- user init pref executed ok
app:log( "init function from preset (advanced settings) executed ok" )
end
else
app:logv( "No init function defined." )
end
-- else rename-finish: dont call pref init func.
end
call.fieldId = app:getPref( 'formattedMetadataFieldIdForRenaming' ) or 'headline'
call.photos = photos
-- *** UPDATE _addMetaForPhoto method too when metadata changes:
-- this can be time consuming - consider progress scope.
call.rawMeta = cat:getBatchRawMetadata( photos, { 'path', 'isVirtualCopy', 'masterPhoto' } )
call.fmtMeta = cat:getBatchFormattedMetadata( photos, { 'fileName', 'copyName' } )
app:log( "Using '^1' field for new filenames.", call.fieldId )
app:logVerbose( "Filenaming preset: ^1", self.filenamePreset )
return true
end
function Renamer:_endRun( call )
local finale = app:getPref( 'finale' )
if finale ~= nil then
if type( finale ) ~= 'function' then
app:error( "bad finale - must be function" )
end
local errm = finale{ call=call }
if str:is( errm ) then
return nil, "error message returned by finale function: " .. errm
else -- user finale pref executed ok
app:log( "finale function from preset (advanced settings) executed ok" )
end
end
end
-- guts of cleanup function which returns headlines, and clears temp storage.
-- logs move stats upon success, and returns true,
-- else logs no finale message, but returns false, err-msg.
function Renamer:_renameFinish( call )
local nFields = 0
assert( call.testMode ~= nil, "no test mode" )
app:log()
call:setCaption( "Moving ^1 back to proper location.", call.fieldId )
local function renameFinish( context, phase )
for i, photo in ipairs( call.photos ) do
repeat
local photoPath = call.rawMeta[photo].path
app:log( "Cleaning up ^1", photoPath )
local isVirtualCopy = call.rawMeta[photo].isVirtualCopy
if isVirtualCopy then
app:log( "Skipping virtual copy '^1'", call.fmtMeta[photo].copyName )
break
end
if fso:existsAsFile( photoPath ) then
-- splattn
else
app:logWarning( "Missing file: ^1", photoPath )
break
end
assert( call.fmtMeta[photo], "formatted metadata is not initialized" )
local prev = photo:getPropertyForPlugin( _PLUGIN, "temp_", nil, true ) -- version, no-throw.
if prev == nil then
prev = "" -- looks like Adobe is doing same as I do: converting nil to "nil" - but in this case, it won't do...
end
if not call.testMode then
photo:setRawMetadata( call.fieldId, prev ) -- regardless
photo:setPropertyForPlugin( _PLUGIN, "temp_", nil ) -- unlike headline field, it is ok to set plugin metadata to nil.
else
app:log( "*** TEST MODE ONLY - NO CHANGE MADE TO CATALOG OR PHOTO FILES (EXCEPT RENAME COLLECTION)" )
end
if str:is( prev ) then
app:log( "^1 data restored", call.fieldId )
nFields = nFields + 1
else
app:log( "No ^1 to move back.", call.fieldId )
end
until true
if call:isQuit() then
app:error( "^1 has been aborted or canceled." ) -- Assures catalog not left in a half-baked state if user cancels.
else
call:setPortionComplete( i, #call.photos )
end
end
end
local s, m
if call.testMode then
s, m = LrTasks.pcall( renameFinish ) -- assures catalog won't change.
else
s, m = cat:update( 15, call.name, renameFinish )
end
if s then
app:log()
app:log( "^1 has been moved back to it's original location.", str:nItems( nFields, str:fmtx( "^1 fields", call.fieldId ) ) )
return true
else
-- app:logErr( "There has been an error: ^1 - your catalog was not altered.", m )
-- app:show{ error="There has been an error: ^1 - your catalog was not altered.", m }
return false, m
end
end
-- Menu handler.
function Renamer:renameStart()
--app:show( self:toString() .. " rename" )
app:call( Service:new{ name="Rename Files - Start", async=true, progress={ caption="Dialog box needs attention..." }, main=function( call )
self:_initOp( call )
if not self.filenamePreset then
app:show{ warning="Requisite filenameing preset not found - try restarting Lightroom." }
call:cancel()
return
end
local photos = catalog:getTargetPhotos()
if #photos == 0 then
app:show{ warning="No photos in filmstrip." }
call:cancel()
return
end
local renameBase = app:getPref( 'renameBase' )
if renameBase == nil then
app:show{ error="No rename-base function." }
call:cancel()
return
end
if type( renameBase ) ~= 'function' then
app:show{ error="rename must be a function." }
call:cancel()
return
end
local presetName = app.prefMgr:getPresetName() -- current preset name.
local viPref = app:getPref( 'viewItems' )
local vi
local props = LrBinding.makePropertyTable( call.context )
if viPref ~= nil then
if type( viPref ) == 'function' then
vi = viPref{ call=call, props=props }
if vi == nil then
app:show{ error="no view items returned - set viewItems to nil, unless it will return view items." }
call:cancel()
return
end
else
app:show{ error="viewItems must be a function." }
call:cancel()
return
end
else
app:log( "No view items." )
end
if vi == nil then
vi = {}
else
vi[#vi + 1] = vf:spacer{ height = 10 }
end
local ttl
if call.testMode then
ttl = "*** TEST MODE ONLY, NO CHANGES WILL BE MADE TO YOUR CATALOG (EXCEPT RENAME COLLECTION) OR PHOTO FILES.\n(you have to visit plugin-manager to enable real mode)"
else
ttl = "*** REAL MODE: CHANGES MAY BE MADE TO YOUR CATALOG, AS INDICATED IN LOG FILE UPON COMPLETION.\n(visit plugin manager if you want to try test mode first)"
end
vi[#vi + 1] =
vf:static_text {
title = ttl,
fill_horizontal = 1,
}
local buttons
local collPhotos = call.renameColl:getPhotos()
if #collPhotos > 0 then
buttons = { dia:btn( "Yes - empty rename collection first", 'other' ), dia:btn( "Yes - add to rename collection", 'ok' ) }
vi[#vi + 1] = vf:spacer{ height = 10 }
vi[#vi + 1] =
vf:static_text {
title = str:fmtx( "^1 in rename collection", str:nItems( #collPhotos, "item" ) ),
fill_horizontal = 1,
}
else
buttons = { dia:btn( "OK", 'ok' ) }
end
local answer = app:show{ confirm="Rename ^1 according to '^2' (plugin manager preset)?",
subs = { str:nItems( #photos, "photos" ), presetName },
buttons = buttons,
viewItems = vi,
}
if answer == 'cancel' then
call:cancel()
return
end
local s, m = self:_initRun( call, photos, props )
if s then
-- ok - details already logged.
else
app:logErr( m )
return
end
-- fall-through => it's gonna happen.
local changes = {}
local nFields = 0
app:log()
call:setCaption( "Preparing for you to rename your files..." )
-- executes with write access if not test mode.
local function renameStart( context, phase )
if phase == 1 then
if answer == 'other' then
if not call.testMode then
call.renameColl:removeAllPhotos()
app:log( "Rename collection cleared." )
else
local s, m = cat:update( 30, "Clear rename collection", function( context, phase )
call.renameColl:removeAllPhotos()
end )
if s then
app:log( "Rename collection cleared." )
else
app:error( "Unable to clear rename collection - ^1", m )
end
end
else
app:log( "Rename collection not emptied." )
end
-- perhaps best to do all photos in one swoop, so that user does not have to figure out which photos were renamed and which not, to reselect and try again... - all or nothing this is.
-- virtual copies? ###3 - perhaps a better handling would be to do the master, but only once: record that it was done..
for i, photo in ipairs( call.photos ) do
repeat
local photoPath = call.rawMeta[photo].path
app:log( "Processing ^1", photoPath )
local isVirtualCopy = call.rawMeta[photo].isVirtualCopy
if isVirtualCopy then
app:log( "Skipping virtual copy '^1'", call.fmtMeta[photo].copyName )
break
end
if fso:existsAsFile( photoPath ) then
-- splattn
else
app:logWarning( "Missing file: ^1", photoPath )
break
end
assert( call.fmtMeta[photo], "formatted metadata is not initialized" )
local oldName = call.fmtMeta[photo].fileName
local oldBase = LrPathUtils.removeExtension( oldName )
local oldExt = LrPathUtils.extension( oldName )
assert( str:is( oldExt ), "old name has no extension" )
local folderPath = LrPathUtils.parent( photoPath )
local newBase, msg = renameBase{ call=call, photo=photo, photoPath=photoPath, folderPath=folderPath, base=oldBase, ext=oldExt }
if call:isQuit() then
app:error( "^1 aborted or canceled.", call.name )
end
if not str:is( newBase ) then
app:error( "No (base) name returned from rename function - ^1", str:to( msg or "nothing to add." ) ) -- toss the whole deal, if any errors - so we don't end up with a partially done job.
else
newBase = LrStringUtils.trimWhitespace( newBase )
end
if str:is( newBase ) then
if msg then
call.specialFlag = true
changes[#changes + 1] = photo
else
local saveBase = newBase
newBase = newBase:gsub( "[\\/\"<>|!:?*]", function( s )
if s == "\\" then
return "{bs}"
elseif s == "/" then
return "{fs}"
elseif s == "\"" then
return "{quote}"
elseif s == "<" then
return "{lt}"
elseif s == ">" then
return "{gt}"
elseif s == "|" then
return "{bar}"
elseif s == '!' then
return "{excl}"
elseif s == ":" then
return "{c}"
elseif s == "?" then
return "{q}"
elseif s == "*" then
return "{star}"
else
return "{oops}"
end
end )
if newBase ~= saveBase then
app:logW( "\"{x}\" substituted for illegal characters." )
end
local newName = LrPathUtils.addExtension( newBase, oldExt ) -- probably not even used, except for logging(?)
if newBase == oldBase then -- Note: it *is* legal to rename file with same letters, but different case.
app:log( "Name will be same: '^1'.", oldName )
else
changes[#changes + 1] = photo
if call.testMode then
app:log( "Old name is: '^1' - if NOT test mode, and YOU (plugin user) renamed via '^3' template, as mentioned in the instructions, new name would be: '^2'", oldName, newName, app:getPluginName() )
else
app:log( "Old name is: '^1' - if YOU (plugin user) rename via '^3' template, as mentioned in the instructions, new name will be: '^2'", oldName, newName, app:getPluginName() )
end
end
end
else
call.specialFlag = true -- this is a field-loader-type plugin, presumably... Reminder: it's entirely possible that special flag is NOT set, when it's a field loader preset, since metadata may never by nil, like 'path' for example.
app:log( "*** no new filename has been returned, so do not attempt to rename... (assuming FileRenamer is being used for some sorta \"field loader\" type functionality..." )
end
local prevField = photo:getPropertyForPlugin( _PLUGIN, "temp_", nil, true ) -- version, no-throw.
local field = photo:getFormattedMetadata( call.fieldId )
if call.specialFlag then
-- field loaders bypass temp field saving / restoral.
else
if str:is( prevField ) then
app:logWarning( "^1 stored in temp location: ^2", call.fieldId, prevField )
self.photos = photos -- this line added 24/Sep/2013 14:57 to help solve the catch-22 problem (can't start and can't finish...).
app:error( "File rename op still pending, shan't overwrite - you must run 'Rename Files - Finish' to clear this condition, before you will be able to rename files again." )
-- the error assures the transaction is unraveled en-total by Lightroom.
else
if str:is( field ) then
if field == oldBase or field == newBase then
--app:error( "File rename op unfinished (^1 matches filename: ^2), shan't overwrite - you must run 'Rename Files - Finish' to clear this condition, before you will be able to rename files again.", call.fieldId, field )
-- the error assures the transaction is unraveled en-total by Lightroom.
app:logWarn( "File rename op probably unfinished (^1 matches filename: ^2). You may want to undo this operation (^3), then run 'Rename Files - Finish' to clear this condition.", call.fieldId, field, call.name )
-- while probably an error, it's not illegal, and could even be likely if user had previously used JB's s&r/transfer plugin before coming over...
else
app:logVerbose( "^1 looks original.", call.fieldId )
end
if not call.testMode then
photo:setPropertyForPlugin( _PLUGIN, "temp_", field )
else
app:log( "*** TEST MODE ONLY - NO CHANGE MADE TO CATALOG OR PHOTO FILES (EXCEPT RENAME COLLECTION)" )
end
nFields = nFields + 1
else
app:log( "No ^1 to move.", call.fieldId )
end
end
end
if not call.testMode then
-- Note: there is no "update raw metadata" method of LrMetadata object for reading first before writing, like there is for photo-(plugin)properties via CustomMetadata class.
-- ###3 perhaps there should be, although I think I considered this once and rejected the idea (maybe Lr has change detection built in and if no change no resources expense?) - or was I dreaming...
photo:setRawMetadata( call.fieldId, newBase ) -- make sure there is no extension.
else
app:log( "*** TEST MODE ONLY - NO CHANGE MADE TO CATALOG OR PHOTO FILES (EXCEPT RENAME COLLECTION)" )
end
until true
-- Note: is-quit is checked in loop body above, and results in error thrown: the idea being to let Lightroom undo rather than depending on user to undo.
-- It's all or nothing. To do partial, one would have to restore headline fields if probs, and deselect photo, so user did not inadvertently screw up a filename.
call:setPortionComplete( i, #call.photos )
end
if not call:isQuit() then
return false
end
elseif phase == 2 then
if #changes > 0 then
if not call.testMode then
call.renameColl:addPhotos( changes )
else
local s, m = cat:update( 30, "Populate rename collection", function( context, phase )
call.renameColl:addPhotos( changes )
end )
if s then
app:log( "Rename collection populated with ^1", str:nItems( #changes, "photos" ) )
else
app:error( "Unable to populate rename collection." )
end
end
else
-- dont
end
return true -- done.
else
app:error( "Catalog update phase is out of range: ^1", phase )
end
end
self.photos = nil -- this line added 24/Sep/2013 14:57 to help solve the catch-22 problem (can't start and can't finish...).
local s, m
if call.testMode then
s, m = LrTasks.pcall( renameStart, nil, 1 ) -- phase 1
if s then
s, m = LrTasks.pcall( renameStart, nil, 2 ) -- phase 2
end
else
s, m = cat:update( 15, call.name, renameStart )
end
if s then
self.photos = photos -- saved for rename, finishing phase.
if call.specialFlag then
app:log( "It seems file renamer is being used for auxiliary purposes..." )
app:show{ info="It seems the FileRenamer/Start function has been invoked for some sorta \"field loading\" purposes, as opposed to file renaming. If that's not true, then please correct or report problem, if it is true, then the job is (presumably) done (e.g. fields loaded)." }
else
app:log()
if #changes > 0 then
app:log( "^1 moved to temp storage as necessary, and ^3 have been placed in ^2 field (corresponding photos were added to rename collection).", str:nItems( nFields, str:fmtx( "^1 fields", call.fieldId ) ), call.fieldId, str:nItems( #changes, "new filename bases", true ) )
app:show{ info="So far, so good (^1 will change), but after clicking 'OK' you must do some things:\n \n1. Rename all selected photos using the '^2' preset.\n2. Invoke: 'Rename Files - Finish' from the 'Library Menu -> Plugin Extras'.\n \nOr, if you don't want to finish the renaming, use Lightroom's 'Undo' in the 'Edit Menu', and things will be as they were...",
subs = { str:nItems( #changes, "filenames", true ), app:getPluginName() },
}
else
if nFields == 0 then
app:log( "No changes - commencing cleanup." )
else
app:log( "^1 fields moved - but shall be moved back - no filenames to change...", nFields )
end
local s, m = self:_renameFinish( call ) -- this is required, since even unchanged files are moved to field, so batch rename works for all.
if s then
app:show{ info="No filenames changed - nothing need be done." }
else
app:logErr( "There has been an error: ^1 - consider using Lightroom's undo to get back to where you were.", m )
end
end
end
else
-- self.photos = nil - this line commented out 24/Sep/2013 14:56 - creates catch-22 situation (can't start & can't finish).
app:logErr( "Unable to complete 'Rename Files - Start' due to error: ^1\n \nNo changes have been made to your catalog.", m )
app:show{ error="Unable to complete 'Rename Files - Start' due to error: ^1\n \nNo changes have been made to your catalog.", m }
end
end, finale=function( call )
self:_endRun( call )
self:_wrapOp( call )
end } )
end
-- menu handler
function Renamer:renameFinish()
--app:show( self:toString() .. " rename" )
app:call( Service:new{ name="Rename Files - Finish", async=true, progress={ caption="Dialog box needs attention..." }, main=function( call )
self:_initOp( call )
if not self.filenamePreset then
app:show{ warning="Requisite filenameing preset not found - try restarting Lightroom." }
call:cancel()
return
end
local photos = catalog:getTargetPhotos()
if #photos == 0 then
app:show{ warning="No photos in filmstrip - the same photos must be selected as were selected when you invoked 'Rename Files - Start'." }
call:cancel()
return
end
if self.photos == nil then
app:show{ warning="You must invoke 'Rename Files - Start' before invoking 'Rename Files - Finish'" }
call:cancel()
return
end
if #self.photos ~= #photos then
app:show{ warning="Uh-oh - the same photos must be selected as were selected when you invoked 'Rename Files - Start'." }
call:cancel()
return
end
local presetName = app.prefMgr:getPresetName() -- current preset name.
--local props = LrBinding.makePropertyTable( call.context )
local vi = {}
local ttl
if call.testMode then
ttl = "*** TEST MODE ONLY: NO CHANGES WILL BE MADE TO YOUR CATALOG OR PHOTO FILES (EXCEPT RENAME COLLECTION)."
else
ttl = "*** REAL MODE: CHANGES MAY BE MADE TO YOUR CATALOG, AS INDICATED IN LOG FILE UPON COMPLETION."
end
vi[#vi + 1] =
vf:static_text {
title = ttl,
fill_horizontal = 1,
}
local answer = app:show{ confirm="Finish rename ^1 according to ^2?",
subs = { str:nItems( #photos, "photos" ), presetName },
viewItems = vi,
}
if answer ~= 'ok' then
call:cancel()
return
end
local s, m = self:_initRun( call, photos ) -- no props
if s then
-- ok - details already logged.
else
app:logErr( m )
return
end
local s, m = self:_renameFinish( call )
if s then
-- enough logged already.
else
app:logErr( "There has been an error: ^1 - your catalog was not altered.", m )
app:show{ error="There has been an error: ^1 - your catalog was not altered.", m }
end
end, finale=function( call )
self:_wrapOp( call )
end } )
end
return Renamer |
package("clhep")
set_homepage("https://proj-clhep.web.cern.ch/proj-clhep/")
set_description("CLHEP - A Class Library for High Energy Physics")
set_license("LGPL-3.0")
add_urls("https://proj-clhep.web.cern.ch/proj-clhep/dist1/clhep-$(version).tgz", {version = function (version) return version:gsub("%+", ".") end})
add_versions("2.4.5+1", "2517c9b344ad9f55974786ae6e7a0ef8b22f4abcbf506df91194ea2299ce3813")
add_patches("2.4.5+1", path.join(os.scriptdir(), "patches", "2.4.5.1", "kind.patch"), "60a65bbe05380f6cd89752bdd662bd1685a8944081c97746f7a0bd2d046edf9d")
if is_plat("windows") then
add_configs("shared", {description = "Build shared library.", default = false, type = "boolean", readonly = true})
end
add_deps("cmake")
on_install("windows", "macosx", "linux", function (package)
os.cd("CLHEP")
if package:is_plat("windows") then
io.replace("cmake/Modules/ClhepVariables.cmake", "/MD", "/" .. package:config("vs_runtime"), {plain = true})
end
local configs = {"-DCLHEP_BUILD_DOCS=OFF", "-DLIB_SUFFIX="}
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release"))
table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF"))
import("package.tools.cmake").install(package, configs)
end)
on_test(function (package)
assert(package:check_cxxsnippets({test = [[
void test() {
HepGeom::Point3D<float> point(1, 2, 3);
point.set(4, 5, 6);
}
]]}, {configs = {languages = "c++11"}, includes = "CLHEP/Geometry/Point3D.h"}))
end)
|
data:extend({
{
type = "item",
name = "biotech-big-wooden-pole",
icon = "__BioTech__/graphics/icons/big-wooden-pole.png",
flags = {"goes-to-quickbar"},
subgroup = "energy-pipe-distribution",
order = "a[energy]-b[small-electric-pole]",
place_result = "biotech-big-wooden-pole",
stack_size = 50,
fuel_value = "20MJ",
fuel_category = "chemical",
},
{
type = "item",
name = "biotech-wooden-fence",
icon = "__BioTech__/graphics/icons/wooden-fence.png",
flags = {"goes-to-quickbar"},
subgroup = "defensive-structure",
order = "a-a[stone-wall]-a[wooden-fence]",
place_result = "biotech-wooden-fence",
fuel_value = "8MJ",
fuel_category = "chemical",
stack_size = 50,
},
{
type = "item",
name = "biotech-seedling",
icon = "__BioTech__/graphics/icons/Seedling.png",
flags = {"goes-to-main-inventory"},
subgroup = "biotech-products",
order = "b[plant]-1",
place_result="biotech-seedling",
fuel_value = "1MJ",
fuel_category = "chemical",
stack_size= 50
},
})
|
local trigger_pickups = {}
function CreatePickupTrigger(modelid, x, y, z, will_be_destroyed, overwrite_event)
local pickup = CreatePickup(modelid, x, y, z)
local tbl = {}
tbl.id = pickup
tbl.model = modelid
tbl.destroy_next = will_be_destroyed
tbl.overwrite_event = overwrite_event
table.insert(trigger_pickups, tbl)
return pickup
end
function DestroyPickupTrigger(pickup)
for i, v in ipairs(trigger_pickups) do
if v.id == pickup then
DestroyPickup(pickup)
table.remove(trigger_pickups, i)
end
end
end
AddEvent("OnPlayerPickupHit", function(ply, pickup)
if GetPlayerVehicle(ply) == 0 then
for i, v in ipairs(trigger_pickups) do
if v.id == pickup then
if v.overwrite_event then
CallEvent(v.overwrite_event, ply, pickup)
else
for i2, v2 in ipairs(pickups_triggers) do
if v2[1] == v.model then
CallEvent(v2[2], ply, pickup)
end
end
end
if v.destroy_next then
table.remove(trigger_pickups, i)
DestroyPickup(pickup)
end
break
end
end
end
end)
AddEvent("OnDimensionDestroyed", function(id, name)
for i,v in ipairs(GetDimensionPickups(id)) do
for i2, v2 in ipairs(trigger_pickups) do
if v2.id == v then
table.remove(trigger_pickups, i2)
end
end
end
end)
|
PLUGIN.name = "Door Bust Charges"
PLUGIN.author = "Black Tea"
PLUGIN.desc = "A Charge that can blow up the door."
if (CLIENT) then
local muzzleMaterials = {}
for i = 1, 8 do
muzzleMaterials[i] = Material("effects/fas_muzzle" .. i .. ".png", "SpriteCard")
muzzleMaterials[i]:SetInt("$additive", 1)
muzzleMaterials[i]:SetInt("$translucent", 1)
muzzleMaterials[i]:SetInt("$vertexcolor", 1)
muzzleMaterials[i]:SetInt("$vertexalpha", 1)
end
local EFFECT = {}
function EFFECT:Init( data )
self:SetNoDraw(true)
local pos = data:GetStart()
local scale = 3
self.emitter = WORLDEMITTER or ParticleEmitter(Vector(0, 0, 0))
for i = 0, 1 do
local smoke = self.emitter:Add( "particle/smokesprites_000"..math.random(1,9), pos + VectorRand()*10)
smoke:SetVelocity(VectorRand()*20*scale)
smoke:SetDieTime(math.Rand(.5,.3))
smoke:SetStartAlpha(math.Rand(244,144))
smoke:SetEndAlpha(0)
smoke:SetStartSize(math.random(0,5)*scale)
smoke:SetEndSize(math.random(55,44)*scale)
smoke:SetRoll(math.Rand(180,480))
smoke:SetRollDelta(math.Rand(-3,3))
smoke:SetColor(33, 33, 33)
smoke:SetGravity( Vector( 0, 0, 20 ) )
smoke:SetAirResistance(250)
end
for i = 0, 4 do
local smoke = self.emitter:Add( "particle/smokesprites_000"..math.random(1,9), pos + VectorRand()*10)
smoke:SetVelocity(VectorRand()*150*scale)
smoke:SetDieTime(math.Rand(.5,1))
smoke:SetStartAlpha(math.Rand(222,122))
smoke:SetEndAlpha(0)
smoke:SetStartSize(math.random(11,22)*scale)
smoke:SetEndSize(math.random(55,77)*scale)
smoke:SetRoll(math.Rand(180,480))
smoke:SetRollDelta(math.Rand(-3,3))
smoke:SetColor(33, 33, 33)
smoke:SetGravity( Vector( 0, 0, 20 ) )
smoke:SetAirResistance(500)
end
local smoke = self.emitter:Add(nut.util.getMaterial("particle/Particle_Glow_04_Additive"), pos + VectorRand()*10)
smoke:SetVelocity(VectorRand()*20*scale)
smoke:SetDieTime(math.Rand(.1,.1))
smoke:SetStartAlpha(math.Rand(33,66))
smoke:SetEndAlpha(0)
smoke:SetStartSize(math.random(33,25)*scale)
smoke:SetEndSize(math.random(100,88)*scale)
smoke:SetRoll(math.Rand(180,480))
smoke:SetRollDelta(math.Rand(-3,3))
smoke:SetColor(255, 66, 111)
smoke:SetGravity( Vector( 0, 0, 20 ) )
smoke:SetAirResistance(250)
for i = 0, 1 do
local smoke = self.emitter:Add( muzzleMaterials[math.random(1, 8)], pos + VectorRand()*10)
smoke:SetVelocity(VectorRand()*20*scale)
smoke:SetDieTime(math.Rand(.1,.1))
smoke:SetStartAlpha(math.Rand(255,200))
smoke:SetEndAlpha(0)
smoke:SetStartSize(math.random(33,25)*scale)
smoke:SetEndSize(math.random(44,66)*scale)
smoke:SetRoll(math.Rand(180,480))
smoke:SetRollDelta(math.Rand(-3,3))
smoke:SetColor(255, 200, 200)
smoke:SetGravity( Vector( 0, 0, 20 ) )
smoke:SetAirResistance(250)
end
self.nig = {}
for i = 0, 15 do
local smoke = self.emitter:Add(nut.util.getMaterial("effects/yellowflare"), pos + VectorRand()*20)
smoke:SetVelocity(VectorRand()*100*scale)
smoke:SetDieTime(math.Rand(.05,.09))
smoke:SetStartAlpha(math.Rand(111,155))
smoke:SetEndAlpha(0)
smoke:SetStartSize(math.random(1,3)*scale)
smoke:SetEndSize(0)
smoke:SetRoll(math.Rand(180,480))
smoke:SetRollDelta(math.Rand(-3,3))
smoke:SetColor(255, 200, 200)
smoke:SetAirResistance(250)
table.insert(self.nig, smoke)
end
end
function EFFECT:Think()
for k, v in ipairs(self.nig) do
v:SetVelocity(VectorRand()*1900)
end
end
effects.Register( EFFECT, "doorCharge" )
end |
-- See LICENSE for terms
return {
PlaceObj("ModItemOptionToggle", {
"name", "EnableMod",
"DisplayName", T(302535920011303, "Enable Mod"),
"Help", T(302535920011793, "Disable mod without having to see missing mod msg."),
"DefaultValue", true,
}),
PlaceObj("ModItemOptionNumber", {
"name", "PercentDrop",
"DisplayName", T(302535920011893, "Percent Drop"),
"Help", T(302535920011894, "How much of full amount to drop."),
"DefaultValue", 100,
"MinValue", 0,
"MaxValue", 100,
}),
}
|
-- Author Pasky13
local pbase = 0xC00
local ppbase = 0xCC0
local ebase = 0x19C0
local epbase = 0xEC0
local xm
local ym
memory.usememorydomain("CARTROM")
function findbit(p)
return 2 ^ (p - 1)
end
function hasbit(x, p)
return x % (p + p) >= p
end
local function hex(val)
val = string.format("%X",val)
return val
end
local function camera()
cx = mainmemory.read_u16_le(0xD9)
cy = mainmemory.read_u16_le(0xDB)
end
local function drawbox(p,x,y,base,player,fill,outl)
local box = {0,0,0,0} --xoff/yoff/xrad/yrad
box[1] = memory.read_s8(p)
box[2] = memory.read_s8(p + 1)
box[3] = memory.read_u8(p + 2)
box[4] = memory.read_u8(p + 3)
if player == false then
if hasbit(mainmemory.read_u8(base+0x14),findbit(7)) then -- megaman facing right
box[1] = box[1] * - 1
end
else
if hasbit(mainmemory.read_u8(base+0x4A),findbit(3)) then -- enemy facing left
box[1] = box[1] * - 1
end
end
gui.drawBox(x+box[1]+box[3],y+box[2]+box[4],x+box[1]-box[3],y+box[2]-box[4],outl, fill)
return box
end
local function proj_vuln(base,x,y,xoff,yoff,xrad,yrad)
local offset = memory.read_u8(0x87D0 +(mainmemory.read_u8(base + 0x31) * 2))
local property = memory.read_s8(0x87D0 + offset)
if property <= 0 then
gui.drawLine(x + xoff + xrad,y + yoff,x + xoff - xrad, y + yoff,0xFFFFFFFF)
gui.drawLine(x + xoff,y + yoff + yrad, x + xoff,y + yoff - yrad,0xFFFFFFFF)
end
--gui.text(x-40,y-20,hex(offset) .. " " .. hex(base))
end
local function player()
local x = mainmemory.read_u16_le(pbase + 5) - cx
local y = mainmemory.read_u16_le(pbase + 8) - cy
local pointer = mainmemory.read_u16_le(pbase + 0x24)
local hp = mainmemory.read_s8(pbase + 0x2F)
drawbox(pointer,x,y,pbase,true,0x400000FF,0xFF0000FF)
gui.text((x-4) * xm,y * ym,"HP:" .. hp)
end
local function player_projectiles()
local x
local y
local base
local pointer
local active
local anim
for i = 0,7,1 do
base = ppbase + (i * 0x40)
active = mainmemory.read_u8(base)
anim = mainmemory.read_u8(base + 1)
if active ~= 0 and anim > 1 then
x = mainmemory.read_u16_le(base + 5) - cx
y = mainmemory.read_u16_le(base + 8) - cy
pointer = mainmemory.read_u16_le(base + 0x24)
drawbox(pointer,x,y,base,false,0x40FFFFFF,0xFFFFFFFF)
end
end
end
local function enemy_projectiles()
local x
local y
local base
local pointer
local active
local anim
for i = 0,7,1 do
base = epbase + (i * 0x40)
active = mainmemory.read_u8(base)
anim = mainmemory.read_u8(base + 1)
if active ~= 0 and anim > 1 then
x = mainmemory.read_u16_le(base + 5) - cx
y = mainmemory.read_u16_le(base + 8) - cy
pointer = mainmemory.read_u16_le(base + 0x24)
drawbox(pointer,x,y,base,false,0x4000FF00,0xFF00FF00)
end
end
end
local function objects()
local x
local y
local hp
local base
local pointer
local active
local anim
local box
for i = 0,15,1 do
base = ebase + (i * 0x40)
active = mainmemory.read_u8(base)
anim = mainmemory.read_u8(base + 1)
if active ~= 0 and anim > 1 then
x = mainmemory.read_u16_le(base + 5) - cx
y = mainmemory.read_u16_le(base + 8) - cy
pointer = mainmemory.read_u16_le(base + 0x24)
hp = mainmemory.read_s8(base + 0x2F)
if hp > 0 then
gui.text((x-8) * xm,(y-8) * ym,"HP: " .. hp)
end
box = drawbox(pointer,x,y,base,false,0x40FF0000,0xFFFF0000)
proj_vuln(base,x,y,box[1],box[2],box[3],box[4])
end
end
end
-- local function unknown() -- Hitstun animations?
-- local x
-- local y
-- local base = 0x15C0
-- for i = 0,8,1 do
-- base = 0x15C0 + (i * 0x20)
-- if mainmemory.read_u16_le(base) ~= 0 then
-- x = mainmemory.read_u16_le(base + 5) - cx
-- y = mainmemory.read_u16_le(base + 8) - cy
-- gui.text(x,y,"UK:" .. i)
-- end
-- end
-- for i = 0,15,1 do
-- base = 0x16C0 + (i * 0x30)
-- if mainmemory.read_u16_le(base) ~= 0 then
-- x = mainmemory.read_u16_le(base + 5) - cx
-- y = mainmemory.read_u16_le(base + 8) - cy
-- gui.text(x,y,"UK2:" .. i)
-- end
-- end
-- end
local function scaler()
xm = client.screenwidth() / 256
ym = client.screenheight() / 224
end
while true do
scaler()
camera()
enemy_projectiles()
player_projectiles()
objects()
player()
emu.frameadvance()
end |
return {
lang = { "multiply" , "number" },
data = {
{"7x7","49",},
{"8x7","56",},
{"9x7","63",},
},
}
|
local playsession = {
{"mewmew", {823670}},
{"flooxy", {1016935}},
{"brfbrf", {60574}},
{"pickles28", {3710}},
{"matjojo", {239492}},
{"snoetje", {798732}},
{"epicmonkey159", {1426}},
{"PuttPutt98", {928965}},
{"Piewdennis", {464597}},
{"adam1285", {701226}},
{"14nickel", {6105}},
{"Connor15_", {81892}},
{"formenis", {4325}},
{"Kyte", {20433}},
{"nagykeccs", {10614}},
{"Hurrock", {1828405}},
{"ghastly_figure", {522372}},
{"ratboyboxshall", {2690}},
{"Shinhan", {583531}},
{"FluffySan", {6086}},
{"Dinnopum", {1006700}},
{"Zorzzz", {4146816}},
{"jer93", {555980}},
{"Akhrem", {49431}},
{"YagaoDirac", {45237}},
{"everLord", {125943}},
{"KeyJoo", {1649706}},
{"tbell91", {1192531}},
{"hasannuh", {2515}},
{"Nikkichu", {263354}},
{"TheNetworkDoctor", {355684}},
{"Taulas", {324795}},
{"larshp", {2333}},
{"Biker", {628063}},
{"VanHate", {451052}},
{"MaxMM", {102028}},
{"FartunaSir", {1670}},
{"php_piranha", {977868}},
{"Kwang2846", {3991127}},
{"DSCD", {531663}},
{"Corlin", {195561}},
{"5b927177f7", {179876}},
{"cpenguinred", {10279}},
{"ralphmace", {1340677}},
{"Baldy34343", {90007}},
{"Kno", {2073524}},
{"raskl", {86937}},
{"Hazzari", {14834}},
{"marokotov", {20680}},
{"vedolv", {76227}},
{"snowbranch", {10686}},
{"joe32", {1574887}},
{"Leon55", {20633}},
{"Unahzaal", {1809628}},
{"paulobr02", {1632}},
{"Podonkov", {5172}},
{"Daveyboy80", {11024}},
{"ksb4145", {7133}},
{"gryph", {3623}},
{"HardcoreRocco", {77727}},
{"Purgen", {10540}},
{"TheHomieDomie", {117324}},
{"ro88ie", {461268}},
{"MooLer", {1121937}},
{"AmoraleS", {52659}},
{"ailishi19", {381707}},
{"Electrosys", {8750}},
{"Kjartan91", {49379}},
{"thislsamerica", {383467}},
{"Xolas", {485631}},
{"therv", {6854}},
{"Olekplane1", {58650}},
{"MegaNoob", {72080}},
{"MachineEmpathist", {9881}},
{"Cubicgraphics", {8629}},
{"darklich14", {24191}},
{"macionek", {564911}},
{"my_saw", {1505400}},
{"xRedHunterx", {24687}},
{"ibadaboom", {291360}},
{"Khlept0", {72337}},
{"Vrron", {84226}},
{"TheLuckyLuke", {13563}},
{"Hugoo", {11411}},
{"S.L", {744260}},
{"Kalkune", {9865}},
{"StarP0wer", {53950}},
{"FAChyba", {272137}},
{"mimosa123", {26753}},
{"Langmans", {275718}},
{"JirkaJaneba", {9033}},
{"Cache", {4078}},
{"Farendur", {38115}},
{"Kondzio8", {29016}},
{"askyyer", {39772}},
{"maggens", {304376}},
{"Nivek3k", {428100}},
{"undefinable", {147208}},
{"realDonaldTrump", {11974}},
{"hunter117x", {57799}},
{"Vladis_Generator", {74578}},
{"dorpdorp", {4947}},
{"lynxlives", {19979}},
{"Allofou", {12370}},
{"Landooney", {3547}},
{"Martox111", {9032}},
{"Player_one_1", {4366}},
{"Edeholland", {4989}},
{"grahamm", {60740}},
{"FireLeaf", {18130}},
{"MdRuz", {70600}},
{"Moistlos", {180296}},
{"Ubilaz", {24659}},
{"Mlmute", {68794}},
{"rocket1560090", {16542}},
{"Pumba81", {237614}},
{"Furancebob", {145371}},
{"Cehe4ka", {7040}},
{"MrCrazy", {971903}},
{"lintaba", {72185}},
{"StandaardStefan", {17091}},
{"TrpaslikLP", {33031}},
{"2716057", {26036}},
{"sobitome", {143942}},
{"Xactdose", {64676}},
{"jagger23", {164055}},
{"SuddenDeathMP", {8585}},
{"_mindframe_", {12582}},
{"samq9", {387997}},
{"Delqvs", {18559}},
{"maxxcz", {14089}},
{"sixtothegrave", {29226}},
{"jimmyhunter", {8403}},
{"CheeseLord", {50860}},
{"Malorie_sXy", {965743}},
{"Nitrobacter", {868}},
{"Factorian12321", {9527}},
{"Merc_Plays", {13131}},
{"doenerlover", {20229}},
{"jrz126", {3673}},
{"vipto", {7209}},
{"umtallguy", {28433}},
{"aTHUGnamedWAFFLE", {123605}},
{"brandon1311", {9367}},
{"bonesoul", {25383}},
{"helmetti", {3990}},
{"Serennie", {3612647}},
{"Animade", {34762}},
{"Thuro", {132261}},
{"mastocker", {1445}},
{"misaelfer", {12387}},
{"thederpyloco", {459558}},
{"Maloy12", {85899}},
{"atlas_242", {7681}},
{"TobiasRocks2004", {5416}},
{"-Nightmare-", {8986}},
{"chris123", {5590}},
{"Multifunktionsmixer", {868475}},
{"RasmusNord", {22151}},
{"Idefix88", {41429}},
{"Grabi", {2661}},
{"Gerkiz", {1055}},
{"Vodk", {190290}},
{"edensg", {1428157}},
{"Churchoo", {1887354}},
{"jaxjace", {361860}},
{"Zippy", {84703}},
{"zbirka", {57919}},
{"Bunchofrocks", {5278}}
}
return playsession |
local ObjectManager = require("managers.object.object_manager")
PadawanTrials = ScreenPlay:new {}
function PadawanTrials:doPadawanTrialsSetup(pPlayer)
local sui = SuiMessageBox.new("JediTrials", "emptyCallback")
if (not JediTrials:isEligibleForPadawanTrials(pPlayer)) then
sui.setTitle("@jedi_trials:padawan_trials_title")
sui.setPrompt("@jedi_trials:padawan_trials_started_not_eligible")
else
JediTrials:createClosestShrineWaypoint(pPlayer)
sui.setTitle("@jedi_trials:force_shrine_title")
sui.setPrompt("@jedi_trials:padawan_trials_intro_msg")
end
sui.sendTo(pPlayer)
end
function PadawanTrials:startPadawanTrials(pObject, pPlayer)
if (not JediTrials:isEligibleForPadawanTrials(pPlayer)) then
local sui = SuiMessageBox.new("JediTrials", "emptyCallback")
sui.setTitle("@jedi_trials:padawan_trials_title")
sui.setPrompt("@jedi_trials:padawan_trials_started_not_eligible")
sui.sendTo(pPlayer)
return
end
local sui = SuiMessageBox.new("PadawanTrials", "jediPadawanTrialsStartCallback")
sui.setTargetNetworkId(SceneObject(pObject):getObjectID())
sui.setTitle("@jedi_trials:force_shrine_title")
sui.setPrompt("@jedi_trials:padawan_trials_start_query")
sui.setOkButtonText("@jedi_trials:button_yes") -- Yes
sui.setCancelButtonText("@jedi_trials:button_no") -- No
sui.sendTo(pPlayer)
end
function PadawanTrials:jediPadawanTrialsStartCallback(pPlayer, pSui, eventIndex, args)
if (pPlayer == nil) then
return
end
local cancelPressed = (eventIndex == 1)
if (cancelPressed) then
return
end
if (not JediTrials:isEligibleForPadawanTrials(pPlayer)) then
local sui = SuiMessageBox.new("JediTrials", "emptyCallback")
sui.setTitle("@jedi_trials:padawan_trials_title")
sui.setPrompt("@jedi_trials:padawan_trials_started_not_eligible")
sui.sendTo(pPlayer)
return
end
local rand = getRandomNumber(1, #padawanTrialQuests) -- 16 Jedi Padawan Trials
while padawanTrialQuests[rand].trialType == TRIAL_LIGHTSABER do
rand = getRandomNumber(1, #padawanTrialQuests)
end
JediTrials:setStartedTrials(pPlayer)
JediTrials:setTrialsCompleted(pPlayer, 0)
self:startTrial(pPlayer, rand)
end
function PadawanTrials:restartCurrentPadawanTrial(pPlayer)
local sui = SuiMessageBox.new("PadawanTrials", "jediPadawanTrialsRestartCallback")
sui.setTitle("@jedi_trials:force_shrine_title")
sui.setPrompt("@jedi_trials:padawan_trials_restart_confirmation")
sui.sendTo(pPlayer)
end
function PadawanTrials:jediPadawanTrialsRestartCallback(pPlayer, pSui, eventIndex, args)
if (pPlayer == nil) then
return
end
local cancelPressed = (eventIndex == 1)
if (cancelPressed) then
return
end
CreatureObject(pPlayer):sendSystemMessage("@jedi_trials:padawan_trials_trial_restarted")
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
local trialName = JediTrials:getTrialStateName(pPlayer, trialNumber)
self:startTrial(pPlayer, trialNumber)
end
function PadawanTrials:quitPadawanTrials(pPlayer)
local sui = SuiMessageBox.new("PadawanTrials", "jediPadawanTrialsAbortCallback")
sui.setTitle("@jedi_trials:force_shrine_title")
sui.setPrompt("@jedi_trials:padawan_trials_abort_confirmation")
sui.sendTo(pPlayer)
end
function PadawanTrials:jediPadawanTrialsAbortCallback(pPlayer, pSui, eventIndex, args)
if (pPlayer == nil) then
return
end
local cancelPressed = (eventIndex == 1)
if (cancelPressed) then
return
end
CreatureObject(pPlayer):sendSystemMessage("@jedi_trials:padawan_trials_aborted")
self:resetAllPadawanTrials(pPlayer)
end
function PadawanTrials:startNextPadawanTrial(pObject, pPlayer)
if (pPlayer == nil) then
return
end
local trialsCompleted = JediTrials:getTrialsCompleted(pPlayer)
if (trialsCompleted == #padawanTrialQuests) then
JediTrials:unlockJediPadawan(pPlayer)
return
elseif (trialsCompleted == 7) then
local trialNum = self:getSaberCraftingTrialNumber()
self:startTrial(pPlayer, trialNum)
else
local incompleteTrials = {}
for i = 1, #padawanTrialQuests, 1 do
local trialState = JediTrials:getTrialStateName(pPlayer, i)
if not CreatureObject(pPlayer):hasScreenPlayState(1, trialState) and padawanTrialQuests[i].trialType ~= TRIAL_LIGHTSABER then
table.insert(incompleteTrials, i)
end
end
local rand = getRandomNumber(1, #incompleteTrials)
local randTrial = incompleteTrials[rand]
self:startTrial(pPlayer, randTrial)
end
end
function PadawanTrials:getSaberCraftingTrialNumber()
for i = 1, #padawanTrialQuests, 1 do
if padawanTrialQuests[i].trialType == TRIAL_LIGHTSABER then
return i
end
end
return -1
end
function PadawanTrials:resetAllPadawanTrials(pPlayer)
--Remove All States.
for i = 1, #padawanTrialQuests, 1 do
local trialState = JediTrials:getTrialStateName(pPlayer, i)
CreatureObject(pPlayer):removeScreenPlayState(1, trialState)
if padawanTrialQuests[i].trialType == TRIAL_LIGHTSABER then
CreatureObject(pPlayer):removeScreenPlayState(1, trialState .. "_saber")
CreatureObject(pPlayer):removeScreenPlayState(1, trialState .. "_crystal")
end
end
self:removeAllAreas(pPlayer)
local pGhost = CreatureObject(pPlayer):getPlayerObject()
if (pGhost == nil) then
return
end
if (CreatureObject(pPlayer):hasSkill("force_title_jedi_rank_01")) then
CreatureObject(pPlayer):surrenderSkill("force_title_jedi_rank_01")
end
JediTrials:resetTrialData(pPlayer, "padawan")
PlayerObject(pGhost):removeWaypointBySpecialType(WAYPOINTQUESTTASK)
end
function PadawanTrials:startTrial(pPlayer, trialNum, skipNotification)
if (skipNotification == nil) then
skipNotification = false
end
dropObserver(KILLEDCREATURE, "PadawanTrials", "notifyKilledHuntTarget", pPlayer)
dropObserver(PROTOTYPECREATED, "PadawanTrials", "notifyCraftedTrainingSaber", pPlayer)
dropObserver(TUNEDCRYSTAL, "PadawanTrials", "notifyTunedLightsaberCrystal", pPlayer)
self:removeAllAreas(pPlayer)
JediTrials:setCurrentTrial(pPlayer, trialNum)
local trialData = padawanTrialQuests[trialNum]
if (trialData == nil) then
printLuaError("PadawanTrials:startTrial, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNum)
return
end
if (trialData.trialType == TRIAL_LIGHTSABER) then
if (not CreatureObject(pPlayer):hasSkill("force_title_jedi_rank_01")) then
awardSkill(pPlayer, "force_title_jedi_rank_01")
end
local trialState = JediTrials:getTrialStateName(pPlayer, trialNum)
CreatureObject(pPlayer):removeScreenPlayState(1, trialState .. "_saber")
CreatureObject(pPlayer):removeScreenPlayState(1, trialState .. "_crystal")
createObserver(PROTOTYPECREATED, "PadawanTrials", "notifyCraftedTrainingSaber", pPlayer)
self:sendSuiNotification(pPlayer)
return
end
local playerID = SceneObject(pPlayer):getObjectID()
deleteData(playerID .. ":JediTrials:acceptedTask")
deleteData(playerID .. ":JediTrials:killedTarget")
deleteData(playerID .. ":JediTrials:spokeToTarget01")
deleteData(playerID .. ":JediTrials:spokeToTarget02")
deleteScreenPlayData(pPlayer, "JediTrials", "huntTarget")
deleteScreenPlayData(pPlayer, "JediTrials", "huntTargetCount")
deleteScreenPlayData(pPlayer, "JediTrials", "huntTargetGoal")
local planetName = trialsCivilizedPlanets[getRandomNumber(1, #trialsCivilizedPlanets)]
local playerPlanet = SceneObject(pPlayer):getZoneName()
local retries = 0
while ((not isZoneEnabled(planetName) or playerPlanet == planetName) and retries < 20) do
planetName = trialsCivilizedPlanets[getRandomNumber(1, #trialsCivilizedPlanets)]
retries = retries + 1
end
if (trialData.trialName == "artist") then
planetName = "naboo"
end
local randomCityTable = trialsCivilizedPlanetCities[planetName]
local randomCity = randomCityTable[getRandomNumber(1, #randomCityTable)]
if (trialData.trialLoc ~= nil) then
local locData = trialData.trialLoc
if locData[4] ~= nil then
planetName = locData[4]
end
if locData[5] ~= nil then
randomCity = locData[5]
else
randomCityTable = trialsCivilizedPlanetCities[planetName]
randomCity = randomCityTable[getRandomNumber(1, #randomCityTable)]
end
end
if (randomCity == nil) then
printLuaError("PadawanTrials:startTrial, unable to get random city for planet " .. planetName .. ".")
return
end
JediTrials:setTrialPlanetAndCity(pPlayer, planetName, randomCity)
local spawnPoint
if (trialData.trialLoc == nil) then
local randomLocTable = trialsCivilizedNpcSpawnPoints[planetName][randomCity]
local randomLoc = randomLocTable[getRandomNumber(1, #randomLocTable)]
if (randomLoc == nil) then
printLuaError("PadawanTrials:startTrial, unable to get random location for " .. randomCity .. " on " .. planetName .. ".")
return
end
spawnPoint = getSpawnPointInArea(planetName, randomLoc[1], randomLoc[2], randomLoc[3])
-- Execute the function again to pick a new random location
if (spawnPoint == nil) then
local pointAttempts = readData(playerID .. ":JediTrials:spawnPointAttempts")
if (pointAttempts <= 5) then
self:startTrial(pPlayer, trialNum, skipNotification)
writeData(playerID .. ":JediTrials:spawnPointAttempts", pointAttempts + 1)
else
printLuaError("PadawanTrials:startTrial, unable to find start point for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial number " .. trialNum .. " after 5 attempts.")
deleteData(playerID .. ":JediTrials:spawnPointAttempts")
end
return
end
deleteData(playerID .. ":JediTrials:spawnPointAttempts")
else
spawnPoint = trialData.trialLoc
end
JediTrials:setTrialLocation(pPlayer, spawnPoint[1], spawnPoint[2], spawnPoint[3], planetName)
if (not skipNotification) then
self:sendSuiNotification(pPlayer)
end
self:createMainLocation(pPlayer)
end
function PadawanTrials:notifyCraftedTrainingSaber(pPlayer, pItem)
if (pPlayer == nil or pItem == nil) then
return 0
end
if (not JediTrials:isEligibleForPadawanTrials(pPlayer)) then
return 1
end
local trialNum = JediTrials:getCurrentTrial(pPlayer)
local trialData = padawanTrialQuests[trialNum]
if (trialData == nil) then
printLuaError("PadawanTrials:notifyCraftedTrainingSaber, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNum)
return 1
end
if (trialData.trialType ~= TRIAL_LIGHTSABER) then
return 1
end
local trialState = JediTrials:getTrialStateName(pPlayer, trialNum)
if (CreatureObject(pPlayer):hasScreenPlayState(1, trialState .. "_saber")) then -- Already crafted a saber
return 1
end
if (not string.find(SceneObject(pItem):getTemplateObjectPath(), "object/weapon/melee/sword/crafted_saber")) then
return 0
end
CreatureObject(pPlayer):setScreenPlayState(1, trialState .. "_saber")
dropObserver(TUNEDCRYSTAL, "PadawanTrials", "notifyTunedLightsaberCrystal", pPlayer)
createObserver(TUNEDCRYSTAL, "PadawanTrials", "notifyTunedLightsaberCrystal", pPlayer)
self:sendSuiNotification(pPlayer)
return 1
end
function PadawanTrials:notifyTunedLightsaberCrystal(pPlayer, pItem)
if (pPlayer == nil or pItem == nil) then
return 0
end
if (not JediTrials:isEligibleForPadawanTrials(pPlayer)) then
return 1
end
local trialNum = JediTrials:getCurrentTrial(pPlayer)
local trialData = padawanTrialQuests[trialNum]
if (trialData == nil) then
printLuaError("PadawanTrials:notifyTunedLightsaberCrystal, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNum)
return 1
end
if (trialData.trialType ~= TRIAL_LIGHTSABER) then
return 1
end
local trialState = JediTrials:getTrialStateName(pPlayer, trialNum)
if (CreatureObject(pPlayer):hasScreenPlayState(1, trialState .. "_crystal")) then -- Already tuned a crystal
return 1
end
CreatureObject(pPlayer):setScreenPlayState(1, trialState .. "_crystal")
self:passTrial(pPlayer)
return 1
end
function PadawanTrials:setupHuntTrial(pPlayer)
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
if (trialNumber <= 1) then
return
end
local trialData = padawanTrialQuests[trialNumber]
if (trialData == nil) then
printLuaError("PadawanTrials:setupHuntTrial, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNumber)
return
end
if (trialData.trialType ~= TRIAL_HUNT) then
return
end
writeScreenPlayData(pPlayer, "JediTrials", "huntTarget", trialData.huntTarget)
writeScreenPlayData(pPlayer, "JediTrials", "huntTargetCount", 0)
writeScreenPlayData(pPlayer, "JediTrials", "huntTargetGoal", trialData.huntGoal)
dropObserver(KILLEDCREATURE, "PadawanTrials", "notifyKilledHuntTarget", pPlayer)
createObserver(KILLEDCREATURE, "PadawanTrials", "notifyKilledHuntTarget", pPlayer)
end
function PadawanTrials:hasCompletedHunt(pPlayer)
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
if (trialNumber <= 1) then
return false
end
local trialData = padawanTrialQuests[trialNumber]
if (trialData == nil) then
printLuaError("PadawanTrials:hasCompletedHunt, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNumber)
return false
end
if (trialData.trialType ~= TRIAL_HUNT) then
return false
end
local targetCount = tonumber(readScreenPlayData(pPlayer, "JediTrials", "huntTargetCount"))
local targetGoal = tonumber(readScreenPlayData(pPlayer, "JediTrials", "huntTargetGoal"))
if (targetCount == nil or targetGoal == nil) then
return false
end
return targetCount >= targetGoal
end
function PadawanTrials:notifyKilledHuntTarget(pPlayer, pVictim)
if (pVictim == nil or pPlayer == nil) then
return 0
end
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
if (trialNumber <= 1) then
return 1
end
local trialData = padawanTrialQuests[trialNumber]
if (trialData == nil) then
printLuaError("PadawanTrials:notifyKilledHuntTarget, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNumber)
return 1
end
if (trialData.trialType ~= TRIAL_HUNT) then
return 1
end
local huntTarget = readScreenPlayData(pPlayer, "JediTrials", "huntTarget")
local targetCount = tonumber(readScreenPlayData(pPlayer, "JediTrials", "huntTargetCount"))
local targetGoal = tonumber(readScreenPlayData(pPlayer, "JediTrials", "huntTargetGoal"))
if (targetCount == nil) then
printLuaError("PadawanTrials:notifyKilledHuntTarget, nil targetCount for player: " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNumber .. " (player killed target: " .. SceneObject(pVictim):getObjectName() .. ").")
return 1
end
if (targetGoal == nil) then
printLuaError("PadawanTrials:notifyKilledHuntTarget, nil targetGoal for player: " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNumber .. " (player killed target: " .. SceneObject(pVictim):getObjectName() .. ").")
return 1
end
if (SceneObject(pVictim):getZoneName() ~= SceneObject(pPlayer):getZoneName() or not CreatureObject(pPlayer):isInRangeWithObject(pVictim, 80)) then
return 0
end
if (string.find(SceneObject(pVictim):getObjectName(), huntTarget)) then
CreatureObject(pPlayer):sendSystemMessage("@jedi_trials:padawan_trials_progress")
targetCount = targetCount + 1
writeScreenPlayData(pPlayer, "JediTrials", "huntTargetCount", targetCount)
if (targetCount >= targetGoal) then
CreatureObject(pPlayer):sendSystemMessage("@jedi_trials:padawan_trials_return_to_npc")
self:createMainLocation(pPlayer)
return 1
end
end
return 0
end
function PadawanTrials:createMainLocation(pPlayer)
local trialNum = JediTrials:getCurrentTrial(pPlayer)
local trialData = padawanTrialQuests[trialNum]
if (trialData == nil) then
printLuaError("PadawanTrials:createMainLocation, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNum)
return
end
local mainLocData = JediTrials:getTrialPlanetAndCity(pPlayer)
local planetName = mainLocData[1]
local spawnLoc = JediTrials:getTrialLocation(pPlayer)
if (trialData.trialLoc == nil) then
local pActiveArea = spawnActiveArea(planetName, "object/active_area.iff", spawnLoc[1], spawnLoc[2], spawnLoc[3], 64, 0)
local playerID = SceneObject(pPlayer):getObjectID()
if pActiveArea == nil then
printLuaError("PadawanTrials:createMainLocation, failed to create active area.")
return
end
local areaID = SceneObject(pActiveArea):getObjectID()
writeData(playerID .. ":mainLocSpawnAreaID", areaID)
writeData(areaID .. ":ownerID", playerID)
createObserver(ENTEREDAREA, "PadawanTrials", "notifyEnteredMainLocSpawnArea", pActiveArea)
end
local pGhost = CreatureObject(pPlayer):getPlayerObject()
if (pGhost ~= nil) then
PlayerObject(pGhost):addWaypoint(planetName, "Speak to this person", "", spawnLoc[1], spawnLoc[3], WAYPOINTBLUE, true, true, WAYPOINTQUESTTASK)
end
end
function PadawanTrials:sendSuiNotification(pPlayer)
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
local trialData = padawanTrialQuests[trialNumber]
if (trialData == nil) then
printLuaError("PadawanTrials:sendSuiNotification, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNumber)
return
end
local msgFinal
if (trialData.trialType == TRIAL_LIGHTSABER) then
local trialState = JediTrials:getTrialStateName(pPlayer, trialNumber)
if (CreatureObject(pPlayer):hasScreenPlayState(1, trialState .. "_saber")) then
msgFinal = "@jedi_trials:craft_lightsaber_02"
else
msgFinal = "@jedi_trials:craft_lightsaber_01"
end
else
local planetData = JediTrials:getTrialPlanetAndCity(pPlayer)
local cityName = planetData[2]
cityName = string.gsub(cityName, "_", " ")
cityName = string.gsub(" "..cityName, "%W%l", string.upper):sub(2)
local msgPrefix = "@jedi_trials:" .. trialData.trialName .. "_01 " .. "@jedi_trials:" .. planetData[1]
local msgPostfix = "@jedi_trials:" .. trialData.trialName .. "_02 " .. cityName .. "."
msgFinal = msgPrefix .. " " .. msgPostfix
end
local sui = SuiMessageBox.new("JediTrials", "emptyCallback")
sui.hideCancelButton()
sui.setTitle("@jedi_trials:force_shrine_title")
sui.setPrompt(msgFinal)
sui.sendTo(pPlayer)
CreatureObject(pPlayer):sendSystemMessage("@jedi_trials:padawan_trials_tell_about_restart")
end
function PadawanTrials:notifyEnteredMainLocSpawnArea(pArea, pPlayer)
if (pArea == nil or pPlayer == nil or not SceneObject(pPlayer):isPlayerCreature()) then
return 0
end
local playerID = SceneObject(pPlayer):getObjectID()
local ownerID = readData(SceneObject(pArea):getObjectID() .. ":ownerID")
if (playerID ~= ownerID) then
return 0
end
local pActiveArea = spawnActiveArea(SceneObject(pPlayer):getZoneName(), "object/active_area.iff", SceneObject(pArea):getWorldPositionX(), SceneObject(pArea):getWorldPositionZ(), SceneObject(pArea):getWorldPositionY(), 32, 0)
if pActiveArea == nil then
printLuaError("PadawanTrials:notifyEnteredMainLocSpawnArea, failed to create npc destroy active area.")
CreatureObject(pPlayer):sendSystemMessage("Failed to spawn quest area, please submit a bug report.")
self:failTrial(pPlayer)
return 1
end
createObserver(EXITEDAREA, "PadawanTrials", "notifyExitedLocDestroyArea", pActiveArea)
local areaID = SceneObject(pActiveArea):getObjectID()
writeData(areaID .. ":ownerID", playerID)
writeData(playerID .. ":destroyAreaID", areaID)
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
local trialData = padawanTrialQuests[trialNumber]
if (trialData == nil) then
printLuaError("PadawanTrials:notifyEnteredMainLocSpawnArea, nil trialData for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial number " .. trialNumber .. "\n.")
self:failTrial(pPlayer)
return 1
end
local spawnLoc = JediTrials:getTrialLocation(pPlayer)
local planetData = JediTrials:getTrialPlanetAndCity(pPlayer)
if (trialData.trialNpc == nil) then
printLuaError("PadawanTrials:notifyEnteredMainLocSpawnArea, nil trialNpc for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial number " .. trialNumber .. "\n.")
self:failTrial(pPlayer)
return 1
end
local pNpc = spawnMobile(planetData[1], trialData.trialNpc, 0, spawnLoc[1], spawnLoc[2], spawnLoc[3], getRandomNumber(180) - 180, 0)
if (pNpc == nil) then
printLuaError("PadawanTrials:notifyEnteredTrialTargetArea, failed to spawn quest mobile.")
CreatureObject(pPlayer):sendSystemMessage("Failed to spawn quest mobile, please submit a bug report.")
self:failTrial(pPlayer)
return 1
end
local npcID = SceneObject(pNpc):getObjectID()
CreatureObject(pNpc):setPvpStatusBitmask(0) -- Prevent attacking.
CreatureObject(pNpc):setOptionsBitmask(136)
CreatureObject(pNpc):setCustomObjectName(trialData.trialNpcName)
writeData(areaID .. ":npcID", npcID)
writeData(npcID .. ":ownerID", playerID)
AiAgent(pNpc):setConvoTemplate("padawan_" .. trialData.trialName .. "_01_convo_template")
deleteData(playerID .. ":mainLocSpawnAreaID")
deleteData(SceneObject(pArea):getObjectID() .. ":ownerID")
SceneObject(pArea):destroyObjectFromWorld()
return 1
end
function PadawanTrials:notifyExitedLocDestroyArea(pArea, pPlayer)
if (pArea == nil or pPlayer == nil or not SceneObject(pPlayer):isPlayerCreature()) then
return 0
end
local playerID = SceneObject(pPlayer):getObjectID()
local ownerID = readData(SceneObject(pArea):getObjectID() .. ":ownerID")
if (playerID ~= ownerID) then
return 0
end
local areaID = SceneObject(pArea):getObjectID()
local npcID = readData(areaID .. ":npcID")
local pNpc = getSceneObject(npcID)
if (pNpc == nil) then
deleteData(npcID .. ":ownerID")
deleteData(npcID .. ":JediTrials:objectSearched")
deleteData(areaID .. ":ownerID")
deleteData(areaID .. ":npcID")
return 1
end
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
if (trialNumber == nil or not JediTrials:isOnPadawanTrials(pPlayer)) then
self:removeNpcDestroyActiveArea(pPlayer)
deleteData(npcID .. ":ownerID")
deleteData(npcID .. ":JediTrials:objectSearched")
deleteData(npcID .. ":destroyNpcOnExit")
SceneObject(pNpc):destroyObjectFromWorld()
return 1
end
local trialState = JediTrials:getTrialStateName(pPlayer, trialNumber)
if (trialState == nil or CreatureObject(pPlayer):hasScreenPlayState(1, trialState) or readData(npcID .. ":destroyNpcOnExit") == 1) then
self:removeNpcDestroyActiveArea(pPlayer)
deleteData(npcID .. ":ownerID")
deleteData(npcID .. ":JediTrials:objectSearched")
deleteData(npcID .. ":destroyNpcOnExit")
SceneObject(pNpc):destroyObjectFromWorld()
return 1
end
return 0
end
function PadawanTrials:removeNpcDestroyActiveArea(pPlayer)
local playerID = SceneObject(pPlayer):getObjectID()
local areaID = readData(playerID .. ":destroyAreaID")
local pArea = getSceneObject(areaID)
if (pArea ~= nil) then
SceneObject(pArea):destroyObjectFromWorld()
end
deleteData(areaID .. ":npcID")
deleteData(areaID .. ":ownerID")
deleteData(playerID .. ":destroyAreaID")
end
function PadawanTrials:createTargetLocation(pPlayer, isThirdLocation)
if (isThirdLocation == nil) then
isThirdLocation = false
end
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
local trialData = padawanTrialQuests[trialNumber]
if (trialData == nil) then
printLuaError("PadawanTrials:createTargetLocation, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNumber)
return
end
local trialName = trialData.trialName
local zoneName = SceneObject(pPlayer):getZoneName()
local targetLoc
if (isThirdLocation and trialData.thirdTargetLoc ~= nil) then
targetLoc = trialData.thirdTargetLoc
zoneName = targetLoc[4]
elseif (trialData.targetLoc ~= nil) then
targetLoc = trialData.targetLoc
zoneName = targetLoc[4]
else
targetLoc = getSpawnPoint(zoneName, SceneObject(pPlayer):getWorldPositionX(), SceneObject(pPlayer):getWorldPositionY(), 900, 1800, true)
end
if (targetLoc == nil) then
printLuaError("Unable to find spawn point in PadawanTrials:createTargetLocation.")
CreatureObject(pPlayer):sendSystemMessage("Failed to get a good spawn location, please submit a bug report.")
self:failTrial(pPlayer)
return
end
local npcTemplate
if (isThirdLocation and trialData.thirdTargetNpc ~= nil) then
npcTemplate = trialData.thirdTargetNpc
elseif (trialData.targetNpc ~= nil) then
npcTemplate = trialData.targetNpc
end
if (npcTemplate ~= nil) then
local pActiveArea = spawnActiveArea(zoneName, "object/active_area.iff", targetLoc[1], targetLoc[2], targetLoc[3], 100, 0)
local playerID = SceneObject(pPlayer):getObjectID()
if pActiveArea == nil then
printLuaError("PadawanTrials:createTargetLocation, failed to create active area.")
CreatureObject(pPlayer):sendSystemMessage("Failed to spawn quest area, please submit a bug report.")
self:failTrial(pPlayer)
return
end
local areaID = SceneObject(pActiveArea):getObjectID()
writeData(areaID .. ":ownerID", playerID)
writeData(playerID .. ":targetLocSpawnAreaID", areaID)
if (isThirdLocation) then
writeData(areaID .. ":isThirdLoc", 1)
end
createObserver(ENTEREDAREA, "PadawanTrials", "notifyEnteredTargetLocSpawnArea", pActiveArea)
end
local pGhost = CreatureObject(pPlayer):getPlayerObject()
if (pGhost ~= nil) then
PlayerObject(pGhost):addWaypoint(zoneName, "Padawan Trial waypoint", "", targetLoc[1], targetLoc[3], WAYPOINTBLUE, true, true, WAYPOINTQUESTTASK)
end
end
function PadawanTrials:notifyEnteredTargetLocSpawnArea(pArea, pPlayer)
if (pArea == nil or pPlayer == nil or not SceneObject(pPlayer):isPlayerCreature()) then
return 0
end
local playerID = SceneObject(pPlayer):getObjectID()
local areaID = SceneObject(pArea):getObjectID()
local ownerID = readData(areaID .. ":ownerID")
local isThirdLocation = readData(areaID .. ":isThirdLoc") == 1
if (playerID ~= ownerID) then
return 0
end
deleteData(playerID .. ":targetLocSpawnAreaID")
deleteData(areaID .. ":ownerID")
deleteData(areaID .. ":isThirdLoc")
SceneObject(pArea):destroyObjectFromWorld()
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
local trialData = padawanTrialQuests[trialNumber]
if (trialData == nil) then
printLuaError("PadawanTrials:notifyEnteredTargetLocSpawnArea, unable to get trial data for player " .. SceneObject(pPlayer):getCustomObjectName() .. " on trial " .. trialNumber)
return 1
end
local npcTemplate
if (isThirdLocation and trialData.thirdTargetNpc ~= nil) then
npcTemplate = trialData.thirdTargetNpc
elseif (trialData.targetNpc ~= nil) then
npcTemplate = trialData.targetNpc
end
if (npcTemplate ~= nil) then
local planetName = SceneObject(pPlayer):getZoneName()
local locX = SceneObject(pArea):getWorldPositionX()
local locZ = SceneObject(pArea):getWorldPositionZ()
local locY = SceneObject(pArea):getWorldPositionY()
local pNpc
if (string.find(trialData.targetNpc, ".iff")) then
pNpc = spawnSceneObject(planetName, trialData.targetNpc, locX, locZ, locY, 0, getRandomNumber(180) - 180)
else
pNpc = spawnMobile(planetName, trialData.targetNpc, 0, locX, locZ, locY, getRandomNumber(180) - 180, 0)
end
if (pNpc == nil) then
printLuaError("PadawanTrials:notifyEnteredTargetLocSpawnArea, failed to spawn quest mobile.")
CreatureObject(pPlayer):sendSystemMessage("Failed to spawn quest mobile, please submit a bug report.")
self:failTrial(pPlayer)
return 1
end
local npcID = SceneObject(pNpc):getObjectID()
writeData(npcID .. ":ownerID", playerID)
if (isThirdLocation and trialData.thirdTargetName ~= nil) then
SceneObject(pNpc):setCustomObjectName(trialData.thirdTargetName)
elseif (trialData.targetNpcName ~= nil) then
SceneObject(pNpc):setCustomObjectName(trialData.targetNpcName)
end
if (not string.find(trialData.targetNpc, ".iff")) then
if ((isThirdLocation and trialData.thirdTargetKillable ~= nil and trialData.thirdTargetKillable) or trialData.targetKillable) then
createObserver(OBJECTDESTRUCTION, "PadawanTrials", "notifyQuestTargetDead", pNpc)
else
CreatureObject(pNpc):setPvpStatusBitmask(0)
end
end
if (trialData.trialType == TRIAL_TALK and not string.find(trialData.targetNpc, ".iff")) then
CreatureObject(pNpc):setOptionsBitmask(136)
if (isThirdLocation) then
AiAgent(pNpc):setConvoTemplate("padawan_" .. trialData.trialName .. "_03_convo_template")
else
AiAgent(pNpc):setConvoTemplate("padawan_" .. trialData.trialName .. "_02_convo_template")
end
end
local pActiveArea = spawnActiveArea(planetName, "object/active_area.iff", locX, locZ, locY, 32, 0)
if pActiveArea == nil then
printLuaError("PadawanTrials:notifyEnteredTargetLocSpawnArea, failed to create npc destroy active area.")
CreatureObject(pPlayer):sendSystemMessage("Failed to spawn quest area, please submit a bug report.")
self:failTrial(pPlayer)
return 1
end
local areaID = SceneObject(pActiveArea):getObjectID()
writeData(areaID .. ":ownerID", playerID)
writeData(areaID .. ":npcID", npcID)
createObserver(EXITEDAREA, "PadawanTrials", "notifyExitedLocDestroyArea", pActiveArea)
end
return 1
end
function PadawanTrials:notifyQuestTargetDead(pVictim, pAttacker)
if (pVictim == nil or pAttacker == nil) then
return 1
end
local ownerID = readData(SceneObject(pVictim):getObjectID() .. ":ownerID")
local pOwner = getSceneObject(ownerID)
if (pOwner == nil) then
return 1
end
local npcID = SceneObject(pVictim):getObjectID()
if (readData(npcID .. ":destroyNpcOnExit") ~= 1) then
local trialNumber = JediTrials:getCurrentTrial(pOwner)
if (trialNumber == 0) then
return 1
end
local trialData = padawanTrialQuests[trialNumber]
if (trialData == nil) then
printLuaError("PadawanTrials:notifyQuestTargetDead, unable to get trial data for player " .. SceneObject(pOwner):getCustomObjectName() .. " on trial " .. trialNumber)
return 1
end
if (trialData.killMessage ~= nil and trialData.killMessage ~= "") then
CreatureObject(pOwner):sendSystemMessage(trialData.killMessage)
end
CreatureObject(pOwner):sendSystemMessage("@jedi_trials:padawan_trials_return_to_npc")
writeData(ownerID .. ":JediTrials:killedTarget", 1)
self:createMainLocation(pOwner)
end
deleteData(npcID .. ":destroyNpcOnExit")
deleteData(npcID .. ":ownerID")
return 1
end
function PadawanTrials:removeAllAreas(pPlayer)
if (pPlayer == nil) then
return
end
local playerID = SceneObject(pPlayer):getObjectID()
local areaID = readData(playerID .. ":mainLocSpawnAreaID")
local pArea = getSceneObject(areaID)
if (pArea ~= nil) then
SceneObject(pArea):destroyObjectFromWorld()
end
deleteData(areaID .. ":ownerID")
deleteData(playerID .. ":mainLocSpawnAreaID")
areaID = readData(playerID .. ":destroyAreaID")
pArea = getSceneObject(areaID)
if (pArea ~= nil) then
SceneObject(pArea):destroyObjectFromWorld()
end
local npcID = readData(areaID .. ":npcID")
deleteData(npcID .. ":JediTrials:objectSearched")
local pMobile = getSceneObject(npcID)
if (pMobile ~= nil) then
createEvent(5000, "HelperFuncs", "despawnMobileTask", pMobile, "")
end
deleteData(areaID .. ":npcID")
deleteData(areaID .. ":ownerID")
deleteData(playerID .. ":destroyAreaID")
areaID = readData(playerID .. ":targetLocSpawnAreaID")
pArea = getSceneObject(areaID)
if (pArea ~= nil) then
SceneObject(pArea):destroyObjectFromWorld()
end
deleteData(areaID .. ":ownerID")
deleteData(areaID .. ":isThirdLoc")
deleteData(playerID .. ":targetLocSpawnAreaID")
end
function PadawanTrials:failTrial(pPlayer)
if (pPlayer == nil) then
return
end
local pGhost = CreatureObject(pPlayer):getPlayerObject()
if (pGhost == nil) then
return
end
local playerID = SceneObject(pPlayer):getObjectID()
self:removeAllAreas(pPlayer)
PlayerObject(pGhost):removeWaypointBySpecialType(WAYPOINTQUESTTASK)
JediTrials:setCurrentTrial(pPlayer, 0)
deleteData(playerID .. ":JediTrials:acceptedTask")
deleteData(playerID .. ":JediTrials:killedTarget")
deleteData(playerID .. ":JediTrials:spokeToTarget01")
deleteData(playerID .. ":JediTrials:spokeToTarget02")
deleteScreenPlayData(pPlayer, "JediTrials", "huntTarget")
deleteScreenPlayData(pPlayer, "JediTrials", "huntTargetCount")
deleteScreenPlayData(pPlayer, "JediTrials", "huntTargetGoal")
dropObserver(KILLEDCREATURE, "PadawanTrials", "notifyKilledHuntTarget", pPlayer)
local failAmount = JediTrials:getTrialFailureCount(pPlayer)
local failAmountMsg = nil
if (failAmount == nil or failAmount == 0) then
JediTrials:setTrialFailureCount(pPlayer, 1)
failAmountMsg = "@jedi_trials:padawan_trials_trial_failed_first"
elseif (failAmount == 1) then
JediTrials:setTrialFailureCount(pPlayer, 2)
failAmountMsg = "@jedi_trials:padawan_trials_trial_failed_second"
elseif (failAmount == 2) then
failAmountMsg = "@jedi_trials:padawan_trials_trial_failed_final"
self:resetAllPadawanTrials(pPlayer)
end
local sui = SuiMessageBox.new("JediTrials", "emptyCallback")
sui.hideCancelButton()
sui.setTitle("@jedi_trials:force_shrine_title")
sui.setPrompt(failAmountMsg)
sui.sendTo(pPlayer)
end
function PadawanTrials:passTrial(pPlayer)
if (pPlayer == nil) then
return
end
local pGhost = CreatureObject(pPlayer):getPlayerObject()
if (pGhost == nil) then
return
end
if (not JediTrials:isEligibleForPadawanTrials(pPlayer)) then
local sui = SuiMessageBox.new("JediTrials", "emptyCallback")
sui.setTitle("@jedi_trials:padawan_trials_title")
if (CreatureObject(pPlayer):hasSkill("force_title_jedi_rank_01")) then
sui.setPrompt("@jedi_trials:padawan_trials_being_removed_revoked")
else
sui.setPrompt("@jedi_trials:padawan_trials_being_removed")
end
sui.setOkButtonText("@jedi_trials:button_close")
sui.sendTo(pPlayer)
self:resetAllPadawanTrials(pPlayer)
return
end
local playerID = SceneObject(pPlayer):getObjectID()
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
local trialState = JediTrials:getTrialStateName(pPlayer, trialNumber)
local trialsCompleted = JediTrials:getTrialsCompleted(pPlayer) + 1
deleteScreenPlayData(pPlayer, "JediTrials", "huntTarget")
deleteScreenPlayData(pPlayer, "JediTrials", "huntTargetCount")
deleteScreenPlayData(pPlayer, "JediTrials", "huntTargetGoal")
dropObserver(KILLEDCREATURE, "PadawanTrials", "notifyKilledHuntTarget", pPlayer)
deleteData(playerID .. ":JediTrials:acceptedTask")
deleteData(playerID .. ":JediTrials:killedTarget")
deleteData(playerID .. ":JediTrials:spokeToTarget01")
deleteData(playerID .. ":JediTrials:spokeToTarget02")
CreatureObject(pPlayer):setScreenPlayState(1, trialState) -- Complete Trial.
JediTrials:setCurrentTrial(pPlayer, 0)
JediTrials:setTrialsCompleted(pPlayer, trialsCompleted)
PlayerObject(pGhost):removeWaypointBySpecialType(WAYPOINTQUESTTASK)
CreatureObject(pPlayer):sendSystemMessage("@jedi_trials:padawan_trials_next_trial") -- You have done well and successfully completed the trial you faced. To undertake your next trial, simply meditate at any Force shrine.
end
function PadawanTrials:showCurrentTrial(pShrine, pPlayer)
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
local trialData = padawanTrialQuests[trialNumber]
local sui = SuiMessageBox.new("PadawanTrials", "handleShowInfoChoice")
sui.setTitle("@jedi_trials:force_shrine_title")
sui.setTargetNetworkId(SceneObject(pShrine):getObjectID())
sui.setCancelButtonText("@jedi_trials:button_close") -- Close
sui.setOtherButtonText("@jedi_trials:button_restart") -- Restart Current Trial
sui.setOkButtonText("@jedi_trials:button_abort_padawan") -- Quit Padawan Trials
-- Other Button setup subscribe
sui.setProperty("btnRevert", "OnPress", "RevertWasPressed=1\r\nparent.btnOk.press=t")
sui.subscribeToPropertyForEvent(SuiEventType.SET_onClosedOk, "btnRevert", "RevertWasPressed")
if (trialData.trialType == TRIAL_LIGHTSABER) then
local trialState = JediTrials:getTrialStateName(pPlayer, trialNumber)
if (CreatureObject(pPlayer):hasScreenPlayState(1, trialState .. "_saber")) then
sui.setPrompt("@jedi_trials:" .. trialData.trialName .. "_02")
else
sui.setPrompt("@jedi_trials:" .. trialData.trialName .. "_01")
end
else
local suiPrompt = "@jedi_trials:" .. trialData.trialName .. "_03"
if (trialData.trialType == TRIAL_HUNT) then
local targetCount = tonumber(readScreenPlayData(pPlayer, "JediTrials", "huntTargetCount"))
if (targetCount ~= nil and targetCount > 0) then
suiPrompt = suiPrompt .. " " .. targetCount
else
local planetData = JediTrials:getTrialPlanetAndCity(pPlayer)
local cityName = planetData[2]
cityName = string.gsub(cityName, "_", " ")
cityName = string.gsub(" "..cityName, "%W%l", string.upper):sub(2)
local msgPrefix = "@jedi_trials:" .. trialData.trialName .. "_01 " .. "@jedi_trials:" .. planetData[1]
local msgPostfix = "@jedi_trials:" .. trialData.trialName .. "_02 " .. cityName .. "."
suiPrompt = msgPrefix .. " " .. msgPostfix
end
end
sui.setPrompt(suiPrompt)
end
sui.sendTo(pPlayer)
end
function PadawanTrials:handleShowInfoChoice(pPlayer, pSui, eventIndex, ...)
if (pPlayer == nil) then
return
end
local cancelPressed = (eventIndex == 1)
local args = {...}
local restart = args[1]
if (cancelPressed) then
return
elseif (restart ~= nil) then
self:restartCurrentPadawanTrial(pPlayer)
elseif (eventIndex == 0) then
self:quitPadawanTrials(pPlayer)
end
end
function PadawanTrials:onPlayerLoggedIn(pPlayer)
local trialNumber = JediTrials:getCurrentTrial(pPlayer)
local playerID = SceneObject(pPlayer):getObjectID()
if (trialNumber >= 1) then
local trialData = padawanTrialQuests[trialNumber]
local trialState = JediTrials:getTrialStateName(pPlayer, trialNumber)
if (trialData.trialType == TRIAL_HUNT and tonumber(readScreenPlayData(pPlayer, "JediTrials", "huntTargetGoal")) ~= nil) then
dropObserver(KILLEDCREATURE, "PadawanTrials", "notifyKilledHuntTarget", pPlayer)
if (self:hasCompletedHunt(pPlayer) and not JediTrials:hasTrialArea(pPlayer)) then
self:createMainLocation(pPlayer)
elseif (not self:hasCompletedHunt(pPlayer)) then
createObserver(KILLEDCREATURE, "PadawanTrials", "notifyKilledHuntTarget", pPlayer)
end
elseif (trialData.trialType == TRIAL_LIGHTSABER and not CreatureObject(pPlayer):hasScreenPlayState(1, trialState .. "_crystal")) then
if (CreatureObject(pPlayer):hasScreenPlayState(1, trialState .. "_saber")) then
dropObserver(TUNEDCRYSTAL, "PadawanTrials", "notifyTunedLightsaberCrystal", pPlayer)
createObserver(TUNEDCRYSTAL, "PadawanTrials", "notifyTunedLightsaberCrystal", pPlayer)
else
dropObserver(PROTOTYPECREATED, "PadawanTrials", "notifyCraftedTrainingSaber", pPlayer)
createObserver(PROTOTYPECREATED, "PadawanTrials", "notifyCraftedTrainingSaber", pPlayer)
end
elseif (trialData.trialType ~= TRIAL_HUNT and trialData.trialType ~= TRIAL_LIGHTSABER and not JediTrials:hasTrialArea(pPlayer) and trialData.trialName ~= "pannaqa" and readData(playerID .. ":JediTrials:acceptedTask") == 0) then
-- Restarts trial if player does not have a properly stored spawn location
if (JediTrials:getTrialLocation(pPlayer) == nil) then
self:startTrial(pPlayer, trialNumber, true)
else
self:createMainLocation(pPlayer)
end
end
end
end
|
local baloon
local frames={}
local activeframe
function love.load()
baloonw=75.5 -- largura do balão
baloonh=78 -- altura do balão
positionx, positiony=250, 250 --variável que armazena a posição do balão
scale=1 --escala do balão
timecontrol=400 -- variável que controla a velocidade em que um balão explode
speedx=1 --variável que controla o movimento do balão no eixo x
speedy=3--variável que controla o movimento do balão no eixo y
cooldown=0--varíavel responsável pelo cooldown entre os toques do mouse
score=0--variável que controla o score do jogo atual
phasecounter=1--variável responsável pela controle entre menu, jogo e tela de game over/scoreboard
scoreboard={}--vetor que armazena os 5 maiores scores desde que o jogo foi inicializado
for i=1,5 do
scoreboard[i]=0
end
life=5 -- variável que armazena as vidas
--imagens/cursor
menuwallpaper=love.graphics.newImage("images/circus2.jpg")
gamewallpaper=love.graphics.newImage("images/clouds.jpg")
baloon=love.graphics.newImage("images/Balloon2.png")
cursor=love.mouse.newCursor("images/fork.png")
--músicas
musicmenu=love.audio.newSource("audio/Stylo8Bit.mp3", stream)
musicgame=love.audio.newSource("audio/7thElement.mp3", stream)
musicboard=love.audio.newSource("audio/FunkyMonks.mp3", stream)
--sons do jogo
miss=love.audio.newSource("audio/false.wav", static)
hit=love.audio.newSource("audio/true.mp3", static)
boom=love.audio.newSource("audio/boom.mp3", static)
--fontes
menufont=love.graphics.newFont("font/babyblocks.ttf", 35)
titlefont=love.graphics.newFont("font/babyblocks.ttf", 60)
gamefont=love.graphics.newFont("font/px10.ttf", 25)
scoreboardfont=love.graphics.newFont("font//px10.ttf", 40)
--frames
frames[1]=love.graphics.newQuad(0, 0, baloonw, baloonh, baloon:getDimensions())
frames[2]=love.graphics.newQuad(baloonw+7, 0, baloonw-7, baloonh, baloon:getDimensions())
activeframe=frames[1]
menuframe=frames[1]
end
local elapsedTime=0
function love.update(dt)
--variáveis que armazenam a posição atual do mouse, respectivamente, no eixo x e y.
mousex=love.mouse.getX()
mousey=love.mouse.getY()
if phasecounter ==1 then -- dentro desta condição, está o menu
love.audio.stop(musicboard, musicgame, boom, hit, miss)-- para as outras musicas/sons
love.audio.play(musicmenu)-- começa a musica do menu
if love.keyboard.isDown("z") or (love.mouse.isDown(1) and mousex >=365 and mousex <= 365+baloonw and mousey>=290 and mousey <= 290+baloonh) then -- condição para fazer o balao do menu explodir
elapsedTime=elapsedTime+2*dt
menuswitch=true --flag para poder fazer o balão do menu expandir
end
if menuswitch==true then-- condição para o balão expandir
scale=scale+(10*elapsedTime/timecontrol)
if scale>=1.4 or (love.mouse.isDown(1) and mousex >=365 and mousex <= 365+baloonw and mousey>=290 and mousey <= 290+baloonh) then -- condição para o balão explodir
scale=1.4
menuframe=frames[2]--o frame do balão vira o do balão estourado
love.audio.play(boom)--barulho de estouro
elapsedTime=0
menuswitch=false
end
end
if menuframe==frames[2] then -- se o balão for estourado
elapsedTime=elapsedTime+2*dt
scale =scale-(4*elapsedTime/timecontrol)--sua escala diminui
if scale <= 1.15 then --chegando nesse limite
scale =1--escala volta ao tamanho original
cooldown=0--reseta o cooldown
menuframe=frames[1]--volta ao frame inicial
phasecounter=2--começa o jogo
end
end
elseif phasecounter==2 then -- dentro desta condição, está o jogo
-- para as musicas das outras telas
love.audio.stop(musicmenu)
love.audio.stop(musicboard)
love.audio.play(musicgame)-- toca a musica do jogo
elapsedTime=elapsedTime+2*dt
cooldown=cooldown-1 -- diminui o cooldown do toque
if life<=0 then -- se a vida chegar a zero, o jogo vai para a tela de game over,
--mas antes disso, armazena-se o score no devido lugar do scoreboard
if score >= scoreboard[1] then
scoreboard[5]=scoreboard[4]
scoreboard[4]=scoreboard[3]
scoreboard[3]=scoreboard[2]
scoreboard[2]=scoreboard[1]
scoreboard[1]=score
phasecounter=3
elseif score>=scoreboard[2] and score<scoreboard[1] then
scoreboard[5]=scoreboard[4]
scoreboard[4]=scoreboard[3]
scoreboard[3]=scoreboard[2]
scoreboard[2]=score
phasecounter=3
elseif score>=scoreboard[3] and score<scoreboard[2] then
scoreboard[5]=scoreboard[4]
scoreboard[4]=scoreboard[3]
scoreboard[3]=score
phasecounter=3
elseif score>=scoreboard[4] and score<scoreboard[3] then
scoreboard[5]=scoreboard[4]
scoreboard[4]=score
phasecounter=3
elseif score>=scoreboard[5] and score<scoreboard[4] then
scoreboard[5]=score
phasecounter=3
else
phasecounter=3--Game over
end
end
--a parte a seguir do código é responsável por controlar a velocidade em que o balão explode, de acordo com o score
if score<50 then
timecontrol=400
end
if score>=50 and score <100 then
timecontrol=300
elseif score>=100 and score<200 then
timecontrol=200
elseif score>=200 and score<300 then
timecontrol=150
elseif score>=300 and score<350 then
timecontrol=130
elseif score>=350 and score<400 then
timecontrol=110
elseif score>=400 and score<500 then
timecontrol=100
elseif score>=500 and score<550 then
timecontrol=90
elseif score>=550 and score<600 then
timecontrol=80
elseif score>=600 and score<650 then
timecontrol=70
elseif score>=650 and score<700 then
timecontrol=60
elseif score>=700 and score<800 then
timecontrol=55
elseif score>=800 and score<900 then
timecontrol=50
elseif score>=900 and score<1000 then
timecontrol=45
elseif score>=1000 then
timecontrol=40
end
if activeframe==frames[1] then
scale=scale+(elapsedTime/timecontrol) -- parte do código responsável por fazer o balão expandir
if scale>=1.4 then -- parte do código responsável por fazer o balão explodir, se chegar a um certo tamanho
love.audio.stop(boom)
love.audio.play(boom)--som de explosão
elapsedTime=0
activeframe=frames[2]--frame de balão explodido
life=life-1 -- menos uma vida
if score > 15 then
score=score-15 -- score desce em 15 pontos
else
score=0
end
end
if love.mouse.isDown(1) and cooldown<=0 then
cooldown=20 --o coodown reseta, para não poder spammar o botão do mouse
love.audio.stop(hit, boom, miss) -- para os sons
--parte do código responsável por checar se o toque coincide com a posição atual do balão
if mousex>=positionx+(speedx*elapsedTime) and mousex<=positionx+(speedx*elapsedTime)+(baloonw*scale)
and mousey>=positiony+(speedy*elapsedTime) and mousey<=positiony+(speedy*elapsedTime)+(baloonh*scale) then
score=score+10 --score aumenta em 10 pontos
activeframe=frames[2] --frame de balão explodido
love.audio.play(hit)--som de acerto
elapsedTime=0
scale=1.4 -- escala aumenta
else -- se o toque for errado
if score > 5 then
score = score-5--score diminui
else
score=0
end
life=life-1 -- menos uma vida
love.audio.play(miss) -- som de erro
end
end
else scale =scale-(5*elapsedTime/timecontrol) -- se o frame atual não for o 1, o balão diminui
if scale <=1.25 then -- chegando nessa escala após ser explodido~:
positionx=math.random(700) -- posições resetam
positiony=math.random(500)
speedx=math.random(-10,10)--velocidades mudam
speedy=math.random(-1,-20)
scale=1-- escala resetam
activeframe=frames[1] --frame volta ao de um balão intacto
elapsedTime=0--tempo reseta
end
end
elseif phasecounter== 3 then-- dentro desta condição está a tela de Game Over
love.audio.stop(musicgame, hit, miss, boom)-- para os outros audios
love.audio.play(musicboard)-- toca a musica da tela de game over
if love.keyboard.isDown("z") then -- se o jogador tocar a tecla Z, voltamos para o jogo, e reseta-se tudo
activeframe=frames[1]
positionx, positiony=250, 250
score=0
life=5
phasecounter=2
scale=1
elapsedTime=0
cooldown=0
elseif love.keyboard.isDown("x") then -- se o jogador tocar a tecla X, voltamos para a tela inicial, e reseta-se tudo
activeframe=frames[1]
positionx, positiony=250, 250
score=0
life=5
phasecounter=1
scale=1
elapsedTime=0
end
end
end
function love.draw()
if phasecounter==1 then -- na tela de menu:
love.mouse.setCursor(cursor) -- transforma o cursor do mouse na imagem do garfo
love.graphics.setColor(255, 255, 255)
love.graphics.draw(menuwallpaper,0,0,0,0.45,0.6)-- desenha o wallpaper do menu
love.graphics.setFont(menufont) -- transforma a fonte atual para a fonte do menu
love.graphics.draw(baloon, menuframe, 365, 290, 0, scale, scale)-- desenha o balão do menu
love.graphics.setColor(0,0,0) --seta preto como a cor das letras
love.graphics.print("Press Z to play", 285, 480) -- escreve "pressione z para jogar" em inglês
love.graphics.setFont(titlefont)--muda a fonte para a fonte do titulo do jogo
--escreve o titulo do jogo
love.graphics.print("Baloon", 250, 80)
love.graphics.print("POP", 300, 140)
elseif phasecounter==2 then -- na tela do jogo:
love.graphics.setColor(255, 255, 255)
love.graphics.draw(gamewallpaper, 0, 0, 0, 0.5, 0.5)--desenha o wallpaper do jogo
--esse segmento do codigo é responsável por desenhar os balões que representam as vidas do jogador
if life == 5 then
love.graphics.draw(baloon, frames[1], 606, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 642, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 678, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 714, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 750, 7, 0, 0.5, 0.5)
elseif life == 4 then -- uma vida se foi, um balão de vida estourou
love.graphics.draw(baloon, frames[1], 606, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 642, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 678, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 714, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 750, 7, 0, 0.5, 0.5)
elseif life == 3 then -- duas vidas, dois balões de vida estourados
love.graphics.draw(baloon, frames[1], 606, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 642, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 678, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 714, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 750, 7, 0, 0.5, 0.5)
elseif life == 2 then -- assim por diante
love.graphics.draw(baloon, frames[1], 606, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[1], 642, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 678, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 714, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 750, 7, 0, 0.5, 0.5)
elseif life == 1 then
love.graphics.draw(baloon, frames[1], 606, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 642, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 678, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 714, 7, 0, 0.5, 0.5)
love.graphics.draw(baloon, frames[2], 750, 7, 0, 0.5, 0.5)
end
love.graphics.draw(baloon, activeframe, positionx+(speedx*elapsedTime), positiony+(speedy*elapsedTime), 0, scale, scale) -- desenha o balão do jogo, com posição, escala e velocidade variáveis
love.graphics.setFont(gamefont) -- transforma a fonte atual na fonte do jogo
love.graphics.setColor(0,0,0) -- seta preto como a cor das letras
love.graphics.print("Score: " .. score, 20, 10)-- escreve o Score atual no canto superior esquerdo da tela
love.graphics.print("Life: ", 550, 10)-- escreve a quantidade atual de vidas no canto superior direito da tela
if score<=100 then
love.graphics.print("Click on the Baloon to pop it!", 230, 550) -- escreve na tela a instrução de como jogar Baloon POP
end
elseif phasecounter==3 then -- na tela de game over
love.graphics.setColor(255, 255, 255)
love.graphics.draw(menuwallpaper,0 ,0, 0, 0.45, 0.6)--desenha o wallpaper da tela de game over
love.graphics.setFont(titlefont)-- transforma a fonte atual na fonte de titulo
love.graphics.setColor(0, 0, 0) -- seta preto como a cor das letras
love.graphics.print("GAME OVER", 180, 30, 0, 0.8, 0.8) --escreve GAME OVER na tela
love.graphics.setFont(menufont)-- transforma a fonte atual como a mesma fonte do menu
love.graphics.print("Press Z to Continue", 230, 430) -- indica para o jogador que deve apertar Z para continuar o jogo
love.graphics.print("Press X to Return to Menu", 200, 500) -- indica para o jogador que deve apertar X para voltar para o menu
--escreve na tela SCOREBOARD e mostra os 5 maiores scores, a partir de quando o jogo foi inicializado
love.graphics.print("SCOREBOARD", 200, 100)
love.graphics.print("1. " ..scoreboard[1], 180, 150)
love.graphics.print("2. " ..scoreboard[2], 180, 200)
love.graphics.print("3. " ..scoreboard[3], 180, 250)
love.graphics.print("4. " ..scoreboard[4], 180, 300)
love.graphics.print("5. " ..scoreboard[5], 180, 350)
end
end |
require("commons")
data:extend({
{
type = "string-setting",
allowed_values = itemsSettingValues,
default_value = defaultItemsSettingValue,
name = spawnItemsSettingName,
setting_type = "runtime-global",
order = "a"
},
{
type = "string-setting",
allowed_values = itemsSettingValues,
default_value = defaultItemsSettingValue,
name = respawnItemsSettingName,
setting_type = "runtime-global",
order = "b"
}
})
|
return {
text = 0
,private = 1
,voice = 2
,group = 3
,category = 4
,news = 5
,store = 6
}
|
function ghost(t, ...)
local g = {}
local exc = {...}
local check = {}
for i = 1, #exc do
check[exc[i]] = true
end
for i = 1, #t do
if not check[i] then
g[#g + 1] = t[i]
end
end
return g
end
|
-- Player Service
-- pobammer
-- August 2, 2020
local Players = game:GetService("Players")
local PointsService = game:GetService("PointsService")
local ConfigurationModule
local Data
local DisplayService
local PointsService
local Promise
local PromiseModule
local TeamService
local PlayerService = {Client = {}}
local RESET_MOUSE_ICON = "ResetMouseIcon"
local PlayersCanSpawn = false
local GameRunning = false
local function CharacterAddedFenv(Player: Player): (Model) -> nil
return function(Character: Model): nil
PromiseModule.Child(Character, "Humanoid", 5):Then(function(Humanoid: Humanoid)
Humanoid.Died:Connect(function()
Promise.Delay(ConfigurationModule.RESPAWN_TIME):Then(function()
if GameRunning then
Player:LoadCharacter()
end
end)
end)
end, function(Error)
warn(string.format("Error trying to get Humanoid: %s", tostring(Error)))
end)
end
end
local function PlayerAdded(Player: Player): nil
if not Player:FindFirstChild("leaderstats") then
-- local PlayerData = Data.ForPlayer(Player.UserId)
local Leaderstats: Folder = Instance.new("Folder")
Leaderstats.Name = "leaderstats"
local Captures: IntValue = Instance.new("IntValue")
Captures.Name = "Captures"
Captures.Value = 0
Captures.Parent = Leaderstats
Leaderstats.Parent = Player
TeamService:AssignPlayerToTeam(Player)
local CharacterAdded = CharacterAddedFenv(Player)
if Player.Character then
CharacterAdded(Player.Character)
end
Player.CharacterAdded:Connect(CharacterAdded)
if PlayersCanSpawn then
Player:LoadCharacter()
else
DisplayService:StartIntermission(Player)
end
end
end
local function PlayerRemoving(Player: Player): nil
TeamService:RemovePlayer(Player)
end
function PlayerService.SetGameRunning(_, Running: boolean): nil
GameRunning = Running
end
function PlayerService.ClearPlayerScores(): nil
for _, Player in ipairs(Players:GetPlayers()) do
local Leaderstats: Folder? = Player:FindFirstChild("leaderstats")
if Leaderstats then
local Captures: IntValue? = Leaderstats:FindFirstChild("Captures")
if Captures then
Captures.Value = 0
end
end
end
end
function PlayerService.LoadPlayers(): nil
for _, Player in ipairs(Players:GetPlayers()) do
Player:LoadCharacter()
end
end
function PlayerService.AllowPlayerSpawn(_, CanSpawn: boolean): nil
PlayersCanSpawn = CanSpawn
end
function PlayerService:DestroyPlayers()
for _, Player in ipairs(Players:GetPlayers()) do
if Player.Character then
Player.Character:Destroy()
end
Player.Backpack:ClearAllChildren()
end
self:FireAllClients(RESET_MOUSE_ICON)
end
function PlayerService.AddPlayerScore(_, Player: Player, Score: number): nil
Player.leaderstats.Captures.Value += Score
PointsService:PromiseAwardPoints(Player, Score):Catch(warn)
end
function PlayerService.Start(): nil
Players.PlayerAdded:Connect(PlayerAdded)
Players.PlayerRemoving:Connect(PlayerRemoving)
end
function PlayerService:Init(): nil
ConfigurationModule = self.Modules.ConfigurationModule
Data = self.Modules.Data
DisplayService = self.Services.DisplayService
PointsService = self.Services.PointsService
Promise = self.Shared.Promise
PromiseModule = self.Shared.PromiseModule
TeamService = self.Services.TeamService
self:RegisterClientEvent(RESET_MOUSE_ICON)
end
return PlayerService |
object_building_player_yt1300 = object_building_player_shared_yt1300:new {
}
ObjectTemplates:addTemplate(object_building_player_yt1300, "object/building/player/yt1300.iff")
|
local skynet = require "skynet"
skynet.register_protocol {
name = "client",
id = skynet.PTYPE_CLIENT,
unpack = skynet.tostring,
}
local CMD = {}
local playerList = {}
local curMoveIndex = nil
local nameList = {}
local chessMap = {}
local curGate
function CMD.enterRoom(source, gate, username, userid)
if #playerList >= 2 then
return false
end
curGate = gate
skynet.error("enterRoom gate="..tostring(gate))
skynet.error("enterRoom username="..tostring(username))
local playInfo = {}
playInfo.gate = gate
playInfo.username = username
playInfo.userid = userid
table.insert(playerList,playInfo)
return true
end
local function updateNameList()
nameList = {}
for i,playInfo in ipairs(playerList) do
table.insert(nameList, playInfo.username)
end
end
local function exitRoom(userid)
curMoveIndex = nil
chessMap = {}
for i,playInfo in ipairs(playerList) do
if playInfo.userid == userid then
skynet.error("Room afk userid="..tostring(userid))
table.remove(playerList, i)
return
end
end
end
function CMD.afk(source, userid)
exitRoom(userid)
updateNameList()
local msgTb = {
msgId = "S_EXITROOM",
userId = userId,
}
skynet.send(curGate, "lua", "roomSendMsg", nameList, msgTb)
end
local function checkIsEnd(curIndexX, curIndexY, curMoveIndex)
local dirList = {{1,0}, {1,1}, {1,-1}, {0,1}}
for i,dir in ipairs(dirList) do
local num = 0
local dirX = dir[1]
local dirY = dir[2]
for j=1,100 do
local indexX = curIndexX + dirX*j
local indexY = curIndexY + dirY*j
if chessMap[indexX] and chessMap[indexX][indexY] == curMoveIndex then
num = num + 1
else
break
end
end
dirX = -dirX
dirY = -dirY
for j=1,100 do
local indexX = curIndexX + dirX*j
local indexY = curIndexY + dirY*j
if chessMap[indexX] and chessMap[indexX][indexY] == curMoveIndex then
num = num + 1
else
break
end
end
if num >= 4 then
return true
end
end
return false
end
local function request(userId, messageTb)
msgId = messageTb.msgId
skynet.error("Room request userId="..tostring(userId))
skynet.error("Room request msgId="..tostring(msgId))
if msgId == "GAMEREADY" then
local readyNum = 0
nameList = {}
for i,playInfo in ipairs(playerList) do
if playInfo.userid == userId then
playInfo.isReady = true
end
if playInfo.isReady then
readyNum = readyNum + 1
table.insert(nameList, playInfo.username)
end
end
if readyNum == 2 then
curMoveIndex = 1
chessMap = {}
skynet.error("Room request playerList[curMoveIndex].userid="..tostring(playerList[curMoveIndex].userid))
local msgTb = {
msgId = "S_G_MOVE",
userId = playerList[curMoveIndex].userid
}
skynet.send(curGate, "lua", "roomSendMsg", nameList, msgTb)
end
elseif msgId == "PLAYCHESS" then
skynet.error("Room request playerList[curMoveIndex].userid="..tostring(playerList[curMoveIndex].userid))
if userId == playerList[curMoveIndex].userid then
local curIndexX = messageTb.chessIndexX
local curIndexY = messageTb.chessIndexY
if not chessMap[curIndexX] then
chessMap[curIndexX] = {}
end
if chessMap[curIndexX][curIndexY] ~= nil then
return
end
chessMap[curIndexX][curIndexY] = curMoveIndex
skynet.error("Room request curIndexX="..tostring(curIndexX))
skynet.error("Room request curIndexY="..tostring(curIndexY))
if checkIsEnd(curIndexX, curIndexY, curMoveIndex) then
local msgTb = {
msgId = "S_PLAYRESULT",
userId = userId,
chessIndexX = messageTb.chessIndexX,
chessIndexY = messageTb.chessIndexY,
}
skynet.send(curGate, "lua", "roomSendMsg", nameList, msgTb)
else
local msgTb = {
msgId = "S_PLAYCHESS",
userId = userId,
chessIndexX = messageTb.chessIndexX,
chessIndexY = messageTb.chessIndexY,
}
skynet.send(curGate, "lua", "roomSendMsg", nameList, msgTb)
curMoveIndex = curMoveIndex + 1
if curMoveIndex > 2 then
curMoveIndex = 1
end
end
end
elseif msgId == "EXITROOM" then
exitRoom(userId)
local msgTb = {
msgId = "S_EXITROOM",
userId = userId,
}
skynet.send(curGate, "lua", "roomSendMsg", nameList, msgTb)
end
end
skynet.start(function()
-- If you want to fork a work thread , you MUST do it in CMD.login
skynet.dispatch("lua", function(session, source, command, ...)
local f = assert(CMD[command])
skynet.ret(skynet.pack(f(source, ...)))
end)
skynet.dispatch("client", function(_,_, info)
-- the simple echo service
skynet.error("Room dispatch client")
local userId, messageTb = skynet.unpack(info)
request(userId, messageTb)
local info = {}
info.cancelResult = true
skynet.ret(skynet.pack(info))
end)
end)
|
ui = {}
require "ui/button"
require "ui/slider"
require "ui/checkBox"
require "ui/textBox"
function mouseOver( x, y, w, h )
local mx = love.mouse.getX()
local my = love.mouse.getY()
return mx >= x and mx <= x + w and my >= y and my <= y + h
end
function pointInsideRectangle( mx, my, x, y, w, h )
return mx >= x and mx <= x + w and my >= y and my <= y + h
end
function setColor( color, r, g, b, a )
if( a == nil ) then a = 255 end
color.r, color.g, color.b, color.a = r, g, b, a
end
function colorTorgb( color )
return color.r, color.g, color.b, color.a
end
function ui.init()
ui.elements = {}
ui.cursorBlinkTime = 1
ui.enableInput = true
ui.input = {}
end
function ui.clear()
ui.elements = {}
end
function ui.reset()
ui.input = {}
ui.cursorBlinkTime = ui.cursorBlinkTime - gDt
if( ui.cursorBlinkTime < 0 ) then ui.cursorBlinkTime = 1 end
end
-- Button +
-- TextButton +
-- Check Box +
-- Slider +
-- TextBox +
-- Scrollable canvas thingy - don't need it
|
-------------------ModuleInfo-------------------
--- Author : jxy
--- Date : 2020/10/04 01:58
--- Description :
--- https://github.com/JomiXedYu/JxCode.LuaSharp
------------------------------------------------
---@class SysLib.IOException : SysLib.Exception
local IOException, base = class.extends("SysLib.IOException", SysLib.Exception)
return IOException |
object_draft_schematic_chemistry_medpack_enhance_health_triad_a = object_draft_schematic_chemistry_shared_medpack_enhance_health_triad_a:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_chemistry_medpack_enhance_health_triad_a, "object/draft_schematic/chemistry/medpack_enhance_health_triad_a.iff")
|
local UTILITY = require(script:GetCustomProperty("TalentSelectorUtility"))
local TALENT_TREES = script:GetCustomProperty("TalentTrees"):WaitForObject()
local PLAYER_STATE_GROUP = script:GetCustomProperty("PlayerStateGroup"):WaitForObject()
local PLAYER_STATE_TEMPLATE = script:GetCustomProperty("PlayerStateTemplate")
local PLAYER_STATE_TREE_TEMPLATE = script:GetCustomProperty("PlayerStateTreeTemplate")
local N_USABLE_TREES = TALENT_TREES:GetCustomProperty("NUsableTrees")
function OnPlayerJoined(player)
local talentTreeTable = UTILITY.TALENT_TREE_TABLE
local playerStateHelper = World.SpawnAsset(PLAYER_STATE_TEMPLATE, {parent = PLAYER_STATE_GROUP})
playerStateHelper.name = UTILITY.GetPlayerStateHelperName(player)
local treeNameTable = {}
for talentTreeName, _ in pairs(talentTreeTable) do
table.insert(treeNameTable, talentTreeName)
end
for endIndex = #treeNameTable, 2, -1 do
local randomIndex = math.random(endIndex)
treeNameTable[randomIndex], treeNameTable[endIndex] = treeNameTable[endIndex], treeNameTable[randomIndex]
end
for i = 1, N_USABLE_TREES do
local talentTreeName = treeNameTable[i]
local playerStateTreeHelper = World.SpawnAsset(PLAYER_STATE_TREE_TEMPLATE, {parent = PLAYER_STATE_GROUP})
playerStateTreeHelper.name = UTILITY.GetPlayerStateTreeHelperName(player, talentTreeName)
local talentString = ""
for _, _ in pairs(talentTreeTable[talentTreeName]) do
talentString = talentString .. "0"
end
playerStateTreeHelper:SetNetworkedCustomProperty("TalentString", talentString)
end
end
function OnPlayerLeft(player)
local playerStateHelper = UTILITY.GetPlayerStateHelper(player)
playerStateHelper:Destroy()
for talentTreeName, _ in pairs(UTILITY.TALENT_TREE_TABLE) do
local playerStateTreeHelper = UTILITY.GetPlayerStateTreeHelper(player, talentTreeName)
if playerStateTreeHelper then
playerStateTreeHelper:Destroy()
end
end
end
function OnTryLearnTalent(player, treeOrder, treeX, treeY)
for treeName, treeData in pairs(UTILITY.TALENT_TREE_DATA) do
if treeData.order == treeOrder then
for _, talentData in pairs(UTILITY.TALENT_TREE_TABLE[treeData.name]) do
if talentData.treeX == treeX and talentData.treeY == treeY then
UTILITY.TryAddPlayerTalent(player, talentData)
return
end
end
local warningFormatString = "Player %s tried to take missing talent in tree %s (%d, %d)"
warn(string.format(warningFormatString, player.name, treeData.name, treeX, treeY))
end
end
local warningFormatString = "Player %s tried to take talent in missing tree with order %d"
warn(string.format(warningFormatString, player.name, treeOrder))
end
UTILITY.InitializeTalentTreeData(TALENT_TREES, PLAYER_STATE_GROUP)
Game.playerJoinedEvent:Connect(OnPlayerJoined)
Game.playerLeftEvent:Connect(OnPlayerLeft)
Events.ConnectForPlayer("TryLearnTalent", OnTryLearnTalent)
|
-----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Porter Moogle
-- Type: Storage Moogle
-- !pos ? ? ? 50
-----------------------------------
local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs")
require("scripts/globals/porter_moogle_util")
local e =
{
TALK_EVENT_ID = 957,
STORE_EVENT_ID = 958,
RETRIEVE_EVENT_ID = 959,
ALREADY_STORED_ID = 960,
MAGIAN_TRIAL_ID = 963
}
function onTrade(player,npc,trade)
porterMoogleTrade(player, trade, e)
end
function onTrigger(player,npc)
-- No idea what the params are, other than event ID and gil.
player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8)
end
function onEventUpdate(player,csid,option)
porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID)
end
function onEventFinish(player,csid,option)
porterEventFinish(player, csid, option, e.TALK_EVENT_ID)
end
|
workspace "jsolibrary"
architecture "x86_64"
configurations { "Debug", "Release" }
flags {"MultiProcessorCompile"}
outputdir = "%{cfg.system}-%{cfg.architecture}"
filter "system:windows"
systemversion "latest"
include "jsolibrary"
group "examples"
include "examples/01"
group ""
|
--premake5.lua - Build File
project "MathLib"
kind "StaticLib"
language "C++"
cppdialect "C++17"
staticruntime "off"
pchheader "MathPCH.h"
pchsource "Source/MathPCH.cpp"
targetdir "%{wks.location}/%{prj.name}/Builds/%{cfg.buildcfg}/%{cfg.platform}"
objdir "%{wks.location}/%{prj.name}/Builds-Int/%{cfg.buildcfg}/%{cfg.platform}"
files
{
"Source/**.h",
"Source/**.cpp",
"Source/**.hpp"
}
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on" |
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
local S = E:GetModule('Skins')
--Lua functions
local _G = _G
local unpack = unpack
local format = format
--WoW API / Variables
local HideUIPanel = HideUIPanel
local ShowUIPanel = ShowUIPanel
local function LoadSkin()
if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.macro ~= true then return end
local MacroFrame = _G.MacroFrame
S:HandlePortraitFrame(MacroFrame, true)
MacroFrame:Width(360)
_G.MacroFrameTextBackground:StripTextures()
_G.MacroFrameTextBackground:SetTemplate()
_G.MacroButtonScrollFrame:StripTextures()
_G.MacroButtonScrollFrame:CreateBackdrop()
S:HandleScrollBar(_G.MacroButtonScrollFrameScrollBar)
S:HandleScrollBar(_G.MacroFrameScrollFrameScrollBar)
local buttons = {
_G.MacroSaveButton,
_G.MacroCancelButton,
_G.MacroDeleteButton,
_G.MacroNewButton,
_G.MacroExitButton,
_G.MacroEditButton,
_G.MacroFrameTab1,
_G.MacroFrameTab2,
}
for i = 1, #buttons do
buttons[i]:StripTextures()
S:HandleButton(buttons[i])
end
_G.MacroNewButton:ClearAllPoints()
_G.MacroNewButton:SetPoint("RIGHT", _G.MacroExitButton, "LEFT", -2 , 0)
for i = 1, 2 do
local tab = _G[format("MacroFrameTab%s", i)]
tab:Height(22)
end
_G.MacroFrameTab1:Point("TOPLEFT", MacroFrame, "TOPLEFT", 85, -39)
_G.MacroFrameTab2:Point("LEFT", _G.MacroFrameTab1, "RIGHT", 4, 0)
--Reposition edit button
_G.MacroEditButton:ClearAllPoints()
_G.MacroEditButton:Point("BOTTOMLEFT", _G.MacroFrameSelectedMacroButton, "BOTTOMRIGHT", 10, 0)
-- Regular scroll bar
S:HandleScrollBar(_G.MacroButtonScrollFrame)
-- Big icon
_G.MacroFrameSelectedMacroButton:StripTextures()
_G.MacroFrameSelectedMacroButton:StyleButton(true)
_G.MacroFrameSelectedMacroButton:GetNormalTexture():SetTexture()
_G.MacroFrameSelectedMacroButton:SetTemplate()
_G.MacroFrameSelectedMacroButtonIcon:SetTexCoord(unpack(E.TexCoords))
_G.MacroFrameSelectedMacroButtonIcon:Point("TOPLEFT", E.mult, -E.mult)
_G.MacroFrameSelectedMacroButtonIcon:Point("BOTTOMRIGHT", -E.mult, E.mult)
-- Skin all buttons
for i = 1, _G.MAX_ACCOUNT_MACROS do
local b = _G["MacroButton"..i]
local t = _G["MacroButton"..i.."Icon"]
if b then
b:StripTextures()
b:StyleButton(true)
b:SetTemplate(nil, true)
end
if t then
t:SetTexCoord(unpack(E.TexCoords))
t:Point("TOPLEFT", E.mult, -E.mult)
t:Point("BOTTOMRIGHT", -E.mult, E.mult)
end
end
--Icon selection frame
ShowUIPanel(MacroFrame); --Toggle frame to create necessary variables needed for popup frame
HideUIPanel(MacroFrame);
local MacroPopupFrame = _G.MacroPopupFrame
MacroPopupFrame:Show() --Toggle the frame in order to create the necessary button elements
MacroPopupFrame:Hide()
-- Popout Frame
S:HandleButton(MacroPopupFrame.BorderBox.OkayButton)
S:HandleButton(MacroPopupFrame.BorderBox.CancelButton)
S:HandleScrollBar(_G.MacroPopupScrollFrameScrollBar)
S:HandleEditBox(_G.MacroPopupEditBox)
_G.MacroPopupNameLeft:SetTexture()
_G.MacroPopupNameMiddle:SetTexture()
_G.MacroPopupNameRight:SetTexture()
S:HandleIconSelectionFrame(MacroPopupFrame, _G.NUM_MACRO_ICONS_SHOWN, "MacroPopupButton", "MacroPopup")
MacroPopupFrame:HookScript("OnShow", function(self)
self:ClearAllPoints()
self:Point("TOPLEFT", MacroFrame, "TOPRIGHT", 2, 0)
end)
end
S:AddCallbackForAddon("Blizzard_MacroUI", "Macro", LoadSkin)
|
local exports = {}
local wildcards = require("lettersmith.wildcards")
local filter = require("lettersmith.transducers").filter
local transformer = require("lettersmith.lazy").transformer
local table_utils = require("lettersmith.table_utils")
local merge = table_utils.merge
-- Create a plugin function that will keep only docs who's path
-- matches a wildcard path string.
local function query(wildcard_string)
return transformer(filter(function(doc)
return doc.relative_filepath:find(wildcards.parse(wildcard_string))
end))
end
exports.query = query
-- Render contents through mapping function `a2b`.
-- Returns a rendering function which will transform a `doc` object,
-- returning a new doc object with contents field transformed by `a2b`.
local function renderer(a2b)
return function(doc)
return merge(doc, { contents = a2b(doc.contents) })
end
end
exports.renderer = renderer
-- Wrap value in a coroutine iterator.
local function wrap_in_iter(thing)
return coroutine.wrap(function ()
coroutine.yield(thing)
end)
end
exports.wrap_in_iter = wrap_in_iter
return exports |
local ls = require "luasnip"
local s = ls.snippet
local t = ls.text_node
local i = ls.insert_node
local fmt = require("luasnip.extras.fmt").fmt
-- local rep = require("luasnip.extras").rep
local l = require("luasnip.extras").lambda
local f = ls.function_node
-- local d = ls.dynamic_node
-- local c = ls.choice_node
-- local sn = ls.snippet_node
-- local isn = ls.indent_snippet_node
-- Needed for fancy snippets
-- local ts_utils_ok, ts_utils = pcall(require, "nvim-treesitter.ts_utils")
-- if not ts_utils_ok then
-- return {}
-- end
-- local query = require "vim.treesitter.query"
-- local function_q = vim.treesitter.parse_query(
-- "lua",
-- [[
-- [
-- (function_declaration parameters: (parameters) @parms)
-- (function_definition parameters: (parameters) @parms)
-- ] @fun
-- ]]
-- )
-- This only matches returns that actually return something, so early return can still be used for
-- control flow!
-- local return_q = vim.treesitter.parse_query("lua", "(return_statement (expression_list)) @ret")
--- Obtains list of parameter names for the next lua function and whether it returns something.
-- @param linenr Line number at which we start searching.
-- @return parms, ret where parms is a list of parameters, in the order that they appear in the
-- function and ret is truthy if the function ever returns something.
-- local function next_fun_parms(linenr)
-- local bufnr = vim.api.nvim_get_current_buf()
--
-- -- TODO: Doesn't work if we land inside of a comment block because that's a different
-- -- "language".
-- local root = ts_utils.get_root_for_position(linenr - 1, 0)
-- if not root then
-- return
-- end
--
-- for _, captures, _ in function_q:iter_matches(root, bufnr) do
-- local sline = captures[1]:range()
--
-- if sline >= linenr - 1 then
-- local parms = {}
-- for parm, node_type in captures[1]:iter_children() do
-- -- Parameters are given via "name" nodes, other nodes might be comments etc.
-- if node_type == "name" then
-- table.insert(parms, query.get_node_text(parm, bufnr))
-- end
-- end
--
-- local returns = return_q:iter_matches(captures[2], bufnr)()
-- return parms, returns
-- end
-- end
-- end
local snippets = {
ls.parser.parse_snippet("lm", "local M = {}\n\nfunction M.setup()\n $1 \nend\n\nreturn M"),
-- s("lm", { t { "local M = {}", "", "function M.setup()", "" }, i(1, ""), t { "", "end", "", "return M" } }),
ls.parser.parse_snippet("for", "for ${1:i} = ${2:1}, ${3:n} do\n\t$0\nend"),
ls.parser.parse_snippet("fun", "local function ${1:name}($2)\n\t$0\nend"),
ls.parser.parse_snippet("while", "while ${1:cond} do\n\t$0\nend"),
ls.parser.parse_snippet("mfun", "function M.${1:name}($2)\n\t$0\nend"),
ls.parser.parse_snippet("pairs", "for ${1:key}, ${2:value} in pairs($3) do\n\t$0\nend"),
ls.parser.parse_snippet("ipairs", "for ${1:i}, ${2:value} in ipairs($3) do\n\t$0\nend"),
ls.parser.parse_snippet("if", "if ${1:cond} then\n\t$0\nend"),
ls.parser.parse_snippet("ifn", "if not ${1:cond} then\n\t$0\nend"),
s("todo", t 'print("TODO")'),
-- s("req", fmt("local {} = require('{}')", { i(1, "default"), rep(1) })),
s(
"localreq",
fmt('local {} = require("{}")', {
l(l._1:match("[^.]*$"):gsub("[^%a]+", "_"), 1),
i(1, "module"),
})
),
s(
"localreq2",
fmt([[local {} = require "{}"]], {
f(function(import_name)
local parts = vim.split(import_name[1][1], ".", true)
return parts[#parts] or ""
end, {
1,
}),
i(1),
})
),
s(
"preq",
fmt('local {1}_ok, {1} = pcall(require, "{}")\nif not {1}_ok then return end', {
l(l._1:match("[^.]*$"):gsub("[^%a]+", "_"), 1),
i(1, "module"),
})
),
-- s("doc", {
-- t "--- ",
-- i(1, "Function description."),
-- d(2, function(_, snip)
-- local parms, ret = next_fun_parms(tonumber(snip.env.TM_LINE_NUMBER))
-- assert(parms, "Did not find a function!")
--
-- local parm_nodes = {}
-- for j, parm in ipairs(parms) do
-- table.insert(parm_nodes, t { "", "-- @param " .. parm .. " " })
-- table.insert(parm_nodes, i(j, "Parameter description."))
-- end
--
-- if ret then
-- table.insert(parm_nodes, t { "", "-- @return " })
-- table.insert(parm_nodes, i(#parms + 1, "Return description."))
-- end
--
-- return s(1, parm_nodes)
-- end),
-- }),
}
return snippets
|
require "plugin/img2D"
local img=API.load_img("data/sss.png",4)
print(img.comp)
local block=get_editable_block(img)
local w,h=#block,#block[1]
print(block.width,block.height)
w=math.floor(w/2)
h=math.floor(h/2)
for i=w-10,w+10 do
for j=h-10,h+10 do
set_block_color(block,i,j,255,0,0,255)
end
end
API.save_img(img,"data/sss-save.png") |
local replyTimeout = 30
local protocolName = "Lupus590:terminalOverRednet"
local protocolEvents = {
terminalCall = "terminal_call",
terminalResponce = "terminal_responce",
terminalError = "terminal_error",
inputEvent = "input_event",
connectionRequest = "connection_request",
connectionResponce = "connection_responce",
disconnection = "disconnection"
}
local inputEvents = {
char = true,
key = true,
key_up = true,
mouse_click = true,
mouse_drag = true,
mouse_scroll = true,
mouse_up = true,
paste = true,
term_resize = true,
}
local eventTranslatiorIsRunning = false
local function eventTranslatorDeamon() -- seperate coroutine may be a cause of slowdown
eventTranslatiorIsRunning = true
while true do
local sender, message, protocol = rednet.receive(protocolName, nil)
if type(message) == "table" then
os.queueEvent(message.type, sender, message)
end
end
end
-- provides methods for sending return values and errors to the host's terminal proxy
local function newTerminalResponder(hostId)
if not eventTranslatiorIsRunning then error("event translator is not running") end
local function returnCall(callId, ...)
rednet.send(hostId, {type = protocolEvents.terminalResponce, callId = callId, returnValues = table.pack(...) }, protocolName)
end
local function returnError(callId, ...)
rednet.send(hostId, {type = protocolEvents.terminalError, callId = callId, returnValues = table.pack(...) }, protocolName)
end
return {
returnCall = returnCall,
returnError = returnError,
}
end
-- creates a fake terminal object which forwards calls to the remote screen
local function newRemoteTerminalProxy(clientId)
if not eventTranslatiorIsRunning then error("event translator is not running") end
local function sendCall(method, ...)
rednet.send(clientId, {type = protocolEvents.terminalCall, method = method, args = table.pack(...) }, protocolName)
while true do
local senderId, message = rednet.receive(protocolName, replyTimeout)
if senderId == clientId and type(message) == "table" then
if message.type == protocolEvents.terminalResponce then
return table.unpack(message.returnValues)
elseif message.type == protocolEvents.terminalError then
error("\nRemote Code:\n "..table.concat(message.returnValues, " \n").."\nEnd of Remote Code", 2)
end
elseif senderId == nil then
error("Timed out awaiting responce",0)
end
end
end
local fakeTermMeta = {
__index = function(_, key)
return function(...)
return sendCall(key, ...)
end
end
}
return setmetatable({}, fakeTermMeta)
end
-- simple net shell like client
local function connectToRemoteTerminal(hostId, parentTerminal)
if not eventTranslatiorIsRunning then error("event translator is not running") end
local terminalResponder = newTerminalResponder(hostId)
rednet.send(hostId, {type = protocolEvents.connectionRequest}, protocolName)
repeat
local _, recievedId, message = os.pullEvent(protocolEvents.connectionResponce)
until recievedId == hostId and message and message.type == protocolEvents.connectionResponce and message.accepted
while true do
local event = table.pack(os.pullEvent())
if event[1] == protocolEvents.terminalCall and event[2] == hostId then
local terminalEventArg = event[3]
local returnValues = table.pack(pcall(parentTerminal[terminalEventArg.method], table.unpack(terminalEventArg.args)))
local ok = table.remove(returnValues,1)
returnValues.n = returnValues.n -1
if ok then
terminalResponder.returnCall(terminalEventArg.callId, table.unpack(returnValues))
else
terminalResponder.returnError(terminalEventArg.callId, table.unpack(returnValues))
end
elseif event[1] == protocolEvents.disconnection then
error("Disconnected by remote host",0)
elseif inputEvents[event[1]] then
rednet.send(hostId, {type = protocolEvents.inputEvent, eventData = event}, protocolName)
end
end
end
-- simple net shell like server
local function remoteTerminalDeamon(startupProgram)
if not eventTranslatiorIsRunning then error("event translator is not running") end
while true do
local _, clientId = os.pullEvent(protocolEvents.connectionRequest)
rednet.send(clientId, {type = protocolEvents.connectionResponce, accepted = true}, protocolName)
local remoteTerminal = newRemoteTerminalProxy(clientId)
local oldTerm = term.redirect(remoteTerminal)
local function shellRun()
os.run({shell = shell}, "rom/programs/shell.lua", startupProgram)
end
local function convertEvents()
while true do
local sender, message, protocol = rednet.receive(protocolName, nil)
if type(message) == "table" and message.type == protocolEvents.inputEvent and sender == clientId then
os.queueEvent(table.unpack(message.eventData))
end
end
end
parallel.waitForAny(convertEvents, shellRun)
rednet.send(clientId, {type = protocolEvents.disconnection}, protocolName)
term.redirect(oldTerm)
return
end
end
return {
protocolName = protocolName,
protocolEvents = protocolEvents,
inputEvents = inputEvents,
eventTranslatorDeamon = eventTranslatorDeamon,
newTerminalResponder = newTerminalResponder,
connectToRemoteTerminal = connectToRemoteTerminal,
newRemoteTerminalProxy = newRemoteTerminalProxy,
remoteTerminalDeamon = remoteTerminalDeamon,
} |
-----------------------------------------
-- ID: 4430
-- Item: bowl_of_pumpkin_soup
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- HP % 1 (cap 110)
-- Vitality -1
-- Agility 3
-- HP Recovered While Healing 5
-- Ranged Accuracy % 8 (cap 20)
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(tpz.effect.FOOD) or target:hasStatusEffect(tpz.effect.FIELD_SUPPORT_FOOD) then
result = tpz.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(tpz.effect.FOOD, 0, 0, 10800, 4430)
end
function onEffectGain(target, effect)
target:addMod(tpz.mod.FOOD_HPP, 1)
target:addMod(tpz.mod.FOOD_HP_CAP, 110)
target:addMod(tpz.mod.VIT, -1)
target:addMod(tpz.mod.AGI, 3)
target:addMod(tpz.mod.HPHEAL, 5)
target:addMod(tpz.mod.FOOD_RACCP, 8)
target:addMod(tpz.mod.FOOD_RACC_CAP, 20)
end
function onEffectLose(target, effect)
target:delMod(tpz.mod.FOOD_HPP, 1)
target:delMod(tpz.mod.FOOD_HP_CAP, 110)
target:delMod(tpz.mod.VIT, -1)
target:delMod(tpz.mod.AGI, 3)
target:delMod(tpz.mod.HPHEAL, 5)
target:delMod(tpz.mod.FOOD_RACCP, 8)
target:delMod(tpz.mod.FOOD_RACC_CAP, 20)
end
|
local CallbackHandler = LibStub('CallbackHandler-1.0')
local SocketMiddleware = LibStub('NetEaseSocketMiddleware-2.0')
local BroadMiddleware = LibStub('NetEaseBroadMiddleware-2.0')
local AceTimer = LibStub('AceTimer-3.0')
local AceEvent = LibStub('AceEvent-3.0')
local MAJOR, MINOR = 'SocketHandler-2.0', 20
local SocketHandler,oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not SocketHandler then return end
local random = fastrandom or random
local SOCKET_NORMAL = 1
local SOCKET_CONNECT = 2
local SOCKET_READY = 3
local CONNECT_DELAY = (...):match('^!!!!!!!!') and 10 or 30
local RETRY_DELAY = CONNECT_DELAY
local NOT_FOUND_MATCH = ERR_CHAT_PLAYER_NOT_FOUND_S:format('(.+)')
local SOCKET_BASE_CMD = {
NETEASE_CONNECT_SUCCESS = true,
NETEASE_CHANNEL_OWNER = true,
}
SocketHandler.EventHandler = SocketHandler.EventHandler or {}
SocketHandler.objects = SocketHandler.objects or {}
SocketHandler.channels = SocketHandler.channels or {}
SocketHandler.connectQueue = SocketHandler.connectQueue or {}
SocketHandler.connectStatus = SocketHandler.connectStatus or {}
SocketHandler.status = SOCKET_NORMAL
SocketHandler.isLoggedIn = false
SocketHandler._meta = {__index = SocketHandler}
local objects = SocketHandler.objects
local channels = SocketHandler.channels
local connectQueue = SocketHandler.connectQueue
local EventHandler = SocketHandler.EventHandler
local function OnUsed(registry, target, cmd)
target:RegisterCallback(cmd, 'OnSocket')
end
local _server
local function getServer()
if not _server then
local realms = GetAutoCompleteRealms()
if not realms or not realms[1] then
_server = GetRealmName():gsub('%s+', '')
else
_server = realms[1]
end
end
return _server
end
local function formatTarget(target)
if target then
return Ambiguate(target .. '-' .. getServer(), 'none')
end
end
local function getChannelId(channelName)
local id = GetChannelName(channelName)
if id and id > 0 then
return id
end
end
function SocketHandler:New()
local obj = setmetatable({}, self._meta)
local socketRegistry = CallbackHandler:New(obj, 'RegisterSocket', 'UnregisterSocket', 'UnregisterAllSocket')
local serverRegistry = CallbackHandler:New(obj, 'RegisterServer', 'UnregisterServer', 'UnregisterAllServer')
local function OnUnused(registry, target, cmd)
if SOCKET_BASE_CMD[cmd] then
return
end
if next(socketRegistry.events[cmd]) or next(socketRegistry.events[cmd]) then
return
end
target:UnregisterCallback(cmd)
end
socketRegistry.OnUsed = OnUsed
socketRegistry.OnUnused = OnUnused
serverRegistry.OnUsed = OnUsed
serverRegistry.OnUnused = OnUnused
obj.FireSocket = socketRegistry.Fire
obj.FireServer = serverRegistry.Fire
SocketMiddleware:Embed(obj)
AceTimer:Embed(obj)
tinsert(objects, obj)
return obj
end
function SocketHandler:PreServer(cmd, distribution, sender, ...)
if cmd == 'NETEASE_CONNECT_SUCCESS' then
local key, channelName = ...
local statusTable = self.statusTable
local connectKey = statusTable and statusTable.connectKey
if connectKey and connectKey == key then
self:CancelTimer(statusTable.retryConnectTimer)
self.target = sender
statusTable.status = SOCKET_READY
statusTable.retryConnectTimer = nil
self:SetChannel(channelName)
self:FireServer('SERVER_CONNECTED')
end
return true
end
if cmd == 'NETEASE_CHANNEL_OWNER' then
if self:IsServer(sender) or not self:IsReady() then
SetChannelOwner(..., sender)
end
return true
end
end
function SocketHandler:OnSocket(cmd, distribution, sender, ...)
if self:PreServer(cmd, distribution, sender, ...) then
return
elseif self:IsServer(sender) and self:IsReady() then
self:FireServer(cmd, ...)
elseif not SOCKET_BASE_CMD[cmd] then
self:FireSocket(cmd, sender, ...)
end
end
function SocketHandler:ListenSocket(prefix, target)
self.prefix = prefix
self.connectTarget = formatTarget(target)
self:UpdateStatusTable()
self:Listen(prefix, 4)
end
function SocketHandler:CheckSendDistribution(target)
if target == '@GROUP' then
if IsInRaid(LE_PARTY_CATEGORY_HOME) then
return 'RAID'
elseif IsInGroup(LE_PARTY_CATEGORY_HOME) then
return 'PARTY'
end
elseif target == '@CHANNEL' then
if self.channelId then
return 'CHANNEL', self.channelId
end
elseif target == '@GUILD' then
return 'GUILD'
elseif target == '@BATTLEGROUND' then
return 'BATTLEGROUND'
else
return 'WHISPER', target
end
end
function SocketHandler:SendSocket(target, cmd, ...)
local distribution, target = self:CheckSendDistribution(target)
if distribution then
self:Send(distribution, target, cmd, ...)
end
end
function SocketHandler:ConnectServer(target)
if not self.prefix then
error('Can`t found prefix in object', 4)
end
self.connectTarget = formatTarget(target) or self.connectTarget
if not self.connectTarget then
error('Can`t found connectTarget in object', 4)
end
self:UpdateStatusTable()
self.statusTable.status = SOCKET_CONNECT
self:RegisterCallback('NETEASE_CONNECT_SUCCESS', 'OnSocket')
self:RegisterCallback('NETEASE_CHANNEL_OWNER', 'OnSocket')
self:TryConnect()
end
function SocketHandler:DisconnectServer()
self.target = nil
self:ScheduleTimer('FireServer', 1, 'SERVER_DISCONNECTED')
end
function SocketHandler:ConnectChannel()
if self.channelName then
local id = getChannelId(self.channelName)
if id then
self.channelId = id
self:FireServer('CHANNEL_CONNECTED')
else
self.channelId = nil
JoinTemporaryChannel(self.channelName)
end
end
end
function SocketHandler:SendServer(cmd, ...)
if self.target then
self:Send('WHISPER', self.target, cmd, ...)
end
end
function SocketHandler:TryConnect()
local statusTable = self.statusTable
if not statusTable then
return
end
if self:TimeLeft(statusTable.retryConnectTimer) > 0 then
return
end
if self.isLoggedIn then
self:Send('WHISPER', self.connectTarget, 'NETEASE_CONNECT', self:GetConnectKey())
statusTable.retryConnectTimer = self:ScheduleTimer('TryConnect', RETRY_DELAY)
else
if not tContains(connectQueue, self) then
tinsert(connectQueue, self)
end
end
end
function SocketHandler:UpdateStatusTable()
if self.prefix and self.connectTarget then
local key = self.prefix .. '.' .. self.connectTarget
self.connectStatus[key] = self.connectStatus[key] or {}
self.statusTable = self.connectStatus[key]
else
self.statusTable = nil
end
end
function SocketHandler:GetConnectKey()
local statusTable = self.statusTable
if not statusTable.connectKey then
statusTable.connectKey = tostring(random(0x100000, 0xFFFFFF))
end
return statusTable.connectKey
end
function SocketHandler:SetChannel(channelName)
if self.channelName and self.channelName ~= channelName then
if channels[self.channelName] then
channels[self.channelName][self] = nil
if next(channels[self.channelName]) then
LeaveChannelByName(self.channelName)
end
end
end
self.channelName = channelName
if self.channelName then
channels[self.channelName] = channels[self.channelName] or {}
channels[self.channelName][self] = true
BroadMiddleware.Listen(self, self.channelName)
self:ConnectChannel()
end
end
function SocketHandler:IsReady()
local statusTable = self.statusTable
return statusTable and statusTable.status == SOCKET_READY
end
function SocketHandler:IsServer(sender)
return self.target == sender or self.connectTarget == sender
end
function SocketHandler:YOU_JOINED()
self.channelId = getChannelId(self.channelName)
self:ScheduleTimer('FireServer', 1, 'CHANNEL_CONNECTED', true)
end
function SocketHandler:YOU_LEFT()
self.channelId = nil
self:ScheduleTimer('FireServer', 1, 'CHANNEL_DISCONNECTED')
end
function SocketHandler:WRONG_PASSWORD()
self.channelId = nil
if self.channelName then
self:SendServer('SCJF', self.channelName)
self:ScheduleTimer('ConnectChannel', 30)
end
end
SocketHandler.YOU_CHANGED = SocketHandler.YOU_JOINED
SocketHandler.BANNED = SocketHandler.WRONG_PASSWORD
---- EventHandler
AceEvent:Embed(EventHandler)
AceTimer:Embed(EventHandler)
function EventHandler:CHAT_MSG_CHANNEL_NOTICE(_, event, _, _, _, _, _, _, id, channelName)
local callback = SocketHandler[event]
if callback and channels[channelName] then
for handler in pairs(channels[channelName]) do
callback(handler)
end
end
if ChannelFrame:IsShown() then
ChannelList_Update()
end
end
function EventHandler:PLAYER_LOGOUT()
self:UnregisterAllEvents()
self:CancelAllTimers()
for channelName in pairs(channels) do
LeaveChannelByName(channelName)
end
end
function EventHandler:PLAYER_LOGIN()
SocketHandler.isLoggedIn = true
self:RegisterEvent('PLAYER_LOGOUT')
self:RegisterEvent('CHAT_MSG_SYSTEM')
self:RegisterEvent('CHAT_MSG_CHANNEL_NOTICE')
for _, handler in ipairs(connectQueue) do
handler:TryConnect()
end
end
function EventHandler:CHAT_MSG_SYSTEM(_, msg)
local name = msg:match(NOT_FOUND_MATCH)
if not name then
return
end
name = Ambiguate(name, 'none')
for _, handler in pairs(objects) do
if handler.target == name then
if handler:IsReady() then
handler:DisconnectServer()
end
end
end
end
EventHandler:CancelAllTimers()
EventHandler:UnregisterAllEvents()
if IsLoggedIn() then
EventHandler:ScheduleTimer('PLAYER_LOGIN', CONNECT_DELAY)
else
EventHandler:RegisterEvent('PLAYER_LOGIN', function()
EventHandler:UnregisterEvent('PLAYER_LOGIN')
EventHandler:ScheduleTimer('PLAYER_LOGIN', CONNECT_DELAY)
end)
end
---- ChatFilter
if not SocketHandler.chatFilter then
ChatFrame_AddMessageEventFilter('CHAT_MSG_SYSTEM', function(_, _, msg)
local name = msg:match(NOT_FOUND_MATCH)
if not name then
return
end
name = Ambiguate(name, 'none')
for _, handler in pairs(objects) do
if handler:IsServer(name) then
return true
end
end
end)
SocketHandler.chatFilter = true
end
---- hook
if not SocketHandler.hooked then
SocketHandler.hooked = true
local orig_GetChannelDisplayInfo = GetChannelDisplayInfo
function GetChannelDisplayInfo(id)
local name, header, collapsed, channelNumber, count, active, category, voiceEnabled, voiceActive = orig_GetChannelDisplayInfo(id)
if channels[name] then
active = nil
end
return name, header, collapsed, channelNumber, count, active, category, voiceEnabled, voiceActive
end
hooksecurefunc('CreateChatChannelList', function()
for i = #CHAT_CONFIG_CHANNEL_LIST, 1, -1 do
local v = CHAT_CONFIG_CHANNEL_LIST[i]
if channels[v.channelName] then
tremove(CHAT_CONFIG_CHANNEL_LIST, i)
end
end
end)
end
|
SGL_FONT_ID_INVALID = 0xFFFF
SGL_MOV_ID_INVALID = 0xFFFF
SGL_SOUND_ID_INVALID = 0xFFFF
SGL_SPRITE_ID_INVALID = 0xFFFF
SGL_TEX_ID_INVALID = 0xFFFF |
function getPlayerDoor()
local world = getElementDimension(localPlayer)
if world == 0 then
return false
else
local doors = getElementsByType("pickup")
for _, door in ipairs(doors) do
if(tonumber(getElementData(door, "door.exitvw")) == world) then
return door
end
end
return false
end
end
function playerEnterDoor()
if getKeyState( "lalt" ) == true then
-- wchodzenie/wychodzenie z drzwi
local world = getElementDimension(getLocalPlayer())
local doors = getElementsByType("pickup")
local x, y, z = getElementPosition(getLocalPlayer())
-- buggerino
if isPedInVehicle(localPlayer) then
return
end
for i, door in ipairs(doors) do
-- wejście
if tonumber(getElementData(door, "door.entervw")) == getElementDimension(getLocalPlayer()) then
local distance = getDistanceBetweenPoints3D(x, y, z, tonumber(getElementData(door, "door.enterx")), tonumber(getElementData(door, "door.entery")), tonumber(getElementData(door,"door.enterz" )))
if distance < 3 then
triggerServerEvent("setPlayerToEnterDoors", getRootElement(), getLocalPlayer(), door)
break
end
end
-- wyjście
if tonumber(getElementData(door, "door.exitvw")) == getElementDimension(getLocalPlayer()) then
local distance = getDistanceBetweenPoints3D(x, y, z, tonumber(getElementData(door, "door.exitx")), tonumber(getElementData(door, "door.exity")), tonumber(getElementData(door, "door.exitz")))
if distance < 3 then
triggerServerEvent("setPlayerToExitDoors", getRootElement(), getLocalPlayer(), door)
break
end
end
end
end
end
addEventHandler("onClientResourceStart", resourceRoot, function() bindKey ( "space", "down", playerEnterDoor ) end)
--[[
Info drzwi
]]--
addEventHandler("onClientResourceStart", resourceRoot,
function()
------------------------------------------------------
-- GUI Sklepów
------------------------------------------------------
wnd_shopping = guiCreateWindow(0.29, 0.25, 0.42, 0.51, "Asortyment w sklepie", true)
guiWindowSetSizable(wnd_shopping, false)
grid_shopping = guiCreateGridList(0.02, 0.07, 0.97, 0.73, true, wnd_shopping)
guiGridListAddColumn(grid_shopping, "Nazwa produktu", 0.3)
guiGridListAddColumn(grid_shopping, "Ilość", 0.3)
guiGridListAddColumn(grid_shopping, "Cena", 0.3)
guiGridListAddRow(grid_shopping)
guiGridListSetItemText(grid_shopping, 0, 1, "Kremówka", false, false)
guiGridListSetItemText(grid_shopping, 0, 2, "2137", false, false)
guiGridListSetItemText(grid_shopping, 0, 3, "$23", false, false)
btn_shopping_buy = guiCreateButton(0.16, 0.83, 0.26, 0.11, "Kup", true, wnd_shopping)
guiSetProperty(btn_shopping_buy, "NormalTextColour", "FFAAAAAA")
btn_shopping_close = guiCreateButton(0.60, 0.83, 0.26, 0.11, "Zamknij", true, wnd_shopping)
guiSetProperty(btn_shopping_close, "NormalTextColour", "FFAAAAAA")
guiSetVisible(wnd_shopping, false)
guiGridListSetSortingEnabled ( grid_shopping, false )
addEventHandler("onClientGUIClick", btn_shopping_close, function() guiSetVisible(wnd_shopping, false) showCursor(false) guiSetInputEnabled(false) end, false)
addEventHandler("onClientGUIClick", btn_shopping_buy, function() finishPlayerShopping() end, false)
------------------------------------------------------
-- GUI Informacji o drzwiach
------------------------------------------------------
wnd_door_info = guiCreateWindow(0.36, 0.28, 0.28, 0.39, "Informacje o drzwiach", true)
guiWindowSetSizable(wnd_door_info, false)
grid_door_inf = guiCreateGridList(0.05, 0.08, 0.89, 0.65, true, wnd_door_info)
guiGridListAddColumn(grid_door_inf, "Typ", 0.5)
guiGridListAddColumn(grid_door_inf, "Wartość", 0.5)
for i = 1, 8 do
guiGridListAddRow(grid_door_inf)
end
guiGridListSetItemText(grid_door_inf, 0, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 0, 2, "-", false, false)
guiGridListSetItemText(grid_door_inf, 1, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 1, 2, "-", false, false)
guiGridListSetItemText(grid_door_inf, 2, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 2, 2, "-", false, false)
guiGridListSetItemText(grid_door_inf, 3, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 3, 2, "-", false, false)
guiGridListSetItemText(grid_door_inf, 4, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 4, 2, "-", false, false)
guiGridListSetItemText(grid_door_inf, 5, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 5, 2, "-", false, false)
guiGridListSetItemText(grid_door_inf, 6, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 6, 2, "-", false, false)
guiGridListSetItemText(grid_door_inf, 7, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 7, 2, "-", false, false)
guiGridListSetItemText(grid_door_inf, 8, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 8, 2, "-", false, false)
guiGridListSetItemText(grid_door_inf, 9, 1, "-", false, false)
guiGridListSetItemText(grid_door_inf, 9, 2, "-", false, false)
guiSetAlpha(grid_door_inf, 0.80)
btn_door_inf_close = guiCreateButton(0.31, 0.78, 0.38, 0.16, "Zamknij", true, wnd_door_info)
guiSetVisible(wnd_door_info, false)
guiGridListSetSortingEnabled ( grid_door_inf, false )
addEventHandler("onClientGUIClick", btn_door_inf_close, function() guiSetVisible(wnd_door_info, false) showCursor(false) guiSetInputEnabled(false) end, false)
end
)
function showDoorInfoView(theDoor)
-- UID
guiGridListSetItemText(grid_door_inf, 0, 1, "UID drzwi", false, false)
guiGridListSetItemText(grid_door_inf, 0, 2, getElementData(theDoor, "door.uid"), false, false)
-- ID
guiGridListSetItemText(grid_door_inf, 1, 1, "ID drzwi", false, false)
guiGridListSetItemText(grid_door_inf, 1, 2, getElementData(theDoor, "id"), false, false)
-- Pickup
guiGridListSetItemText(grid_door_inf, 2, 1, "ID Pickupa", false, false)
guiGridListSetItemText(grid_door_inf, 2, 2, getElementModel(theDoor), false, false)
-- Zamek
guiGridListSetItemText(grid_door_inf, 3, 1, "Zamek", false, false)
if tonumber(getElementData(theDoor, "door.lock")) == 1 then
guiGridListSetItemText(grid_door_inf, 3, 2, "zamknięty", false, false)
else
guiGridListSetItemText(grid_door_inf, 3, 2, "otwarty", false, false)
end
-- Nazwa drzwi
guiGridListSetItemText(grid_door_inf, 4, 1, "Nazwa drzwi", false, false)
guiGridListSetItemText(grid_door_inf, 4, 2, getElementData(theDoor, "door.name"), false, false)
-- Typ właściciela
guiGridListSetItemText(grid_door_inf, 5, 1, "Typ właściciela", false, false)
if tonumber(getElementData(theDoor, "door.ownertype")) == 1 then
guiGridListSetItemText(grid_door_inf, 5, 2, "Gracz", false, false)
elseif tonumber(getElementData(theDoor, "vehicle.ownertype")) == 0 then
guiGridListSetItemText(grid_door_inf, 5, 2, "Brak", false, false)
else
guiGridListSetItemText(grid_door_inf, 5, 2, "Grupa", false, false)
end
-- UID właściciela
guiGridListSetItemText(grid_door_inf, 6, 1, "UID właściciela", false, false)
guiGridListSetItemText(grid_door_inf, 6, 2, getElementData(theDoor, "door.owner"), false, false)
-- Nazwa grupy / Nick gracza
--guiGridListSetItemText(grid_door_inf, 7, 1, "UID właściciela", false, false)
--guiGridListSetItemText(grid_door_inf, 7, 2, getElementData(theDoor, "door.owner"), false, false)
guiSetVisible(wnd_door_info, true)
guiSetInputEnabled(true)
showCursor(true)
end
addEvent( "showDoorInfoView", true )
addEventHandler( "showDoorInfoView", getLocalPlayer(), showDoorInfoView ) |
---
-- @classmod AnimatedSpritesheetPlayer
-- @author Quenty
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local RunService = game:GetService("RunService")
local BaseObject = require("BaseObject")
local Maid = require("Maid")
local AnimatedSpritesheetPlayer = setmetatable({}, BaseObject)
AnimatedSpritesheetPlayer.ClassName = "AnimatedSpritesheetPlayer"
AnimatedSpritesheetPlayer.__index = AnimatedSpritesheetPlayer
function AnimatedSpritesheetPlayer.new(imageLabel, spritesheet)
local self = setmetatable(BaseObject.new(spritesheet), AnimatedSpritesheetPlayer)
self._imageLabel = assert(imageLabel)
if spritesheet then
self:SetSheet(spritesheet)
end
return self
end
function AnimatedSpritesheetPlayer:SetSheet(spritesheet)
assert(spritesheet)
self._spritesheet = spritesheet
self:_play()
end
function AnimatedSpritesheetPlayer:_play()
local maid = Maid.new()
local fps = self._spritesheet:GetFramesPerSecond()
local frames = self._spritesheet:GetFrames()
maid:GiveTask(RunService.RenderStepped:Connect(function()
local frame = (math.floor(tick()*fps)%frames)+1
self._spritesheet:GetSprite(frame):Style(self._imageLabel)
end))
self._maid._play = maid
end
return AnimatedSpritesheetPlayer |
function GM:CanPlayerSuicide(ply)
return not RPGM.Config.DisableSuicide
end |
describe("empty parsing", function()
setup(function()
TOML = require "toml"
end)
it("empty", function()
local obj = TOML.parse""
local sol = {}
assert.same(sol, obj)
end)
end)
|
--------------------------------------------------------------------------------
-- Module declaration
--
local mod, CL = BigWigs:NewBoss("Yor", 557, 536)
if not mod then return end
mod:RegisterEnableMob(22927)
-- mod.engageId = 250 --no boss frames
-- mod.respawnTime = 0 -- no idea
--------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
36405, -- Stomp
38361, -- Double Breath
}
end
function mod:OnBossEnable()
self:Log("SPELL_CAST_SUCCESS", "Stomp", 36405)
self:Log("SPELL_CAST_START", "DoubleBreath", 38361)
self:Death("Win", 22927)
end
--------------------------------------------------------------------------------
-- Event Handlers
--
function mod:Stomp(args)
self:Message(args.spellId, "red", "Info")
end
function mod:DoubleBreath(args)
self:Message(args.spellId, "yellow", "Long")
end
|
-----------------------------------
-- Area: Lower Jeuno
-- NPC: Muckvix
-- Involved in Mission: Magicite
-- !pos -26.824 3.601 -137.082 245
-----------------------------------
require("scripts/globals/keyitems")
local ID = require("scripts/zones/Lower_Jeuno/IDs")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
if player:hasKeyItem(tpz.ki.SILVER_BELL) and not player:hasKeyItem(tpz.ki.YAGUDO_TORCH) then
if player:getCharVar("YagudoTorchCS") == 1 then
player:startEvent(184)
else
player:startEvent(80)
end
else
player:startEvent(15)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 184 then
player:addKeyItem(tpz.ki.YAGUDO_TORCH)
player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.YAGUDO_TORCH)
player:setCharVar("YagudoTorchCS",0)
player:setCharVar("FickblixCS",1)
end
end
|
return {
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68471
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68481,
delay = 0.5
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68472
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68482,
delay = 0.5
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68473
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68483,
delay = 0.5
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68474
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68484,
delay = 0.5
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68475
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68485,
delay = 0.5
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68476
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68486,
delay = 0.5
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68477
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68487,
delay = 0.5
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68478
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68488,
delay = 0.5
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68479
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68489,
delay = 0.5
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68480
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 68490,
delay = 0.5
}
}
}
},
uiEffect = "",
name = "最适化武装-增强弹幕",
cd = 0,
painting = 1,
id = 12152,
picture = "1",
castCV = "skill",
desc = "",
aniEffect = {
effect = "jineng",
offset = {
0,
-2,
0
}
},
effect_list = {}
}
|
local Fluid = require("lib.fluid")
local Lit = Fluid.component(function(e, direction)
e.direction = direction
end)
return Lit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.