content
stringlengths 5
1.05M
|
---|
-----------------------------------
-- Area: Bhaflau Thickets
-- Mob: Sea Puk
-- Note: Place holder Nis Puk
-----------------------------------
local ID = require("scripts/zones/Bhaflau_Thickets/IDs")
require("scripts/globals/mobs")
function onMobDeath(mob, player, isKiller)
end
function onMobDespawn(mob)
tpz.mob.phOnDespawn(mob, ID.mob.NIS_PUK_PH, 5, 43200) -- 12 hours
end
|
-- LoadModule is by default included in 5.3, If people use 5.1 load 5.3's version manualy.
if not LoadModule then
function LoadModule(ModuleName,...)
local Path = THEME:GetCurrentThemeDirectory().."Modules/"..ModuleName
if THEME.get_theme_fallback_list then -- pre-5.1 support.
for _,theme in pairs(THEME:get_theme_fallback_list()) do
if not FILEMAN:DoesFileExist(Path) then
Path = "Appearance/Themes/"..theme.."/Modules/"..ModuleName
end
end
end
if not FILEMAN:DoesFileExist(Path) then
Path = "Appearance/Themes/_fallback/Modules/"..ModuleName
end
if ... then
return loadfile(Path)(...)
end
return loadfile(Path)()
end
end
-- We hate using globals, So use 1 global table.
TF_WHEEL = {}
TF_WHEEL.StyleDB = {
["dance_single"] = "single", ["dance_double"] = "double", ["dance_couple"] = "couple", ["dance_solo"] = "solo", ["dance_threepanel"] = "threepanel", ["dance_routine"] = "routine",
["pump_single"] = "single", ["pump_halfdouble"] = "halfdouble", ["pump_double"] = "double", ["pump_couple"] = "couple", ["pump_routine"] = "routine",
["ez2_single"] = "single", ["ez2_double"] = "double", ["ez2-real"] = "real",
["para_single"] = "single", ["para_double"] = "double", ["para_eight"] = "single-eight",
["ds3ddx_single"] = "single",
["bm_single5"] = "single5", ["bm_double5"] = "double5", ["bm_single7"] = "single7", ["bm_double7"] = "double7",
["maniax_single"] = "single", ["maniax_double"] = "double",
["techno_single4"] = "single4", ["techno_single5"] = "single5", ["techno_single8"] = "single8", ["techno_single9"] = "single9", ["techno_double4"] = "double4", ["techno_double5"] = "double5", ["techno_double8"] = "double8", ["techno_double9"] = "double9",
["pnm_three"] = "popn-three", ["pnm_four"] = "pnm-four", ["pnm_five"] = "popn-five", ["pnm_seven"] = "popn-seven", ["pnm_nine"] = "popn-nine",
["gddm_new"] = "gddm-new", ["gddm_old"] = "gddm-old",
["guitar_five"] = "guitar-five", ["bass_six"] = "bass-six", ["guitar_six"] = "guitar-six", ["guitar_three"] = "guitar-three", ["bass_four"] = "bass-four",
["gh_solo"] = "solo", ["gh_solo6"] = "solo6", ["gh_bass"] = "bass", ["gh_bass6"] = "bass6", ["gh_rhythm"] = "rhythm", ["gh_rhythm6"] = "rhythm6",
["kb1_single"] = "single1", ["kb2_single"] = "single2", ["kb3_single"] = "single3", ["kb4_single"] = "single4", ["kb5_single"] = "single5", ["kb6_single"] = "single6", ["kb7_single"] = "single7", ["kb8_single"] = "single8", ["kb9_single"] = "single9", ["kb10_single"] = "single10", ["kb11_single"] = "single11", ["kb12_single"] = "single12", ["kb13_single"] = "single13", ["kb14_single"] = "single14", ["kb15_single"] = "single15",
["taiko"] = "taiko-single",
["lights_cabinet"] = "cabinet",
["kickbox_human"] = "human", ["kickbox_quadarm"] = "quadarm", ["kickbox_insect"] = "insect", ["kickbox_arachnid"] = "arachnid"
}
TF_WHEEL.MPath = THEME:GetCurrentThemeDirectory().."Modules/"
function Actor:ForParent(Amount)
local CurSelf = self
for i = 1,Amount do
CurSelf = CurSelf:GetParent()
end
return CurSelf
end
-- Change Difficulties to numbers.
TF_WHEEL.DiffTab = {
["Difficulty_Beginner"] = 1,
["Difficulty_Easy"] = 2,
["Difficulty_Medium"] = 3,
["Difficulty_Hard"] = 4,
["Difficulty_Challenge"] = 5,
["Difficulty_Edit"] = 6
}
-- Resize function, We use this to resize images to size while keeping aspect ratio.
function TF_WHEEL.Resize(width,height,setwidth,sethight)
if height >= sethight and width >= setwidth then
if height*(setwidth/sethight) >= width then
return sethight/height
else
return setwidth/width
end
elseif height >= sethight then
return sethight/height
elseif width >= setwidth then
return setwidth/width
else
return 1
end
end
-- TO WRITE DOC.
function TF_WHEEL.CountingNumbers(self,NumStart,NumEnd,Duration,format)
self:stoptweening()
TF_WHEEL.Cur = 1
TF_WHEEL.Count = {}
if format == nil then format = "%.0f" end
local Length = (NumEnd - NumStart)/10
if string.format("%.0f",Length) == "0" then Length = 1 end
if string.format("%.0f",Length) == "-0" then Length = -1 end
if not self:GetCommand("Count") then
self:addcommand("Count",function(self)
self:settext(TF_WHEEL.Count[TF_WHEEL.Cur])
TF_WHEEL.Cur = TF_WHEEL.Cur + 1
end)
end
for n = NumStart,NumEnd,string.format("%.0f",Length) do
TF_WHEEL.Count[#TF_WHEEL.Count+1] = string.format(format,n)
self:sleep(Duration/10):queuecommand("Count")
end
TF_WHEEL.Count[#TF_WHEEL.Count+1] = string.format(format,NumEnd)
self:sleep(Duration/10):queuecommand("Count")
end
-- Main Input Function.
-- We use this so we can do ButtonCommand.
-- Example: MenuLeftCommand=function(self) end.
function TF_WHEEL.Input(self)
return function(event)
if not event.PlayerNumber then return end
self.pn = event.PlayerNumber
if ToEnumShortString(event.type) == "FirstPress" or ToEnumShortString(event.type) == "Repeat" then
self:queuecommand(event.GameButton)
end
if ToEnumShortString(event.type) == "Release" then
self:queuecommand(event.GameButton.."Release")
end
end
end
|
--***********************************************************
--** ROBERT JOHNSON **
--***********************************************************
---@class ISSafehousesList : ISPanel
ISSafehousesList = ISPanel:derive("ISSafehousesList");
ISSafehousesList.messages = {};
local FONT_HGT_SMALL = getTextManager():getFontHeight(UIFont.Small)
local FONT_HGT_MEDIUM = getTextManager():getFontHeight(UIFont.Medium)
--************************************************************************--
--** ISSafehousesList:initialise
--**
--************************************************************************--
function ISSafehousesList:initialise()
ISPanel.initialise(self);
local btnWid = 100
local btnHgt = math.max(25, FONT_HGT_SMALL + 3 * 2)
local padBottom = 10
self.no = ISButton:new(10, self:getHeight() - padBottom - btnHgt, btnWid, btnHgt, getText("IGUI_CraftUI_Close"), self, ISSafehousesList.onClick);
self.no.internal = "CANCEL";
self.no.anchorTop = false
self.no.anchorBottom = true
self.no:initialise();
self.no:instantiate();
self.no.borderColor = {r=1, g=1, b=1, a=0.1};
self:addChild(self.no);
local listY = 20 + FONT_HGT_MEDIUM + 20
self.datas = ISScrollingListBox:new(10, listY, self.width - 20, self.height - padBottom - btnHgt - padBottom - listY);
self.datas:initialise();
self.datas:instantiate();
self.datas.itemheight = FONT_HGT_SMALL + 2 * 2;
self.datas.selected = 0;
self.datas.joypadParent = self;
self.datas.font = UIFont.NewSmall;
self.datas.doDrawItem = self.drawDatas;
self.datas.drawBorder = true;
self:addChild(self.datas);
self.teleportBtn = ISButton:new(self:getWidth() - btnWid - 10, self:getHeight() - padBottom - btnHgt, btnWid, btnHgt, getText("IGUI_PlayerStats_Teleport"), self, ISSafehousesList.onClick);
self.teleportBtn.internal = "TELEPORT";
self.teleportBtn.anchorTop = false
self.teleportBtn.anchorBottom = true
self.teleportBtn:initialise();
self.teleportBtn:instantiate();
self.teleportBtn.borderColor = {r=1, g=1, b=1, a=0.1};
self:addChild(self.teleportBtn);
self.teleportBtn.enable = false;
self.viewBtn = ISButton:new(self.teleportBtn.x - self.teleportBtn.width - 10, self:getHeight() - padBottom - btnHgt, btnWid, btnHgt, getText("IGUI_PlayerStats_View"), self, ISSafehousesList.onClick);
self.viewBtn.internal = "VIEW";
self.viewBtn.anchorTop = false
self.viewBtn.anchorBottom = true
self.viewBtn:initialise();
self.viewBtn:instantiate();
self.viewBtn.borderColor = {r=1, g=1, b=1, a=0.1};
self:addChild(self.viewBtn);
self.viewBtn.enable = false;
self:populateList();
end
function ISSafehousesList:populateList()
self.datas:clear();
for i=0,SafeHouse.getSafehouseList():size()-1 do
local safe = SafeHouse.getSafehouseList():get(i);
self.datas:addItem(safe:getTitle(), safe);
end
end
function ISSafehousesList:drawDatas(y, item, alt)
local a = 0.9;
-- self.parent.selectedSafehouse = nil;
self:drawRectBorder(0, (y), self:getWidth(), self.itemheight - 1, a, self.borderColor.r, self.borderColor.g, self.borderColor.b);
if self.selected == item.index then
self:drawRect(0, (y), self:getWidth(), self.itemheight - 1, 0.3, 0.7, 0.35, 0.15);
self.parent.teleportBtn.enable = true;
self.parent.viewBtn.enable = true;
self.parent.selectedSafehouse = item.item;
end
self:drawText(item.item:getTitle() .. " - " .. getText("IGUI_FactionUI_FactionsListPlayers", item.item:getPlayers():size() + 1, item.item:getOwner()), 10, y + 2, 1, 1, 1, a, self.font);
return y + self.itemheight;
end
function ISSafehousesList:prerender()
local z = 20;
local splitPoint = 100;
local x = 10;
self:drawRect(0, 0, self.width, self.height, self.backgroundColor.a, self.backgroundColor.r, self.backgroundColor.g, self.backgroundColor.b);
self:drawRectBorder(0, 0, self.width, self.height, self.borderColor.a, self.borderColor.r, self.borderColor.g, self.borderColor.b);
self:drawText(getText("IGUI_AdminPanel_SeeSafehouses"), self.width/2 - (getTextManager():MeasureStringX(UIFont.Medium, getText("IGUI_AdminPanel_SeeSafehouses")) / 2), z, 1,1,1,1, UIFont.Medium);
z = z + 30;
end
function ISSafehousesList:onClick(button)
if button.internal == "CANCEL" then
self:close()
end
if button.internal == "TELEPORT" then
self.player:setX(self.selectedSafehouse:getX());
self.player:setY(self.selectedSafehouse:getY());
self.player:setZ(0);
self.player:setLx(self.selectedSafehouse:getX());
self.player:setLy(self.selectedSafehouse:getY());
self.player:setLz(0);
end
if button.internal == "VIEW" then
local safehouseUI = ISSafehouseUI:new(getCore():getScreenWidth() / 2 - 250,getCore():getScreenHeight() / 2 - 225, 500, 450, self.selectedSafehouse, self.player);
safehouseUI:initialise()
safehouseUI:addToUIManager()
end
end
function ISSafehousesList:close()
self:setVisible(false)
self:removeFromUIManager()
ISSafehousesList.instance = nil
end
--************************************************************************--
--** ISSafehousesList:new
--**
--************************************************************************--
function ISSafehousesList:new(x, y, width, height, player)
local o = {}
x = getCore():getScreenWidth() / 2 - (width / 2);
y = getCore():getScreenHeight() / 2 - (height / 2);
o = ISPanel:new(x, y, width, height);
setmetatable(o, self)
self.__index = self
o.borderColor = {r=0.4, g=0.4, b=0.4, a=1};
o.backgroundColor = {r=0, g=0, b=0, a=0.8};
o.width = width;
o.height = height;
o.player = player;
o.selectedFaction = nil;
o.moveWithMouse = true;
ISSafehousesList.instance = o;
return o;
end
function ISSafehousesList.OnSafehousesChanged()
if ISSafehousesList.instance then
ISSafehousesList.instance:populateList()
end
end
Events.OnSafehousesChanged.Add(ISSafehousesList.OnSafehousesChanged)
|
object_tangible_loot_mustafar_cube_loot_cube_loot_1w = object_tangible_loot_mustafar_cube_loot_shared_cube_loot_1w:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_mustafar_cube_loot_cube_loot_1w, "object/tangible/loot/mustafar/cube/loot/cube_loot_1w.iff")
|
local IdGenerator = {}
local id = 0
function IdGenerator:getId()
id = id + 1
return id
end
return IdGenerator
|
local Sink
Sink = require("debugkit.log").Sink
local safeOpen, getSize
do
local _obj_0 = require("filekit")
safeOpen, getSize = _obj_0.safeOpen, _obj_0.getSize
end
local levels
levels = function(t)
local _tbl_0 = { }
for i, v in ipairs(t) do
_tbl_0[v] = i
end
return _tbl_0
end
local inverse = levels
local _cache_contains = { }
local contains
contains = function(e, t)
if not (_cache_contains[t]) then
_cache_contains[t] = inverse(t)
end
return _cache_contains[t][e] and true or false
end
local sink = { }
local encode
do
local ok, json = pcall(function()
return require("cjson")
end)
if ok then
encode = json.encode
end
ok, json = pcall(function()
return require("dkjson")
end)
if ok then
encode = json.encode
end
ok, json = pcall(function()
return require("json")
end)
if ok then
encode = json.encode
else
local _
_ = function()
return 404
end
end
end
sink.json = function()
return Sink({
write = function(self, L, tag, level, msg)
local data = {
name = L.name,
level = L.level,
time = L.time(),
date = L.date(),
exclude = L.exclude,
flag = self.flag
}
msg = encode({
message = msg,
level = level,
data = data,
tag = tag
})
if (msg == 404) or (msg == nil) then
return
end
if (L.levels[level] >= L.levels[L.level]) and (not contains(tag, L.exclude)) then
return io.write(msg)
end
end
})
end
sink.rollingFile = function(file, size)
if size == nil then
size = 1000000
end
return Sink({
open = function(self, f)
if f == nil then
f = file
end
self.flag.current = f
if not (self.flag.opened) then
local fh = safeOpen(f, "a")
if fh.error then
error("sink.rollingFile $ could not open file " .. tostring(f) .. "!")
end
self.fh, self.flag.opened = fh, true
end
if not (self.flag.initialized) then
self.flag.size = self.flag.size or size
self.flag.filename = self.flag.filename or file
self.flag.count = self.flag.count or 0
self.flag.initialized = true
end
end,
write = function(self, L, tag, level, msg)
if self.flag.opened then
if ((getSize(self.flag.current)) + #msg) < self.flag.size then
if (L.levels[level] >= L.levels[L.level]) and (not contains(tag, L.exclude)) then
return self.fh:write(msg)
end
else
self:close()
self.flag.count = self.flag.count + 1
self:open(tostring(self.flag.filename) .. "." .. tostring(self.flag.count))
return self:write(L, level, msg)
end
else
return error("sink.file $ sink is not open!")
end
end,
close = function(self)
if self.flag.opened then
self.fh:close()
self.flag.opened = false
end
end
})
end
return sink
|
local __Scripts = LibStub:GetLibrary("ovale/Scripts")
local OvaleScripts = __Scripts.OvaleScripts
do
local name = "icyveins_monk_brewmaster"
local desc = "[7.3.2] Icy-Veins: Monk Brewmaster"
local code = [[
Include(ovale_common)
Include(ovale_trinkets_mop)
Include(ovale_trinkets_wod)
Include(ovale_monk_spells)
AddCheckBox(opt_interrupt L(interrupt) default specialization=brewmaster)
AddCheckBox(opt_melee_range L(not_in_melee_range) specialization=brewmaster)
AddCheckBox(opt_monk_bm_aoe L(AOE) default specialization=brewmaster)
AddCheckBox(opt_use_consumables L(opt_use_consumables) default specialization=brewmaster)
AddFunction BrewmasterHealMe
{
unless(DebuffPresent(healing_immunity_debuff))
{
if (HealthPercent() < 35)
{
Spell(healing_elixir)
Spell(expel_harm)
}
if (HealthPercent() <= 100 - (15 * 2.6)) Spell(healing_elixir)
if (HealthPercent() < 35) UseHealthPotions()
}
}
AddFunction StaggerPercentage
{
StaggerRemaining() / MaxHealth() * 100
}
AddFunction BrewmasterRangeCheck
{
if CheckBoxOn(opt_melee_range) and not target.InRange(tiger_palm) Texture(misc_arrowlup help=L(not_in_melee_range))
}
AddFunction BrewMasterIronskinMin
{
if(DebuffRemaining(any_stagger_debuff) > BaseDuration(ironskin_brew_buff)) BaseDuration(ironskin_brew_buff)
DebuffRemaining(any_stagger_debuff)
}
AddFunction BrewmasterDefaultShortCDActions
{
# keep ISB up always when taking dmg
if BuffRemaining(ironskin_brew_buff) < BrewMasterIronskinMin() Spell(ironskin_brew text=min)
# keep stagger below 100% (or 30% when BOB is up)
if (StaggerPercentage() >= 100 or (StaggerPercentage() >= 30 and Talent(black_ox_brew_talent) and SpellCooldown(black_ox_brew) <= 0)) Spell(purifying_brew)
# use black_ox_brew when at 0 charges and low energy (or in an emergency)
if ((SpellCharges(purifying_brew) == 0) and (Energy() < 40 or StaggerPercentage() >= 60 or BuffRemaining(ironskin_brew_buff) < BrewMasterIronskinMin())) Spell(black_ox_brew)
# heal mean
BrewmasterHealMe()
# range check
BrewmasterRangeCheck()
unless StaggerPercentage() > 100 or BrewmasterHealMe()
{
# purify heavy stagger when we have enough ISB
if (StaggerPercentage() >= 60 and (BuffRemaining(ironskin_brew_buff) >= 2*BaseDuration(ironskin_brew_buff))) Spell(purifying_brew)
# always bank 1 charge (or bank 2 with light_brewing)
unless (SpellCharges(ironskin_brew count=0) <= SpellData(ironskin_brew charges)-2)
{
# never be at (almost) max charges
unless (SpellFullRecharge(ironskin_brew) > 3)
{
if (BuffRemaining(ironskin_brew_buff) < 2*BaseDuration(ironskin_brew_buff)) Spell(ironskin_brew text=max)
if (StaggerPercentage() > 30 or Talent(special_delivery_talent)) Spell(purifying_brew text=max)
}
# keep brew-stache rolling
if (IncomingDamage(4 physical=1)>0 and HasArtifactTrait(brew_stache_trait) and BuffExpires(brew_stache_buff))
{
if (BuffRemaining(ironskin_brew_buff) < 2*BaseDuration(ironskin_brew_buff)) Spell(ironskin_brew text=stache)
if (StaggerPercentage() > 30) Spell(purifying_brew text=stache)
}
# purify stagger when talent elusive dance
if (Talent(elusive_dance_talent) and BuffExpires(elusive_dance_buff)) Spell(purifying_brew)
}
}
}
#
# Single-Target
#
AddFunction BrewmasterDefaultMainActions
{
if Talent(blackout_combo_talent) BrewmasterBlackoutComboMainActions()
unless Talent(blackout_combo_talent)
{
Spell(keg_smash)
Spell(blackout_strike)
if (target.DebuffPresent(keg_smash_debuff)) Spell(breath_of_fire)
if (BuffRefreshable(rushing_jade_wind_buff)) Spell(rushing_jade_wind)
if (EnergyDeficit() <= 35 or (Talent(black_ox_talent) and SpellCooldown(black_ox_brew) <= 0)) Spell(tiger_palm)
Spell(chi_burst)
Spell(chi_wave)
Spell(exploding_keg)
}
}
AddFunction BrewmasterBlackoutComboMainActions
{
if(not BuffPresent(blackout_combo_buff) or SpellCharges(ironskin_brew) == 0) Spell(keg_smash)
if(not BuffPresent(blackout_combo_buff)) Spell(blackout_strike)
if(BuffPresent(blackout_combo_buff)) Spell(tiger_palm)
unless BuffPresent(blackout_combo_buff)
{
if target.DebuffPresent(keg_smash_debuff) Spell(breath_of_fire)
if BuffRefreshable(rushing_jade_wind_buff) Spell(rushing_jade_wind)
Spell(chi_burst)
Spell(chi_wave)
Spell(exploding_keg)
}
}
#
# AOE
#
AddFunction BrewmasterDefaultAoEActions
{
if(Talent(blackout_combo_talent) and not BuffPresent(blackout_combo_buff)) Spell(blackout_strike)
Spell(exploding_keg)
Spell(keg_smash)
Spell(chi_burst)
Spell(chi_wave)
if (target.DebuffPresent(keg_smash_debuff) and (not HasEquippedItem(salsalabims_lost_tunic) or not BuffPresent(blackout_combo_buff))) Spell(breath_of_fire)
if (BuffRefreshable(rushing_jade_wind_buff)) Spell(rushing_jade_wind)
if (EnergyDeficit() <= 35 or (Talent(black_ox_talent) and SpellCooldown(black_ox_brew) <= 0)) Spell(tiger_palm)
if (not BuffPresent(blackout_combo_buff)) Spell(blackout_strike)
}
AddFunction BrewmasterBlackoutComboAoEActions
{
if(not BuffPresent(blackout_combo_buff)) Spell(blackout_strike)
if(BuffPresent(blackout_combo_buff))
{
Spell(keg_smash)
Spell(breath_of_fire)
Spell(tiger_palm)
}
unless (BuffPresent(blackout_combo_buff))
{
Spell(exploding_keg)
Spell(rushing_jade_wind)
Spell(chi_burst)
Spell(chi_wave)
if EnergyDeficit() <= 35 Spell(tiger_palm)
}
}
AddFunction BrewmasterDefaultCdActions
{
BrewmasterInterruptActions()
if not PetPresent(name=Niuzao) Spell(invoke_niuzao)
if (HasEquippedItem(firestone_walkers)) Spell(fortifying_brew)
if (HasEquippedItem(shifting_cosmic_sliver)) Spell(fortifying_brew)
if (HasEquippedItem(fundamental_observation)) Spell(zen_meditation text=FO)
Item(Trinket0Slot usable=1 text=13)
Item(Trinket1Slot usable=1 text=14)
Spell(fortifying_brew)
Spell(dampen_harm)
if CheckBoxOn(opt_use_consumables) Item(unbending_potion usable=1)
Spell(zen_meditation)
UseRacialSurvivalActions()
}
AddFunction BrewmasterInterruptActions
{
if CheckBoxOn(opt_interrupt) and not target.IsFriend() and target.Casting()
{
if target.InRange(spear_hand_strike) and target.IsInterruptible() Spell(spear_hand_strike)
if target.Distance(less 5) and not target.Classification(worldboss) Spell(leg_sweep)
if target.Distance(less 8) and target.IsInterruptible() Spell(arcane_torrent_chi)
if target.InRange(quaking_palm) and not target.Classification(worldboss) Spell(quaking_palm)
if target.Distance(less 5) and not target.Classification(worldboss) Spell(war_stomp)
if target.InRange(paralysis) and not target.Classification(worldboss) Spell(paralysis)
}
}
AddIcon help=shortcd specialization=brewmaster
{
BrewmasterDefaultShortCDActions()
}
AddIcon enemies=1 help=main specialization=brewmaster
{
BrewmasterDefaultMainActions()
}
AddIcon checkbox=opt_monk_bm_aoe help=aoe specialization=brewmaster
{
BrewmasterDefaultAoEActions()
}
AddIcon help=cd specialization=brewmaster
{
BrewmasterDefaultCdActions()
}
]]
OvaleScripts:RegisterScript("MONK", "brewmaster", name, desc, code, "script")
end
do
local name = "sc_monk_windwalker_t19"
local desc = "[7.0] Simulationcraft: Monk_Windwalker_T19"
local code = [[
# Based on SimulationCraft profile "Monk_Windwalker_T19P".
# class=monk
# spec=windwalker
# talents=3010032
Include(ovale_common)
Include(ovale_trinkets_mop)
Include(ovale_trinkets_wod)
Include(ovale_monk_spells)
AddCheckBox(opt_interrupt L(interrupt) default specialization=windwalker)
AddCheckBox(opt_melee_range L(not_in_melee_range) specialization=windwalker)
AddCheckBox(opt_use_consumables L(opt_use_consumables) default specialization=windwalker)
AddCheckBox(opt_touch_of_death_on_elite_only L(touch_of_death_on_elite_only) default specialization=windwalker)
AddCheckBox(opt_touch_of_karma SpellName(touch_of_karma) specialization=windwalker)
AddCheckBox(opt_chi_burst SpellName(chi_burst) default specialization=windwalker)
AddCheckBox(opt_storm_earth_and_fire SpellName(storm_earth_and_fire) specialization=windwalker)
AddFunction WindwalkerInterruptActions
{
if CheckBoxOn(opt_interrupt) and not target.IsFriend() and target.Casting()
{
if target.InRange(paralysis) and not target.Classification(worldboss) Spell(paralysis)
if target.Distance(less 5) and not target.Classification(worldboss) Spell(war_stomp)
if target.InRange(quaking_palm) and not target.Classification(worldboss) Spell(quaking_palm)
if target.Distance(less 8) and target.IsInterruptible() Spell(arcane_torrent_chi)
if target.Distance(less 5) and not target.Classification(worldboss) Spell(leg_sweep)
if target.InRange(spear_hand_strike) and target.IsInterruptible() Spell(spear_hand_strike)
}
}
AddFunction WindwalkerGetInMeleeRange
{
if CheckBoxOn(opt_melee_range) and not target.InRange(tiger_palm) Texture(misc_arrowlup help=L(not_in_melee_range))
}
### actions.st
AddFunction WindwalkerStMainActions
{
#call_action_list,name=cd
WindwalkerCdMainActions()
unless WindwalkerCdMainPostConditions()
{
#tiger_palm,cycle_targets=1,if=!prev_gcd.1.tiger_palm&energy.time_to_max<=0.5&chi.max-chi>=2
if not PreviousGCDSpell(tiger_palm) and TimeToMaxEnergy() <= 0 and MaxChi() - Chi() >= 2 Spell(tiger_palm)
#strike_of_the_windlord,if=!talent.serenity.enabled|cooldown.serenity.remains>=10
if not Talent(serenity_talent) or SpellCooldown(serenity) >= 10 Spell(strike_of_the_windlord)
#rising_sun_kick,cycle_targets=1,if=((chi>=3&energy>=40)|chi>=5)&(!talent.serenity.enabled|cooldown.serenity.remains>=6)
if { Chi() >= 3 and Energy() >= 40 or Chi() >= 5 } and { not Talent(serenity_talent) or SpellCooldown(serenity) >= 6 } Spell(rising_sun_kick)
#fists_of_fury,if=talent.serenity.enabled&!equipped.drinking_horn_cover&cooldown.serenity.remains>=5&energy.time_to_max>2
if Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and SpellCooldown(serenity) >= 5 and TimeToMaxEnergy() > 2 Spell(fists_of_fury)
#fists_of_fury,if=talent.serenity.enabled&equipped.drinking_horn_cover&(cooldown.serenity.remains>=15|cooldown.serenity.remains<=4)&energy.time_to_max>2
if Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(serenity) >= 15 or SpellCooldown(serenity) <= 4 } and TimeToMaxEnergy() > 2 Spell(fists_of_fury)
#fists_of_fury,if=!talent.serenity.enabled&energy.time_to_max>2
if not Talent(serenity_talent) and TimeToMaxEnergy() > 2 Spell(fists_of_fury)
#rising_sun_kick,cycle_targets=1,if=!talent.serenity.enabled|cooldown.serenity.remains>=5
if not Talent(serenity_talent) or SpellCooldown(serenity) >= 5 Spell(rising_sun_kick)
#whirling_dragon_punch
if SpellCooldown(fists_of_fury) > 0 and SpellCooldown(rising_sun_kick) > 0 Spell(whirling_dragon_punch)
#blackout_kick,cycle_targets=1,if=!prev_gcd.1.blackout_kick&chi.max-chi>=1&set_bonus.tier21_4pc&(!set_bonus.tier19_2pc|talent.serenity.enabled|buff.bok_proc.up)
if not PreviousGCDSpell(blackout_kick) and MaxChi() - Chi() >= 1 and ArmorSetBonus(T21 4) and { not ArmorSetBonus(T19 2) or Talent(serenity_talent) or BuffPresent(bok_proc_buff) } Spell(blackout_kick)
#spinning_crane_kick,if=(active_enemies>=3|(buff.bok_proc.up&chi.max-chi>=0))&!prev_gcd.1.spinning_crane_kick&set_bonus.tier21_4pc
if { Enemies() >= 3 or BuffPresent(bok_proc_buff) and MaxChi() - Chi() >= 0 } and not PreviousGCDSpell(spinning_crane_kick) and ArmorSetBonus(T21 4) Spell(spinning_crane_kick)
#crackling_jade_lightning,if=equipped.the_emperors_capacitor&buff.the_emperors_capacitor.stack>=19&energy.time_to_max>3
if HasEquippedItem(the_emperors_capacitor) and BuffStacks(the_emperors_capacitor_buff) >= 19 and TimeToMaxEnergy() > 3 Spell(crackling_jade_lightning)
#crackling_jade_lightning,if=equipped.the_emperors_capacitor&buff.the_emperors_capacitor.stack>=14&cooldown.serenity.remains<13&talent.serenity.enabled&energy.time_to_max>3
if HasEquippedItem(the_emperors_capacitor) and BuffStacks(the_emperors_capacitor_buff) >= 14 and SpellCooldown(serenity) < 13 and Talent(serenity_talent) and TimeToMaxEnergy() > 3 Spell(crackling_jade_lightning)
#spinning_crane_kick,if=active_enemies>=3&!prev_gcd.1.spinning_crane_kick
if Enemies() >= 3 and not PreviousGCDSpell(spinning_crane_kick) Spell(spinning_crane_kick)
#rushing_jade_wind,if=chi.max-chi>1&!prev_gcd.1.rushing_jade_wind
if MaxChi() - Chi() > 1 and not PreviousGCDSpell(rushing_jade_wind) Spell(rushing_jade_wind)
#blackout_kick,cycle_targets=1,if=(chi>1|buff.bok_proc.up|(talent.energizing_elixir.enabled&cooldown.energizing_elixir.remains<cooldown.fists_of_fury.remains))&((cooldown.rising_sun_kick.remains>1&(!artifact.strike_of_the_windlord.enabled|cooldown.strike_of_the_windlord.remains>1)|chi>2)&(cooldown.fists_of_fury.remains>1|chi>3)|prev_gcd.1.tiger_palm)&!prev_gcd.1.blackout_kick
if { Chi() > 1 or BuffPresent(bok_proc_buff) or Talent(energizing_elixir_talent) and SpellCooldown(energizing_elixir) < SpellCooldown(fists_of_fury) } and { { SpellCooldown(rising_sun_kick) > 1 and { not HasArtifactTrait(strike_of_the_windlord) or SpellCooldown(strike_of_the_windlord) > 1 } or Chi() > 2 } and { SpellCooldown(fists_of_fury) > 1 or Chi() > 3 } or PreviousGCDSpell(tiger_palm) } and not PreviousGCDSpell(blackout_kick) Spell(blackout_kick)
#chi_wave,if=energy.time_to_max>1
if TimeToMaxEnergy() > 1 Spell(chi_wave)
#chi_burst,if=energy.time_to_max>1
if TimeToMaxEnergy() > 1 and CheckBoxOn(opt_chi_burst) Spell(chi_burst)
#tiger_palm,cycle_targets=1,if=!prev_gcd.1.tiger_palm&(chi.max-chi>=2|energy.time_to_max<1)
if not PreviousGCDSpell(tiger_palm) and { MaxChi() - Chi() >= 2 or TimeToMaxEnergy() < 1 } Spell(tiger_palm)
#chi_wave
Spell(chi_wave)
#chi_burst
if CheckBoxOn(opt_chi_burst) Spell(chi_burst)
}
}
AddFunction WindwalkerStMainPostConditions
{
WindwalkerCdMainPostConditions()
}
AddFunction WindwalkerStShortCdActions
{
#call_action_list,name=cd
WindwalkerCdShortCdActions()
unless WindwalkerCdShortCdPostConditions()
{
#energizing_elixir,if=chi<=1&(cooldown.rising_sun_kick.remains=0|(artifact.strike_of_the_windlord.enabled&cooldown.strike_of_the_windlord.remains=0)|energy<50)
if Chi() <= 1 and { not SpellCooldown(rising_sun_kick) > 0 or HasArtifactTrait(strike_of_the_windlord) and not SpellCooldown(strike_of_the_windlord) > 0 or Energy() < 50 } Spell(energizing_elixir)
}
}
AddFunction WindwalkerStShortCdPostConditions
{
WindwalkerCdShortCdPostConditions() or not PreviousGCDSpell(tiger_palm) and TimeToMaxEnergy() <= 0 and MaxChi() - Chi() >= 2 and Spell(tiger_palm) or { not Talent(serenity_talent) or SpellCooldown(serenity) >= 10 } and Spell(strike_of_the_windlord) or { Chi() >= 3 and Energy() >= 40 or Chi() >= 5 } and { not Talent(serenity_talent) or SpellCooldown(serenity) >= 6 } and Spell(rising_sun_kick) or Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and SpellCooldown(serenity) >= 5 and TimeToMaxEnergy() > 2 and Spell(fists_of_fury) or Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(serenity) >= 15 or SpellCooldown(serenity) <= 4 } and TimeToMaxEnergy() > 2 and Spell(fists_of_fury) or not Talent(serenity_talent) and TimeToMaxEnergy() > 2 and Spell(fists_of_fury) or { not Talent(serenity_talent) or SpellCooldown(serenity) >= 5 } and Spell(rising_sun_kick) or SpellCooldown(fists_of_fury) > 0 and SpellCooldown(rising_sun_kick) > 0 and Spell(whirling_dragon_punch) or not PreviousGCDSpell(blackout_kick) and MaxChi() - Chi() >= 1 and ArmorSetBonus(T21 4) and { not ArmorSetBonus(T19 2) or Talent(serenity_talent) or BuffPresent(bok_proc_buff) } and Spell(blackout_kick) or { Enemies() >= 3 or BuffPresent(bok_proc_buff) and MaxChi() - Chi() >= 0 } and not PreviousGCDSpell(spinning_crane_kick) and ArmorSetBonus(T21 4) and Spell(spinning_crane_kick) or HasEquippedItem(the_emperors_capacitor) and BuffStacks(the_emperors_capacitor_buff) >= 19 and TimeToMaxEnergy() > 3 and Spell(crackling_jade_lightning) or HasEquippedItem(the_emperors_capacitor) and BuffStacks(the_emperors_capacitor_buff) >= 14 and SpellCooldown(serenity) < 13 and Talent(serenity_talent) and TimeToMaxEnergy() > 3 and Spell(crackling_jade_lightning) or Enemies() >= 3 and not PreviousGCDSpell(spinning_crane_kick) and Spell(spinning_crane_kick) or MaxChi() - Chi() > 1 and not PreviousGCDSpell(rushing_jade_wind) and Spell(rushing_jade_wind) or { Chi() > 1 or BuffPresent(bok_proc_buff) or Talent(energizing_elixir_talent) and SpellCooldown(energizing_elixir) < SpellCooldown(fists_of_fury) } and { { SpellCooldown(rising_sun_kick) > 1 and { not HasArtifactTrait(strike_of_the_windlord) or SpellCooldown(strike_of_the_windlord) > 1 } or Chi() > 2 } and { SpellCooldown(fists_of_fury) > 1 or Chi() > 3 } or PreviousGCDSpell(tiger_palm) } and not PreviousGCDSpell(blackout_kick) and Spell(blackout_kick) or TimeToMaxEnergy() > 1 and Spell(chi_wave) or TimeToMaxEnergy() > 1 and CheckBoxOn(opt_chi_burst) and Spell(chi_burst) or not PreviousGCDSpell(tiger_palm) and { MaxChi() - Chi() >= 2 or TimeToMaxEnergy() < 1 } and Spell(tiger_palm) or Spell(chi_wave) or CheckBoxOn(opt_chi_burst) and Spell(chi_burst)
}
AddFunction WindwalkerStCdActions
{
#call_action_list,name=cd
WindwalkerCdCdActions()
unless WindwalkerCdCdPostConditions() or Chi() <= 1 and { not SpellCooldown(rising_sun_kick) > 0 or HasArtifactTrait(strike_of_the_windlord) and not SpellCooldown(strike_of_the_windlord) > 0 or Energy() < 50 } and Spell(energizing_elixir)
{
#arcane_torrent,if=chi.max-chi>=1&energy.time_to_max>=0.5
if MaxChi() - Chi() >= 1 and TimeToMaxEnergy() >= 0 Spell(arcane_torrent_chi)
}
}
AddFunction WindwalkerStCdPostConditions
{
WindwalkerCdCdPostConditions() or Chi() <= 1 and { not SpellCooldown(rising_sun_kick) > 0 or HasArtifactTrait(strike_of_the_windlord) and not SpellCooldown(strike_of_the_windlord) > 0 or Energy() < 50 } and Spell(energizing_elixir) or not PreviousGCDSpell(tiger_palm) and TimeToMaxEnergy() <= 0 and MaxChi() - Chi() >= 2 and Spell(tiger_palm) or { not Talent(serenity_talent) or SpellCooldown(serenity) >= 10 } and Spell(strike_of_the_windlord) or { Chi() >= 3 and Energy() >= 40 or Chi() >= 5 } and { not Talent(serenity_talent) or SpellCooldown(serenity) >= 6 } and Spell(rising_sun_kick) or Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and SpellCooldown(serenity) >= 5 and TimeToMaxEnergy() > 2 and Spell(fists_of_fury) or Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(serenity) >= 15 or SpellCooldown(serenity) <= 4 } and TimeToMaxEnergy() > 2 and Spell(fists_of_fury) or not Talent(serenity_talent) and TimeToMaxEnergy() > 2 and Spell(fists_of_fury) or { not Talent(serenity_talent) or SpellCooldown(serenity) >= 5 } and Spell(rising_sun_kick) or SpellCooldown(fists_of_fury) > 0 and SpellCooldown(rising_sun_kick) > 0 and Spell(whirling_dragon_punch) or not PreviousGCDSpell(blackout_kick) and MaxChi() - Chi() >= 1 and ArmorSetBonus(T21 4) and { not ArmorSetBonus(T19 2) or Talent(serenity_talent) or BuffPresent(bok_proc_buff) } and Spell(blackout_kick) or { Enemies() >= 3 or BuffPresent(bok_proc_buff) and MaxChi() - Chi() >= 0 } and not PreviousGCDSpell(spinning_crane_kick) and ArmorSetBonus(T21 4) and Spell(spinning_crane_kick) or HasEquippedItem(the_emperors_capacitor) and BuffStacks(the_emperors_capacitor_buff) >= 19 and TimeToMaxEnergy() > 3 and Spell(crackling_jade_lightning) or HasEquippedItem(the_emperors_capacitor) and BuffStacks(the_emperors_capacitor_buff) >= 14 and SpellCooldown(serenity) < 13 and Talent(serenity_talent) and TimeToMaxEnergy() > 3 and Spell(crackling_jade_lightning) or Enemies() >= 3 and not PreviousGCDSpell(spinning_crane_kick) and Spell(spinning_crane_kick) or MaxChi() - Chi() > 1 and not PreviousGCDSpell(rushing_jade_wind) and Spell(rushing_jade_wind) or { Chi() > 1 or BuffPresent(bok_proc_buff) or Talent(energizing_elixir_talent) and SpellCooldown(energizing_elixir) < SpellCooldown(fists_of_fury) } and { { SpellCooldown(rising_sun_kick) > 1 and { not HasArtifactTrait(strike_of_the_windlord) or SpellCooldown(strike_of_the_windlord) > 1 } or Chi() > 2 } and { SpellCooldown(fists_of_fury) > 1 or Chi() > 3 } or PreviousGCDSpell(tiger_palm) } and not PreviousGCDSpell(blackout_kick) and Spell(blackout_kick) or TimeToMaxEnergy() > 1 and Spell(chi_wave) or TimeToMaxEnergy() > 1 and CheckBoxOn(opt_chi_burst) and Spell(chi_burst) or not PreviousGCDSpell(tiger_palm) and { MaxChi() - Chi() >= 2 or TimeToMaxEnergy() < 1 } and Spell(tiger_palm) or Spell(chi_wave) or CheckBoxOn(opt_chi_burst) and Spell(chi_burst)
}
### actions.serenity_opener
AddFunction WindwalkerSerenityopenerMainActions
{
#tiger_palm,cycle_targets=1,if=!prev_gcd.1.tiger_palm&energy=energy.max&chi<1&!buff.serenity.up&cooldown.fists_of_fury.remains<=0
if not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) and SpellCooldown(fists_of_fury) <= 0 Spell(tiger_palm)
#call_action_list,name=cd,if=cooldown.fists_of_fury.remains>1
if SpellCooldown(fists_of_fury) > 1 WindwalkerCdMainActions()
unless SpellCooldown(fists_of_fury) > 1 and WindwalkerCdMainPostConditions()
{
#rising_sun_kick,cycle_targets=1,if=active_enemies<3&buff.serenity.up
if Enemies() < 3 and BuffPresent(serenity_buff) Spell(rising_sun_kick)
#strike_of_the_windlord,if=buff.serenity.up
if BuffPresent(serenity_buff) Spell(strike_of_the_windlord)
#blackout_kick,cycle_targets=1,if=(!prev_gcd.1.blackout_kick)&(prev_gcd.1.strike_of_the_windlord)
if not PreviousGCDSpell(blackout_kick) and PreviousGCDSpell(strike_of_the_windlord) Spell(blackout_kick)
#fists_of_fury,if=cooldown.rising_sun_kick.remains>1|buff.serenity.down,interrupt=1
if SpellCooldown(rising_sun_kick) > 1 or BuffExpires(serenity_buff) Spell(fists_of_fury)
#blackout_kick,cycle_targets=1,if=buff.serenity.down&chi<=2&cooldown.serenity.remains<=0&prev_gcd.1.tiger_palm
if BuffExpires(serenity_buff) and Chi() <= 2 and SpellCooldown(serenity) <= 0 and PreviousGCDSpell(tiger_palm) Spell(blackout_kick)
#tiger_palm,cycle_targets=1,if=chi=1
if Chi() == 1 Spell(tiger_palm)
}
}
AddFunction WindwalkerSerenityopenerMainPostConditions
{
SpellCooldown(fists_of_fury) > 1 and WindwalkerCdMainPostConditions()
}
AddFunction WindwalkerSerenityopenerShortCdActions
{
unless not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) and SpellCooldown(fists_of_fury) <= 0 and Spell(tiger_palm)
{
#call_action_list,name=cd,if=cooldown.fists_of_fury.remains>1
if SpellCooldown(fists_of_fury) > 1 WindwalkerCdShortCdActions()
unless SpellCooldown(fists_of_fury) > 1 and WindwalkerCdShortCdPostConditions()
{
#serenity,if=cooldown.fists_of_fury.remains>1
if SpellCooldown(fists_of_fury) > 1 Spell(serenity)
}
}
}
AddFunction WindwalkerSerenityopenerShortCdPostConditions
{
not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) and SpellCooldown(fists_of_fury) <= 0 and Spell(tiger_palm) or SpellCooldown(fists_of_fury) > 1 and WindwalkerCdShortCdPostConditions() or Enemies() < 3 and BuffPresent(serenity_buff) and Spell(rising_sun_kick) or BuffPresent(serenity_buff) and Spell(strike_of_the_windlord) or not PreviousGCDSpell(blackout_kick) and PreviousGCDSpell(strike_of_the_windlord) and Spell(blackout_kick) or { SpellCooldown(rising_sun_kick) > 1 or BuffExpires(serenity_buff) } and Spell(fists_of_fury) or BuffExpires(serenity_buff) and Chi() <= 2 and SpellCooldown(serenity) <= 0 and PreviousGCDSpell(tiger_palm) and Spell(blackout_kick) or Chi() == 1 and Spell(tiger_palm)
}
AddFunction WindwalkerSerenityopenerCdActions
{
unless not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) and SpellCooldown(fists_of_fury) <= 0 and Spell(tiger_palm)
{
#arcane_torrent,if=chi.max-chi>=1&energy.time_to_max>=0.5
if MaxChi() - Chi() >= 1 and TimeToMaxEnergy() >= 0 Spell(arcane_torrent_chi)
#call_action_list,name=cd,if=cooldown.fists_of_fury.remains>1
if SpellCooldown(fists_of_fury) > 1 WindwalkerCdCdActions()
}
}
AddFunction WindwalkerSerenityopenerCdPostConditions
{
not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) and SpellCooldown(fists_of_fury) <= 0 and Spell(tiger_palm) or SpellCooldown(fists_of_fury) > 1 and WindwalkerCdCdPostConditions() or SpellCooldown(fists_of_fury) > 1 and Spell(serenity) or Enemies() < 3 and BuffPresent(serenity_buff) and Spell(rising_sun_kick) or BuffPresent(serenity_buff) and Spell(strike_of_the_windlord) or not PreviousGCDSpell(blackout_kick) and PreviousGCDSpell(strike_of_the_windlord) and Spell(blackout_kick) or { SpellCooldown(rising_sun_kick) > 1 or BuffExpires(serenity_buff) } and Spell(fists_of_fury) or BuffExpires(serenity_buff) and Chi() <= 2 and SpellCooldown(serenity) <= 0 and PreviousGCDSpell(tiger_palm) and Spell(blackout_kick) or Chi() == 1 and Spell(tiger_palm)
}
### actions.serenity
AddFunction WindwalkerSerenityMainActions
{
#tiger_palm,cycle_targets=1,if=!prev_gcd.1.tiger_palm&energy=energy.max&chi<1&!buff.serenity.up
if not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) Spell(tiger_palm)
#call_action_list,name=cd
WindwalkerCdMainActions()
unless WindwalkerCdMainPostConditions()
{
#rising_sun_kick,cycle_targets=1,if=active_enemies<3
if Enemies() < 3 Spell(rising_sun_kick)
#strike_of_the_windlord
Spell(strike_of_the_windlord)
#blackout_kick,cycle_targets=1,if=(!prev_gcd.1.blackout_kick)&(prev_gcd.1.strike_of_the_windlord|prev_gcd.1.fists_of_fury)&active_enemies<2
if not PreviousGCDSpell(blackout_kick) and { PreviousGCDSpell(strike_of_the_windlord) or PreviousGCDSpell(fists_of_fury) } and Enemies() < 2 Spell(blackout_kick)
#fists_of_fury,if=((equipped.drinking_horn_cover&buff.pressure_point.remains<=2&set_bonus.tier20_4pc)&(cooldown.rising_sun_kick.remains>1|active_enemies>1)),interrupt=1
if HasEquippedItem(drinking_horn_cover) and BuffRemaining(pressure_point_buff) <= 2 and ArmorSetBonus(T20 4) and { SpellCooldown(rising_sun_kick) > 1 or Enemies() > 1 } Spell(fists_of_fury)
#fists_of_fury,if=((!equipped.drinking_horn_cover|buff.bloodlust.up|buff.serenity.remains<1)&(cooldown.rising_sun_kick.remains>1|active_enemies>1)),interrupt=1
if { not HasEquippedItem(drinking_horn_cover) or BuffPresent(burst_haste_buff any=1) or BuffRemaining(serenity_buff) < 1 } and { SpellCooldown(rising_sun_kick) > 1 or Enemies() > 1 } Spell(fists_of_fury)
#spinning_crane_kick,if=active_enemies>=3&!prev_gcd.1.spinning_crane_kick
if Enemies() >= 3 and not PreviousGCDSpell(spinning_crane_kick) Spell(spinning_crane_kick)
#rushing_jade_wind,if=!prev_gcd.1.rushing_jade_wind&buff.rushing_jade_wind.down&buff.serenity.remains>=4
if not PreviousGCDSpell(rushing_jade_wind) and BuffExpires(rushing_jade_wind_buff) and BuffRemaining(serenity_buff) >= 4 Spell(rushing_jade_wind)
#rising_sun_kick,cycle_targets=1,if=active_enemies>=3
if Enemies() >= 3 Spell(rising_sun_kick)
#rushing_jade_wind,if=!prev_gcd.1.rushing_jade_wind&buff.rushing_jade_wind.down&active_enemies>1
if not PreviousGCDSpell(rushing_jade_wind) and BuffExpires(rushing_jade_wind_buff) and Enemies() > 1 Spell(rushing_jade_wind)
#spinning_crane_kick,if=!prev_gcd.1.spinning_crane_kick
if not PreviousGCDSpell(spinning_crane_kick) Spell(spinning_crane_kick)
#blackout_kick,cycle_targets=1,if=!prev_gcd.1.blackout_kick
if not PreviousGCDSpell(blackout_kick) Spell(blackout_kick)
}
}
AddFunction WindwalkerSerenityMainPostConditions
{
WindwalkerCdMainPostConditions()
}
AddFunction WindwalkerSerenityShortCdActions
{
unless not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) and Spell(tiger_palm)
{
#call_action_list,name=cd
WindwalkerCdShortCdActions()
unless WindwalkerCdShortCdPostConditions()
{
#serenity
Spell(serenity)
}
}
}
AddFunction WindwalkerSerenityShortCdPostConditions
{
not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) and Spell(tiger_palm) or WindwalkerCdShortCdPostConditions() or Enemies() < 3 and Spell(rising_sun_kick) or Spell(strike_of_the_windlord) or not PreviousGCDSpell(blackout_kick) and { PreviousGCDSpell(strike_of_the_windlord) or PreviousGCDSpell(fists_of_fury) } and Enemies() < 2 and Spell(blackout_kick) or HasEquippedItem(drinking_horn_cover) and BuffRemaining(pressure_point_buff) <= 2 and ArmorSetBonus(T20 4) and { SpellCooldown(rising_sun_kick) > 1 or Enemies() > 1 } and Spell(fists_of_fury) or { not HasEquippedItem(drinking_horn_cover) or BuffPresent(burst_haste_buff any=1) or BuffRemaining(serenity_buff) < 1 } and { SpellCooldown(rising_sun_kick) > 1 or Enemies() > 1 } and Spell(fists_of_fury) or Enemies() >= 3 and not PreviousGCDSpell(spinning_crane_kick) and Spell(spinning_crane_kick) or not PreviousGCDSpell(rushing_jade_wind) and BuffExpires(rushing_jade_wind_buff) and BuffRemaining(serenity_buff) >= 4 and Spell(rushing_jade_wind) or Enemies() >= 3 and Spell(rising_sun_kick) or not PreviousGCDSpell(rushing_jade_wind) and BuffExpires(rushing_jade_wind_buff) and Enemies() > 1 and Spell(rushing_jade_wind) or not PreviousGCDSpell(spinning_crane_kick) and Spell(spinning_crane_kick) or not PreviousGCDSpell(blackout_kick) and Spell(blackout_kick)
}
AddFunction WindwalkerSerenityCdActions
{
unless not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) and Spell(tiger_palm)
{
#call_action_list,name=cd
WindwalkerCdCdActions()
}
}
AddFunction WindwalkerSerenityCdPostConditions
{
not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and not BuffPresent(serenity_buff) and Spell(tiger_palm) or WindwalkerCdCdPostConditions() or Spell(serenity) or Enemies() < 3 and Spell(rising_sun_kick) or Spell(strike_of_the_windlord) or not PreviousGCDSpell(blackout_kick) and { PreviousGCDSpell(strike_of_the_windlord) or PreviousGCDSpell(fists_of_fury) } and Enemies() < 2 and Spell(blackout_kick) or HasEquippedItem(drinking_horn_cover) and BuffRemaining(pressure_point_buff) <= 2 and ArmorSetBonus(T20 4) and { SpellCooldown(rising_sun_kick) > 1 or Enemies() > 1 } and Spell(fists_of_fury) or { not HasEquippedItem(drinking_horn_cover) or BuffPresent(burst_haste_buff any=1) or BuffRemaining(serenity_buff) < 1 } and { SpellCooldown(rising_sun_kick) > 1 or Enemies() > 1 } and Spell(fists_of_fury) or Enemies() >= 3 and not PreviousGCDSpell(spinning_crane_kick) and Spell(spinning_crane_kick) or not PreviousGCDSpell(rushing_jade_wind) and BuffExpires(rushing_jade_wind_buff) and BuffRemaining(serenity_buff) >= 4 and Spell(rushing_jade_wind) or Enemies() >= 3 and Spell(rising_sun_kick) or not PreviousGCDSpell(rushing_jade_wind) and BuffExpires(rushing_jade_wind_buff) and Enemies() > 1 and Spell(rushing_jade_wind) or not PreviousGCDSpell(spinning_crane_kick) and Spell(spinning_crane_kick) or not PreviousGCDSpell(blackout_kick) and Spell(blackout_kick)
}
### actions.sef
AddFunction WindwalkerSefMainActions
{
#tiger_palm,cycle_targets=1,if=!prev_gcd.1.tiger_palm&energy=energy.max&chi<1
if not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 Spell(tiger_palm)
#call_action_list,name=cd
WindwalkerCdMainActions()
unless WindwalkerCdMainPostConditions()
{
#call_action_list,name=st
WindwalkerStMainActions()
}
}
AddFunction WindwalkerSefMainPostConditions
{
WindwalkerCdMainPostConditions() or WindwalkerStMainPostConditions()
}
AddFunction WindwalkerSefShortCdActions
{
unless not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and Spell(tiger_palm)
{
#call_action_list,name=cd
WindwalkerCdShortCdActions()
unless WindwalkerCdShortCdPostConditions()
{
#call_action_list,name=st
WindwalkerStShortCdActions()
}
}
}
AddFunction WindwalkerSefShortCdPostConditions
{
not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and Spell(tiger_palm) or WindwalkerCdShortCdPostConditions() or WindwalkerStShortCdPostConditions()
}
AddFunction WindwalkerSefCdActions
{
unless not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and Spell(tiger_palm)
{
#arcane_torrent,if=chi.max-chi>=1&energy.time_to_max>=0.5
if MaxChi() - Chi() >= 1 and TimeToMaxEnergy() >= 0 Spell(arcane_torrent_chi)
#call_action_list,name=cd
WindwalkerCdCdActions()
unless WindwalkerCdCdPostConditions()
{
#storm_earth_and_fire,if=!buff.storm_earth_and_fire.up
if not BuffPresent(storm_earth_and_fire_buff) and CheckBoxOn(opt_storm_earth_and_fire) and not BuffPresent(storm_earth_and_fire_buff) Spell(storm_earth_and_fire)
#call_action_list,name=st
WindwalkerStCdActions()
}
}
}
AddFunction WindwalkerSefCdPostConditions
{
not PreviousGCDSpell(tiger_palm) and Energy() == MaxEnergy() and Chi() < 1 and Spell(tiger_palm) or WindwalkerCdCdPostConditions() or WindwalkerStCdPostConditions()
}
### actions.precombat
AddFunction WindwalkerPrecombatMainActions
{
#chi_burst
if CheckBoxOn(opt_chi_burst) Spell(chi_burst)
#chi_wave
Spell(chi_wave)
}
AddFunction WindwalkerPrecombatMainPostConditions
{
}
AddFunction WindwalkerPrecombatShortCdActions
{
}
AddFunction WindwalkerPrecombatShortCdPostConditions
{
CheckBoxOn(opt_chi_burst) and Spell(chi_burst) or Spell(chi_wave)
}
AddFunction WindwalkerPrecombatCdActions
{
#flask
#food
#augmentation
#snapshot_stats
#potion
if CheckBoxOn(opt_use_consumables) and target.Classification(worldboss) Item(prolonged_power_potion usable=1)
}
AddFunction WindwalkerPrecombatCdPostConditions
{
CheckBoxOn(opt_chi_burst) and Spell(chi_burst) or Spell(chi_wave)
}
### actions.cd
AddFunction WindwalkerCdMainActions
{
#touch_of_death,cycle_targets=1,max_cycle_targets=2,if=!artifact.gale_burst.enabled&equipped.hidden_masters_forbidden_touch&!prev_gcd.1.touch_of_death
if DebuffCountOnAny(touch_of_death_debuff) < Enemies() and DebuffCountOnAny(touch_of_death_debuff) <= 2 and not HasArtifactTrait(gale_burst) and HasEquippedItem(hidden_masters_forbidden_touch) and not PreviousGCDSpell(touch_of_death) and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } Spell(touch_of_death)
#touch_of_death,if=!artifact.gale_burst.enabled&!equipped.hidden_masters_forbidden_touch
if not HasArtifactTrait(gale_burst) and not HasEquippedItem(hidden_masters_forbidden_touch) and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } Spell(touch_of_death)
#touch_of_death,cycle_targets=1,max_cycle_targets=2,if=artifact.gale_burst.enabled&((talent.serenity.enabled&cooldown.serenity.remains<=1)|chi>=2)&(cooldown.strike_of_the_windlord.remains<8|cooldown.fists_of_fury.remains<=4)&cooldown.rising_sun_kick.remains<7&!prev_gcd.1.touch_of_death
if DebuffCountOnAny(touch_of_death_debuff) < Enemies() and DebuffCountOnAny(touch_of_death_debuff) <= 2 and HasArtifactTrait(gale_burst) and { Talent(serenity_talent) and SpellCooldown(serenity) <= 1 or Chi() >= 2 } and { SpellCooldown(strike_of_the_windlord) < 8 or SpellCooldown(fists_of_fury) <= 4 } and SpellCooldown(rising_sun_kick) < 7 and not PreviousGCDSpell(touch_of_death) and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } Spell(touch_of_death)
}
AddFunction WindwalkerCdMainPostConditions
{
}
AddFunction WindwalkerCdShortCdActions
{
}
AddFunction WindwalkerCdShortCdPostConditions
{
DebuffCountOnAny(touch_of_death_debuff) < Enemies() and DebuffCountOnAny(touch_of_death_debuff) <= 2 and not HasArtifactTrait(gale_burst) and HasEquippedItem(hidden_masters_forbidden_touch) and not PreviousGCDSpell(touch_of_death) and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death) or not HasArtifactTrait(gale_burst) and not HasEquippedItem(hidden_masters_forbidden_touch) and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death) or DebuffCountOnAny(touch_of_death_debuff) < Enemies() and DebuffCountOnAny(touch_of_death_debuff) <= 2 and HasArtifactTrait(gale_burst) and { Talent(serenity_talent) and SpellCooldown(serenity) <= 1 or Chi() >= 2 } and { SpellCooldown(strike_of_the_windlord) < 8 or SpellCooldown(fists_of_fury) <= 4 } and SpellCooldown(rising_sun_kick) < 7 and not PreviousGCDSpell(touch_of_death) and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death)
}
AddFunction WindwalkerCdCdActions
{
#invoke_xuen_the_white_tiger
Spell(invoke_xuen_the_white_tiger)
#blood_fury
Spell(blood_fury_apsp)
#berserking
Spell(berserking)
#arcane_torrent,if=chi.max-chi>=1&energy.time_to_max>=0.5
if MaxChi() - Chi() >= 1 and TimeToMaxEnergy() >= 0 Spell(arcane_torrent_chi)
}
AddFunction WindwalkerCdCdPostConditions
{
DebuffCountOnAny(touch_of_death_debuff) < Enemies() and DebuffCountOnAny(touch_of_death_debuff) <= 2 and not HasArtifactTrait(gale_burst) and HasEquippedItem(hidden_masters_forbidden_touch) and not PreviousGCDSpell(touch_of_death) and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death) or not HasArtifactTrait(gale_burst) and not HasEquippedItem(hidden_masters_forbidden_touch) and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death) or DebuffCountOnAny(touch_of_death_debuff) < Enemies() and DebuffCountOnAny(touch_of_death_debuff) <= 2 and HasArtifactTrait(gale_burst) and { Talent(serenity_talent) and SpellCooldown(serenity) <= 1 or Chi() >= 2 } and { SpellCooldown(strike_of_the_windlord) < 8 or SpellCooldown(fists_of_fury) <= 4 } and SpellCooldown(rising_sun_kick) < 7 and not PreviousGCDSpell(touch_of_death) and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death)
}
### actions.default
AddFunction WindwalkerDefaultMainActions
{
#touch_of_death,if=target.time_to_die<=9
if target.TimeToDie() <= 9 and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } Spell(touch_of_death)
#call_action_list,name=serenity_opener,if=((talent.serenity.enabled&cooldown.serenity.remains<=0)|buff.serenity.up)&active_enemies<2&set_bonus.tier20_4pc&set_bonus.tier19_2pc&equipped.drinking_horn_cover&time<20
if { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and Enemies() < 2 and ArmorSetBonus(T20 4) and ArmorSetBonus(T19 2) and HasEquippedItem(drinking_horn_cover) and TimeInCombat() < 20 WindwalkerSerenityopenerMainActions()
unless { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and Enemies() < 2 and ArmorSetBonus(T20 4) and ArmorSetBonus(T19 2) and HasEquippedItem(drinking_horn_cover) and TimeInCombat() < 20 and WindwalkerSerenityopenerMainPostConditions()
{
#call_action_list,name=serenity,if=(((talent.serenity.enabled&cooldown.serenity.remains<=0)|buff.serenity.up)&(!set_bonus.tier20_4pc&!set_bonus.tier19_2pc&!equipped.drinking_horn_cover))|(((talent.serenity.enabled&cooldown.serenity.remains<=0)|buff.serenity.up)&time>20)
if { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and not ArmorSetBonus(T20 4) and not ArmorSetBonus(T19 2) and not HasEquippedItem(drinking_horn_cover) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and TimeInCombat() > 20 WindwalkerSerenityMainActions()
unless { { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and not ArmorSetBonus(T20 4) and not ArmorSetBonus(T19 2) and not HasEquippedItem(drinking_horn_cover) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and TimeInCombat() > 20 } and WindwalkerSerenityMainPostConditions()
{
#call_action_list,name=sef,if=!talent.serenity.enabled&(buff.storm_earth_and_fire.up|cooldown.storm_earth_and_fire.charges=2)
if not Talent(serenity_talent) and { BuffPresent(storm_earth_and_fire_buff) or SpellCharges(storm_earth_and_fire) == 2 } WindwalkerSefMainActions()
unless not Talent(serenity_talent) and { BuffPresent(storm_earth_and_fire_buff) or SpellCharges(storm_earth_and_fire) == 2 } and WindwalkerSefMainPostConditions()
{
#call_action_list,name=sef,if=!talent.serenity.enabled&equipped.drinking_horn_cover&(cooldown.strike_of_the_windlord.remains<=18&cooldown.fists_of_fury.remains<=12&chi>=3&cooldown.rising_sun_kick.remains<=1|target.time_to_die<=25|cooldown.touch_of_death.remains>112)&cooldown.storm_earth_and_fire.charges=1
if not Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 18 and SpellCooldown(fists_of_fury) <= 12 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 25 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 WindwalkerSefMainActions()
unless not Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 18 and SpellCooldown(fists_of_fury) <= 12 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 25 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefMainPostConditions()
{
#call_action_list,name=sef,if=!talent.serenity.enabled&!equipped.drinking_horn_cover&(cooldown.strike_of_the_windlord.remains<=14&cooldown.fists_of_fury.remains<=6&chi>=3&cooldown.rising_sun_kick.remains<=1|target.time_to_die<=15|cooldown.touch_of_death.remains>112)&cooldown.storm_earth_and_fire.charges=1
if not Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 14 and SpellCooldown(fists_of_fury) <= 6 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 15 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 WindwalkerSefMainActions()
unless not Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 14 and SpellCooldown(fists_of_fury) <= 6 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 15 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefMainPostConditions()
{
#call_action_list,name=st
WindwalkerStMainActions()
}
}
}
}
}
}
AddFunction WindwalkerDefaultMainPostConditions
{
{ Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and Enemies() < 2 and ArmorSetBonus(T20 4) and ArmorSetBonus(T19 2) and HasEquippedItem(drinking_horn_cover) and TimeInCombat() < 20 and WindwalkerSerenityopenerMainPostConditions() or { { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and not ArmorSetBonus(T20 4) and not ArmorSetBonus(T19 2) and not HasEquippedItem(drinking_horn_cover) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and TimeInCombat() > 20 } and WindwalkerSerenityMainPostConditions() or not Talent(serenity_talent) and { BuffPresent(storm_earth_and_fire_buff) or SpellCharges(storm_earth_and_fire) == 2 } and WindwalkerSefMainPostConditions() or not Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 18 and SpellCooldown(fists_of_fury) <= 12 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 25 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefMainPostConditions() or not Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 14 and SpellCooldown(fists_of_fury) <= 6 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 15 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefMainPostConditions() or WindwalkerStMainPostConditions()
}
AddFunction WindwalkerDefaultShortCdActions
{
#auto_attack
WindwalkerGetInMeleeRange()
unless target.TimeToDie() <= 9 and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death)
{
#call_action_list,name=serenity_opener,if=((talent.serenity.enabled&cooldown.serenity.remains<=0)|buff.serenity.up)&active_enemies<2&set_bonus.tier20_4pc&set_bonus.tier19_2pc&equipped.drinking_horn_cover&time<20
if { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and Enemies() < 2 and ArmorSetBonus(T20 4) and ArmorSetBonus(T19 2) and HasEquippedItem(drinking_horn_cover) and TimeInCombat() < 20 WindwalkerSerenityopenerShortCdActions()
unless { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and Enemies() < 2 and ArmorSetBonus(T20 4) and ArmorSetBonus(T19 2) and HasEquippedItem(drinking_horn_cover) and TimeInCombat() < 20 and WindwalkerSerenityopenerShortCdPostConditions()
{
#call_action_list,name=serenity,if=(((talent.serenity.enabled&cooldown.serenity.remains<=0)|buff.serenity.up)&(!set_bonus.tier20_4pc&!set_bonus.tier19_2pc&!equipped.drinking_horn_cover))|(((talent.serenity.enabled&cooldown.serenity.remains<=0)|buff.serenity.up)&time>20)
if { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and not ArmorSetBonus(T20 4) and not ArmorSetBonus(T19 2) and not HasEquippedItem(drinking_horn_cover) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and TimeInCombat() > 20 WindwalkerSerenityShortCdActions()
unless { { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and not ArmorSetBonus(T20 4) and not ArmorSetBonus(T19 2) and not HasEquippedItem(drinking_horn_cover) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and TimeInCombat() > 20 } and WindwalkerSerenityShortCdPostConditions()
{
#call_action_list,name=sef,if=!talent.serenity.enabled&(buff.storm_earth_and_fire.up|cooldown.storm_earth_and_fire.charges=2)
if not Talent(serenity_talent) and { BuffPresent(storm_earth_and_fire_buff) or SpellCharges(storm_earth_and_fire) == 2 } WindwalkerSefShortCdActions()
unless not Talent(serenity_talent) and { BuffPresent(storm_earth_and_fire_buff) or SpellCharges(storm_earth_and_fire) == 2 } and WindwalkerSefShortCdPostConditions()
{
#call_action_list,name=sef,if=!talent.serenity.enabled&equipped.drinking_horn_cover&(cooldown.strike_of_the_windlord.remains<=18&cooldown.fists_of_fury.remains<=12&chi>=3&cooldown.rising_sun_kick.remains<=1|target.time_to_die<=25|cooldown.touch_of_death.remains>112)&cooldown.storm_earth_and_fire.charges=1
if not Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 18 and SpellCooldown(fists_of_fury) <= 12 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 25 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 WindwalkerSefShortCdActions()
unless not Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 18 and SpellCooldown(fists_of_fury) <= 12 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 25 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefShortCdPostConditions()
{
#call_action_list,name=sef,if=!talent.serenity.enabled&!equipped.drinking_horn_cover&(cooldown.strike_of_the_windlord.remains<=14&cooldown.fists_of_fury.remains<=6&chi>=3&cooldown.rising_sun_kick.remains<=1|target.time_to_die<=15|cooldown.touch_of_death.remains>112)&cooldown.storm_earth_and_fire.charges=1
if not Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 14 and SpellCooldown(fists_of_fury) <= 6 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 15 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 WindwalkerSefShortCdActions()
unless not Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 14 and SpellCooldown(fists_of_fury) <= 6 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 15 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefShortCdPostConditions()
{
#call_action_list,name=st
WindwalkerStShortCdActions()
}
}
}
}
}
}
}
AddFunction WindwalkerDefaultShortCdPostConditions
{
target.TimeToDie() <= 9 and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and Enemies() < 2 and ArmorSetBonus(T20 4) and ArmorSetBonus(T19 2) and HasEquippedItem(drinking_horn_cover) and TimeInCombat() < 20 and WindwalkerSerenityopenerShortCdPostConditions() or { { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and not ArmorSetBonus(T20 4) and not ArmorSetBonus(T19 2) and not HasEquippedItem(drinking_horn_cover) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and TimeInCombat() > 20 } and WindwalkerSerenityShortCdPostConditions() or not Talent(serenity_talent) and { BuffPresent(storm_earth_and_fire_buff) or SpellCharges(storm_earth_and_fire) == 2 } and WindwalkerSefShortCdPostConditions() or not Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 18 and SpellCooldown(fists_of_fury) <= 12 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 25 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefShortCdPostConditions() or not Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 14 and SpellCooldown(fists_of_fury) <= 6 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 15 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefShortCdPostConditions() or WindwalkerStShortCdPostConditions()
}
AddFunction WindwalkerDefaultCdActions
{
#spear_hand_strike,if=target.debuff.casting.react
if target.IsInterruptible() WindwalkerInterruptActions()
#touch_of_karma,interval=90,pct_health=0.5
if CheckBoxOn(opt_touch_of_karma) Spell(touch_of_karma)
#potion,if=buff.serenity.up|buff.storm_earth_and_fire.up|(!talent.serenity.enabled&trinket.proc.agility.react)|buff.bloodlust.react|target.time_to_die<=60
if { BuffPresent(serenity_buff) or BuffPresent(storm_earth_and_fire_buff) or not Talent(serenity_talent) and BuffPresent(trinket_proc_agility_buff) or BuffPresent(burst_haste_buff any=1) or target.TimeToDie() <= 60 } and CheckBoxOn(opt_use_consumables) and target.Classification(worldboss) Item(prolonged_power_potion usable=1)
unless target.TimeToDie() <= 9 and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death)
{
#call_action_list,name=serenity_opener,if=((talent.serenity.enabled&cooldown.serenity.remains<=0)|buff.serenity.up)&active_enemies<2&set_bonus.tier20_4pc&set_bonus.tier19_2pc&equipped.drinking_horn_cover&time<20
if { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and Enemies() < 2 and ArmorSetBonus(T20 4) and ArmorSetBonus(T19 2) and HasEquippedItem(drinking_horn_cover) and TimeInCombat() < 20 WindwalkerSerenityopenerCdActions()
unless { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and Enemies() < 2 and ArmorSetBonus(T20 4) and ArmorSetBonus(T19 2) and HasEquippedItem(drinking_horn_cover) and TimeInCombat() < 20 and WindwalkerSerenityopenerCdPostConditions()
{
#call_action_list,name=serenity,if=(((talent.serenity.enabled&cooldown.serenity.remains<=0)|buff.serenity.up)&(!set_bonus.tier20_4pc&!set_bonus.tier19_2pc&!equipped.drinking_horn_cover))|(((talent.serenity.enabled&cooldown.serenity.remains<=0)|buff.serenity.up)&time>20)
if { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and not ArmorSetBonus(T20 4) and not ArmorSetBonus(T19 2) and not HasEquippedItem(drinking_horn_cover) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and TimeInCombat() > 20 WindwalkerSerenityCdActions()
unless { { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and not ArmorSetBonus(T20 4) and not ArmorSetBonus(T19 2) and not HasEquippedItem(drinking_horn_cover) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and TimeInCombat() > 20 } and WindwalkerSerenityCdPostConditions()
{
#call_action_list,name=sef,if=!talent.serenity.enabled&(buff.storm_earth_and_fire.up|cooldown.storm_earth_and_fire.charges=2)
if not Talent(serenity_talent) and { BuffPresent(storm_earth_and_fire_buff) or SpellCharges(storm_earth_and_fire) == 2 } WindwalkerSefCdActions()
unless not Talent(serenity_talent) and { BuffPresent(storm_earth_and_fire_buff) or SpellCharges(storm_earth_and_fire) == 2 } and WindwalkerSefCdPostConditions()
{
#call_action_list,name=sef,if=!talent.serenity.enabled&equipped.drinking_horn_cover&(cooldown.strike_of_the_windlord.remains<=18&cooldown.fists_of_fury.remains<=12&chi>=3&cooldown.rising_sun_kick.remains<=1|target.time_to_die<=25|cooldown.touch_of_death.remains>112)&cooldown.storm_earth_and_fire.charges=1
if not Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 18 and SpellCooldown(fists_of_fury) <= 12 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 25 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 WindwalkerSefCdActions()
unless not Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 18 and SpellCooldown(fists_of_fury) <= 12 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 25 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefCdPostConditions()
{
#call_action_list,name=sef,if=!talent.serenity.enabled&!equipped.drinking_horn_cover&(cooldown.strike_of_the_windlord.remains<=14&cooldown.fists_of_fury.remains<=6&chi>=3&cooldown.rising_sun_kick.remains<=1|target.time_to_die<=15|cooldown.touch_of_death.remains>112)&cooldown.storm_earth_and_fire.charges=1
if not Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 14 and SpellCooldown(fists_of_fury) <= 6 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 15 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 WindwalkerSefCdActions()
unless not Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 14 and SpellCooldown(fists_of_fury) <= 6 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 15 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefCdPostConditions()
{
#call_action_list,name=st
WindwalkerStCdActions()
}
}
}
}
}
}
}
AddFunction WindwalkerDefaultCdPostConditions
{
target.TimeToDie() <= 9 and { not CheckBoxOn(opt_touch_of_death_on_elite_only) or not UnitInRaid() and target.Classification(elite) or target.Classification(worldboss) or not BuffExpires(hidden_masters_forbidden_touch_buff) } and Spell(touch_of_death) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and Enemies() < 2 and ArmorSetBonus(T20 4) and ArmorSetBonus(T19 2) and HasEquippedItem(drinking_horn_cover) and TimeInCombat() < 20 and WindwalkerSerenityopenerCdPostConditions() or { { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and not ArmorSetBonus(T20 4) and not ArmorSetBonus(T19 2) and not HasEquippedItem(drinking_horn_cover) or { Talent(serenity_talent) and SpellCooldown(serenity) <= 0 or BuffPresent(serenity_buff) } and TimeInCombat() > 20 } and WindwalkerSerenityCdPostConditions() or not Talent(serenity_talent) and { BuffPresent(storm_earth_and_fire_buff) or SpellCharges(storm_earth_and_fire) == 2 } and WindwalkerSefCdPostConditions() or not Talent(serenity_talent) and HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 18 and SpellCooldown(fists_of_fury) <= 12 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 25 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefCdPostConditions() or not Talent(serenity_talent) and not HasEquippedItem(drinking_horn_cover) and { SpellCooldown(strike_of_the_windlord) <= 14 and SpellCooldown(fists_of_fury) <= 6 and Chi() >= 3 and SpellCooldown(rising_sun_kick) <= 1 or target.TimeToDie() <= 15 or SpellCooldown(touch_of_death) > 112 } and SpellCharges(storm_earth_and_fire) == 1 and WindwalkerSefCdPostConditions() or WindwalkerStCdPostConditions()
}
### Windwalker icons.
AddCheckBox(opt_monk_windwalker_aoe L(AOE) default specialization=windwalker)
AddIcon checkbox=!opt_monk_windwalker_aoe enemies=1 help=shortcd specialization=windwalker
{
if not InCombat() WindwalkerPrecombatShortCdActions()
unless not InCombat() and WindwalkerPrecombatShortCdPostConditions()
{
WindwalkerDefaultShortCdActions()
}
}
AddIcon checkbox=opt_monk_windwalker_aoe help=shortcd specialization=windwalker
{
if not InCombat() WindwalkerPrecombatShortCdActions()
unless not InCombat() and WindwalkerPrecombatShortCdPostConditions()
{
WindwalkerDefaultShortCdActions()
}
}
AddIcon enemies=1 help=main specialization=windwalker
{
if not InCombat() WindwalkerPrecombatMainActions()
unless not InCombat() and WindwalkerPrecombatMainPostConditions()
{
WindwalkerDefaultMainActions()
}
}
AddIcon checkbox=opt_monk_windwalker_aoe help=aoe specialization=windwalker
{
if not InCombat() WindwalkerPrecombatMainActions()
unless not InCombat() and WindwalkerPrecombatMainPostConditions()
{
WindwalkerDefaultMainActions()
}
}
AddIcon checkbox=!opt_monk_windwalker_aoe enemies=1 help=cd specialization=windwalker
{
if not InCombat() WindwalkerPrecombatCdActions()
unless not InCombat() and WindwalkerPrecombatCdPostConditions()
{
WindwalkerDefaultCdActions()
}
}
AddIcon checkbox=opt_monk_windwalker_aoe help=cd specialization=windwalker
{
if not InCombat() WindwalkerPrecombatCdActions()
unless not InCombat() and WindwalkerPrecombatCdPostConditions()
{
WindwalkerDefaultCdActions()
}
}
### Required symbols
# energizing_elixir
# rising_sun_kick
# strike_of_the_windlord
# arcane_torrent_chi
# tiger_palm
# serenity_talent
# serenity
# fists_of_fury
# drinking_horn_cover
# whirling_dragon_punch
# blackout_kick
# bok_proc_buff
# spinning_crane_kick
# crackling_jade_lightning
# the_emperors_capacitor
# the_emperors_capacitor_buff
# rushing_jade_wind
# energizing_elixir_talent
# chi_wave
# chi_burst
# serenity_buff
# pressure_point_buff
# rushing_jade_wind_buff
# storm_earth_and_fire
# storm_earth_and_fire_buff
# prolonged_power_potion
# invoke_xuen_the_white_tiger
# blood_fury_apsp
# berserking
# hidden_masters_forbidden_touch_buff
# touch_of_death
# touch_of_death_debuff
# gale_burst
# hidden_masters_forbidden_touch
# touch_of_karma
# paralysis
# war_stomp
# quaking_palm
# leg_sweep
# spear_hand_strike
]]
OvaleScripts:RegisterScript("MONK", "windwalker", name, desc, code, "script")
end
|
return {
level = 81,
need_exp = 230000,
clothes_attrs = {
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
},
}
|
-- Fix broken job postings
posting_structs_known = pcall(function() return df.job:new().posting_index end)
world = df.global.world
print(dfhack.getDFHackVersion())
if posting_structs_known then
print('Posting structs known')
job_postings = 'job_postings'
posting_index = 'posting_index'
function is_dead(posting)
return posting.flags.dead
end
function set_dead(posting)
posting.flags.dead = true
end
else
print('Posting structs not known')
job_postings = 'anon_1'
posting_index = 'unk_v4020_1'
function is_dead(posting)
return posting.flags % 2 == 1
end
function set_dead(posting)
posting.flags = -1
end
end
dry_run = #{...} >= 1
count = 0
link = world.job_list
while link do
job = link.item
if job then
for id, posting in pairs(world[job_postings]) do
if posting.job == job and id ~= job[posting_index] and not is_dead(posting) then
count = count + 1
print(('Found extra job posting: Job %i: %s'):format(job.id, dfhack.job.getName(job)))
if not dry_run then
set_dead(posting)
end
end
end
end
link = link.next
end
print(tostring(count) .. ' issue(s) ' .. (dry_run and 'detected' or 'fixed'))
|
-----------------------------------
-- Area: Ru'Lud Gardens
-- NPC: Laityn
-- Involved In Quest: Recollections
-----------------------------------
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.RECOLLECTIONS) == QUEST_ACCEPTED and player:getCharVar("recollectionsQuest") == 0) then
player:startEvent(10003) -- Option CS for "Recollections"
else
player:startEvent(10006)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 10003) then
player:setCharVar("recollectionsQuest", 1)
end
end
|
--[[
-- added by passion @ 2021/5/31 8:37:36
-- ExamItemDes模块窗口配置,要使用还需要导出到UI.Config.UIConfig.lua
--]]
-- 窗口配置
local ExamItemDes= {
Name = UIWindowNames.ExamItemDes,
Layer = UILayers.SceneLayer,
Model = require "UI.ExamItemDes.Model.ExamItemDesModel",
Ctrl = require "UI.ExamItemDes.Controller.ExamItemDesCtrl",
View = require "UI.ExamItemDes.View.ExamItemDesView",
PrefabPath = "UI/Prefabs/View/ExamItemDes.prefab",
}
return {
ExamItemDes=ExamItemDes,
}
|
function Server_StartDistribution(game, standing)
overriddenTerris=Mod.Settings.OverriddenTerris;
for _, terr in pairs(standing.Territories) do
print('ID: ' .. terr.ID .. ', Arr: ' .. overriddenTerris[terr.ID]);
if (overriddenTerris[terr.ID]~=nil) then
if (overriddenTerris[terr.ID]==1) then
if(terr.IsNeutral) then
print('Tried NumArmyChange');
terr.NumArmies = WL.Armies.Create(Mod.Settings.TroopValue);
end
end
end
end
end
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
|
StandAndAttack = Class(BehaviourNode, function(self, inst, findnewtargetfn)
BehaviourNode._ctor(self, "StandAndAttack")
self.inst = inst
self.findnewtargetfn = findnewtargetfn
self.numattacks = 0
-- we need to store this function as a key to use to remove itself later
self.onattackfn = function(inst, data)
self:OnAttackOther(data.target)
end
self.inst:ListenForEvent("onattackother", self.onattackfn)
self.inst:ListenForEvent("onmissother", self.onattackfn)
end)
function StandAndAttack:__tostring()
return string.format("target %s", tostring(self.inst.components.combat.target))
end
function StandAndAttack:OnStop()
self.inst:RemoveEventCallback("onattackother", self.onattackfn)
self.inst:RemoveEventCallback("onmissother", self.onattackfn)
end
function StandAndAttack:OnAttackOther(target)
--print ("on attack other", target)
self.numattacks = self.numattacks + 1
self.startruntime = nil -- reset max chase time timer
end
function StandAndAttack:Visit()
local combat = self.inst.components.combat
if self.status == READY then
combat:ValidateTarget()
if not combat.target and self.findnewtargetfn then
combat.target = self.findnewtargetfn(self.inst)
end
if combat.target then
self.inst.components.combat:BattleCry()
self.status = RUNNING
else
self.status = FAILED
end
end
if self.status == RUNNING then
local is_attacking = self.inst.sg:HasStateTag("attack")
if not combat.target or not combat.target.entity:IsValid() then
self.status = FAILED
combat:SetTarget(nil)
elseif combat.target.components.health and combat.target.components.health:IsDead() then
self.status = SUCCESS
combat:SetTarget(nil)
else
local hp = Point(combat.target.Transform:GetWorldPosition())
local pt = Point(self.inst.Transform:GetWorldPosition())
local dsq = distsq(hp, pt)
local angle = self.inst:GetAngleToPoint(hp)
local r= self.inst.Physics:GetRadius()+ combat.target.Physics:GetRadius() + .1
if self.inst.sg:HasStateTag("canrotate") then
self.inst:FacePoint(hp)
end
combat:TryAttack()
self:Sleep(.125)
end
end
end
|
--[[
"Get A Job, Baby!" is a game written by Eetu Rantanen for Ludum Dare 45
Copyright (C) 2019 - Spyric Entertainment
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
]]--
local composer = require( "composer" )
local screen = require( "scripts.screen" )
local settings = require( "data.settings" )
local sfx = require( "scripts.sfx" )
local sceneGroupRef
local groupUI = display.newGroup()
local groupBG = display.newGroup()
local daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
local monthNames = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
local calendar = {}
local continue
local previousMonth = 0
-------------------------------------------------------------------------------
local function resetYear()
for i = 1, 12 do
for j = 1, daysInMonth[i] do
calendar[i].days[j]:setFillColor( unpack( settings.colours.ground ) )
end
calendar[i].moneyMade.text = "$0"
end
previousMonth = 0
-- composer.money = 0
-- composer.month = 1
-- G_money.text = "$0"
-- G_month.text = "Month 1"
end
local function updateMonth( score, rate, skipped )
if skipped then
-- If player skipped working for a month, then just autofill the year instantly
for i = 1, daysInMonth[rate] do
calendar[rate].days[i]:setFillColor( unpack( settings.colours.b ) )
end
if rate == 12 then
G_block.isHitTestable = false
transition.blink( continue, {time=2000} )
end
else
local days = daysInMonth[GLOBAL_FIX.month]
local daysEmployed = math.ceil( days*rate )
local delay = 25
for i = 1, daysEmployed do
timer.performWithDelay( delay*i, function()
calendar[GLOBAL_FIX.month].days[i]:setFillColor( unpack( settings.colours.a ) )
end )
end
if daysEmployed < days then
for i = daysEmployed+1, days do
timer.performWithDelay( delay*i, function()
calendar[GLOBAL_FIX.month].days[i]:setFillColor( unpack( settings.colours.b ) )
end )
end
end
timer.performWithDelay( delay*(days+2), function()
local monthlyScore = score * daysEmployed
GLOBAL_FIX.money = GLOBAL_FIX.money + monthlyScore
G_money.text = "$" .. GLOBAL_FIX.money
calendar[GLOBAL_FIX.month].moneyMade.text = "$" .. monthlyScore
previousMonth = GLOBAL_FIX.month
GLOBAL_FIX.month = GLOBAL_FIX.month+1
continue.isVisible = true
G_block.isHitTestable = false
transition.blink( continue, {time=2000} )
end )
end
end
local function nextScene( event )
if event.phase == "ended" then
sfx.play()
G_block.isHitTestable = true
G_performance.text = "$0 - 100%"
G_performance.isVisible = false
transition.cancel( continue )
if GLOBAL_FIX.month >= 13 then
G_month.text = "Month 12"
composer.gotoScene( "scenes.hospital", { effect = "slideUp", params = { gameover=true } } )
else
G_month.text = "Month " .. GLOBAL_FIX.month
composer.gotoScene( "scenes.yard", { effect = "slideUp" } )
end
end
return true
end
-------------------------------------------------------------------------------
local scene = composer.newScene()
function scene:create( event )
local sceneGroup = self.view
sceneGroupRef = sceneGroup
local background = display.newRect( groupBG, screen.centreX, screen.centreY, screen.width, screen.height )
background:setFillColor( unpack( settings.colours.sky ) )
background:addEventListener( "touch", nextScene )
continue = display.newText( groupBG, "Tap to Continue", screen.centreX, screen.maxY - 4, "fonts/Roboto-Black.ttf", 32 )
continue.isVisible = false
continue.anchorY = 1
local x, y, xOffset, yOffset = 48, 180, 0, 0
local monthWidth = 50
local monthHeight = 240
local monthPadding = 106
local daySize = 20
local cellOffset = monthWidth*0.5
for i = 1, 12 do
calendar[i] = display.newText( groupBG, monthNames[i], x+monthWidth*xOffset + monthPadding*xOffset, y+monthHeight*yOffset, "fonts/Roboto-Black.ttf", 40 )
calendar[i].anchorY = 1
calendar[i]:setFillColor( unpack( settings.colours.a ) )
calendar[i].days = {}
calendar[i].moneyMade = display.newText( groupBG, "$0", x+monthWidth*xOffset + monthPadding*xOffset - 26, calendar[i].y + 150, "fonts/Roboto-Regular.ttf", 26 )
calendar[i].moneyMade.anchorX = 0
local row, column = 1, 0
local xStart, yStart = calendar[i].x - cellOffset, calendar[i].y
for j = 1, daysInMonth[i] do
calendar[i].days[j] = display.newRect( groupBG, xStart+daySize*column, yStart+daySize*row, daySize, daySize )
calendar[i].days[j].anchorX, calendar[i].days[j].anchorY = 0, 0
calendar[i].days[j]:setFillColor( unpack( settings.colours.ground ) )
if j % 7 == 0 then
row = row+1
column = -1
end
column = column+1
end
if i == 6 then
xOffset, yOffset = -1, 1
end
xOffset = xOffset+1
end
sceneGroup:insert( groupBG )
sceneGroup:insert( groupUI )
end
function scene:show( event )
if event.phase == "will" then
for i = previousMonth+1, GLOBAL_FIX.month-1 do
updateMonth( 0, i, true )
end
elseif event.phase == "did" then
if event.params then
updateMonth( event.params.score or 0, (event.params.rate and event.params.rate) or 0 )
end
end
end
function scene:hide( event )
if event.phase == "did" then
if GLOBAL_FIX.month == 13 then
resetYear()
end
end
end
-------------------------------------------------------------------------------
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
-------------------------------------------------------------------------------
return scene
|
return {
name = "Crystal",
desc = "Glows at night",
sprite = 'crystal',
usage = 'torch',
torch = {radius = 92, color = {0.9, 0.5, 1}, night_glow = true}
}
|
return {
config = 1,
cpath = 1,
loaded = 4,
loadlib = 1,
path = 1,
preload = 4,
searchers = 4,
searchpath = 1,
}
|
-- ======= Copyright (c) 2003-2011, Unknown Worlds Entertainment, Inc. All rights reserved. =======
--
-- lua\Fade.lua
--
-- Created by: Charlie Cleveland ([email protected]) and
-- Max McGuire ([email protected])
--
-- Role: Surgical striker, harassment
--
-- The Fade should be a fragile, deadly-sharp knife. Wielded properly, it's force is undeniable. But
-- used clumsily or without care will only hurt the user. Make sure Fade isn't better than the Skulk
-- in every way (notably, vs. Structures). To harass, he must be able to stay out in the field
-- without continually healing at base, and needs to be able to use blink often.
--
-- ========= For more information, visit us at http://www.unknownworlds.com =====================
Script.Load("lua/Utility.lua")
Script.Load("lua/Weapons/Alien/SwipeBlink.lua")
Script.Load("lua/Weapons/Alien/StabBlink.lua")
Script.Load("lua/Weapons/Alien/Metabolize.lua")
Script.Load("lua/Weapons/Alien/Vortex.lua")
Script.Load("lua/Weapons/Alien/ReadyRoomBlink.lua")
Script.Load("lua/Alien.lua")
Script.Load("lua/Mixins/BaseMoveMixin.lua")
Script.Load("lua/Mixins/GroundMoveMixin.lua")
Script.Load("lua/CelerityMixin.lua")
Script.Load("lua/Mixins/JumpMoveMixin.lua")
Script.Load("lua/Mixins/CrouchMoveMixin.lua")
Script.Load("lua/Mixins/CameraHolderMixin.lua")
Script.Load("lua/DissolveMixin.lua")
Script.Load("lua/TunnelUserMixin.lua")
Script.Load("lua/BabblerClingMixin.lua")
Script.Load("lua/RailgunTargetMixin.lua")
Script.Load("lua/IdleMixin.lua")
Script.Load("lua/FadeVariantMixin.lua")
class 'Fade' (Alien)
Fade.kMapName = "fade"
Fade.kModelName = PrecacheAsset("models/alien/fade/fade.model")
local kViewModelName = PrecacheAsset("models/alien/fade/fade_view.model")
local kFadeAnimationGraph = PrecacheAsset("models/alien/fade/fade.animation_graph")
PrecacheAsset("models/alien/fade/fade.surface_shader")
local kViewOffsetHeight = 1.7
Fade.XZExtents = 0.4
Fade.YExtents = 1.05
Fade.kHealth = kFadeHealth
Fade.kArmor = kFadeArmor
-- ~350 pounds.
local kMass = 158
local kJumpHeight = 1.4
local kFadeScanDuration = 4
local kShadowStepCooldown = 0.73
local kShadowStepForce = 4
local kShadowStepSpeed = 30
local kMaxSpeed = 6.2
local kBlinkSpeed = 14
local kBlinkAcceleration = 40
local kBlinkAddAcceleration = 1
local kMetabolizeAnimationDelay = 0.65
-- Delay before you can blink again after a blink.
local kMinEnterEtherealTime = 0.4
local kFadeGravityMod = 1.0
if Server then
Script.Load("lua/Fade_Server.lua")
elseif Client then
Script.Load("lua/Fade_Client.lua")
end
local networkVars =
{
isScanned = "boolean",
shadowStepping = "boolean",
timeShadowStep = "private compensated time",
shadowStepDirection = "private vector",
shadowStepSpeed = "private compensated interpolated float",
etherealStartTime = "private time",
etherealEndTime = "private time",
-- True when we're moving quickly "through the ether"
ethereal = "boolean",
landedAfterBlink = "private compensated boolean",
timeMetabolize = "private compensated time",
timeOfLastPhase = "time",
hasEtherealGate = "boolean"
}
AddMixinNetworkVars(BaseMoveMixin, networkVars)
AddMixinNetworkVars(GroundMoveMixin, networkVars)
AddMixinNetworkVars(JumpMoveMixin, networkVars)
AddMixinNetworkVars(CrouchMoveMixin, networkVars)
AddMixinNetworkVars(CelerityMixin, networkVars)
AddMixinNetworkVars(CameraHolderMixin, networkVars)
AddMixinNetworkVars(DissolveMixin, networkVars)
AddMixinNetworkVars(TunnelUserMixin, networkVars)
AddMixinNetworkVars(BabblerClingMixin, networkVars)
AddMixinNetworkVars(IdleMixin, networkVars)
AddMixinNetworkVars(FadeVariantMixin, networkVars)
function Fade:OnCreate()
InitMixin(self, BaseMoveMixin, { kGravity = Player.kGravity * kFadeGravityMod })
InitMixin(self, GroundMoveMixin)
InitMixin(self, JumpMoveMixin)
InitMixin(self, CrouchMoveMixin)
InitMixin(self, CelerityMixin)
InitMixin(self, CameraHolderMixin, { kFov = kFadeFov })
Alien.OnCreate(self)
InitMixin(self, DissolveMixin)
InitMixin(self, TunnelUserMixin)
InitMixin(self, BabblerClingMixin)
InitMixin(self, FadeVariantMixin)
if Client then
InitMixin(self, RailgunTargetMixin)
end
self.shadowStepDirection = Vector()
if Server then
self.timeLastScan = 0
self.isBlinking = false
self.timeShadowStep = 0
self.shadowStepping = false
end
self.etherealStartTime = 0
self.etherealEndTime = 0
self.ethereal = false
self.landedAfterBlink = true
end
function Fade:OnInitialized()
Alien.OnInitialized(self)
self:SetModel(Fade.kModelName, kFadeAnimationGraph)
if Client then
self.blinkDissolve = 0
self:AddHelpWidget("GUIFadeBlinkHelp", 2)
self:AddHelpWidget("GUITunnelEntranceHelp", 1)
end
InitMixin(self, IdleMixin)
end
function Fade:GetShowElectrifyEffect()
return self.hasEtherealGate or self.electrified
end
function Fade:ModifyJump(input, velocity, jumpVelocity)
jumpVelocity:Scale(kFadeGravityMod)
end
function Fade:OnDestroy()
Alien.OnDestroy(self)
if Client then
self:DestroyTrailCinematic()
end
end
function Fade:GetControllerPhysicsGroup()
if self.isHallucination then
return PhysicsGroup.SmallStructuresGroup
end
return PhysicsGroup.BigPlayerControllersGroup
end
function Fade:GetInfestationBonus()
return kFadeInfestationSpeedBonus
end
function Fade:GetCarapaceSpeedReduction()
return kFadeCarapaceSpeedReduction
end
function Fade:GetCelerityArmorReduction()
return kFadeCelerityArmorReduction
end
function Fade:MovementModifierChanged(newMovementModifierState, input)
if newMovementModifierState and self:GetActiveWeapon() ~= nil then
local weaponMapName = self:GetActiveWeapon():GetMapName()
local metabweapon = self:GetWeapon(Metabolize.kMapName)
if metabweapon and not metabweapon:GetHasAttackDelay() and self:GetEnergy() >= metabweapon:GetEnergyCost() then
self:SetActiveWeapon(Metabolize.kMapName)
self:PrimaryAttack()
if weaponMapName ~= Metabolize.kMapName then
self.previousweapon = weaponMapName
end
end
end
end
function Fade:ModifyCrouchAnimation(crouchAmount)
return Clamp(crouchAmount * (1 - ( (self:GetVelocityLength() - kMaxSpeed) / (kMaxSpeed * 0.5))), 0, 1)
end
function Fade:GetHeadAttachpointName()
return "fade_tongue2"
end
-- Prevents reseting of celerity.
function Fade:OnSecondaryAttack()
end
function Fade:GetBaseArmor()
return Fade.kArmor
end
function Fade:GetBaseHealth()
return Fade.kHealth
end
function Fade:GetHealthPerBioMass()
return kFadeHealthPerBioMass
end
function Fade:GetArmorFullyUpgradedAmount()
return kFadeArmorFullyUpgradedAmount
end
function Fade:GetArmorCombinedAmount()
return kFadeCombinedArmor
end
function Fade:GetMaxViewOffsetHeight()
return kViewOffsetHeight
end
function Fade:GetViewModelName()
return self:GetVariantViewModel(self:GetVariant())
end
function Fade:GetCanStep()
return not self:GetIsBlinking()
end
function Fade:ModifyGravityForce(gravityTable)
if self:GetIsBlinking() or self:GetIsOnGround() then
gravityTable.gravity = 0
end
end
function Fade:GetPerformsVerticalMove()
return self:GetIsBlinking()
end
function Fade:GetAcceleration()
return 11
end
function Fade:GetGroundFriction()
return 9
end
function Fade:GetAirControl()
return 40
end
function Fade:GetAirFriction()
return (self:GetIsBlinking() or self:GetRecentlyShadowStepped()) and 0 or (0.17 - (GetHasCelerityUpgrade(self) and GetSpurLevel(self:GetTeamNumber()) or 0) * 0.01)
end
function Fade:ModifyVelocity(input, velocity, deltaTime)
if self:GetIsBlinking() then
local wishDir = self:GetViewCoords().zAxis
local maxSpeedTable = { maxSpeed = kBlinkSpeed }
self:ModifyMaxSpeed(maxSpeedTable, input)
local prevSpeed = velocity:GetLength()
local maxSpeed = math.max(prevSpeed, maxSpeedTable.maxSpeed)
local maxSpeed = math.min(25, maxSpeed)
velocity:Add(wishDir * kBlinkAcceleration * deltaTime)
if velocity:GetLength() > maxSpeed then
velocity:Normalize()
velocity:Scale(maxSpeed)
end
-- additional acceleration when holding down blink to exceed max speed
velocity:Add(wishDir * kBlinkAddAcceleration * deltaTime)
end
end
function Fade:GetIsStabbing()
local stabWeapon = self:GetWeapon(StabBlink.kMapName)
return stabWeapon and stabWeapon:GetIsStabbing()
end
function Fade:GetCanJump()
return self:GetIsOnGround() and not self:GetIsBlinking() and not self:GetIsStabbing()
end
function Fade:GetIsShadowStepping()
return false
end
function Fade:GetMaxSpeed(possible)
if possible then
return kMaxSpeed
end
if self:GetIsBlinking() then
return kBlinkSpeed
end
-- Take into account crouching.
return kMaxSpeed
end
function Fade:GetMass()
return kMass
end
function Fade:GetJumpHeight()
return kJumpHeight
end
function Fade:GetIsBlinking()
return self.ethereal and self:GetIsAlive()
end
function Fade:GetRecentlyBlinked(player)
return Shared.GetTime() - self.etherealEndTime < kMinEnterEtherealTime
end
function Fade:GetHasShadowStepAbility()
return self:GetHasOneHive()
end
function Fade:GetHasShadowStepCooldown()
return self.timeShadowStep + kShadowStepCooldown > Shared.GetTime()
end
function Fade:GetRecentlyShadowStepped()
return self.timeShadowStep + kShadowStepCooldown * 2 > Shared.GetTime()
end
function Fade:GetMovementSpecialTechId()
if self:GetCanMetabolizeHealth() then
return kTechId.MetabolizeHealth
else
return kTechId.MetabolizeEnergy
end
end
function Fade:GetHasMovementSpecial()
return self:GetHasOneHive()
end
function Fade:GetMovementSpecialEnergyCost()
return kMetabolizeEnergyCost
end
function Fade:GetCollisionSlowdownFraction()
return 0.05
end
function Fade:ModifyCelerityBonus(celerityBonus)
return celerityBonus - self:GetCarapaceMovementScalar()
end
function Fade:TriggerShadowStep(direction)
if not self:GetHasMovementSpecial() then
return
end
if direction:GetLength() == 0 then
direction.z = 1
end
--[[
if direction.z == 1 then
direction.x = 0
end
--]]
local movementDirection = self:GetViewCoords():TransformVector(direction)
movementDirection:Normalize()
if not self:GetIsBlinking() and not self:GetHasShadowStepCooldown() and self:GetEnergy() > kFadeShadowStepCost then
local celerityAddSpeed = (GetHasCelerityUpgrade(self) and GetSpurLevel(self:GetTeamNumber()) or 0) * 0.7
-- add small force in the direction we are stepping
local currentSpeed = movementDirection:DotProduct(self:GetVelocity())
local shadowStepStrength = math.max(currentSpeed, 11 + celerityAddSpeed) + 0.5
self:SetVelocity(movementDirection * shadowStepStrength * self:GetSlowSpeedModifier())
self.timeShadowStep = Shared.GetTime()
self.shadowStepSpeed = kShadowStepSpeed
self.shadowStepping = true
self.shadowStepDirection = Vector(movementDirection)
self:TriggerEffects("shadow_step", { effecthostcoords = Coords.GetLookIn(self:GetOrigin(), movementDirection) })
self:DeductAbilityEnergy(kFadeShadowStepCost)
self:TriggerUncloak()
end
end
function Fade:GetHasMetabolizeAnimationDelay()
return self.timeMetabolize + kMetabolizeAnimationDelay > Shared.GetTime()
end
function Fade:GetCanMetabolizeHealth()
return self:GetHasTwoHives()
end
function Fade:OverrideInput(input)
Alien.OverrideInput(self, input)
if self:GetIsBlinking() then
input.move.z = 1
input.move.x = 0
end
return input
end
function Fade:OnProcessMove(input)
Alien.OnProcessMove(self, input)
if Server then
if self.isScanned and self.timeLastScan + kFadeScanDuration < Shared.GetTime() then
self.isScanned = false
end
end
-- move without manipulating velocity
if self:GetIsShadowStepping() then
self.shadowStepSpeed = math.max(0, self.shadowStepSpeed - input.time * 90)
local completedMove, hitEntities, averageSurfaceNormal = self:PerformMovement(self.shadowStepDirection * self.shadowStepSpeed * input.time, 3)
local breakShadowStep = false
--stop when colliding with an enemy player
if hitEntities then
for _, entity in ipairs(hitEntities) do
if entity:isa("Player") and GetAreEnemies(self, entity) then
breakShadowStep = true
break
end
end
end
local enemyTeamNumber = GetEnemyTeamNumber(self:GetTeamNumber())
local function FilterFriendAndDead(entity)
return HasMixin(entity, "Team") and entity:GetTeamNumber() == enemyTeamNumber and HasMixin(entity, "Live") and entity:GetIsAlive()
end
-- trigger break when enemy player is nearby
if not breakShadowStep and self.shadowStepSpeed < 35 then
breakShadowStep = #Shared.GetEntitiesWithTagInRange("class:Player", self:GetOrigin(), 1.8, FilterFriendAndDead) > 0
end
if breakShadowStep then
self.shadowStepping = false
self.shadowStepSpeed = 0
local velocity = self:GetVelocity()
velocity.x = 0
velocity.z = 0
self:SetVelocity(velocity)
end
end
if not self:GetHasMetabolizeAnimationDelay() and self.previousweapon ~= nil then
self:SetActiveWeapon(self.previousweapon)
self.previousweapon = nil
end
end
function Fade:GetBlinkAllowed()
local weapons = self:GetWeapons()
for i = 1, #weapons do
if not weapons[i]:GetBlinkAllowed() then
return false
end
end
return true
end
function Fade:OnScan()
if Server then
self.timeLastScan = Shared.GetTime()
self.isScanned = true
end
end
function Fade:GetStepHeight()
if self:GetIsBlinking() then
return 2
end
return Player.GetStepHeight()
end
function Fade:SetDetected(state)
if Server then
if state then
self.timeLastScan = Shared.GetTime()
self.isScanned = true
else
self.isScanned = false
end
end
end
function Fade:OnUpdateAnimationInput(modelMixin)
if not self:GetHasMetabolizeAnimationDelay() then
Alien.OnUpdateAnimationInput(self, modelMixin)
if self.timeOfLastPhase + 0.5 > Shared.GetTime() then
modelMixin:SetAnimationInput("move", "teleport")
end
else
local weapon = self:GetActiveWeapon()
if weapon ~= nil and weapon.OnUpdateAnimationInput and weapon:GetMapName() == Metabolize.kMapName then
weapon:OnUpdateAnimationInput(modelMixin)
end
end
end
function Fade:TriggerBlink()
self.ethereal = true
self.landedAfterBlink = false
end
function Fade:OnBlinkEnd()
self.ethereal = false
end
function Fade:PostUpdateMove(input, runningPrediction)
if self.shadowStepSpeed == 0 then
self.shadowStepping = false
end
end
--[[
function Fade:ModifyAttackSpeed(attackSpeedTable)
attackSpeedTable.attackSpeed = attackSpeedTable.attackSpeed * 1.06
end
--]]
function Fade:GetEngagementPointOverride()
return self:GetOrigin() + Vector(0, 0.8, 0)
end
--[[
function Fade:ModifyHeal(healTable)
Alien.ModifyHeal(self, healTable)
healTable.health = healTable.health * 1.7
end
--]]
function Fade:OverrideVelocityGoal(velocityGoal)
if not self:GetIsOnGround() and self:GetCrouching() then
velocityGoal:Scale(0)
end
end
--[[
function Fade:HandleButtons(input)
Alien.HandleButtons(self, input)
if self:GetIsBlinking() then
input.commands = bit.bor(input.commands, Move.Crouch)
end
end
--]]
function Fade:OnGroundChanged(onGround, impactForce, normal, velocity)
Alien.OnGroundChanged(self, onGround, impactForce, normal, velocity)
if onGround then
self.landedAfterBlink = true
end
end
function Fade:GetMovementSpecialCooldown()
local cooldown = 0
local timeLeft = (Shared.GetTime() - self.timeMetabolize)
local metabolizeWeapon = self:GetWeapon(Metabolize.kMapName)
local metaDelay = metabolizeWeapon and metabolizeWeapon:GetAttackDelay() or 0
if timeLeft < metaDelay then
return 1 - Clamp(timeLeft / metaDelay, 0, 1)
end
return cooldown
end
Shared.LinkClassToMap("Fade", Fade.kMapName, networkVars, true)
|
--[[-----------------------------------------------------------------------------
ColorPicker Widget
-------------------------------------------------------------------------------]]
local Type, Version = "ColorPicker", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local pairs = pairs
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: ShowUIPanel, HideUIPanel, ColorPickerFrame, OpacitySliderFrame
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function ColorCallback(self, r, g, b, a, isAlpha)
if not self.HasAlpha then
a = 1
end
self:SetColor(r, g, b, a)
if ColorPickerFrame:IsVisible() then
--colorpicker is still open
self:Fire("OnValueChanged", r, g, b, a)
else
--colorpicker is closed, color callback is first, ignore it,
--alpha callback is the final call after it closes so confirm now
if isAlpha then
self:Fire("OnValueConfirmed", r, g, b, a)
end
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function ColorSwatch_OnClick(frame)
HideUIPanel(ColorPickerFrame)
local self = frame.obj
if not self.disabled then
ColorPickerFrame:SetFrameStrata("FULLSCREEN_DIALOG")
ColorPickerFrame:SetClampedToScreen(true)
ColorPickerFrame.func = function()
local r, g, b = ColorPickerFrame:GetColorRGB()
local a = 1 - OpacitySliderFrame:GetValue()
ColorCallback(self, r, g, b, a)
end
ColorPickerFrame.hasOpacity = self.HasAlpha
ColorPickerFrame.opacityFunc = function()
local r, g, b = ColorPickerFrame:GetColorRGB()
local a = 1 - OpacitySliderFrame:GetValue()
ColorCallback(self, r, g, b, a, true)
end
local r, g, b, a = self.r, self.g, self.b, self.a
if self.HasAlpha then
ColorPickerFrame.opacity = 1 - (a or 0)
end
ColorPickerFrame:SetColorRGB(r, g, b)
ColorPickerFrame.cancelFunc = function()
ColorCallback(self, r, g, b, a, true)
end
ShowUIPanel(ColorPickerFrame)
end
AceGUI:ClearFocus()
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetHeight(24)
self:SetWidth(200)
self:SetHasAlpha(false)
self:SetColor(0, 0, 0, 1)
self:SetDisabled(nil)
self:SetLabel(nil)
end,
-- ["OnRelease"] = nil,
["SetLabel"] = function(self, text)
self.text:SetText(text)
end,
["SetColor"] = function(self, r, g, b, a)
self.r = r
self.g = g
self.b = b
self.a = a or 1
self.colorSwatch:SetVertexColor(r, g, b, a)
end,
["SetHasAlpha"] = function(self, HasAlpha)
self.HasAlpha = HasAlpha
end,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if self.disabled then
self.frame:Disable()
self.text:SetTextColor(0.5, 0.5, 0.5)
else
self.frame:Enable()
self.text:SetTextColor(1, 1, 1)
end
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Button", nil, UIParent)
frame:Hide()
frame:EnableMouse(true)
frame:SetScript("OnEnter", Control_OnEnter)
frame:SetScript("OnLeave", Control_OnLeave)
frame:SetScript("OnClick", ColorSwatch_OnClick)
local colorSwatch = frame:CreateTexture(nil, "OVERLAY")
colorSwatch:SetWidth(19)
colorSwatch:SetHeight(19)
colorSwatch:SetTexture("Interface\\ChatFrame\\ChatFrameColorSwatch")
colorSwatch:SetPoint("LEFT")
local texture = frame:CreateTexture(nil, "BACKGROUND")
texture:SetWidth(16)
texture:SetHeight(16)
texture:SetTexture(1, 1, 1)
texture:SetPoint("CENTER", colorSwatch)
texture:Show()
local checkers = frame:CreateTexture(nil, "BACKGROUND")
checkers:SetWidth(14)
checkers:SetHeight(14)
checkers:SetTexture("Tileset\\Generic\\Checkers")
checkers:SetTexCoord(.25, 0, 0.5, .25)
checkers:SetDesaturated(true)
checkers:SetVertexColor(1, 1, 1, 0.75)
checkers:SetPoint("CENTER", colorSwatch)
checkers:Show()
local text = frame:CreateFontString(nil,"OVERLAY","GameFontHighlight")
text:SetHeight(24)
text:SetJustifyH("LEFT")
text:SetTextColor(1, 1, 1)
text:SetPoint("LEFT", colorSwatch, "RIGHT", 2, 0)
text:SetPoint("RIGHT")
--local highlight = frame:CreateTexture(nil, "HIGHLIGHT")
--highlight:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")
--highlight:SetBlendMode("ADD")
--highlight:SetAllPoints(frame)
local widget = {
colorSwatch = colorSwatch,
text = text,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
|
-- ref.: https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
local AM = torch.class("torch.AliasMultinomial")
function AM:__init(probs)
self.J, self.q = self:setup(probs)
end
function AM:setup(probs)
assert(probs:dim() == 1)
local K = probs:nElement()
local q = probs.new(K):zero()
local J = torch.LongTensor(K):zero()
-- Sort the data into the outcomes with probabilities
-- that are larger and smaller than 1/K.
local smaller, larger = {}, {}
local maxk, maxp = 0, -1
for kk = 1,K do
local prob = probs[kk]
q[kk] = K*prob
if q[kk] < 1 then
table.insert(smaller, kk)
else
table.insert(larger, kk)
end
if maxk > maxp then
end
end
-- Loop through and create little binary mixtures that
-- appropriately allocate the larger outcomes over the
-- overall uniform mixture.
while #smaller > 0 and #larger > 0 do
local small = table.remove(smaller)
local large = table.remove(larger)
J[small] = large
q[large] = q[large] - (1.0 - q[small])
if q[large] < 1.0 then
table.insert(smaller,large)
else
table.insert(larger,large)
end
end
assert(q:min() >= 0)
if q:max() > 1 then
q:div(q:max())
end
assert(q:max() <= 1)
if J:min() <= 0 then
-- sometimes an large index isn't added to J.
-- fix it by making the probability 1 so that J isn't indexed.
local i = 0
J:apply(function(x)
i = i + 1
if x <= 0 then
q[i] = 1
end
end)
end
return J, q
end
function AM:draw()
J = self.J
q = self.q
local K = J:nElement()
-- Draw from the overall uniform mixture.
local kk = math.random(1,K)
-- Draw from the binary mixture, either keeping the
-- small one, or choosing the associated larger one.
if math.random() < q[kk] then
return kk
else
return J[kk]
end
end
function AM:batchdraw(output)
assert(torch.type(output) == 'torch.LongTensor')
assert(output:nElement() > 0)
local J = self.J
local K = J:nElement()
self._kk = self._kk or output.new()
self._kk:resizeAs(output):random(1,K)
self._q = self._q or self.q.new()
self._q:index(self.q, 1, self._kk:view(-1))
self._mask = self._b or torch.LongTensor()
self._mask:resize(self._q:size()):bernoulli(self._q)
self.__kk = self.__kk or output.new()
self.__kk:resize(self._kk:size()):copy(self._kk)
self.__kk:cmul(self._mask)
-- if mask == 0 then output[i] = J[kk[i]] else output[i] = 0
self._mask:add(-1):mul(-1) -- (1,0) - > (0,1)
output:view(-1):index(J, 1, self._kk:view(-1))
output:cmul(self._mask)
-- elseif mask == 1 then output[i] = kk[i]
output:add(self.__kk)
return output
end
|
local nitro = true
local backfire = true
local dev = false
local time_after_finish_ms = 60000
local time_bef_start_s = 6
local car = 12
local plyvehs = {}
local checkpoints = {}
local finished = {}
local playerscheckpoints = {}
local lastclassement = {}
local notready = {}
local finishclassement = {}
local currace = {}
function createcheckpoints(mapname, idnb)
local id = tostring(idnb)
if checkpoints[id] then
for i,v in ipairs(checkpoints[id]) do
DestroyObject(v)
end
end
checkpoints[id] = {}
for i,v in ipairs(races[mapname]) do
if i+1 == #races[mapname] then
local obj = CreateObject(111111, races[mapname][i+1][1], races[mapname][i+1][2], races[mapname][i+1][3] , 0, races[mapname][i+1][4], 0, 1, 1, 1)
AddObjectInDimension(obj, idnb)
table.insert(checkpoints[id],obj)
else
if races[mapname][i+1] then
local obj = CreateObject(336, races[mapname][i+1][1], races[mapname][i+1][2], races[mapname][i+1][3] , 0, 0, 0, 10, 10, 10)
AddObjectInDimension(obj, idnb)
table.insert(checkpoints[id],obj)
end
end
end
end
function changerace(idnb, race_id)
local id = tostring(idnb)
finishclassement[id] = {}
notready[id] = {}
lastclassement[id] = {}
playerscheckpoints[id] = {}
plyvehs[id] = {}
currace[id] = race_id
createcheckpoints(racesnumbers[currace[id]], idnb)
for i,v in ipairs(GetDimensionPlayers(idnb)) do
if IsValidPlayer(v) then
local tbl = {}
tbl.ply = v
tbl.number = 1
table.insert(playerscheckpoints[id],tbl)
table.insert(notready[id],v)
SetPlayerSpawnLocation(v, spawns[racesnumbers[currace[id]]][i+1][1], spawns[racesnumbers[currace[id]]][i+1][2], spawns[racesnumbers[currace[id]]][i+1][3], spawns[racesnumbers[currace[id]]][1])
SetPlayerHealth(v, 0)
--CallRemoteEvent(v,"SpecRemoteEvent",false)
CallRemoteEvent(v,"classement_update",i,table_count(GetDimensionPlayers(idnb)),true)
end
end
end
--AddEvent("OnPlayerJoin", function(ply)
--SetPlayerSpawnLocation(ply, spawns[racesnumbers[currace]][2][1], spawns[racesnumbers[currace]][2][2], 0, spawns[racesnumbers[currace]][1])
--SetPlayerRespawnTime(ply, 500)
--if not checkpoints then
--changerace()
--end
--end)
function spawnveh(ply,id,first)
local did = GetPlayerDimension(ply)
local strid = tostring(did)
for i,v in ipairs(plyvehs[strid]) do
if v.ply == ply then
DestroyVehicle(v.vid)
table.remove(plyvehs[strid],i)
end
end
local px,py,pz = GetPlayerLocation(ply)
local h = GetPlayerHeading(ply)
local veh = CreateVehicle(id, px, py, pz , h)
SetVehicleLicensePlate(veh, "RACING")
SetVehicleRespawnParams(veh, false)
AttachVehicleNitro(veh, nitro)
EnableVehicleBackfire(veh, backfire)
AddVehicleInDimension(veh, did)
local tbin = {}
tbin.ply = ply
tbin.vid = veh
tbin.vhp = GetVehicleHealth(veh)
table.insert(plyvehs[strid],tbin)
if first == true then
local ping = GetPlayerPing(ply)
if ping == 0 then
ping = 50
else
ping=ping*6
end
Delay(ping,function()
SetPlayerInVehicle(ply, veh)
end)
else
SetPlayerInVehicle(ply, veh)
end
end
AddEvent("OnPlayerSpawnRacing", function(ply)
local idnb = GetPlayerDimension(ply)
local id = tostring(idnb)
local found = false
for i,v in ipairs(playerscheckpoints[id]) do
if v.ply == ply then
found=true
spawnveh(ply,car,true)
end
end
if not found then
for i,v in ipairs(playerscheckpoints[id]) do
local ping = GetPlayerPing(ply)
if ping == 0 then
ping = 50
else
ping=ping*6
end
for i,v in ipairs(playerscheckpoints[id]) do
CallRemoteEvent(v.ply,"startlookingforafk")
end
Delay(ping,function()
speclogic(ply,playerscheckpoints[id][i].ply)
end)
break
end
end
end)
AddEvent("OnPlayerLeaveVehicleRacing",function(ply,veh,seat)
local idnb = GetPlayerDimension(ply)
local id = tostring(idnb)
if GetPlayerPropertyValue(ply,"leaving")==nil then
if GetPlayerPropertyValue(ply,"leavingtospec")==nil then
spawnveh(ply,car)
else
for i,v in ipairs(plyvehs[id]) do
if v.ply == ply then
DestroyVehicle(v.vid)
table.remove(plyvehs[id],i)
local ping = GetPlayerPing(ply)
if ping == 0 then
ping = 50
else
ping=ping*6
end
Delay(ping,function()
for i,v in ipairs(playerscheckpoints[id]) do
speclogic(ply,playerscheckpoints[id][i].ply)
break
end
end)
end
end
SetPlayerPropertyValue(ply,"leavingtospec",nil,false)
end
end
end)
AddEvent("OnPlayerQuitRacing",function(ply, idnb, leave)
--local idnb = GetPlayerDimension(ply)
--print(idnb)
if not leave then
CallRemoteEvent(ply,"SpecRemoteEvent",false)
end
local id = tostring(idnb)
for i,v in ipairs(plyvehs[id]) do
if v.ply == ply then
SetPlayerPropertyValue(ply,"leaving",true,false)
DestroyVehicle(v.vid)
table.remove(plyvehs[id],i)
end
end
for i,v in ipairs(playerscheckpoints[id]) do
if v.ply == ply then
table.remove(playerscheckpoints[id],i)
end
end
for i,v in ipairs(finishclassement[id]) do
if v == ply then
table.remove(finishclassement[id],i)
end
end
for ilc,vlc in ipairs(lastclassement[id]) do
if vlc.ply == ply then
table.remove(lastclassement[id],ilc)
end
end
if #playerscheckpoints[id]>0 then
for i,v in ipairs(notready[id]) do
if v==ply then
if #notready[id]<=1 then
for i,v in ipairs(playerscheckpoints[id]) do
CallRemoteEvent(v.ply,"checkpointstbl",races[racesnumbers[currace[id]]],time_bef_start_s)
end
end
table.remove(notready[id],i)
end
end
end
if (IsValidDimension(idnb) and table_count(GetDimensionPlayers(idnb))>1) then
if #playerscheckpoints[id] == 0 then
Delay(250,function() -- wait some time so GetAllPlayers and GetPlayerCount won't return this player
checktorestart(idnb)
end)
end
--elseif checkpoints[id] then
--for i,v in ipairs(checkpoints[id]) do
--DestroyObject(v)
--end
--checkpoints[id] = nil
end
end)
function checktorestart(idnb)
local id = tostring(idnb)
if #playerscheckpoints[id] == 0 then
-- finish race
--print("race finished")
--print(tostring(idnb) .. " " .. type(idnb))
for i,v in ipairs(GetDimensionPlayers(idnb)) do
if IsValidPlayer(v) then
CallRemoteEvent(v,"Start_finish_timer",time_after_finish_ms,true)
CallRemoteEvent(v,"SpecRemoteEvent",false)
end
end
if checkpoints[id] then
for i,v in ipairs(checkpoints[id]) do
DestroyObject(v)
end
end
for i,v in ipairs(plyvehs[id]) do
if IsValidVehicle(v.vid) then
SetPlayerPropertyValue(v.ply, "leaving", true, false)
RemovePlayerFromVehicle(v.ply)
Delay(600, function()
DestroyVehicle(v.vid)
SetPlayerPropertyValue(v.ply, "leaving", nil, false)
end)
end
end
finished[id] = true
CallEvent("OnRaceFinished", idnb, finishclassement[id], lastclassement[id])
finishclassement[id] = {}
notready[id] = {}
lastclassement[id] = {}
playerscheckpoints[id] = {}
plyvehs[id] = {}
checkpoints[id] = {}
--[[
if #racesnumbers==currace then
currace=1
changerace()
else
currace=currace+1
changerace()
end]]--
else
if #finishclassement[id]==1 then
for i,v in ipairs(GetDimensionPlayers(idnb)) do
CallRemoteEvent(v,"Start_finish_timer",time_after_finish_ms,false)
end
finished[id] = false
Delay(time_after_finish_ms,function()
if finished[id] == false then
playerscheckpoints[id]={}
checktorestart(idnb)
end
end)
end
end
end
function timercheck()
for k,uh in pairs(playerscheckpoints) do
for i,v in ipairs(uh) do
if GetPlayerVehicle(v.ply)~=0 then
local veh = GetPlayerVehicle(v.ply)
if IsValidVehicle(veh) then
for i2,vc in ipairs(checkpoints[k]) do
if i2+1==v.number+1 then
local x,y,z = GetVehicleLocation(veh)
if z>0 then
if GetDistance2D(x, y, races[racesnumbers[currace[k]]][i2+1][1], races[racesnumbers[currace[k]]][i2+1][2])<750 then
v.number=i2+1
local vh = GetVehicleHeading(GetPlayerVehicle(v.ply))
SetPlayerSpawnLocation(v.ply, x, y, z+200, vh)
CallRemoteEvent(v.ply,"hidecheckpoint",vc)
local place = 0
if i2 == #checkpoints[k] then
table.insert(finishclassement[k],v.ply)
place = #finishclassement[k]
CallRemoteEvent(v.ply,"classement_update",place,table_count(GetDimensionPlayers(tonumber(k))))
table.remove(playerscheckpoints[k],i)
for ilc,vlc in ipairs(lastclassement[k]) do
if vlc.ply == v.ply then
table.remove(lastclassement[k],ilc)
end
end
if #playerscheckpoints[k]>0 then
SetPlayerPropertyValue(v.ply,"leavingtospec",true,false)
RemovePlayerFromVehicle(v.ply)
end
checktorestart(tonumber(k))
end
end
else
SetPlayerHealth(v.ply, 0)
end
end
end
end
end
end
end
for k,uh in pairs(plyvehs) do
for i,v in ipairs(uh) do
if IsValidVehicle(v.vid) then
if v.vhp > GetVehicleHealth(v.vid) then
SetVehicleHealth(v.vid, v.vhp)
SetVehicleDamage(v.vid, 1, 0.0)
SetVehicleDamage(v.vid, 2, 0.0)
SetVehicleDamage(v.vid, 3, 0.0)
SetVehicleDamage(v.vid, 4, 0.0)
SetVehicleDamage(v.vid, 5, 0.0)
SetVehicleDamage(v.vid, 6, 0.0)
SetVehicleDamage(v.vid, 7, 0.0)
SetVehicleDamage(v.vid, 8, 0.0)
end
end
end
end
for k, v in pairs(GetAllDimensions()) do
if v.name == "racing" then
for i,v in ipairs(GetDimensionPlayers(k)) do
if GetPlayerVehicle(v)~=0 then
local veh = GetPlayerVehicle(v)
if (IsValidVehicle(veh) and finishclassement[tostring(k)]) then
local place = #finishclassement[tostring(k)]+1
local pnumber = nil
local pindex = nil
for ic,vc in ipairs(playerscheckpoints[tostring(k)]) do
if vc.ply == v then
pnumber = vc.number
pindex = ic
end
end
if pnumber~=nil then
for ic,vc in ipairs(playerscheckpoints[tostring(k)]) do
if vc.ply ~= v then
if GetPlayerVehicle(vc.ply)~=0 then
local pveh = GetPlayerVehicle(vc.ply)
if IsValidVehicle(pveh) then
if vc.number > pnumber then
place = place+1
elseif vc.number == pnumber then
local x1,y1,z1 = GetVehicleLocation(veh)
local dist1 = GetDistance2D(x1, y1, races[racesnumbers[currace[tostring(k)]]][pnumber+1][1], races[racesnumbers[currace[tostring(k)]]][pnumber+1][2])
local x2,y2,z2 = GetVehicleLocation(pveh)
local dist2 = GetDistance2D(x2, y2, races[racesnumbers[currace[tostring(k)]]][pnumber+1][1], races[racesnumbers[currace[tostring(k)]]][pnumber+1][2])
if dist1>dist2 then
place=place+1
end
end
end
end
end
end
local lastpl = 0
for ilc,vlc in ipairs(lastclassement[tostring(k)]) do
if vlc.ply == v then
lastpl = vlc.lplace
table.remove(lastclassement[tostring(k)],ilc)
end
end
if place ~= lastpl then
local lc = {}
lc.ply = v
lc.lplace = place
table.insert(lastclassement[tostring(k)],lc)
CallRemoteEvent(v,"classement_update",place,table_count(GetDimensionPlayers(k)))
end
end
end
end
end
end
end
end
AddEvent("OnPackageStart",function()
CreateTimer(timercheck, 50)
if dev then
print("DEV MODE ACTIVATED FOR " .. GetPackageName())
end
end)
AddRemoteEvent("returncar_racing",function(ply)
local veh = GetPlayerVehicle(ply)
if IsValidVehicle(veh) then
local rx,ry,rz = GetVehicleRotation(veh)
SetVehicleRotation(veh, 0,ry,0)
end
end)
AddCommand("race",function(ply,id)
if dev then
if id ~= nil then
currace=tonumber(id)
playerscheckpoints={}
changerace()
end
end
end)
AddRemoteEvent("changespec",function(ply,spectated)
local idnb = GetPlayerDimension(ply)
local id = tostring(idnb)
if #playerscheckpoints[id]>0 then
local lookindex = false
local found = false
local compt = 0
for i,v in ipairs(playerscheckpoints[id]) do
if lookindex then
speclogic(ply,v.ply)
break
end
compt=compt+1
if v.ply==spectated then
found = true
if compt==#playerscheckpoints[id] then
for i,v in ipairs(playerscheckpoints[id]) do
speclogic(ply,playerscheckpoints[id][i].ply)
break
end
else
lookindex=true
end
end
end
if not found then
for i,v in ipairs(playerscheckpoints[id]) do
speclogic(ply,playerscheckpoints[id][i].ply)
break
end
end
end
end)
function speclogic(cmdply,ply)
AddPlayerChat(cmdply,"You are spectating " .. GetPlayerName(ply))
local x, y, z = GetPlayerLocation(ply)
CallRemoteEvent(cmdply,"SpecRemoteEvent",true,ply,x,y,z)
end
AddRemoteEvent("last_checkpoint",function(ply)
local idnb = GetPlayerDimension(ply)
local id = tostring(idnb)
for i,v in ipairs(playerscheckpoints[id]) do
if v.ply == ply then
if v.number == 1 then
SetPlayerHealth(ply,0)
else
local veh = GetPlayerVehicle(ply)
local rx,ry,rz = GetVehicleRotation(veh)
SetVehicleRotation(veh, 0,ry,0)
SetVehicleLinearVelocity(veh, 0, 0, 0 ,true)
SetVehicleAngularVelocity(veh, 0, 0, 0 ,true)
SetVehicleLocation(veh,races[racesnumbers[currace[id]]][v.number][1], races[racesnumbers[currace[id]]][v.number][2], races[racesnumbers[currace[id]]][v.number][3] + 200)
end
end
end
end)
AddCommand("showspawns",function(ply)
if dev then
for i,v in ipairs(spawns[racesnumbers[currace]]) do
if i > 1 then
CreateObject(1363, v[1], v[2], v[3] , 0, spawns[racesnumbers[currace]][1], 0, 1, 1, 1)
end
end
end
end)
AddRemoteEvent("imafk",function(ply)
KickPlayer(ply,"Afk")
end)
local locktimer = nil
local lockyaw = nil
function refreshyaw(ply)
if IsValidPlayer(ply) then
local veh = GetPlayerVehicle(ply)
local rx,ry,rz = GetVehicleRotation(veh)
if veh~=0 then
SetVehicleRotation(veh,rx,lockyaw,rz)
end
else
DestroyTimer(locktimer)
locktimer = nil
localyaw = nil
end
end
AddCommand("lockyaw",function(ply,yaw)
if dev then
if yaw then
yaw = tonumber(yaw)
lockyaw=yaw
if locktimer then
DestroyTimer(locktimer)
end
locktimer = CreateTimer(refreshyaw,1000,ply)
local veh = GetPlayerVehicle(ply)
local rx,ry,rz = GetVehicleRotation(veh)
if veh~=0 then
SetVehicleRotation(veh,rx,lockyaw,rz)
end
else
if locktimer then
DestroyTimer(locktimer)
locktimer = nil
localyaw = nil
end
end
end
end)
AddRemoteEvent("Readytostart",function(ply)
local idnb = GetPlayerDimension(ply)
local id = tostring(idnb)
for i,v in ipairs(notready[id]) do
if v==ply then
if table_count(notready[id])<=1 then
for i,v in ipairs(playerscheckpoints[id]) do
CallRemoteEvent(v.ply,"checkpointstbl",races[racesnumbers[currace[id]]],time_bef_start_s)
end
end
table.remove(notready[id],i)
end
end
end)
|
local class = require 'middleclass'
local Scene = require 'scene'
local MainMenu = class('MainMenu', Scene)
function MainMenu:initialize(manager)
Scene.initialize(self, manager)
end
function MainMenu:onLoad()
self.fontTitle = love.graphics.newFont('assets/neuropol.ttf', 48)
self.fontText = love.graphics.newFont('assets/neuropol.ttf', 24)
self.title = love.graphics.newText(self.fontTitle, 'WEXD')
self.text1 = love.graphics.newText(self.fontText, 'Press any key to start')
self:start()
end
function MainMenu:update(dt)
if self.currentState ~= 'running' then
return
end
end
function MainMenu:draw()
if self.currentState ~= 'running' then
return
end
local wh = love.graphics:getHeight()
local ww = love.graphics:getWidth()
love.graphics.draw(self.title, ww / 2 - self.title:getWidth() / 2, wh / 2 - self.title:getHeight() / 2)
love.graphics.draw(self.text1, ww / 2 - self.text1:getWidth() / 2, wh / 2 - self.text1:getHeight() / 2 + 40)
end
function MainMenu:keyreleased(key)
self.manager:replaceScene('level-1')
end
return function(manager)
return MainMenu:new(manager)
end
|
-- This is a part of uJIT's testing suite.
-- Copyright (C) 2020-2021 LuaVela Authors. See Copyright Notice in COPYRIGHT
-- Copyright (C) 2015-2020 IPONWEB Ltd. See Copyright Notice in COPYRIGHT
jit.off()
local tests = {}
local function assert_immutable_nyi_type(obj)
local status, errmsg = pcall(ujit.immutable, obj)
assert(status == false)
assert(string.match(errmsg, "attempt to make immutable"))
end
local function assert_modification_error(...)
local status, errmsg = pcall(...)
assert(status == false)
assert(string.match(errmsg, "attempt to modify .+ object$"))
end
function tests.immutable_types()
-- Values below are immutable per se, a no-op behaviour expected:
assert(ujit.immutable() == nil)
assert(ujit.immutable(nil) == nil)
assert(ujit.immutable(false) == false)
assert(ujit.immutable(true) == true)
assert(ujit.immutable(4.2) == 4.2)
assert(ujit.immutable(1/0) == 1/0)
assert(ujit.immutable("") == "")
assert(ujit.immutable("xxx") == "xxx")
assert(ujit.immutable(io.stdout) == io.stdout)
assert(type(io.stdout) == "userdata")
-- any function is a no-op:
local upvalue = 0
local foo1 = function (x, y)
return x + y
end
local foo2 = function (x, y)
upvalue = upvalue + 1
return upvalue > 100 and x + y or x - y
end
assert(ujit.immutable(foo1) == foo1)
assert(ujit.immutable(foo2) == foo2)
assert(type(pairs) == "function" and ujit.immutable(pairs) == pairs)
end
function tests.immutable_nyi_types()
-- coroutine
local co = coroutine.create(function() end)
assert(type(co) == "thread")
assert_immutable_nyi_type(co)
-- cdata
local has_ffi, ffi = pcall(require, "ffi")
if has_ffi then
local cdata = ffi.new("uint64_t")
assert(type(cdata) == "cdata")
assert_immutable_nyi_type(cdata)
end
end
function tests.immutable_tables_basic()
local mutator_tsets = function (t) t.k = "v" end
local mutator_tsetb = function (t) t[1] = "v" end
local mutator_tsetv = function (t) local k = "k"; t[k] = "v" end
local mutator_raw = function (t) rawset(t, "k", "v") end
local t1 = ujit.immutable{}
assert_modification_error(mutator_tsets, t1)
assert_modification_error(mutator_tsetb, t1)
assert_modification_error(mutator_tsetv, t1)
assert_modification_error(mutator_raw, t1)
local t2 = ujit.immutable{ nested = {} }
assert_modification_error(mutator_tsets, t2.nested)
assert_modification_error(mutator_tsetb, t2.nested)
assert_modification_error(mutator_tsetv, t2.nested)
assert_modification_error(mutator_raw, t2.nested)
local t3 = ujit.immutable{ nested = { nested = {} } }
assert_modification_error(mutator_tsets, t3.nested.nested)
assert_modification_error(mutator_tsetb, t3.nested.nested)
assert_modification_error(mutator_tsetv, t3.nested.nested)
assert_modification_error(mutator_raw, t3.nested.nested)
local t4 = ujit.immutable(ujit.immutable(ujit.immutable{
[true] = true,
[false] = false,
[42] = 4.2,
["xxx"] = "xxx",
}))
assert(type(t4) == "table")
end
function tests.immutable_iterable_pairs()
local t1 = ujit.immutable{
foo = "bar",
baz = 42,
}
local t2 = {}
local n = 0
assert(t1.foo == "bar")
assert(t1.baz == 42)
for k, v in pairs(t1) do
n = n + 1
t2[k] = v
end
assert(n == 2)
assert(t2.foo == t1.foo)
assert(t2.baz == t1.baz)
end
function tests.immutable_iterable_ipairs()
local t1 = ujit.immutable{10, 20, 30}
local t2 = {}
assert(t1[1] == 10)
assert(t1[2] == 20)
assert(t1[3] == 30)
for k, v in ipairs(t1) do
t2[k] = v
end
assert(#t1 == #t2)
assert(t2[1] == t1[1])
assert(t2[2] == t1[2])
assert(t2[3] == t1[3])
end
function tests.immutable_iterable_next()
local k, v
local t = {}
k, v = next(ujit.immutable{foo = "bar"})
assert(k == "foo")
assert(v == "bar")
k, v = next(ujit.immutable{[1] = "foo"})
assert(k == 1)
assert(v == "foo")
k, v = next(ujit.immutable{[t] = t})
assert(k == t)
assert(v == t)
end
function tests.immutable_recursive()
local function mutator(tbl, key, value) tbl[key] = value end
local t1 = {}
t1.t1 = t1
ujit.immutable(t1)
assert(t1.t1 == t1)
assert_modification_error(mutator, t1, "t1", "t1")
end
local function assert_mutable(t, exp_level, exp_oops_type)
local t1 = t
local level = 0
while t1.nested ~= nil do
t1.foo = "bar"
t1 = t1.nested
level = level + 1
end
assert(level == exp_level)
assert(type(t1.oops) == exp_oops_type)
end
function tests.immutable_tables_nyi_types()
local t1 = {
nested = {
nested = {
nested = {
nested = {
oops = coroutine.create(function() end),
},
},
},
},
}
assert_immutable_nyi_type(t1)
assert_mutable(t1, 4, "thread")
end
function tests.immutable_unmarking()
-- NB! This test relies on the order in which table elements are traversed.
-- If we encounter an error in-between marking immutable (iteration 2),
-- we must be able to unmark the *entire* object.
local c = coroutine.create(function() end)
local t = {
-- Iteration# Marked? Success? Unmarked?
{}, -- 1 YES YES YES
c, -- 2 YES NO NO
{}, -- 3 NO N/A YES
}
local status = pcall(ujit.immutable, t)
assert(status == false)
end
-- An immutable object t1 gets referenced from a mutable object t2, which cannot
-- be made immutable. After that, t1 and t2 should preserve their states:
-- t1 should still be immutable, and t2 should still be mutable.
function tests.immutable_consistency()
local mutator = function (t, k, v) t[k] = v end
local t1 = ujit.immutable{}
local t2 = {
nested = {
nested = {
t1 = t1,
oops = coroutine.create(function() end),
},
},
}
assert_modification_error(mutator, t1, "foo", "bar")
assert_immutable_nyi_type(t2)
assert_mutable(t2, 2, "thread")
assert_modification_error(mutator, t1, "foo", "bar")
end
function tests.ok_copying_immutable()
local t1 = ujit.immutable{
k = "v",
}
local t2 = {}
for k, _ in pairs(t1) do
t2[k] = t1[k]
end
assert(t2.k == "v")
t2.k = "v"
t2.K = "V"
end
function tests.metatable_immutability()
local mutator = function (t, k, v) t[k] = v end
local mt = {
__index = function(_, k)
return k
end,
__newindex = function (_, _, _)
error("Unreachable")
end
}
local t1 = ujit.immutable(setmetatable({}, mt))
assert(t1.foo == "foo")
assert(t1[true] == true)
-- table itself is immutable:
assert_modification_error(mutator, t1, "k", "v")
-- metatable is immutable, too:
assert_modification_error(mutator, mt, "k", "v")
end
function tests.error_on_setmetatable()
local mt = {}
assert_modification_error(setmetatable, ujit.immutable{}, mt)
end
function tests.error_on_debug_setmetatable()
local t1 = ujit.immutable{}
assert_modification_error(debug.setmetatable, t1, {})
end
function tests.error_on_table_sort()
local t1 = ujit.immutable{5, 3, 14}
assert_modification_error(table.sort, t1)
end
function tests.error_on_table_insert()
local t1 = ujit.immutable{5, 3, 14}
assert_modification_error(table.insert, t1, 'foo') -- push_back
assert_modification_error(table.insert, t1, 2, 'foo') -- insert
end
function tests.error_on_table_remove()
local t1 = ujit.immutable{5, 3, 14}
assert_modification_error(table.remove, t1, 2) -- remove
assert_modification_error(table.remove, t1, 3) -- pop_back
end
-- A k-weak table referencing an immutable object should not
-- preserve corresponding key-value pair over GC cycle.
function tests.sweeping_weak_keys()
local kweak = setmetatable({ [{}] = ujit.immutable{} }, {__mode = 'k'})
assert(next(kweak) ~= nil)
collectgarbage()
assert(next(kweak) == nil)
end
-- A v-weak table referencing an immutable object should not
-- preserve corresponding key-value pair over GC cycle.
function tests.sweeping_weak_values()
local vweak = setmetatable({ x = ujit.immutable{y = 42} }, {__mode = 'v'})
assert(vweak.x.y == 42)
collectgarbage()
assert(vweak.x == nil)
end
-- If a table is made immutable, it will be sealed.
function tests.seal()
local t = ujit.immutable{
foo = {
bar = {
baz = "qux"
}
}
}
ujit.seal(t)
end
for k, v in pairs(tests) do
if (type(k) == 'string' and type(v) == 'function')
then
v()
end
end
|
local value = event.getvalue()
local address = event.dst
local message = ""
if value == true then
message = "Fancoil " .. address .. " gikk INN i alarm.\nDato/Tid: " .. os.date()
else
message = "Fancoil " .. address .. " gikk UT av alarm.\nDato/Tid: " .. os.date()
end
local username = 'GMAIL_USERNAME'
local password = 'GMAIL_PASSWORD'
require("user.alert")
Alert:construct(username, password)
Alert:setSubject("Alert Fancoil")
Alert:setMessage(message)
Alert:send("[email protected]")
|
return {
id = 3004,
value = "any",
}
|
if not modules then modules = { } end modules ['mult-aux'] = {
version = 1.001,
comment = "companion to mult-aux.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
local find = string.find
interfaces.namespaces = interfaces.namespaces or { }
local namespaces = interfaces.namespaces
local variables = interfaces.variables
local context = context
local trace_namespaces = false trackers.register("interfaces.namespaces", function(v) trace_namespaces = v end)
local report_namespaces = logs.reporter("interface","namespaces")
local v_yes, v_list = variables.yes, variables.list
local prefix = "????"
local meaning = "@@@@"
local data = { }
function namespaces.define(namespace,settings)
if trace_namespaces then
report_namespaces("installing namespace %a with settings %a",namespace,settings)
end
if data[namespace] then
report_namespaces("namespace %a is already taken",namespace)
end
if #namespace < 2 then
report_namespaces("namespace %a should have more than 1 character",namespace)
end
local ns = { }
data[namespace] = ns
utilities.parsers.settings_to_hash(settings,ns)
local name = ns.name
if not name or name == "" then
report_namespaces("provide a (command) name in namespace %a",namespace)
end
local self = "\\" .. prefix .. namespace
context.unprotect()
-- context.installnamespace(namespace)
context("\\def\\%s%s{%s%s}",prefix,namespace,meaning,namespace) -- or context.setvalue
if trace_namespaces then
report_namespaces("using namespace %a for %a",namespace,name)
end
local parent = ns.parent or ""
if parent ~= "" then
if trace_namespaces then
report_namespaces("namespace %a for %a uses parent %a",namespace,name,parent)
end
if not find(parent,"\\",1,true) then
parent = "\\" .. prefix .. parent
-- todo: check if defined
end
end
context.installparameterhandler(self,name)
if trace_namespaces then
report_namespaces("installing parameter handler for %a",name)
end
context.installparameterhashhandler(self,name)
if trace_namespaces then
report_namespaces("installing parameterhash handler for %a",name)
end
local style = ns.style
if style == v_yes then
context.installstyleandcolorhandler(self,name)
if trace_namespaces then
report_namespaces("installing attribute handler for %a",name)
end
end
local command = ns.command
if command == v_yes then
context.installdefinehandler(self,name,parent)
if trace_namespaces then
report_namespaces("installing definition command for %a (single)",name)
end
elseif command == v_list then
context.installdefinehandler(self,name,parent)
if trace_namespaces then
report_namespaces("installing definition command for %a (multiple)",name)
end
end
local setup = ns.setup
if setup == v_yes then
context.installsetuphandler(self,name)
if trace_namespaces then
report_namespaces("installing setup command for %a (%s)",name,"single")
end
elseif setup == v_list then
context.installsetuphandler(self,name)
if trace_namespaces then
report_namespaces("installing setup command for %a (%s)",name,"multiple")
end
end
local set = ns.set
if set == v_yes then
context.installparametersethandler(self,name)
if trace_namespaces then
report_namespaces("installing set/let/reset command for %a (%s)",name,"single")
end
elseif set == v_list then
context.installparametersethandler(self,name)
if trace_namespaces then
report_namespaces("installing set/let/reset command for %a (%s)",name,"multiple")
end
end
local frame = ns.frame
if frame == v_yes then
context.installinheritedframed(name)
if trace_namespaces then
report_namespaces("installing framed command for %a",name)
end
end
context.protect()
end
function utilities.formatters.list(data,key,keys)
if not keys then
keys = { }
for _, v in next, data do
for k, _ in next, v do
keys[k] = true
end
end
keys = table.sortedkeys(keys)
end
context.starttabulate { "|"..string.rep("l|",#keys+1) }
context.NC()
context(key)
for i=1,#keys do
context.NC()
context(keys[i])
end context.NR()
context.HL()
for k, v in table.sortedhash(data) do
context.NC()
context(k)
for i=1,#keys do
context.NC()
context(v[keys[i]])
end context.NR()
end
context.stoptabulate()
end
function namespaces.list()
-- utilities.formatters.list(data,"namespace")
local keys = { "type", "name", "comment", "version", "parent", "definition", "setup", "style" }
utilities.formatters.list(data,"namespace",keys)
end
interfaces.implement {
name = "definenamespace",
arguments = { "string", "string" },
actions = namespaces.define
}
interfaces.implement {
name = "listnamespaces",
actions = namespaces.list
}
|
---@meta
---@class cc.Sprite3D :cc.Node@all parent class: Node,BlendProtocol
local Sprite3D={ }
cc.Sprite3D=Sprite3D
---*
---@param enable boolean
---@return self
function Sprite3D:setCullFaceEnabled (enable) end
---@overload fun(string0:cc.Texture2D):self
---@overload fun(string:string):self
---@param texFile string
---@return self
function Sprite3D:setTexture (texFile) end
---*
---@return unsigned_int
function Sprite3D:getLightMask () end
---* Adds a new material to a particular mesh of the sprite.<br>
---* meshIndex is the mesh that will be applied to.<br>
---* if meshIndex == -1, then it will be applied to all the meshes that belong to the sprite.
---@param meshIndex int
---@return cc.Material
function Sprite3D:getMaterial (meshIndex) end
---*
---@param side int
---@return self
function Sprite3D:setCullFace (side) end
---* Get meshes used in sprite 3d
---@return array_table
function Sprite3D:getMeshes () end
---* remove all attach nodes
---@return self
function Sprite3D:removeAllAttachNode () end
---@overload fun(cc.Material:cc.Material,int:int):self
---@overload fun(cc.Material:cc.Material):self
---@param material cc.Material
---@param meshIndex int
---@return self
function Sprite3D:setMaterial (material,meshIndex) end
---* get mesh
---@return cc.Mesh
function Sprite3D:getMesh () end
---* get mesh count
---@return int
function Sprite3D:getMeshCount () end
---* get Mesh by index
---@param index int
---@return cc.Mesh
function Sprite3D:getMeshByIndex (index) end
---*
---@return boolean
function Sprite3D:isForceDepthWrite () end
---*
---@return cc.BlendFunc
function Sprite3D:getBlendFunc () end
---* light mask getter & setter, light works only when _lightmask & light's flag is true, default value of _lightmask is 0xffff
---@param mask unsigned_int
---@return self
function Sprite3D:setLightMask (mask) end
---* get AttachNode by bone name, return nullptr if not exist
---@param boneName string
---@return cc.AttachNode
function Sprite3D:getAttachNode (boneName) end
---*
---@param blendFunc cc.BlendFunc
---@return self
function Sprite3D:setBlendFunc (blendFunc) end
---* force set this Sprite3D to 2D render queue
---@param force2D boolean
---@return self
function Sprite3D:setForce2DQueue (force2D) end
---* generate default material
---@return self
function Sprite3D:genMaterial () end
---* remove attach node
---@param boneName string
---@return self
function Sprite3D:removeAttachNode (boneName) end
---*
---@return cc.Skeleton3D
function Sprite3D:getSkeleton () end
---* Force to write to depth buffer, this is useful if you want to achieve effects like fading.
---@param value boolean
---@return self
function Sprite3D:setForceDepthWrite (value) end
---* get Mesh by Name, it returns the first one if there are more than one mesh with the same name
---@param name string
---@return cc.Mesh
function Sprite3D:getMeshByName (name) end
---@overload fun(string:string):self
---@overload fun():self
---@overload fun(string:string,string:string):self
---@param modelPath string
---@param texturePath string
---@return self
function Sprite3D:create (modelPath,texturePath) end
---* draw
---@param renderer cc.Renderer
---@param transform mat4_table
---@param flags unsigned_int
---@return self
function Sprite3D:draw (renderer,transform,flags) end
---* Executes an action, and returns the action that is executed. For Sprite3D special logic are needed to take care of Fading.<br>
---* This node becomes the action's target. Refer to Action::getTarget()<br>
---* warning Actions don't retain their target.<br>
---* return An Action pointer
---@param action cc.Action
---@return cc.Action
function Sprite3D:runAction (action) end
---* set ProgramState, you should bind attributes by yourself
---@param programState cc.backend.ProgramState
---@return self
function Sprite3D:setProgramState (programState) end
---* Returns 2d bounding-box<br>
---* Note: the bounding-box is just get from the AABB which as Z=0, so that is not very accurate.
---@return rect_table
function Sprite3D:getBoundingBox () end
|
local awful = require('awful')
local hotkeys_popup = require('awful.hotkeys_popup')
require('awful.hotkeys_popup.keys')
local join = require('gears.table').join
local menu_position = require('utils.common').menus.get_position
local tag_edit = require('utils.tag_editor')
local default_modkeys = {
super = 'Mod4',
ctrl = 'Control',
shift = 'Shift',
alt = 'Mod1',
}
local user_mod = require('config.modkeys')
local mod = join(default_modkeys, user_mod)
local default_vars = {
mouse_snap_edge = true,
mouse_snap_client = true,
}
local user_vars = require('config.vars')
local vars = join(default_vars, user_vars)
local default_apps = {
terminal = 'xterm',
}
local user_apps = require('config.apps')
local apps = join(default_apps, user_apps)
--- Mouse options
awful.mouse.snap.edge_enabled = vars.mouse_snap_edge
awful.mouse.snap.client_enabled = vars.mouse_snap_client
---- Global: core
awful.keyboard.append_global_keybindings({
-- Show hotkeys popup
awful.key({ mod.super }, 's', function() hotkeys_popup.show_help() end,
{description='show help', group='awesome'}),
-- Show main menu
awful.key({ mod.super }, 'w',
function()
local pos = menu_position('tl')
_G.menus.main:show({coords=pos})
end,
{description = 'show main menu', group = 'awesome'}
),
-- Restart Awesome
awful.key({ mod.super, mod.ctrl }, 'r', awesome.restart,
{description = 'reload awesome', group = 'awesome'}),
-- Launch terminal
awful.key({ mod.super }, 'Return', function() awful.spawn(apps.terminal) end,
{description = 'open a terminal', group = 'launcher'}),
})
---- Global: Focus clients
awful.keyboard.append_global_keybindings({
-- Focus client to left
awful.key({ mod.super }, 'Left',
function()
awful.client.focus.bydirection('left')
if client.focus and vars.client_focus_raise then
client.focus:raise()
end
end,
{description = 'focus client to left', group = 'client'}
),
-- Focus client below
awful.key({ mod.super }, 'Down',
function()
awful.client.focus.bydirection('down')
if client.focus and vars.client_focus_raise then
client.focus:raise()
end
end,
{description = 'focus client below', group = 'client'}
),
-- Focus client above
awful.key({ mod.super }, 'Up',
function()
awful.client.focus.bydirection('up')
if client.focus and vars.client_focus_raise then
client.focus:raise()
end
end,
{description = 'focus client above', group = 'client'}
),
-- Focus client to right
awful.key({ mod.super }, 'Right',
function()
awful.client.focus.bydirection('right')
if client.focus and vars.client_focus_raise then
client.focus:raise()
end
end,
{description = 'focus client to right', group = 'client'}
),
-- Cycle focus previous
awful.key({ mod.super }, 'Tab',
function()
awful.client.focus.byidx(-1)
if client.focus then
client.focus:raise()
end
end,
{description = 'focus previous client', group = 'client'}
),
-- Cycle focus next
awful.key({ mod.super, mod.shift }, 'Tab',
function()
awful.client.focus.byidx( 1)
if client.focus then
client.focus:raise()
end
end,
{description = 'focus next client', group = 'client'}
),
-- Focus (random) minimized client
awful.key({ mod.super, mod.shift }, 'n',
function()
local c = awful.client.restore()
if c then
c:activate { raise = true, context = 'key.unminimize' }
end
end,
{description = 'restore minimized', group = 'client'}
),
-- Focus urgent client
awful.key({ mod.super, mod.shift }, 'u', awful.client.urgent.jumpto,
{description = 'jump to urgent client', group = 'client'}),
})
---- Global: Swap clients
awful.keyboard.append_global_keybindings({
-- Swap with client to left
awful.key({ mod.super, mod.shift }, 'Left', function() awful.client.swap.bydirection('left') end,
{description = 'swap with client to left', group = 'client'}),
-- Swap with client below
awful.key({ mod.super, mod.shift }, 'Down', function() awful.client.swap.bydirection('down') end,
{description = 'swap with client below', group = 'client'}),
-- Swap with client right
awful.key({ mod.super, mod.shift }, 'Up', function() awful.client.swap.bydirection('up') end,
{description = 'swap with client above', group = 'client'}),
-- Swap with client to right
awful.key({ mod.super, mod.shift }, 'Right', function() awful.client.swap.bydirection('right') end,
{description = 'swap with client to right', group = 'client'}),
})
---- Global: Focus screen
awful.keyboard.append_global_keybindings({
-- Focus screen to left
awful.key({ mod.super, mod.ctrl }, 'Left', function() awful.screen.focus_bydirection('left') end,
{description = 'focus screen to left', group = 'screen'}),
-- Focus screen below
awful.key({ mod.super, mod.ctrl }, 'Down', function() awful.screen.focus_bydirection('down') end,
{description = 'focus screen below', group = 'screen'}),
-- Focus screen above
awful.key({ mod.super, mod.ctrl }, 'Up', function() awful.screen.focus_bydirection('up') end,
{description = 'focus screen above', group = 'screen'}),
-- Focus screen to right
awful.key({ mod.super, mod.ctrl }, 'Right', function() awful.screen.focus_bydirection('right') end,
{description = 'focus screen to right', group = 'screen'}),
})
---- Global: Tags
awful.keyboard.append_global_keybindings({
-- View last tag
awful.key({ mod.super }, '`', awful.tag.history.restore,
{description = 'go back', group = 'tag'}),
-- Go to tag by index
awful.key {
modifiers = { mod.super },
keygroup = 'numrow',
description = 'view tag',
group = 'tag',
on_press = function(index)
local screen = awful.screen.focused()
local tag = screen.tags[index]
if not tag then
return
elseif tag.selected then
awful.tag.history.restore(screen, 1)
else
tag:view_only()
end
end,
},
-- Toggle tag by index
awful.key {
modifiers = { mod.super, mod.ctrl },
keygroup = 'numrow',
description = 'toggle tag',
group = 'tag',
on_press = function(index)
local screen = awful.screen.focused()
local tag = screen.tags[index]
if tag then
awful.tag.viewtoggle(tag)
end
end,
},
-- Move client to tag by index
awful.key {
modifiers = { mod.super, mod.shift },
keygroup = 'numrow',
description = 'move focused client to tag',
group = 'tag',
on_press = function(index)
if client.focus then
local tag = client.focus.screen.tags[index]
if tag then
client.focus:move_to_tag(tag)
end
end
end,
},
-- Toggle focused client on tag by index
awful.key {
modifiers = { mod.super, mod.ctrl, mod.shift },
keygroup = 'numrow',
description = 'toggle focused client on tag',
group = 'tag',
on_press = function(index)
if client.focus then
local tag = client.focus.screen.tags[index]
if tag then
client.focus:toggle_tag(tag)
end
end
end,
},
-- Add new tag (utils.tag_editor)
awful.key({ mod.super, mod.ctrl }, 'a', function() tag_edit.add() end,
{description = 'add new', group = 'tag'}),
-- Edit current tag (utils.tag_editor)
awful.key({ mod.super, mod.ctrl }, 'e', function() tag_edit.rename() end,
{description = 'edit selected', group = 'tag'}),
-- Move tag left (utils.tag_editor)
awful.key({ mod.super, mod.ctrl }, '[', function() tag_edit.move('left') end,
{description = 'move left', group = 'tag'}),
-- Move tag right (utils.tag_editor)
awful.key({ mod.super, mod.ctrl }, ']', function() tag_edit.move('right') end,
{description = 'move right', group = 'tag'}),
-- Delete current tag (utils.tag_editor)
awful.key({ mod.super, mod.ctrl }, 'd', function() tag_edit.delete() end,
{description = 'delete selected', group = 'tag'}),
})
--- Global: Layouts
awful.keyboard.append_global_keybindings({
-- Next layout
awful.key({ mod.super, }, ']', function() awful.layout.inc( 1) end,
{description = 'select next', group = 'layout'}),
-- Previous layout
awful.key({ mod.super, }, '[', function() awful.layout.inc(-1) end,
{description = 'select previous', group = 'layout'}),
})
--- Client
client.connect_signal('request::default_keybindings', function()
awful.keyboard.append_client_keybindings({
-- Toggle fullscreen
awful.key({ mod.super, mod.shift }, 'f',
function(c)
c.fullscreen = not c.fullscreen
c:raise()
end,
{description = 'toggle fullscreen', group = 'client'}
),
-- Toggle floating
awful.key({ mod.super, mod.ctrl }, 'f',
awful.client.floating.toggle,
{description = 'toggle floating', group = 'client'}
),
-- Toggle ontop
awful.key({ mod.super, mod.ctrl }, 't',
function(c)
c.ontop = not c.ontop
end,
{description = 'toggle keep on top', group = 'client'}
),
-- Toggle sticky
awful.key({ mod.super, mod.ctrl }, 's',
function(c)
c.sticky = not c.sticky
end,
{description = 'toggle sticky', group = 'client'}
),
-- Minimize client
awful.key({ mod.super, }, 'n',
function(c)
c.minimized = true
end,
{description = 'minimize', group = 'client'}
),
-- Toggle maximize
awful.key({ mod.super, }, 'm',
function(c)
c.maximized = not c.maximized
c:raise()
end ,
{description = '(un)maximize', group = 'client'}
),
-- Toggle vertical maximize
awful.key({ mod.super, mod.ctrl }, 'm',
function(c)
c.maximized_vertical = not c.maximized_vertical
c:raise()
end ,
{description = '(un)maximize vertically', group = 'client'}
),
-- Toggle horizontal maximize
awful.key({ mod.super, mod.shift }, 'm',
function(c)
c.maximized_horizontal = not c.maximized_horizontal
c:raise()
end ,
{description = '(un)maximize horizontally', group = 'client'}
),
-- Swap with primary client
awful.key({ mod.super, mod.shift }, 'p',
function(c)
c:swap(awful.client.getmaster())
end,
{description = 'swap with primary', group = 'client'}
),
-- Move client to next screen
awful.key({ mod.super, mod.shift }, 'o',
function(c)
c:move_to_screen()
end,
{description = 'move to screen', group = 'client'}
),
-- Kill client (close)
awful.key({ mod.super, mod.ctrl }, 'Escape',
function(c)
c:kill()
end,
{description = 'close', group = 'client'}
),
})
end)
--- Client: Mouse bindings
client.connect_signal('request::default_mousebindings', function()
awful.mouse.append_client_mousebindings({
awful.button({ }, 1, function(c)
c:activate { context = 'mouse_click' }
end),
})
end)
|
-----------------------------------
-- Area: Port Windurst
-- NPC: Ryan
-- Standard Merchant NPC
-----------------------------------
local ID = require("scripts/zones/Port_Windurst/IDs")
require("scripts/globals/shop")
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local stock =
{
16640, 290, -- Bronze Axe
16535, 246, -- Bronze Sword
17336, 5, -- Crossbow Bolt
12576, 235, -- Bronze Harness
12577, 2286, -- Brass Harness
12704, 128, -- Bronze Mittens
12705, 1255, -- Brass Mittens
12832, 191, -- Bronze Subligar
12833, 1840, -- Brass Subligar
12960, 117, -- Bronze Leggings
12961, 1140, -- Brass Leggings
12584, 1145, -- Kenpogi
12712, 630, -- Tekko
12840, 915, -- Sitabaki
12968, 584, -- Kyahan
}
player:showText(npc, ID.text.RYAN_SHOP_DIALOG)
tpz.shop.general(player, stock, WINDURST)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
|
settings {
statusFile = "/tmp/lsyncd.status",
statusInterval = 10,
nodaemon = true,
insist = true,
inotifyMode = "CloseWrite or Modify",
maxProcesses = 1
}
rclone_command = "/usr/bin/rclone -v sync ^source ^target"
rclone = {
delay = 600,
maxProcesses = 1,
onAttrib = rclone_command,
onCreate = rclone_command,
onModify = rclone_command,
onStartup = rclone_command,
onDelete = rclone_command,
onMove = true
}
sync {
rclone,
source = "/home/{{ username }}/Documents/sync/",
target = "gdrive:data/"
}
|
PLUGIN.name = "Advanced Citizen Outfit"
PLUGIN.author = "Black Tea"
PLUGIN.desc = "This plugin allows the server having good amount of customizable citizens."
-- http://steamcommunity.com/sharedfiles/filedetails/?id=320536858
-- workshop Address = 320536858
if SERVER then resource.AddWorkshop(320536858) end
nut.util.include("sh_sheets.lua")
nut.util.include("sh_citizenmodels.lua")
nut.util.include("cl_vgui.lua")
nut.util.include("sh_generateitem.lua")
-- requires material preload to acquire submaterial change.
if (CLIENT) then
local time = os.time()
-- preventing vast loading
for model, modelData in pairs(RESKINDATA) do
for k, v in ipairs(modelData.facemaps) do
surface.SetMaterial(Material(v))
end
end
for model, modelData in pairs(CITIZENSHEETS) do
for k, v in ipairs(modelData) do
surface.SetMaterial(Material(v))
end
end
function PLUGIN:OnEntityCreated(ragdoll)
if (ragdoll and ragdoll:IsValid() and ragdoll:GetClass() == "class C_HL2MPRagdoll") then
local client = ragdoll:GetRagdollOwner()
self:CreateEntityRagdoll(client, ragdoll)
end
end
-- currently only applies on local player.
-- should store cloth data on char or player.
function PLUGIN:CreateEntityRagdoll(client, ragdoll)
if (client and ragdoll and client:IsValid() and ragdoll:IsValid() and client:getChar()) then
local mats = client:GetMaterials()
for k, v in pairs(mats) do
ragdoll:SetSubMaterial(k - 1, client:GetSubMaterial(k - 1))
end
end
end
end
function PLUGIN:OnCharFallover(client, ragdoll, isFallen)
if (client and ragdoll and client:IsValid() and ragdoll:IsValid() and client:getChar() and isFallen) then
local mats = client:GetMaterials()
for k, v in pairs(mats) do
ragdoll:SetSubMaterial(k - 1, client:GetSubMaterial(k - 1))
end
end
end
function changeFacemap(client, value, ragdoll)
local model = string.lower(client:GetModel())
local modelData = RESKINDATA[model]
if (modelData) then
if (value == 0) then
client:SetSubMaterial(modelData[2] - 1, "")
else
local facemap = modelData.facemaps[value]
client:SetSubMaterial(modelData[2] - 1, facemap)
end
end
end
function recoverCloth(client, target)
local inv = client:getChar():getInv()
if (inv and inv.getItems) then
for k, v in pairs(inv:getItems()) do
if (v.isCloth and v:getData("equip")) then
local model = string.lower(client:GetModel())
local modelData = RESKINDATA[model]
if (!model) then
return false
end
if (modelData) then
if (modelData.sheets == v.sheet[1]) then
local sheet = CITIZENSHEETS[v.sheet[1]][v.sheet[2]]
if (!sheet) then
return false
end
(target or client):SetSubMaterial(modelData[1] - 1, sheet)
else
return false
end
end
return false
end
end
end
end
function PLUGIN:PostPlayerLoadout(client)
local mats = client:GetMaterials()
-- You have to reset entity texture replacement if you don't want texture fuckups.
for k, v in ipairs(mats) do
client:SetSubMaterial(k - 1, "")
end
timer.Simple(0, function() -- to prevent getmodel failing.
if (client:getChar()) then
timer.Simple(0, function()
local value = client:getChar():getData("charFacemap")
if (value) then
changeFacemap(client, value)
end
recoverCloth(client)
end)
end
end)
end
netstream.Hook("charFacemap", function(client, value)
value = math.ceil(value)
client:getChar():setData("charFacemap", value)
changeFacemap(client, value)
end)
nut.command.add("charfacemap", {
onRun = function(client, arguments)
netstream.Start(client, "charFacemapMenu")
end
})
|
-- { name = "Muldraugh, KY - Spawn As A Outsider", file = "media/maps/Muldraugh, KY - Outside/spawnregions.lua" },
function SpawnPoints()
return {
unemployed = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
policeofficer = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
securityguard = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
parkranger = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
fireofficer = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
doctor = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
nurse = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
customerservice = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
constructionworker = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
engineer = {
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
electrician = {
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
fitnessInstructor = {
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
lumberjack = {
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
veteran = {
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
fisherman = {
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
repairman = {
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
carpenter = {
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
itworker = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
bookkeeper = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
officeworker = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
secretary = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
accountant = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
teacher = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
janitor = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
salesperson = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
cashier = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
shopclerk = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
fastfoodcook = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
chef = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
cook = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
waiter = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
burglar = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
drugdealer = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
farmer = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
truckdriver = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
militarysoldier = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
militaryofficer = {
-- 35x35
{worldX=35, worldY=35, posX=90, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=91, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=92, posY=299}, -- South Western MSR City Entry
{worldX=35, worldY=35, posX=93, posY=299}, -- South Western MSR City Entry
},
}
end
|
#!/usr/bin/env lua
-- Load cfg first so that luarocks.loader knows it is running inside LuaRocks
local cfg = require("luarocks.core.cfg")
local loader = require("luarocks.loader")
local cmd = require("luarocks.cmd")
local description = "LuaRocks repository administration interface"
local commands = {
help = "luarocks.cmd.help",
make_manifest = "luarocks.admin.cmd.make_manifest",
add = "luarocks.admin.cmd.add",
remove = "luarocks.admin.cmd.remove",
refresh_cache = "luarocks.admin.cmd.refresh_cache",
}
cmd.run_command(description, commands, "luarocks.admin.cmd.external", ...)
|
local combat = Combat()
combat:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_EARTH)
combat:setParameter(COMBAT_PARAM_CREATEITEM, ITEM_WILDGROWTH)
function onCastSpell(creature, variant, isHotkey)
return combat:execute(creature, variant)
end
|
--[[
a lua interface (build with luajit ffi) for maxminddb to get country code from ip address
]]
local json = require('cjson');
local json_encode = json.encode
local json_decode = json.decode
local ht_print = ngx.print
local ngx_log = ngx.log
local ngx_ERR = ngx.ERR
local ngx_CRIT = ngx.CRIT
local ngx_INFO = ngx.INFO
local ngx_sub = ngx.re.sub;
local ngx_gsub = ngx.re.gsub;
local ngx_unescape_uri = ngx.unescape_uri
local ngx_find = ngx.re.find
local string_sub = string.sub
local string_len = string.len
local string_byte = string.byte
local ngx_read_body = ngx.req.read_body
local ngx_decode_base64 = ngx.decode_base64
local ngx_now = ngx.now
local ngx_exit = ngx.exit
local ffi = require 'ffi'
local ffi_new = ffi.new
local ffi_str = ffi.string
local ffi_copy = ffi.copy
local ffi_cast = ffi.cast
ffi.cdef[[
typedef unsigned int mmdb_uint128_t __attribute__ ((__mode__(TI)));
typedef struct MMDB_entry_s {
struct MMDB_s *mmdb;
uint32_t offset;
} MMDB_entry_s;
typedef struct MMDB_lookup_result_s {
bool found_entry;
MMDB_entry_s entry;
uint16_t netmask;
} MMDB_lookup_result_s;
typedef struct MMDB_entry_data_s {
bool has_data;
union {
uint32_t pointer;
const char *utf8_string;
double double_value;
const uint8_t *bytes;
uint16_t uint16;
uint32_t uint32;
int32_t int32;
uint64_t uint64;
mmdb_uint128_t uint128;
bool boolean;
float float_value;
};
uint32_t offset;
uint32_t offset_to_next;
uint32_t data_size;
uint32_t type;
} MMDB_entry_data_s;
typedef struct MMDB_entry_data_list_s {
MMDB_entry_data_s entry_data;
struct MMDB_entry_data_list_s *next;
} MMDB_entry_data_list_s;
typedef struct MMDB_description_s {
const char *language;
const char *description;
} MMDB_description_s;
typedef struct MMDB_metadata_s {
uint32_t node_count;
uint16_t record_size;
uint16_t ip_version;
const char *database_type;
struct {
size_t count;
const char **names;
} languages;
uint16_t binary_format_major_version;
uint16_t binary_format_minor_version;
uint64_t build_epoch;
struct {
size_t count;
MMDB_description_s **descriptions;
} description;
} MMDB_metadata_s;
typedef struct MMDB_ipv4_start_node_s {
uint16_t netmask;
uint32_t node_value;
} MMDB_ipv4_start_node_s;
typedef struct MMDB_s {
uint32_t flags;
const char *filename;
ssize_t file_size;
const uint8_t *file_content;
const uint8_t *data_section;
uint32_t data_section_size;
const uint8_t *metadata_section;
uint32_t metadata_section_size;
uint16_t full_record_byte_size;
uint16_t depth;
MMDB_ipv4_start_node_s ipv4_start_node;
MMDB_metadata_s metadata;
} MMDB_s;
typedef char * pchar;
MMDB_lookup_result_s MMDB_lookup_string(MMDB_s *const mmdb, const char *const ipstr, int *const gai_error,int *const mmdb_error);
int MMDB_open(const char *const filename, uint32_t flags, MMDB_s *const mmdb);
int MMDB_aget_value(MMDB_entry_s *const start, MMDB_entry_data_s *const entry_data, const char *const *const path);
char *MMDB_strerror(int error_code);
]]
local MMDB_SUCCESS = 0
local MMDB_DATA_TYPE_POINTER = 1
local MMDB_DATA_TYPE_UTF8_STRING= 2
local MMDB_DATA_TYPE_DOUBLE = 3
local MMDB_DATA_TYPE_BYTES = 4
-- you should install the libmaxminddb to your system
local maxm = ffi.load('libmaxminddb.so')
--https://github.com/maxmind/libmaxminddb
local _M ={}
local mt = { __index = _M }
function _M.new(maxmind_country_geoip2_file)
local mmdb = ffi_new('MMDB_s')
local file_name_ip2 = ffi_new('char[?]',#maxmind_country_geoip2_file,maxmind_country_geoip2_file)
local maxmind_reday = maxm.MMDB_open(file_name_ip2,0,mmdb)
return setmetatable({ mmdb=mmdb }, mt);
end
function _M:lookup(ip)
local ip_str = ffi_cast('const char *',ffi_new('char[?]',#ip+1,ip))
local gai_error = ffi_new('int[1]')
local mmdb_error = ffi_new('int[1]')
local result = maxm.MMDB_lookup_string(self.mmdb,ip_str,gai_error,mmdb_error)
if mmdb_error[0] ~= MMDB_SUCCESS then
return nil,'fail when lookup'
end
if gai_error[0] ~= MMDB_SUCCESS then
return nil,'ga error'
end
if true~=result.found_entry then
ngx_log(ngx_ERR, "stream lua mmdb lookup: entry not found")
return nil,'not found'
end
local lookup = ffi_new('const char*[3]')
lookup[0] = ffi_cast('const char *',ffi_new('char[?]',8,'country'))
lookup[1] = ffi_cast('const char *',ffi_new('char[?]',9,'iso_code'))
local entry_data = ffi_new('MMDB_entry_data_s[1]')
lookup = ffi_cast('const char *const *const',lookup)
local mmdb_error = maxm.MMDB_aget_value(result.entry, entry_data, lookup);
if mmdb_error ~= MMDB_SUCCESS then
return nil,'no value'
end
if true ~= entry_data[0].has_data then
ngx_log(ngx_ERR, "stream lua mmdb lookup: entry has no data")
return nil,'no data'
end
local country = ''
if entry_data[0].type == MMDB_DATA_TYPE_UTF8_STRING then
return ffi_str(entry_data[0].utf8_string,entry_data[0].data_size)
end
if entry_data[0].type ==MMDB_DATA_TYPE_BYTES then
return ffi_str(ffi_cast('char * ',entry_data[0].bytes),entry_data[0].data_size)
end
return nil,'no data'
end
-- https://www.maxmind.com/en/geoip2-databases you should download the mmdb file from maxmind
function _M:get_area_code(ip)
local succ,country,err = pcall(self.lookup,self,ip)
if succ==true then
return country
else
return nil,err
end
end
return _M;
|
return [==[
body {
font-family: sans-serif;
font-size: 16px;
background: #D6D6D6;
margin: 0; }
#editor .CodeMirror {
height: auto; }
#editor .CodeMirror-scroll {
overflow-y: hidden;
overflow-x: auto; }
#editor .editor_top {
background: whitesmoke;
padding: 20px;
border-bottom: 1px solid #B1AFAF;
box-shadow: 0 -2px 4px 4px rgba(0, 0, 0, 0.15); }
#editor .log {
padding: 0 20px; }
#editor .footer {
text-align: center;
margin: 10px;
font-size: 12px;
color: #838383; }
#editor .buttons_top {
font-size: 0;
margin-bottom: 7px; }
#editor .buttons_top button {
font-size: 16px;
background: #8AA8CF;
color: #294364;
border: 0;
margin: 0 10px 0 0;
padding: 5px 10px;
border-radius: 4px;
-webkit-transition: background 0.2s ease-in-out;
-moz-transition: background 0.2s ease-in-out;
transition: background 0.2s ease-in-out; }
#editor .buttons_top button:hover {
background: #9cb5d6; }
#editor .buttons_top button:active {
position: relative;
top: 1px; }
#editor .status {
background: #7BB87B;
text-shadow: 1px 1px 1px #488548;
color: white;
padding: 4px 8px;
-webkit-transition: background 0.2s ease-in-out;
-moz-transition: background 0.2s ease-in-out;
transition: background 0.2s ease-in-out; }
#editor .status.error {
background: #C25353;
text-shadow: 1px 1px 1px #a73b3b; }
#editor .status.loading {
background: #E9D674;
text-shadow: 1px 1px 1px #a9921b; }
#editor .has_error {
background: rgba(255, 0, 0, 0.2); }
#editor .result {
border: 1px solid silver;
background: white;
box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.15);
color: #444;
margin: 10px 0; }
#editor .result.no_output {
font-style: italic;
color: #888;
padding: 10px; }
#editor .result .line {
font-family: monospace; }
#editor .result .value {
margin: 5px;
padding: 5px;
display: inline-block;
vertical-align: top; }
#editor .result .value.string {
color: #648164; }
#editor .result .value.string:before {
font-weight: bold;
content: '"'; }
#editor .result .value.string:after {
font-weight: bold;
content: '"'; }
#editor .result .value.string.key:before {
content: ""; }
#editor .result .value.boolean {
color: #664B66; }
#editor .result .value.number {
color: #5076A0; }
#editor .result .value.function, #editor .result .value.recursion, #editor .result .value.metatable {
color: #888;
font-style: italic; }
#editor .result .value .recursion:before {
content: "(recursion) ";
font-style: normal;
font-weight: bold;
font-size: 14px; }
#editor .result .value.key {
margin-right: 0;
padding-right: 0; }
#editor .result .value.key:after {
content: ": ";
font-style: normal;
font-weight: bold;
color: #444; }
#editor .result .value:hover {
background: #eee;
border-radius: 3px; }
#editor .result .value.expanded {
border-left: 1px dashed silver;
margin-left: 10px;
padding: 0; }
#editor .result .value.expanded:hover {
background: white; }
#editor .result .sep {
padding: 5px 0;
font-weight: bold;
display: inline-block; }
#editor .result .tuple {
margin-left: 10px; }
#editor .result .tuple > .value {
margin-top: 0;
margin-bottom: 0; }
#editor .result .expandable {
cursor: pointer;
font-weight: bold; }
#editor .result .closable {
font-weight: bold;
vertical-align: top;
display: inline-block;
cursor: pointer;
padding: 5px;
margin: 5px; }
#editor .result .closable:first-child {
margin-bottom: 0; }
#editor .result .closable:last-child {
margin-top: 0; }
#editor .result .closable:hover {
background: #eee;
border-radius: 3px; }
#editor .result .queries {
font-family: monospace;
background: #ddd;
border: 1px solid white; }
#editor .result .queries:before {
content: "Queries:";
display: block;
background: #c4c4c4;
border-bottom: 1px solid #B4B4B4;
text-shadow: 1px 1px 0 #ddd;
font-size: 12px;
padding: 5px;
font-family: sans-serif; }
#editor .result .queries .query {
padding: 5px; }
]==]
|
return {
three = "333",
seven = "7",
five = {
eight = "8"
}
}
|
local config = require("pandoc.config")
local M = {}
M.create_output = function(name, template)
local template_string = template or config.get().default.output
assert(type(template_string) == "string", "output must be a string")
return template_string:format(name:gsub(".[^.]+$", ""))
end
M.has_argument = function(tbl, name)
for _, value in ipairs(tbl) do
if value[1] == name then
return true
end
end
return false
end
M.get_argument = function(tbl, name)
for _, value in ipairs(tbl) do
if value[1] == name then
return value[2]
end
end
end
M.add_argument = function(tbl, name)
return vim.list_extend(tbl, name)
end
M.validate = function(argument)
local lhs, rhs = unpack(argument)
local type_ = config.types[lhs]
local argument_name = lhs:gsub("^%-+", "")
-- Assert than argument exist
assert(type_, argument_name .. " is a invalid argument")
if type_ == "flag" then
assert(rhs == nil, argument_name .. " must be a flag")
end
if type_ == "string" then
assert(type(rhs) == "string", argument_name .. " must be a string")
assert(string.len(rhs) > 0, argument_name .. " is empty")
end
if type_ == "number" then
assert(type(tonumber(rhs)) == "number", argument_name .. " must be a number")
end
if type(type_) == "table" then
assert(vim.tbl_contains(type_, rhs), argument_name .. " must be " .. table.concat(type_, ", "))
end
return true
end
M.parse_vim_command = function(arguments)
return vim.tbl_map(function(argument)
local lhs, rhs = unpack(vim.split(argument, "=", true))
return { "--" .. lhs, rhs }
end, vim.split(arguments, " ", true))
end
M.on_keypress = function(key)
local binding = config.get().mapping[key:gsub("%[", "<"):gsub("%]", ">")]
assert(type(binding) == "function", "Mapping bind must be a function")
binding()
end
local keymap_callback = function(key)
return string.format('<cmd>lua require"pandoc.utils".on_keypress("%s")<CR>', key:gsub("<", "["):gsub(">", "]"))
end
M.register_key = function(mapping)
local opts = { noremap = true, silent = true, nowait = true }
for mode, keymap in pairs(mapping) do
for key, _ in pairs(keymap) do
vim.api.nvim_set_keymap(mode, key, keymap_callback(key), opts)
end
end
end
return M
|
local PANEL = {};
function PANEL:PerformLayout ( )
local x, y = self:GetPos()
if (self.ModelPanel) then
self.ModelPanel:SetPos(x + 1, y + 1);
self.ModelPanel:SetSize(self:GetWide() - 2, self:GetTall() - 2);
end
end
function PANEL:GrabItem ( itemTable )
self.itemTable = itemTable;
if (!self.ModelPanel) then
self.ModelPanel = vgui.Create('perp2_shop_store_item', self:GetParent());
end
local x, y = self:GetPos()
self.ModelPanel:SetPos(x + 1, y + 1);
self.ModelPanel:SetSize(self:GetWide() - 2, self:GetTall() - 2);
self.ModelPanel:SetItemTable(self.itemTable);
self.ModelPanel.trueParent = self;
end
vgui.Register("perp2_shop_store_block", PANEL, "perp2_inventory_block");
|
AddCSLuaFile('shared.lua')
AddCSLuaFile('cl_init.lua')
include('shared.lua')
util.AddNetworkString('bw_ents_radar')
function ENT:Initialize()
local antenna = ents.Create('prop_physics')
local ang = self:GetAngles()
antenna:SetModelScale(0.9)
antenna:SetPos(self:GetPos() +ang:Up() *30 -ang:Forward() *4.5)
antenna:SetAngles(ang)
antenna:SetParent(self)
antenna:SetModel('models/props_rooftop/roof_dish001.mdl')
antenna:Spawn()
antenna:SetSolid(SOLID_NONE)
antenna:SetMoveType(SOLID_NONE)
antenna:PhysicsInit(SOLID_NONE)
self.Antenna = antenna
self:SetModel('models/props_wasteland/gaspump001a.mdl')
self:SetSolid(SOLID_VPHYSICS)
self:SetMoveType(SOLID_VPHYSICS)
self:PhysicsInit(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
self.NextCharge = nil
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
end
function ENT:Use(caller)
net.Start('bw_ents_radar')
net.WriteEntity(self)
net.Send(caller)
end
function ENT:Think()
if self:IsPowered() then
if self:GetTarget():IsValid() then
if self:GetChargeStored() > 0 then
self:SetChargeStored(self:GetChargeStored() -(5 -math.floor(4 *self:GetEfficiency())))
else
self:SetTarget(NULL)
end
else
if not self.NextCharge then
self.NextCharge = CurTime() +self.ChargeDelay
elseif self.NextCharge <= CurTime() then
self:SetChargeStored(math.Clamp(self:GetChargeStored() +1, 0, self.MaxCharge))
self.NextCharge = CurTime() +self.ChargeDelay
end
end
else
if self:GetTarget():IsValid() then
self:SetTarget(NULL)
end
self.NextCharge = nil
end
self:NextThink(CurTime() +1)
return true
end
net.Receive('bw_ents_radar', function(len, ply)
local ent = net.ReadEntity()
if ent:IsValid() and ent:GetClass() == 'bw_radar' then
local isScan = net.ReadBool()
if isScan then
if ent:CanScan() then
local target = net.ReadEntity()
if target:IsPlayer() then
if ent:GetTarget() == target then
ent:SetTarget(NULL)
else
ent.NextCharge = nil
ent:SetTarget(target)
end
end
end
else
if ent:GetTurnedOn() then
ent:SetTarget(NULL)
ent:SetTurnedOn(false)
else
ent:SetTurnedOn(true)
end
ent:EmitSound('buttons/button3.wav')
end
end
end)
|
local GlobalAddonName, WQLdb = ...
local ELib = WQLdb.ELib
-- Enigma helper
local KirinTorQuests = {
[43756]=true, --VS
[43772]=true, --SH
[43767]=true, --HM
[43328]=true, --A
[43778]=true, --SU
}
local KirinTorPatt = { --Patterns created by flow0284
[1] = { [9]=1,[10]=1,[11]=1,[12]=1,[13]=1,[20]=1,[23]=1,[24]=1,[25]=1,[26]=1,[27]=1,[30]=1,[37]=1,[38]=1,[39]=1,[40]=1,[41]=2,},
[2] = { [9]=1,[11]=1,[12]=1,[13]=1,[16]=1,[18]=1,[20]=1,[23]=1,[24]=1,[25]=1,[27]=1,[34]=1,[41]=2,},
[3] = { [9]=1,[10]=1,[11]=1,[12]=1,[19]=1,[25]=1,[26]=1,[32]=1,[39]=1,[40]=1,[41]=2,},
[4] = { [9]=1,[10]=1,[11]=1,[18]=1,[23]=1,[24]=1,[25]=1,[30]=1,[37]=1,[38]=1,[39]=1,[40]=1,[41]=2,},
[5] = { [9]=1,[10]=1,[11]=1,[12]=1,[13]=1,[16]=1,[23]=1,[25]=1,[26]=1,[27]=1,[30]=1,[32]=1,[34]=1,[37]=1,[38]=1,[39]=1,[41]=2,},
[6] = { [12]=1,[13]=1,[18]=1,[19]=1,[25]=1,[32]=1,[33]=1,[40]=1,[41]=2,},
[7] = { [9]=1,[11]=1,[12]=1,[13]=1,[16]=1,[18]=1,[20]=1,[23]=1,[25]=1,[27]=1,[30]=1,[31]=1,[32]=1,[34]=1,[41]=2,},
[8] = { [9]=1,[10]=1,[17]=1,[24]=1,[25]=1,[32]=1,[33]=1,[40]=1,[41]=2,},
[9] = { [9]=1,[16]=1,[17]=1,[18]=1,[19]=1,[20]=1,[27]=1,[34]=1,[41]=2,},
[10] = { [9]=1,[10]=1,[11]=1,[12]=1,[13]=1,[16]=1,[23]=1,[24]=1,[25]=1,[26]=1,[33]=1,[40]=1,[41]=2,},
[11] = { [9]=1,[10]=1,[11]=1,[12]=1,[13]=1,[16]=1,[23]=1,[30]=1,[37]=1,[38]=1,[39]=1,[40]=1,[41]=2,},
[12] = { [11]=1,[12]=1,[13]=1,[18]=1,[23]=1,[24]=1,[25]=1,[30]=1,[37]=1,[38]=1,[39]=1,[40]=1,[41]=2,},
[13] = { [13]=1,[20]=1,[23]=1,[24]=1,[25]=1,[26]=1,[27]=1,[30]=1,[37]=1,[38]=1,[39]=1,[40]=1,[41]=2,},
}
local KIRIN_TOR_SIZE = 7
local KirinTorSelecter_Big_BSize = 30
local KirinTorSelecter_Big_Size = KIRIN_TOR_SIZE * KirinTorSelecter_Big_BSize + 10
local KirinTorSelecter_BSize = 12
local KirinTorSelecter_Size = KIRIN_TOR_SIZE * KirinTorSelecter_BSize + 10
local KirinTorSelecter_Big = CreateFrame('Button',nil,UIParent)
KirinTorSelecter_Big:SetPoint("LEFT",30,0)
KirinTorSelecter_Big:SetSize(KirinTorSelecter_Big_Size,KirinTorSelecter_Big_Size)
KirinTorSelecter_Big:SetAlpha(.8)
ELib:CreateBorder(KirinTorSelecter_Big)
KirinTorSelecter_Big:SetBorderColor(0,0,0,0)
KirinTorSelecter_Big.back = KirinTorSelecter_Big:CreateTexture(nil,"BACKGROUND")
KirinTorSelecter_Big.back:SetAllPoints()
KirinTorSelecter_Big.back:SetColorTexture(0,0,0,1)
KirinTorSelecter_Big.T = {}
KirinTorSelecter_Big:Hide()
do
local L = (KirinTorSelecter_Big_Size - KirinTorSelecter_Big_BSize * KIRIN_TOR_SIZE) / 2
for j=0,KIRIN_TOR_SIZE-1 do
for k=0,KIRIN_TOR_SIZE-1 do
local t = KirinTorSelecter_Big:CreateTexture(nil,"ARTWORK")
t:SetSize(KirinTorSelecter_Big_BSize,KirinTorSelecter_Big_BSize)
t:SetPoint("TOPLEFT",L + k*KirinTorSelecter_Big_BSize,-L-j*KirinTorSelecter_Big_BSize)
KirinTorSelecter_Big.T[ j*KIRIN_TOR_SIZE+k+1 ] = t
end
local l = KirinTorSelecter_Big:CreateTexture(nil,"OVERLAY")
l:SetPoint("TOPLEFT",L+j*KirinTorSelecter_Big_BSize,-L)
l:SetSize(1,KirinTorSelecter_Big_BSize*KIRIN_TOR_SIZE)
l:SetColorTexture(0,0,0,.3)
end
for j=0,7 do
local l = KirinTorSelecter_Big:CreateTexture(nil,"OVERLAY")
l:SetPoint("TOPLEFT",L,-L-j*KirinTorSelecter_Big_BSize)
l:SetSize(KirinTorSelecter_Big_BSize*KIRIN_TOR_SIZE,1)
l:SetColorTexture(0,0,0,.3)
end
end
local KirinTorSelecter = CreateFrame('Frame',nil,UIParent)
KirinTorSelecter:SetPoint("LEFT",30,0)
KirinTorSelecter:SetSize(KirinTorSelecter_Size * 4,KirinTorSelecter_Size * 3)
KirinTorSelecter:SetAlpha(.7)
KirinTorSelecter:Hide()
KirinTorSelecter.back = KirinTorSelecter:CreateTexture(nil,"BACKGROUND")
KirinTorSelecter.back:SetAllPoints()
KirinTorSelecter.back:SetColorTexture(0,0,0,1)
for i=1,#KirinTorPatt do
local b = CreateFrame('Button',nil,KirinTorSelecter)
b:SetSize(KirinTorSelecter_Size,KirinTorSelecter_Size)
b:SetPoint("TOPLEFT",((i-1)%4)*KirinTorSelecter_Size,-floor((i-1)/4)*KirinTorSelecter_Size)
ELib:CreateBorder(b)
b:SetBorderColor(0,0,0,1)
b:SetScript("OnEnter",function(self)
self:SetBorderColor(1,1,1,1)
end)
b:SetScript("OnLeave",function(self)
self:SetBorderColor(0,0,0,1)
end)
b:SetScript("OnClick",function(self)
for j=0,KIRIN_TOR_SIZE-1 do
for k=0,KIRIN_TOR_SIZE-1 do
local n = j*KIRIN_TOR_SIZE+k+1
local c = KirinTorPatt[i][n]
if c == 2 then
KirinTorSelecter_Big.T[n]:SetColorTexture(0,1,0,1)
elseif c then
KirinTorSelecter_Big.T[n]:SetColorTexture(1,0,0,1)
else
KirinTorSelecter_Big.T[n]:SetColorTexture(1,.7,.4,1)
end
end
end
KirinTorSelecter:Hide()
KirinTorSelecter_Big:Show()
end)
local L = (KirinTorSelecter_Size - KirinTorSelecter_BSize * KIRIN_TOR_SIZE) / 2
for j=0,KIRIN_TOR_SIZE-1 do
for k=0,KIRIN_TOR_SIZE-1 do
local t = b:CreateTexture(nil,"ARTWORK")
t:SetSize(KirinTorSelecter_BSize,KirinTorSelecter_BSize)
t:SetPoint("TOPLEFT",L + k*KirinTorSelecter_BSize,-L-j*KirinTorSelecter_BSize)
local c = KirinTorPatt[i][ j*KIRIN_TOR_SIZE+k+1 ]
if c == 2 then
t:SetColorTexture(0,1,0,1)
elseif c then
t:SetColorTexture(1,0,0,1)
else
t:SetColorTexture(1,.7,.4,1)
end
end
end
end
KirinTorSelecter.Close = CreateFrame('Button',nil,KirinTorSelecter)
KirinTorSelecter.Close:SetSize(10,10)
KirinTorSelecter.Close:SetPoint("BOTTOMRIGHT",KirinTorSelecter,"TOPRIGHT")
KirinTorSelecter.Close.Text = KirinTorSelecter.Close:CreateFontString(nil,"ARTWORK","GameFontWhite")
KirinTorSelecter.Close.Text:SetPoint("CENTER")
KirinTorSelecter.Close.Text:SetText("X")
KirinTorSelecter_Big:SetScript("OnClick",function (self)
self:Hide()
KirinTorSelecter:Show()
end)
local KirinTorHelper = CreateFrame'Frame'
KirinTorHelper:RegisterEvent('QUEST_ACCEPTED')
KirinTorHelper:RegisterEvent('QUEST_REMOVED')
KirinTorHelper:SetScript("OnEvent",function(self,event,arg1,arg2)
if event == 'QUEST_ACCEPTED' then
if arg2 and KirinTorQuests[arg2] then
if VWQL and not VWQL.EnableEnigma then
print('"|cff00ff00/enigmahelper|r" - to see all patterns')
return
end
print("World Quests List: Enigma helper loaded")
self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
end
elseif event == 'QUEST_REMOVED' then
if arg1 and KirinTorQuests[arg1] then
self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
end
elseif event == 'COMBAT_LOG_EVENT_UNFILTERED' then
local timestamp,arg2,hideCaster,sourceGUID,sourceName,sourceFlags,sourceFlags2,destGUID,destName,destFlags,destFlags2,spellId = CombatLogGetCurrentEventInfo()
if arg2 == "SPELL_AURA_APPLIED" and spellId == 219247 and destGUID == UnitGUID'player' then
KirinTorSelecter:Show()
elseif arg2 == "SPELL_AURA_REMOVED" and spellId == 219247 and destGUID == UnitGUID'player' then
KirinTorSelecter:Hide()
KirinTorSelecter_Big:Hide()
end
end
end)
KirinTorSelecter.Close:SetScript("OnClick",function ()
KirinTorSelecter:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
KirinTorSelecter:Hide()
end)
SlashCmdList["WQLEnigmaSlash"] = function()
KirinTorHelper:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
KirinTorSelecter:Show()
end
SLASH_WQLEnigmaSlash1 = "/enigmahelper"
-- Barrels o' Fun
local BarrelsHelperQuests = {
[45070]=true, --Valsh
[45068]=true, --Suramar
[45069]=true, --Azuna
[45071]=true, --Highm
[45072]=true, --Stormh
}
local BarrelsHelper_guid = {}
local BarrelsHelper_count = 8
local BarrelsHelper = CreateFrame'Frame'
BarrelsHelper:RegisterEvent('QUEST_ACCEPTED')
BarrelsHelper:RegisterEvent('QUEST_REMOVED')
BarrelsHelper:RegisterEvent('PLAYER_ENTERING_WORLD')
BarrelsHelper:SetScript("OnEvent",function(self,event,arg1,arg2)
if event == 'QUEST_ACCEPTED' then
if arg2 and BarrelsHelperQuests[arg2] then
if VWQL and VWQL.DisableBarrels then
return
end
print("World Quests List: Barrels helper loaded")
BarrelsHelper_count = 8
self:RegisterEvent("UPDATE_MOUSEOVER_UNIT")
end
elseif event == 'QUEST_REMOVED' then
if arg1 and BarrelsHelperQuests[arg1] then
self:UnregisterEvent("UPDATE_MOUSEOVER_UNIT")
BarrelsHelper_count = 8
end
elseif event == 'UPDATE_MOUSEOVER_UNIT' then
local guid = UnitGUID'mouseover'
if guid then
local type,_,serverID,instanceID,zoneUID,id,spawnID = strsplit("-", guid)
if id == "115947" then
if not BarrelsHelper_guid[guid] then
BarrelsHelper_guid[guid] = BarrelsHelper_count
BarrelsHelper_count = BarrelsHelper_count - 1
if BarrelsHelper_count < 1 then
BarrelsHelper_count = 8
end
end
if GetRaidTargetIndex("mouseover") ~= BarrelsHelper_guid[guid] then
SetRaidTarget("mouseover", BarrelsHelper_guid[guid])
end
end
end
elseif event == "PLAYER_ENTERING_WORLD" then
self:UnregisterEvent("PLAYER_ENTERING_WORLD")
if VWQL and VWQL.DisableBarrels then
return
end
for i=1,GetNumQuestLogEntries() do
local title, _, _, _, _, _, _, questID = GetQuestLogTitle(i)
if questID and BarrelsHelperQuests[questID] then
BarrelsHelper_count = 8
self:RegisterEvent("UPDATE_MOUSEOVER_UNIT")
break
end
end
end
end)
SlashCmdList["WQLBarrelsSlash"] = function(arg)
arg = (arg or ""):lower()
if arg == "off" or arg == "on" then
if not VWQL then
return
end
VWQL.DisableBarrels = not VWQL.DisableBarrels
if VWQL.DisableBarrels then
print("Barrels helper disabled")
BarrelsHelper:UnregisterEvent('UPDATE_MOUSEOVER_UNIT')
else
print("Barrels helper enabled")
end
elseif arg == "load" then
BarrelsHelper:RegisterEvent("UPDATE_MOUSEOVER_UNIT")
print("Barrels helper loaded")
else
print("Commands:")
print("/barrelshelper on")
print("/barrelshelper off")
print("/barrelshelper load")
end
end
SLASH_WQLBarrelsSlash1 = "/barrelshelper"
-- Shell Game
do
local ShellGameQuests = {
[51625]=true,
[51626]=true,
[51627]=true,
[51628]=true,
[51629]=true,
[51630]=true,
}
--[[
фиол пилон 71324
валькирия 73430 73591
краб-пират 87999 75367
шар 71960 72772
капля 81077 81388
черепаха 81098
робот 72873 31549
челюсти 67537 76371 81664
63509 - arrow
75066 - quest
46201 - bomb
47270 - kirintor
]]
local size,center = 200,30
local modelIDs = {71324,73430,87999,71960,81077,81098,72873,67537}
local ShellGameDisable
local ShellGameIsCreated
local UpdatePos,ResizeFrame,CenterFrame,OkButton,pointsFrames,CloseButton
local function CreateShellGame()
if ShellGameIsCreated then
return
end
ShellGameIsCreated = true
local function SmallModelOnMouseDown(self)
self:GetParent().M:SetDisplayInfo(self.modelID)
end
local function SmallModelOnEnter(self)
self.b:SetColorTexture(0.74,0.74,0.74,.2)
end
local function SmallModelOnLeave(self)
self.b:SetColorTexture(0.04,0.04,0.04,0)
end
local function PuzzleFrameOnUpdate(self)
if MouseIsOver(self) and not self.Mstatus then
self.Mstatus = true
for j=1,8 do
self.m[j]:Show()
end
elseif not MouseIsOver(self) and self.Mstatus then
self.Mstatus = false
for j=1,8 do
self.m[j]:Hide()
end
end
end
pointsFrames = {}
for i=1,16 do
local frame = CreateFrame("Frame",nil,UIParent)
pointsFrames[i] = frame
frame.M = CreateFrame("PlayerModel",nil,frame)
frame.M:SetPoint("TOP")
frame.M:SetMouseClickEnabled(false)
frame.M:SetMouseMotionEnabled(false)
frame.m = {}
for j=1,8 do
local m=CreateFrame("PlayerModel",nil,frame)
frame.m[j] = m
m:SetDisplayInfo(modelIDs[j])
m.modelID = modelIDs[j]
if j==1 then
m:SetPoint("TOPLEFT")
elseif j == 5 then
m:SetPoint("TOPRIGHT")
else
m:SetPoint("TOP",frame.m[j-1],"BOTTOM")
end
m:Hide()
m:SetScript("OnMouseDown",SmallModelOnMouseDown)
m:SetScript("OnEnter",SmallModelOnEnter)
m:SetScript("OnLeave",SmallModelOnLeave)
m.b = m:CreateTexture(nil,"BACKGROUND")
m.b:SetAllPoints()
end
frame:SetScript("OnUpdate",PuzzleFrameOnUpdate)
frame:Hide()
end
OkButton = CreateFrame("Button",nil,UIParent,"UIPanelButtonTemplate")
OkButton:SetSize(120,20)
OkButton:SetText("World Quests List: Lock")
OkButton:Hide()
CloseButton = CreateFrame("Button",nil,UIParent,"UIPanelButtonTemplate")
CloseButton:SetSize(120,20)
CloseButton:SetPoint("TOP",OkButton,"BOTTOM")
CloseButton:SetText(CLOSE)
CloseButton:SetScript("OnClick",function()
ShellGameDisable()
end)
CloseButton:Hide()
ResizeFrame = CreateFrame("Frame",nil,UIParent)
ResizeFrame:SetPoint("TOP",200,0)
ResizeFrame:SetPoint("BOTTOM",200,0)
ResizeFrame:SetWidth(8)
ResizeFrame:Hide()
ResizeFrame.b = ResizeFrame:CreateTexture(nil,"BACKGROUND")
ResizeFrame.b:SetAllPoints()
ResizeFrame.b:SetColorTexture(0.04,0.04,0.04,.9)
ResizeFrame.lv,ResizeFrame.lh = {},{}
for i=1,5 do
ResizeFrame.lv[i] = ResizeFrame:CreateTexture(nil,"BACKGROUND")
ResizeFrame.lv[i]:SetColorTexture(0.04,0.04,0.04,.9)
ResizeFrame.lv[i]:SetWidth(3)
ResizeFrame.lh[i] = ResizeFrame:CreateTexture(nil,"BACKGROUND")
ResizeFrame.lh[i]:SetColorTexture(0.04,0.04,0.04,.9)
ResizeFrame.lh[i]:SetHeight(3)
end
function UpdatePos(updateResizers)
if updateResizers then
ResizeFrame:SetPoint("TOP",size,0)
ResizeFrame:SetPoint("BOTTOM",size,0)
CenterFrame:SetPoint("LEFT",0,center)
CenterFrame:SetPoint("RIGHT",0,center)
end
for i=1,5 do
ResizeFrame.lh[i]:ClearAllPoints()
ResizeFrame.lh[i]:SetPoint("CENTER",UIParent,0,(i == 1 and size or i==2 and size / 2 or i==3 and 0 or i==4 and -size / 2 or i==5 and -size)+center)
ResizeFrame.lh[i]:SetWidth(size*2)
ResizeFrame.lv[i]:ClearAllPoints()
ResizeFrame.lv[i]:SetPoint("CENTER",UIParent,i == 1 and -size or i==2 and -size / 2 or i==3 and 0 or i==4 and size / 2 or i==5 and size,center)
ResizeFrame.lv[i]:SetHeight(size*2)
end
for i=1,4 do
for j=1,4 do
local frame = pointsFrames[(i-1)*4+j]
frame:ClearAllPoints()
frame:SetPoint("TOPLEFT",UIParent,"CENTER",j==1 and -size or j==2 and -size/2 or j==3 and 0 or j==4 and size/2,(i==1 and size or i==2 and size/2 or i==3 and 0 or i==4 and -size/2)+center)
frame:SetSize(size/2,size/2)
for k=1,8 do
frame.m[k]:SetSize(size/4/2,size/4/2)
end
frame.M:SetSize(size/4,size/4)
end
end
OkButton:SetPoint("TOPRIGHT",UIParent,"CENTER",size,center-size)
end
local function ResizeFrameOnUpdate(self)
size = self:GetLeft() - GetScreenWidth() / 2
VWQL.ShellGameSize = size
UpdatePos()
end
ResizeFrame:EnableMouse(true)
ResizeFrame:SetMovable(true)
ResizeFrame:RegisterForDrag("LeftButton")
ResizeFrame:SetScript("OnDragStart", function(self)
if self:IsMovable() then
self:StartMoving()
self:SetScript("OnUpdate", ResizeFrameOnUpdate)
end
end)
ResizeFrame:SetScript("OnDragStop", function(self)
self:StopMovingOrSizing()
self:SetScript("OnUpdate", nil)
end)
ResizeFrame:SetClampedToScreen(true)
ResizeFrame:SetClampRectInsets(-GetScreenWidth() / 2 - 1, 0, 0, 0)
ResizeFrame.ArrowHelp1 = CreateFrame("PlayerModel",nil,ResizeFrame)
ResizeFrame.ArrowHelp1:SetPoint("TOPRIGHT",-5,-10)
ResizeFrame.ArrowHelp1:SetSize(48,48)
ResizeFrame.ArrowHelp1:SetMouseClickEnabled(false)
ResizeFrame.ArrowHelp1:SetMouseMotionEnabled(false)
ResizeFrame.ArrowHelp1:SetDisplayInfo(63509)
ResizeFrame.ArrowHelp1:SetRoll(-math.pi / 2)
ResizeFrame.ArrowHelp2 = CreateFrame("PlayerModel",nil,ResizeFrame)
ResizeFrame.ArrowHelp2:SetPoint("TOPLEFT",5,-10)
ResizeFrame.ArrowHelp2:SetSize(48,48)
ResizeFrame.ArrowHelp2:SetMouseClickEnabled(false)
ResizeFrame.ArrowHelp2:SetMouseMotionEnabled(false)
ResizeFrame.ArrowHelp2:SetDisplayInfo(63509)
ResizeFrame.ArrowHelp2:SetRoll(math.pi / 2)
ResizeFrame:SetFrameStrata("DIALOG")
CenterFrame = CreateFrame("Frame",nil,UIParent)
CenterFrame:SetPoint("LEFT",0,0)
CenterFrame:SetPoint("RIGHT",0,0)
CenterFrame:SetHeight(6)
CenterFrame:Hide()
CenterFrame.b = CenterFrame:CreateTexture(nil,"BACKGROUND")
CenterFrame.b:SetAllPoints()
CenterFrame.b:SetColorTexture(0.04,0.04,0.04,.9)
local function OnUpdateCenter(self)
center = self:GetTop() - GetScreenHeight() / 2
VWQL.ShellGameCenter = center
UpdatePos()
end
CenterFrame:EnableMouse(true)
CenterFrame:SetMovable(true)
CenterFrame:RegisterForDrag("LeftButton")
CenterFrame:SetScript("OnDragStart", function(self)
if self:IsMovable() then
self:StartMoving()
self:SetScript("OnUpdate", OnUpdateCenter)
end
end)
CenterFrame:SetScript("OnDragStop", function(self)
self:StopMovingOrSizing()
self:SetScript("OnUpdate", nil)
end)
CenterFrame:SetClampedToScreen(true)
CenterFrame:SetClampRectInsets(0, 0, 0, 0)
CenterFrame.ArrowHelp1 = CreateFrame("PlayerModel",nil,CenterFrame)
CenterFrame.ArrowHelp1:SetPoint("BOTTOMLEFT",CenterFrame,"TOPLEFT",10,5)
CenterFrame.ArrowHelp1:SetSize(48,48)
CenterFrame.ArrowHelp1:SetMouseClickEnabled(false)
CenterFrame.ArrowHelp1:SetMouseMotionEnabled(false)
CenterFrame.ArrowHelp1:SetDisplayInfo(63509)
CenterFrame.ArrowHelp1:SetRoll(-math.pi)
CenterFrame.ArrowHelp2 = CreateFrame("PlayerModel",nil,CenterFrame)
CenterFrame.ArrowHelp2:SetPoint("TOPLEFT",CenterFrame,"BOTTOMLEFT",10,-5)
CenterFrame.ArrowHelp2:SetSize(48,48)
CenterFrame.ArrowHelp2:SetMouseClickEnabled(false)
CenterFrame.ArrowHelp2:SetMouseMotionEnabled(false)
CenterFrame.ArrowHelp2:SetDisplayInfo(63509)
--CenterFrame.ArrowHelp2:SetRoll(math.pi)
OkButton:SetScript("OnClick",function(self)
if ResizeFrame:IsShown() then
ResizeFrame:Hide()
CenterFrame:Hide()
VWQL.ShellGameLocked = true
self:SetText("WQL: Resize")
else
ResizeFrame:Show()
CenterFrame:Show()
self:SetText("WQL: Lock")
end
end)
end
local function ShellGameEnable()
CreateShellGame()
print("World Quests List: Shell Game helper loaded")
size,center = VWQL.ShellGameSize or size,VWQL.ShellGameCenter or center
UpdatePos(true)
if not VWQL.ShellGameLocked then
ResizeFrame:Show()
CenterFrame:Show()
OkButton:SetText("WQL: Lock")
else
OkButton:SetText("WQL: Resize")
end
for i=1,16 do
pointsFrames[i]:Show()
pointsFrames[i].M:ClearModel()
end
OkButton:Show()
CloseButton:Show()
end
function ShellGameDisable()
CreateShellGame()
ResizeFrame:Hide()
CenterFrame:Hide()
for i=1,16 do
pointsFrames[i]:Hide()
end
OkButton:Hide()
CloseButton:Hide()
end
WQLdb.ToMain = WQLdb.ToMain or {}
WQLdb.ToMain.ShellGameEnable = ShellGameEnable
WQLdb.ToMain.ShellGameDisable = ShellGameDisable
local ShellGameHelper = CreateFrame'Frame'
ShellGameHelper:RegisterEvent('QUEST_ACCEPTED')
ShellGameHelper:RegisterEvent('QUEST_REMOVED')
ShellGameHelper:RegisterEvent('PLAYER_ENTERING_WORLD')
ShellGameHelper:SetScript("OnEvent",function(self,event,arg1,arg2)
if event == 'QUEST_ACCEPTED' then
if arg2 and ShellGameQuests[arg2] then
if VWQL and VWQL.DisableShellGame then
return
end
self:RegisterEvent('UNIT_ENTERED_VEHICLE')
self:RegisterEvent('UNIT_EXITED_VEHICLE')
end
elseif event == 'QUEST_REMOVED' then
if arg1 and ShellGameQuests[arg1] then
ShellGameDisable()
self:UnregisterEvent('UNIT_ENTERED_VEHICLE')
self:UnregisterEvent('UNIT_EXITED_VEHICLE')
end
elseif event == 'UNIT_ENTERED_VEHICLE' then
if arg1 ~= "player" then
return
end
ShellGameEnable()
elseif event == 'UNIT_EXITED_VEHICLE' then
if arg1 ~= "player" then
return
end
ShellGameDisable()
elseif event == "PLAYER_ENTERING_WORLD" then
self:UnregisterEvent("PLAYER_ENTERING_WORLD")
if VWQL and VWQL.DisableShellGame then
return
end
for i=1,GetNumQuestLogEntries() do
local title, _, _, _, _, _, _, questID = GetQuestLogTitle(i)
if questID and ShellGameQuests[questID] then
return self:GetScript("OnEvent")(self,'QUEST_ACCEPTED',i,questID)
end
end
end
end)
end
|
AddCSLuaFile("shared.lua")
include("shared.lua")
/*-----------------------------------------------
*** Copyright (c) 2012-2017 by DrVrej, All rights reserved. ***
No parts of this code or any of its contents may be reproduced, copied, modified or adapted,
without the prior written consent of the author, unless otherwise indicated for stand-alone materials.
-----------------------------------------------*/
ENT.Model = {"models/Gibs/HGIBS.mdl"} -- The models it should spawn with | Picks a random one from the table
ENT.DoesDirectDamage = true -- Should it do a direct damage when it hits something?
ENT.DirectDamage = 100 -- How much damage should it do when it hits something
ENT.DirectDamageType = DMG_BURN -- Damage type
ENT.DecalTbl_DeathDecals = {"Scorch"}
ENT.SoundTbl_Idle = {"fx/spl/spl_restoration_travel_lp.wav"}
ENT.SoundTbl_OnCollide = {"fx/spl/spl_restoration_hit.wav"}
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomOnInitialize()
//util.SpriteTrail(self, 0, Color(90,90,90,255), false, 10, 1, 3, 1/(15+1)*0.5, "trails/smoke.vmt")
//ParticleEffectAttach("rocket_smoke", PATTACH_ABSORIGIN_FOLLOW, self, 0)
ParticleEffectAttach("death_spasm", PATTACH_ABSORIGIN_FOLLOW, self, 0)
local char = self:GetOwner():getChar()
if !(self:GetOwner():IsPlayer()) then return end
self.DirectDamage = 100 + (char:getAttrib("mgc") * 2) + ((25 * (char:getLevel()*char:getLevel()) / (char:getLevel()+char:getLevel())))
self.HasParticle = false
self:SetMaterial("Models/effects/vol_light001")
local enttarget1 = ents.Create("info_target")
enttarget1:SetParent(self)
enttarget1:SetPos(self:GetPos() + Vector(0,0,10))
enttarget1:Spawn()
local enttarget2 = ents.Create("info_target")
enttarget2:SetParent(self)
enttarget2:SetPos(self:GetPos() + Vector(-10,0,-10))
enttarget2:Spawn()
local enttarget3 = ents.Create("info_target")
enttarget3:SetParent(self)
enttarget3:SetPos(self:GetPos() + Vector(10,0,-10))
enttarget3:Spawn()
local enttarget4 = ents.Create("info_target")
enttarget4:SetParent(self)
enttarget4:SetPos(self:GetPos() + Vector(10, 10,-10))
enttarget4:Spawn()
local enttarget5 = ents.Create("info_target")
enttarget5:SetParent(self)
enttarget5:SetPos(self:GetPos() + Vector(10, 10, 10))
enttarget5:Spawn()
local enttarget6 = ents.Create("info_target")
enttarget6:SetParent(self)
enttarget6:SetPos(self:GetPos() + Vector(-10, 10,-10))
enttarget6:Spawn()
local enttarget7 = ents.Create("info_target")
enttarget6:SetParent(self)
enttarget6:SetPos(self:GetPos() + Vector(-20, 10,-10))
enttarget6:Spawn()
local enttarget8 = ents.Create("info_target")
enttarget6:SetParent(self)
enttarget6:SetPos(self:GetPos() + Vector(-10, 10,-20))
enttarget6:Spawn()
local enttarget9 = ents.Create("info_target")
enttarget6:SetParent(self)
enttarget6:SetPos(self:GetPos() + Vector(-10, 20,-10))
enttarget6:Spawn()
----------------------------------------------------------------------
local enttarget10 = ents.Create("info_target")
enttarget1:SetParent(self)
enttarget1:SetPos(self:GetPos() + Vector(30,0,10))
enttarget1:Spawn()
local enttarget11 = ents.Create("info_target")
enttarget2:SetParent(self)
enttarget2:SetPos(self:GetPos() + Vector(-30,0,-10))
enttarget2:Spawn()
local enttarget12 = ents.Create("info_target")
enttarget3:SetParent(self)
enttarget3:SetPos(self:GetPos() + Vector(10,0,-30))
enttarget3:Spawn()
local enttarget13 = ents.Create("info_target")
enttarget4:SetParent(self)
enttarget4:SetPos(self:GetPos() + Vector(10, 40,-10))
enttarget4:Spawn()
local enttarget14 = ents.Create("info_target")
enttarget5:SetParent(self)
enttarget5:SetPos(self:GetPos() + Vector(40, 10, 10))
enttarget5:Spawn()
local enttarget15 = ents.Create("info_target")
enttarget6:SetParent(self)
enttarget6:SetPos(self:GetPos() + Vector(-10, 10,-40))
enttarget6:Spawn()
local enttarget16 = ents.Create("info_target")
enttarget6:SetParent(self)
enttarget6:SetPos(self:GetPos() + Vector(-50, 10,-10))
enttarget6:Spawn()
local enttarget17 = ents.Create("info_target")
enttarget6:SetParent(self)
enttarget6:SetPos(self:GetPos() + Vector(-10, 50,-20))
enttarget6:Spawn()
local enttarget18 = ents.Create("info_target")
enttarget6:SetParent(self)
enttarget6:SetPos(self:GetPos() + Vector(-10, 20,-50))
enttarget6:Spawn()
util.SpriteTrail( enttarget1, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget2, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget3, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget4, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget5, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget6, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget7, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget8, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget9, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget10, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget11, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget12, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget13, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget14, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget15, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget16, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget17, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
util.SpriteTrail( enttarget18, 0, Color( 200, 105, 105, 255 ), false, 10, 1, 1, 1/(10+1)*0.5, "trails/laser.vmt" )
self.StartLight1 = ents.Create("light_dynamic")
self.StartLight1:SetKeyValue("brightness", "5")
self.StartLight1:SetKeyValue("distance", "200")
self.StartLight1:SetLocalPos(self:GetPos())
self.StartLight1:SetLocalAngles( self:GetAngles() )
self.StartLight1:Fire("Color", "255 200 100")
self.StartLight1:SetParent(self)
self.StartLight1:Spawn()
self.StartLight1:Activate()
self.StartLight1:Fire("TurnOn", "", 0)
self:DeleteOnRemove(self.StartLight1)
timer.Simple(10, function()
if(IsValid(self)) then
self:Remove()
end
end
)
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:DeathEffects(data,phys)
local effectdata = EffectData()
effectdata:SetOrigin(data.HitPos)
//effectdata:SetScale( 500 )
self.ExplosionLight1 = ents.Create("light_dynamic")
self.ExplosionLight1:SetKeyValue("brightness", "6")
self.ExplosionLight1:SetKeyValue("distance", "300")
self.ExplosionLight1:SetLocalPos(data.HitPos)
self.ExplosionLight1:SetLocalAngles(self:GetAngles())
self.ExplosionLight1:Fire("Color", "255 200 100")
self.ExplosionLight1:SetParent(self)
self.ExplosionLight1:Spawn()
self.ExplosionLight1:Activate()
self.ExplosionLight1:Fire("TurnOn", "", 0)
self:DeleteOnRemove(self.ExplosionLight1)
local char = self:GetOwner():getChar()
if !(self:GetOwner():IsPlayer()) then return end
local Ents = ents.FindInSphere(self:GetPos(), 500)
local hits = 0
for k, v in pairs(Ents) do
if hits > 10 then break end
if ((v:IsPlayer() and v != self:GetOwner() and !(v:Team() == self:GetOwner():Team())) or v:IsNPC()) then
local effectdata = EffectData()
effectdata:SetOrigin( v:GetPos() + v:OBBCenter() )
effectdata:SetStart( data.HitPos )
util.Effect( "effect_zad_dark_lightning", effectdata )
v:TakeDamage(50 + (char:getAttrib("mgc") * 2) + ((25 * (char:getLevel()*char:getLevel()) / (char:getLevel()+char:getLevel()))), self:GetOwner(), self:GetOwner())
v:Ignite(5)
hits = hits + 1
end
end
end
function ENT:CustomPhysicsObjectOnInitialize(phys)
phys:Wake()
phys:EnableGravity(false)
phys:SetMass( 20 )
phys:AddAngleVelocity( Vector( math.random( 500, 1000 )))
phys:EnableDrag( false )
end
function ENT:CustomOnThink()
if !(self.HasParticle) then
ParticleEffectAttach("death_spasm", PATTACH_ABSORIGIN_FOLLOW, self, 0)
self.HasParticle = true
end
local phys = self:GetPhysicsObject()
if IsValid(phys) then -- If the physics object is valid
if SERVER and IsValid(self.InitialTarget) then -- Is the VictimToTarget a valid entity?
local pos = Vector(self.InitialTarget:GetPos().x,self.InitialTarget:GetPos().y,-50)
phys:SetVelocity((pos - Vector(self:GetPos().x,self:GetPos().y,0)):GetNormal() * 200) -- Home in on the target
elseif SERVER and not IsValid(self.InitialTarget) then
local Ents = ents.FindInSphere(self:GetPos(), 200)
for k, v in pairs(Ents) do
if ((v:IsPlayer() and v != self:GetOwner()) or v:IsNPC()) then
self.InitialTarget = v
end
end
phys:SetVelocity(self:GetForward() * 500) -- Fly straight forward
end
end
end
function ENT:CustomOnDoDamage(data,phys,hitent)
hitent:Ignite(10)
end
/*-----------------------------------------------
*** Copyright (c) 2012-2017 by DrVrej, All rights reserved. ***
No parts of this code or any of its contents may be reproduced, copied, modified or adapted,
without the prior written consent of the author, unless otherwise indicated for stand-alone materials.
-----------------------------------------------*/
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
local OldVoltage
function ENT:Initialize()
self:SetModel("models/z-o-m-b-i-e/metro_2033/electro/m33_electro_box_12_4.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
if not Metrostroi.OldVoltage then
Metrostroi.OldVoltage = 0
end
end
function ENT:Use(ply)
--if not ply:IsAdmin() then return end
if Metrostroi.Voltage == 0 then
RunConsoleCommand("metrostroi_voltage",Metrostroi.OldVoltage ~= 0 and Metrostroi.OldVoltage or 750)
Metrostroi.OldVoltage = 0
else
Metrostroi.OldVoltage = GetConVar("metrostroi_voltage"):GetInt()
RunConsoleCommand("metrostroi_voltage",0)
Metrostroi.Voltage = 0
Metrostroi.VoltageOffByPlayerUse = true
end
self:EmitSound("buttons/lever8.wav",100,100)
end
function ENT:Think()
self:SetTotal(Metrostroi.TotalkWh)
self:SetRate(Metrostroi.TotalRateWatts)
self:SetV(Metrostroi.Voltage)
self:SetA(Metrostroi.Current)
if Metrostroi.Voltage >= 10 then
Metrostroi.VoltageOffByPlayerUse = nil
end
if Metrostroi.Voltage < 10 and not Metrostroi.VoltageOffByPlayerUse then
self.SoundTimer = self.SoundTimer or CurTime()
if (CurTime() - self.SoundTimer) > 1.0 then
self:EmitSound("ambient/alarms/klaxon1.wav", 100, 100)
self.SoundTimer = CurTime()
end
end
self:NextThink(CurTime())
return true
end
function ENT:OnRemove()
if Metrostroi.Voltage == 0 then
RunConsoleCommand("metrostroi_voltage",Metrostroi.OldVoltage ~= 0 and Metrostroi.OldVoltage or 750)
end
end
|
PrismObject = {
type = "PrismObject",
ENTITY_DETAIL_ID = 1,
Properties = {
},
Editor = {
Model = "Editor/Objects/Particles.cgf",
Icon = "Clouds.bmp",
},
}
-------------------------------------------------------
function PrismObject:OnSpawn()
self:SetFlags(ENTITY_FLAG_CLIENT_ONLY, 0);
end
-------------------------------------------------------
function PrismObject:OnInit()
self:NetPresent(0);
self:Create();
end
-------------------------------------------------------
function PrismObject:OnShutDown()
end
-------------------------------------------------------
function PrismObject:Create()
local props = self.Properties;
self:LoadPrismObject(0);
end
-------------------------------------------------------
function PrismObject:Delete()
self:FreeSlot(0);
end
------------------------------------------------------------------------------------------------------
-- OnReset called only by the editor.
------------------------------------------------------------------------------------------------------
function PrismObject:OnReset()
local bCurrentlyHasObj = self:IsSlotValid(0);
if (not bCurrentlyHasObj) then
self:Create();
end
end
-------------------------------------------------------
function PrismObject:OnSave(tbl)
tbl.bHasObject = self:IsSlotValid(0);
if (tbl.bHasObject) then
-- todo: save pos
end
end
-------------------------------------------------------
function PrismObject:OnLoad(tbl)
local bCurrentlyHasObject = self:IsSlotValid(0);
local bWantObject = tbl.bHasObject;
if (bWantObject and not bCurrentlyHasObject) then
self:Create();
-- todo: restore pos
elseif (not bWantObject and bCurrentlyHasObject) then
self:Delete();
end
end
-------------------------------------------------------
-- Hide Event
-------------------------------------------------------
function PrismObject:Event_Hide()
self:Delete();
end
-------------------------------------------------------
-- Show Event
-------------------------------------------------------
function PrismObject:Event_Show()
self:Create();
end
PrismObject.FlowEvents =
{
Inputs =
{
Hide = { PrismObject.Event_Hide, "bool" },
Show = { PrismObject.Event_Show, "bool" },
},
Outputs =
{
Hide = "bool",
Show = "bool",
},
}
|
UT.Spawn = {}
UT.Spawn.available = {}
UT.Spawn.position = "crosshair"
function UT.Spawn.setMode(mode)
UT.Spawn.index = 1
UT.Spawn.mode = mode
UT.showMessage("spawn mode set to " .. mode, UT.colors.info)
end
function UT.Spawn.setModeEnemies()
UT.Spawn.setMode("enemies")
end
function UT.Spawn.setModeAllies()
UT.enableUnlimitedConversions()
UT.Spawn.setMode("allies")
end
function UT.Spawn.setModeCivilians()
UT.Spawn.available.civilians = {}
for key, value in pairs(UT.Tables.civilians) do
if not UT.unitLoaded(Idstring(value)) then goto continue end
table.insert(UT.Spawn.available.civilians, value)
::continue::
end
if not UT.checkTable(UT.Spawn.available.civilians) then
UT.showMessage("no civilians available here", UT.colors.error)
return
end
UT.Spawn.setMode("civilians")
end
function UT.Spawn.setModeLoots()
UT.Spawn.available.loots = {}
for key, value in pairs(UT.Tables.loots) do
if not UT.unitLoaded(Idstring(value)) then goto continue end
table.insert(UT.Spawn.available.loots, value)
::continue::
end
if not UT.checkTable(UT.Spawn.available.loots) then
UT.showMessage("no loots available here", UT.colors.error)
return
end
UT.Spawn.setMode("loots")
end
function UT.Spawn.setModeEquipments()
UT.Spawn.available.equipments = {}
for key, value in pairs(UT.Tables.equipments) do
table.insert(UT.Spawn.available.equipments, value)
end
UT.Spawn.setMode("equipments")
end
function UT.Spawn.setModePackages()
UT.Spawn.available.packages = {}
for key, value in pairs(UT.Tables.packages) do
table.insert(UT.Spawn.available.packages, value)
end
function tweak_data.gage_assignment:get_num_assignment_units()
return 1000000
end
UT.Spawn.setMode("packages")
end
function UT.Spawn.setModeBags()
local message = "Your game may crash by spawning a bag that doesn't exist in this level."
managers.chat:_receive_message(1, "Ultimate Trainer", message, UT.colors.danger)
UT.Spawn.setMode("bags")
end
function UT.Spawn.spawnEnemy(id)
local position = UT.Spawn.getPosition()
if not position then return end
local rotation = UT.getCameraRotationFlat()
local unit = UT.spawnUnit(Idstring(id), position, rotation)
if not unit then return end
UT.Spawn.setTeam(unit, "combatant")
end
function UT.Spawn.spawnAlly(id)
local position = UT.Spawn.getPosition()
if not position then return end
local rotation = UT.getCameraRotationFlat()
local unit = UT.spawnUnit(Idstring(id), position, rotation)
if not unit then return end
UT.Spawn.setTeam(unit, "combatant")
UT.Spawn.convertEnemy(unit)
end
function UT.Spawn.spawnCivilian(id)
local position = UT.Spawn.getPosition()
if not position then return end
local rotation = UT.getCameraRotationFlat()
local unit = UT.spawnUnit(Idstring(id), position, rotation)
if not unit then return end
UT.Spawn.setTeam(unit, "non_combatant")
unit:brain():action_request({
type = "act",
variant = "cm_sp_stand_idle"
})
end
function UT.Spawn.spawnLoot(name)
local position = UT.Spawn.getPosition()
if not position then return end
local rotation = UT.getCameraRotationFlat()
UT.spawnUnit(Idstring(name), position, rotation)
end
function UT.Spawn.spawnEquipment(name)
local position = UT.Spawn.getPosition()
if not position then return end
local rotation = UT.getCameraRotationFlat()
if name == "ammo_bag" then
AmmoBagBase.spawn(position, rotation, 1)
elseif name == "doctor_bag" then
DoctorBagBase.spawn(position, rotation, 4)
elseif name == "first_aid_kit" then
FirstAidKitBase.spawn(position, rotation, 1)
elseif name == "body_bags_bag" then
BodyBagsBagBase.spawn(position, rotation)
elseif name == "grenade_crate" then
GrenadeCrateBase.spawn(position, rotation)
elseif name == "trip_mine" then
if UT.Spawn.position == "crosshair" then
local crosshairRay = Utils:GetCrosshairRay()
if not crosshairRay then return end
rotation = Rotation(crosshairRay.normal, math.UP)
elseif UT.Spawn.position == "self" then
rotation = Rotation(UT.getCameraRotation():yaw(), 90, 0)
end
local unit = TripMineBase.spawn(position, rotation, true)
if not unit then return end
local playerUnit = managers.player:player_unit()
unit:base():set_active(true, playerUnit)
elseif name == "sentry_gun" then
UT.Spawn.setEquipment("sentry_gun")
local playerUnit = managers.player:player_unit()
local unit = SentryGunBase.spawn(playerUnit, position, rotation)
if not unit then return end
unit:base():post_setup(1)
managers.network:session():send_to_peers_synched("from_server_sentry_gun_place_result", 1, 0, unit, 2, 2, true, 2)
end
end
function UT.Spawn.spawnPackage(id)
local position = UT.Spawn.getPosition()
if not position then return end
local rotation = UT.getCameraRotationFlat()
UT.spawnUnit(Idstring(id), position, rotation)
end
function UT.Spawn.spawnBag(name)
local position = UT.getCameraPosition()
local rotation = UT.getCameraRotation()
local forward = UT.getCameraForward()
managers.player:server_drop_carry(name, managers.money:get_bag_value(name), true, true, 1, position, rotation, forward, 100, nil, nil)
end
function UT.Spawn.removeNPCs()
local units = {}
for key, value in pairs(managers.enemy:all_civilians()) do
table.insert(units, value.unit)
end
for key, value in pairs(managers.enemy:all_enemies()) do
if value.unit:brain()._attention_handler._team.id == "neutral1" then
goto continue
end
table.insert(units, value.unit)
::continue::
end
local count = UT.removeUnits(units)
UT.showMessage("removed " .. tostring(count) .. " npc" .. (count > 1 and "s" or ""), UT.colors.info)
end
function UT.Spawn.removeLoots()
local units = {}
for key, unit in pairs(managers.interaction._interactive_units) do
if not alive(unit) then goto continue end
if not UT.Tables.loots[unit:name():key()] then goto continue end
table.insert(units, unit)
::continue::
end
local count = UT.removeUnits(units)
UT.showMessage("removed " .. tostring(count) .. " loot" .. (count > 1 and "s" or ""), UT.colors.info)
end
function UT.Spawn.removeEquipments()
local units = {}
for key, unit in pairs(World:find_units_quick("all")) do
if not alive(unit) then goto continue end
if not UT.Tables.equipments[unit:name():key()] then goto continue end
table.insert(units, unit)
::continue::
end
local count = UT.removeUnits(units)
UT.showMessage("removed " .. tostring(count) .. " equipment" .. (count > 1 and "s" or ""), UT.colors.info)
end
function UT.Spawn.removePackages()
local units = {}
for key, unit in pairs(managers.interaction._interactive_units) do
if not alive(unit) then goto continue end
if not UT.Tables.packages[unit:name():key()] then goto continue end
table.insert(units, unit)
::continue::
end
local count = UT.removeUnits(units)
UT.showMessage("removed " .. tostring(count) .. " package" .. (count > 1 and "s" or ""), UT.colors.info)
end
function UT.Spawn.removeBags()
local units = {}
for key, unit in pairs(managers.interaction._interactive_units) do
if not alive(unit) then goto continue end
if not UT.Tables.bagsKeys[unit:name():key()] then goto continue end
table.insert(units, unit)
::continue::
end
local count = UT.removeUnits(units)
UT.showMessage("removed " .. tostring(count) .. " bag" .. (count > 1 and "s" or ""), UT.colors.info)
end
function UT.Spawn.disposeCorpses()
managers.enemy:dispose_all_corpses()
UT.showMessage("corpses disposed", UT.colors.info)
end
function UT.Spawn.getPosition()
if UT.Spawn.position == "crosshair" then
local crosshairRay = Utils:GetCrosshairRay()
if not crosshairRay then
UT.showMessage("impossible to spawn", UT.colors.error)
return
end
return crosshairRay.position
elseif UT.Spawn.position == "self" then
return UT.getPlayerPosition()
end
end
function UT.Spawn.setPosition(position)
UT.Spawn.position = position
UT.showMessage("spawn position set to " .. position, UT.colors.info)
end
function UT.Spawn.setTeam(unit, team)
if not alive(unit) then return end
local teamId = tweak_data.levels:get_default_team_ID(team)
local teamData = managers.groupai:state():team_data(teamId)
unit:movement():set_team(teamData)
end
function UT.Spawn.convertEnemy(unit)
if not alive(unit) then return end
managers.groupai:state():convert_hostage_to_criminal(unit)
managers.groupai:state():sync_converted_enemy(unit)
unit:contour():add("friendly", true)
end
function UT.Spawn.setEquipment(equipment)
managers.player:clear_equipment()
managers.player._equipment.selections = {}
managers.player:add_equipment({equipment = equipment})
end
UTClassSpawn = true
|
config = {
t0 = true,
t1 = 10
}
|
local ffi = require("ffi");
local Queue = require("schedlua.queue")
local Task = require("schedlua.task");
print("== SCHEDULER INCLUDED==")
--[[
The Scheduler supports a cooperative multi-tasking
environment. The fundamental unit of execution is the Lua coroutine.
Lua coroutines allow a program to rapidly switch between different coding
contexts. The language itself provides the simple switching mechanism, but
does not provide a mechanism to organize these various tasks, which means there
are no guarantees in terms of fairness, nor organizing principles to ensure any
particular model or multi-tasking. The scheduler provides a mechanism by which
work can be organized and executed in a manner that provides coherence to a larger
application.
The scheduler is of primary benefit which it is managing hundreds, if not
thousands of tasks which intend to execute concurrently.
Work that is to be performed is encapsulated in a 'task' object. The task object
contains the entirety of the context related to a particular task. This is the
parameters that were used to begin execution, as well as a reference to the function
that is actually to be run to perform the task.
The scheduler works by maintaining a 'ReadyList', which are the tasks which
are ready to receive some compute cycles. Tasks are added to the list by
calling the scheduler's 'scheduleTask()' function.
Putting a task on the ready list does not cause it to execute immediately. It
is just an indicator that at some point in the future this task will execute.
Which task is to execute next is determined in the scheduler's 'step()' function.
Here, the schedulers task picking routine (first in first out) pulls the next
task out of the ReadyList, and resumes it.
A task will run until it explicitly calls 'yield()', or yields implicitly by
performing an operation that in turn calls yield.
This scheduler is fairly simple, and will be appropriate for many relatively
simple cooperative multi-tasking environments. In cases where a different
policy of fairness is required, a different scheduler might be more appropriate.
The scheduler is implemented as an object, and you must create an instance of
it to be used in your application. This allows for the possibility of
maintaining multiple different schedulers within the same Lua state. It is
not likely that this will be a highly used featured, but the possibility exists.
--]]
local Scheduler = {}
setmetatable(Scheduler, {
__call = function(self, ...)
return self:new(...)
end,
})
local Scheduler_mt = {
__index = Scheduler,
}
function Scheduler.init(self, ...)
local obj = {
TasksReadyToRun = Queue();
}
setmetatable(obj, Scheduler_mt)
return obj;
end
function Scheduler.new(self, ...)
return self:init(...)
end
--[[
Instance Methods
--]]
--[[
tasksPending
A simple method to let anyone know how many tasks are currently
on the ready to run list.
This might be useful when you're running some predicate logic based
on how many tasks there are.
--]]
function Scheduler.tasksPending(self)
return self.TasksReadyToRun:length();
end
--[[
Task Handling
--]]
-- put a task on the ready list
-- the 'task' should be something that can be executed,
-- whether it's a function, functor, or something that has a '__call'
-- metamethod implemented.
-- The 'params' is a table of parameters which will be passed to the function
-- when it's ready to run.
function Scheduler.scheduleTask(self, task, params, priority)
--print("Scheduler.scheduleTask: ", task, params)
params = params or {}
if not task then
return false, "no task specified"
end
-- this is totally screwy to me - "priority" is nill everywhere, but "Priority" holds the appropriate value. I changed "if priority" to "if task.Priority" and it works now, but i have no idea why
task:setParams(params);
if task.Priority == 0 then
--print("if: ", task.Priority);
self.TasksReadyToRun:pushFront(task);
else
--print("else: ", task.Priority);
self.TasksReadyToRun:enqueue(task);
end
task.state = "readytorun"
return task;
end
function Scheduler.removeTask(self, task)
--print("REMOVING DEAD TASK: ", task);
return true;
end
function Scheduler.getCurrentTask(self)
return self.CurrentFiber;
end
function Scheduler.suspendCurrentTask(self, ...)
self.CurrentFiber.state = "suspended"
end
function Scheduler.step(self)
-- Now check the regular fibers
local task = self.TasksReadyToRun:dequeue()
--print("task in step: ", priority);
-- If no fiber in ready queue, then just return
if task == nil then
--print("Scheduler.step: NO TASK")
return true
end
if task:getStatus() == "dead" then
self:removeTask(task)
return true;
end
-- If the task we pulled off the active list is
-- not dead, then perhaps it is suspended. If that's true
-- then it needs to drop out of the active list.
-- We assume that some other part of the system is responsible for
-- keeping track of the task, and rescheduling it when appropriate.
if task.state == "suspended" then
--print("suspended task wants to run")
return true;
end
-- If we have gotten this far, then the task truly is ready to
-- run, and it should be set as the currentFiber, and its coroutine
-- is resumed.
self.CurrentFiber = task;
local results = {task:resume()};
-- once we get results back from the resume, one
-- of two things could have happened.
-- 1) The routine exited normally
-- 2) The routine yielded
--
-- In both cases, we parse out the results of the resume
-- into a success indicator and the rest of the values returned
-- from the routine
--local pcallsuccess = results[1];
--table.remove(results,1);
local success = results[1];
table.remove(results,1);
--print("PCALL, RESUME: ", pcallsuccess, success)
-- no task is currently executing
self.CurrentFiber = nil;
if not success then
print("RESUME ERROR")
print(unpack(results));
end
-- Again, check to see if the task is dead after
-- the most recent resume. If it's dead, then don't
-- bother putting it back into the readytorun queue
-- just remove the task from the list of tasks
if task:getStatus() == "dead" then
self:removeTask(task)
return true;
end
-- The only way the task will get back onto the readylist
-- is if it's state is 'readytorun', otherwise, it will
-- stay out of the readytorun list.
if task.state == "readytorun" then
self:scheduleTask(task, results);
end
end
return Scheduler
|
local compile = function(f)
if file.exists(f) then
local newf = f:gsub("%w+/", "")
file.rename(f, newf)
print('Compiling:', newf)
node.compile(newf)
file.remove(newf)
collectgarbage()
end
end
local serverFiles = {
'sofar_hyd6es.lua',
'sofar_read_grid.lua',
}
for i, f in ipairs(serverFiles) do
compile(f)
end
file.remove("invertor_compile.lua")
|
DefineClass.SupplyRocket = {
__parents = { "RocketBase" },
}
-- backward compatibility
--[[
Some rocket states used to happen in game-time threads which aren't saved anywhere and can be potentially saved.
The following functions are used to hook onto these running threads and phase the rocket to a proper command.
--]]
-- potentially called from a created GameTime thread within LandOnSite
function SupplyRocket:UnloadCargo()
self:SetCommand("Unload")
Halt()
end
-- potentially called from a created GameTime thread within LandOnSite or BuildingUpdate
function SupplyRocket:Launch()
self:SetCommand("Takeoff")
Halt()
end
-- potentially called from within Launch (see above), in that case it's an automated return to Mars
function SupplyRocket:OrderLanding()
self:SetCommand("FlyToMars")
Halt()
end
-- potentially called at the very start of the created GameTime thread within LandOnSite
function SupplyRocket:Land()
if IsValid(self.landing_site) then
self:SetCommand("LandOnMars", self.landing_site)
else
self:SetCommand("WaitInOrbit")
end
Halt()
end
-- end backward compatibility
function SupplyRocket:UnloadCargoObjects(cargo, out)
RocketBase.UnloadCargoObjects(self, cargo, out)
self.cargo = nil
end
function SupplyRocket:CheatGenerateDepartures()
self:GenerateDepartures(true, true)
end
function SupplyRocket:GenerateDepartures(count_earthsick, count_tourists)
if not self.can_fly_colonists then -- for compatibility
return
end
assert(self:IsValidPos())
local domes = self.city.labels.Dome or ""
if not self.departures then self.departures = {} end
if not self.boarding then self.boarding = {} end
if not self.boarded then self.boarded = {} end
local earthsick = {}
local tourists = {}
local colonists = UIColony.city_labels.labels.Colonist or {}
for _, colonist in ipairs(colonists) do
if colonist:CanChangeCommand() and (count_earthsick and colonist.status_effects.StatusEffect_Earthsick or (count_tourists and colonist:IsTouristReadyToGoHome())) then
local is_viable_rocket = colonist:GetMapID() ~= self:GetMapID() or IsInWalkingDist(self, colonist, const.ColonistMaxDepartureRocketDist)
if is_viable_rocket then
if colonist.traits.Tourist then
tourists[#tourists + 1] = colonist
else
earthsick[#earthsick + 1] = colonist
end
colonist:SetCommand("LeavingMars", self)
end
end
end
if count_earthsick and #earthsick > 0 then
AddOnScreenNotification("LeavingMars", false, {colonists_count = #earthsick}, earthsick, self:GetMapID())
end
if count_tourists and #tourists > 0 then
AddOnScreenNotification("LeavingMarsTourists", false, {tourists_count = #tourists}, tourists, self:GetMapID())
end
end
function SupplyRocket:UIOpenTouristOverview()
local reward_info = self:GetTourismRewardInfo()
HolidayRating:OpenTouristOverview(reward_info)
end
function SupplyRocket:ToggleAutoExport()
self.auto_export = not self.auto_export
self:AttachSign(self.auto_export, "SignTradeRocket")
if not self.auto_export then -- can be disabled at any time
if self.reserved_site then
assert(IsValid(self.landing_site))
DoneObject(self.landing_site)
self.landing_site = nil
end
self.reserved_site = nil
else -- can only be enabled when rocket is landed and has valid landing site
assert(IsValid(self.landing_site))
self.landing_site.disable_selection = false
if self.waiting_resources then
Wakeup(self.command_thread)
end
end
if not self.auto_export and IsValid(self.site_particle) and self.status ~= "landing" then
StopParticles(self.site_particle)
if SelectedObj == self then
SelectObj(false)
end
end
ObjModified(self)
end
function SupplyRocket:ToggleAllowExport(broadcast)
local allow = not self.allow_export
if broadcast then
local list = self.city.labels.SupplyRocket or empty_table
for _, rocket in ipairs(list) do
if rocket.allow_export ~= allow then
rocket:ToggleAllowExport()
end
end
return
end
self.allow_export = not self.allow_export
if not self.allow_export and self.auto_export then
self:ToggleAutoExport()
end
if self.command == "Refuel" or self.command == "WaitLaunchOrder" then
if self.allow_export then
-- cancel any remaining supply requests, interrupt drones, carry remaining supply to the new demand request
self:InterruptDrones(nil, function(drone)
if (drone.target == self) or
(drone.d_request and drone.d_request:GetBuilding() == self) or
(drone.s_request and drone.s_request:GetBuilding() == self) then
return drone
end
end)
self:DisconnectFromCommandCenters()
-- create export request, transfer the remaining unload amount, close the unload request
local stored = self.unload_request and self.unload_request:GetActualAmount() or 0
local unit_count = 1 + (self.max_export_storage / (const.ResourceScale * 10)) --1 per 10
self.export_requests = { self:AddDemandRequest("PreciousMetals", self.max_export_storage - stored, 0, unit_count) }
if self.unload_request then
table.remove_entry(self.task_requests, self.unload_request)
self.unload_request = nil
end
self:ConnectToCommandCenters()
else
-- cancel demand request, interrupt drones, create supply request for the already stocked amount
if self.export_requests and #self.export_requests > 0 then
assert(#self.export_requests == 1)
self:InterruptDrones(nil, function(drone)
if (drone.target == self) or
(drone.d_request and drone.d_request:GetBuilding() == self) or
(drone.s_request and drone.s_request:GetBuilding() == self) then
return drone
end
end)
self:DisconnectFromCommandCenters()
-- create unload request, transfer the amount delivered, close the export request
local amount = self:GetStoredExportResourceAmount()
local unit_count = 1 + (self.max_export_storage / (const.ResourceScale * 10)) --1 per 10
self.unload_request = self:AddSupplyRequest("PreciousMetals", amount, const.rfPostInQueue, unit_count)
table.remove_entry(self.task_requests, self.export_requests[1])
self.export_requests = nil
self:ConnectToCommandCenters()
end
end
end
ObjModified(self)
end
function SupplyRocket:GetUIExportStatus()
if self.allow_export then
return T(286, "Gathering exports<right><preciousmetals(StoredExportResourceAmount, max_export_storage)>")
elseif self:GetStoredExportResourceAmount() > 0 then
return T(11470, "Unloading <right><preciousmetals(StoredExportResourceAmount, max_export_storage)>")
end
end
function SupplyRocket:GetNumBoardedTourists()
local count = 0
for _, colonist in ipairs(self.boarded or empty_table) do
if colonist.traits.Tourist then
count = count + 1
end
end
return count
end
function SupplyRocket:WaitingRefurbish()
WaitWakeup()
end
|
local angleshit = 1;
local anglevar = 1;
local camBumpFunny = 0.005;
local draintheshit = 0;
local addedthe = 0;
function onCreatePost()
initSaveData('luaCustomOptions')
for i = 0, getProperty('opponentStrums.length')-1 do
setPropertyFromGroup('opponentStrums',i,'visible',false)
setPropertyFromGroup('opponentStrums',i,'y',130)
setPropertyFromGroup('opponentStrums',i,'x',-9999)
end
for i = 0, getProperty('playerStrums.length')-1 do
setPropertyFromGroup('playerStrums',i,'visible',false)
end
makeAnimatedLuaSprite('DialogBoxes', 'DialogBoxes', 400, 500);
addLuaSprite('DialogBoxes', true);
scaleObject('DialogBoxes', 0.5, 0.5)
end
function onBeatHit()
if getDataFromSave('luaCustomOptions', 'modcharts') then
if curBeat % 2 == 0 then
angleshit = anglevar;
else
angleshit = -anglevar;
end
setProperty('camHUD.angle',angleshit*3)
setProperty('camGame.angle',angleshit*3)
doTweenAngle('turn', 'camHUD', angleshit, stepCrochet*0.002, 'circOut')
doTweenAngle('tt', 'camGame', angleshit, stepCrochet*0.002, 'circOut')
if curBeat == 32 then
for i = 0, getProperty('playerStrums.length')-1 do
setPropertyFromGroup('playerStrums',i,'visible',true)
end
camBumpFunny = 0.015
end
triggerEvent('Add Camera Zoom', camBumpFunny)
end
if getDataFromSave('luaCustomOptions', 'screen-effects') then
if curBeat == 126 or curBeat == 238 or curBeat == 279 or curBeat == 302 then
makeLuaSprite('rip', 'rip', 0, 200);
addLuaSprite('rip', true);
scaleObject('rip', 0.8, 0.8)
end
if curBeat == 128 or curBeat == 240 or curBeat == 280 or curBeat == 304 then
triggerEvent('Screen Shake', "0.8, 0.05")
removeLuaSprite('rip')
end
if curBeat == 241 or curBeat == 243 or curBeat == 245 or curBeat == 384 then
makeLuaSprite('rip', 'rip', 0, 200);
addLuaSprite('rip', false);
scaleObject('rip', 0.8, 0.8)
end
if curBeat == 242 or curBeat == 244 or curBeat == 246 or curBeat == 386 then
triggerEvent('Screen Shake', "0.8, 0.05")
removeLuaSprite('rip')
end
end
if getDataFromSave('luaCustomOptions', 'screen-effects') then
if curBeat == 92 then
triggerEvent('Screen Shake', "1, 0.025")
addAnimationByPrefix('DialogBoxes', 'HelpMeDialog', 'HelpMeDialog', 60, false);
objectPlayAnimation('DialogBoxes', 'HelpMeDialog', true);
end
end
if getDataFromSave('luaCustomOptions', 'mechanics') then
if curBeat == 126 or curBeat == 240 or curBeat == 304 or curBeat == 352 then
if addedthe == 0 then
addAnimationByPrefix('DialogBoxes', 'SpaceDialog', 'SpaceDialog', 30, false);
addedthe = 1
end
objectPlayAnimation('DialogBoxes', 'SpaceDialog', true);
draintheshit = 1
end
end
end
function onStepHit()
if curStep == 1 or curStep == 32 or curStep == 64 or curStep == 96 then
makeAnimatedLuaSprite('Fade', 'Fade', -500, -150);
addLuaSprite('Fade', false);
scaleObject('Fade', 25, 25)
addAnimationByPrefix('Fade', 'Fade', 'Fade', 30, false);
objectPlayAnimation('Fade', 'Fade', false);
end
if getDataFromSave('luaCustomOptions', 'mechanics') then
if draintheshit == 1 then
healthreal = getProperty('health');
setProperty('health', (healthreal - 0.05));
end
end
end
function onUpdate()
if getProperty('dad.animation.curAnim.name') == 'idle' then
else
triggerEvent('Screen Shake', "0.1, 0.003")
end
if getDataFromSave('luaCustomOptions', 'mechanics') then
if keyPressed('space') == true then
if draintheshit == 1 then
draintheshit = 0
addAnimationByPrefix('DialogBoxes', 'SpaceDialogClose', 'SpaceDialogClose', 30, false);
objectPlayAnimation('DialogBoxes', 'SpaceDialogClose', true);
end
end
end
end
|
module ('content.draw', package.seeall)
require 'base.drawable'
rectangle = base.drawable:new {
mode = 'fill',
width = 32,
height = 32
}
function rectangle:getWidth ()
return self.width
end
function rectangle:getHeight ()
return self.height
end
function rectangle:draw (element, graphics)
graphics.setColor(self.color)
graphics.rectangle(
self.mode,
-self.width/2,
-self.height/2,
self.width,
self.height
)
end
function rectangle:left ()
return -self.width/2
end
function rectangle:right ()
return self.width/2
end
function rectangle:top ()
return -self.height/2
end
function rectangle:bottom ()
return self.height/2
end
function rectangle:inside (p)
if p.x < self:left() then return false end
if p.y < self:top() then return false end
if p.x > self:right() then return false end
if p.y > self:bottom() then return false end
return true
end
|
AddCSLuaFile()
SWEP.ViewModel = Model( "models/weapons/c_arms_animations.mdl" )
SWEP.WorldModel = Model( "models/MaxOfS2D/camera.mdl" )
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = true
SWEP.Secondary.Ammo = "none"
SWEP.PrintName = "#GMOD_Camera"
SWEP.Slot = 5
SWEP.SlotPos = 1
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = false
SWEP.Spawnable = true
SWEP.ShootSound = Sound( "NPC_CScanner.TakePhoto" )
if ( SERVER ) then
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
--
-- A concommand to quickly switch to the camera
--
concommand.Add( "gmod_camera", function( player, command, arguments )
player:SelectWeapon( "gmod_camera" )
end )
end
--
-- Network/Data Tables
--
function SWEP:SetupDataTables()
self:NetworkVar( "Float", 0, "Zoom" )
self:NetworkVar( "Float", 1, "Roll" )
if ( SERVER ) then
self:SetZoom( 70 )
self:SetRoll( 0 )
end
end
--
-- Initialize Stuff
--
function SWEP:Initialize()
self:SetHoldType( "camera" )
end
--
-- Reload resets the FOV and Roll
--
function SWEP:Reload()
if ( !self.Owner:KeyDown( IN_ATTACK2 ) ) then self:SetZoom( self.Owner:IsBot() && 75 || self.Owner:GetInfoNum( "fov_desired", 75 ) ) end
self:SetRoll( 0 )
end
--
-- PrimaryAttack - make a screenshot
--
function SWEP:PrimaryAttack()
self:DoShootEffect()
-- If we're multiplayer this can be done totally clientside
if ( !game.SinglePlayer() && SERVER ) then return end
if ( CLIENT && !IsFirstTimePredicted() ) then return end
self.Owner:ConCommand( "jpeg" )
end
--
-- SecondaryAttack - Nothing. See Tick for zooming.
--
function SWEP:SecondaryAttack()
end
--
-- Mouse 2 action
--
function SWEP:Tick()
if ( CLIENT && self.Owner != LocalPlayer() ) then return end -- If someone is spectating a player holding this weapon, bail
local cmd = self.Owner:GetCurrentCommand()
if ( !cmd:KeyDown( IN_ATTACK2 ) ) then return end -- Not holding Mouse 2, bail
self:SetZoom( math.Clamp( self:GetZoom() + cmd:GetMouseY() * 0.1, 0.1, 175 ) ) -- Handles zooming
self:SetRoll( self:GetRoll() + cmd:GetMouseX() * 0.025 ) -- Handles rotation
end
--
-- Override players Field Of View
--
function SWEP:TranslateFOV( current_fov )
return self:GetZoom()
end
--
-- Deploy - Allow lastinv
--
function SWEP:Deploy()
return true
end
--
-- Set FOV to players desired FOV
--
function SWEP:Equip()
if ( self:GetZoom() == 70 && self.Owner:IsPlayer() && !self.Owner:IsBot() ) then
self:SetZoom( self.Owner:GetInfoNum( "fov_desired", 75 ) )
end
end
function SWEP:ShouldDropOnDie() return false end
--
-- The effect when a weapon is fired successfully
--
function SWEP:DoShootEffect()
self:EmitSound( self.ShootSound )
self:SendWeaponAnim( ACT_VM_PRIMARYATTACK )
self.Owner:SetAnimation( PLAYER_ATTACK1 )
if ( SERVER && !game.SinglePlayer() ) then
--
-- Note that the flash effect is only
-- shown to other players!
--
local vPos = self.Owner:GetShootPos()
local vForward = self.Owner:GetAimVector()
local trace = {}
trace.start = vPos
trace.endpos = vPos + vForward * 256
trace.filter = self.Owner
local tr = util.TraceLine( trace )
local effectdata = EffectData()
effectdata:SetOrigin( tr.HitPos )
util.Effect( "camera_flash", effectdata, true )
end
end
if ( SERVER ) then return end -- Only clientside lua after this line
SWEP.WepSelectIcon = surface.GetTextureID( "vgui/gmod_camera" )
-- Don't draw the weapon info on the weapon selection thing
function SWEP:DrawHUD() end
function SWEP:PrintWeaponInfo( x, y, alpha ) end
function SWEP:HUDShouldDraw( name )
-- So we can change weapons
if ( name == "CHudWeaponSelection" ) then return true end
if ( name == "CHudChat" ) then return true end
return false
end
function SWEP:FreezeMovement()
-- Don't aim if we're holding the right mouse button
if ( self.Owner:KeyDown( IN_ATTACK2 ) || self.Owner:KeyReleased( IN_ATTACK2 ) ) then
return true
end
return false
end
function SWEP:CalcView( ply, origin, angles, fov )
if ( self:GetRoll() != 0 ) then
angles.Roll = self:GetRoll()
end
return origin, angles, fov
end
function SWEP:AdjustMouseSensitivity()
if ( self.Owner:KeyDown( IN_ATTACK2 ) ) then return 1 end
return self:GetZoom() / 80
end
|
--[[
Vector of two elements. Extremely useful for 2D math.
]]--
local obj = require('src.lua-cor.obj')
local typ = require('src.lua-cor.typ')
local ass = require 'src.lua-cor.ass'
local wrp = require('src.lua-cor.wrp')
local log = require('src.lua-cor.log').get('obj')
-- Define 2d vector type
local vec = obj:extend('vec')
vec.x = 0
vec.y = 0
-- Static copy vector value from one table to another
function vec.copy(from, to)
to.x = from.x
to.y = from.y
end
-- Static initialize table to screen center
function vec.center(obj)
obj.x = display.contentWidth / 2
obj.y = display.contentHeight / 2
end
-- Math operators
function vec.__add(l, r) return vec:new(l.x + r.x, l.y + r.y) end
function vec.__sub(l, r) return vec:new(l.x - r.x, l.y - r.y) end
function vec.__div(l, r) return vec:new(l.x / r.x, l.y / r.y) end
function vec.__mul(l, r) return vec:new(l.x * r.x, l.y * r.y) end
function vec.__eq (l, r) return (l.x == r.x) and (l.y == r.y) end
function vec.__lt (l, r) return (l.x < r.x) and (l.y < r.y) end
function vec.__le (l, r) return (l.x <= r.x) and (l.y <= r.y) end
-- Create a new vector
function vec:new(x, y)
return obj.new(self, {x = x, y = y})
end
-- Create a random vector in range
function vec:random(min, max)
return setmetatable({x = math.random(min.x, max.x), y = math.random(min.y, max.y)}, vec)
end
-- Create vector as a copy
function vec:from(obj)
return vec(obj.x, obj.y)
end
-- Convert to log friendly string
function vec:__tostring()
return '{'..self.x.. ",".. self.y..'}'
end
-- Compute square length
function vec:length2()
return (self.x * self.x) + (self.y * self.y)
end
-- Create new vector rounding x,y to closest integer values
function vec:round()
return vec:new(math.floor(self.x + 0.5), math.floor(self.y + 0.5))
end
-- Copy x,y into obj
function vec:to(obj)
obj.x = self.x
obj.y = self.y
end
-- Create positive vector
function vec:abs()
return vec:new(math.abs(self.x), math.abs(self.y))
end
-- Call fn for each integer in grid [0, vec-1]
function vec:iterate_grid_wrap_before(fn)
ass.nat(self.x)
ass.nat(self.y)
end
function vec:iterate_grid(fn)
for x = 0, self.x - 1 do
for y = 0, self.y - 1 do
fn(vec(x, y))
end
end
end
-- Calculate 1D array index of this position in 2D grid
function vec:to_index_in_grid_wrap_before(grid_size)
ass.nat(self.x)
ass.nat(self.y)
ass.nat(grid_size.x)
ass.nat(grid_size.y)
ass.gt(grid_size.x, self.x)
ass.gt(grid_size.y, self.y)
end
function vec:to_index_in_grid(grid_size)
return self.x * grid_size.y + self.y;
end
-- Random integer in grid [0, vec-1]
function vec:random_in_grid_wrap_before()
ass.nat(self.x)
ass.nat(self.y)
end
function vec:random_in_grid()
return vec(math.random(0, self.x - 1), math.random(0, self.y - 1))
end
-- Iterate neightbourhood on grid, wrapping
function vec:each_neighbour_wrap_before(grid_size, fn)
ass.nat(self.x)
ass.nat(self.y)
ass.nat(grid_size.x)
ass.nat(grid_size.y)
ass.gt(grid_size.x, self.x)
ass.gt(grid_size.y, self.y)
end
local function module(v, mod)
if v < 0 then return v + mod end
if v >= mod then return v - mod end
return v
end
function vec:each_neighbour_in_grid(grid_size, fn)
--fn(vec(module(self.x - 1, grid_size.x), module(self.y - 1, grid_size.y)))
fn(vec(module(self.x , grid_size.x), module(self.y - 1, grid_size.y)))
--fn(vec(module(self.x + 1, grid_size.x), module(self.y - 1, grid_size.y)))
fn(vec(module(self.x + 1, grid_size.x), module(self.y , grid_size.y)))
--fn(vec(module(self.x + 1, grid_size.x), module(self.y + 1, grid_size.y)))
fn(vec(module(self.x , grid_size.x), module(self.y + 1, grid_size.y)))
--fn(vec(module(self.x - 1, grid_size.x), module(self.y + 1, grid_size.y)))
fn(vec(module(self.x - 1, grid_size.x), module(self.y , grid_size.y)))
end
-- Constant zero vector
vec.zero = vec(0, 0)
-- Constant ones vector
vec.one = vec(1, 1)
-- Wrap vector functions
function vec:wrap()
local ex = typ.new_ex(vec)
wrp.fn(log.info, vec, 'copy', typ.tab, typ.tab)
wrp.fn(log.info, vec, 'center', typ.tab)
wrp.fn(log.info, vec, 'new', vec, typ.num, typ.num)
wrp.fn(log.info, vec, 'random', vec, vec, vec)
wrp.fn(log.info, vec, 'from', vec, typ.tab)
wrp.fn(log.info, vec, 'length2', ex)
wrp.fn(log.info, vec, 'round', ex)
wrp.fn(log.info, vec, 'to', ex, typ.tab)
wrp.fn(log.info, vec, 'abs', ex)
wrp.fn(log.info, vec, 'iterate_grid', ex, typ.fun)
wrp.fn(log.info, vec, 'to_index_in_grid', ex, vec)
wrp.fn(log.info, vec, 'random_in_grid', ex)
wrp.fn(log.info, vec, 'each_neighbour_in_grid', ex, vec, typ.fun)
end
return vec
|
addEventHandler ( "onPlayerJoin", root,
function()
setPlayerInternalChannel ( player, root )
end
)
function refreshPlayers()
for i,player in ipairs(getElementsByType"player") do
if not tonumber(getPlayerChannel ( player )) then --If he's not in a scripted channel
setPlayerDefaultChannel ( player )
end
end
end
setTimer ( refreshPlayers, TEAM_REFRESH, 0 )
function setPlayerDefaultChannel ( player )
local team = getPlayerTeam(player)
if team and settings.autoassign_to_teams then --He has a team, so let's put him in that team's voice channel
return setPlayerInternalChannel ( player, team, getPlayerMutedByList(player) )
else --If he doesn't have a team, stick him in the root
return setPlayerInternalChannel ( player, root, getPlayerMutedByList(player) )
end
end
function setPlayerInternalChannel ( player, element, muted )
if playerChannels[player] == element then
return false
end
playerChannels[player] = element
channels[element] = player
setPlayerVoiceBroadcastTo ( player, element, muted )
return true
end
|
_PACKAGE = (...):match "^(.+)[%./][^%./]+" or ""
local util = require(_PACKAGE .. "/util")
local dep = require(_PACKAGE .. "/dep")
local Vector = dep.Vector
local Button = require(_PACKAGE .. "/button")
local Input = require(_PACKAGE .. "/input")
--@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
local Slider = Input:extend()
Slider.classname = "Slider"
function Slider:new(args)
Input.new(self, args)
self:listenMousePressed()
self:listenMouseMoved()
self.onReleased = args.onReleased
self.onDragged = args.onDragged
self.stylebox_filled = args.stylebox_filled or self.stylebox
self.stylebox_empty = args.stylebox_empty or self.stylebox
self.min_value = args.min_value or 0
self.max_value = args.max_value or 100
self._value = args.value or 50
self.sliderhead = args.sliderhead or self:createSliderhead(args)
self:addChild(self.sliderhead)
self:moveSliderHeadToValue()
end
function Slider:__get_value()
return self._value
end
function Slider:__get_ratio()
return (self.value - self.min_value) / (self.max_value - self.min_value)
end
function Slider:__get_percent()
return 100 * self.ratio
end
function Slider:__set_value(v)
self._value = v
self:moveSliderHeadToValue()
end
function Slider:__set_ratio(r)
self.value = self.min_value + r * (self.max_value - self.min_value)
end
function Slider:__set_percent(p)
self.ratio = p / 100
end
--@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-- own callbacks
function Slider:pressed(button, x, y)
self.sliderhead.x = x - self.sliderhead.size.x / 2
self:setValueOnHead()
if self.onReleased then self.onReleased() end
end
--@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-- Sliderhead stuff
function Slider:ready()
Input.ready(self)
self.sliderhead:ready()
end
function Slider:createSliderhead(args)
local sliderhead = Button {
name = "sliderhead",
size_x = args.sliderhead_size_x or self.size.y,
size_y = args.sliderhead_size_y or self.size.y,
stylebox = args.sliderhead_stylebox_unpressed,
stylebox_unpressed = args.sliderhead_stylebox_unpressed,
stylebox_pressed = args.sliderhead_stylebox_pressed,
stylebox_hovered = args.sliderhead_stylebox_hovered
}
sliderhead.pressed = self.onSliderHeadPressed
sliderhead.releasedAnywhere = self.onSliderHeadReleasedAnywhere
sliderhead.mousedragged = self.onSliderHeadDragged
sliderhead.slider = self
return sliderhead
end
function Slider:moveSliderHeadToValue()
local dist = self.ratio * (self.size.x - self.sliderhead.size.x)
self.sliderhead:move(
self.pos.x + dist,
self.pos.y + (self.size.y - self.sliderhead.size.y) / 2
)
end
function Slider:setValueOnHead()
-- we use @_value because we don't want to trigger the setter
-- which will move the slider head again
local dist = self.sliderhead.pos.x - self.pos.x
local max_dist = self.size.x - self.sliderhead.size.x
self.value = self.min_value + (dist / max_dist) * (self.max_value - self.min_value)
end
-- callbacks
function Slider.onSliderHeadPressed(head, button, x, y)
head:setState("pressed")
head.grablocation = Vector(x, y) - head.pos
end
function Slider.onSliderHeadReleasedAnywhere(head)
if head.flags.MOUSEOVERED then
head:setState("hovered")
else
head:setState("unpressed")
end
head.grablocation = nil
if head.slider.onReleased then head.slider.onReleased() end
end
function Slider.onSliderHeadDragged(head, x, y)
head.x = x - head.grablocation.x
local slider = head.slider
local distance_from_left = head.pos.x - slider.pos.x
local max_distance_from_left = slider.size.x - head.size.x
if distance_from_left < 0 then
head.x = slider.pos.x
distance_from_left = 0
elseif distance_from_left > max_distance_from_left then
head.x = slider.pos.x + max_distance_from_left
distance_from_left = max_distance_from_left
end
slider:setValueOnHead()
if slider.onDragged then slider.onDragged() end
end
--@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-- draw stuff
function Slider:draw()
local filled_size = Vector(self.ratio * self.size.x, self.size.y)
self.stylebox_empty:draw(self.pos, self.size)
if self._value > self.min_value then
self.stylebox_filled:draw(self.pos, filled_size)
end
self:drawChildren()
end
--@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
return Slider
|
-------------------------------------
--- PANELS
-------------------------------------
local Panels = MR.CL.Panels
-- Section: clean up modifications
function Panels:SetCleanup(parent, frameType, info)
local frame = MR.CL.Panels:StartContainer("Cleanup", parent, frameType, info)
MR.CL.ExposedPanels:Set(frame, "cleanup", "frame")
local width = frame:GetWide()
local panel = vgui.Create("DPanel")
panel:SetSize(width, 0)
panel:SetBackgroundColor(Color(255, 255, 255, 0))
local cleanBox1Info = {
x = MR.CL.Panels:GetTextMarginLeft(),
y = MR.CL.Panels:GetGeneralBorders()
}
local cleanBox2Info = {
x = cleanBox1Info.x,
y = cleanBox1Info.y + MR.CL.Panels:GetCheckboxHeight() + MR.CL.Panels:GetGeneralBorders()
}
local cleanBox3Info = {
x = cleanBox2Info.x + 67,
y = cleanBox1Info.y
}
local cleanBox4Info = {
x = cleanBox3Info.x,
y = cleanBox3Info.y + MR.CL.Panels:GetCheckboxHeight() + MR.CL.Panels:GetGeneralBorders()
}
local cleanBox5Info = {
x = cleanBox3Info.x + 97,
y = cleanBox1Info.y
}
local cleanupButtonInfo = {
width = width - MR.CL.Panels:GetGeneralBorders() * 2,
height = MR.CL.Panels:GetTextHeight(),
x = MR.CL.Panels:GetGeneralBorders(),
y = cleanBox2Info.y + MR.CL.Panels:GetTextHeight()
}
local instantCleanupInfo = {
width = cleanupButtonInfo.width,
height = MR.CL.Panels:GetTextHeight(),
x = cleanupButtonInfo.x,
y = cleanupButtonInfo.y + cleanupButtonInfo.height + MR.CL.Panels:GetGeneralBorders() * 2
}
--------------------------
-- Cleanup options
--------------------------
local options = {}
local cleanBox1 = vgui.Create("DCheckBoxLabel", panel)
options[1] = { cleanBox1, "Map" }
cleanBox1:SetPos(cleanBox1Info.x, cleanBox1Info.y)
cleanBox1:SetText("Map")
cleanBox1:SetTextColor(Color(0, 0, 0, 255))
cleanBox1:SetValue(true)
local cleanBox2 = vgui.Create("DCheckBoxLabel", panel)
options[2] = { cleanBox2, "Models" }
cleanBox2:SetPos(cleanBox2Info.x, cleanBox2Info.y)
cleanBox2:SetText("Models")
cleanBox2:SetTextColor(Color(0, 0, 0, 255))
cleanBox2:SetValue(true)
local cleanBox3 = vgui.Create("DCheckBoxLabel", panel)
options[3] = { cleanBox3, "Decals" }
cleanBox3:SetPos(cleanBox3Info.x, cleanBox3Info.y)
cleanBox3:SetText("Decals")
cleanBox3:SetTextColor(Color(0, 0, 0, 255))
cleanBox3:SetValue(true)
local cleanBox4 = vgui.Create("DCheckBoxLabel", panel)
options[4] = { cleanBox4, "Displacements" }
cleanBox4:SetPos(cleanBox4Info.x, cleanBox4Info.y)
cleanBox4:SetText("Displacements")
cleanBox4:SetTextColor(Color(0, 0, 0, 255))
cleanBox4:SetValue(true)
local cleanBox5 = vgui.Create("DCheckBoxLabel", panel)
options[5] = { cleanBox5, "Skybox" }
cleanBox5:SetPos(cleanBox5Info.x, cleanBox5Info.y)
cleanBox5:SetText("Skybox")
cleanBox5:SetTextColor(Color(0, 0, 0, 255))
cleanBox5:SetValue(true)
--------------------------
-- Cleanup button
--------------------------
local cleanupButton = vgui.Create("DButton", panel)
cleanupButton:SetSize(cleanupButtonInfo.width, cleanupButtonInfo.height)
cleanupButton:SetPos(cleanupButtonInfo.x, cleanupButtonInfo.y)
cleanupButton:SetText("Cleanup")
cleanupButton:SetIcon("icon16/bin.png")
cleanupButton.DoClick = function()
local remove = ""
for k,v in pairs(options) do
if v[1]:GetChecked() then
remove = remove .. v[2] .. "+"
end
end
net.Start("SV.Materials:RemoveAll")
net.WriteString(remove)
net.SendToServer()
end
--------------------------
-- Instant cleanup
--------------------------
local instantCleanup = vgui.Create("DCheckBoxLabel", panel)
MR.Sync:Set(instantCleanup, "cleanup", "instant")
instantCleanup:SetPos(instantCleanupInfo.x, instantCleanupInfo.y)
instantCleanup:SetText("Fast cleanup (freezes the screen for a while)")
instantCleanup:SetTextColor(Color(0, 0, 0, 255))
instantCleanup:SetValue(GetConVar("internal_mr_instant_cleanup"):GetBool())
instantCleanup.OnChange = function(self, val)
-- Force the field to update and disable a sync loop block
if MR.CL.Sync:GetLoopBlock() then
MR.Sync:Get("cleanup", "instant"):SetChecked(val)
MR.CL.Sync:SetLoopBlock(false)
return
-- Admin only: reset the option if it's not being synced
elseif not MR.Ply:IsAdmin(LocalPlayer()) then
MR.Sync:Get("cleanup", "instant"):SetChecked(GetConVar("internal_mr_instant_cleanup"):GetBool())
end
net.Start("SV.Sync:Replicate")
net.WriteString("internal_mr_instant_cleanup")
net.WriteString(val and "1" or "0")
net.WriteString("cleanup")
net.WriteString("instant")
net.SendToServer()
end
-- Margin bottom
local extraBorder = vgui.Create("DPanel", panel)
extraBorder:SetSize(MR.CL.Panels:GetGeneralBorders(), MR.CL.Panels:GetGeneralBorders())
extraBorder:SetPos(0, cleanupButtonInfo.y + cleanupButtonInfo.height)
extraBorder:SetBackgroundColor(Color(0, 0, 0, 0))
return MR.CL.Panels:FinishContainer(frame, panel, frameType)
end
|
-- Copyright (C) Asseco Poland SA
local BasePlugin = require "kong.plugins.base_plugin"
require("kong.plugins.asseco-debug.serialize")
local DebugHandler = BasePlugin:extend()
DebugHandler.PRIORITY = 5000
DebugHandler.VERSION = "1.0.0"
function DebugHandler:new()
DebugHandler.super.new(self, "asseco-debug")
end
function DebugHandler:access(conf)
DebugHandler.super.access(self)
local ngx_log_level = ngx.INFO
if conf.writing_log_level == "off" then
return
elseif conf.writing_log_level == "debug" then
ngx_log_level = ngx.DEBUG
elseif conf.writing_log_level == "info" then
ngx_log_level = ngx.INFO
elseif conf.writing_log_level == "notice" then
ngx_log_level = ngx.NOTICE
else
return
end
--local started_at = ngx.req.start_time()
--local started_str = os.date('%d/%b/%Y:%H:%M:%S',started_at)
local headers = ngx.req.get_headers()
--local method = ngx.req.get_method()
--local request_uri = ngx.var.request_uri or ""
-- method, " ", request_uri,
local xfor_str = serializeTable( headers["x-forwarded-for"] or "", "x-forwarded-for", true )
ngx.log(ngx_log_level,
xfor_str,
", remote_addr: ", tostring(ngx.var.remote_addr),
", x-real-ip: ", tostring(headers["x-real-ip"]),
", user-agent: ", headers["user-agent"] or "",
", x-forwarded-proto: ", headers["x-forwarded-proto"] or "",
", x-forwarded-port: ", headers["x-forwarded-port"] or "" )
end
return DebugHandler
|
--[[
The majority of the lua parsing code in LibParse is based on the JSON
Lua 5.1 Encoder and Parser found here:
http://www.chipmunkav.com/downloads/Json.lua
------------------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person
obtaining a copy of this 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.
Usage:
-- Lua script:
local lib = LibStub("LibParse")
local t = {
["name1"] = "value1",
["name2"] = {1, false, true, 23.54, "a \021 string"},
name3 = Json.Null()
}
local json = lib:JsonEncode (t)
print (json)
--> {"name1":"value1","name3":null,"name2":[1,false,true,23.54,"a \u0015 string"]}
local t = lib:JsonDecode(json)
print(t.name2[4])
--> 23.54
-- WoW test script:
/run local lib = LibStub("LibParse") local t = {name1 = "value1", ["name2"]={1, false, true, 23.54, "a \u0015 string"}} local json = lib:JSONEncode(t) print(json) local tt = lib:JSONDecode(json) print(tt.name2[4])
--> {"name1":"value1","name3":null,"name2":[1,false,true,23.54,"a \u0015 string"]}
--> 23.54
Notes:
1) Encodable Lua types: string, number, boolean, table, nil
2) Use Json.Null() to insert a null value into a Json object
3) All control chars are encoded to \uXXXX format eg "\021" encodes to "\u0015"
4) All Json \uXXXX chars are decoded to chars (0-255 byte range only)
5) Json single line // and /* */ block comments are discarded during decoding
6) Numerically indexed Lua arrays are encoded to Json Lists eg [1,2,3]
7) Lua dictionary tables are converted to Json objects eg {"one":1,"two":2}
8) Json nulls are decoded to Lua nil and treated by Lua in the normal way
--]]
local lib = LibStub:NewLibrary("LibParse", 2)
if not lib then return end
local pairs, ipairs, tonumber, tostring = pairs, ipairs, tonumber, tostring
local setmetatable, type, error = setmetatable, type, error
local format, gsub, strfind, strsub, strchar, strbyte, floor = format, gsub, strfind, strsub, strchar, strbyte, floor
local null = {} -- table ref to use for Null
local JsonWriter = {
backslashes = {
['\b'] = "\\b",
['\t'] = "\\t",
['\n'] = "\\n",
['\f'] = "\\f",
['\r'] = "\\r",
['"'] = "\\\"",
['\\'] = "\\\\",
['/'] = "\\/"
}
}
function JsonWriter:New()
local o = {buffer={}}
setmetatable(o, self)
self.__index = self
return o
end
function JsonWriter:Append(s)
self.buffer[#self.buffer+1] = s
if #self.buffer > 1000 then
local temp = table.concat(self.buffer)
self.buffer = {temp}
end
end
function JsonWriter:ToString()
return table.concat(self.buffer)
end
function JsonWriter:Write(o)
local t = type(o)
if t == "nil" or o == null then
self:Append("null")
elseif t == "boolean" or t == "number" then
self:Append(tostring(o))
elseif t == "string" then
self:ParseString(o)
elseif t == "table" then
self:WriteTable(o)
else
error(format("Encoding of %s unsupported", tostring(o)))
end
end
function JsonWriter:ParseString(s)
self:Append('"')
self:Append(gsub(s, "[%z%c\\\"/]", function(n)
local c = self.backslashes[n]
if c then return c end
return format("\\u%.4X", strbyte(n))
end))
self:Append('"')
end
function JsonWriter:IsArray(t)
local count = 0
local isindex = function(k)
if type(k) == "number" and k > 0 then
if floor(k) == k then
return true
end
end
return false
end
for k,v in pairs(t) do
if not isindex(k) then
return false, '{', '}'
else
count = max(count, k)
end
end
return true, '[', ']', count
end
function JsonWriter:WriteTable(t)
local ba, st, et, n = self:IsArray(t)
self:Append(st)
if ba then
for i = 1, n do
self:Write(t[i])
if i < n then
self:Append(',')
end
end
else
local first = true;
for k, v in pairs(t) do
if not first then
self:Append(',')
end
first = false;
self:ParseString(k)
self:Append(':')
self:Write(v)
end
end
self:Append(et)
end
local StringReader = {
s = "",
i = 0
}
function StringReader:New(s)
local o = {}
setmetatable(o, self)
self.__index = self
o.s = s or o.s
return o
end
function StringReader:Peek()
local i = self.i + 1
if i <= #self.s then
return strsub(self.s, i, i)
end
return nil
end
function StringReader:Next()
self.i = self.i+1
if self.i <= #self.s then
return strsub(self.s, self.i, self.i)
end
return nil
end
function StringReader:All()
return self.s
end
local JsonReader = {
escapes = {
['t'] = '\t',
['n'] = '\n',
['f'] = '\f',
['r'] = '\r',
['b'] = '\b',
}
}
function JsonReader:New(s)
local o = {}
o.reader = StringReader:New(s)
setmetatable(o, self)
self.__index = self
return o;
end
function JsonReader:Read()
self:SkipWhiteSpace()
local peek = self:Peek()
if peek == nil then
error(format("Nil string: '%s'", self:All()))
elseif peek == '{' then
return self:ReadObject()
elseif peek == '[' then
return self:ReadArray()
elseif peek == '"' then
return self:ReadString()
elseif strfind(peek, "[%+%-%d]") then
return self:ReadNumber()
elseif peek == 't' then
return self:ReadTrue()
elseif peek == 'f' then
return self:ReadFalse()
elseif peek == 'n' then
return self:ReadNull()
elseif peek == '/' then
self:ReadComment()
return self:Read()
else
error(format("Invalid input: '%s'", self:All()))
end
end
function JsonReader:ReadTrue()
self:TestReservedWord{'t','r','u','e'}
return true
end
function JsonReader:ReadFalse()
self:TestReservedWord{'f','a','l','s','e'}
return false
end
function JsonReader:ReadNull()
self:TestReservedWord{'n','u','l','l'}
return nil
end
function JsonReader:TestReservedWord(t)
for i, v in ipairs(t) do
if self:Next() ~= v then
error(format("Error reading '%s': %s", table.concat(t), self:All()))
end
end
end
function JsonReader:ReadNumber()
local result = self:Next()
local peek = self:Peek()
while peek ~= nil and strfind(peek, "[%+%-%d%.eE]") do
result = result .. self:Next()
peek = self:Peek()
end
result = tonumber(result)
if result == nil then
error(format("Invalid number: '%s'", result))
else
return result
end
end
function JsonReader:ReadString()
local result = ""
if self:Next() ~= '"' then error("Assertion error: self:Next() ~= '\"'") end
while self:Peek() ~= '"' do
local ch = self:Next()
if ch == '\\' then
ch = self:Next()
if self.escapes[ch] then
ch = self.escapes[ch]
end
end
result = result .. ch
end
if self:Next() ~= '"' then error("Assertion error: self:Next() ~= '\"'") end
return gsub(result, "u%x%x(%x%x)", function(m) return strchar(tonumber(m, 16)) end)
end
function JsonReader:ReadComment()
if self:Next() ~= '/' then error("Assertion error: self:Next() ~= '/'") end
local second = self:Next()
if second == '/' then
self:ReadSingleLineComment()
elseif second == '*' then
self:ReadBlockComment()
else
error(format("Invalid comment: %s", self:All()))
end
end
function JsonReader:ReadBlockComment()
local done = false
while not done do
local ch = self:Next()
if ch == '*' and self:Peek() == '/' then
done = true
end
if not done and ch == '/' and self:Peek() == "*" then
error(format("Invalid comment: %s, '/*' illegal.", self:All()))
end
end
self:Next()
end
function JsonReader:ReadSingleLineComment()
local ch = self:Next()
while ch ~= '\r' and ch ~= '\n' do
ch = self:Next()
end
end
function JsonReader:ReadArray()
local result = {}
if self:Next() ~= '[' then error("Assertion error: self:Next() ~= '['") end
local done = false
if self:Peek() == ']' then
done = true;
end
while not done do
local item = self:Read()
result[#result+1] = item
self:SkipWhiteSpace()
if self:Peek() == ']' then
done = true
end
if not done then
local ch = self:Next()
if ch ~= ',' then
error(format("Invalid array: '%s' due to: '%s'", self:All(), ch))
end
end
end
if self:Next() ~= ']' then error("Assertion error: self:Next() ~= ']'") end
return result
end
function JsonReader:ReadObject()
local result = {}
if self:Next() ~= '{' then error("Assertion error: self:Next() ~= '{'") end
local done = false
if self:Peek() == '}' then
done = true
end
while not done do
local key = self:Read()
if type(key) ~= "string" then
error(format("Invalid non-string object key: %s", key))
end
self:SkipWhiteSpace()
local ch = self:Next()
if ch ~= ':' then
error(format("Invalid object: '%s' due to: '%s'", self:All(), ch))
end
self:SkipWhiteSpace()
local val = self:Read()
result[key] = val
self:SkipWhiteSpace()
if self:Peek() == '}' then
done = true
end
if not done then
ch = self:Next()
if ch ~= ',' then
error(format("Invalid array: '%s' near: '%s'", self:All(), ch))
end
end
end
if self:Next() ~= "}" then error("Assertion error: self:Next() ~= '}'") end
return result
end
function JsonReader:SkipWhiteSpace()
local p = self:Peek()
while p ~= nil and strfind(p, "[%s/]") do
if p == '/' then
self:ReadComment()
else
self:Next()
end
p = self:Peek()
end
end
function JsonReader:Peek()
return self.reader:Peek()
end
function JsonReader:Next()
return self.reader:Next()
end
function JsonReader:All()
return self.reader:All()
end
function lib:JSONEncode(o)
local writer = JsonWriter:New()
writer:Write(o)
return writer:ToString()
end
function lib:JSONDecode(s)
local reader = JsonReader:New(s)
return reader:Read()
end
function lib:JSONNull()
return null
end
-- ###############################################################
-- CSV Functions
-- ###############################################################
function lib:CSVEncode(keys, data)
local lines = {}
tinsert(lines, table.concat(keys, ","))
for _, entry in ipairs(data) do
local lineParts = {}
for _, key in ipairs(keys) do
tinsert(lineParts, entry[key] or "")
end
tinsert(lines, table.concat(lineParts, ","))
end
return table.concat(lines, "\n")
end
local function SafeStrSplit(str, sep)
local parts = {}
local s = 1
while true do
local e = strfind(str, sep, s)
if not e then
tinsert(parts, strsub(str, s))
break
end
tinsert(parts, strsub(str, s, e-1))
s = e + 1
end
return parts
end
function lib:CSVDecode(str)
local keys
local result = {}
local lines = SafeStrSplit(str, "\n")
for i, line in ipairs(lines) do
if i == 1 then
keys = {(","):split(lines[1])}
else
local entry = {}
local lineParts = {(","):split(line)}
for j, key in ipairs(keys) do
if lineParts[j] ~= "" then
entry[key] = tonumber(lineParts[j]) or lineParts[j]
end
end
tinsert(result, entry)
end
end
return keys, result
end
|
local _test = clnn._test
local times = _test.times
local clnntest = _test.clnntest
local x_clnntest = _test.x_clnntest
local nloop = _test.nloop
local precision_forward = 1e-6
local precision_backward = 1e-6
function clnntest.SpatialMaxPooling_forward_batch()
torch.manualSeed(123)
local bs = 7
local from = 37
local to = from
local ki = 4
local kj = 3
local si = 3
local sj = 2
local outi = 129
local outj = 43
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local tm = {}
local title = string.format('SpatialMaxPooling.forward %dx%dx%dx%d o %dx%d -> %dx%dx%dx%d',
bs, from, inj, ini, kj, ki, bs, to, outj, outi)
times[title] = tm
local input = torch.randn(bs,from,inj,ini)
local sconv = nn.SpatialMaxPooling(ki,kj,si,sj)
local groundtruth = sconv:forward(input)
local a = torch.Timer()
for i = 1,nloop do
groundtruth = sconv:forward(input)
end
tm.cpu = a:time().real
input = input:cl()
local gconv = nn.SpatialMaxPooling(ki,kj,si,sj):cl()
local rescl = gconv:forward(input)
a:reset()
for i = 1,nloop do
rescl = gconv:forward(input)
end
cltorch.synchronize()
tm.gpu = a:time().real
local error = rescl:float() - groundtruth
mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ')
end
function clnntest.SpatialMaxPooling_forward_batch_ceil()
-- FIXME factorize these a bit better :-P
torch.manualSeed(123)
local bs = 7
local from = 37
local to = from
local ki = 4
local kj = 3
local si = 3
local sj = 2
local outi = 129
local outj = 43
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local ceil_mode = 1
local tm = {}
local title = string.format('SpatialMaxPooling.forward %dx%dx%dx%d o %dx%d -> %dx%dx%dx%d',
bs, from, inj, ini, kj, ki, bs, to, outj, outi)
times[title] = tm
local input = torch.randn(bs,from,inj,ini)
local sconv = nn.SpatialMaxPooling(ki,kj,si,sj)
if ceil_mode then sconv:ceil() end
local groundtruth = sconv:forward(input)
local a = torch.Timer()
for i = 1,nloop do
groundtruth = sconv:forward(input)
end
tm.cpu = a:time().real
input = input:cl()
local gconv = nn.SpatialMaxPooling(ki,kj,si,sj):cl()
if ceil_mode then gconv:ceil() end
local rescl = gconv:forward(input)
a:reset()
for i = 1,nloop do
rescl = gconv:forward(input)
end
cltorch.synchronize()
tm.gpu = a:time().real
local error = rescl:float() - groundtruth
mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ')
end
function clnntest.SpatialMaxPooling_forward()
-- FIXME test for different configs (and not just have non-deterministic tests :-P or
-- incomplete tests)
torch.manualSeed(123)
local from = 37 -- math.random(1,64)
local to = from
local ki = 3 -- math.random(2,4)
local kj = 3 -- math.random(2,4)
local si = 2 -- math.random(1,4)
local sj = 2 -- math.random(1,4)
local outi = 43 -- math.random(32,256)
local outj = 51 -- math.random(32,256)
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local tm = {}
local title = string.format('SpatialMaxPooling.forward %dx%dx%d o %dx%d -> %dx%dx%d',
from, inj, ini, kj, ki, to, outj, outi)
times[title] = tm
local input = torch.randn(from,inj,ini)
local sconv = nn.SpatialMaxPooling(ki,kj,si,sj)
local groundtruth = sconv:forward(input)
local a = torch.Timer()
for i = 1,nloop do
groundtruth = sconv:forward(input)
end
tm.cpu = a:time().real
input = input:cl()
local gconv = nn.SpatialMaxPooling(ki,kj,si,sj):cl()
local rescl = gconv:forward(input)
a:reset()
for i = 1,nloop do
rescl = gconv:forward(input)
end
cltorch.synchronize()
tm.gpu = a:time().real
local error = rescl:float() - groundtruth
mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ')
local error_ind = gconv.indices:float() - sconv.indices
mytester:asserteq(error_ind:max(), 0, 'error on indices (forward) ')
end
function clnntest.SpatialMaxPooling_forward_ceil()
torch.manualSeed(123)
-- vgg in neural-scaling geometry:
local from = 256
local to = from
local ki = 2
local kj = 2
local si = 2
local sj = 2
local outi = 2
local outj = 2
local ini = 4
local inj = 3
local ceil_mode = 1
local tm = {}
local title = string.format('SpatialMaxPooling.forward %dx%dx%d o %dx%d -> %dx%dx%d',
from, inj, ini, kj, ki, to, outj, outi)
times[title] = tm
local input = torch.randn(from,inj,ini)
local sconv = nn.SpatialMaxPooling(ki,kj,si,sj)
if ceil_mode then sconv:ceil() end
local groundtruth = sconv:forward(input)
local a = torch.Timer()
for i = 1,nloop do
groundtruth = sconv:forward(input)
end
tm.cpu = a:time().real
input = input:cl()
local gconv = nn.SpatialMaxPooling(ki,kj,si,sj):cl()
if ceil_mode then gconv:ceil() end
local rescl = gconv:forward(input)
a:reset()
for i = 1,nloop do
rescl = gconv:forward(input)
end
cltorch.synchronize()
tm.gpu = a:time().real
mytester:asserteq(groundtruth:size(1), rescl:size(1))
mytester:asserteq(groundtruth:size(2), rescl:size(2))
mytester:asserteq(groundtruth:size(3), rescl:size(3))
local error = rescl:float() - groundtruth
mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ')
local error_ind = gconv.indices:float() - sconv.indices
mytester:asserteq(error_ind:max(), 0, 'error on indices (forward) ')
end
function clnntest.SpatialMaxPooling_backward()
-- FIXME test for different configs (and not just have non-deterministic tests :-P or
-- incomplete tests)
torch.manualSeed(123)
local from = 32 -- math.random(1,64)
local to = from
local ki = 4 -- math.random(2,4)
local kj = 3 -- math.random(2,4)
local si = 3 -- math.random(1,4)
local sj = 2 --math.random(1,4)
local outi = 27 -- math.random(32,64)
local outj = 31 -- math.random(32,64)
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local tm = {}
local title = string.format('SpatialMaxPooling.backward %dx%dx%d o %dx%d -> %dx%dx%d',
from, inj, ini, kj, ki, to, outj, outi)
times[title] = tm
local input = torch.randn(from,inj,ini)
local gradOutput = torch.randn(to,outj,outi)
local sconv = nn.SpatialMaxPooling(ki,kj,si,sj)
sconv:forward(input)
sconv:zeroGradParameters()
local groundgrad = sconv:backward(input, gradOutput)
local a = torch.Timer()
for i = 1,nloop do
sconv:zeroGradParameters()
groundgrad = sconv:backward(input, gradOutput)
end
tm.cpu = a:time().real
input = input:cl()
gradOutput = gradOutput:cl()
local gconv = nn.SpatialMaxPooling(ki,kj,si,sj):cl()
gconv:forward(input)
gconv:zeroGradParameters()
local rescl = gconv:backward(input, gradOutput)
a:reset()
for i = 1,nloop do
gconv:zeroGradParameters()
rescl = gconv:backward(input, gradOutput)
end
cltorch.synchronize()
tm.gpu = a:time().real
local error = rescl:float() - groundgrad
mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ')
end
function clnntest.SpatialMaxPooling_backward_ceil()
-- FIXME test for different configs (and not just have non-deterministic tests :-P or
-- incomplete tests)
torch.manualSeed(123)
local from = 32 -- math.random(1,64)
local to = from
local ki = 4 -- math.random(2,4)
local kj = 3 -- math.random(2,4)
local si = 3 -- math.random(1,4)
local sj = 2 --math.random(1,4)
local outi = 27 -- math.random(32,64)
local outj = 31 -- math.random(32,64)
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local ceil_mode = 1
local tm = {}
local title = string.format('SpatialMaxPooling.backward %dx%dx%d o %dx%d -> %dx%dx%d',
from, inj, ini, kj, ki, to, outj, outi)
times[title] = tm
local input = torch.randn(from,inj,ini)
local gradOutput = torch.randn(to,outj,outi)
local sconv = nn.SpatialMaxPooling(ki,kj,si,sj)
if ceil_mode then sconv:ceil() end
sconv:forward(input)
sconv:zeroGradParameters()
local groundgrad = sconv:backward(input, gradOutput)
local a = torch.Timer()
for i = 1,nloop do
sconv:zeroGradParameters()
groundgrad = sconv:backward(input, gradOutput)
end
tm.cpu = a:time().real
input = input:cl()
gradOutput = gradOutput:cl()
local gconv = nn.SpatialMaxPooling(ki,kj,si,sj):cl()
if ceil_mode then gconv:ceil() end
gconv:forward(input)
gconv:zeroGradParameters()
local rescl = gconv:backward(input, gradOutput)
a:reset()
for i = 1,nloop do
gconv:zeroGradParameters()
rescl = gconv:backward(input, gradOutput)
end
cltorch.synchronize()
tm.gpu = a:time().real
local error = rescl:float() - groundgrad
mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ')
end
function clnntest.SpatialMaxPooling_backward_batch()
torch.manualSeed(123)
local bs = math.random(4,10)
local from = math.random(1,64)
local to = from
local ki = math.random(2,4)
local kj = math.random(2,4)
-- enforce testing non-atomic kernel (dW == kW) and (dH == kH)
local si = ki
local sj = kj
local outi = math.random(32,64)
local outj = math.random(32,64)
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local tm = {}
local title = string.format('SpatialMaxPooling.backward %dx%dx%dx%d o %dx%d -> %dx%dx%dx%d',
bs, from, inj, ini, kj, ki, bs, to, outj, outi)
times[title] = tm
local input = torch.randn(bs,from,inj,ini)
local gradOutput = torch.randn(bs,to,outj,outi)
local sconv = nn.SpatialMaxPooling(ki,kj,si,sj)
sconv:forward(input)
sconv:zeroGradParameters()
local groundgrad = sconv:backward(input, gradOutput)
local a = torch.Timer()
for i = 1,nloop do
sconv:zeroGradParameters()
groundgrad = sconv:backward(input, gradOutput)
end
tm.cpu = a:time().real
input = input:cl()
gradOutput = gradOutput:cl()
local gconv = nn.SpatialMaxPooling(ki,kj,si,sj):cl()
gconv:forward(input)
gconv:zeroGradParameters()
local rescl = gconv:backward(input, gradOutput)
a:reset()
for i = 1,nloop do
gconv:zeroGradParameters()
rescl = gconv:backward(input, gradOutput)
end
cltorch.synchronize()
tm.gpu = a:time().real
local error = rescl:float() - groundgrad
mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ')
end
function clnntest.SpatialMaxPooling_backward_batch_ceil()
torch.manualSeed(123)
local bs = math.random(4,10)
local from = math.random(1,64)
local to = from
local ki = math.random(2,4)
local kj = math.random(2,4)
-- enforce testing non-atomic kernel (dW == kW) and (dH == kH)
local si = ki
local sj = kj
local outi = math.random(32,64)
local outj = math.random(32,64)
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local ceil_mode = 1
local tm = {}
local title = string.format('SpatialMaxPooling.backward %dx%dx%dx%d o %dx%d -> %dx%dx%dx%d',
bs, from, inj, ini, kj, ki, bs, to, outj, outi)
times[title] = tm
local input = torch.randn(bs,from,inj,ini)
local gradOutput = torch.randn(bs,to,outj,outi)
local sconv = nn.SpatialMaxPooling(ki,kj,si,sj)
if ceil_mode then sconv:ceil() end
sconv:forward(input)
sconv:zeroGradParameters()
local groundgrad = sconv:backward(input, gradOutput)
local a = torch.Timer()
for i = 1,nloop do
sconv:zeroGradParameters()
groundgrad = sconv:backward(input, gradOutput)
end
tm.cpu = a:time().real
input = input:cl()
gradOutput = gradOutput:cl()
local gconv = nn.SpatialMaxPooling(ki,kj,si,sj):cl()
if ceil_mode then gconv:ceil() end
gconv:forward(input)
gconv:zeroGradParameters()
local rescl = gconv:backward(input, gradOutput)
a:reset()
for i = 1,nloop do
gconv:zeroGradParameters()
rescl = gconv:backward(input, gradOutput)
end
cltorch.synchronize()
tm.gpu = a:time().real
local error = rescl:float() - groundgrad
mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ')
end
|
--after upgrading for the first time
function start(keys)
local ability = keys.ability
local level = ability:GetLevel()
if level == 1 then
ability.caster = keys.caster
ability.dmg_table = {}
end
end
--each time an enemy hero deals damage
function store(keys)
local attacker = keys.attacker
local damage = keys.attack_damage
local ability = keys.ability
ability.dmg_table[GameRules:GetGameTime()] = {hero = attacker, amount = damage}
for k, v in pairs(ability.dmg_table) do
if k < (GameRules:GetGameTime() - (ability:GetLevelSpecialValueFor("time_interval", (ability:GetLevel()-1)))) then
ability.dmg_table[k] = nil
end
end
end
--when the spell is cast
function gamble(keys)
local ability = keys.ability
local target = keys.target
local caster = keys.caster
local damage_done = 0
for key,value in pairs(ability.dmg_table) do
if value.hero == target then
damage_done = damage_done + value.amount
end
end
local formula_bolada = damage_done * 0.5 * ability:GetLevelSpecialValueFor("damage_constant", (ability:GetLevel()-1))
local damage_to_be = formula_bolada
--[[ local damageTable{
victim = target,
attacker = caster,
damage = damage_to_be,
damage_type = DAMAGE_TYPE_MAGICAL,
ability = ability,
}
ApplyDamage(damageTable)]]--
end
end
|
--[[
TheNexusAvenger
Implementation of a command.
--]]
local HttpService = game:GetService("HttpService")
local BaseCommand = require(script.Parent.Parent:WaitForChild("BaseCommand"))
local Command = BaseCommand:Extend()
--[[
Creates the command.
--]]
function Command:__new()
self:InitializeSuper("countdown","BasicCommands","Creates a countdown with the given seconds.")
self.Arguments = {
{
Type = "integer",
Name = "Time",
Description = "Time to count down.",
},
}
--Create the remote event.
local CountdownEvent = Instance.new("RemoteEvent")
CountdownEvent.Name = "StartCountdown"
CountdownEvent.Parent = self.API.EventContainer
self.CountdownEvent = CountdownEvent
--Create the storage value to allow countdowns for players who join after they start.
local PreviousCountdownsValue = Instance.new("StringValue")
PreviousCountdownsValue.Name = "PreviousCountdowns"
PreviousCountdownsValue.Value = "[]"
PreviousCountdownsValue.Parent = self.API.EventContainer
self.PreviousCountdownsValue = PreviousCountdownsValue
end
--[[
Runs the command.
--]]
function Command:Run(CommandContext,Duration)
self.super:Run(CommandContext)
--Send the countdown.
self.CountdownEvent:FireAllClients(Duration)
--Store the countdown.
local PreviousCountdowns = HttpService:JSONDecode(self.PreviousCountdownsValue.Value)
table.insert(PreviousCountdowns,os.time() + Duration)
self.PreviousCountdownsValue.Value = HttpService:JSONEncode(PreviousCountdowns)
end
return Command
|
local Books = {}
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local List = require(ReplicatedStorage.Utilities.List)
local ServerScriptService = game:GetService("ServerScriptService")
local BookChildren = require(ServerScriptService.BookChildren)
local Genres = require(ServerScriptService.Genres)
local books = {} -- List<Book> where each book is {.Id .Title .Author .Models} note: everything in books can be replicated as-is to clients
local idToBook = {}
local bookModelToContent = {} -- content stored here so it is not replicated to clients automatically
local defaultCover = "http://www.roblox.com/asset/?id=428733812"
local ServerStorage = game:GetService("ServerStorage")
local storage = ServerStorage:FindFirstChild("Book Data Storage")
local modelToId = {}
local warnOutdated
if storage then
warnOutdated = function()
warn("Books missing ids - Book Maintenance required.")
warnOutdated = function() end
end
else
warnOutdated = function() end
end
if storage then
local idsFolder = storage:FindFirstChild("Ids")
for _, obj in ipairs(idsFolder:GetChildren()) do
local id = tonumber(obj.Name)
if id then
if obj.Value then
modelToId[obj.Value] = id
else
warn("Improperly configured Ids:", obj:GetFullName())
end
for _, c in ipairs(obj:GetChildren()) do
if c.Value then
modelToId[c.Value] = id
else
warn("Improperly configured Ids in:", obj:GetFullName())
end
end
else
warn("Improperly configured Ids:", obj:GetFullName())
end
end
end
local getData = Instance.new("RemoteFunction")
getData.Name = "GetBookData"
getData.Parent = ReplicatedStorage
getData.OnServerInvoke = function(player, bookModel)
local response = bookModelToContent[bookModel] or error(tostring(bookModel:GetFullName()) .. " has no data")
return response[1], response[2], response[3] -- cover, authorsNote, words
end
local getBooks = Instance.new("RemoteFunction")
getBooks.Name = "GetBooks"
getBooks.Parent = ReplicatedStorage
getBooks.OnServerInvoke = function(player) return books end
local function convertEmptyToAnonymous(authorNames)
for _, name in ipairs(authorNames) do -- Check to see if generating a new list is necessary
if name == "" or not name then
local new = {}
for i, name in ipairs(authorNames) do
new[i] = (name == "" or not name) and "Anonymous" or name
end
return new
end
end
return authorNames
end
function Books:Register(book, genres, cover, title, customAuthorLine, authorNames, authorIds, authorsNote, publishDate, words, librarian)
BookChildren.AddTo(book)
-- BookScript specific startup code
if customAuthorLine == "" then customAuthorLine = nil end
if not cover or cover == "" then cover = defaultCover end
local orig = genres
genres = {}
for _, raw in ipairs(orig) do
local genre = Genres.InputToGenre(raw)
if genre then
genres[#genres + 1] = genre
else
warn("Unrecognized genre '" .. tostring(raw) .. "' in", book:GetFullName())
end
end
local coverDecal = book:FindFirstChild("Cover")
if coverDecal then
coverDecal.Texture = cover
end
if not storage then -- if storage exists, maintenance plugin takes care of this
BookChildren.UpdateGuis(book, title)
end
authorNames = convertEmptyToAnonymous(authorNames)
local authorLine = customAuthorLine or List.ToEnglish(authorNames)
-- Register book into system
local id = modelToId[book]
if not id and not book.Name:find("Example Book") and not book.Name:find("The Secret Book") then -- todo generalize exceptions
warnOutdated()
end
local bookData = id and idToBook[id]
if bookData then
bookData.Models[#bookData.Models + 1] = book
local copyModel = bookData.Models[1]
bookModelToContent[book] = bookModelToContent[copyModel]
else
bookData = {
Id = id,
Title = title,
AuthorLine = authorLine == "" and "Anonymous" or authorLine,
Authors = authorNames,
AuthorIds = authorIds, -- todo use this for players who are in-game in case they changed their name recently
PublishDate = publishDate,
Librarian = librarian,
Models = {book},
Genres = genres,
}
if id then
idToBook[id] = bookData
end
books[#books + 1] = bookData
bookModelToContent[book] = {cover, authorsNote, words}
end
end
function Books:GetCount() return #books end
function Books:GetBooks() return books end
return Books
|
ModifyEvent(-2, -2, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -2);
AddItem(181, 1);
do return end;
|
local _package = require 'lulz.package'
return _package(...)
|
local cc = require "@nasso/epine-cc/v0.2.0-alpha"
return {
epine.var("CC", "g++"):targets("MyGKrellm"),
epine.br,
-- supported target types: cc.binary, cc.static
-- planned: cc.shared
cc.binary "MyGKrellm" {
-- target prerequisites
prerequisites = {"./lib/libjzon.a"},
-- language ("C" (default) or "C++")
lang = "C++",
-- source files
srcs = {find "./src/*.cpp"},
-- preprocessor flags (include dirs)
cppflags = {"-I./include", "-I./lib/libjzon/include"},
-- compiler flags
cxxflags = {"-Wall", "-Wextra"},
-- libraries
ldlibs = {
"-lsfml-graphics",
"-lsfml-window",
"-lsfml-system",
"-ljzon"
},
-- lib dirs and other linker flags
ldflags = {"-L./lib"}
},
-- [...]
action "clean" {
-- cc.cleanlist represents all the files generated during compilation
-- it does NOT contain the final executable or library
rm(cc.cleanlist)
},
epine.br,
epine.comment " no idea if this works this is just a test file",
epine.sprule {
targets = {"lib/libjzon.a", "lib/libmy.a"},
target_pattern = "lib/%.a",
prereq_patterns = {"lib/%"},
order_only_prerequisites = {"lib"},
recipe = {
make("-C", "lib/$*", "$*.a"),
"cp lib/$*/$*.a $@"
}
}
}
|
--------------------------------------------------------------------------------
-- 0650-legacy.lua: tests for replacements of legacy Lua functions
-- This file is a part of lua-nucleo library
-- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license)
--------------------------------------------------------------------------------
local make_suite = assert(loadfile("test/test-lib/init/strict.lua"))(...)
local loadstring,
legacy_exports
= import "lua-nucleo/legacy.lua"
{
"loadstring"
}
--------------------------------------------------------------------------------
local test = make_suite("legacy", legacy_exports)
--------------------------------------------------------------------------------
test:UNTESTED 'loadstring'
|
ok function MqttNode:new(qnode)
ok function MqttNode:setDevAttrs(devAttrs)
ok function MqttNode:initResrc(...) -- iid should be given, resrcs should be a table
ok function MqttNode:readResrc(oid, iid, rid, callback)
ok function MqttNode:writeResrc(oid, iid, rid, value, callback)
function MqttNode:execResrc(oid, iid, rid, value, callback) -- [?] arg
ok function MqttNode:dump()
ok function MqttNode:objectList()
ok function MqttNode:encrypt(msg)
ok function MqttNode:decrypt(msg)
ok function MqttNode:resrcList(oid)
ok function MqttNode:connect(url, opts)
ok function MqttNode:close(callback)
ok function MqttNode:_rawMessageHandler(conn, topic, message)
ok function MqttNode:_requestHandler(msg)
ok function MqttNode:pubRegister(callback)
ok function MqttNode:pubDeregister(callback)
ok function MqttNode:pubNotify(data, callback)
ok function MqttNode:pingServer(callback)
ok function MqttNode:pubUpdate(devAttrs, callback)
ok function MqttNode:pubResponse(rsp, callback)
ok function MqttNode:publish(topic, message, qos, retain, callback)
ok function MqttNode:subscribe(topic, qos, callback)
ok function MqttNode:getAttrs(...) nil for notfound, default if empty, yes if there
ok function MqttNode:setAttrs(...)
-- _findAttrs
ok function MqttNode:_target(oid, iid, rid)
ok function MqttNode:_nextTransId(intf)
-- function MqttNode:_dumpInstance(oid, iid)
ok function MqttNode:_dumpObject(oid)
function MqttNode:_buildDefaultSo()
ok function MqttNode:_lifeUpdate(enable)
ok function MqttNode:_checkAndReportResrc(rid, currentValue)
ok function MqttNode:enableReport(oid, iid, rid)
ok function MqttNode:disableReport(oid, iid, rid)
ok function MqttNode:_readResrc(chk, oid, iid, rid, callback)
ok function MqttNode:_timeoutCtrl(key, delay)
|
-- test with cloudmqtt.com
m_dis={}
function dispatch(m,t,pl)
if pl~=nil and m_dis[t] then
m_dis[t](m,pl)
end
end
function topic1func(m,pl)
print("get1: "..pl)
end
function topic2func(m,pl)
print("get2: "..pl)
end
m_dis["/topic1"]=topic1func
m_dis["/topic2"]=topic2func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
m=mqtt.Client("nodemcu1",60,"test","test123")
m:on("connect",function(m)
print("connection "..node.heap())
m:subscribe("/topic1",0,function(m) print("sub done") end)
m:subscribe("/topic2",0,function(m) print("sub done") end)
m:publish("/topic1","hello",0,0) m:publish("/topic2","world",0,0)
end )
m:on("offline", function(conn)
print("disconnect to broker...")
print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
m:connect("m11.cloudmqtt.com",11214,0,1)
tmr.alarm(0,10000,1,function() local pl = "time: "..tmr.time()
m:publish("/topic1",pl,0,0)
end)
|
return require('packer').startup({function()
use {
'wbthomason/packer.nvim',
}
use {
'hrsh7th/nvim-cmp',
requires = {
'hrsh7th/cmp-buffer',
'hrsh7th/cmp-nvim-lsp',
'neovim/nvim-lspconfig',
'onsails/lspkind-nvim'
}
}
use {
'nvim-treesitter/nvim-treesitter',
requires = {
{'nvim-treesitter/nvim-treesitter-refactor'},
{'nvim-treesitter/playground'},
'JoosepAlviste/nvim-ts-context-commentstring'
},
run = ':TSUpdate'
}
use {
'famiu/feline.nvim',
requires = {
{'kyazdani42/nvim-web-devicons'}
}
}
use {
'nvim-telescope/telescope.nvim',
requires = {
{'nvim-lua/popup.nvim'},
{'nvim-lua/plenary.nvim'},
{'nvim-telescope/telescope-fzy-native.nvim'},
}
}
use {
'kyazdani42/nvim-tree.lua',
-- opt = true,
requires = {
{'kyazdani42/nvim-web-devicons'}
}
}
use {
'vim-utils/vim-man',
-- opt = true
}
use {
'mbbill/undotree',
}
use 'windwp/nvim-autopairs'
use 'gruvbox-community/gruvbox'
use {
'tpope/vim-surround',
}
use {
'tpope/vim-commentary'
}
use {
'lewis6991/gitsigns.nvim',
requires = {
'nvim-lua/plenary.nvim'
},
-- tag = 'release' -- To use the latest release
}
use 'neovim/nvim-lspconfig'
use {
'williamboman/nvim-lsp-installer',
-- opt = true
}
use {
'glepnir/dashboard-nvim',
opt = true
}
use {
'sbdchd/neoformat',
}
use {
'folke/zen-mode.nvim',
opt = true
}
use {
'tpope/vim-fugitive',
-- opt = true
}
use {
'TimUntersberger/neogit',
opt = true,
requires = 'nvim-lua/plenary.nvim'
}
use {
'folke/which-key.nvim',
opt = true
}
use {
'folke/lsp-trouble.nvim',
opt = true,
requires = "kyazdani42/nvim-web-devicons"
}
use {
'folke/twilight.nvim',
opt = true
}
use {
'sindrets/diffview.nvim',
opt = true,
}
use {
'norcalli/nvim-colorizer.lua',
opt = true,
-- load on specific filetypes
ft = {'html', 'css', 'javascript', 'javascriptreact', 'typescriptreact'}
}
use "lukas-reineke/indent-blankline.nvim"
end
})
|
local F, C = unpack(select(2, ...))
C.themes["Blizzard_BindingUI"] = function()
local r, g, b = C.r, C.g, C.b
local KeyBindingFrame = KeyBindingFrame
KeyBindingFrame.header:DisableDrawLayer("BACKGROUND")
KeyBindingFrame.header:DisableDrawLayer("BORDER")
KeyBindingFrame.scrollFrame.scrollBorderTop:SetTexture("")
KeyBindingFrame.scrollFrame.scrollBorderBottom:SetTexture("")
KeyBindingFrame.scrollFrame.scrollBorderMiddle:SetTexture("")
KeyBindingFrame.scrollFrame.scrollFrameScrollBarBackground:SetTexture("")
F.StripTextures(KeyBindingFrame.categoryList)
KeyBindingFrame.bindingsContainer:SetBackdrop(nil)
F.CreateBD(KeyBindingFrame)
F.CreateSD(KeyBindingFrame)
F.Reskin(KeyBindingFrame.defaultsButton)
F.Reskin(KeyBindingFrame.unbindButton)
F.Reskin(KeyBindingFrame.okayButton)
F.Reskin(KeyBindingFrame.cancelButton)
F.ReskinCheck(KeyBindingFrame.characterSpecificButton)
F.ReskinScroll(KeyBindingFrameScrollFrameScrollBar)
KeyBindingFrameScrollFrame.scrollFrameScrollBarBackground:Hide()
for i = 1, KEY_BINDINGS_DISPLAYED do
local button1 = _G["KeyBindingFrameKeyBinding"..i.."Key1Button"]
local button2 = _G["KeyBindingFrameKeyBinding"..i.."Key2Button"]
button2:SetPoint("LEFT", button1, "RIGHT", 1, 0)
end
hooksecurefunc("BindingButtonTemplate_SetupBindingButton", function(_, button)
if not button.styled then
local selected = button.selectedHighlight
selected:SetTexture(C.media.bdTex)
selected:SetPoint("TOPLEFT", C.Mult, -C.Mult)
selected:SetPoint("BOTTOMRIGHT", -C.Mult, C.Mult)
selected:SetColorTexture(r, g, b, .25)
F.Reskin(button)
button.styled = true
end
end)
KeyBindingFrame.header.text:ClearAllPoints()
KeyBindingFrame.header.text:SetPoint("TOP", KeyBindingFrame, "TOP", 0, -8)
KeyBindingFrame.unbindButton:ClearAllPoints()
KeyBindingFrame.unbindButton:SetPoint("BOTTOMRIGHT", -207, 16)
KeyBindingFrame.okayButton:ClearAllPoints()
KeyBindingFrame.okayButton:SetPoint("BOTTOMLEFT", KeyBindingFrame.unbindButton, "BOTTOMRIGHT", 1, 0)
KeyBindingFrame.cancelButton:ClearAllPoints()
KeyBindingFrame.cancelButton:SetPoint("BOTTOMLEFT", KeyBindingFrame.okayButton, "BOTTOMRIGHT", 1, 0)
local line = KeyBindingFrame:CreateTexture(nil, "ARTWORK")
line:SetSize(1, 546)
line:SetPoint("LEFT", 205, 10)
line:SetColorTexture(1, 1, 1, .2)
end
|
-- Windows 7 taskbar icon extensions (progress bar, custom thumbnail buttons)
require 'extern.mswindows'
local com = require 'extern.mswindows.com'
com.def {
{"ITaskbarList";
methods = {
{'HrInit'};
{'AddTab', 'void* hwnd'};
{'DeleteTab', 'void* hwnd'};
{'ActivateTab', 'void* hwnd'};
{'SetActiveAlt', 'void* hwnd'};
};
iid = '56FDF344-FD6D-11d0-958A006097C9A090';
};
{"ITaskbarList2", inherits='ITaskbarList';
methods = {
{'MarkFullscreenWindow', 'void* hwnd, bool32'};
};
iid = '602D4995-B13A-429b-A66E1935E44F4317';
};
{"ITaskbarList3", inherits='ITaskbarList2';
methods = {
{'SetProgressValue', 'void* hwnd, uint64_t done, uint64_t total'};
{'SetProgressState', 'void* hwnd, uint32_t tbpfFlags'};
{'RegisterTab', 'void* hwndTab, void* hwndMDI'};
{'UnregisterTab', 'void* hwndTab'};
{'SetTabOrder', 'void* hwndTab, void* hwndInsertBefore'};
{'SetTabActive', 'void* hwndTab, void* hwndMDI, uint32_t tbatFlags'};
{'ThumbBarAddButtons', 'void* hwnd, uint32_t buttons, void* button'};
{'ThumbBarUpdateButtons', 'void* hwnd, uint32_t buttons, void* button'};
{'ThumbBarSetImageList', 'void* hwnd, void* himagelist'};
{'SetOverlayIcon', 'void* hwnd, void* hicon, const wchar_t* description'};
{'SetThumbnailTooltip', 'void* hwnd, const wchar_t* toolTip'};
{'SetThumbnailClip', 'void* hwnd, RECT* clip'};
};
iid = 'EA1AFB91-9E28-4B86-90E99E9F8A5EEFAF';
};
}
return {
clsid = '56FDF344-FD6D-11d0-958A006097C9A090';
TBPF_NOPROGRESS = 0;
TBPF_INDETERMINATE = 0x1;
TBPF_NORMAL = 0x2;
TBPF_ERROR = 0x4;
TBPF_PAUSED = 0x8;
TBATF_USEMDITHUMBNAIL = 0x1;
TBATF_USEMDILIVEPREVIEW = 0x2;
}
|
local Entity = require('__stdlib__/stdlib/data/entity')
local Item = require('__stdlib__/stdlib/data/item')
local Recipe = require('__stdlib__/stdlib/data/recipe')
local recipes = settings.startup['picker-cheat-recipes'].value
local icon_path = '__PickerCheats__/graphics/icons/creative-lab.png'
local entity_path = '__PickerCheats__/graphics/entities/creative-lab.png'
local lab = Entity('lab', 'lab'):copy('picker-cheats-lab'):set('icon', icon_path):set('icon_size', 32)
lab.minable.mining_time = 0.5
lab.on_animation = {
filename = entity_path,
width = 113,
height = 91,
frame_count = 33,
line_length = 11,
animation_speed = 1 / 3,
shift = {0.25, 0}
}
lab.off_animation = lab.on_animation
lab.module_specification.module_slots = 7
lab.energy_source = {type = 'void'}
lab.energy_usage = '1W'
local item = Item('lab', 'item'):copy('picker-cheats-lab')
item:set_field('icon', icon_path):set_field('icon_size', 32):subgroup_order('picker-cheats-research', 'a')
if recipes then
item:Flags():remove('hidden')
Recipe {
name = 'picker-cheats-lab',
type = 'recipe',
enabled = true,
hidden = false,
ingredients = {},
result = 'picker-cheats-lab'
}
else
item:Flags():add('hidden')
end
|
local ok, harpoon = pcall(require, 'harpoon')
if not ok then
vim.cmd('echom "plugin error: harpoon is missing"')
return
end
harpoon.setup {
menu = {
width = 100,
}
}
|
return{
name= "Cube",
attributes= {
{
componentType= 5126,
name= "POSITION",
type= "VEC3",
offset= 0,
length= 288
},
{
componentType= 5126,
name= "NORMAL",
type= "VEC3",
offset= 288,
length= 288
},
{
componentType= 5126,
name= "TEXCOORD_0",
type= "VEC2",
offset= 576,
length= 192
}
},
indices= {
componentType= 5123,
type= "SCALAR",
offset= 768,
length= 72,
}
}
|
--singles
resource.AddSingleFile("resource/localization/en/pyrition.properties")
--[[
resource.AddSingleFile("materials/pyrition/memes/enjoyer/contemplate.png")
resource.AddSingleFile("materials/pyrition/memes/enjoyer/joker.png")
resource.AddSingleFile("materials/pyrition/memes/enjoyer/smile.png")
resource.AddSingleFile("materials/pyrition/memes/enjoyer/standing.png")
resource.AddSingleFile("sound/pyrition/commands/bakse/shutdown.mp3")
resource.AddSingleFile("sound/pyrition/memes/enjoyer.mp3")
]]
|
--[[-----------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2010-2020 Mark Rogaski
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.
--]]-----------------------------------------------------------------------
GwHoldDown = {}
GwHoldDown.__index = GwHoldDown
--- GwHoldDown constructor function.
-- @param interval The length, in seconds, of the hold-down interval.
-- @param limit The maximum hold time when the continue method is invoked.
-- If no value is supplied, the interval value is used.
-- @return An initialized GwHoldDown instance.
function GwHoldDown:new(interval, limit)
assert(type(interval) == 'number')
assert(type(limit) == 'number' or limit == nil)
local self = {}
setmetatable(self, GwHoldDown)
self.interval = interval
if limit then
self.limit = limit
else
self.limit = interval
end
self.timestamp = 0
self.scale = 0
return self
end
--- Update the timer interval.
-- @param interval The length, in seconds, of the hold-down interval.
-- @param limit The maximum hold time when the continue method is invoked.
-- @return The GwHoldDown instance.
function GwHoldDown:set(interval, limit)
assert(type(interval) == 'number')
gw.Debug(GW_LOG_DEBUG, 'hold-down set; timer=%s, interval=%d, limit=%s', tostring(self), interval, tostring(limit))
self.interval = interval
if limit then
self.limit = limit
else
self.limit = interval
end
return self
end
--- Start the hold-down interval.
-- @param f (optional) A callback function that will be called when the timer expires.
-- @return The time at which the interval will end.
function GwHoldDown:start(f)
local function handler(frame, elapsed)
if not self:hold() then
gw.Debug(GW_LOG_NOTICE, 'hold-down expired; timer=%s', tostring(self))
if type(f) == 'function' then
gw.Debug(GW_LOG_NOTICE, 'triggered hold-down callback; function=%s', tostring(f))
f()
end
frame:SetScript('OnUpdate', nil)
end
end
local t = time()
local expiry = t + self.interval
self.timestamp = t
self.scale = 0
local frame = CreateFrame('frame')
frame:SetScript('OnUpdate', handler)
gw.Debug(GW_LOG_NOTICE, 'hold-down start; timer=%s, timestamp=%d, expiry=%d, function=%s',
tostring(self), self.timestamp, expiry, tostring(f))
return expiry
end
--- Continue the hold down, scaling the interval.
function GwHoldDown:continue()
-- Pass-through for first invocation
if self.timestamp == 0 then
return self:start()
end
-- Increase scaling factor
if self.interval * 2 ^ (self.scale + 1) <= self.limit then
self.scale = self.scale + 1
end
-- Set the timer
local t = time()
local expiry = t + self.interval * 2 ^ self.scale
self.timestamp = t
gw.Debug(GW_LOG_NOTICE, 'hold-down continue; timer=%s, timestamp=%d, scale=%d, expiry=%d',
tostring(self), self.timestamp, self.scale, expiry)
return expiry
end
--- Clear the hold-down timer.
function GwHoldDown:clear()
self.timestamp = 0
self.scale = 0
gw.Debug(GW_LOG_NOTICE, 'hold-down cleared; timer=%s', tostring(self))
end
--- Test the hold-down status.
-- @return True if a hold-down is in effect, false otherwise.
function GwHoldDown:hold()
if self.timestamp > 0 then
local t = time()
return self.timestamp + self.interval * 2 ^ self.scale > t
else
return false
end
end
GwHoldDownCache = {}
GwHoldDownCache.__index = GwHoldDownCache
--- GwHoldDownCache constructor function.
-- @param interval The length, in seconds, of the hold-down interval.
-- @param soft_max Table size threshold for compaction.
-- @param hard_max Limit on table size.
-- @return An initialized GwHoldDownCache instance.
function GwHoldDownCache:new(interval, soft_max, hard_max)
assert(type(interval) == 'number')
assert(type(soft_max) == 'number')
assert(type(hard_max) == 'number')
local self = {}
setmetatable(self, GwHoldDownCache)
self.interval = interval
self.soft_max = soft_max
self.hard_max = hard_max
self.cache = {}
return self
end
--- Test the hold-down status of an element.
-- @return True if a hold-down is in effect, false otherwise.
function GwHoldDownCache:hold(s)
local t = time()
local rv = false
-- Check for hold-down
if self.cache[s] == nil then
self.cache[s] = t
gw.Debug(GW_LOG_DEBUG, 'cache miss; target=%s, cache=%s', s, tostring(self))
else
gw.Debug(GW_LOG_DEBUG, 'cache hit; target=%s, cache=%s', s, tostring(self))
if self.cache[s] > t + self.interval then
rv = true
else
self.cache[s] = nil
gw.Debug(GW_LOG_DEBUG, 'cache expire; target=%s, cache=%s', s, tostring(self))
end
end
-- Prune if necessary
if #self.cache > self.soft_max then
for k, v in pairs(self.cache) do
if v > t + self.interval then
table.remove(self.cache, k)
gw.Debug(GW_LOG_DEBUG, 'cache soft prune; target=%s, cache=%s', k, tostring(self))
end
end
end
-- Hard prune if necessary
if #self.cache > self.hard_max then
local index = {}
for k, ts in pairs(self.cache) do
table.insert(index, {ts, k})
end
table.sort(index, function(a, b) return a[1] < b [1] end)
for i = self.hard_max, #index do
table.remove(self.cache, index[i][2])
gw.Debug(GW_LOG_DEBUG, 'cache hard prune; target=%s, cache=%s', index[i][2], tostring(self))
end
end
return rv
end
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
--[[
Trading House Manager
--]]
local ZO_TradingHouseManager = ZO_TradingHouse_Shared:Subclass()
function ZO_TradingHouseManager:Initialize(control)
ZO_TradingHouse_Shared.Initialize(self, control)
self.initialized = false
self.titleLabel = control:GetNamedChild("TitleLabel")
TRADING_HOUSE_SCENE = ZO_InteractScene:New("tradinghouse", SCENE_MANAGER, ZO_TRADING_HOUSE_INTERACTION)
SYSTEMS:RegisterKeyboardRootScene(ZO_TRADING_HOUSE_SYSTEM_NAME, TRADING_HOUSE_SCENE)
end
do
local INVENTORY_TYPE_LIST = { INVENTORY_BACKPACK }
function ZO_TradingHouseManager:InitializeScene()
local function SceneStateChange(oldState, newState)
if newState == SCENE_SHOWING then
PLAYER_INVENTORY:SetContextForInventories("guildTraderTextSearch", INVENTORY_TYPE_LIST)
TEXT_SEARCH_MANAGER:ActivateTextSearch("guildTraderTextSearch")
self:UpdateFragments()
elseif newState == SCENE_HIDING then
SetPendingItemPost(BAG_BACKPACK, 0, 0)
ClearMenu()
ZO_InventorySlot_RemoveMouseOverKeybinds()
elseif newState == SCENE_HIDDEN then
TEXT_SEARCH_MANAGER:DeactivateTextSearch("guildTraderTextSearch")
local REMOVE_CONTEXT = nil
PLAYER_INVENTORY:SetContextForInventories(REMOVE_CONTEXT, INVENTORY_TYPE_LIST)
self:ClearSearchResults()
KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptor)
self.keybindStripDescriptor = nil
end
end
TRADING_HOUSE_SCENE:RegisterCallback("StateChange", SceneStateChange)
end
end
function ZO_TradingHouseManager:InitializeEvents()
local function FilterForKeyboardEvents(callback)
return function(...)
if not IsInGamepadPreferredMode() then
callback(...)
end
end
end
TRADING_HOUSE_SEARCH:RegisterCallback("OnSearchStateChanged", FilterForKeyboardEvents(function(...) self:OnSearchStateChanged(...) end))
TRADING_HOUSE_SEARCH:RegisterCallback("OnAwaitingResponse", FilterForKeyboardEvents(function(...) self:OnAwaitingResponse(...) end))
TRADING_HOUSE_SEARCH:RegisterCallback("OnResponseReceived", FilterForKeyboardEvents(function(...) self:OnResponseReceived(...) end))
TRADING_HOUSE_SEARCH:RegisterCallback("OnSelectedGuildChanged", FilterForKeyboardEvents(function() self:UpdateForGuildChange() end))
TRADING_HOUSE_SEARCH_HISTORY_KEYBOARD:RegisterCallback("MouseOverRowChanged", function()
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end)
local function OnUpdateStatus()
self:UpdateStatus()
end
self.control:RegisterForEvent(EVENT_TRADING_HOUSE_STATUS_RECEIVED, FilterForKeyboardEvents(OnUpdateStatus))
local function OnOperationTimeout()
self:OnOperationTimeout()
end
self.control:RegisterForEvent(EVENT_TRADING_HOUSE_OPERATION_TIME_OUT, FilterForKeyboardEvents(OnOperationTimeout))
local function OnPendingPostItemUpdated(_, slotId, isPending)
self:OnPendingPostItemUpdated(slotId, isPending)
end
self.control:RegisterForEvent(EVENT_TRADING_HOUSE_PENDING_ITEM_UPDATE, FilterForKeyboardEvents(OnPendingPostItemUpdated))
local function OnConfirmPendingPurchase(_, pendingPurchaseIndex)
if pendingPurchaseIndex ~= nil then
self:ConfirmPendingPurchase(pendingPurchaseIndex)
end
end
self.control:RegisterForEvent(EVENT_TRADING_HOUSE_CONFIRM_ITEM_PURCHASE, FilterForKeyboardEvents(OnConfirmPendingPurchase))
end
function ZO_TradingHouseManager:InitializeKeybindDescriptor()
local switchGuildsKeybind =
{
name = function()
local selectedGuildId = GetSelectedTradingHouseGuildId()
if selectedGuildId then
return GetGuildName(selectedGuildId)
end
end,
keybind = "UI_SHORTCUT_TERTIARY",
visible = function()
return GetNumTradingHouseGuilds() > 1
end,
enabled = function()
return TRADING_HOUSE_SEARCH:CanDoCommonOperation()
end,
callback = function()
ZO_Dialogs_ShowDialog("SELECT_TRADING_HOUSE_GUILD")
end,
}
self.browseKeybindStripDescriptor =
{
alignment = KEYBIND_STRIP_ALIGN_CENTER,
-- Do Search
{
keybind = "UI_SHORTCUT_SECONDARY",
name = GetString(SI_TRADING_HOUSE_DO_SEARCH),
callback = function()
TRADING_HOUSE_SEARCH:DoSearch()
end,
},
--Switch Guilds
switchGuildsKeybind,
--Reset Search / Delete Search History Entry
{
name = function()
if TRADING_HOUSE_SEARCH_HISTORY_KEYBOARD:GetMouseOverSearchTable() then
return GetString(SI_TRADING_HOUSE_DELETE_SEARCH_HISTORY_ENTRY)
else
return GetString(SI_TRADING_HOUSE_RESET_SEARCH)
end
end,
keybind = "UI_SHORTCUT_NEGATIVE",
callback = function()
local mouseOverSearchTable = TRADING_HOUSE_SEARCH_HISTORY_KEYBOARD:GetMouseOverSearchTable()
if mouseOverSearchTable then
TRADING_HOUSE_SEARCH_HISTORY_MANAGER:RemoveSearchTable(mouseOverSearchTable)
else
self:ClearSearchResults()
self:ResetSearchTerms()
TRADING_HOUSE_SEARCH:ResetAllSearchData()
TRADING_HOUSE_SEARCH:CancelPendingSearch()
end
end,
},
--End Preview
{
name = GetString(SI_CRAFTING_EXIT_PREVIEW_MODE),
keybind = "UI_SHORTCUT_QUATERNARY",
visible = function()
return ITEM_PREVIEW_KEYBOARD:IsInteractionCameraPreviewEnabled()
end,
callback = function()
self:TogglePreviewMode()
end,
},
}
self.sellKeybindStripDescriptor =
{
alignment = KEYBIND_STRIP_ALIGN_CENTER,
-- Post Item
{
keybind = "UI_SHORTCUT_SECONDARY",
name = GetString(SI_TRADING_HOUSE_POST_ITEM),
callback = function()
if self:CanPostWithMoneyCheck() then
self:PostPendingItem()
end
end,
visible = function()
return self:CanPost()
end,
enabled = function()
return self:HasEnoughMoneyToPostPendingItem()
end,
},
--Switch Guilds
switchGuildsKeybind,
}
self.listingsKeybindStripDescriptor =
{
alignment = KEYBIND_STRIP_ALIGN_CENTER,
--Switch Guilds
switchGuildsKeybind,
}
end
function ZO_TradingHouseManager:InitializeMenuBar(control)
self.menuBar = control:GetNamedChild("MenuBar")
self.tabLabel = self.menuBar:GetNamedChild("Label")
local function HandleTabSwitch(tabData)
self:HandleTabSwitch(tabData)
end
local function LayoutSellTabTooltip(tooltip)
local guildId = GetSelectedTradingHouseGuildId()
local tooltipText
if not IsPlayerInGuild(guildId) then
tooltipText = GetString(SI_TRADING_HOUSE_POSTING_LOCKED_NOT_A_GUILD_MEMBER)
elseif not DoesGuildHavePrivilege(guildId, GUILD_PRIVILEGE_TRADING_HOUSE) then
tooltipText = zo_strformat(GetString(SI_TRADING_HOUSE_POSTING_LOCKED_NO_PERMISSION_GUILD), GetNumGuildMembersRequiredForPrivilege(GUILD_PRIVILEGE_TRADING_HOUSE))
elseif not DoesPlayerHaveGuildPermission(guildId, GUILD_PERMISSION_STORE_SELL) then
tooltipText = GetString(SI_TRADING_HOUSE_POSTING_LOCKED_NO_PERMISSION_PLAYER)
else
tooltipText = GetString(SI_TRADING_HOUSE_MODE_SELL)
end
SetTooltipText(tooltip, tooltipText)
end
local function LayoutListingTabTooltip(tooltip)
local guildId = GetSelectedTradingHouseGuildId()
local tooltipText
if not IsPlayerInGuild(guildId) then
tooltipText = GetString(SI_TRADING_HOUSE_POSTING_LOCKED_NOT_A_GUILD_MEMBER)
else
tooltipText = GetString(SI_TRADING_HOUSE_MODE_LISTINGS)
end
SetTooltipText(tooltip, tooltipText)
end
local iconData =
{
{
categoryName = SI_TRADING_HOUSE_MODE_BROWSE,
descriptor = ZO_TRADING_HOUSE_MODE_BROWSE,
normal = "EsoUI/Art/TradingHouse/tradinghouse_browse_tabIcon_up.dds",
pressed = "EsoUI/Art/TradingHouse/tradinghouse_browse_tabIcon_down.dds",
disabled = "EsoUI/Art/TradingHouse/tradinghouse_browse_tabIcon_disabled.dds",
highlight = "EsoUI/Art/TradingHouse/tradinghouse_browse_tabIcon_over.dds",
callback = HandleTabSwitch,
},
{
categoryName = SI_TRADING_HOUSE_MODE_SELL,
descriptor = ZO_TRADING_HOUSE_MODE_SELL,
normal = "EsoUI/Art/TradingHouse/tradinghouse_sell_tabIcon_up.dds",
pressed = "EsoUI/Art/TradingHouse/tradinghouse_sell_tabIcon_down.dds",
disabled = "EsoUI/Art/TradingHouse/tradinghouse_sell_tabIcon_disabled.dds",
highlight = "EsoUI/Art/TradingHouse/tradinghouse_sell_tabIcon_over.dds",
callback = HandleTabSwitch,
CustomTooltipFunction = LayoutSellTabTooltip,
alwaysShowTooltip = true,
},
{
categoryName = SI_TRADING_HOUSE_MODE_LISTINGS,
descriptor = ZO_TRADING_HOUSE_MODE_LISTINGS,
normal = "EsoUI/Art/TradingHouse/tradinghouse_listings_tabIcon_up.dds",
pressed = "EsoUI/Art/TradingHouse/tradinghouse_listings_tabIcon_down.dds",
disabled = "EsoUI/Art/TradingHouse/tradinghouse_listings_tabIcon_disabled.dds",
highlight = "EsoUI/Art/TradingHouse/tradinghouse_listings_tabIcon_over.dds",
callback = HandleTabSwitch,
CustomTooltipFunction = LayoutListingTabTooltip,
alwaysShowTooltip = true,
},
}
for _, button in ipairs(iconData) do
ZO_MenuBar_AddButton(self.menuBar, button)
end
end
function ZO_TradingHouseManager:HandleTabSwitch(tabData)
local mode = tabData.descriptor
self:SetCurrentMode(mode)
self.tabLabel:SetText(GetString(tabData.categoryName))
local notSellMode = mode ~= ZO_TRADING_HOUSE_MODE_SELL
local notBrowseMode = mode ~= ZO_TRADING_HOUSE_MODE_BROWSE
local notListingsMode = mode ~= ZO_TRADING_HOUSE_MODE_LISTINGS
-- sell mode controls
self.postItemPane:SetHidden(notSellMode)
-- search/browse mode controls
self.browseItemsLeftPane:SetHidden(notBrowseMode)
self.itemNameSearch:SetHidden(notBrowseMode)
self.itemNameSearchLabel:SetHidden(notBrowseMode)
self.searchResultsList:SetHidden(notBrowseMode)
self.searchSortHeadersControl:SetHidden(notBrowseMode)
self.nagivationBar:SetHidden(notBrowseMode)
self.searchResultsMessageContainer:SetHidden(notBrowseMode)
self.subcategoryTabsControl:SetHidden(notBrowseMode)
self.featureAreaControl:SetHidden(notBrowseMode)
-- player listings mode controls
self.postedItemsList:SetHidden(notListingsMode)
self.postedItemsHeader:SetHidden(notListingsMode)
self.noPostedItemsContainer:SetHidden(notListingsMode)
if mode == ZO_TRADING_HOUSE_MODE_LISTINGS then
self:RefreshListings()
end
if mode == ZO_TRADING_HOUSE_MODE_SELL then
self:UpdateListingCounts()
end
local newKeybindStripDescriptor
if mode == ZO_TRADING_HOUSE_MODE_BROWSE then
newKeybindStripDescriptor = self.browseKeybindStripDescriptor
elseif mode == ZO_TRADING_HOUSE_MODE_SELL then
newKeybindStripDescriptor = self.sellKeybindStripDescriptor
else
newKeybindStripDescriptor = self.listingsKeybindStripDescriptor
end
if self.keybindStripDescriptor ~= newKeybindStripDescriptor then
if self.keybindStripDescriptor then
KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptor)
end
self.keybindStripDescriptor = newKeybindStripDescriptor
KEYBIND_STRIP:AddKeybindButtonGroup(newKeybindStripDescriptor)
end
if ITEM_PREVIEW_KEYBOARD:IsInteractionCameraPreviewEnabled() and notBrowseMode then
self:TogglePreviewMode()
else
self:UpdateFragments()
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end
end
function ZO_TradingHouseManager:UpdateFragments()
if TRADING_HOUSE_SCENE:IsShowing() then
if self:IsInSellMode() then
SCENE_MANAGER:AddFragment(INVENTORY_FRAGMENT)
else
SCENE_MANAGER:RemoveFragment(INVENTORY_FRAGMENT)
end
if self:IsInListingsMode() then
SCENE_MANAGER:RemoveFragment(TREE_UNDERLAY_FRAGMENT)
else
SCENE_MANAGER:AddFragment(TREE_UNDERLAY_FRAGMENT)
end
if self:IsInSearchMode() and not ITEM_PREVIEW_KEYBOARD:IsInteractionCameraPreviewEnabled() then
SCENE_MANAGER:AddFragment(TRADING_HOUSE_SEARCH_HISTORY_KEYBOARD_FRAGMENT)
else
SCENE_MANAGER:RemoveFragment(TRADING_HOUSE_SEARCH_HISTORY_KEYBOARD_FRAGMENT)
end
end
end
function ZO_TradingHouseManager:HasValidPendingItemPost()
return self.pendingItemSlot ~= nil
end
function ZO_TradingHouseManager:HasEnoughMoneyToPostPendingItem()
return self:HasValidPendingItemPost() and self.pendingSaleIsValid
end
function ZO_TradingHouseManager:CanPost()
return TRADING_HOUSE_SEARCH:CanDoCommonOperation() and self:IsInSellMode()
end
function ZO_TradingHouseManager:CanPostWithMoneyCheck()
return TRADING_HOUSE_SEARCH:CanDoCommonOperation() and self:IsInSellMode() and self:HasEnoughMoneyToPostPendingItem()
end
function ZO_TradingHouseManager:InitializePostItem(control)
self.postItemPane = control:GetNamedChild("PostItemPane")
self.pendingItemBG = self.postItemPane:GetNamedChild("PendingBG")
self.pendingItemName = self.postItemPane:GetNamedChild("FormInfoName")
self.pendingItem = self.postItemPane:GetNamedChild("FormInfoItem")
self.currentListings = self.postItemPane:GetNamedChild("FormInfoListingCount")
self.invoice = self.postItemPane:GetNamedChild("FormInvoice")
self.invoiceSellPrice = self.invoice:GetNamedChild("SellPriceAmount")
self.invoiceListingFee = self.invoice:GetNamedChild("ListingFeePrice")
self.invoiceTheirCut = self.invoice:GetNamedChild("TheirCutPrice")
self.invoiceProfit = self.invoice:GetNamedChild("ProfitAmount")
self:OnPendingPostItemUpdated(0, false)
end
function ZO_TradingHouseManager:InitializeBrowseItems(control)
self.browseItemsLeftPane = control:GetNamedChild("BrowseItemsLeftPane")
self.itemNameSearch = control:GetNamedChild("ItemNameSearch")
self.itemNameSearchLabel = control:GetNamedChild("ItemNameSearchLabel")
self.itemNameSearchAutoComplete = control:GetNamedChild("ItemNameSearchAutoComplete")
self.itemPane = control:GetNamedChild("BrowseItemsRightPane")
self.subcategoryTabsControl = control:GetNamedChild("SubcategoryTabs")
self.nagivationBar = control:GetNamedChild("SearchControls")
self.featureAreaControl = self.itemPane:GetNamedChild("FeatureArea")
self.searchSortHeadersControl = self.itemPane:GetNamedChild("SearchSortBy")
self.searchResultsList = self.itemPane:GetNamedChild("SearchResults")
self.searchResultsMessageContainer = self.itemPane:GetNamedChild("SearchResultsMessageContainer")
self.searchResultsMessageLabel = self.searchResultsMessageContainer:GetNamedChild("Message")
self:InitializeSearchTerms()
self:InitializeSearchResults(control)
self:InitializeSearchSortHeaders(control)
self:InitializeSearchNavigationBar(control)
self:ClearSearchResults()
end
function ZO_TradingHouseManager:InitializeSearchSortHeaders(control)
local sortHeaders = ZO_SortHeaderGroup:New(self.searchSortHeadersControl, true)
self.searchSortHeaders = sortHeaders
local function OnSortHeaderClicked(key, order)
TRADING_HOUSE_SEARCH:ChangeSort(key, order)
end
sortHeaders:RegisterCallback(ZO_SortHeaderGroup.HEADER_CLICKED, OnSortHeaderClicked)
sortHeaders:AddHeadersFromContainer()
local DONT_FORCE_RESELECT = nil
local sortKey, sortOrder = TRADING_HOUSE_SEARCH:GetSortOptions()
sortHeaders:SelectHeaderByKey(sortKey, ZO_SortHeaderGroup.SUPPRESS_CALLBACKS, DONT_FORCE_RESELECT, sortOrder)
end
function ZO_TradingHouseManager:InitializeSearchNavigationBar(control)
self.resultCount = self.nagivationBar:GetNamedChild("ResultCount")
self.previousPage = self.nagivationBar:GetNamedChild("PreviousPage")
self.nextPage = self.nagivationBar:GetNamedChild("NextPage")
self.pageNumberLabel = self.nagivationBar:GetNamedChild("PageNumber")
local moneyControl = self.nagivationBar:GetNamedChild("Money")
local function UpdateMoney()
self.playerMoney[CURT_MONEY] = GetCurrencyAmount(CURT_MONEY, CURRENCY_LOCATION_CHARACTER)
ZO_CurrencyControl_SetSimpleCurrency(moneyControl, CURT_MONEY, self.playerMoney[CURT_MONEY], ZO_KEYBOARD_CURRENCY_OPTIONS)
end
moneyControl:RegisterForEvent(EVENT_MONEY_UPDATE, UpdateMoney)
UpdateMoney()
local function UpdateAlliancePoints()
self.playerMoney[CURT_ALLIANCE_POINTS] = GetCurrencyAmount(CURT_ALLIANCE_POINTS, CURRENCY_LOCATION_CHARACTER)
end
moneyControl:RegisterForEvent(EVENT_ALLIANCE_POINT_UPDATE, UpdateAlliancePoints)
UpdateAlliancePoints()
self.previousPage:SetHandler("OnClicked", function() TRADING_HOUSE_SEARCH:SearchPreviousPage() end)
self.nextPage:SetHandler("OnClicked", function() TRADING_HOUSE_SEARCH:SearchNextPage() end)
end
function ZO_TradingHouseManager:ToggleLevelRangeMode()
if self.levelRangeFilterType == TRADING_HOUSE_FILTER_TYPE_LEVEL then
self.levelRangeFilterType = TRADING_HOUSE_FILTER_TYPE_CHAMPION_POINTS
self.levelRangeToggle:SetState(BSTATE_PRESSED, true)
self.levelRangeLabel:SetText(GetString(SI_TRADING_HOUSE_BROWSE_CHAMPION_POINTS_RANGE_LABEL))
else
self.levelRangeFilterType = TRADING_HOUSE_FILTER_TYPE_LEVEL
self.levelRangeToggle:SetState(BSTATE_NORMAL, false)
self.levelRangeLabel:SetText(GetString(SI_TRADING_HOUSE_BROWSE_LEVEL_RANGE_LABEL))
end
end
function ZO_TradingHouseManager:InitializeSearchTerms()
local globalFeatureArea = self.browseItemsLeftPane:GetNamedChild("GlobalFeatureArea")
-- Name Search
local nameSearchFeature = ZO_TradingHouse_CreateKeyboardFeature("NameSearch")
nameSearchFeature:AttachToControl(self.itemNameSearch, self.itemNameSearchAutoComplete)
self.itemNameSearchLabel:SetText(nameSearchFeature:GetDisplayName())
-- Category List
local categoryListControl = self.browseItemsLeftPane:GetNamedChild("CategoryListContainer")
local subCategoryTabsControl = self.subcategoryTabsControl
local featuresParentControl = self.featureAreaControl
local searchCategoryFeature = ZO_TradingHouse_CreateKeyboardFeature("SearchCategory")
searchCategoryFeature:AttachToControl(categoryListControl, subCategoryTabsControl, featuresParentControl)
-- Quality dropdown
local qualityFeature = ZO_TradingHouse_CreateKeyboardFeature("Quality")
qualityFeature:AttachToControl(globalFeatureArea:GetNamedChild("Quality"))
-- Price range
local priceRangeFeature = ZO_TradingHouse_CreateKeyboardFeature("PriceRange")
priceRangeFeature:AttachToControl(globalFeatureArea:GetNamedChild("PriceRange"))
self.features =
{
nameSearchFeature = nameSearchFeature,
searchCategoryFeature = searchCategoryFeature,
qualityFeature = qualityFeature,
priceRangeFeature = priceRangeFeature,
}
self:ResetSearchTerms()
end
local SEARCH_RESULTS_DATA_TYPE = 1
local ITEM_LISTINGS_DATA_TYPE = 2
local GUILD_SPECIFIC_ITEM_DATA_TYPE = 3
local ITEM_RESULT_CURRENCY_OPTIONS =
{
showTooltips = false,
font = "ZoFontGameShadow",
iconSide = RIGHT,
}
function ZO_TradingHouseManager:InitializeSearchResults(control)
self.searchResultsControlsList = {}
self.searchResultsInfoList = {}
local function SetupBaseSearchResultRow(rowControl, result)
self.searchResultsControlsList[#self.searchResultsControlsList + 1] = rowControl
self.searchResultsInfoList[#self.searchResultsInfoList + 1] = result
local nameControl = rowControl:GetNamedChild("Name")
nameControl:SetText(ZO_TradingHouse_GetItemDataFormattedName(result))
-- result.quality is deprecated, included here for addon backwards compatibility
local displayQuality = result.displayQuality or result.quality
local r, g, b = GetInterfaceColor(INTERFACE_COLOR_TYPE_ITEM_QUALITY_COLORS, displayQuality)
nameControl:SetColor(r, g, b, 1)
local traitInformationControl = GetControl(rowControl, "TraitInfo")
traitInformationControl:ClearIcons()
if not result.isGuildSpecificItem then
local traitInformation = GetItemTraitInformationFromItemLink(result.itemLink)
if traitInformation ~= ITEM_TRAIT_INFORMATION_NONE then
traitInformationControl:AddIcon(GetPlatformTraitInformationIcon(traitInformation))
traitInformationControl:Show()
end
end
local sellPricePerUnitControl = rowControl:GetNamedChild("SellPricePerUnit")
ZO_CurrencyControl_SetSimpleCurrency(sellPricePerUnitControl, result.currencyType, result.purchasePricePerUnit, ITEM_RESULT_CURRENCY_OPTIONS, nil, false)
local sellPriceControl = rowControl:GetNamedChild("SellPrice")
ZO_CurrencyControl_SetSimpleCurrency(sellPriceControl, result.currencyType, result.purchasePrice, ITEM_RESULT_CURRENCY_OPTIONS, nil, self.playerMoney[result.currencyType] < result.purchasePrice)
local resultControl = rowControl:GetNamedChild("Button")
ZO_Inventory_SetupSlot(resultControl, result.stackCount, result.icon)
-- Cached for verification when the player tries to purchase this
resultControl.sellerName = result.sellerName
resultControl.purchasePrice = result.purchasePrice
resultControl.currencyType = result.currencyType
return resultControl
end
local function SetupSearchResultRow(rowControl, result)
local resultControl = SetupBaseSearchResultRow(rowControl, result)
local timeRemainingControl = GetControl(rowControl, "TimeRemaining")
local timeRemainingString = ZO_TradingHouse_GetItemDataFormattedTime(result)
timeRemainingControl:SetText(timeRemainingString)
ZO_Inventory_BindSlot(resultControl, SLOT_TYPE_TRADING_HOUSE_ITEM_RESULT, result.slotIndex)
end
local function SetupGuildSpecificItemRow(rowControl, result)
local resultControl = SetupBaseSearchResultRow(rowControl, result)
ZO_Inventory_BindSlot(resultControl, SLOT_TYPE_GUILD_SPECIFIC_ITEM, result.slotIndex)
end
ZO_ScrollList_Initialize(self.searchResultsList)
ZO_ScrollList_AddDataType(self.searchResultsList, SEARCH_RESULTS_DATA_TYPE, "ZO_TradingHouseSearchResult", 52, SetupSearchResultRow, nil, nil, ZO_InventorySlot_OnPoolReset)
ZO_ScrollList_AddDataType(self.searchResultsList, GUILD_SPECIFIC_ITEM_DATA_TYPE, "ZO_TradingHouseSearchResult", 52, SetupGuildSpecificItemRow, nil, nil, ZO_InventorySlot_OnPoolReset)
ZO_ScrollList_AddResizeOnScreenResize(self.searchResultsList)
end
function ZO_TradingHouseManager:InitializeListings(control)
self.postedItemsHeader = control:GetNamedChild("PostedItemsHeader")
local postedItemsList = control:GetNamedChild("PostedItemsList")
self.postedItemsList = postedItemsList
self.noPostedItemsContainer = control:GetNamedChild("PostedItemsNoItemsContainer")
self.noPostedItemsLabel = self.noPostedItemsContainer:GetNamedChild("NoItems")
local function CancelListing(cancelButton)
local postedItem = cancelButton:GetParent():GetNamedChild("Button")
local listingIndex = ZO_Inventory_GetSlotIndex(postedItem)
self:ShowCancelListingConfirmation(listingIndex)
end
local function SetupPostedItemRow(rowControl, postedItem)
local index = postedItem.slotIndex
local nameControl = rowControl:GetNamedChild("Name")
nameControl:SetText(zo_strformat(SI_TOOLTIP_ITEM_NAME, postedItem.name))
-- postedItem.quality is deprecated, included here for addon backwards compatibility
local displayQuality = postedItem.displayQuality or postedItem.quality
local r, g, b = GetInterfaceColor(INTERFACE_COLOR_TYPE_ITEM_QUALITY_COLORS, displayQuality)
nameControl:SetColor(r, g, b, 1)
local timeRemainingControl = rowControl:GetNamedChild("TimeRemaining")
timeRemainingControl:SetText(zo_strformat(SI_TRADING_HOUSE_BROWSE_ITEM_REMAINING_TIME, ZO_FormatTime(postedItem.timeRemaining, TIME_FORMAT_STYLE_SHOW_LARGEST_UNIT_DESCRIPTIVE, TIME_FORMAT_PRECISION_SECONDS, TIME_FORMAT_DIRECTION_DESCENDING)))
local sellPriceControl = rowControl:GetNamedChild("SellPrice")
ZO_CurrencyControl_SetSimpleCurrency(sellPriceControl, CURT_MONEY, postedItem.purchasePrice, ITEM_RESULT_CURRENCY_OPTIONS)
local postedItemControl = rowControl:GetNamedChild("Button")
ZO_Inventory_BindSlot(postedItemControl, SLOT_TYPE_TRADING_HOUSE_ITEM_LISTING, index)
ZO_Inventory_SetupSlot(postedItemControl, postedItem.stackCount, postedItem.icon)
local cancelButton = rowControl:GetNamedChild("CancelSale")
cancelButton:SetHandler("OnClicked", CancelListing)
end
ZO_ScrollList_Initialize(postedItemsList)
ZO_ScrollList_AddDataType(postedItemsList, ITEM_LISTINGS_DATA_TYPE, "ZO_TradingHouseItemListing", 52, SetupPostedItemRow, nil, nil, ZO_InventorySlot_OnPoolReset)
ZO_ScrollList_AddResizeOnScreenResize(postedItemsList)
end
function ZO_TradingHouseManager:RebuildListingsScrollList()
local list = self.postedItemsList
local scrollData = ZO_ScrollList_GetDataList(list)
ZO_ScrollList_Clear(list)
for i = 1, GetNumTradingHouseListings() do
local itemData = ZO_TradingHouse_CreateListingItemData(i)
if itemData then
scrollData[#scrollData + 1] = ZO_ScrollList_CreateDataEntry(ITEM_LISTINGS_DATA_TYPE, itemData)
end
end
ZO_ScrollList_Commit(list)
self.noPostedItemsLabel:SetHidden(#scrollData > 0)
end
function ZO_TradingHouseManager:OnPendingPostItemUpdated(slotId, isPending)
self.pendingSaleIsValid = false
if isPending then
self.pendingItemSlot = slotId
self:SetupPendingPost(slotId)
else
self.pendingItemSlot = nil
self:ClearPendingPost()
end
self:UpdateListingCounts()
end
function ZO_TradingHouseManager:OnPostSuccess()
-- convenience wrapper for clearing out the pending item and updating the post count
self:OnPendingPostItemUpdated()
end
function ZO_TradingHouseManager:UpdateListingCounts()
local currentListings, maxListings = GetTradingHouseListingCounts()
if currentListings < maxListings then
self.currentListings:SetText(zo_strformat(SI_TRADING_HOUSE_LISTING_COUNT, currentListings, maxListings))
else
self.currentListings:SetText(zo_strformat(SI_TRADING_HOUSE_LISTING_COUNT_FULL, currentListings, maxListings))
end
end
local INVOICE_CURRENCY_OPTIONS =
{
showTooltips = false,
font = "ZoFontWinT1",
}
function ZO_TradingHouseManager:SetInvoicePriceColors(color)
local r, g, b = color:UnpackRGB()
self.invoiceListingFee:SetColor(r, g, b)
self.invoiceTheirCut:SetColor(r, g, b)
self.invoiceProfit:SetColor(r, g, b)
end
-- Only called from the CURRENCY_INPUT control callback chain
function ZO_TradingHouseManager:SetPendingPostPrice(sellPrice)
sellPrice = tonumber(sellPrice) or 0
self.invoiceSellPrice.sellPrice = sellPrice
ZO_CurrencyControl_SetSimpleCurrency(self.invoiceSellPrice, CURT_MONEY, sellPrice, INVOICE_CURRENCY_OPTIONS)
self:SetInvoicePriceColors(ZO_DEFAULT_ENABLED_COLOR)
if self.pendingItemSlot then
local listingFee, tradingHouseCut, profit = GetTradingHousePostPriceInfo(sellPrice)
ZO_CurrencyControl_SetSimpleCurrency(self.invoiceListingFee, CURT_MONEY, listingFee, INVOICE_CURRENCY_OPTIONS)
ZO_CurrencyControl_SetSimpleCurrency(self.invoiceTheirCut, CURT_MONEY, tradingHouseCut, INVOICE_CURRENCY_OPTIONS)
ZO_CurrencyControl_SetSimpleCurrency(self.invoiceProfit, CURT_MONEY, profit, INVOICE_CURRENCY_OPTIONS)
-- verify the user has enough cash
if (GetCurrencyAmount(CURT_MONEY, CURRENCY_LOCATION_CHARACTER) - listingFee) >= 0 then
self.pendingSaleIsValid = true
else
self.pendingSaleIsValid = false
self:SetInvoicePriceColors(ZO_ERROR_COLOR)
end
else
self.invoiceListingFee:SetText("0")
self.invoiceTheirCut:SetText("0")
self.invoiceProfit:SetText("0")
end
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end
function ZO_TradingHouseManager:GetPendingPostPrice()
return self.invoiceSellPrice.sellPrice
end
function ZO_TradingHouseManager:SetupPendingPost()
if self.pendingItemSlot then
local icon, stackCount = GetItemInfo(BAG_BACKPACK, self.pendingItemSlot)
ZO_Inventory_BindSlot(self.pendingItem, SLOT_TYPE_TRADING_HOUSE_POST_ITEM, self.pendingItemSlot, BAG_BACKPACK)
ZO_ItemSlot_SetupSlot(self.pendingItem, stackCount, icon)
self.pendingItemName:SetText(zo_strformat(SI_TOOLTIP_ITEM_NAME, GetItemName(BAG_BACKPACK, self.pendingItemSlot)))
self.pendingItemBG:SetHidden(false)
self.invoice:SetHidden(false)
local initialPostPrice = ZO_TradingHouse_CalculateItemSuggestedPostPrice(BAG_BACKPACK, self.pendingItemSlot)
self:SetPendingPostPrice(initialPostPrice)
ZO_InventorySlot_HandleInventoryUpdate(self.pendingItem)
end
end
function ZO_TradingHouseManager:ClearPendingPost()
ZO_Inventory_BindSlot(self.pendingItem, SLOT_TYPE_TRADING_HOUSE_POST_ITEM)
ZO_ItemSlot_SetupSlot(self.pendingItem, 0, "EsoUI/Art/TradingHouse/tradinghouse_emptySellSlot_icon.dds")
self.pendingItemName:SetText(GetString(SI_TRADING_HOUSE_SELECT_AN_ITEM_TO_SELL))
self.pendingItemBG:SetHidden(true)
self.invoice:SetHidden(true)
self:SetPendingPostPrice(0)
SetPendingItemPost(BAG_BACKPACK, 0, 0)
ZO_InventorySlot_HandleInventoryUpdate(self.pendingItem)
end
function ZO_TradingHouseManager:PostPendingItem()
if self.pendingItemSlot and self.pendingSaleIsValid then
local stackCount = ZO_InventorySlot_GetStackCount(self.pendingItem)
local desiredPrice = self.invoiceSellPrice.sellPrice or 0
RequestPostItemOnTradingHouse(BAG_BACKPACK, self.pendingItemSlot, stackCount, desiredPrice)
end
end
function ZO_TradingHouseManager:RefreshListings()
if HasTradingHouseListings() then
self:RebuildListingsScrollList()
else
self:ClearListedItems()
if TRADING_HOUSE_SEARCH:CanDoCommonOperation() then
self.requestListings = false
RequestTradingHouseListings()
else
-- only queue the request if we are not currently waiting for a listings response
if not TRADING_HOUSE_SEARCH:IsWaitingForResponseType(TRADING_HOUSE_RESULT_LISTINGS_PENDING) then
self.requestListings = true
end
end
end
end
function ZO_TradingHouseManager:OnSearchStateChanged(searchState, searchOutcome)
if searchState == TRADING_HOUSE_SEARCH_STATE_NONE then
self.previousPage:SetHidden(true)
self.nextPage:SetHidden(true)
self.searchResultsMessageLabel:SetHidden(true)
self.resultCount:SetHidden(true)
self.pageNumberLabel:SetHidden(true)
elseif searchState == TRADING_HOUSE_SEARCH_STATE_WAITING then
--Update the page number while we're waiting for it to load (page number is 0 based). The page number label may not have been shown yet since we don't show it until the initial search completes, but
--we update it here for when it does show.
local targetPage = TRADING_HOUSE_SEARCH:GetTargetPage() or 0
self.pageNumberLabel:SetText(targetPage + 1)
--Clear the result count label until we know the number of results
self.resultCount:SetText(zo_strformat(SI_TRADING_HOUSE_RESULT_COUNT, ""))
self:ShowSearchResultMessage(GetString("SI_TRADINGHOUSESEARCHSTATE", searchState))
elseif searchState == TRADING_HOUSE_SEARCH_STATE_COMPLETE then
if searchOutcome == TRADING_HOUSE_SEARCH_OUTCOME_HAS_RESULTS then
self.searchResultsMessageLabel:SetHidden(true)
self:RebuildSearchResultsPage()
ZO_ScrollList_ResetToTop(self.searchResultsList)
else
self.resultCount:SetText(zo_strformat(SI_TRADING_HOUSE_RESULT_COUNT, 0))
self:ShowSearchResultMessage(GetString("SI_TRADINGHOUSESEARCHOUTCOME", searchOutcome))
end
end
end
function ZO_TradingHouseManager:OnAwaitingResponse(responseType)
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end
function ZO_TradingHouseManager:OnResponseReceived(responseType, result)
local success = result == TRADING_HOUSE_RESULT_SUCCESS
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
if responseType == TRADING_HOUSE_RESULT_POST_PENDING then
if success then
self:OnPostSuccess()
self:RefreshListings()
end
elseif responseType == TRADING_HOUSE_RESULT_SEARCH_PENDING then
if success then
-- Hide the fictional "awaiting search results" animation?
end
elseif responseType == TRADING_HOUSE_RESULT_PURCHASE_PENDING then
if success then
self:OnPurchaseSuccess()
end
elseif responseType == TRADING_HOUSE_RESULT_LISTINGS_PENDING then
if success then
self:RefreshListings()
self.requestListings = false -- make sure that we don't request again right after we get an answer.
end
elseif responseType == TRADING_HOUSE_RESULT_CANCEL_SALE_PENDING then
if success then
-- Refresh all listings when the cancel goes through
-- This doesn't need to ensure that the listings were received because the interface to cancel a listing requires that
-- the listings have been received from the server.
self:RefreshListings()
end
end
if self.requestListings then
self:RefreshListings()
end
end
function ZO_TradingHouseManager:ShowSearchResultMessage(messageText)
local list = self.searchResultsList
ZO_ScrollList_Clear(list)
ZO_ScrollList_Commit(list)
self.previousPage:SetEnabled(false)
self.nextPage:SetEnabled(false)
self.searchResultsMessageLabel:SetHidden(false)
self.searchResultsMessageLabel:SetText(messageText)
end
function ZO_TradingHouseManager:RebuildSearchResultsPage(isInitialResults)
local list = self.searchResultsList
local scrollData = ZO_ScrollList_GetDataList(list)
ZO_ScrollList_Clear(list)
local showingGuildSpecificItems = TRADING_HOUSE_SEARCH:ShouldShowGuildSpecificItems() or isInitialResults
local numItemsOnPage = 0
if showingGuildSpecificItems then
for i = 1, GetNumGuildSpecificItems() do
local result = self:CreateGuildSpecificItemData(i, GetGuildSpecificItemInfo)
if result then
scrollData[#scrollData + 1] = ZO_ScrollList_CreateDataEntry(GUILD_SPECIFIC_ITEM_DATA_TYPE, result)
numItemsOnPage = numItemsOnPage + 1
end
end
else
for i = 1, TRADING_HOUSE_SEARCH:GetNumItemsOnPage() do
local result = ZO_TradingHouse_CreateSearchResultItemData(i)
if result then
scrollData[#scrollData + 1] = ZO_ScrollList_CreateDataEntry(SEARCH_RESULTS_DATA_TYPE, result)
numItemsOnPage = numItemsOnPage + 1
end
end
end
ZO_ScrollList_Commit(list)
if showingGuildSpecificItems then
--Don't show the search stats or controls for the guild specific items
self.pageNumberLabel:SetHidden(true)
self.resultCount:SetHidden(true)
self.previousPage:SetHidden(true)
self.nextPage:SetHidden(true)
else
self.previousPage:SetHidden(false)
self.nextPage:SetHidden(false)
local hasPreviousPage = TRADING_HOUSE_SEARCH:HasPreviousPage()
local hasNextPage = TRADING_HOUSE_SEARCH:HasNextPage()
self.previousPage:SetEnabled(hasPreviousPage)
self.nextPage:SetEnabled(hasNextPage)
--The page number is set above while waiting for results, but we don't show it until the first results arrive.
self.pageNumberLabel:SetHidden(false)
self.resultCount:SetHidden(false)
self.resultCount:SetText(zo_strformat(SI_TRADING_HOUSE_RESULT_COUNT, numItemsOnPage))
end
end
function ZO_TradingHouseManager:OnPurchaseSuccess()
self:RebuildSearchResultsPage()
end
function ZO_TradingHouseManager:ClearSearchResults()
ZO_ScrollList_Clear(self.searchResultsList)
ZO_ScrollList_Commit(self.searchResultsList)
self.previousPage:SetHidden(true)
self.nextPage:SetHidden(true)
self.searchResultsMessageLabel:SetHidden(true)
self.resultCount:SetHidden(true)
self.pageNumberLabel:SetHidden(true)
end
function ZO_TradingHouseManager:ClearListedItems()
ZO_ScrollList_Clear(self.postedItemsList)
ZO_ScrollList_Commit(self.postedItemsList)
self.noPostedItemsLabel:SetHidden(false)
end
function ZO_TradingHouseManager:ResetSearchTerms()
for _, feature in pairs(self.features) do
feature:ResetSearch()
end
end
function ZO_TradingHouseManager:OpenTradingHouse()
if not self.initialized then
self:RunInitialSetup(self.control)
self.initialized = true
end
self:SetCurrentMode(ZO_TRADING_HOUSE_MODE_BROWSE)
TRADING_HOUSE_SEARCH:AssociateWithSearchFeatures(self.features)
ZO_MenuBar_SelectDescriptor(self.menuBar, self:GetCurrentMode())
self.currentDisplayName = GetDisplayName()
end
function ZO_TradingHouseManager:CloseTradingHouse()
SYSTEMS:HideScene(ZO_TRADING_HOUSE_SYSTEM_NAME)
if self.initialized then
self.currentDisplayName = nil
self:SetCurrentMode(nil)
ZO_MenuBar_ClearSelection(self.menuBar)
end
TRADING_HOUSE_SEARCH:DisassociateWithSearchFeatures()
end
function ZO_TradingHouseManager:TogglePreviewMode()
ITEM_PREVIEW_KEYBOARD:ToggleInteractionCameraPreview(FRAME_TARGET_STANDARD_RIGHT_PANEL_FRAGMENT, FRAME_PLAYER_ON_SCENE_HIDDEN_FRAGMENT, RIGHT_BG_EMPTY_WORLD_ITEM_PREVIEW_OPTIONS_FRAGMENT)
self:UpdateFragments()
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end
function ZO_TradingHouseManager:PreviewSearchResult(tradingHouseIndex)
if not ITEM_PREVIEW_KEYBOARD:IsInteractionCameraPreviewEnabled() then
self:TogglePreviewMode()
end
ITEM_PREVIEW_KEYBOARD:ClearPreviewCollection()
ITEM_PREVIEW_KEYBOARD:PreviewTradingHouseSearchResult(tradingHouseIndex)
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end
--Override
function ZO_TradingHouseManager:SearchForItemLink(itemLink)
if TRADING_HOUSE_SCENE:IsShowing() then
TRADING_HOUSE_SEARCH:LoadSearchItem(itemLink)
--Changing to browse will add the quaternary bind for preview so we need to get rid of the quaternary bind for search before that
ZO_InventorySlot_RemoveMouseOverKeybinds()
ZO_MenuBar_SelectDescriptor(self.menuBar, ZO_TRADING_HOUSE_MODE_BROWSE)
TRADING_HOUSE_SEARCH:DoSearch()
end
end
-- Select Active Guild for Trading House Dialog
----------------------
local function SelectTradingHouseGuildDialogInitialize(dialogControl, tradingHouseManager)
local function SelectTradingHouseGuild(selectedGuildId)
if selectedGuildId then
SelectTradingHouseGuildId(selectedGuildId)
end
end
local dialog = ZO_SelectGuildDialog:New(dialogControl, "SELECT_TRADING_HOUSE_GUILD", SelectTradingHouseGuild)
dialog:SetTitle(SI_PROMPT_TITLE_SELECT_GUILD_STORE)
dialog:SetPrompt(GetString(SI_SELECT_GUILD_STORE_INSTRUCTIONS))
dialog:SetCurrentStateSource(GetSelectedTradingHouseGuildId)
end
function ZO_TradingHouseManager:UpdateStatus()
if not self.changeGuildDialog then
self.changeGuildDialog = ZO_SelectTradingHouseGuildDialog
SelectTradingHouseGuildDialogInitialize(self.changeGuildDialog, self)
end
self:UpdateForGuildChange()
end
function ZO_TradingHouseManager:OnOperationTimeout()
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end
function ZO_TradingHouseManager:UpdateForGuildChange()
local guildId = GetSelectedTradingHouseGuildId()
if not IsPlayerInGuild(guildId) then
-- Player is using a Guild Trader
self:UpdateListingCounts()
self:ClearListedItems()
self:ClearPendingPost()
self:ClearSearchResults()
ZO_MenuBar_SelectDescriptor(self.menuBar, ZO_TRADING_HOUSE_MODE_BROWSE)
ZO_MenuBar_SetDescriptorEnabled(self.menuBar, ZO_TRADING_HOUSE_MODE_SELL, false)
ZO_MenuBar_SetDescriptorEnabled(self.menuBar, ZO_TRADING_HOUSE_MODE_LISTINGS, false)
else
-- Player is using a regular Guild Store
local canSell = CanSellOnTradingHouse(guildId)
self:UpdateListingCounts()
if self:GetCurrentMode() == ZO_TRADING_HOUSE_MODE_LISTINGS then
self:RefreshListings()
end
self:ClearPendingPost()
self:ClearSearchResults()
local IS_INITIAL_RESULTS = true
self:RebuildSearchResultsPage(IS_INITIAL_RESULTS)
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
if self:IsInSellMode() and not canSell then
ZO_MenuBar_SelectDescriptor(self.menuBar, ZO_TRADING_HOUSE_MODE_BROWSE)
end
ZO_MenuBar_SetDescriptorEnabled(self.menuBar, ZO_TRADING_HOUSE_MODE_SELL, canSell)
ZO_MenuBar_SetDescriptorEnabled(self.menuBar, ZO_TRADING_HOUSE_MODE_LISTINGS, true)
end
local _, guildName = GetCurrentTradingHouseGuildDetails()
if guildName ~= "" then
self.titleLabel:SetText(guildName)
else
self.titleLabel:SetText(GetString(SI_WINDOW_TITLE_TRADING_HOUSE))
end
end
-- Utility to show a confirmation for some kind of trading house item (listing or search result)
local function SetupTradingHouseItemDialog(dialogControl, itemInfoFn, slotIndex, slotType, costLabelStringId)
-- Item data is set up on the dialog control before the dialog is shown
local icon, itemName, displayQuality, stackCount, _, _, purchasePrice, currencyType = itemInfoFn(slotIndex)
local nameControl = dialogControl:GetNamedChild("ItemName")
nameControl:SetText(zo_strformat(SI_TOOLTIP_ITEM_NAME, itemName))
local r, g, b = GetInterfaceColor(INTERFACE_COLOR_TYPE_ITEM_QUALITY_COLORS, displayQuality)
nameControl:SetColor(r, g, b, 1)
local itemControl = dialogControl:GetNamedChild("Item")
ZO_Inventory_BindSlot(itemControl, slotType, slotIndex)
ZO_Inventory_SetupSlot(itemControl, stackCount, icon)
local costControl = dialogControl:GetNamedChild("Cost")
costControl:SetHidden(costLabelStringId == nil)
if costLabelStringId then
costControl:SetText(zo_strformat(costLabelStringId, ZO_Currency_FormatKeyboard(currencyType, purchasePrice, ZO_CURRENCY_FORMAT_WHITE_AMOUNT_ICON)))
end
end
-- Confirm Item Purchase Dialog
local function PurchaseItemDialogInitialize(dialogControl, tradingHouseManager)
ZO_Dialogs_RegisterCustomDialog("CONFIRM_TRADING_HOUSE_PURCHASE",
{
customControl = dialogControl,
setup = function(self) SetupTradingHouseItemDialog(self, GetTradingHouseSearchResultItemInfo, self.purchaseIndex, SLOT_TYPE_TRADING_HOUSE_ITEM_RESULT, SI_TRADING_HOUSE_PURCHASE_ITEM_AMOUNT) end,
title =
{
text = SI_TRADING_HOUSE_PURCHASE_ITEM_DIALOG_TITLE,
},
buttons =
{
[1] =
{
control = GetControl(dialogControl, "Accept"),
text = SI_TRADING_HOUSE_PURCHASE_ITEM_DIALOG_CONFIRM,
callback = function(dialog)
ConfirmPendingItemPurchase()
end,
},
[2] =
{
control = GetControl(dialogControl, "Cancel"),
text = SI_TRADING_HOUSE_PURCHASE_ITEM_DIALOG_CANCEL,
callback = function(dialog)
ClearPendingItemPurchase()
end,
}
}
})
end
function ZO_TradingHouseManager:ConfirmPendingPurchase(pendingPurchaseIndex)
if not self.purchaseDialog then
self.purchaseDialog = ZO_TradingHousePurchaseItemDialog
PurchaseItemDialogInitialize(self.purchaseDialog, self)
end
self.purchaseDialog.purchaseIndex = pendingPurchaseIndex
ZO_Dialogs_ShowDialog("CONFIRM_TRADING_HOUSE_PURCHASE")
end
-- Confirm Guild Specific Item Purchase Dialog
local function PurchaseGuildSpecificItemDialogInitialize(dialogControl, tradingHouseManager)
ZO_Dialogs_RegisterCustomDialog("CONFIRM_TRADING_HOUSE_GUILD_SPECIFIC_PURCHASE",
{
customControl = dialogControl,
setup = function(self) SetupTradingHouseItemDialog(self, GetGuildSpecificItemInfo, self.guildSpecificItemIndex, SLOT_TYPE_GUILD_SPECIFIC_ITEM, SI_TRADING_HOUSE_PURCHASE_ITEM_AMOUNT) end,
title =
{
text = SI_TRADING_HOUSE_PURCHASE_ITEM_DIALOG_TITLE,
},
buttons =
{
[1] =
{
control = GetControl(dialogControl, "Accept"),
text = SI_TRADING_HOUSE_PURCHASE_ITEM_DIALOG_CONFIRM,
callback = function(dialog)
BuyGuildSpecificItem(dialog.guildSpecificItemIndex)
tradingHouseManager:HandleGuildSpecificPurchase(dialog.guildSpecificItemIndex)
end,
},
[2] =
{
control = GetControl(dialogControl, "Cancel"),
text = SI_TRADING_HOUSE_PURCHASE_ITEM_DIALOG_CANCEL,
callback = function(dialog)
-- Do nothing
end,
}
}
})
end
function ZO_TradingHouseManager:ConfirmPendingGuildSpecificPurchase(guildSpecificItemIndex)
if not self.purchaseGuildSpecificDialog then
self.purchaseGuildSpecificDialog = ZO_TradingHousePurchaseItemDialog
PurchaseGuildSpecificItemDialogInitialize(self.purchaseGuildSpecificDialog, self)
end
self.purchaseGuildSpecificDialog.guildSpecificItemIndex = guildSpecificItemIndex
ZO_Dialogs_ShowDialog("CONFIRM_TRADING_HOUSE_GUILD_SPECIFIC_PURCHASE")
end
function ZO_TradingHouseManager:HandleGuildSpecificPurchase(guildSpecificItemIndex)
local purchasedItemValue = self.searchResultsInfoList[guildSpecificItemIndex].purchasePrice
for i = 1, #self.searchResultsControlsList do
local purchasePrice = self.searchResultsInfoList[i].purchasePrice
local currencyType = self.searchResultsInfoList[i].currencyType
local sellPriceControl = GetControl(self.searchResultsControlsList[i], "SellPrice")
ZO_CurrencyControl_SetSimpleCurrency(sellPriceControl, currencyType, purchasePrice, ITEM_RESULT_CURRENCY_OPTIONS, nil, self.playerMoney[currencyType] - purchasedItemValue < purchasePrice)
end
end
-- Cancel Listing Confirmation Dialog
local function CancelListingDialogInitialize(dialogControl, tradingHouseManager)
ZO_Dialogs_RegisterCustomDialog("CONFIRM_TRADING_HOUSE_CANCEL_LISTING",
{
customControl = dialogControl,
setup = function(self) SetupTradingHouseItemDialog(self, GetTradingHouseListingItemInfo, self.listingIndex, SLOT_TYPE_TRADING_HOUSE_ITEM_LISTING) end,
title =
{
text = SI_TRADING_HOUSE_CANCEL_LISTING_DIALOG_TITLE,
},
buttons =
{
[1] =
{
control = GetControl(dialogControl, "Accept"),
text = SI_TRADING_HOUSE_CANCEL_LISTING_DIALOG_CONFIRM,
callback = function(dialog)
CancelTradingHouseListing(dialog.listingIndex)
dialog.listingIndex = nil
end,
},
[2] =
{
control = GetControl(dialogControl, "Cancel"),
text = SI_TRADING_HOUSE_CANCEL_LISTING_DIALOG_CANCEL,
callback = function(dialog)
dialog.listingIndex = nil
end,
}
}
})
-- Update the text on the cancel dialog (since it inherited from the purchase item dialog)
dialogControl:GetNamedChild("Description"):SetText(GetString(SI_TRADING_HOUSE_CANCEL_LISTING_DIALOG_DESCRIPTION))
end
function ZO_TradingHouseManager:ShowCancelListingConfirmation(listingIndex)
if not self.cancelListingDialog then
self.cancelListingDialog = ZO_TradingHouseCancelListingDialog
CancelListingDialogInitialize(self.cancelListingDialog, self)
end
self.cancelListingDialog.listingIndex = listingIndex
ZO_Dialogs_ShowDialog("CONFIRM_TRADING_HOUSE_CANCEL_LISTING")
end
--[[
End of Dialog Section
--]]
function ZO_TradingHouseManager:CanBuyItem(inventorySlot)
if not TRADING_HOUSE_SEARCH:IsAtTradingHouse() then
return false
end
if inventorySlot.sellerName == self.currentDisplayName then
return false
end
return true
end
function ZO_TradingHouseManager:VerifyBuyItemAndShowErrors(inventorySlot)
if inventorySlot.purchasePrice > self.playerMoney[inventorySlot.currencyType] then
ZO_AlertNoSuppression(UI_ALERT_CATEGORY_ALERT, SOUNDS.PLAYER_ACTION_INSUFFICIENT_GOLD, SI_TRADING_HOUSE_ERROR_NOT_ENOUGH_GOLD)
return false
end
return true
end
function ZO_TradingHouseManager:RunInitialSetup(control)
self.playerMoney = {}
self:InitializeEvents()
self:InitializeKeybindDescriptor()
self:InitializeMenuBar(control)
self:InitializePostItem(control)
self:InitializeBrowseItems(control)
self:InitializeListings(control)
self:InitializeScene()
end
local function SetPostPriceCallback(moneyInput, gold, eventType)
local tradingHouse = moneyInput:GetContext()
if eventType == "confirm" then
tradingHouse:SetPendingPostPrice(gold)
tradingHouse.invoiceSellPrice:SetHidden(false)
elseif eventType == "cancel" then
tradingHouse.invoiceSellPrice:SetHidden(false)
end
end
function ZO_TradingHouseManager:BeginSetPendingPostPrice(anchorTo)
if self:HasValidPendingItemPost() then
self.invoiceSellPrice:SetHidden(true)
CURRENCY_INPUT:SetContext(self)
CURRENCY_INPUT:Show(SetPostPriceCallback, false, self:GetPendingPostPrice(), CURT_MONEY, anchorTo, 20)
end
end
--[[ Globals ]]--
ZO_TRADING_HOUSE_SEARCH_RESULT_ITEM_ICON_MAX_WIDTH = 60 -- this is larger than the item icon to allow the icon to scale up
ZO_TRADING_HOUSE_SEARCH_RESULT_ITEM_NAME_WIDTH = 240
ZO_TRADING_HOUSE_SEARCH_RESULT_TRAIT_COLUMN_WIDTH = 42 -- this is larger than the trait icon to create a right margin
ZO_TRADING_HOUSE_SEARCH_RESULT_ITEM_NAME_WITHOUT_TRAIT_COLUMN_WIDTH = ZO_TRADING_HOUSE_SEARCH_RESULT_ITEM_NAME_WIDTH - ZO_TRADING_HOUSE_SEARCH_RESULT_TRAIT_COLUMN_WIDTH
ZO_TRADING_HOUSE_SEARCH_RESULT_TIME_LEFT_WIDTH = 60
ZO_TRADING_HOUSE_SEARCH_RESULT_UNIT_PRICE_WIDTH = 120
ZO_TRADING_HOUSE_SEARCH_RESULT_PRICE_WIDTH = 130
local function GetTradingHouseIndexForPreviewFromSlot(storeEntrySlot)
local inventorySlot = ZO_InventorySlot_GetInventorySlotComponents(storeEntrySlot)
local slotType = ZO_InventorySlot_GetType(inventorySlot)
if slotType == SLOT_TYPE_TRADING_HOUSE_ITEM_RESULT then
local tradingHouseIndex = ZO_Inventory_GetSlotIndex(inventorySlot)
local itemLink = GetTradingHouseSearchResultItemLink(tradingHouseIndex)
if CanItemLinkBePreviewed(itemLink) then
return tradingHouseIndex
end
end
return nil
end
function ZO_TradingHouse_OnSearchResultClicked(searchResultSlot, button)
-- left button for an inventory slot click will only try and drag and drop, but that
-- should be handled for us by the OnReceiveDrag handler, so if we left click
-- we'll do our custom behavior
if button ~= MOUSE_BUTTON_INDEX_LEFT then
ZO_InventorySlot_OnSlotClicked(searchResultSlot, button)
else
local tradingHouseIndex = GetTradingHouseIndexForPreviewFromSlot(searchResultSlot)
if tradingHouseIndex ~= nil then
TRADING_HOUSE:PreviewSearchResult(tradingHouseIndex)
end
end
end
function ZO_TradingHouse_OnSearchResultMouseEnter(searchResultSlot)
ZO_InventorySlot_OnMouseEnter(searchResultSlot)
local tradingHouseIndex = GetTradingHouseIndexForPreviewFromSlot(searchResultSlot)
local cursor = MOUSE_CURSOR_DO_NOT_CARE
if tradingHouseIndex ~= nil then
cursor = MOUSE_CURSOR_PREVIEW
end
WINDOW_MANAGER:SetMouseCursor(cursor)
end
function ZO_TradingHouse_OnSearchResultMouseExit(searchResultSlot)
ZO_InventorySlot_OnMouseExit(searchResultSlot)
WINDOW_MANAGER:SetMouseCursor(MOUSE_CURSOR_DO_NOT_CARE)
end
function ZO_TradingHouse_SearchResult_TraitInfo_OnMouseEnter(control)
local _, listPart = ZO_InventorySlot_GetInventorySlotComponents(control:GetParent())
ZO_InventorySlot_SetHighlightHidden(listPart, false)
local slotData = control:GetParent().dataEntry.data
if slotData.isGuildSpecificItem then
return
end
local traitInformation = GetItemTraitInformationFromItemLink(slotData.itemLink)
if traitInformation ~= ITEM_TRAIT_INFORMATION_NONE then
local itemTrait = GetItemLinkTraitInfo(slotData.itemLink)
local traitName = GetString("SI_ITEMTRAITTYPE", itemTrait)
local traitInformationString = GetString("SI_ITEMTRAITINFORMATION", traitInformation)
InitializeTooltip(InformationTooltip, control, TOPRIGHT, -10, 0, TOPLEFT)
InformationTooltip:AddLine(zo_strformat(SI_INVENTORY_TRAIT_STATUS_TOOLTIP, traitName, ZO_SELECTED_TEXT:Colorize(traitInformationString)), "", ZO_NORMAL_TEXT:UnpackRGB())
end
end
function ZO_TradingHouse_SearchResult_TraitInfo_OnMouseExit(control)
ClearTooltip(InformationTooltip)
local _, listPart = ZO_InventorySlot_GetInventorySlotComponents(control:GetParent())
ZO_InventorySlot_SetHighlightHidden(listPart, true)
end
function ZO_TradingHouse_OnInitialized(self)
TRADING_HOUSE = ZO_TradingHouseManager:New(self)
SYSTEMS:RegisterKeyboardObject(ZO_TRADING_HOUSE_SYSTEM_NAME, TRADING_HOUSE)
end
|
#!/usr/bin/env lua
--[[
Makes a request to an HTTP2 endpoint that has an infinite length response.
Usage: lua examples/h2_streaming.lua
]]
local request = require "http.request"
-- This endpoint returns a never-ending stream of chunks containing the current time
local req = request.new_from_uri("https://http2.golang.org/clockstream")
local _, stream = assert(req:go())
for chunk in stream:each_chunk() do
io.write(chunk)
end
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
---------------
--String Search
---------------
ZO_StringSearch = ZO_Object:Subclass()
function ZO_StringSearch:New(doCaching)
local search = ZO_Object.New(self)
search.data = {}
search.processors = {}
search.cache = doCaching or false
return search
end
function ZO_StringSearch:AddProcessor(typeId, processingFunction)
self.processors[typeId] = processingFunction
end
function ZO_StringSearch:Insert(data)
if(data) then
table.insert(self.data, data)
end
end
function ZO_StringSearch:Remove(data)
if(data) then
local numData = #self.data
for i = 1, numData do
if(self.data[i] == data) then
self.data[i] = self.data[numData]
table.remove(self.data, numData)
return
end
end
end
end
function ZO_StringSearch:RemoveAll()
self.data = {}
end
function ZO_StringSearch:ClearCache()
local data = self.data
local max = #data
for i = 1, max do
data[i].cache = nil
data[i].cached = false
end
end
function ZO_StringSearch:Process(data, searchTerms)
local numTerms = #searchTerms
for i = 1, numTerms do
local processFunc = self.processors[data.type]
if(not processFunc(self, data, searchTerms[i], self.cache)) then
return false
end
end
return true
end
function ZO_StringSearch:GetSearchTerms(str)
local strLen = #str
local lowerStr = str:lower()
local searchTerms = {}
for term in lowerStr:gmatch("%S+") do
table.insert(searchTerms, term:lower())
end
return searchTerms
end
function ZO_StringSearch:IsMatch(str, data)
if(not str or str == "") then return true end
local searchTerms = self:GetSearchTerms(str)
return self:Process(data, searchTerms)
end
function ZO_StringSearch:GetFromCache(data, cache, dataFunction, ...)
if(cache) then
if(not data.cached) then
--store the result list as a table
data.cache = { dataFunction(...) }
data.cached = true
end
--return the list of results
return unpack(data.cache)
else
--if we're not using caching, just call the function
return dataFunction(...)
end
end
|
local C = ccn2.C
local SpatialCrossResponseNormalization, parent = torch.class('ccn2.SpatialCrossResponseNormalization', 'nn.Module')
function SpatialCrossResponseNormalization:__init(size, addScale, powScale, minDiv, blocked)
parent.__init(self)
self.size = size
self.addScale = addScale or 0.0001
-- dic['scale'] /= dic['size'] if self.norm_type == self.CROSSMAP_RESPONSE_NORM else dic['size']**2
self.addScale = self.addScale / self.size
self.powScale = powScale or 0.75
self.minDiv = minDiv or 1.0
self.blocked = blocked or false
-- TODO: check layer.py:1333
self.output = torch.Tensor()
self.gradInput = torch.Tensor()
end
function SpatialCrossResponseNormalization:updateOutput(input)
ccn2.typecheck(input)
ccn2.inputcheck(input)
local nBatch = input:size(4)
local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4))
self.output:resize(inputC:size())
C['convResponseNormCrossMap'](cutorch.getState(), inputC:cdata(), self.output:cdata(),
input:size(1), self.size,
self.addScale, self.powScale, self.minDiv, self.blocked)
self.output = self.output:view(input:size(1), input:size(2), input:size(3), input:size(4))
return self.output
end
function SpatialCrossResponseNormalization:updateGradInput(input, gradOutput)
ccn2.typecheck(input); ccn2.typecheck(gradOutput);
ccn2.inputcheck(input); ccn2.inputcheck(gradOutput);
local nBatch = input:size(4)
local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4))
local gradOutputC = gradOutput:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4))
local outputC = self.output:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4))
self.gradInput:resize(inputC:size())
C['convResponseNormCrossMapUndo'](cutorch.getState(), gradOutputC:cdata(), inputC:cdata(), outputC:cdata(),
self.gradInput:cdata(), input:size(1), self.size,
self.addScale, self.powScale, self.minDiv, self.blocked, 0, 1)
self.gradInput = self.gradInput:view(input:size(1), input:size(2), input:size(3), input:size(4))
return self.gradInput
end
|
--[[
Pac-man: adaptive ambient soundtrack
Script for FCEUX + Emstrument
This script creates an alternate adaptive soundtrack for Pac-man. Sounds are generated
in response to game events and the player's and ghosts' positions.
This script works with the Logic Pro X project "pacman.logicx"
Tested with Pac-Man (USA) (Namco).nes
First published 12/2015 by Ben/Signal Narrative
Special thanks to http://datacrystal.romhacking.net/wiki/Pac-Man:RAM_map
]]
-- This script sends MIDI over 6 channels:
-- 1: FX 1 (pellets, etc).
-- 2-5: 4 synths corresponding to each ghost
-- 6: FX 2 (ghost eaten, etc)
require('emstrument');
MIDI.init();
lastscore = 0;
powerup = 0; -- Tracks whether or not any ghosts are still blue
pellets = 0;
-- The direction of each ghost determines which note it plays (g1___ = ghost 1's ____, etc)
g1lastdir = 0; -- ghost directions: 0 = stationary (beginning level or paused)
g2lastdir = 0; -- 1 = right, 2 = up, 3 = left, 4 = down
g3lastdir = 0;
g4lastdir = 0;
function getdirection(dx,dy)
if ((dx>0) and (dy==0)) then
return 1;
end;
if ((dx<0) and (dy==0)) then
return 3;
end;
if ((dx==0) and (dy>0)) then
return 4;
end;
if ((dx==0) and (dy<0)) then
return 2;
end;
-- object is either stationary or did something unexpected
return 0;
end;
g1lastx = 0;
g1lasty = 0;
g2lastx = 0;
g2lasty = 0;
g3lastx = 0;
g3lasty = 0;
g4lastx = 0;
g4lasty = 0;
lastlives = 0;
ghostnoteson = 0; -- only play the ghosts' notes during gameplay (obviously)
g1lastnote = 0;
g2lastnote = 0;
g3lastnote = 0;
g4lastnote = 0;
-- the basic notes for the ghosts (one per direction), which are gradually transposed.
ghostnotes1 = {55, 67, 59, 70};
ghostnotes2 = {52, 64, 56, 67};
ghostnotes = ghostnotes1; -- changes to ghostnotes1 or ghostnotes2 based on player x position
-- the notes played when eating pellets, chosen at random
pacnotes1 = {71, 72, 76, 78, 80, 82, 85, 86};
pacnotes2 = {69, 70, 73, 75, 79, 81, 82, 85};
pacnotes = pacnotes1; -- changes to pacnotes1 or pacnotes2 based on player y position
pacnotecount = 8; -- number of notes in each array
lastpacnote = 1; -- the last note played from the array. Used to avoid playing the same note twice
while (true) do
level = memory.readbyte(0x0068);
-- Score is used to determine when events occur
-- Each digit is stored in a byte:
score10s = memory.readbyte(0x0070);
score10_2s = memory.readbyte(0x0071);
score10_3s = memory.readbyte(0x0072);
score10_4s = memory.readbyte(0x0073);
score10_5s = memory.readbyte(0x0074);
score10_6s = memory.readbyte(0x0075);
score = 10*score10s + 100*score10_2s + 1000*score10_3s +
10000*score10_4s + 100000*score10_5s + 1000000*score10_6s;
pacx = memory.readbyte(0x001A);
pacy = memory.readbyte(0x001C);
lives = memory.readbyte(0x0067);
-- Read the memory indicating which graphic each ghost has:
-- 10 or 11 if heading up, 16 or 17 if heading right
-- 14 or 15 if heading down, 12 or 13 if heading left
-- 30 or 31 if ghost is blue
-- Can't use this for determing ghost direction because blue ghosts don't tell direction
g1graphic = memory.readbyte(0x0033);
g2graphic = memory.readbyte(0x0034);
g3graphic = memory.readbyte(0x0035);
g4graphic = memory.readbyte(0x0036);
-- Figure out where the ghosts are
g1x = memory.readbyte(0x001E);
g1y = memory.readbyte(0x0020);
g2x = memory.readbyte(0x0022);
g2y = memory.readbyte(0x0024);
g3x = memory.readbyte(0x0026);
g3y = memory.readbyte(0x0028);
g4x = memory.readbyte(0x002A);
g4y = memory.readbyte(0x002C);
-- If any ghosts are blue (graphic is 30 or 31), powerup is still active
if ((g1graphic-(g1graphic%2)==30) or (g2graphic-(g2graphic%2)==30) or
(g3graphic-(g3graphic%2)==30) or (g4graphic-(g4graphic%2)==30)) then
powerup = 1;
else
powerup = 0;
end;
-- Update CCs based on player's location
-- Channel 1 modulation/mod wheel = pacman's distance from center (96,112)
-- ll corner: (24,208)
-- lr corner: (168,208)
-- tl corner: (24,16)
-- tr corner: (168,16)
-- Max distance = 120
-- Controls filter cutoff for channel 1 instrument
centerdist = math.pow(math.pow(pacx - 96, 2) + math.pow(pacy - 112, 2), 0.5)
MIDI.CC(1, 64 - math.floor(centerdist/2 + 0.5), 1);
-- channel 2-5 mod = modified ghost distance from player
-- controls the intensity of each of the ghosts' notes
g1dist = math.max(0, 127 - math.pow(math.pow(pacx - g1x, 2) + math.pow(pacy - g1y, 2), 0.5));
g2dist = math.max(0, 127 - math.pow(math.pow(pacx - g2x, 2) + math.pow(pacy - g2y, 2), 0.5));
g3dist = math.max(0, 127 - math.pow(math.pow(pacx - g3x, 2) + math.pow(pacy - g3y, 2), 0.5));
g4dist = math.max(0, 127 - math.pow(math.pow(pacx - g4x, 2) + math.pow(pacy - g4y, 2), 0.5));
-- Set ghosts' channels modulation values based on distance to player
MIDI.CC(1, math.floor(g1dist), 2);
MIDI.CC(1, math.floor(g2dist), 3);
MIDI.CC(1, math.floor(g3dist), 4);
MIDI.CC(1, math.floor(g4dist), 5);
-- Set ghosts' general purpose 1 control values based on L/R distance to player (for
-- a panning effect). This causes an interesting effect when you go through the tunnel.
MIDI.CC(16, math.floor(64 + (g1x - pacx)/3 + 0.5), 2);
MIDI.CC(16, math.floor(64 + (g2x - pacx)/3 + 0.5), 3);
MIDI.CC(16, math.floor(64 + (g3x - pacx)/3 + 0.5), 4);
MIDI.CC(16, math.floor(64 + (g4x - pacx)/3 + 0.5), 5);
-- Get ghosts' directions
g1dir = getdirection(g1x - g1lastx, g1y - g1lasty);
g2dir = getdirection(g2x - g2lastx, g2y - g2lasty);
g3dir = getdirection(g3x - g3lastx, g3y - g3lasty);
g4dir = getdirection(g4x - g4lastx, g4y - g4lasty);
-- Play notes based on change in score and location on channels 1,6
if (score ~= lastscore) then
-- 10 points per pellet (modulo 50 so ghosts eaten at the same time as a pellet make noise)
if (((score - lastscore)%50) == 10) then
-- pick a random note from pacnotes array
pacnote = math.floor(pacnotecount * math.random()) + 1;
-- don't repeat notes, play the next note in the array if it's the same one as last time
if (pacnote == lastpacnote) then
pacnote = pacnote % (pacnotecount) + 1;
end;
-- transpose note based on which level the player is on.
MIDI.noteonwithduration(pacnotes[pacnote] - ((level%3)*2), 80, 1, 1);
if (powerup == 1) then
-- if powerup is enabled play another higher note at the same time
MIDI.noteonwithduration(pacnotes[pacnote] - ((level%3)*2) + 7, 80, 1, 1);
end;
lastpacnote = pacnote;
pellets = pellets + 1;
if (pellets % 30 == 0) then
-- add an octave to the ghost note every 30 pellets
MIDI.noteonwithduration(g1lastnote + 24, 100, 60, 5);
MIDI.noteonwithduration(g2lastnote + 12, 100, 60, 4);
MIDI.noteonwithduration(g3lastnote + 24, 100, 60, 3);
MIDI.noteonwithduration(g4lastnote + 12, 100, 60, 2);
end;
end;
-- 50 points for power pellet
if (score-lastscore == 50) then
-- play longer note for power pellet
MIDI.noteonwithduration(60, 100, 6, 1);
end;
-- 200, 400, 800, 1600 points for eating ghosts
-- (the -10 case is for when a pellet and ghost coincide)
if ((score - lastscore == 200) or (score - 10 - lastscore == 200)) then
MIDI.noteonwithduration(56, 100, 60, 6);
end;
if ((score - lastscore == 400) or (score - 10 - lastscore == 400)) then
MIDI.noteonwithduration(56, 100, 60, 6);
end;
if ((score - lastscore == 800) or (score - 10 - lastscore == 800)) then
MIDI.noteonwithduration(49, 100, 60, 6);
end;
if ((score - lastscore == 1600) or (score - 10 - lastscore == 1600)) then
MIDI.noteonwithduration(49, 100, 60, 6);
end;
-- 100, 300, 500, 700, 1000, 2000+ for various fruits
if (score-lastscore == 100) then
MIDI.noteonwithduration(60, 100, 6, 1);
end;
if (score-lastscore == 300) then
MIDI.noteonwithduration(60, 100, 6, 1);
end;
if (score-lastscore == 500) then
MIDI.noteonwithduration(60, 100, 6, 1);
end;
if (score-lastscore == 700) then
MIDI.noteonwithduration(60, 100, 6, 1);
end;
if ((score-lastscore == 1000) or (score-lastscore >= 2000)) then
MIDI.noteonwithduration(60, 100, 6, 1);
end;
end;
-- Choose the set of notes based on pacman's position:
if (pacx > 96) then
ghostnotes = ghostnotes1;
else
ghostnotes = ghostnotes2;
end;
if (pacy < 112) then
pacnotes = pacnotes1;
else
pacnotes = pacnotes2;
end;
-- play starts: lives reduced by 1, or ghosts jump back in
if ((lastlives - lives == 1)) or
((g1x ~= 0) and (g1y ~= 0) and (g1lastx == 0) and (g1lasty == 0)) then
-- start playing ghosts' notes again when play starts
ghostnoteson = true;
-- play the starting sound
MIDI.noteonwithduration(38, 100, 60, 1);
end;
-- pacman died if ghosts reset to location 0,0 (only need to check ghost1); stop playing ghosts' notes
if ((g1x == 0) and (g1y == 0) and (g1lastx ~= 0) and (g1lasty ~= 0)) then
-- stop note corresponding to g1dir, g2dir, etc
MIDI.noteoff(g1lastnote, 2);
MIDI.noteoff(g2lastnote, 3);
MIDI.noteoff(g3lastnote, 4);
MIDI.noteoff(g4lastnote, 5);
ghostnoteson = false;
MIDI.noteonwithduration(58, 100, 80, 6);
elseif (ghostnoteson) then
-- If the game is active, play the ghosts' notes:
offset = math.floor((level*3)/2) -- increase the notes pitch every level
-- If one of their directions changed, stop the last note and start playing the new one
if ((g1dir ~= 0) and (g1dir ~= g1lastdir)) then
-- stop the last note
MIDI.noteoff(g1lastnote, 2);
-- play the note corresponding to g1dir
MIDI.noteon(ghostnotes[g1dir] + offset, 100, 2);
g1lastnote = ghostnotes[g1dir] + offset;
g1lastdir = g1dir;
end;
if ((g2dir ~= 0) and (g2dir ~= g2lastdir)) then
MIDI.noteoff(g2lastnote, 3);
MIDI.noteon(ghostnotes[g2dir] + offset, 100, 3);
g2lastnote = ghostnotes[g2dir] + offset;
g2lastdir = g2dir;
end;
if ((g3dir ~= 0) and (g3dir ~= g3lastdir)) then
MIDI.noteoff(g3lastnote, 4);
MIDI.noteon(ghostnotes[g3dir] + offset, 100, 4);
g3lastnote = ghostnotes[g3dir] + offset;
g3lastdir = g3dir;
end;
if ((g4dir ~= 0) and (g4dir ~= g4lastdir)) then
MIDI.noteoff(g4lastnote, 5);
MIDI.noteon(ghostnotes[g4dir] + offset, 100, 5);
g4lastnote = ghostnotes[g4dir] + offset;
g4lastdir = g4dir;
end;
end;
-- Update last values for comparison later
lastscore = score;
g1lastx = g1x;
g1lasty = g1y;
g2lastx = g2x;
g2lasty = g2y;
g3lastx = g3x;
g3lasty = g3y;
g4lastx = g4x;
g4lasty = g4y;
lastlives = lives;
-- send midi messages
MIDI.sendmessages();
FCEU.frameadvance();
end;
|
local Array = require("AlgoLua.Libs.lockbox.util.array")
local Stream = require("AlgoLua.Libs.lockbox.util.stream")
local CBCMode = require("AlgoLua.Libs.lockbox.cipher.mode.cbc")
local PKCS7Padding = require("AlgoLua.Libs.lockbox.padding.pkcs7")
local ZeroPadding = require("AlgoLua.Libs.lockbox.padding.zero")
local AES256Cipher = require("AlgoLua.Libs.lockbox.cipher.aes256")
local UUID = require("AlgoLua.Libs.uuid4")
local HMAC = require("AlgoLua.Libs.lockbox.mac.hmac")
local SHA2_256 = require("AlgoLua.Libs.lockbox.digest.sha2_256")
local json = require("AlgoLua.Libs.json")
local QRCode = require("AlgoLua.WalletConnect.QRCode")
local ws = require("AlgoLua.WalletConnect.ws")
local http_client = require("AlgoLua.Api.HttpClient")
local Client = {
connected = false,
key = nil,
app = {},
session_topic = nil,
encrypt = function() end,
decript = function() end,
session_request = function() end,
network = 'testnet', -- testnet | mainnet,
connection = nil,
qrcode = nil,
account = nil
}
function Client.encrypt(data, key, iv)
local v = {
cipher = CBCMode.Cipher,
decipher = CBCMode.Decipher,
key = key,
iv = iv,
plaintext = Array.fromString(data),
padding = PKCS7Padding,
hmac = HMAC
}
local cipher = v.cipher()
.setKey(v.key)
.setBlockCipher(AES256Cipher)
.setPadding(v.padding);
local cipherText = cipher
.init()
.update(Stream.fromArray(v.iv))
.update(Stream.fromArray(v.plaintext))
.finish()
.asHex();
local unsigned = Array.concat(Array.fromHex(cipherText), v.iv)
local hmac = v.hmac()
.setKey(key)
.setDigest(SHA2_256)
.init()
.update(Stream.fromArray(unsigned))
.finish()
.asHex();
return {
data = cipherText,
hmac = hmac,
iv = Array.toHex(v.iv)
}
end
function Client.decrypt(data, key, iv)
local v = {
decipher = CBCMode.Decipher,
key = key,
iv = iv,
padding = ZeroPadding
}
local decipher = v.decipher()
.setKey(v.key)
.setBlockCipher(AES256Cipher)
.setPadding(v.padding);
local plainOutput = decipher
.init()
.update(Stream.fromArray(v.iv))
.update(Stream.fromArray(data))
.finish()
.asHex();
local jsonString = Client.remove_padding(Array.toString(Array.fromHex(plainOutput)))
return json.decode(jsonString)
end
function Client.remove_padding(jsonString)
return string.gsub(jsonString, "[%z\1-\16]*", "")
end
function Client.connect(app, on_connect_callback, on_message_callback)
Client.app = {
name = app.name,
description = app.description,
url = app.url,
icon = app.icon
}
ws.init()
ws.on_connect(function (conn, data)
Client.connected = true
if on_connect_callback then
on_connect_callback(message)
end
end)
ws.on_message(function (conn, message)
local message = json.decode(message)
if Client.session_topic == message.topic then
local payload = json.decode(message.payload)
local decrypted = Client.decrypt(Array.fromHex(payload.data), Array.fromHex(Client.key), Array.fromHex(payload.iv))
local result = decrypted.result
if result.approved and result.chainId == 4160 then -- Algorand
Client.draw_state = 'draw_connected'
Client.connection = result
msg.post("WalletConnect#interface", "draw_connected")
Client.get_account(
result.accounts[1],
function(account)
Client.draw_state = 'draw_balance'
msg.post("WalletConnect#interface", "draw_balance")
end)
else
pprint('canceled')
end
end
if on_message_callback then
on_message_callback(message)
end
end)
end
function Client.random_hex(length)
local res = ""
for i = 1, length do
local char = math.random(48, 62)
res = res .. string.char(char < 58 and char or char+40)
end
return res
end
function Client.payload_id()
local date = os.time(os.date("!*t")) * math.pow(10, 3)
local extra = math.floor(math.random() * math.pow(10, 3))
return date + extra
end
function Client.session_request()
local pub_topic = UUID.getUUID():lower()
local sub_topic = UUID.getUUID():lower()
local key = Client.random_hex(64)
local iv = Client.random_hex(32)
Client.key = key
local wcLink = "wc:" .. pub_topic .. "@1?bridge=https%3A%2F%2Fc.bridge.walletconnect.org&key=" .. key
pprint('wcLink', wcLink)
Client.qrcode = QRCode.draw(wcLink)
Client.draw_state = 'draw_qrcode'
msg.post("WalletConnect#interface", "draw_qrcode")
local app = Client.app
local encrypted = Client.encrypt(
json.encode({
id = Client.payload_id(),
jsonrpc = '2.0',
method = 'wc_sessionRequest',
params = {{
peerId = sub_topic,
peerMeta = {
name = app.name,
description = app.description,
url = app.url,
icon = app.icon
},
chainId = nil
}}
}),
Array.fromHex(key),
Array.fromHex(iv)
)
local sessionPublish = json.encode({
topic = pub_topic,
type = 'pub',
payload = json.encode({
data = encrypted.data,
hmac = encrypted.hmac,
iv = encrypted.iv
}),
silent = true
})
ws.send(sessionPublish)
local sessionSubscribe = json.encode({
topic = sub_topic,
type = 'sub',
payload = '',
silent = true
})
Client.session_topic = sub_topic
ws.send(sessionSubscribe)
end
function Client.get_account(address, callback)
network_url_part = (Client.network == 'testnet' and Client.network..'.' or '')
local on_success = function(account)
Client.account = account
local balance = {}
Client.account.balance = balance
balance[#balance+1] = {
['name'] = 'Algorand',
['unit-name'] = 'ALGO',
['decimals'] = 6,
['amount'] = account['amount']
}
if #account.assets == 0 then
callback(Client.account)
else
local count_assets = 1
local on_success_asset_detail = function(asset)
local params = asset.params
for idx,acc_asset in pairs(account.assets) do
if asset.index == acc_asset['asset-id'] then
balance[#balance+1] = {
['name'] = params['name'],
['unit-name'] = params['unit-name'],
['decimals'] = params['decimals'],
['amount'] = account.assets[idx]['amount']
}
end
end
if count_assets >= #account.assets and callback then
callback(Client.account)
end
count_assets = count_assets + 1
end
for _,asset in pairs(account.assets) do
http_client.get('https://' .. network_url_part .. 'algoexplorerapi.io/v2/assets/' .. asset['asset-id'], {}, on_success_asset_detail, on_error)
end
end
end
http_client.get('https://' .. network_url_part .. 'algoexplorerapi.io/v2/accounts/' .. address, {}, on_success, on_error)
end
return Client
|
local registered_emoji = {}
function refreshTable ()
local file = fileOpen("emojis.json")
registered_emoji = fromJSON(fileRead(file, fileGetSize(file)))
fileClose(file)
end
addEventHandler("onClientResourceStart",rroot,function()
refreshTable()
end,false)
local root = getRootElement()
local rroot = getResourceRootElement()
local sx,sy = guiGetScreenSize()
local chatbox = getChatboxLayout()
local y = chatbox["chat_scale"][2]
local lineas = chatbox["chat_lines"]
local font = "default"
if chatbox["chat_font"] == 1 then
font = "clear"
elseif chatbox["chat_font"] == 2 then
font = "default-bold"
elseif chatbox["chat_font"] == 3 then
font = "arial"
end
addEventHandler("onClientChatMessage",root,function(txt)
for k,v in ipairs(getElementsByType("gui-staticimage",rroot)) do
local gx,gy = guiGetPosition(v,true)
if string.len(txt) > 100 then
guiSetPosition(v, gx,gy-0.025,true)
else
guiSetPosition(v, gx,gy-0.025,true)
end
if gy <= 0.01 then
destroyElement(v)
end
end
txt = string.gsub(txt,"#%x%x%x%x%x%x","")
local len = 0
if string.len(txt) > 48 then
return
end
for i=1, #registered_emoji do
if string.find(txt,registered_emoji[i][1]) then
local text = string.gsub(txt,registered_emoji[i][1],"")
local len = dxGetTextWidth(text,chatbox["chat_scale"][1],font)
local lfin = convertirRelativo(len)
outputDebugString("LEN="..tostring(len).." LFIN="..tostring(lfin))
local img = guiCreateStaticImage(0.01875+lfin,0.02+(0.025*(lineas-1)),0.02,0.025,"emojis/"..registered_emoji[i][2],true)
end
end
end)
function convertirRelativo(x)
local rx = x/sx
return rx
end
|
--[[
Copyright 2019 Manticore Games, Inc.
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.
--]]
--[[
This script adds shot impulse in opposite direction of the projectile to the weapon owner.
Useful if used on weapons like revolver.
Define ProjectileKnockbackSpeed under custom property of the weapon to set the impulse power.
--]]
-- Internal custom properties
local WEAPON = script:FindAncestorByType('Weapon')
if not WEAPON:IsA('Weapon') then
error(script.name .. " should be part of Weapon object hierarchy.")
end
-- Exposed variables
local KNOCKBACK_SPEED = script:GetCustomProperty("ProjectileKnockbackSpeed")
-- Adds impulse to the owner once the attack ability is executed
function OnProjectileSpawned(weapon, projectile)
local player = weapon.owner
local displacement = -projectile:GetWorldTransform():GetForwardVector()
-- Create a direction at which the player is pushed away from the spawned projectile
player:AddImpulse((displacement):GetNormalized() * player.mass * KNOCKBACK_SPEED)
end
-- Initialize
WEAPON.projectileSpawnedEvent:Connect(OnProjectileSpawned)
|
-- -*- coding:utf-8 -*-
-- Copyright (C) 2017 ifritJP
local log = require( 'lctags.LogCtrl' )
local gcc = {}
local function processParen( arg, macroParen )
for paren in string.gmatch( arg, "[()]" ) do
if paren == "(" then
macroParen = macroParen + 1
else
macroParen = macroParen - 1
if macroParen < 0 then
log( 1, "unmatch arg paren", arg )
os.exit( 1 )
end
end
end
return macroParen
end
function gcc:createCompileOptionConverter( compiler )
if compiler ~= "gcc" then
return nil
end
local obj = {
nextType = nil,
macroParen = 0,
convert = function( self, arg )
if compiler == "gcc" then
if self.nextType == "skip" then
self.nextType = nil
return "skip"
elseif self.nextType == "opt" then
self.nextType = nil
return "opt", arg
elseif self.nextType == "macroParen" then
self.macroParen = processParen( arg, self.macroParen )
if self.macroParen == 0 then
self.nextType = nil
end
return "opt", arg
end
if string.find( arg, "^-" ) then
if string.find( arg, "^-[IDo]" ) then
if string.find( arg, "^-D" ) then
self.macroParen = processParen( arg, self.macroParen )
if self.macroParen > 0 then
self.nextType = "macroParen"
end
end
if arg == "-I" then
self.nextType = "opt"
end
if arg == "-o" then
self.nextType = "skip"
return "skip"
end
return "opt", arg
elseif string.find( arg, "-std=", 1, true ) then
return "opt", arg
elseif arg == "-include" then
self.nextType = "skip"
return "skip"
end
return "skip"
end
return "src", arg
end
end,
}
return obj
end
function gcc:getDefaultOptionList( compiler )
return {}
end
return gcc
|
local plr = game.Players.LocalPlayer.Backpack["Makarov"] --Change Mk 17 to whatever gun you have
plr.Stats.Recoil.Value = 0
plr.Stats.Accuracy.Value = 0
plr.Stats.Offset.Value = 0
|
local colors = require("cobalt2.utils").colors
local Group = require("cobalt2.utils").Group
local styles = require("cobalt2.utils").styles
---------------------------------------------------------------------------------
-- lir.nvim --
---------------------------------------------------------------------------------
Group.new("LirFloatNormal", colors.white, nil, nil)
Group.new("LirDir", colors.blue, nil, styles.bold)
Group.new("LirSymLink", colors.pink, nil, nil)
Group.new("LirEmptyDirText", colors.light_grey, nil, nil)
Group.new("LirFloatCurdirWindowNormal", colors.white, colors.cursor_hover, nil)
Group.new("LirFloatCurdirWindowDirName", colors.blue, nil, styles.italic)
Group.new("LirFloatBorder", colors.blue, nil, styles.bold)
|
local a=module('_core','libs/Tunnel')local b=module('_core','libs/Proxy')local c=a.getInterface("hpp_sellvehs")API=b.getInterface('API')cAPI=a.getInterface('cAPI')Citizen.CreateThread(function()while true do Citizen.Wait(5*60*1000)collectgarbage("count")collectgarbage("collect")end end)local d={[1]={["x"]=-32.130405426025,["y"]=-1111.6166992188,["z"]=26.422355651855}}function ToogleSellVehMenu(e)if e then PlaySoundFrontend(-1,"Pin_Good","DLC_HEIST_BIOLAB_PREP_HACKING_SOUNDS",1)end;SetNuiFocus(e,e)SendNUIMessage({open=e})end;Citizen.CreateThread(function()SetNuiFocus(false,false)end)RegisterNUICallback("closeMenu",function()PlaySoundFrontend(-1,"Hack_Success","DLC_HEIST_BIOLAB_PREP_HACKING_SOUNDS",1)ToogleSellVehMenu(false)end)RegisterNUICallback("buyVehicle",function(f)local g=c.buyCar(f.vehicle,parseInt(f.price),f.imageUrl,f.stock,f.trunk)if g.error then if g.reason=="Vehicle already exist in garage"then TriggerEvent("Notify","negado","Já existe esse veículo em sua garagem!")end;if g.reason=="Don't have money to buy this car"then TriggerEvent("Notify","negado","Você não tem dinheiro!")end;if g.reason=="Maximum number of cars in the garage"then TriggerEvent("Notify","negado","Número máximo de carros na garagem atingido!")end;if g.reason=="Stock is empty"then TriggerEvent("Notify","negado","O estoque deste carro acabou!")end else TriggerEvent("Notify","sucesso","Você comprou o veículo com sucesso!")end;print(g.reason)end)local h=4000;Citizen.CreateThread(function()while true do Citizen.Wait(h)for i=1,#d do local j=GetPlayerPed(-1)local k,l,m=table.unpack(GetEntityCoords(j))local n,o=GetGroundZFor_3dCoord(d[i].x,d[i].y,d[i].z)local p=GetDistanceBetweenCoords(d[i].x,d[i].y,o,k,l,m,true)if p<20 then h=1;DrawMarker(36,d[i].x,d[i].y,d[i].z,0,0,0,0,0,0,0.4,0.4,0.4,255,150,255,50,1,1,1,1)if p<1.5 then if IsControlJustPressed(0,38)then ToogleSellVehMenu(true)end end else h=4000 end end end end)function newNotify(q,r,s,t)if r~=-1 then SetNotificationBackgroundColor(r)end;SetNotificationTextEntry(q)for u,v in ipairs(s)do AddTextComponentSubstringPlayerName(v)end;DrawNotification(false,false)if t then PlaySoundFrontend(-1,"Menu_Accept","Phone_SoundSet_Default",1)end end;function notify(w)newNotify("STRING",11,{""..w},true)end
|
local playsession = {
{"mewmew", {446374}},
{"MeggalBozale", {345804}},
{"morcup", {326930}},
{"Serennie", {30279}},
{"MadClown01", {895914}},
{"ikeikeeng", {725686}},
{"flooxy", {100696}},
{"maigiee", {4346}},
{"Satyr", {306340}},
{"urss2", {7619}},
{"adee", {788954}},
{"ETK03", {50928}},
{"Irx99", {1776}},
{"Krono", {984677}},
{"yw2001ay", {116013}},
{"elprazeo", {49809}},
{"CrazyCrabEater", {114022}},
{"lagking", {125160}},
{"Hitman451", {308768}},
{"hasannuh", {782008}},
{"backburn", {84744}},
{"mr__meeseeks", {585136}},
{"Drahakar", {22961}},
{"Coletrain3", {609273}},
{"myphoneisdead", {4022}},
{"BlaQkout", {5862}},
{"Phireant", {245278}},
{"BrokeAsAJoke", {227192}},
{"yanfang8", {71730}},
{"tdrockstar", {314447}},
{"remarkablysilly", {4624}},
{"Kruv", {6656}},
{"umtallguy", {24835}},
{"c1eave", {2749}},
{"SilentLog", {11526}},
{"bigboyyy", {17175}},
{"AkimHUN", {433583}},
{"hyunbeen", {2414}},
{"Renekrause", {4909}},
{"gearmach1ne", {448413}},
{"Rasip", {5743}},
{"ajicurry", {158894}},
{"Zory", {278585}},
{"Gerkiz", {7256}},
{"loadover", {5376}},
{"quintkiller", {14467}}
}
return playsession
|
--Phantom Forces ESP V3 By RelentlessRaptor / !!!RelentlessRaptor#5709 on discord.
--Please credit me in any videos you use this in. Thanks.
wait(0.5)
plrs = nil
for _,p in pairs(game:GetChildren()) do
if p.ClassName == ("Players") then
plrs = p
end
end
function tors(plr)
local fr = Instance.new("SurfaceGui",plr.Character.Torso)
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(1,0,0)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character.Torso)
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(1,0,0)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character.Torso)
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(1,0,0)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character.Torso)
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(1,0,0)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character.Torso)
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(1,0,0)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character.Torso)
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(1,0,0)
bof.BackgroundTransparency = 0.2
end
function rightar(plr)
local fr = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(1,0,0)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(1,0,0)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(1,0,0)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(1,0,0)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(1,0,0)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(1,0,0)
bof.BackgroundTransparency = 0.2
end
function leftar(plr)
local fr = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(1,0,0)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(1,0,0)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(1,0,0)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(1,0,0)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(1,0,0)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(1,0,0)
bof.BackgroundTransparency = 0.2
end
function leftle(plr)
local fr = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(1,0,0)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(1,0,0)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(1,0,0)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(1,0,0)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(1,0,0)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(1,0,0)
bof.BackgroundTransparency = 0.2
end
function rightle(plr)
local fr = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(1,0,0)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(1,0,0)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(1,0,0)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(1,0,0)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(1,0,0)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(1,0,0)
bof.BackgroundTransparency = 0.2
end
function hea(plr)
local fr = Instance.new("SurfaceGui",plr.Character.Head)
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(1,0,0)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character.Head)
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(1,0,0)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character.Head)
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(1,0,0)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character.Head)
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(1,0,0)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character.Head)
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(1,0,0)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character.Head)
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(1,0,0)
bof.BackgroundTransparency = 0.2
end
------------------------------------------------------------------------------------------------------------------------
function ttors(plr)
local fr = Instance.new("SurfaceGui",plr.Character.Torso)
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character.Torso)
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character.Torso)
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character.Torso)
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character.Torso)
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character.Torso)
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
bof.BackgroundTransparency = 0.2
end
function trightar(plr)
local fr = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character["Right Arm"])
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
bof.BackgroundTransparency = 0.2
end
function tleftar(plr)
local fr = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character["Left Arm"])
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
bof.BackgroundTransparency = 0.2
end
function tleftle(plr)
local fr = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character["Left Leg"])
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
bof.BackgroundTransparency = 0.2
end
function trightle(plr)
local fr = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character["Right Leg"])
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
bof.BackgroundTransparency = 0.2
end
function thea(plr)
local fr = Instance.new("SurfaceGui",plr.Character.Head)
local frf = Instance.new("Frame",fr)
fr.Face = "Front"
fr.AlwaysOnTop = true
frf.Size = UDim2.new(1,0,1,0)
frf.BorderSizePixel = 0
frf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
frf.BackgroundTransparency = 0.2
local ba = Instance.new("SurfaceGui",plr.Character.Head)
local baf = Instance.new("Frame",ba)
ba.Face = "Back"
ba.AlwaysOnTop = true
baf.Size = UDim2.new(1,0,1,0)
baf.BorderSizePixel = 0
baf.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
baf.BackgroundTransparency = 0.2
local le = Instance.new("SurfaceGui",plr.Character.Head)
local lef = Instance.new("Frame",le)
le.Face = "Left"
le.AlwaysOnTop = true
lef.Size = UDim2.new(1,0,1,0)
lef.BorderSizePixel = 0
lef.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
lef.BackgroundTransparency = 0.2
local ri = Instance.new("SurfaceGui",plr.Character.Head)
local rif = Instance.new("Frame",ri)
ri.Face = "Right"
ri.AlwaysOnTop = true
rif.Size = UDim2.new(1,0,1,0)
rif.BorderSizePixel = 0
rif.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
rif.BackgroundTransparency = 0.2
local to = Instance.new("SurfaceGui",plr.Character.Head)
local tof = Instance.new("Frame",to)
to.Face = "Top"
to.AlwaysOnTop = true
tof.Size = UDim2.new(1,0,1,0)
tof.BorderSizePixel = 0
tof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
tof.BackgroundTransparency = 0.2
local bo = Instance.new("SurfaceGui",plr.Character.Head)
local bof = Instance.new("Frame",bo)
bo.Face = "Bottom"
bo.AlwaysOnTop = true
bof.Size = UDim2.new(1,0,1,0)
bof.BorderSizePixel = 0
bof.BackgroundColor3 = Color3.new(0/255, 255/255, 255/255)
bof.BackgroundTransparency = 0.2
end
while true do
wait(0.1)
for _, v in pairs(plrs:GetChildren()) do
if v.TeamColor ~= plrs.LocalPlayer.TeamColor and not v.Character.Torso:FindFirstChild("SurfaceGui") then -- ~=
tors(v)
rightar(v)
leftar(v)
leftle(v)
rightle(v)
hea(v)
end
if v.TeamColor == plrs.LocalPlayer.TeamColor and v.Name ~= plrs.LocalPlayer.Name and not v.Character.Torso:FindFirstChild("SurfaceGui") then -- ~=
ttors(v)
trightar(v)
tleftar(v)
tleftle(v)
trightle(v)
thea(v)
end
end
end
|
object_draft_schematic_weapon_component_new_weapon_comp_projectile_rifle_barrel = object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_rifle_barrel:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_weapon_component_new_weapon_comp_projectile_rifle_barrel, "object/draft_schematic/weapon/component/new_weapon_comp_projectile_rifle_barrel.iff")
|
fx_version 'adamant'
game 'gta5'
-- Manifest Version
description 'interact-sound'
version '1.0.0'
-- Client Scripts
client_script 'client/main.lua'
-- Server Scripts
server_script 'server/main.lua'
-- NUI Default Page
ui_page('client/html/index.html')
-- Arquivos necessários para NUI
-- NÃO ESQUEÇA DE ADICIONAR OS ARQUIVOS DE SOM A AQUI EM BAIXO!
files {
'client/html/index.html',
-- Comece os arquivos de som aqui...
-- client/html/sounds/ ... .ogg
'client/html/sounds/toux.ogg',
'client/html/sounds/touxfemme.ogg',
'client/html/sounds/demo.ogg'
}
|
task:add_args({one(config['filename']) or 'bootstrap.sh'})
task:add_args(get_commandline())
register_task(task)
|
-- See LICENSE for terms
--~ local Translate = ChoGGi.ComFuncs.Translate
local SettingState = ChoGGi.ComFuncs.SettingState
local Strings = ChoGGi.Strings
local Actions = ChoGGi.Temp.Actions
local c = #Actions
c = c + 1
Actions[c] = {ActionName = Strings[302535920000031--[[Find Nearest Resource]]],
ActionMenubar = "ECM.ECM",
ActionId = ".Find Nearest Resource",
ActionIcon = "CommonAssets/UI/Menu/EV_OpenFirst.tga",
RolloverText = Strings[302535920000554--[[Select an object and click this to display a list of resources (Shows nearest resource to object).]]],
OnAction = ChoGGi.ComFuncs.FindNearestResource,
}
c = c + 1
Actions[c] = {ActionName = Strings[302535920000333--[[Building Info]]],
ActionMenubar = "ECM.ECM",
ActionId = ".Building Info",
ActionIcon = "CommonAssets/UI/Menu/ExportImageSequence.tga",
RolloverText = Strings[302535920000345--[[Shows info about building in text above it.]]],
OnAction = ChoGGi.MenuFuncs.BuildingInfo_Toggle,
}
c = c + 1
Actions[c] = {ActionName = Strings[302535920001307--[[Grid Info]]],
ActionMenubar = "ECM.ECM",
ActionId = ".Grid Info",
ActionIcon = "CommonAssets/UI/Menu/ExportImageSequence.tga",
RolloverText = Strings[302535920001477--[["List objects in grids (air, electricity, and water)."]]],
OnAction = ChoGGi.MenuFuncs.BuildGridList,
}
--~ c = c + 1
--~ Actions[c] = {ActionName = Strings[302535920000555--[[Monitor Info]]],
--~ ActionMenubar = "ECM.ECM",
--~ ActionId = ".Monitor Info",
--~ ActionIcon = "CommonAssets/UI/Menu/EV_OpenFirst.tga",
--~ RolloverText = Strings[302535920000556--[[Shows a list of updated information about your city.]]],
--~ OnAction = ChoGGi.MenuFuncs.MonitorInfo,
--~ }
c = c + 1
Actions[c] = {ActionName = Strings[302535920000688--[[Clean All Objects]]],
ActionMenubar = "ECM.ECM",
ActionId = ".Clean All Objects",
ActionIcon = "CommonAssets/UI/Menu/DisableAOMaps.tga",
RolloverText = Strings[302535920000689--[[Removes all dust from all objects.]]],
OnAction = ChoGGi.MenuFuncs.CleanAllObjects,
}
c = c + 1
Actions[c] = {ActionName = Strings[302535920000690--[[Fix All Objects]]],
ActionMenubar = "ECM.ECM",
ActionId = ".Fix All Objects",
ActionIcon = "CommonAssets/UI/Menu/DisableAOMaps.tga",
RolloverText = Strings[302535920000691--[[Fixes all malfunctioned objects.]]],
OnAction = ChoGGi.MenuFuncs.FixAllObjects,
}
c = c + 1
Actions[c] = {ActionName = Strings[302535920000700--[[Scanner Queue Larger]]],
ActionMenubar = "ECM.ECM",
ActionId = ".Scanner Queue Larger",
ActionIcon = "CommonAssets/UI/Menu/ViewArea.tga",
RolloverText = function()
return SettingState(
ChoGGi.UserSettings.ExplorationQueueMaxSize,
Strings[302535920000701--[[Queue up to 100 squares.]]]
)
end,
OnAction = ChoGGi.MenuFuncs.ScannerQueueLarger_Toggle,
}
c = c + 1
Actions[c] = {ActionName = Strings[302535920000469--[[Close Dialogs]]],
ActionMenubar = "ECM.ECM",
ActionId = ".Close Dialogs",
ActionIcon = "CommonAssets/UI/Menu/remove_water.tga",
RolloverText = Strings[302535920000470--[[Close any dialogs opened by ECM (Examine, Object Editor, Change Colours, etc...)]]],
OnAction = ChoGGi.ComFuncs.CloseDialogsECM,
ActionSortKey = "99",
}
|
local Deque = require('plenary.async.structs').Deque
local eq = assert.are.same
-- just a helper to create the test deque
local function new_deque()
local deque = Deque.new()
eq(deque:len(), 0)
deque:pushleft(1)
eq(deque:len(), 1)
deque:pushleft(2)
eq(deque:len(), 2)
deque:pushright(3)
eq(deque:len(), 3)
deque:pushright(4)
eq(deque:len(), 4)
deque:pushright(5)
eq(deque:len(), 5)
return deque
end
describe('deque', function()
it('should allow pushing and popping and finding len', function()
new_deque()
end)
it('should be able to iterate from left', function()
local deque = new_deque()
local iter = deque:ipairs_left()
local i, v = iter()
eq(i, -2)
eq(v, 2)
i, v = iter()
eq(i, -1)
eq(v, 1)
i, v = iter()
eq(i, 0)
eq(v, 3)
i, v = iter()
eq(i, 1)
eq(v, 4)
i, v = iter()
eq(i, 2)
eq(v, 5)
end)
it('should be able to iterate from right', function()
local deque = new_deque()
local iter = deque:ipairs_right()
local i, v = iter()
eq(i, 2)
eq(v, 5)
i, v = iter()
eq(i, 1)
eq(v, 4)
i, v = iter()
eq(i, 0)
eq(v, 3)
i, v = iter()
eq(i, -1)
eq(v, 1)
i, v = iter()
eq(i, -2)
eq(v, 2)
end)
it('should allow clearing', function()
local deque = new_deque()
deque:clear()
assert(deque:is_empty())
end)
end)
|
module(..., package.seeall)
local io = require("io")
local http = require("socket.http")
local ltn12 = require("ltn12")
require "jester.support.file"
local cjson = require("cjson")
--[[
Speech to text using Google's API.
]]
function speech_to_text_from_file_google(action)
require "lfs"
local filepath = action.filepath
local area = action.storage_area or "speech_to_text"
if filepath then
-- Verify file exists.
local success, file_error = lfs.attributes(filepath, "mode")
if success then
local flac_file = os.tmpname()
local command = string.format("flac -f --compression-level-0 --sample-rate=8000 -o %s %s", flac_file, filepath)
local result = os.execute(command)
jester.debug_log("Flac return code: %s", result)
-- TODO: This call is sometimes returning -1, which is the C system()
-- call error code for a failure, even though the file is converted
-- successfully. This only seems to happen when flac is called from
-- within FreeSWITCH, calling the exact same command from the shell
-- returns 0, no idea why. Since flac error codes are always greater
-- than 0, this is at least a workable approach to make things function
-- until the real problem is uncovered.
if result < 1 then
local file = io.open(flac_file, "rb")
local filesize = (filesize(file))
local response = {}
local body, status_code, headers, status_description = http.request({
method = "POST",
headers = {
["content-length"] = filesize,
["content-type"] = "audio/x-flac; rate=8000",
},
url = "http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=en-US",
sink = ltn12.sink.table(response),
source = ltn12.source.file(file),
})
os.remove(flac_file)
if status_code == 200 then
local response_string = table.concat(response)
jester.debug_log("Google API server response: %s", response_string)
local data = cjson.decode(response_string)
jester.set_storage(area, "status", data.status or 1)
if data.status == 0 and data.hypotheses then
for k, chunk in ipairs(data.hypotheses) do
jester.set_storage(area, "translation_" .. k, chunk.utterance)
jester.set_storage(area, "confidence_" .. k, chunk.confidence)
end
end
else
jester.debug_log("ERROR: Request to Google API server failed: %s", status_description)
jester.set_storage(area, "status", 1)
end
else
jester.debug_log("ERROR: Unable to convert file %s to FLAC format via flac executable", filepath)
end
else
jester.debug_log("ERROR: File %s does not exist", filepath)
end
end
end
|
local skynet = require("skynet")
local proxy_meta = {}
proxy_meta.__index = proxy_meta
---@param query table query conditiron
---@param selector table fields to be returned
---@return boolean #whether call ok
---@return table|string # success data or error message
function proxy_meta:find(query, selector)
return skynet.call(self.addr, "lua", "find", query, selector)
end
---@param query table query conditiron
---@param selector table fields to be returned
---@return boolean #whether call ok
---@return table|string # success data or error message
function proxy_meta:findOne(tableName, query, selector)
return skynet.call(self.addr, "lua", "findOne", tableName, query, selector)
end
function proxy_meta:update(tableName, selector, update, upsert, multi)
return skynet.call(self.addr, "lua", "update", tableName, selector, update,
upsert, multi)
end
function proxy_meta:delete(tableName, selector, single)
return skynet.call(self.addr, "lua", "delete", tableName, selector, single)
end
function proxy_meta:insert(tableName, document)
return skynet.call(self.addr, "lua", "insert", tableName, document)
end
---Run a custom command. This cmd will be handled by the handler
---@param cmd any
---@param ... any
---@return any
function proxy_meta:run(cmd, ...)
return skynet.call(self.addr, "lua", cmd, ...)
end
---Execute a cmd or a query directly.
---For mongodb , see https://docs.mongodb.com/manual/reference/command/, the result is different
---@param ... any for mysql this is only a string sql.
---@return boolean , any
function proxy_meta:exec(...)
return skynet.call(self.addr, "lua", "exec", ...)
end
---This can start a service or wrapper to call to a db proxy service
local M = {}
---Used to start a db proxy service
---@param conf table {host, port, username, password, db}
function M.mongo(conf, handler)
skynet.start(function()
local mongo = require("skynet.db.mongo")
---@type mongo_db
local db = mongo.client(conf):getDB(conf.db)
local cmd = {}
function cmd.find(c, query, selector)
---@type mongo_cursor
local cur = db[c]:find(query, selector)
if cur:count() < 1 then
cur:close()
return false, "No data"
end
local res = {}
while cur:hasNext() do
res[#res + 1] = cur:next()
end
cur:close()
return true, res
end
function cmd.findOne(c, query, selector)
local r = db[c]:findOne(query, selector)
return r and true or false, r or false
end
function cmd.update(c, selector, update, upsert, multi)
local ok, err, r = db[c]:safe_update(selector, { ["$set"] = update },
upsert, multi)
return ok, ok and r or err
end
function cmd.delete(c, selector, single)
local ok, err, r = db[c]:safe_delete(selector, single)
return ok, ok and r or err
end
function cmd.insert(c, doc)
local ok, err, r = db[c]:safe_insert(doc)
return ok, ok and r or err
end
function cmd.exec(...)
local r = db:runCommand(...)
if r.ok == 1 then
return true, r
else
return false, r
end
end
skynet.dispatch("lua", function(_, _, action, ...)
local ok, res
if handler and handler[action] then
ok, success, res = pcall(handler[action], db, ...)
else
ok, success, res = pcall(cmd[action], ...)
end
if not ok then
return skynet.retpack(ok, success)
end
skynet.retpack(success, res)
end)
end)
end
---comment
---@param opts table {database,host, port, user, password,charset }
function M.mysql(opts, handler)
skynet.start(function()
local mysql = require("skynet.db.mysql")
---@type MySQL
local db = mysql.connect(opts)
local tconcat = table.concat
local sfmt = string.format
local cmd = {}
local type_fmt_map = { string = "%s = %s", number = "%s = %d" }
local function kv_list(document)
local kf, vf = {}, {}
for k, v in pairs(document) do
kf[#kf + 1] = k
vf[#vf + 1] = type(v) == "string" and mysql.quote_sql_str(v) or v
end
return tconcat(kf, ","), tconcat(vf, ",")
end
local function kv_equal(t)
local cond = {}
for k, v in pairs(t) do
cond[#cond + 1] = sfmt(type_fmt_map[type(v)], k, type(v) == "string" and
mysql.quote_sql_str(v) or v)
end
return cond
end
function cmd.find(c, query, selector)
local sql = sfmt("select %%s from %s where %%s", c)
sql = sfmt(sql, selector and tconcat(selector, ",") or "*",
tconcat(kv_equal(query), " and "))
return db:query(sql)
end
function cmd.findOne(c, query, selector)
local sql = sfmt("select %%s from %s where %%s limit 1", c)
sql = sfmt(sql, selector and tconcat(selector, ",") or "*",
tconcat(kv_equal(query), " and "))
return db:query(sql)
end
function cmd.update(c, selector, update, upsert, multi)
local sql = multi and sfmt("update %s set %%s where %%s", c) or
sfmt("update %s set %%s where %%s limit 1", c)
sql = sfmt(sql, tconcat(kv_equal(update)),
tconcat(kv_equal(selector), " and "))
return db:query(sql)
end
function cmd.delete(c, selector, single)
local sql = single and sfmt("delete from %s where %%s limit 1", c) or
sfmt("delete from %s where %%s", c)
sql = sfmt(sql, tconcat(kv_equal(selector), " and "))
return db:query(sql)
end
function cmd.insert(c, document)
local sql = sfmt("insert into %s(%%s) values(%%s)", c)
sql = sfmt(sql, kv_list(document))
return db:query(sql)
end
function cmd.exec(sql)
return db:query(sql)
end
skynet.dispatch("lua", function(_, _, action, ...)
local ok, res
if handler and handler[action] then
ok, res = pcall(handler[action], db, ...)
else
ok, res = pcall(cmd[action], ...)
end
if not ok then
return skynet.retpack(ok, res)
end
if res.badresult then
return skynet.retpack(false, res.err)
end
return skynet.retpack(true, res)
end)
end)
end
---Used to wrappe a db proxy service, will can direct call it
---@param addr any
function M.wrap(addr)
return setmetatable({ addr = addr }, proxy_meta)
end
return M
|
-- inculdes
local prompt = require 'prompt'
local Dialog = require 'dialog'
local app = require 'app'
local utils = require 'utils'
local Player = require 'player'
local NodeClass = require('nodes/npc')
return {
width = 32,
height = 48,
greeting = 'My name is {{red_light}}Juan{{white}}, I spend my days lazying around {{olive}}Tacotown{{white}}.',
animations = {
default = {
'loop',{'1,1','11,1'},.5,
},
walking = {
'loop',{'1,1','2,1','3,1'},.2,
},
},
talk_items = {
{ ['text']='i am done with you' },
{ ['text']='More options...', ['option']={
{ ['text']='Lay off that booze, pal' },
{ ['text']='You own that goat farm?', freeze = true },
{ ['text']='Tell me about this place' },
{ ['text']='I could sure use a beer' },
}},
{ ['text']='Any useful info for me?' },
{ ['text']='Donde esta...', ['option']={
{ ['text']='Castle Hawkthorne?' },
{ ['text']='the town blacksmith?' },
{ ['text']='the sandpits?' },
{ ['text']='la biblioteca?' },
}},
},
talk_commands = {
['You own that goat farm?']= function(npc, player)
if player.quest == 'Aliens! - Investigate Goat Farm' and npc.db:get('juan1-key', false) == false then
local Item = require 'items/item'
local itemNode = require ('items/keys/farm_key')
local item = Item.new(itemNode, 1)
if npc.db:get('juan1-negotiation', true) then
Dialog.new ("So you wanna poke around my goat farm a bit huh? Yeah I'll let you in-- for a price...", function()
npc.prompt = prompt.new("I'll lend you a spare key to the farm for {{orange}}60 coins{{white}}, how does that sound?", function(result)
if result == 'Yes' then
if player.money < 60 then
Dialog.new("Hey, you don't even have 60 coins! Get out of here!", function()
npc.menu:close(player)
end)
else
Dialog.new("Pleasure doing business with you. Here's the spare key to the farm.", function()
player.inventory:addItem(item, true)
player.money = player.money - 60
npc.db:set('juan1-key', true)
npc.menu:close(player)
end)
end
else
npc.prompt = prompt.new("Alright fine, how does {{orange}}40 coins{{white}} sound?", function(result2)
if result2 == 'Yes' then
if player.money < 40 then
Dialog.new("Hey, you don't even have 40 coins! Get out of here!", function()
npc.menu:close(player)
end)
else
Dialog.new("Pleasure doing business with you. Here's the spare key to the farm.", function()
player.money = player.money - 40
player.inventory:addItem(item, true)
npc.db:set('juan1-key', true)
npc.menu:close(player)
end)
end
else
Dialog.new("You cheapskate, I'm not doing business with you!", function()
npc.db:set('juan1-negotiation', false)
npc.menu:close(player)
end)
end
end)
end
npc.menu:close(player)
npc.prompt = nil
end)
end)
else
npc.prompt = prompt.new("Alright you cheapskate, I'm not giving away the farm key for anything less than {{orange}}100 coins{{white}}.", function(result3)
if result3 == 'Yes' then
if player.money < 100 then
Dialog.new("You don't even have 100 coins, get out of here you bum!", function()
npc.menu:close(player)
end)
else
Dialog.new("Pleasure doing business with you. See, you should have took my first offer and not have been greedy!", function()
player.money = player.money - 100
player.inventory:addItem(item, true)
npc.db:set('juan1-key', true)
npc.menu:close(player)
end)
end
else
Dialog.new("You cheapskate, I'm not doing business with you!", function()
npc.menu:close(player)
end)
end
end)
end
else
Dialog.new("Yup, all mine. Gotta make a living somehow.", function()
npc.menu:close(player)
end)
end
player.freeze = false
end,
},
talk_responses = {
['Lay off that booze, pal']={
"Buzz off, guy. You're not my mother.",
"Besides, I'm only on my 6th bottle of the day.",
},
['I could sure use a beer']={
"Well, you ain't getting any of mine.",
},
['Tell me about this place']={
"This stinkhole of a town? Nothing much to tell.",
"There's {{red_light}}Senor Juan{{white}} and his goons guarding the passage out of the valley...",
"Not that anyone's had a good reason to try and leave.",
},
['Castle Hawkthorne?']={
"I really hope you're not thinking of going there, that's a pretty darn dangrous place.",
"That being said, the castle is {{red_dark}}northeast{{white}} of here, past {{olive}}Gay Island{{white}} and the {{olive}}Black Caverns{{white}}.",
},
['the town blacksmith?']={
"Sleeping on the streets somewhere, probably,",
"He's one of the few employed guys around here, and he's the laziest out of all of us.",
},
['the sandpits?']={
"The {{olive}}sandpits{{white}}? Haven't heard anyone talk about that place in a while.",
"I believe it's somewhere past the {{olive}}chili fields{{white}}, I hear the entrance is very well hidden though.",
},
['la biblioteca?']={
"The library? We don't got no library here.",
"Is that like the only Spanish word you know?",
},
['Any useful info for me?']={
"If you're thinking about going into the {{olive}}sandpits{{white}}, it would be a good idea to bring a weapon.",
"I hear the ceiling is so low you can't even jump on enemies to hurt them.",
},
},
}
|
local dir = ... or "/tmp"
local maps = {}
local lookup = {}
local autofillCache
local function addRaw(filePath, funct, m, errLevel)
if type(filePath) ~= "string" then
error("Invalid filename", errLevel or 2)
elseif type(funct) ~= "function" then
error("Invalid function", errLevel or 2)
end
filePath = shell.resolve(filePath)
local i = #maps + 1
maps[i] = {
m = m or -1,
filePath = filePath,
funct = funct,
data = {}
}
lookup[filePath] = i
return i
end
local function addFile(filePath, funct)
return addRaw(filePath, funct, 0, 3)
end
local function addDir(filePath, funct)
return addRaw(filePath, funct, 1, 3)
end
local function removeNode(i)
local lookedUp = lookup[i]
if lookedUp then
lookup[i] = nil
maps[lookedUp] = nil
elseif type(i) == "number" then
lookup[maps[i].filePath] = nil
maps[i] = nil
else
error("Invalid index", 2)
end
end
local oldFS = _G.fs
local newFS = {}
function newFS.open(filePath, mode)
if type(filePath) ~= "string" then
error("Invalid filename", 2)
end
filePath = shell.resolve(filePath)
local i = lookup[filePath]
if i then
local node = maps[i]
if node.m ~= 0 and node.m ~= -1 then
error("Could not open file, not a file", 2)
end
return node.funct(data, "open", filePath, mode)
else
return oldFS.open(filePath, mode)
end
end
function newFS.list(path)
if path == nil
path = ""
elseif type(path) ~= "string" then
error("Invalid path", 2)
end
path = oldResolve
local results, ri = nil, 1
local i = lookup[pa
elseif oldFS.isDir(path) then
results = fs.list(path)
else
results = {}
end
for i, node in pairs(maps) do
local cmp = node.filePath
if #cmp < #path and path:sub(1, #cmp) == cmp and not path:sub(#cmp + 1):find("/") then
results[ri] = path:sub(#cmp + 1)
ri++
end
end
|
AddCSLuaFile("shared.lua")
if CLIENT then
SWEP.PrintName = "Dog"
SWEP.Category = "XYZ Weapons"
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = true
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false
SWEP.CSMuzzleFlashes = false
SWEP.Slot = 4
end
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.HoldType = "knife"
SWEP.Author = ""
SWEP.Purpose = ""
SWEP.Instructions = "W00f w00f."
SWEP.ViewModel = ""
SWEP.WorldModel = ""
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "none"
SWEP.Primary.Delay = 1.5
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = true
SWEP.Secondary.Ammo = "none"
SWEP.Sounds = {
"barks/dogbark_1.wav",
"barks/dogbark_2.wav",
"barks/dogbark_3.wav",
"barks/doggrowl_1.wav"
}
function SWEP:Precache()
util.PrecacheModel(self.ViewModel)
for k, v in pairs(self.Sounds) do
util.PrecacheSound(v)
end
end
SWEP.NextBark = 0
function SWEP:Bark()
if CurTime() < self.NextBark then return end
if SERVER and not CLIENT then
local bark = table.Random(self.Sounds)
self.Owner:EmitSound(bark)
end
self.NextBark = CurTime() + 2.5
end
function SWEP:PrimaryAttack()
self:Bark()
end
function SWEP:SecondaryAttack()
self:Bark()
end
function SWEP:Reload()
self:Bark()
end
|
fileNames = "abcdefgh"
rankNames = "12345678"
function SquareToCordinate(square)
square = square
-- local file = square % 7
local file = FileIndex(square)
local rank = RankIndex(square)
local placeX = file * Loader.pieceSize
local placeY = rank * Loader.pieceSize
return placeX, placeY
end
function RankIndex(squareIndex)
return 7 - bit.rshift(squareIndex - 1, 3)
end
function FileIndex(squareIndex)
return bit.band(squareIndex - 1, 7)
end
function IndexFromCoord(fileIndex, rankIndex)
return rankIndex * 8 + fileIndex + 1
end
function LightSquare(squareIndex)
return (FileIndex(squareIndex) + RankIndex(squareIndex)) % 2 ~= 0
end
function DarkSquare(squareIndex)
return (FileIndex(squareIndex) + RankIndex(squareIndex)) % 2 == 0
end
function IsClearSquare(squareIndex)
if IsSquare(squareIndex) then
if Board.Square[squareIndex][1] == 0 then
return true
end
end
return false
end
function IsMoved(squareIndex)
return Board.Square[squareIndex][3]
end
function IsSquare(squareIndex)
return squareIndex > 0 and squareIndex <= 64
end
function IsCheck(col)
local eCol = Piece().ReverseColor(col)
local t = (col == Piece().White and 'w') or 'b'
local changedTurn = false
local gamTurn = Game.turn
local pType = Piece().PieceType
local pCol = Piece.IsColor
local gen_moves = GenerateMoves
local gmBoard =Game.Board
for i, v in ipairs(gmBoard.Square) do
if v[1] ~= 0 then
if pCol(v[1], eCol) then
local aMoves = gen_moves(i)
for j, o in ipairs(aMoves) do
if pType(gmBoard.Square[o.TargetSquare][1]) == Piece().King then
return {true, o.TargetSquare}
end
end
end
end
end
Game.NextTurn()
for i, v in ipairs(gmBoard.Square) do
if v[1] ~= 0 then
if pCol(v[1], eCol) then
local aMoves = gen_moves(i)
for j, o in ipairs(aMoves) do
if pType(gmBoard.Square[o.TargetSquare][1]) == Piece().King then
Game.NextTurn()
return {true, o.TargetSquare}
end
end
end
end
end
Game.NextTurn()
return false
end
function CurrentlyInCheck(col)
local pType = Piece().PieceType
local eCol = Piece().ReverseColor(col)
local pCol = Piece.IsColor
Game.NextTurn()
for i, v in ipairs(Game.Board.Square) do
if v[1] ~= 0 and pType(v[1]) ~= Piece().King then
if pCol(v[1], eCol) then
local aMoves = GenerateMoves(i)
for j, o in ipairs(aMoves) do
if pType(Game.Board.Square[o.TargetSquare][1]) == Piece().King then
Game.NextTurn()
return {true, o.TargetSquare}
end
end
end
end
end
Game.NextTurn()
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.