content
stringlengths 5
1.05M
|
|---|
--ZFUNC-camelcase-v1
local function camelcase( strlst ) --> str
--ZFUNC-cutstr-v1
local function cutstr( str, n )
return str:sub( 1, n ), str:sub( n + 1, #str )
end
local str = {}
for i, v in ipairs( strlst ) do
local left, right = cutstr( v, 1 )
table.insert( str, string.upper( left ) )
table.insert( str, string.lower( right ) )
end
return table.concat( str )
end
return camelcase
|
local AtlasLoot = _G.AtlasLoot
local Pet = AtlasLoot.Button:AddType("Pet", "pet")
local Item = AtlasLoot.Button:GetType("Item")
local AL = AtlasLoot.Locales
--lua
local type = type
local tonumber = tonumber
local str_match = string.match
-- blizzard
local IsAddOnLoaded, LoadAddOn = IsAddOnLoaded, LoadAddOn
local ShowUIPanel = ShowUIPanel
local C_PetJournal_GetPetInfoBySpeciesID = C_PetJournal.GetPetInfoBySpeciesID
local PET_COLOR = "|cffffff00"
local PET_JOURNAL_TEXTURE = "Interface\\PetBattles\\PetJournal"
local PetClickHandler = nil
function Pet.OnSet(button, second)
if not PetClickHandler then
PetClickHandler = AtlasLoot.ClickHandler:Add(
"Pet",
{
GoTo = { "LeftButton", "None" },
types = {
GoTo = true,
},
},
AtlasLoot.db.Button.Pet.ClickHandler,
{
{ "GoTo", AL["Show Pet in Journal"], AL["Show Pet in Journal"] },
})
end
if not button then return end
if second and button.__atlaslootinfo.secType then
if type(button.__atlaslootinfo.secType[2]) == "table" then
button.secButton.PetID = button.__atlaslootinfo.secType[2][1]
button.secButton.ItemID = button.__atlaslootinfo.secType[2][2]
else
button.secButton.PetID = button.__atlaslootinfo.secType[2]
end
Pet.Refresh(button.secButton)
else
if type(button.__atlaslootinfo.type[2]) == "table" then
button.PetID = button.__atlaslootinfo.type[2][1]
button.ItemID = button.__atlaslootinfo.type[2][2]
else
button.PetID = button.__atlaslootinfo.type[2]
end
Pet.Refresh(button)
end
end
function Pet.OnMouseAction(button, mouseButton)
if not mouseButton then return end
mouseButton = PetClickHandler:Get(mouseButton)
if mouseButton == "GoTo" then
if not IsAddOnLoaded("Blizzard_Collections") then
LoadAddOn("Blizzard_Collections")
end
ShowUIPanel(CollectionsJournal)
CollectionsJournal_SetTab(CollectionsJournal, 2) -- 1 = Mounts
PetJournal_ShowPetCardBySpeciesID(button.PetID)
end
end
function Pet.OnClear(button)
button.PetID = nil
button.secButton.PetID = nil
button.info = nil
button.secButton.info = nil
button.overlay:Hide()
button.overlay:SetHeight(button.icon:GetWidth())
button.overlay:SetWidth(button.icon:GetWidth())
button.secButton.overlay:Hide()
button.secButton.overlay:SetTexCoord(1, 1, 1, 1)
button.secButton.overlay:SetHeight(button.icon:GetWidth())
button.secButton.overlay:SetWidth(button.icon:GetWidth())
end
function Pet.OnEnter(button)
Pet.ShowToolTipFrame(button)
end
function Pet.OnLeave(button)
if Pet.tooltipFrame then Pet.tooltipFrame:Hide() end
if button.ItemID then Item.OnLeave(button) end
end
--[[
self.TypeInfo.type:SetText(_G["BATTLE_PET_NAME_"..petType]);
self.TypeInfo.typeIcon:SetTexture("Interface\\PetBattles\\PetIcon-"..PET_TYPE_SUFFIX[petType]);
self.TypeInfo.abilityID = PET_BATTLE_PET_TYPE_PASSIVES[petType];
--Update pet abilites
local abilities, levels = C_PetJournal.GetPetAbilityList(speciesID);
for i=1,NUM_PET_ABILITIES do -- 6 abilities
local spellFrame = self["spell"..i];
if abilities[i] and canBattle then
local name, icon, petType = C_PetJournal.GetPetAbilityInfo(abilities[i]);
local isNotUsable = not level or level < levels[i];
spellFrame.icon:SetTexture(icon);
spellFrame.icon:SetDesaturated(isNotUsable);
spellFrame.LevelRequirement:SetText(levels[i]);
spellFrame.LevelRequirement:SetShown(isNotUsable);
spellFrame.BlackCover:SetShown(isNotUsable);
if (not level or level < levels[i]) then
spellFrame.additionalText = format(PET_ABILITY_REQUIRES_LEVEL, levels[i]);
else
spellFrame.additionalText = nil;
end
spellFrame.abilityID = abilities[i];
spellFrame.petID = PetJournalPetCard.petID;
spellFrame.speciesID = speciesID;
spellFrame:Show();
else
spellFrame:Hide();
end
end
<Texture name="$parentIconBorder" file="Interface\PetBattles\PetJournal" parentKey="iconBorder">
<Anchors>
<Anchor point="CENTER" relativeTo="$parentIcon" x="0" y="0"/>
</Anchors>
<Size x="53" y="54"/>
<TexCoords left="0.41992188" right="0.52343750" top="0.02246094" bottom="0.07519531"/>
</Texture>
]]--
function Pet.Refresh(button)
-- speciesName, speciesIcon, petType, companionID, tooltipSource, tooltipDescription, isWild, canBattle, isTradeable, isUnique, obtainable = C_PetJournal.GetPetInfoBySpeciesID(button.PetID)
local speciesName, speciesIcon, petType, companionID, tooltipSource, tooltipDescription = C_PetJournal_GetPetInfoBySpeciesID(button.PetID)
if not speciesName then return end
if button.type == "secButton" then
--/dump C_PetJournal.GetPetInfoBySpeciesID(1145)
else
button.name:SetText(PET_COLOR..speciesName)
button.extra:SetText(_G["BATTLE_PET_NAME_"..petType])
end
button.overlay:Show()
button.overlay:SetTexture(PET_JOURNAL_TEXTURE)
button.overlay:SetTexCoord(0.41992188, 0.52343750, 0.02246094, 0.07519531)
button.overlay:SetHeight(button.icon:GetHeight()*1.2)
button.overlay:SetWidth(button.icon:GetWidth()*1.2)
button.icon:SetTexture(speciesIcon)
button.info = {speciesName, speciesIcon, petType, tooltipSource, tooltipDescription, companionID}
end
function Pet.GetStringContent(str)
if tonumber(str) then
return tonumber(str)
else
return {
str_match(str, "(%d+)"),
str_match(str, "i(%d+)"), -- linked item
}
end
end
--################################
-- Pet frame
--################################
function Pet.ShowToolTipFrame(button)
if not Pet.tooltipFrame then
local name = "AtlasLoot-PetToolTip"
local frame = CreateFrame("Frame", name)
frame:SetClampedToScreen(true)
frame:SetSize(300, 50)
frame:SetBackdrop({bgFile = "Interface/Tooltips/UI-Tooltip-Background",
edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 4, right = 4, top = 4, bottom = 4 }})
frame:SetBackdropColor(0,0,0,1)
frame.icon = frame:CreateTexture(name.."-icon", frame)
frame.icon:SetPoint("TOPLEFT", frame, "TOPLEFT", 5, -5)
frame.icon:SetHeight(26)
frame.icon:SetWidth(26)
frame.icon:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
frame.name = frame:CreateFontString(name.."-name", "ARTWORK", "GameFontNormal")
frame.name:SetPoint("TOPLEFT", frame.icon, "TOPRIGHT", 3, 0)
frame.name:SetJustifyH("LEFT")
frame.name:SetWidth(250)
--frame.name:SetHeight(12)
frame.name:SetTextColor(1, 1, 1, 1)
frame.source = frame:CreateFontString(name.."-source", "ARTWORK", "GameFontNormalSmall")
frame.source:SetPoint("TOPLEFT", frame.name, "BOTTOMLEFT", 0, -1)
frame.source:SetJustifyH("LEFT")
frame.source:SetJustifyV("TOP")
frame.source:SetWidth(250)
--frame.info:SetHeight(20)
frame.source:SetTextColor(1, 1, 1, 1)
frame.model = CreateFrame("PlayerModel", name.."-model")
frame.model:ClearAllPoints()
frame.model:SetParent(frame)
frame.model:SetPoint("TOPLEFT", frame.icon, "BOTTOMLEFT", 0, -3)
frame.model:SetSize(145,145)
frame.model:SetRotation(MODELFRAME_DEFAULT_ROTATION)
frame.desc = frame:CreateFontString(name.."-desc", "ARTWORK", "GameFontNormalSmall")
frame.desc:SetPoint("TOPLEFT", frame.model, "TOPRIGHT", 0, -3)
frame.desc:SetJustifyH("LEFT")
frame.desc:SetJustifyV("TOP")
frame.desc:SetWidth(145)
frame.desc:SetHeight(145)
frame.desc:SetTextColor(1, 1, 1, 1)
frame.typeIcon = frame:CreateTexture(name.."-typeIcon", frame)
frame.typeIcon:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -5, -5)
frame.typeIcon:SetHeight(20)
frame.typeIcon:SetWidth(20)
frame.typeIcon:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
frame.typeIcon:SetTexCoord(0.79687500, 0.49218750, 0.50390625, 0.65625000)
Pet.tooltipFrame = frame
end
local tmp
local frame = Pet.tooltipFrame
frame:ClearAllPoints()
frame:SetParent(button:GetParent():GetParent())
frame:SetFrameStrata("TOOLTIP")
frame:SetPoint("BOTTOMLEFT", button, "TOPRIGHT")
frame.name:SetText(button.info[1])
frame.source:SetText(button.info[4])
frame.icon:SetTexture(button.info[2])
tmp = frame.name:GetHeight()+frame.source:GetHeight()
frame.icon:SetSize(tmp,tmp)
frame:SetHeight(tmp+155)
frame.desc:SetText(button.info[5])
frame.model:SetCreature(button.info[6])
frame.model:SetDoBlend(false)
--frame.model:SetAnimation(0,-1) 0=alive, 6=dead
frame.typeIcon:SetTexture("Interface\\PetBattles\\PetIcon-"..PET_TYPE_SUFFIX[button.info[3]])
frame:Show()
if button.ItemID then
Item.OnEnter(button, {frame, "ANCHOR_TOPLEFT", 0, 2})
end
end
|
require "scripts/library/timers"
require "scripts.common";
local PickScreenAbilityScript =
{
CurrentAbility = nil;
OwnButton = nil;
Info = nil;
abilityHandler = nil;
ToolTip = nil;
AbilityPanel = nil;
spawnTickets = {};
init = false;
Properties =
{
ManaText = {default = EntityId()},
Image = {default = EntityId()},
CurrentLevelTextColour = {default = Color(255/255, 255/255, 255/255)},
NonCurrentLevelTextColour = {default = Color(0/255, 0/255, 0/255)},
LeveledColour = {default = Color(255/255, 255/255, 255/255)},
DisabledColour = {default = Color(126/255, 126/255, 126/255)},
}
}
-- On Activate
function PickScreenAbilityScript:OnActivate()
self.OwnButton = UiElementBus.Event.FindChildByName(self.entityId, "Button")
self.canvasNotificationHandler = nil
self.handler = InputMapperNotificationBus.Connect(self);
CreateTimer(function()
self:Init()
end,0.1);
end
function PickScreenAbilityScript:Init()
self.CanvasEntityId = self.CanvasEntityId or UiElementBus.Event.GetCanvas(self.entityId)
if self.CanvasEntityId ~= nil then
if self.canvasNotificationHandler then
self.canvasNotificationHandler:Disconnect()
self.canvasNotificationHandler = nil
end
self.canvasNotificationHandler = UiCanvasNotificationBus.Connect(self, self.CanvasEntityId)
self.ToolTip = self.Tooltip or UiCanvasBus.Event.FindElementByName(self.CanvasEntityId, "AbilityDescriptor")
self.AbilityPanel = self.AbilityPanel or UiCanvasBus.Event.FindElementByName(self.CanvasEntityId, "Abilities")
self.ChosenHero = self.ChosenHero or UiCanvasBus.Event.FindElementByName(self.CanvasEntityId, "ChosenHero")
end
if UiElementBus.Event.IsEnabled(self.ChosenHero) == true and self.init == false and self.OwnButton ~= nil then
local parentSlot = UiElementBus.Event.GetParent(self.OwnButton)
if parentSlot ~= nil then
self.CurrentAbility = UiTextBus.Event.GetText(UiElementBus.Event.FindDescendantByName(parentSlot, "AbilityName"))
end
end
--Setting Ability Button Images
if self.CurrentAbility ~= nil then
if GetAbilityInfo(self.CurrentAbility) ~= nil then
local Info = GetAbilityInfo(self.CurrentAbility);
if Info~=nil and Info["icon-file"] ~= nil then
local AbilityImage = Info["icon-file"]
local ImageString = tostring(tostring(AbilityImage) .. ".dds")
UiImageBus.Event.SetSpritePathname(self.Properties.Image, ImageString)
else
UiImageBus.Event.SetSpritePathname(self.Properties.Image, "textures/core.dds")
end
self.init = true
end
end
end
function PickScreenAbilityScript:OnEntitySpawned(ticket, id)
end
function PickScreenAbilityScript:OnSpawnEnd(ticket)
end
function PickScreenAbilityScript:OnSpawnFailed(ticket)
end
-- Deactivate
function PickScreenAbilityScript:OnDeactivate()
if self.abilityHandler then
self.abilityHandler:Disconnect()
end
if self.canvasNotificationHandler then
self.canvasNotificationHandler:Disconnect()
end
if self.selectionHandler then
self.selectionHandler:Disconnect()
end
end
-- Actions In Ability Script
function PickScreenAbilityScript:OnAction(entityId, actionName)
if self.OwnButton == entityId then
-- Ability Tool Tip
if actionName == "AbilityHovering" then
local AbilityButton = UiElementBus.Event.GetParent(entityId)
local text = UiTextBus.Event.GetText(UiElementBus.Event.FindDescendantByName(AbilityButton, "AbilityName"))
local CurrentHoverAbility = text
self:UpdateToolTip(CurrentHoverAbility)
end
end
end
-- Tool Tip Function
function PickScreenAbilityScript:UpdateToolTip(ability)
-- Check If Ability Is Valid
if not ability then
return;
end
local ItemPanel = UiElementBus.Event.FindDescendantByName(self.ToolTip, "Item")
local AbilityPanel = UiElementBus.Event.FindDescendantByName(self.ToolTip, "Ability")
UiElementBus.Event.SetIsEnabled(ItemPanel, false)
UiElementBus.Event.SetIsEnabled(AbilityPanel, true)
local StatArea = UiElementBus.Event.FindDescendantByName(AbilityPanel, "AbilityStats")
local NamePanel = UiElementBus.Event.FindDescendantByName(AbilityPanel, "AbilityName")
local LevelPanel = UiElementBus.Event.FindDescendantByName(AbilityPanel, "AbilityLevel")
local DescriptionPanel = UiElementBus.Event.FindDescendantByName(AbilityPanel, "AbilityDescription")
UiElementBus.Event.SetIsEnabled(LevelPanel, false)
local CoolDownArea = UiElementBus.Event.FindDescendantByName(AbilityPanel, "CoolDownPanel")
local ManaPanel = UiElementBus.Event.FindDescendantByName(AbilityPanel, "ManaPanel")
local CoolDownTextPanel = UiElementBus.Event.FindDescendantByName(AbilityPanel, "CoolDownTextPanel")
local ManaTextPanel = UiElementBus.Event.FindDescendantByName(AbilityPanel, "ManaTextPanel")
-- Assign Ability Info
if self.Info ~= ability or self.Info == nil then
self.Info = GetAbilityInfo(ability)
end
-- Set Tool Tip Ability Name
if ability ~= nil then
--Debug.Log("LOOK HERE FOR ABILITY CASTING BEHAVIOR !" .. tostring(Ability.GetCastingBehavior({entityId = ability})))
local values=splitstring(ability, "/")
file_name = tostring(values[2])
localizeText = LocalizationRequestBus.Broadcast.LocalizeString("@ui_ability_" .. tostring(file_name))
UiTextBus.Event.SetText(NamePanel, localizeText)
descriptionLocalizeText = LocalizationRequestBus.Broadcast.LocalizeString("@ui_ability_" .. tostring(file_name) .. "_description")
UiTextBus.Event.SetText(DescriptionPanel, descriptionLocalizeText)
else
UiTextBus.Event.SetText(NamePanel, "Ability Name")
end
--needs to be updated once max level can be found, currently setting to 4 for default
local MaxLevel = self.Info.maxlevel or 4
Debug.Log(tostring(MaxLevel))
for i=1,MaxLevel do
local CoolDownText = UiElementBus.Event.GetChild(CoolDownTextPanel,i-1)
local ManaText = UiElementBus.Event.GetChild(ManaTextPanel,i-1)
-- Update Tool Tip Cooldown
if self.Info.cooldown ~= nil then
UiElementBus.Event.SetIsEnabled(CoolDownArea, true)
if GetKvValue(self.Info.cooldown,i) ~= nil then
if i <= 1 then
UiElementBus.Event.SetIsEnabled(CoolDownText, true)
UiTextBus.Event.SetText(CoolDownText, GetKvValue(self.Info.cooldown,i))
UiTextBus.Event.SetColor(CoolDownText, self.Properties.CurrentLevelTextColour)
elseif i >= 2 and GetKvValue(self.Info.cooldown,i) ~= GetKvValue(self.Info.cooldown,1) then
UiElementBus.Event.SetIsEnabled(CoolDownText, true)
UiTextBus.Event.SetText(CoolDownText, GetKvValue(self.Info.cooldown,i))
UiTextBus.Event.SetColor(CoolDownText, self.Properties.CurrentLevelTextColour)
elseif i >= 2 and GetKvValue(self.Info.cooldown,i) == GetKvValue(self.Info.cooldown,1) then
UiElementBus.Event.SetIsEnabled(CoolDownText, false)
end
else
UiElementBus.Event.SetIsEnabled(CoolDownText, false)
end
else
UiElementBus.Event.SetIsEnabled(CoolDownArea, false)
end
-- Update Tool Tip Mana Cost
if self.Info.costs ~= nil then
UiElementBus.Event.SetIsEnabled(ManaPanel, true)
if self.Info.costs.mana ~= nil then
if GetKvValue(self.Info.costs.mana,i) ~= nil then
if i <= 1 then
UiElementBus.Event.SetIsEnabled(ManaText, true)
UiTextBus.Event.SetText(ManaText, GetKvValue(self.Info.costs.mana,i))
UiTextBus.Event.SetColor(ManaText, self.Properties.CurrentLevelTextColour)
elseif i >= 2 and GetKvValue(self.Info.costs.mana,i) ~= GetKvValue(self.Info.costs.mana,1) then
UiElementBus.Event.SetIsEnabled(ManaText, true)
UiTextBus.Event.SetText(ManaText, GetKvValue(self.Info.costs.mana,i))
UiTextBus.Event.SetColor(ManaText, self.Properties.CurrentLevelTextColour)
elseif i >= 2 and GetKvValue(self.Info.costs.mana,i) == GetKvValue(self.Info.costs.mana,1) then
UiElementBus.Event.SetIsEnabled(ManaText, false)
end
else
UiElementBus.Event.SetIsEnabled(ManaText, false)
end
else
UiElementBus.Event.SetIsEnabled(ManaPanel, false)
end
else
UiElementBus.Event.SetIsEnabled(ManaPanel, false)
end
if self.Info["special-values"] ~= nil then
local count = 0
for i=1,9 do
UiElementBus.Event.SetIsEnabled(UiElementBus.Event.GetChild(StatArea,i),false)
end
for k,v in pairs(self.Info["special-values"]) do
if type(k) == "string" then
count = count + 1
self.statName = k
local child = UiElementBus.Event.GetChild(StatArea,count)
UiElementBus.Event.SetIsEnabled(child,true)
local name = UiElementBus.Event.GetChild(child,0)
local stat = UiElementBus.Event.GetChild(child,1)
local StatText = UiElementBus.Event.GetChild(stat,i-1)
statLocalizeText = LocalizationRequestBus.Broadcast.LocalizeString("@ui_ability_" .. tostring(file_name) .. "_" .. tostring(k))
UiTextBus.Event.SetText(name,statLocalizeText)
local json = self.Info["special-values"][k]
if GetKvValue(tostring(json),i) ~= nil then
if i <= 1 then
UiElementBus.Event.SetIsEnabled(StatText, true)
UiTextBus.Event.SetText(StatText, GetKvValue(tostring(json),i))
UiTextBus.Event.SetColor(StatText, self.Properties.CurrentLevelTextColour)
elseif i >= 2 and GetKvValue(tostring(json),i) ~= GetKvValue(tostring(json),1) then
UiElementBus.Event.SetIsEnabled(StatText, true)
UiTextBus.Event.SetText(StatText, GetKvValue(tostring(json),i))
UiTextBus.Event.SetColor(StatText, self.Properties.CurrentLevelTextColour)
elseif i >= 2 and GetKvValue(tostring(json),i) == GetKvValue(tostring(json),1) then
UiElementBus.Event.SetIsEnabled(StatText, false)
end
else
UiElementBus.Event.SetIsEnabled(StatText, false)
end
end
end
end
end
end
return PickScreenAbilityScript;
|
local Events = require "scripts/ToolKit/events"
local Utilities = require "scripts/ToolKit/utilities"
local LimitedSpawner =
{
Properties =
{
Debug = false,
Event = "OnSpawn",
},
}
function LimitedSpawner:OnActivate()
Utilities:InitLogging(self, "LimitedSpawner")
self.gameplayListener = GameplayNotificationBus.Connect(self, GameplayNotificationId(self.entityId, self.Properties.Event, "float"))
end
function LimitedSpawner:OnEventBegin(value)
SpawnerComponentRequestBus.Event.DestroyAllSpawnedSlices(self.entityId)
SpawnerComponentRequestBus.Event.Spawn(self.entityId)
end
function LimitedSpawner:OnDeactivate()
if self.gameplayListener ~= nil then
self.gameplayListener:Disconnect()
self.gameplayListener = nil
end
end
return LimitedSpawner
|
local Roact = require(script.Parent.Parent.Parent.Libraries.Roact)
local function App(props)
return Roact.createElement("Frame", {
Size = UDim2.fromScale(1, 1),
BackgroundColor3 = Color3.fromRGB(71, 71, 69)
}, props[Roact.Children])
end
return App
|
local frozArena = LibStub("AceAddon-3.0"):GetAddon("frozArena")
frozArena.data = {
general = {
classIcons = {
["DRUID"] = 625999,
["HUNTER"] = 626000,
["MAGE"] = 626001,
["MONK"] = 626002,
["PALADIN"] = 626003,
["PRIEST"] = 626004,
["ROGUE"] = 626005,
["SHAMAN"] = 626006,
["WARLOCK"] = 626007,
["WARRIOR"] = 626008,
["DEATHKNIGHT"] = 135771,
["DEMONHUNTER"] = 1260827,
}
}
}
|
--[[
#part of the 3DreamEngine by Luke100000
jobs.lua - processes all kind of side tasks (shadows, blurring ambient lighting, rendering sky dome, ...)
--]]
local lib = _3DreamEngine
local timeRequirement = { }
local executionsPerSecond = { }
local executions = { }
local times = { }
local pointShadowProjectionMatrix
do
local n = 0.01
local f = 1000.0
local fov = 90
local scale = math.tan(fov/2*math.pi/180)
local r = scale * n
local l = -r
pointShadowProjectionMatrix = mat4(
2*n / (r-l), 0, (r+l) / (r-l), 0,
0, -2*n / (r - l), (r+l) / (r-l), 0,
0, 0, -(f+n) / (f-n), -2*f*n / (f-n),
0, 0, -1, 0
)
end
local lookNormals = {
vec3(1, 0, 0),
vec3(-1, 0, 0),
vec3(0, -1, 0),
vec3(0, 1, 0),
vec3(0, 0, 1),
vec3(0, 0, -1),
}
local blurVecs = {
{
{1.0, 0.0, 0.0},
{0.0, 0.0, -1.0},
{0.0, -1.0, 0.0},
{0.0, 0.0, 1.0},
},
{
{-1.0, 0.0, 0.0},
{0.0, 0.0, 1.0},
{0.0, -1.0, 0.0},
{0.0, 0.0, 1.0},
},
{
{0.0, 1.0, 0.0},
{1.0, 0.0, 0.0},
{0.0, 0.0, 1.0},
{1.0, 0.0, 0.0},
},
{
{0.0, -1.0, 0.0},
{1.0, 0.0, 0.0},
{0.0, 0.0, -1.0},
{1.0, 0.0, 0.0},
},
{
{0.0, 0.0, 1.0},
{1.0, 0.0, 0.0},
{0.0, -1.0, 0.0},
{1.0, 0.0, 0.0},
},
{
{0.0, 0.0, -1.0},
{-1.0, 0.0, 0.0},
{0.0, -1.0, 0.0},
{1.0, 0.0, 0.0},
},
}
local identityMatrix = mat4:getIdentity()
local blurCanvases = { }
function lib.blurCubeMap(self, cube, level)
local f = cube:getFormat()
local resolution = math.ceil(cube:getWidth() / self.reflection_downsample)
--create canvases if needed
blurCanvases[f] = blurCanvases[f] or { }
if not blurCanvases[f][resolution] then
blurCanvases[f][resolution] = { }
end
if not blurCanvases[f][resolution][level] then
local size = math.ceil(resolution / math.max(1, 2^(level-1)))
blurCanvases[f][resolution][level] = love.graphics.newCanvas(size, size, {format = f, readable = true, msaa = 0, type = "2d", mipmaps = "none"})
end
--blurring
love.graphics.push("all")
love.graphics.reset()
love.graphics.setBlendMode("replace", "premultiplied")
local can = blurCanvases[f][resolution][level]
local res = can:getWidth()
for side = 1, 6 do
love.graphics.setCanvas(can)
love.graphics.setShader(self.shaders.blur_cube)
self.shaders.blur_cube:send("tex", cube)
self.shaders.blur_cube:send("strength", 0.025)
self.shaders.blur_cube:send("scale", 1.0 / res)
self.shaders.blur_cube:send("normal", blurVecs[side][1])
self.shaders.blur_cube:send("dirX", blurVecs[side][2])
self.shaders.blur_cube:send("dirY", blurVecs[side][3])
self.shaders.blur_cube:send("lod", level - 2.0)
love.graphics.rectangle("fill", 0, 0, res, res)
--paste
love.graphics.setCanvas(cube, side, level)
love.graphics.setShader()
love.graphics.draw(can, 0, 0, 0, self.reflection_downsample)
end
love.graphics.pop()
end
local lastSkyTex
function lib.executeJobs(self, cam)
local t = love.timer.getTime()
local dt = love.timer.getDelta()
local timeAvailable = 5.0 / 1000
local operations = { }
--re render sky cube
if self.sky_as_reflection then
local changes = false
local tex = self.sky_cube or self.sky_hdri
if tex then
if self.sky_refreshRateTexture > 0 and t - (times["sky"] or 0) > self.sky_refreshRateTexture or tostring(tex) ~= lastSkyTexID then
changes = true
lastSkyTexID = tostring(tex)
end
else
if self.sky_refreshRate > 0 and t - (times["sky"] or 0) > self.sky_refreshRate or self.sky_refreshRate == 0 and not times["sky"] then
changes = true
end
end
if changes then
operations[#operations+1] = {"sky", 1.0}
end
--blur sky reflection cubemap
for level = 2, self.reflections_levels do
local id = "cubemap_sky" .. level
local time = times[id]
if (times["sky"] or 0) > (time or 0) then
operations[#operations+1] = {"cubemap", time and (1.0 / level) or 1.0, id, self.defaultReflection, level}
break
end
end
end
--re check exposure
if self.autoExposure_enabled and (t - (times["autoExposure"] or 0)) > self.autoExposure_interval then
operations[#operations+1] = {"autoExposure", 0.25}
end
--modules
for d,s in pairs(self.allActiveShaderModules) do
if s.jobCreator then
s:jobCreator(self, operations, cam)
end
end
--shadows
for d,s in ipairs(self.lighting) do
if s.shadow and s.active then
if s.shadow.typ == "sun" then
local pos = vec3(s.x, s.y, s.z):normalize()
for cascade = 1, 3 do
if not s.shadow.static or not s.shadow.done[cascade] then
local id = "shadow_sun_" .. tostring(s.shadow) .. tostring(cascade)
operations[#operations+1] = {"shadow_sun", 1.0 / 2^cascade, id, s, pos, cascade}
end
end
elseif s.shadow.typ == "point" then
local pos = vec3(s.x, s.y, s.z)
local dist = (pos - cam.pos):length() / 10.0 + 1.0
if not s.shadow.static or not s.shadow.done[1] then
local id = "shadow_point_" .. tostring(s.shadow)
operations[#operations+1] = {"shadow_point", s.shadow.priority / dist, id, s, pos}
end
end
end
end
--reflections
for reflection, task in pairs(self.reflections_last) do
--render reflections
for face = 1, 6 do
if not reflection.static or not reflection.done[face] then
local id = "reflections_" .. (reflection.id + face)
operations[#operations+1] = {"reflections", reflection.priority / (task.dist / 10 + 1), id, task.obj, task.pos, face}
end
end
--blur mipmaps
for level = 2, self.reflections_levels do
local id_blur = "cubemap_" .. (reflection.id + level)
if (times[id] or 0) > (times[id_blur] or 0) then
operations[#operations+1] = {"cubemap", times[id_blur] and (1.0 / level) or 1.0, id_blur, reflection.canvas, level}
break
end
end
end
--sort operations based on priority and time since last execution
table.sort(operations, function(a, b) return a[2] * (t - (times[a[3] or a[1]] or 0)) > b[2] * (t - (times[b[3] or b[1]] or 0)) end)
--debug
if _DEBUGMODE and love.keyboard.isDown("#") then
--measure the total priority, this is an approximation for the outstanding work
local total = 0
for d,s in ipairs(operations) do
total = total + (t - (times[s[3] or s[1]] or t))
end
--print approximate time requirement
print(string.format("%.2f ms behind, %d operations in queue, %.2f ms per step available", total * 1000, #operations, timeAvailable * 1000))
for d,s in pairs(timeRequirement) do
print(string.format("\t%s: %0.2f ms", d, s*1000))
end
--print execution per second
print("e/s:")
for d,s in pairs(executionsPerSecond) do
print(string.format("\t%s: %.2f/s", d, s))
end
--print execution per second
print("e total:")
for d,s in pairs(executions) do
print(string.format("\t%s: %d", d, s))
end
print("queue:")
for d,s in ipairs(operations) do
print(string.format("\t%s\tpriority: %.2f\tdelta: %.2f ms", s[1], s[2], (t - (times[s[3] or s[1]] or 0)) * 1000))
end
print()
os.exit()
end
--execute operations
while operations[1] do
local o = operations[1]
table.remove(operations, 1)
--remember time stamp
local delta = t - (times[o[3] or o[1]] or t)
times[o[3] or o[1]] = t
local time = love.timer.getTime()
if type(o[1]) == "function" then
o[1](o, delta)
elseif o[1] == "sky" then
love.graphics.push("all")
love.graphics.reset()
love.graphics.setDepthMode()
local pos = vec3(0.0, 0.0, 0.0)
local transformations = {
pointShadowProjectionMatrix * self:lookAt(pos, lookNormals[1], vec3(0, -1, 0)),
pointShadowProjectionMatrix * self:lookAt(pos, lookNormals[2], vec3(0, -1, 0)),
pointShadowProjectionMatrix * self:lookAt(pos, lookNormals[3], vec3(0, 0, -1)),
pointShadowProjectionMatrix * self:lookAt(pos, lookNormals[4], vec3(0, 0, 1)),
pointShadowProjectionMatrix * self:lookAt(pos, lookNormals[5], vec3(0, -1, 0)),
pointShadowProjectionMatrix * self:lookAt(pos, lookNormals[6], vec3(0, -1, 0)),
}
for side = 1, 6 do
love.graphics.setBlendMode("replace", "premultiplied")
love.graphics.setCanvas(self.defaultReflection, side)
love.graphics.clear(1.0, 1.0, 1.0)
love.graphics.setDepthMode()
self:renderSky(transformations[side])
end
love.graphics.pop()
elseif o[1] == "cubemap" then
self:blurCubeMap(o[4], o[5])
elseif o[1] == "autoExposure" then
love.graphics.push("all")
love.graphics.reset()
--vignette and downscale
local c = self.canvas_exposure
love.graphics.setCanvas(c)
love.graphics.setShader(self.shaders.autoExposure)
self.shaders.autoExposure:send("targetBrightness", self.autoExposure_targetBrightness)
love.graphics.draw(self.canvases.color, 0, 0, 0, c:getWidth() / self.canvases.width, c:getHeight() / self.canvases.height)
love.graphics.setShader()
--fetch
local f = self.autoExposure_adaptionSpeed * math.sqrt(self.autoExposure_interval)
love.graphics.setBlendMode("alpha")
love.graphics.setCanvas(self.canvas_exposure_fetch)
love.graphics.setColor(1, 0, 0, f)
love.graphics.draw(self.canvas_exposure, 0, 0, 0, 1 / self.autoExposure_resolution)
love.graphics.pop()
elseif o[1] == "shadow_sun" then
local cascade = o[6]
o[4].shadow.lastPos = o[5]
--create new canvases if necessary
if not o[4].shadow.canvases then
o[4].shadow.canvases = { }
end
--render
local r = self.shadow_distance / 2 * (self.shadow_factor ^ (cascade-1))
local t = self.shadow_distance / 2 * (self.shadow_factor ^ (cascade-1))
local l = -r
local b = -t
local n = 1.0
local f = 100
local projection = mat4(
2 / (r - l), 0, 0, -(r + l) / (r - l),
0, -2 / (t - b), 0, -(t + b) / (t - b),
0, 0, -2 / (f - n), -(f + n) / (f - n),
0, 0, 0, 1
)
local shadowCam = self:newCam()
shadowCam.noFrustumCheck = true
shadowCam.pos = cam.pos
shadowCam.normal = o[5]
shadowCam.transform = self:lookAt(cam.pos + shadowCam.normal * f * 0.5, cam.pos, vec3(0.0, 1.0, 0.0))
shadowCam.transformProj = projection * shadowCam.transform
local m = shadowCam.transform
shadowCam.transformProjOrigin = projection * mat4(m[1], m[2], m[3], 0.0, m[5], m[6], m[7], 0.0, m[9], m[10], m[11], 0.0, 0.0, 0.0, 0.0, 1.0)
o[4].shadow["transformation_" .. cascade] = shadowCam.transformProj
o[4].shadow.canvases[cascade] = o[4].shadow.canvases[cascade] or self:newShadowCanvas("sun", o[4].shadow.res)
local scene = self:buildScene(shadowCam, 1, o[4].blacklist)
self:renderShadows(scene, shadowCam, {depthstencil = o[4].shadow.canvases[cascade]})
o[4].shadow.done[cascade] = true
elseif o[1] == "shadow_point" then
local pos = o[5]
o[4].shadow.lastPos = pos
local transformations = {
self:lookAt(pos, pos + lookNormals[1], vec3(0, -1, 0)),
self:lookAt(pos, pos + lookNormals[2], vec3(0, -1, 0)),
self:lookAt(pos, pos + lookNormals[3], vec3(0, 0, -1)),
self:lookAt(pos, pos + lookNormals[4], vec3(0, 0, 1)),
self:lookAt(pos, pos + lookNormals[5], vec3(0, -1, 0)),
self:lookAt(pos, pos + lookNormals[6], vec3(0, -1, 0)),
}
--create new canvases if necessary
if not o[4].shadow.canvas then
time = love.timer.getTime()
o[4].shadow.canvas = self:newShadowCanvas("point", o[4].shadow.res)
end
--render
for face = 1, 6 do
local shadowCam = self:newCam(transformations[face], pointShadowProjectionMatrix, pos, lookNormals[face])
local scene = self:buildScene(shadowCam, 1, o[4].blacklist)
self:renderShadows(scene, shadowCam, {{o[4].shadow.canvas, face = face}})
end
o[4].shadow.done[1] = true
elseif o[1] == "reflections" then
local pos = o[5]
local face = o[6]
local transformations = {
self:lookAt(pos, pos + lookNormals[1], vec3(0, -1, 0)),
self:lookAt(pos, pos + lookNormals[2], vec3(0, -1, 0)),
self:lookAt(pos, pos + lookNormals[3], vec3(0, 0, -1)),
self:lookAt(pos, pos + lookNormals[4], vec3(0, 0, 1)),
self:lookAt(pos, pos + lookNormals[5], vec3(0, -1, 0)),
self:lookAt(pos, pos + lookNormals[6], vec3(0, -1, 0)),
}
--prepare
love.graphics.push("all")
love.graphics.reset()
local cam = self:newCam(transformations[face], pointShadowProjectionMatrix, pos, lookNormals[face])
local canvas = o[4].reflection.canvas
love.graphics.setCanvas({{canvas, face = face}})
o[4].reflection.canvas = nil
--render
lib:renderFull(cam, self.canvases_reflections, false, {[o[4]] = true})
o[4].reflection.canvas = canvas
love.graphics.pop()
o[4].reflection.done[face] = true
end
--executions per second
if delta > 0 then
local eps = 1 / delta
executionsPerSecond[o[1]] = (executionsPerSecond[o[1]] or eps) * 0.9 + eps * 0.1
end
--measure time to adjust
local delta = math.min(love.timer.getTime() - time, 1 / 10)
timeRequirement[o[1]] = (timeRequirement[o[1]] or delta) * 0.9 + delta * 0.1
executions[o[1]] = (executions[o[1]] or 0) + 1
--limit processing time
timeAvailable = timeAvailable - (timeRequirement[o[1]] or 1 / 1000)
if timeAvailable <= 0 then
break
end
end
local delta = love.timer.getTime() - t
self.jobRenderTime = self.jobRenderTime + delta
end
function lib:take3DScreenshot(pos, resolution)
resolution = resolution or 512
local canvases = self:newCanvasSet(resolution, resolution, 8, self.alphaBlendMode, false)
local results = love.graphics.newCanvas(resolution, resolution, {format = "rgba16f", type = "cube", mipmaps = "manual"})
--view matrices
local transformations = {
self:lookAt(pos, pos + lookNormals[1], vec3(0, -1, 0)),
self:lookAt(pos, pos + lookNormals[2], vec3(0, -1, 0)),
self:lookAt(pos, pos + lookNormals[3], vec3(0, 0, -1)),
self:lookAt(pos, pos + lookNormals[4], vec3(0, 0, 1)),
self:lookAt(pos, pos + lookNormals[5], vec3(0, -1, 0)),
self:lookAt(pos, pos + lookNormals[6], vec3(0, -1, 0)),
}
--render all faces
for face = 1, 6 do
love.graphics.push("all")
love.graphics.reset()
love.graphics.setCanvas({{results, face = face}})
love.graphics.clear()
--render
local cam = self:newCam(transformations[face], pointShadowProjectionMatrix, pos, lookNormals[face])
lib:renderFull(cam, canvases, false)
love.graphics.pop()
end
--blur cubemap
for level = 2, results:getMipmapCount() do
self:blurCubeMap(results, level)
end
--export mimg data
cimg:export(results, "results.cimg")
end
|
local sx, sy = guiGetScreenSize()
local sx = sx/1366
local sy = sy/768
local markers = getMarkersTable()
local jM2jN = {}
for k, v in ipairs (markers) do
-- Markers creation.
local jMarker = createMarker(v.x, v.y, v.z - 1, "cylinder", 1.5, v.r, v.g, v.b, 255)
jM2jN[jMarker] = k
end
addEventHandler("onClientRender", root,
function()
if (isElement(tempVeh)) then
dxDrawText("Vehicle Name: "..getVehicleName(tempVeh), sx*900 - 1, sy*397 - 1, sx*1362 - 1, sy*449 - 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Vehicle Name: "..getVehicleName(tempVeh), sx*900 + 1, sy*397 - 1, sx*1362 + 1, sy*449 - 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Vehicle Name: "..getVehicleName(tempVeh), sx*900 - 1, sy*397 + 1, sx*1362 - 1, sy*449 + 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Vehicle Name: "..getVehicleName(tempVeh), sx*900 + 1, sy*397 + 1, sx*1362 + 1, sy*449 + 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Vehicle Name: "..getVehicleName(tempVeh), sx*900, sy*397, sx*1362, sy*449, tocolor(255, 255, 255, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Max speed: "..math.floor(getVehicleHandling(tempVeh).maxVelocity/1.7), sx*900 - 1, sy*459 - 1, sx*1362 - 1, sy*511 - 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Max speed: "..math.floor(getVehicleHandling(tempVeh).maxVelocity/1.7), sx*900 + 1, sy*459 - 1, sx*1362 + 1, sy*511 - 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Max speed: "..math.floor(getVehicleHandling(tempVeh).maxVelocity/1.7), sx*900 - 1, sy*459 + 1, sx*1362 - 1, sy*511 + 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Max speed: "..math.floor(getVehicleHandling(tempVeh).maxVelocity/1.7), sx*900 + 1, sy*459 + 1, sx*1362 + 1, sy*511 + 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Max speed: "..math.floor(getVehicleHandling(tempVeh).maxVelocity/1.7), sx*900, sy*459, sx*1362, sy*511, tocolor(255, 255, 255, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Press backspace to close.", sx*900 - 1, sy*521 - 1, sx*1362 - 1, sy*573 - 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Press backspace to close.", sx*900 + 1, sy*521 - 1, sx*1362 + 1, sy*573 - 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Press backspace to close.", sx*900 - 1, sy*521 + 1, sx*1362 - 1, sy*573 + 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Press backspace to close.", sx*900 + 1, sy*521 + 1, sx*1362 + 1, sy*573 + 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Press backspace to close.", sx*900, sy*521, sx*1362, sy*573, tocolor(255, 255, 255, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Use left and right arrows to navigate.", sx*900 - 1, sy*583 - 1, sx*1362 - 1, sy*635 - 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Use left and right arrows to navigate.", sx*900 + 1, sy*583 - 1, sx*1362 + 1, sy*635 - 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Use left and right arrows to navigate.", sx*900 - 1, sy*583 + 1, sx*1362 - 1, sy*635 + 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Use left and right arrows to navigate.", sx*900 + 1, sy*583 + 1, sx*1362 + 1, sy*635 + 1, tocolor(0, 0, 0, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
dxDrawText("Use left and right arrows to navigate.", sx*900, sy*583, sx*1362, sy*635, tocolor(255, 255, 255, 255), 1.00, "pricedown", "left", "center", false, false, false, false, false)
end
end
)
function onHit(hElem, mDim)
if mDim and jM2jN[source] and (localPlayer == hElem) and (not getPedOccupiedVehicle(hElem)) and (isPedOnGround(localPlayer)) then
if (getElementData(localPlayer, "wantedPoints") > 20) then
exports.NGCdxmsg:createNewDxMessage("You cannot take free a vehicle if you are wanted!", 255, 255, 255)
return false end
currentMarker = source
setElementAlpha(source, 0)
local occupation = markers[jM2jN[source]].occupation
x, y, z = markers[jM2jN[source]].x, markers[jM2jN[source]].y, markers[jM2jN[source]].z
vehicles = markers[jM2jN[source]].vehicles
rx, ry, rz = markers[jM2jN[source]].rx, markers[jM2jN[source]].ry, markers[jM2jN[source]].rz
r, g, b = markers[jM2jN[source]].r, markers[jM2jN[source]].g, markers[jM2jN[source]].b
local cx, cy, cz = markers[jM2jN[source]].cx, markers[jM2jN[source]].cy, markers[jM2jN[source]].cz
if (occupation == "None") or (getElementData(getRandomPlayer(), "Occupation") == occupation) or (getPlayerTeam(localPlayer) and getTeamName(getPlayerTeam(localPlayer)) == "Staff") then
setCameraMatrix(cx, cy, cz, x, y, z)
tempVeh = createVehicle(getVehicleModelFromName(vehicles[1]), x, y, z+1.5, rx, ry, rz)
currentIndex = 1
setTimer(function()
setVehicleColor(tempVeh, r, g, b)
end, 400, 1)
setElementPosition(localPlayer, cx, cy, cz)
setElementFrozen(localPlayer, true)
guiSetInputMode("no_binds")
setElementFrozen(tempVeh, true)
end
end
end
addEventHandler("onClientMarkerHit", root, onHit)
function switchToNext(button, pressed)
if (isElement(tempVeh)) then
if (button == "arrow_r") and (pressed) then
if (currentIndex == #vehicles) then
currentIndex = 1
else
currentIndex = currentIndex + 1
end
setElementModel(tempVeh, getVehicleModelFromName(vehicles[currentIndex]))
end
if (button == "arrow_l") and (pressed) then
if (currentIndex == 1) then
currentIndex = #vehicles
else
currentIndex = currentIndex - 1
end
setElementModel(tempVeh, getVehicleModelFromName(vehicles[currentIndex]))
end
end
end
addEventHandler("onClientKey", root, switchToNext)
function spawnCar(button, pressed)
if (isElement(tempVeh)) then
if (button == "enter") and (pressed) then
local vehName = getVehicleName(tempVeh)
setPedAnimation(localPlayer, false)
destroyElement(tempVeh)
setElementAlpha(currentMarker, 255)
guiSetInputMode("allow_binds")
setCameraTarget(localPlayer)
triggerServerEvent("AURspawners.spawnMarkerCar", resourceRoot, localPlayer, vehName, x, y, z, rx, ry, rz, r, g, b)
end
if (button == "backspace") and (pressed) then
destroyElement(tempVeh)
guiSetInputMode("allow_binds")
setPedAnimation(localPlayer, false)
setElementAlpha(currentMarker, 255)
setCameraTarget(localPlayer)
setElementFrozen(localPlayer, false)
setElementPosition(localPlayer, x, y+2, z+1)
end
end
end
addEventHandler("onClientKey", root, spawnCar)
|
frame_count = 0
frames = {}
last_status = nil
function IPC_CreateFrames()
local size = 12
frame_count = math.floor(GetScreenWidth() / size)
-- print("Max bytes that can be stored: " .. (frame_count * 3) - 1)
for i=1, frame_count do
frames[i] = CreateFrame("Frame", nil, UIParent)
frames[i]:SetFrameStrata("TOOLTIP")
frames[i]:SetWidth(size)
frames[i]:SetHeight(size)
-- initialise it as black
local t = frames[i]:CreateTexture(nil, "TOOLTIP")
t:SetTexture(0, 0, 0, 0)
t:SetAllPoints(frames[i])
frames[i].texture = t
frames[i]:SetPoint("TOPLEFT", (i - 1) * size, 0)
frames[i]:Show()
end
return frames
end
function IPC_PaintFrame(frame, r, g, b, force)
-- turn them into black if they are null
if r == nil then r = 0 end
if g == nil then g = 0 end
if b == nil then b = 0 end
-- from 0-255 to 0.0-1.0
r = r / 255
g = g / 255
b = b / 255
-- set alpha to 1 if this pixel is black and force is 0 or null
if r == 0 and g == 0 and b == 0 and (force == 0 or force == nil) then a = 0 else a = 1 end
-- and now paint it
frame.texture:SetTexture(r, g, b, a)
frame.texture:SetAllPoints(frame)
end
function IPC_CleanFrames()
for i=1, frame_count do
IPC_PaintFrame(frames[i], 0, 0, 0, 0)
end
end
function IPC_PaintSomething(text)
local max_bytes = (frame_count - 1) * 3
if text:len() >= max_bytes then
-- print("You're painting too many bytes (" .. #text .. " vs " .. max_bytes .. ")")
return
end
-- clean all
IPC_CleanFrames()
local squares_painted = 0
for trio in text:gmatch".?.?.?" do
r = 0; g = 0; b = 0
r = string.byte(trio:sub(1,1))
if #trio > 1 then g = string.byte(trio:sub(2,2)) end
if #trio > 2 then b = string.byte(trio:sub(3,3)) end
squares_painted = squares_painted + 1
IPC_PaintFrame(frames[squares_painted], r, g, b)
end
-- and then paint the last one black
IPC_PaintFrame(frames[squares_painted], 0, 0, 0, 1)
end
function GetContinentName(continentID)
-- this is here because it doesn't exist in wotlk. if you are porting this
-- to retail you'll just have to remove this whole function.
if continentID == 1 then
return 'Kalimdor'
elseif continentID == 2 then
return 'Eastern Kingdoms'
elseif continentID == 3 then
return 'Outland'
elseif continentID == 4 then
return 'Northrend'
end
end
function IPC_EncodeZoneType()
local name, type, difficultyIndex, difficultyName, maxPlayers,
dynamicDifficulty, isDynamic, instanceMapId, lfgID = GetInstanceInfo()
local zone_name = GetRealZoneText()
if type == 'party' then
status = 'In Dungeon'
elseif type == 'raid' then
status = 'In Raid'
elseif type == 'pvp' then
status = 'In Battleground'
else
if UnitIsDeadOrGhost("player") and not UnitIsDead("player") then
status = "Corpse running"
-- if the world map is open we can't rely on it so send the last status
-- or something generic if we've never seen a status
elseif WorldMapFrame:IsVisible() then
if last_status == nil then
status = "In the overworld"
else
status = last_status
end
else
local continent_name = GetContinentName(GetCurrentMapContinent())
if continent_name then
status = continent_name
last_status = status
else
status = "In the overworld"
end
end
end
if zone_name == "" or zone_name == nil then return nil end
local encoded = "$WorldOfWarcraftIPC$" .. zone_name .. "|" .. status .. "$WorldOfWarcraftIPC$"
return encoded
end
-- received addon events.
function IPC_OnEvent(event, ...)
if event == "PLAYER_LOGIN" then
IPC_CreateFrames()
elseif event == "PLAYER_LOGIN" or event == "ZONE_CHANGED_NEW_AREA" or event == "WORLD_MAP_UPDATE" then
local encoded = IPC_EncodeZoneType()
if encoded ~= nil then IPC_PaintSomething(encoded) end
end
end
function IPC_OnLoad()
IPCFrame:RegisterEvent("PLAYER_LOGIN")
IPCFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
IPCFrame:RegisterEvent("ZONE_CHANGED_NEW_AREA")
IPCFrame:RegisterEvent("WORLD_MAP_UPDATE")
SlashCmdList["IPC"] = IPC_PaintSomething
SLASH_IPC1 = "/ipc"
SlashCmdList["CLEAN"] = IPC_CleanFrames
SLASH_CLEAN1 = "/clean"
end
|
object_tangible_item_beast_converted_verne_decoration = object_tangible_item_beast_shared_converted_verne_decoration:new {
}
ObjectTemplates:addTemplate(object_tangible_item_beast_converted_verne_decoration, "object/tangible/item/beast/converted_verne_decoration.iff")
|
#!/usr/bin/lua
local font = dofile(arg[1])
local lookUp = { string.byte(string.rep("\0", 256), 1, -1) }
local fontTable = ""
-- print("--[[")
local maxIndex = 0
for i,v in pairs(font) do
local pos = fontTable:len()
lookUp[i+1] = pos
if i > maxIndex then
maxIndex = i
end
-- print(i, string.char(i), pos, #v)
local l = { string.char(#v) }
for _,b in ipairs({v:byte(1, -1)}) do
-- print("", b)
table.insert( l, string.char(b))
end
local buf = table.concat(l, "")
fontTable = fontTable .. buf
end
local struct = require("struct")
local lookUpString = ""
for i=1,maxIndex do
lookUpString = lookUpString .. struct.pack("H", lookUp[i])
end
-- print "]]\n"
io.write("return {\n\"")
for _,b in ipairs({lookUpString:byte(1, -1)}) do
io.write(string.format([[\%d]], b))
end
io.write("\",\n\"")
for _,b in ipairs({fontTable:byte(1, -1)}) do
io.write(string.format([[\%d]], b))
end
io.write("\"\n}")
-- io.write("return { [[")
-- io.write(lookUpString)
-- io.write("]],\n[[")
-- io.write(fontTable)
-- io.write("]]\n}")
|
local M = {}
local lsputils = require "config.lsp.utils"
function M.config(installed_server)
return {
-- https://github.com/golang/tools/blob/master/gopls/doc/settings.md
experimentalPostfixCompletions = true,
analyses = { unusedparams = true, unreachable = false },
codelenses = { generate = true, gc_details = true, test = true, tidy = true },
usePlaceholders = true,
completeUnimported = true,
staticcheck = true,
matcher = "fuzzy",
experimentalDiagnosticsDelay = "500ms",
symbolMatcher = "fuzzy",
gofumpt = true,
buildFlags = { "-tags", "integration" },
capabilities = lsputils.get_capabilities(),
on_attach = lsputils.lsp_attach,
on_init = lsputils.lsp_init,
on_exit = lsputils.lsp_exit,
flags = { debounce_text_changes = 150 },
}
end
function M.setup(installed_server)
return M.config(installed_server)
end
return M
|
---@class CS.FairyEditor.DragDropManager
---@field public agent CS.FairyGUI.GObject
---@field public dragging boolean
---@type CS.FairyEditor.DragDropManager
CS.FairyEditor.DragDropManager = { }
---@return CS.FairyEditor.DragDropManager
function CS.FairyEditor.DragDropManager.New() end
---@param source CS.FairyGUI.GObject
---@param sourceData CS.System.Object
---@param icon CS.System.Object
---@param cursor string
---@param onComplete (fun(arg1:CS.FairyGUI.GObject, arg2:CS.System.Object):void)
---@param onCancel (fun(arg1:CS.FairyGUI.GObject, arg2:CS.System.Object):void)
---@param onMove (fun(arg1:CS.FairyGUI.GObject, arg2:CS.System.Object, arg3:CS.FairyGUI.EventContext):void)
function CS.FairyEditor.DragDropManager:StartDrag(source, sourceData, icon, cursor, onComplete, onCancel, onMove) end
function CS.FairyEditor.DragDropManager:Cancel() end
return CS.FairyEditor.DragDropManager
|
DefineClass.DustGenerator =
{
__parents = { "Building" },
properties =
{
{id = "dust_per_sol", name = T{653, "Dust per Sol"}, editor = "number", default = 6000, category = "Dust Generator" },
{id = "dust_range", name = T{654, "Dust Range"}, editor = "number", default = 70 * guim, category = "Dust Generator" },
},
last_dust_throw_time = false,
}
function DustGenerator:GameInit()
self.last_dust_throw_time = GameTime()
end
local hour_duration = const.HourDuration
local sol_duration = const.DayDuration
local dust_generator_query =
{
class = "Building",
area = false,
arearadius = false,
exec = function(bld, dust)
if bld.accumulate_dust then
bld:AddDust(dust)
end
end,
}
local dust_generator_elements_query =
{
class = "DustGridElement",
area = false,
arearadius = false,
exec = function (obj, dust)
obj:AddDust(dust)
end,
}
function DustGenerator:ThrowDust()
if not self.working then
return
end
local time = GameTime() - self.last_dust_throw_time
if time > hour_duration then
local dust = MulDivTrunc(self.dust_per_sol, time, sol_duration)
if dust > 0 then -- allow dust to accumulate if update time is small and always leads to 0 dust
dust_generator_query.area = self
dust_generator_query.arearadius = self.dust_range
ForEach(dust_generator_query, dust)
dust_generator_query.area = false
dust_generator_elements_query.area = self
dust_generator_elements_query.arearadius = self.dust_range
ForEach(dust_generator_elements_query, dust)
dust_generator_elements_query.area = false
self.last_dust_throw_time = GameTime()
end
end
end
|
cc = cc or {}
---PhysicsBody object
---@class PhysicsBody : Component
local PhysicsBody = {}
cc.PhysicsBody = PhysicsBody
--------------------------------
--- Whether this physics body is affected by the physics world's gravitational force.
---@return bool
function PhysicsBody:isGravityEnabled() end
--------------------------------
---reset all the force applied to body.
---@return PhysicsBody
function PhysicsBody:resetForces() end
--------------------------------
--- get the max of velocity
---@return float
function PhysicsBody:getVelocityLimit() end
--------------------------------
---Set the group of body.<br>
---Collision groups let you specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index).<br>
---It have high priority than bit masks.
---@param group int
---@return PhysicsBody
function PhysicsBody:setGroup(group) end
--------------------------------
--- Get the body mass.
---@return float
function PhysicsBody:getMass() end
--------------------------------
---Return bitmask of first shape.<br>
---return If there is no shape in body, return default value.(0xFFFFFFFF)
---@return int
function PhysicsBody:getCollisionBitmask() end
--------------------------------
--- set the body rotation offset
---@return float
function PhysicsBody:getRotationOffset() end
--------------------------------
--- get the body rotation.
---@return float
function PhysicsBody:getRotation() end
--------------------------------
--- Get the body moment of inertia.
---@return float
function PhysicsBody:getMoment() end
--------------------------------
---Applies a immediate force to body.<br>
---param impulse The impulse is applies to this body.<br>
---param offset A Vec2 object, it is the offset from the body's center of gravity in world coordinates.
---@param impulse vec2_table
---@param offset vec2_table
---@return PhysicsBody
function PhysicsBody:applyImpulse(impulse, offset) end
--------------------------------
--- set body rotation offset, it's the rotation witch relative to node
---@param rotation float
---@return PhysicsBody
function PhysicsBody:setRotationOffset(rotation) end
--------------------------------
---Applies a continuous force to body.<br>
---param force The force is applies to this body.<br>
---param offset A Vec2 object, it is the offset from the body's center of gravity in world coordinates.
---@param force vec2_table
---@param offset vec2_table
---@return PhysicsBody
function PhysicsBody:applyForce(force, offset) end
--------------------------------
---brief Add a shape to body.<br>
---param shape The shape to be added.<br>
---param addMassAndMoment If this is true, the shape's mass and moment will be added to body. The default is true.<br>
---return This shape's pointer if added success or nullptr if failed.
---@param shape PhysicsShape
---@param addMassAndMoment bool
---@return PhysicsShape
function PhysicsBody:addShape(shape, addMassAndMoment) end
--------------------------------
---Applies a torque force to body.<br>
---param torque The torque is applies to this body.
---@param torque float
---@return PhysicsBody
function PhysicsBody:applyTorque(torque) end
--------------------------------
--- get the max of angular velocity
---@return float
function PhysicsBody:getAngularVelocityLimit() end
--------------------------------
--- set the max of angular velocity
---@param limit float
---@return PhysicsBody
function PhysicsBody:setAngularVelocityLimit(limit) end
--------------------------------
--- Get the velocity of a body.
---@return vec2_table
function PhysicsBody:getVelocity() end
--------------------------------
--- get linear damping.
---@return float
function PhysicsBody:getLinearDamping() end
--------------------------------
---Remove all shapes.<br>
---param reduceMassAndMoment If this is true, the body mass and moment will be reduced by shape. The default is true.
---@return PhysicsBody
function PhysicsBody:removeAllShapes() end
--------------------------------
---Set angular damping.<br>
---It is used to simulate fluid or air friction forces on the body.<br>
---param damping The value is 0.0f to 1.0f.
---@param damping float
---@return PhysicsBody
function PhysicsBody:setAngularDamping(damping) end
--------------------------------
--- set the max of velocity
---@param limit float
---@return PhysicsBody
function PhysicsBody:setVelocityLimit(limit) end
--------------------------------
--- set body to rest
---@param rest bool
---@return PhysicsBody
function PhysicsBody:setResting(rest) end
--------------------------------
--- get body position offset.
---@return vec2_table
function PhysicsBody:getPositionOffset() end
--------------------------------
---A mask that defines which categories this physics body belongs to.<br>
---Every physics body in a scene can be assigned to up to 32 different categories, each corresponding to a bit in the bit mask. You define the mask values used in your game. In conjunction with the collisionBitMask and contactTestBitMask properties, you define which physics bodies interact with each other and when your game is notified of these interactions.<br>
---param bitmask An integer number, the default value is 0xFFFFFFFF (all bits set).
---@param bitmask int
---@return PhysicsBody
function PhysicsBody:setCategoryBitmask(bitmask) end
--------------------------------
--- get the world body added to.
---@return PhysicsWorld
function PhysicsBody:getWorld() end
--------------------------------
--- get the angular velocity of a body
---@return float
function PhysicsBody:getAngularVelocity() end
--------------------------------
--- get the body position.
---@return vec2_table
function PhysicsBody:getPosition() end
--------------------------------
--- Set the body is affected by the physics world's gravitational force or not.
---@param enable bool
---@return PhysicsBody
function PhysicsBody:setGravityEnable(enable) end
--------------------------------
---Return group of first shape.<br>
---return If there is no shape in body, return default value.(0)
---@return int
function PhysicsBody:getGroup() end
--------------------------------
---brief Set the body moment of inertia.<br>
---note If you need add/subtract moment to body, don't use setMoment(getMoment() +/- moment), because the moment of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMoment() instead.
---@param moment float
---@return PhysicsBody
function PhysicsBody:setMoment(moment) end
--------------------------------
--- Get the body's tag.
---@return int
function PhysicsBody:getTag() end
--------------------------------
--- Convert the local point to world.
---@param point vec2_table
---@return vec2_table
function PhysicsBody:local2World(point) end
--------------------------------
---Return bitmask of first shape.<br>
---return If there is no shape in body, return default value.(0xFFFFFFFF)
---@return int
function PhysicsBody:getCategoryBitmask() end
--------------------------------
---brief Set dynamic to body.<br>
---A dynamic body will effect with gravity.
---@param dynamic bool
---@return PhysicsBody
function PhysicsBody:setDynamic(dynamic) end
--------------------------------
---Get the first shape of the body shapes.<br>
---return The first shape in this body.
---@return PhysicsShape
function PhysicsBody:getFirstShape() end
--------------------------------
---Get the body shapes.<br>
---return A Vector<PhysicsShape*> object contains PhysicsShape pointer.
---@return array_table
function PhysicsBody:getShapes() end
--------------------------------
---Return bitmask of first shape.<br>
---return If there is no shape in body, return default value.(0x00000000)
---@return int
function PhysicsBody:getContactTestBitmask() end
--------------------------------
---Set the angular velocity of a body.<br>
---param velocity The angular velocity is set to this body.
---@param velocity float
---@return PhysicsBody
function PhysicsBody:setAngularVelocity(velocity) end
--------------------------------
--- Convert the world point to local.
---@param point vec2_table
---@return vec2_table
function PhysicsBody:world2Local(point) end
--------------------------------
---@overload fun(int, bool:bool):PhysicsBody
---@overload fun(PhysicsShape, bool:bool):PhysicsBody
---@param shape PhysicsShape
---@param reduceMassAndMoment bool
---@return PhysicsBody
function PhysicsBody:removeShape(shape, reduceMassAndMoment) end
--------------------------------
---brief Set the body mass.<br>
---attention If you need add/subtract mass to body, don't use setMass(getMass() +/- mass), because the mass of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMass() instead.
---@param mass float
---@return PhysicsBody
function PhysicsBody:setMass(mass) end
--------------------------------
---brief Add moment of inertia to body.<br>
---param moment If _moment(moment of the body) == PHYSICS_INFINITY, it remains.<br>
---if moment == PHYSICS_INFINITY, _moment will be PHYSICS_INFINITY.<br>
---if moment == -PHYSICS_INFINITY, _moment will not change.<br>
---if moment + _moment <= 0, _moment will equal to MASS_DEFAULT(1.0)<br>
---other wise, moment = moment + _moment;
---@param moment float
---@return PhysicsBody
function PhysicsBody:addMoment(moment) end
--------------------------------
---Set the velocity of a body.<br>
---param velocity The velocity is set to this body.
---@param velocity vec2_table
---@return PhysicsBody
function PhysicsBody:setVelocity(velocity) end
--------------------------------
---Set linear damping.<br>
---it is used to simulate fluid or air friction forces on the body.<br>
---param damping The value is 0.0f to 1.0f.
---@param damping float
---@return PhysicsBody
function PhysicsBody:setLinearDamping(damping) end
--------------------------------
---A mask that defines which categories of physics bodies can collide with this physics body.<br>
---When two physics bodies contact each other, a collision may occur. This body's collision mask is compared to the other body's category mask by performing a logical AND operation. If the result is a non-zero value, then this body is affected by the collision. Each body independently chooses whether it wants to be affected by the other body. For example, you might use this to avoid collision calculations that would make negligible changes to a body's velocity.<br>
---param bitmask An integer number, the default value is 0xFFFFFFFF (all bits set).
---@param bitmask int
---@return PhysicsBody
function PhysicsBody:setCollisionBitmask(bitmask) end
--------------------------------
--- set body position offset, it's the position witch relative to node
---@param position vec2_table
---@return PhysicsBody
function PhysicsBody:setPositionOffset(position) end
--------------------------------
--- Set the body is allow rotation or not
---@param enable bool
---@return PhysicsBody
function PhysicsBody:setRotationEnable(enable) end
--------------------------------
--- Whether the body can rotation.
---@return bool
function PhysicsBody:isRotationEnabled() end
--------------------------------
--- Get the rigid body of chipmunk.
---@return cpBody
function PhysicsBody:getCPBody() end
--------------------------------
--- Get angular damping.
---@return float
function PhysicsBody:getAngularDamping() end
--------------------------------
--- Get the angular velocity of a body at a local point.
---@param point vec2_table
---@return vec2_table
function PhysicsBody:getVelocityAtLocalPoint(point) end
--------------------------------
--- Whether the body is at rest.
---@return bool
function PhysicsBody:isResting() end
--------------------------------
---brief Add mass to body.<br>
---param mass If _mass(mass of the body) == PHYSICS_INFINITY, it remains.<br>
---if mass == PHYSICS_INFINITY, _mass will be PHYSICS_INFINITY.<br>
---if mass == -PHYSICS_INFINITY, _mass will not change.<br>
---if mass + _mass <= 0, _mass will equal to MASS_DEFAULT(1.0)<br>
---other wise, mass = mass + _mass;
---@param mass float
---@return PhysicsBody
function PhysicsBody:addMass(mass) end
--------------------------------
---get the shape of the body.<br>
---param tag An integer number that identifies a PhysicsShape object.<br>
---return A PhysicsShape object pointer or nullptr if no shapes were found.
---@param tag int
---@return PhysicsShape
function PhysicsBody:getShape(tag) end
--------------------------------
--- set the body's tag.
---@param tag int
---@return PhysicsBody
function PhysicsBody:setTag(tag) end
--------------------------------
--- get the angular velocity of a body at a world point
---@param point vec2_table
---@return vec2_table
function PhysicsBody:getVelocityAtWorldPoint(point) end
--------------------------------
---A mask that defines which categories of bodies cause intersection notifications with this physics body.<br>
---When two bodies share the same space, each body's category mask is tested against the other body's contact mask by performing a logical AND operation. If either comparison results in a non-zero value, an PhysicsContact object is created and passed to the physics world’s delegate. For best performance, only set bits in the contacts mask for interactions you are interested in.<br>
---param bitmask An integer number, the default value is 0x00000000 (all bits cleared).
---@param bitmask int
---@return PhysicsBody
function PhysicsBody:setContactTestBitmask(bitmask) end
--------------------------------
--- remove the body from the world it added to
---@return PhysicsBody
function PhysicsBody:removeFromWorld() end
--------------------------------
---brief Test the body is dynamic or not.<br>
---A dynamic body will effect with gravity.
---@return bool
function PhysicsBody:isDynamic() end
--------------------------------
--- get the node the body set to.
---@return Node
function PhysicsBody:getNode() end
--------------------------------
---Create a body contains a box shape.<br>
---param size Size contains this box's width and height.<br>
---param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.<br>
---param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.<br>
---return An autoreleased PhysicsBody object pointer.
---@param size
---@param material PhysicsMaterial
---@param offset vec2_table
---@return PhysicsBody
function PhysicsBody:createBox(size, material, offset) end
--------------------------------
---Create a body contains a EdgeSegment shape.<br>
---param a It's the edge's begin position.<br>
---param b It's the edge's end position.<br>
---param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.<br>
---param border It's a edge's border width.<br>
---return An autoreleased PhysicsBody object pointer.
---@param a vec2_t
---@param b vec2_ta
---@param material PhysicsMaterial
---@param border float
---@return PhysicsBody
function PhysicsBody:createEdgeSegment(a, b, material, border) end
--------------------------------
---@overload fun(float):PhysicsBody
---@overload fun():PhysicsBody
---@overload fun(float, float):PhysicsBody
---@param mass float
---@param moment float
---@return PhysicsBody
function PhysicsBody:create(mass, moment) end
--------------------------------
---Create a body contains a EdgeBox shape.<br>
---param size Size contains this box's width and height.<br>
---param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.<br>
---param border It's a edge's border width.<br>
---param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.<br>
---return An autoreleased PhysicsBody object pointer.
---@param size
---@param material PhysicsMaterial
---@param border float
---@param offset vec2_table
---@return PhysicsBody
function PhysicsBody:createEdgeBox(size, material, border, offset) end
--------------------------------
---Create a body contains a circle.<br>
---param radius A float number, it is the circle's radius.<br>
---param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.<br>
---param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.<br>
---return An autoreleased PhysicsBody object pointer.
---@param radius float
---@param material PhysicsMaterial
---@param offset vec2_table
---@return PhysicsBody
function PhysicsBody:createCircle(radius, material, offset) end
--------------------------------
---Set the enable value.<br>
---If the body it isn't enabled, it will not has simulation by world.
---@param enable bool
---@return PhysicsBody
function PhysicsBody:setEnabled(enable) end
--------------------------------
--
---@return PhysicsBody
function PhysicsBody:onRemove() end
--------------------------------
--
---@return PhysicsBody
function PhysicsBody:onEnter() end
--------------------------------
--
---@return PhysicsBody
function PhysicsBody:onExit() end
--------------------------------
--
---@return PhysicsBody
function PhysicsBody:onAdd() end
return PhysicsBody
|
-- misc utilities
function clone_list(tensor_list, zero_too)
-- utility function. todo: move away to some utils file?
-- takes a list of tensors and returns a list of cloned tensors
local out = {}
for k,v in pairs(tensor_list) do
out[k] = v:clone()
if zero_too then out[k]:zero() end
end
return out
end
|
--[[--------------------------------------------------------------------------
--
-- File: UAStalktheLantern.State.RoundLoop.lua
-- Copyright (c) Ubisoft Entertainment. All rights reserved.
--
-- Project: Ubitoys.Tag
-- Date: November 25, 2010
--
------------------------------------------------------------------------------
--
-- Description: ...
--
----------------------------------------------------------------------------]]
--[[ Dependencies ----------------------------------------------------------]]
require "UTActivity.State.RoundLoop"
require "UAStalktheLantern.Ui.RoundLoop"
--[[ Class -----------------------------------------------------------------]]
UAStalktheLantern.State.RoundLoop = UTClass(UTActivity.State.RoundLoop)
-- defaults ------------------------------------------------------------------
UAStalktheLantern.State.RoundLoop.uiClass = UAStalktheLantern.Ui.RoundLoop
-- __ctor --------------------------------------------------------------------
function UAStalktheLantern.State.RoundLoop:__ctor(activity, ...)
-- timer
self.time = quartz.system.time.gettimemicroseconds()
activity.timer = 0
assert(activity)
end
-- Begin ---------------------------------------------------------------------
function UAStalktheLantern.State.RoundLoop:Begin()
UTActivity.State.RoundLoop.Begin(self)
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_13.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_14.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_15.wav"}, probas = {0.8, 0.1, 0.1}})
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_32.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_33.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_34.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_35.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_125.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_126.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_132.wav",}, priority = 4 })
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_45.wav"},offset = activity.settings.playtime * 60 - 60,})
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_48.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_49.wav"},
offset = activity.settings.playtime * 60 - 57, priority = 3, proba = 0.333})
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_46.wav"},
offset = activity.settings.playtime * 60 - 30,})
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_48.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_49.wav"},
offset = activity.settings.playtime * 60 - 27,priority = 3, proba = 0.333})
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_47.wav"},
offset = activity.settings.playtime * 60 - 15,})
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_48.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_49.wav"},
offset = activity.settings.playtime * 60 - 12, priority = 3, proba = 0.333})
-- timer
self.time = quartz.system.time.gettimemicroseconds()
self.shootCount = 0
self.shootCountTime = self.time
activity.timer = activity.settings.playtime * 60 * 1000000
game.gameplayData = { 0x00, 0x00 }
end
-- Message received from device -----------------------------------------------------------------------
function UAStalktheLantern.State.RoundLoop:OnDispatchMessage(device, addressee, command, arg)
-- base
UTActivity.State.RoundLoop.OnDispatchMessage(self)
if (0x95 == command) then
-- decode this msg !!
local gunseconds = (arg[8] * 256) + arg[9]
if (gunseconds ~= device.owner.data.heap.gunseconds or gunseconds == 0 or device.owner.data.heap.lifePoints == 0) then
device.owner.data.heap.guntime = quartz.system.time.gettimemicroseconds()
device.owner.vestconnect = false
if (gunseconds == 0) then
device.owner.gameplayData[2] = 0
end
elseif (device.owner.data.heap.guntime + 5000000 < quartz.system.time.gettimemicroseconds() and game.settings.GameSettings.vestdisconnect == 0 and not device.timedout) then
device.owner.gameplayData[2] = 7
end
if (device.owner.data.heap.guntime + 1000000 < quartz.system.time.gettimemicroseconds()) then
device.owner.vestconnect = true
end
if (device.owner.secondary) then
if (device.owner.data.heap.guntime + 900000 < quartz.system.time.gettimemicroseconds() or device.owner.data.heap.lifePoints == 0) then
device.owner.secondary.gameplayData[2] = 7
elseif (device.owner.gameplayData[2] ~= 7) then
device.owner.secondary.gameplayData[2] = 6
end
end
device.owner.data.heap.gunseconds = gunseconds
if (device.rejoin) then
if ((arg[2] * 256) + arg[3] > 0) then
device.rejoin = false
end
end
if (device.owner and not device.rejoin) then
-- ammunitions and clip
local ammunitions = (arg[4] * 256) + arg[5]
if (ammunitions == 3) then
if (game.settings.audio.gmtalkative == 1) then
-- throw "We need Ammo! Now" sound
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_22.wav","base:audio/gamemaster/DLG_GM_GLOBAL_23.wav"},priority = 3,})
end
end
local clips = (arg[6] * 256) + arg[7]
if (0 == device.owner.data.heap.isDead) then
if ((device.owner.defender or not device.owner.defender and activity.settings.ammunitionsStalker < 255) and (device.owner.data.heap.ammunitions < ammunitions and device.owner.data.heap.clips <= clips or device.owner.data.heap.clips < clips)) then
device.owner.data.heap.nbAmmoPack = device.owner.data.heap.nbAmmoPack + 1
activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame006", UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Ammunition.tga")
elseif (device.owner.data.heap.ammunitions > ammunitions) then
device.owner.data.heap.nbShot = device.owner.data.heap.nbShot + (device.owner.data.heap.ammunitions - ammunitions)
device.owner.data.heap.hitLost = device.owner.data.heap.hitLost + 1
if (device.owner.data.heap.hitLost == 5) then
if (game.settings.audio.gmtalkative == 1) then
-- throw "T'es aveugle" sound
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_43.wav","base:audio/gamemaster/DLG_GM_GLOBAL_44.wav"},priority = 2,})
end
device.owner.data.heap.hitLost = 0
end
if (device.owner.data.heap.hitLost >= 2) then
device.owner.data.nbHitLastPlayerShooted = 0
end
end
end
device.owner.data.heap.clips = clips
device.owner.data.heap.ammunitions = ammunitions
if (not device.owner.defender and activity.settings.ammunitionsStalker == 255) then
device.owner.data.heap.ammunitionsAndClips = "-/-"
else
device.owner.data.heap.ammunitionsAndClips = device.owner.data.heap.ammunitions .. "/" .. device.owner.data.heap.clips
end
-- data
local lifePoints = (arg[2] * 256) + arg[3]
if (device.owner.primary) then
lifePoints = device.owner.primary.data.heap.lifePoints
end
if (lifePoints == 1) then
if (game.settings.audio.gmtalkative == 1) then
-- throw "Mediiiic!" sound
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_18.wav","base:audio/gamemaster/DLG_GM_GLOBAL_19.wav"},priority = 3,})
end
end
-- check if I have been shot ...
if (device.owner.data.heap.lifePoints > lifePoints) then
if (self.shootCount) then
self.shootCount = self.shootCount + 1
if (self.shootCount == 10) then
local time = quartz.system.time.gettimemicroseconds()
if (time - self.shootCountTime < 10 * 1000000) then
if (game.settings.audio.gmtalkative == 1) then
-- ouais jsuis a donf
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_24.wav","base:audio/gamemaster/DLG_GM_GLOBAL_25.wav",}, priority = 2, proba = 0.25})
end
end
self.shootCountTime = time
self.shootCount = 0
end
end
end
local curIndex = math.max(0, device.owner.data.heap.lifePoints - lifePoints)
while (curIndex > 0) do
device.owner.data.heap.timeshit = device.owner.data.heap.timeshit + 1
-- get device that shot me
local shooterDevice = engine.libraries.usb.proxy.devices.byRadioProtocolId[arg[math.min(16, curIndex + 11)]]
curIndex = curIndex - 1
if (shooterDevice and shooterDevice.owner and shooterDevice.owner.primary ~= device.owner and device.owner.primary ~= shooterDevice.owner) then
-- get shooter
local shooter = shooterDevice.owner
if (shooterDevice.owner.primary) then
shooter = shooterDevice.owner.primary
end
if (0 == lifePoints and curIndex == 0) then
-- KILL ------------------------------------------------------
if (shooter.team ~= device.owner.team) then
activity.uiAFP:PushLine(shooter.profile.name .. " " .. l"ingame011" .. " " .. device.owner.profile.name, UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Death.tga")
shooter.data.heap.death = shooter.data.heap.death + 1
shooter.data.heap.killByName[device.owner.nameId] = (shooter.data.heap.killByName[device.owner.nameId] or 0) + 1
if (game.settings.audio.gmtalkative == 1) then
-- throw "Dans le mille!" sound
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_27.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_28.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_37.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_38.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_128.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_129.wav",
"base:audio/gamemaster/DLG_GM_GLOBAL_130.wav",
}, priority = 2,})
end
elseif (activity.settings.teamFrag == 1) then
activity.uiAFP:PushLine(shooter.profile.name .. " " .. l"ingame011" .. " " .. device.owner.profile.name, UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Death" .. shooter.team.profiles[shooter.team.index].teamColor .. ".tga" )
shooter.data.heap.death = shooter.data.heap.death + 1
shooter.data.heap.killByName[device.owner.nameId] = (shooter.data.heap.killByName[device.owner.nameId] or 0) + 1
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_41.wav","base:audio/gamemaster/DLG_GM_GLOBAL_42.wav"}, priority = 2,})
end
device.owner.data.heap.isDead = 1
else
-- HIT ------------------------------------------------------
if (shooter.data.heap.lastPlayerShooted == device.owner) then
shooter.data.heap.nbHitLastPlayerShooted = shooter.data.heap.nbHitLastPlayerShooted + 1
if (shooter.data.heap.nbHitLastPlayerShooted == 3) then
if (game.settings.audio.gmtalkative == 1) then
-- throw "Tireur d'�lite" sound
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_26.wav",}, priority = 3, proba = 0.33})
end
shooter.data.heap.nbHitLastPlayerShooted = 0
end
else
shooter.data.heap.nbHitLastPlayerShooted = 1
shooter.data.heap.lastPlayerShooted = device.owner
end
shooter.data.heap.hitLost = 0
if (shooter.team ~= device.owner.team) then
activity.uiAFP:PushLine(shooter.profile.name .. " " .. l"ingame009" .. " " .. device.owner.profile.name, UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Hit.tga")
shooter.data.heap.hitByName[device.owner.nameId] = (shooter.data.heap.hitByName[device.owner.nameId] or 0) + 1
shooter.data.heap.hit = shooter.data.heap.hit + 1
elseif (activity.settings.teamFrag == 1) then
-- throw "teammateshoot" sound
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_41.wav","base:audio/gamemaster/DLG_GM_GLOBAL_42.wav"}, priority = 2,})
activity.uiAFP:PushLine(shooter.profile.name .. " " .. l"ingame009" .. " " .. device.owner.profile.name, UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Hit" .. shooter.team.profiles[shooter.team.index].teamColor .. ".tga" )
shooter.data.heap.hitByName[device.owner.nameId] = (shooter.data.heap.hitByName[device.owner.nameId] or 0) + 1
shooter.data.heap.hit = shooter.data.heap.hit + 1
end
end
end
if (0 == lifePoints and (device.owner.defender and activity.settings.livesDefender >= 1 and device.owner.data.heap.nbRespawn == activity.settings.livesDefender - 1 or not device.owner.defender and activity.settings.livesStalker >= 1 and device.owner.data.heap.nbRespawn == activity.settings.livesStalker - 1)) then
-- This player is out
device.owner.data.heap.icon = string.sub(device.owner.data.heap.icon, 0, #device.owner.data.heap.icon - 4)
device.owner.data.heap.icon = device.owner.data.heap.icon .. "_Out.tga"
device.owner.team.data.heap.nbPlayerAlive = device.owner.team.data.heap.nbPlayerAlive - 1
-- check end of game
if (device.owner.team.data.heap.nbPlayerAlive == 0) then
if (device.owner.defender) then
defenders.data.heap.score = 0
stalkers.data.heap.score = 1
end
activity:PostStateChange("endround")
end
-- only one player left in this team
if (device.owner.team.data.heap.nbPlayerAlive == 1) then
local curTeam = {"DLG_GM_LAST_TEAM_02.wav", "DLG_GM_LAST_TEAM_05.wav" }
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/" .. curTeam[device.owner.team.index],}, priority = 1,})
elseif (device.owner.team.data.heap.nbPlayerAlive == 2) then
local curTeam = {"DLG_GM_LAST_TEAM_07.wav", "DLG_GM_LAST_TEAM_10.wav" }
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/" .. curTeam[device.owner.team.index],}, priority = 1,})
elseif (device.owner.team.data.heap.nbPlayerAlive > 0) then
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_LAST_TEAM_01.wav",}, priority = 1,})
end
end
end
-- back to life or medkit !
if (device.owner.data.heap.lifePoints < lifePoints) then
if (1 == device.owner.data.heap.isDead or game.settings.addons.medkitPack == 0) then
device.owner.data.heap.nbRespawn = device.owner.data.heap.nbRespawn + 1
activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame014", UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Respawn" .. device.owner.team.profiles[device.owner.team.index].teamColor .. ".tga")
device.owner.data.heap.isDead = 0
if (game.settings.audio.gmtalkative == 1) then
-- throw "De retour" sound
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_36.wav"}, priority = 2,})
end
else
device.owner.data.heap.nbMediKit = device.owner.data.heap.nbMediKit + 1
activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame012", UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Heart.tga")
if (game.settings.audio.gmtalkative == 1) then
-- throw "�a va mieux?" sound
game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_16.wav","base:audio/gamemaster/DLG_GM_GLOBAL_17.wav"}, priority = 2,})
end
end
end
-- store life points
device.owner.data.heap.lifePoints = lifePoints
local lastBaseScanned = (arg[10] * 256) + arg[11]
if (lastBaseScanned == 0 and device.owner.team.index == 2 and not device.owner.primary) then
--activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame064", teamcolor, "base:texture/Ui/Icons/16x/FlagIcon" .. device.owner.team.index .. ".tga")
device.owner.team.data.heap.score = 2
activity:PostStateChange("endround")
end
end
end
end
function UAStalktheLantern.State.RoundLoop:Update()
UTActivity.State.RoundLoop.Update(self)
-- end match
if (activity.timer <= 0) then
activity:PostStateChange("endround")
end
end
|
-- Delete these so we can replace all oil products with our own:
-- heavy-oil
data.raw["fluid"]["heavy-oil"] = nil
-- light-oil
data.raw["fluid"]["light-oil"] = nil
-- petroleum-gas
data.raw["fluid"]["petroleum-gas"] = nil
-- oil
data:extend(
{
{
type = "fluid",
name = "oil",
default_temperature = 25,
heat_capacity = "0.1KJ",
base_color = {r=0.3, g=0.1, b=0.3},
flow_color = {r=0.8, g=0.8, b=0.8},
max_temperature = 100,
icon = "__LaNMod__/graphics/icons/fluid/oil.png",
icon_size = 32,
-- This isn't entirely arbitrary, but we can use the draw order of crude oil too:
order = "a[fluid]-b[oil]"
}
})
-- sulfuric-acid
data.raw["fluid"]["sulfuric-acid"].icon = "__LaNMod__/graphics/icons/fluid/sulfuric-acid.png"
|
--------------------------------------------------------------------------------
-- 81-717 ventilation switching unit
--------------------------------------------------------------------------------
-- Copyright (C) 2013-2018 Metrostroi Team & FoxWorks Aerospace s.r.o.
-- Contains proprietary code. See license.txt for additional information.
--------------------------------------------------------------------------------
Metrostroi.DefineSystem("81_718_BUVS")
function TRAIN_SYSTEM:Initialize()
self.KM1 = 0 --Контактор вентиляции агрегатов 1 группы
self.KM2 = 0 --Контактор вентиляции агрегатов 2 группы
self.KM3 = 0 --Реле наличия минимального тока
self.KM4 = 0 --Реле контроля наличия тормозного тока
self.KV1 = 0
end
function TRAIN_SYSTEM:Inputs()
return { }
end
function TRAIN_SYSTEM:Outputs()
return { "KM1","KM2" }
end
function TRAIN_SYSTEM:TriggerInput(name,value)
end
function TRAIN_SYSTEM:Think()
local Train = self.Train
self.RKTTCurrent = math.abs(Train.Electric.I13) + math.abs(Train.Electric.I24)
self.RKTTClose = 275 + 100*self.Train.Pneumatic.WeightLoadRatio --125
self.RKTTOpen = 370 + 130*self.Train.Pneumatic.WeightLoadRatio --130
if self.RKTTCurrent < self.RKTTClose then
self.KM4 = 0
else
self.KM4 = self.RKTTCurrent >= self.RKTTOpen
end
end
|
-- Converts a LuaJIT bytecode number to name
--
-- usage: luajit bcname.lua bytecode_number [bytecode_number2 [...]]
--
-- example:
-- $ luajit-2.1 bcname.lua 71 72
-- VARG
-- ISNEXT
--
-- From: http://www.freelists.org/post/luajit/frames-and-tail-calls,1
local function bcnumber_to_name( bcnum )
if not bcnum then return '' end
return string.sub(require("jit.vmdef").bcnames, bcnum*6+1, bcnum*6+6)
end
for _, v in ipairs(arg) do
print(bcnumber_to_name(tonumber(v)))
end
|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You under the Apache License, Version 2.0
-- (the "License"); you may not use this file except in compliance with
-- the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
local string = string
local core = require("apisix.core")
local ngx_re = require("ngx.re")
local openidc = require("resty.openidc")
local ngx = ngx
local ngx_encode_base64 = ngx.encode_base64
local plugin_name = "openid-connect"
local schema = {
type = "object",
properties = {
client_id = {type = "string"},
client_secret = {type = "string"},
discovery = {type = "string"},
scope = {
type = "string",
default = "openid",
},
ssl_verify = {
type = "boolean",
default = false,
},
timeout = {
type = "integer",
minimum = 1,
default = 3,
description = "timeout in seconds",
},
introspection_endpoint = {
type = "string"
},
introspection_endpoint_auth_method = {
type = "string",
default = "client_secret_basic"
},
bearer_only = {
type = "boolean",
default = false,
},
realm = {
type = "string",
default = "apisix",
},
logout_path = {
type = "string",
default = "/logout",
},
redirect_uri = {
type = "string",
description = "use ngx.var.request_uri if not configured"
},
public_key = {type = "string"},
token_signing_alg_values_expected = {type = "string"},
set_access_token_header = {
description = "Whether the access token should be added as a header to the request " ..
"for downstream",
type = "boolean",
default = true
},
access_token_in_authorization_header = {
description = "Whether the access token should be added in the Authorization " ..
"header as opposed to the X-Access-Token header.",
type = "boolean",
default = false
},
set_id_token_header = {
description = "Whether the ID token should be added in the X-ID-Token header to " ..
"the request for downstream.",
type = "boolean",
default = true
},
set_userinfo_header = {
description = "Whether the user info token should be added in the X-Userinfo " ..
"header to the request for downstream.",
type = "boolean",
default = true
}
},
required = {"client_id", "client_secret", "discovery"}
}
local _M = {
version = 0.1,
priority = 2599,
name = plugin_name,
schema = schema,
}
function _M.check_schema(conf)
if conf.ssl_verify == "no" then
-- we used to set 'ssl_verify' to "no"
conf.ssl_verify = false
end
local ok, err = core.schema.check(schema, conf)
if not ok then
return false, err
end
return true
end
local function get_bearer_access_token(ctx)
-- Get Authorization header, maybe.
local auth_header = core.request.header(ctx, "Authorization")
if not auth_header then
-- No Authorization header, get X-Access-Token header, maybe.
local access_token_header = core.request.header(ctx, "X-Access-Token")
if not access_token_header then
-- No X-Access-Token header neither.
return false, nil, nil
end
-- Return extracted header value.
return true, access_token_header, nil
end
-- Check format of Authorization header.
local res, err = ngx_re.split(auth_header, " ", nil, nil, 2)
if not res then
-- No result was returned.
return false, nil, err
elseif #res < 2 then
-- Header doesn't split into enough tokens.
return false, nil, "Invalid Authorization header format."
end
if string.lower(res[1]) == "bearer" then
-- Return extracted token.
return true, res[2], nil
end
return false, nil, nil
end
local function introspect(ctx, conf)
-- Extract token, maybe.
local has_token, token, err = get_bearer_access_token(ctx)
if err then
return ngx.HTTP_BAD_REQUEST, err, nil, nil
end
if not has_token then
-- Could not find token.
if conf.bearer_only then
-- Token strictly required in request.
ngx.header["WWW-Authenticate"] = 'Bearer realm="' .. conf.realm .. '"'
return ngx.HTTP_UNAUTHORIZED, "No bearer token found in request.", nil, nil
else
-- Return empty result.
return nil, nil, nil, nil
end
end
-- If we get here, token was found in request.
if conf.public_key then
-- Validate token against public key.
-- TODO: In the called method, the openidc module will try to extract
-- the token by itself again -- from a request header or session cookie.
-- It is inefficient that we also need to extract it (just from headers)
-- so we can add it in the configured header. Find a way to use openidc
-- module's internal methods to extract the token.
local res, err = openidc.bearer_jwt_verify(conf)
if err then
-- Error while validating or token invalid.
ngx.header["WWW-Authenticate"] = 'Bearer realm="' .. conf.realm ..
'", error="invalid_token", error_description="' .. err .. '"'
return ngx.HTTP_UNAUTHORIZED, err, nil, nil
end
-- Token successfully validated.
return res, err, token, nil
else
-- Validate token against introspection endpoint.
-- TODO: Same as above for public key validation.
local res, err = openidc.introspect(conf)
if err then
ngx.header["WWW-Authenticate"] = 'Bearer realm="' .. conf.realm ..
'", error="invalid_token", error_description="' .. err .. '"'
return ngx.HTTP_UNAUTHORIZED, err, nil, nil
end
-- Token successfully validated and response from the introspection
-- endpoint contains the userinfo.
return res, err, token, res
end
end
local function add_access_token_header(ctx, conf, token)
if token then
-- Add Authorization or X-Access-Token header, respectively, if not already set.
if conf.set_access_token_header then
if conf.access_token_in_authorization_header then
if not core.request.header(ctx, "Authorization") then
-- Add Authorization header.
core.request.set_header(ctx, "Authorization", "Bearer " .. token)
end
else
if not core.request.header(ctx, "X-Access-Token") then
-- Add X-Access-Token header.
core.request.set_header(ctx, "X-Access-Token", token)
end
end
end
end
end
function _M.rewrite(plugin_conf, ctx)
local conf = core.table.clone(plugin_conf)
-- Previously, we multiply conf.timeout before storing it in etcd.
-- If the timeout is too large, we should not multiply it again.
if not (conf.timeout >= 1000 and conf.timeout % 1000 == 0) then
conf.timeout = conf.timeout * 1000
end
if not conf.redirect_uri then
conf.redirect_uri = ctx.var.request_uri
end
if not conf.ssl_verify then
-- openidc use "no" to disable ssl verification
conf.ssl_verify = "no"
end
local response, err
if conf.bearer_only or conf.introspection_endpoint or conf.public_key then
-- An introspection endpoint or a public key has been configured. Try to
-- validate the access token from the request, if it is present in a
-- request header. Otherwise, return a nil response. See below for
-- handling of the case where the access token is stored in a session cookie.
local access_token, userinfo
response, err, access_token, userinfo = introspect(ctx, conf)
if err then
-- Error while validating token or invalid token.
core.log.error("OIDC introspection failed: ", err)
return response
end
if response then
-- Add configured access token header, maybe.
add_access_token_header(ctx, conf, access_token)
if userinfo and conf.set_userinfo_header then
-- Set X-Userinfo header to introspection endpoint response.
core.request.set_header(ctx, "X-Userinfo",
ngx_encode_base64(core.json.encode(userinfo)))
end
end
end
if not response then
-- Either token validation via introspection endpoint or public key is
-- not configured, and/or token could not be extracted from the request.
-- Authenticate the request. This will validate the access token if it
-- is stored in a session cookie, and also renew the token if required.
-- If no token can be extracted, the response will redirect to the ID
-- provider's authorization endpoint to initiate the Relying Party flow.
-- This code path also handles when the ID provider then redirects to
-- the configured redirect URI after successful authentication.
response, err = openidc.authenticate(conf)
if err then
core.log.error("OIDC authentication failed: ", err)
return 500
end
if response then
-- If the openidc module has returned a response, it may contain,
-- respectively, the access token, the ID token, and the userinfo.
-- Add respective headers to the request, if so configured.
-- Add configured access token header, maybe.
add_access_token_header(ctx, conf, response.access_token)
-- Add X-ID-Token header, maybe.
if response.id_token and conf.set_id_token_header then
local token = core.json.encode(response.id_token)
core.request.set_header(ctx, "X-ID-Token", ngx.encode_base64(token))
end
-- Add X-Userinfo header, maybe.
if response.user and conf.set_userinfo_header then
core.request.set_header(ctx, "X-Userinfo",
ngx_encode_base64(core.json.encode(response.user)))
end
end
end
end
return _M
|
-- unsigned ints
local io = require "vstruct.io"
local u = {}
function u.unpack(_, buf)
local n = 0
local e = io("endianness", "get")
local sof,eof,step
if e == "big" then
sof,eof,step = 1,#buf,1
else
sof,eof,step = #buf,1,-1
end
for i=sof,eof,step do
n = n * 256 + buf:byte(i,i)
end
return n
end
function u.unpackbits(bit, width)
local n = 0
for i=1,width do
n = n * 2 + bit()
end
return n
end
function u.pack(_, data, width)
local s = ""
local e = io("endianness", "get")
for i=1,width do
if e == "big" then
s = string.char(data % 256) .. s
else
s = s .. string.char(data % 256)
end
data = math.trunc(data/256)
end
return s
end
function u.packbits(bit, data, width)
for i=width-1,0,-1 do
bit(math.floor(data/2^i) % 2)
end
end
return u
|
local skynet = require("skynet")
print("params: ", ...)
local CMD = {}
function CMD.add(a, b)
return a+b
end
function CMD.print(o)
skynet.error(o)
end
skynet.start(function()
skynet.dispatch("lua", function(session, source, cmd, ...)
print("session: ", session, "source: ", source, "cmd", cmd, "params", ...)
local f = CMD[cmd]
assert(f, "can't find cmd " .. (cmd or nil))
if(session == 0) then
f(...)
else
skynet.ret(skynet.pack(f(...)))
end
end)
end)
|
function GetMapTexture(id)
-- 1134 Tiger's peak
-- 2373 Sunglasses arena
-- 2167 Robodrome
-- 617 Dalaran sewers
-- 980 tolviron
-- 572 Ruins
-- 1672 Blade's edge
-- 1552 Ashamane
-- 1911 Mugambala
-- 1504 Blackrook hold
-- 1825 Hookpoint
-- 1505 Nagrand
if id == 1134 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadingScreen_Shadowpan_bg";
elseif id == 2373 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadScreenSkywallRaid";
elseif id == 2167 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadScreenGnomeregan";
elseif id == 617 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadScreenDalaranSewersArena";
elseif id == 980 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadScreenTolvirArena";
elseif id == 572 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadScreenRuinsofLordaeronBattlegrounds";
elseif id == 1672 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadScreenBladesEdgeArena";
elseif id == 1552 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadScreenWanderingIsle";
elseif id == 1911 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadingScreen_ZuldazarArena";
elseif id == 1504 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadingScreen_BlackrookHoldArena_wide";
elseif id == 1825 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadingScreen_AlliancePVParena_MasterWidescreen_BattleforAzeroth";
elseif id == 1505 then
return "Interface\\GLUES\\LOADINGSCREENS\\LoadScreenNagrandArenaBattlegrounds";
else
return "Interface\\GLUES\\LOADINGSCREENS\\LoadScreenOrgrimmarArena";
end
end
function GetExpansionForMap(id)
if id == 1134 then
return textInserts.expansions.mists;
elseif id == 2373 then
return textInserts.expansions.sl;
elseif id == 2167 then
return textInserts.expansions.bfa;
elseif id == 617 then
return textInserts.expansions.wotlk;
elseif id == 980 then
return textInserts.expansions.mists;
elseif id == 572 then
return textInserts.expansions.bc;
elseif id == 1672 then
return textInserts.expansions.bc;
elseif id == 1552 then
return textInserts.expansions.legion;
elseif id == 1911 then
return textInserts.expansions.bfa;
elseif id == 1504 then
return textInserts.expansions.legion;
elseif id == 1825 then
return textInserts.expansions.bfa;
elseif id == 1505 then
return textInserts.expansions.bc;
else
return textInserts.expansions.unknown;
end
end
function GetExpansionBackdrop(id)
if id == 1134 then
return "Interface\\GLUES\\COMMON\\Glues-WoW-MPLogo";
elseif id == 2373 then
return "Interface\\GLUES\\COMMON\\Glues-WoW-ShadowlandsLogo";
elseif id == 2167 then
return "Interface\\GLUES\\COMMON\\Glues-WoW-BattleforAzerothLogo";
elseif id == 617 then
return "Interface\\GLUES\\COMMON\\Glues-WOW-WoltkLogo";
elseif id == 980 then
return "Interface\\GLUES\\COMMON\\Glues-WoW-MPLogo";
elseif id == 572 then
return "Interface\\GLUES\\COMMON\\GLUES-WOW-BCLOGO";
elseif id == 1672 then
return "Interface\\GLUES\\COMMON\\GLUES-WOW-BCLOGO";
elseif id == 1552 then
return "Interface\\GLUES\\COMMON\\Glues-WoW-LegionLogo";
elseif id == 1911 then
return "Interface\\GLUES\\COMMON\\Glues-WoW-BattleforAzerothLogo";
elseif id == 1504 then
return "Interface\\GLUES\\COMMON\\Glues-WoW-LegionLogo";
elseif id == 1825 then
return "Interface\\GLUES\\COMMON\\Glues-WoW-BattleforAzerothLogo";
elseif id == 1505 then
return "Interface\\GLUES\\COMMON\\GLUES-WOW-BCLOGO";
else
return "Interface\\GLUES\\COMMON\\GLUES-WOW-CLASSICLOGO";
end
end
|
UIFont = {}
UIFont.Small = {}
UIFont.Medium = {}
|
local self = {}
GLib.Geometry.IParametricSurface = GLib.MakeConstructor (self)
function self:ctor ()
end
function self:Evaluate (t1, t2, out)
GLib.Error ("IParametricSurface:Evaluate : Not implemented.")
end
function self:GetDegree ()
GLib.Error ("IParametricCurve:GetDegree : Not implemented.")
return 2
end
function self:GetParameter1Minimum ()
return 0
end
function self:GetParameter1Maximum ()
return 1
end
function self:GetParameter2Minimum ()
return 0
end
function self:GetParameter2Maximum ()
return 1
end
function self:GetParameter1Range ()
return self:GetParameter1Minimum (), self:GetParameter1Maximum ()
end
function self:GetParameter2Range ()
return self:GetParameter2Minimum (), self:GetParameter2Maximum ()
end
|
require 'mock.gfx.movie.MovieAsset'
require 'mock.gfx.movie.MovieClipPlane'
|
// Wildfire Black Mesa Roleplay
// File description: BMRP Xen script
// Copyright (c) 2022 KiwifruitDev
// Licensed under the MIT License.
//*********************************************************************************************
// 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.
//*********************************************************************************************
// BASE FILE HEADER DO NOT MODIFY!! //
local ent = FindMetaTable("Entity") //
local ply = FindMetaTable("Player") //
local vec = FindMetaTable("Vector") //
// ================================ //
// Every file needs this :)
include("autorun/sh_bmrp.lua")
// Add our really cool HEV suits to the map so people can suit-up with them. //
BMRP.AddToMapReset("BMRP_AddSuitsToMap", function()
// HEV SUITS //
print("[BMRP] Replacing suits...")
for k,v in pairs(ents.FindByClass("item_suit")) do
local newsuit = ents.Create("bms_hev_suit")
newsuit:SetPos(v:GetPos())
newsuit:SetAngles(v:GetAngles())
v:Remove()
newsuit.persistant = true
newsuit:Spawn()
newsuit.persistant = true // double sure
print("[BMRP] Replacing HEV Suit #"..k)
end
print("[BMRP] Done replacing suits!")
end)
// This table of models is allowed to "breathe" or not die in Xen.
local models = {
"models/motorhead/hevscientist.mdl",
"models/cs/playermodels/vortigaunt.mdl",
"models/vj_hlr/hl1/headcrab.mdl",
"models/houndeye.mdl",
"models/bullsquid.mdl",
}
hook.Add("MDAreaEnter", "BMRP_XenGravityEnter", function(ent, trigger, settings) // Happens when you enter the MapDefine trigger for Xen
if settings.name == "Xen" then
if IsValid(ent) then
if ent:IsPlayer() and ( not ent:GetNWBool("MDSpawning", false) ) then
if not GetGlobalBool("staff_xencheck", false) then
ent:SetGravity(0.4) // very low moon gravity
for k,v in pairs(models) do
if ent:GetModel() == v then
return
end
end
// put stuff here if you enter without an hev suit
local index = ent:EntIndex()
local lastplayerhealth = ent:Health()
timer.Create("XenDeath_"..index, 1.5, 0, function() // we want a unique index so we can delete it when you exit
if GetGlobalBool("staff_xencheck", false) then
timer.Remove("XenDeath_"..index)
return
end
if lastplayerhealth <= 15 then
ent:Kill()
timer.Remove("XenDeath_"..index) // no need
return
end
local dmg = DamageInfo() //drowning damage
dmg:SetDamage(15)
dmg:SetDamageType(DMG_DROWN)
ent:TakeDamageInfo(dmg)
ent:ScreenFade( SCREENFADE.IN, Color( 0, 0, 255, 10 ), 0.3, 0 )
lastplayerhealth = ent:Health()
hook.Run("PlayerDrowning", ent)
end)
end
end
end
elseif settings.name == "HECUKILLER" then
if IsValid(ent) then
if ent:IsPlayer() and ( not ent:GetNWBool("MDSpawning", false) ) then
if GetGlobalBool("hecuallowed", false) == false then
if ent:CategoryCheck() ~= "hecu" then return end
if ent:IsStaff() then return end
ent:KillSilent()
hook.Run("SystemMessage", ent, "", "H.E.C.U are not allowed in the facility at this time. You have been respawned.")
end
end
end
elseif settings.name == "xentp" then
if IsValid(ent) then
if ent:GetClass() ~= "xen_crystal" then return end
if not ent:IsPlayer() and ( not ent:GetNWBool("MDSpawning", false) ) then
ent:SetPos(Vector(-13457.995117, 525.824951, -303.379181))
end
end
end
end)
hook.Add("MDAreaExit", "BMRP_XenGravityExit", function(ent, trigger, settings) // Happens when you leave the MapDefine trigger for Xen
if settings.name == "Xen" then
if IsValid(ent) then
if ent:IsPlayer() and ( not ent:GetNWBool("MDSpawning", false) ) then
ent:SetGravity(1) // go back to default gravity
if timer.Exists("XenDeath_"..ent:EntIndex()) then
timer.Remove("XenDeath_"..ent:EntIndex()) // deleting unique index
end
end
end
end
end)
// This spawns random NPC's around the map If there are actually enough players to kill them. //
// How many players before random NPCs start to spawn?
local playercount = 10
// How many seconds before a random NPC spawns?
local spawndelay = 2200
local SpawnPositions = {
Vector(-10274.734375, -973.662415, 634.031250), // Right inside topside entrance.
Vector(-10278.618164, -1043.493408, -188.968750), // Sector F after elevator
}
local RandomNPCs = {
"npc_vj_hlr1_headcrab",
"npc_vj_hlr1_headcrab_baby",
"npc_vj_hlr1_zombie",
"npc_vj_hlr1_houndeye",
"npc_vj_hlr1_bullsquid",
}
timer.Create("RandomNPCSpawner", spawndelay, 0, function()
if player.GetCount() >= playercount then
if GetGlobalBool("staff_npcspawner", false) == true then
local spawnpos = table.Random(SpawnPositions)
local npc = ents.Create(table.Random(RandomNPCs))
npc:SetPos(spawnpos)
npc:Spawn()
npc:DropToFloor()
npc:Activate()
local sprite = ents.Create("env_sprite")
sprite:SetPos(spawnpos + Vector(0, 0, -64))
sprite:SetKeyValue("rendercolor", "77 210 130")
sprite:SetKeyValue("renderfx", "14")
sprite:SetKeyValue("rendermode", "3")
sprite:SetKeyValue("model", "sprites/Fexplo1.spr")
sprite:SetKeyValue("scale", "1")
sprite:SetKeyValue("spawnflags", "3")
sprite:SetKeyValue("framerate", "10")
sprite:Spawn()
sprite:EmitSound("debris/beamstart2.wav")
sprite:Activate()
timer.Simple(5, function()
if IsValid(sprite) then
sprite:Remove()
end
end)
end
end
end)
|
-- Copyright (C) Sony Computer Entertainment America LLC.
-- All Rights Reserved.
--
-- Dependencies
--
include "../sledluaplugin/libsce_sledluaplugin-5.1.4.lua"
include "../sleddebugger/libsce_sleddebugger.lua"
--
-- Premake build script for the sce simple test sample
--
sdk_project "libsce_testsimple-5.1.4_sample"
sdk_location "."
sdk_kind "ConsoleApp"
uuid "1223423A-2390-43F3-B433-B232456FECAB"
configurations { sdk.DEBUG, sdk.RELEASE }
platforms { sdk.WIN_STATIC_ALL }
files {
"*.cpp",
"../sleddebugger_unittests/scoped_network.*",
"../sledluaplugin_SharedSampleCode/fileutilities.*",
"../sledcore/*.h",
"../sledcore/windows/*.h"
}
vpaths {
["Headers"] = {
"**.h",
"../sleddebugger_unittests/**.h",
"../sledluaplugin_SharedSampleCode/**.h" } }
vpaths {
["Source"] = {
"**.cpp",
"../sleddebugger_unittests/**.cpp",
"../sledluaplugin_SharedSampleCode/**.cpp" } }
includedirs { "../../", "../../../" }
links { "libsce_sledluaplugin-5.1.4", "lua-5.1.4", "libsce_sleddebugger" }
objdir(path.join(sdk.rootdir, "tmp/sce_sled/%{prj.name}/%{sdk.platform(cfg)}"))
targetdir(path.join(sdk.rootdir, "bin/sce_sled/runtime/%{sdk.platform(cfg)}"))
defines { "SCE_LUA_VER=514", "WWS_LUA_VER=514" }
configuration { "Debug*" }
defines { "SCE_SLED_ASSERT_ENABLED=1" }
configuration { "Win*" }
links { "ws2_32", get_sledcore_pathname() }
|
SRC := $(filter-out loadlib.c lua.c luac.c,$(wildcard *.c))
ifneq (llvm, $(TOOLCHAIN))
CFLAGS += -fstack-usage -fconserve-stack
endif
CFLAGS += -DLUA_MAXCAPTURES=16 -DL_MAXLENNUM=50
# Enable these options to debug stack usage
# -Wstack-usage=128 -Wno-error=stack-usage=128
include $(RIOTBASE)/Makefile.base
ifneq (,$(filter -Wformat-nonliteral -Wformat=2, $(CFLAGS)))
CFLAGS += -Wno-format-nonliteral
endif
|
function onTick()
for i = 4, 1, -1 do
local num = property.getNumber("Input #"..i)
if num == 0 then return end
local inp = input.getBool(num)
if inp ~= true then
output.setBool(num, true)
end
end
end
|
data:extend({
{
type = "bool-setting",
name = "hw-print",
default_value = true,
setting_type = "runtime-per-user",
},
{
type = "bool-setting",
name = "hw-stats",
default_value = true,
setting_type = "runtime-global",
},
{
type = "bool-setting",
name = "hw-wood",
default_value = true,
setting_type = "startup",
},
{
type = "string-setting",
name = "hw-mode",
default_value = "standard",
allowed_values = { "standard", "military" },
setting_type = "startup",
},
})
|
-- This file is generated by proto-gen-lua. DO NOT EDIT.
-- The protoc version is 'v3.19.2'
-- The proto-gen-lua version is 'Develop'
local protobuf = require "protobuf.protobuf"
local registry = require "protobuf.registry"
local import_public_sub2_a_pb_desc = require "import_public.sub2.a_pb_desc"
local import_public_sub2_a_pb = {}
---@class import_public_sub2_a_pb.Sub2Message : protobuf.Message
---@type fun():import_public_sub2_a_pb.Sub2Message
import_public_sub2_a_pb.Sub2Message = protobuf.Message(import_public_sub2_a_pb_desc.message_type[1])
import_public_sub2_a_pb.Sub2Message._FullName = ".goproto.protoc.import_public.sub2.Sub2Message"
import_public_sub2_a_pb.Sub2Message._Descriptor = "import_public_sub2_a_pb_desc.message_type[1]"
registry.RegistMessage(import_public_sub2_a_pb.Sub2Message)
return import_public_sub2_a_pb
|
local race = {
["human"] = {
name = "human",
home = "Stormwind City",
pos_x = 100,
pos_y = 10,
pos_z = 100,
pos_o = 180,
},
["orc"] = {
name = "orc",
home = "Orgrimmar",
pos_x = 900,
pos_y = 10,
pos_z = 900,
pos_o = 0,
},
}
return race
|
-- Begin of auto-script
loadMesh("Data/WTF/rollfield.wtf")
loadTexture("Data/Images/rollfield.png")
loadTexture("Data/Images/grass.png")
loadTexture("Data/Images/drewjetfighter.png")
loadTexture("Data/WTF/fighter/fighter.png")
loadTexture("Data/WTF/fighter/fighter3.png")
loadTexture("Data/WTF/fighter/fighter2.png")
loadTexture("Data/WTF/fighter/fighter4.png")
loadTexture("Data/WTF/fighter/fighter5.png")
loadTexture("Data/WTF/fighter/fighter6.png")
loadTexture("Data/WTF/fighter/fighter8.png")
loadTexture("Data/WTF/fighter/fighte10.png")
loadTexture("Data/WTF/fighter/fighter7.png")
loadTexture("Data/FontPngs/monaco32_1.png")
loadTexture("Data/FontPngs/monaco32_2.png")
loadFont("Data/FontPngs/monaco32_1.png", "Data/FontPngs/monaco32_2.png")
setCameraInfo(IG3D_POSITION, 0.478085, 5.897385, 24.126522)
setCameraInfo(IG3D_ROTATION, 69.999992, 1.666718, -0.000000)
gObjects={}
gNumObjects=2
gObjects[1]={}
gObjects[1].cObj=make(ig3d_object, "avatarp1.wtf")
setObjectInfo(gObjects[1].cObj, IG3D_NAME, "avatarp11")
setObjectInfo(gObjects[1].cObj, IG3D_POSITION, -2.734422, 0.645847, 25.779594)
setObjectInfo(gObjects[1].cObj, IG3D_ROTATION, 0.000000, 70.000000, 0.000000)
setObjectInfo(gObjects[1].cObj, IG3D_SIZE, 100.000000,100.000000,100.000000)
gObjects[2]={}
gObjects[2].cObj=make(ig3d_object, "avatarp1.wtf")
setObjectInfo(gObjects[2].cObj, IG3D_NAME, "avatarp12")
setObjectInfo(gObjects[2].cObj, IG3D_POSITION, 0.258888, 0.436259, 29.563126)
setObjectInfo(gObjects[2].cObj, IG3D_ROTATION, 0.000000, 0.000000, 0.000000)
setObjectInfo(gObjects[2].cObj, IG3D_SIZE, 100.000000,100.000000,100.000000)
gParticleEmitters={}
gNumParticleEmitters=0
gSoundEmitters={}
gNumSoundEmitters=0
gGroups={}
gNumGroups=0
gTextboxes={}
gNumTextboxes=1
gTextboxes[1]=make(ig3d_text_box, "Data/FontPngs/monaco32_1.png")
setText_boxInfo(gTextboxes[1], IG3D_POSITION, 20, 20)
setText_boxInfo(gTextboxes[1], IG3D_SIZE, 14)
setText_boxInfo(gTextboxes[1], IG3D_COLOR, 1.000000, 1.000000, 1.000000, 1.000000)
setSceneInfo(IG3D_TINT_COLOR, 1.000000,1.000000,1.000000)
setSceneInfo(IG3D_FOG, false,0.500000,0.500000,0.500000,0.000000,200.000000)
setSceneInfo(IG3D_BACKGROUND_COLOR, 0.650000,0.650000,0.650000)
setSceneInfo(IG3D_FOV, true, 90.000000)
setLightInfo(1, IG3D_ENABLED, true)
setLightInfo(1, IG3D_POSITION, -0.500000,2.000000,-1.000000,0.000000)
setLightInfo(1, IG3D_AMBIENT, 0.400000,0.400000,0.400000,1.000000)
setLightInfo(1, IG3D_DIFFUSE, 1.000000,1.000000,1.000000,1.000000)
setLightInfo(1, IG3D_SPECULAR, 1.000000,1.000000,1.000000,1.000000)
setLightInfo(1, IG3D_CONSTANT_ATTENUATION, 1.000000)
setLightInfo(1, IG3D_LINEAR_ATTENUATION, 0.000000)
setLightInfo(1, IG3D_QUADRATIC_ATTENUATION, 0.000000)
setLightInfo(1, IG3D_SPOTLIGHT, 0.000000,0.000000,0.000000,180.000000,0.000000)
setLightInfo(2, IG3D_ENABLED, false)
setLightInfo(3, IG3D_ENABLED, false)
setLightInfo(4, IG3D_ENABLED, false)
setLightInfo(5, IG3D_ENABLED, false)
setLightInfo(6, IG3D_ENABLED, false)
setLightInfo(7, IG3D_ENABLED, false)
setLightInfo(8, IG3D_ENABLED, false)
-- End of auto-script
f=io.open(getSceneInfo(IG3D_ROOT).."Data/name.txt","r")
playerName=f:read("*line")
f:close()
briefing="MISSION BRIEFING\n\nAttention, "..playerName..",\nOur sensors have detected a large enemy air frigate\nin sector Z42. It is heading towards one of their outposts\nin the south. Since it is heavily guarded and it's flighing a\ndifferent route than the standard weapon transport convoys\nwe believe it to carry some unusual cargo.\n\nObjectives:\n- Destroy all enemies escorting that frigate\n- Force the frigate to stop and land\n You may destroy its engines if they don't cooperate\n\nDO NOT ENTER the enemy frigate under any circumstances!\nWe will be sending a special investigation team for any further\nactions."
setText_boxInfo(gTextboxes[1], IG3D_TEXT, briefing)
setSceneInfo(IG3D_MOUSE_VIEW, true)
setSceneInfo(IG3D_RECEIVE_SHADOW, true)
setObjectInfo(gObjects[1].cObj, IG3D_CAST_SHADOW, true, "avatarp1shadow.wtf")
setObjectInfo(gObjects[2].cObj, IG3D_CAST_SHADOW, true, "avatarp1shadow.wtf")
setLightInfo(2, IG3D_POSITION, 1,1,0,0)
theLevel="Data/Levels/TurretTest"
loadtime=0
function loop()
if loadtime~=0 then
if time()>=loadtime then
loadLevel(theLevel)
end
else
if click("n") then
loadtime=time()+2
setObjectInfo(gObjects[2].cObj, IG3D_FORCE, 0,0,2)
end
end
end
game_func=loop
|
local classes = classes;
local super = classes.Object;
local class = inherit({
name = "UDim",
super = super,
func = inherit({}, super.func),
get = inherit({}, super.get),
set = inherit({}, super.set),
concrete = true,
}, super);
classes[class.name] = class;
local cache = setmetatable({}, { __mode = "v" });
function class.new(scale, offset)
if (scale ~= nil) then
local scale_t = type(scale);
if (scale_t ~= "number") then
error("bad argument #1 to '" ..__func__.. "' (number expected, got " ..scale_t.. ")", 2);
end
else
scale = 0;
end
if (offset ~= nil) then
local offset_t = type(offset);
if (offset_t ~= "number") then
error("bad argument #1 to '" ..__func__.. "' (number expected, got " ..offset_t.. ")", 2);
end
else
offset = 0;
end
local cacheId = scale.. ":" ..offset;
local obj = cache[cacheId];
if (not obj) then
local success;
success, obj = pcall(super.new, class);
if (not success) then error(obj, 2) end
obj.scale = scale;
obj.offset = offset;
cache[cacheId] = obj;
end
return obj;
end
class.meta = extend({
__metatable = super.name.. ":" ..class.name,
__add = function(obj1, obj2)
local obj1_t = type(obj1);
if (obj1_t ~= "UDim" and obj1_t ~= "number") then
error("bad operand #1 to '+' (UDim/number expected, got " ..obj1_t.. ")", 2);
end
local obj2_t = type(obj2);
if (obj2_t ~= "UDim" and obj2_t ~= "number") then
error("bad operand #2 to '+' (UDim/number expected, got " ..obj2_t.. ")", 2);
end
return (obj1_t == "number") and class.new(obj1+obj2.scale, obj1+obj2.offset)
or (obj2_t == "number") and class.new(obj1.scale+obj2, obj1.offset+obj2)
or class.new(obj1.scale+obj2.scale, obj1.offset+obj2.offset);
end,
__sub = function(obj1, obj2)
local obj1_t = type(obj1);
if (obj1_t ~= "UDim" and obj1_t ~= "number") then
error("bad operand #1 to '-' (UDim/number expected, got " ..obj1_t.. ")", 2);
end
local obj2_t = type(obj2);
if (obj2_t ~= "UDim" and obj2_t ~= "number") then
error("bad operand #2 to '-' (UDim/number expected, got " ..obj2_t.. ")", 2);
end
return (obj1_t == "number") and class.new(obj1-obj2.scale, obj1-obj2.offset)
or (obj2_t == "number") and class.new(obj1.scale-obj2, obj1.offset-obj2)
or class.new(obj1.scale-obj2.scale, obj1.offset-obj2.offset);
end,
__mul = function(obj1, obj2)
local obj1_t = type(obj1);
if (obj1_t ~= "UDim" and obj1_t ~= "number") then
error("bad operand #1 to '*' (UDim/number expected, got " ..obj1_t.. ")", 2);
end
local obj2_t = type(obj2);
if (obj2_t ~= "UDim" and obj2_t ~= "number") then
error("bad operand #2 to '*' (UDim/number expected, got " ..obj2_t.. ")", 2);
end
return (obj1_t == "number") and class.new(obj1*obj2.scale, obj1*obj2.offset)
or (obj2_t == "number") and class.new(obj1.scale*obj2, obj1.offset*obj2)
or class.new(obj1.scale*obj2.scale, obj1.offset*obj2.offset);
end,
__div = function(obj1, obj2)
local obj1_t = type(obj1);
if (obj1_t ~= "UDim" and obj1_t ~= "number") then
error("bad operand #1 to '/' (UDim/number expected, got " ..obj1_t.. ")", 2);
end
local obj2_t = type(obj2);
if (obj2_t ~= "UDim" and obj2_t ~= "number") then
error("bad operand #2 to '/' (UDim/number expected, got " ..obj2_t.. ")", 2);
end
return (obj1_t == "number") and class.new(obj1/obj2.scale, obj1/obj2.offset)
or (obj2_t == "number") and class.new(obj1.scale/obj2, obj1.offset/obj2)
or class.new(obj1.scale/obj2.scale, obj1.offset/obj2.offset);
end,
__unm = function(obj)
return class.new(-obj.scale, -obj.offset);
end,
__tostring = function(obj)
return obj.scale.. ", " ..obj.offset;
end,
}, super.meta);
function class.func.unpack(obj)
return obj.scale, obj.offset;
end
|
item_greater_tranquil_boots = class(ItemBaseClass)
LinkLuaModifier( "modifier_item_greater_tranquil_boots", "items/farming/greater_tranquil_boots.lua", LUA_MODIFIER_MOTION_NONE )
--LinkLuaModifier( "modifier_intrinsic_multiplexer", "modifiers/modifier_intrinsic_multiplexer.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( "modifier_greater_tranquils_tranquilize_debuff", "items/farming/greater_tranquil_boots.lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
function item_greater_tranquil_boots:GetAbilityTextureName()
local baseName = self.BaseClass.GetAbilityTextureName( self )
if not self:IsBreakable() then
return baseName
end
-- local brokeName = ""
-- if self:GetCaster():HasModifier("modifier_greater_tranquils_broken_debuff") then
-- brokeName = "_active"
-- end
-- return baseName .. brokeName
end
function item_greater_tranquil_boots:GetIntrinsicModifierName()
return "modifier_item_greater_tranquil_boots" -- "modifier_intrinsic_multiplexer"
end
-- uncomment this if we plan to add more effects to Greater Tranquil Boots
--[[
function item_greater_tranquil_boots:GetIntrinsicModifierNames()
return {
"modifier_item_greater_tranquil_boots",
}
end
]]
function item_greater_tranquil_boots:ShouldUseResources()
return true
end
function item_greater_tranquil_boots:OnSpellStart()
local caster = self:GetCaster()
local target = self:GetCursorTarget()
-- Don't do anything if target has Linken's effect
if target:TriggerSpellAbsorb(self) then
return
end
local duration = self:GetSpecialValueFor("tranquilize_duration")
-- Apply status resistance only if its a ranged hero
if target:IsRangedAttacker() then
duration = target:GetValueChangedByStatusResistance(duration)
end
target:AddNewModifier(caster, self, "modifier_greater_tranquils_tranquilize_debuff", {duration = duration})
end
function item_greater_tranquil_boots:IsBreakable()
return self:GetSpecialValueFor("break_time") > 0
end
---------------------------------------------------------------------------------------------------
modifier_item_greater_tranquil_boots = class(ModifierBaseClass)
function modifier_item_greater_tranquil_boots:IsHidden()
return true
end
function modifier_item_greater_tranquil_boots:IsDebuff()
return false
end
function modifier_item_greater_tranquil_boots:IsPurgable()
return false
end
function modifier_item_greater_tranquil_boots:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
function modifier_item_greater_tranquil_boots:OnCreated( event )
local spell = self:GetAbility()
if spell and not spell:IsNull() then
self.moveSpd = spell:GetSpecialValueFor( "bonus_movement_speed" )
--self.moveSpdBroken = spell:GetSpecialValueFor( "broken_movement_speed" )
self.armor = spell:GetSpecialValueFor( "bonus_armor" )
self.healthRegen = spell:GetSpecialValueFor( "bonus_health_regen" )
end
end
modifier_item_greater_tranquil_boots.OnRefresh = modifier_item_greater_tranquil_boots.OnCreated
--[[ Old checking distance traveled and modifying charges accordingly (part of Naturalize)
if IsServer() then
function modifier_item_greater_tranquil_boots:OnIntervalThink()
local parent = self:GetParent()
local spell = self:GetAbility()
-- disable everything here for illusions or during duels / pre 0:00
if parent:IsIllusion() or not Gold:IsGoldGenActive() then
return
end
if self.storedDamage and self.storedDamage > 0 then
local parent = self:GetParent()
local maxHeal = math.min( spell:GetSpecialValueFor( "regen_from_creeps" ) * self.interval, self.storedDamage )
parent:Heal( maxHeal, parent )
self.storedDamage = self.storedDamage - maxHeal
end
local currentCharges = spell:GetCurrentCharges()
if currentCharges < self.maxCharges then
-- get the current point of the parent
local originParent = parent:GetAbsOrigin()
-- get the distance between that point and their old point
local dist = ( originParent - self.originOld ):Length2D()
-- cap the amount of distances so tps don't instafill it
dist = math.min( dist, self.distMax )
-- add the distance to the fraction charge
self.fracCharge = self.fracCharge + dist
-- determine the amount of charges to give
local addedCharges = math.floor( self.fracCharge / self.distPer )
-- give those charges, then subtract their fractional charge from the item
spell:SetCurrentCharges( math.min( currentCharges + addedCharges, self.maxCharges ) )
self.fracCharge = self.fracCharge - ( self.distPer * addedCharges )
-- set the old point of the parent
self.originOld = originParent
end
end
end
]]
function modifier_item_greater_tranquil_boots:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_UNIQUE,
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS,
MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT,
--MODIFIER_EVENT_ON_ATTACK_LANDED,
}
return funcs
end
-- if IsServer() then
-- function modifier_item_greater_tranquil_boots:OnAttackLanded( event )
-- local parent = self:GetParent()
-- local attacker = event.attacker
-- local attacked_unit = event.target
-- if attacked_unit == parent then
-- local spell = self:GetAbility()
-- --Break Tranquils only in the following cases:
-- --old 1. If the parent attacked a hero
-- --old 2. If the parent was attacked by a hero, boss, hero creep or a player-controlled creep.
-- --((attacker == parent and attacked_unit:IsHero()) or (attacked_unit == parent and (attacker:IsConsideredHero() or attacker:IsControllableByAnyPlayer())))
-- --new 1: if the parent was attacked by a real hero (not an illusion and not a hero creep or boss)
-- if spell:IsBreakable() and attacker:IsRealHero() then
-- spell:UseResources(false, false, true)
-- local cdRemaining = spell:GetCooldownTimeRemaining()
-- if cdRemaining > 0 then
-- parent:AddNewModifier(parent, spell, "modifier_greater_tranquils_broken_debuff", {duration = cdRemaining})
-- end
-- end
-- end
-- end
-- end
function modifier_item_greater_tranquil_boots:GetModifierMoveSpeedBonus_Special_Boots()
-- local spell = self:GetAbility()
-- if self:GetRemainingTime() <= 0 or not spell:IsBreakable() then
-- return self.moveSpd
-- end
-- return self.moveSpdBroken
return self.moveSpd
end
function modifier_item_greater_tranquil_boots:GetModifierPhysicalArmorBonus()
return self.armor
end
function modifier_item_greater_tranquil_boots:GetModifierConstantHealthRegen()
-- local spell = self:GetAbility()
-- if self:GetRemainingTime() <= 0 or not spell:IsBreakable() then
-- return self.healthRegen
-- end
-- return 0
return self.healthRegen
end
---------------------------------------------------------------------------------------------------
--[[ Old Tranquils effect
LinkLuaModifier( "modifier_item_greater_tranquil_boots_sap", "items/farming/greater_tranquil_boots.lua", LUA_MODIFIER_MOTION_NONE )
modifier_item_greater_tranquil_boots_sap = class(ModifierBaseClass)
function modifier_item_greater_tranquil_boots_sap:IsHidden()
return true
end
function modifier_item_greater_tranquil_boots_sap:IsDebuff()
return true
end
function modifier_item_greater_tranquil_boots_sap:IsPurgable()
return false
end
if IsServer() then
function modifier_item_greater_tranquil_boots_sap:OnCreated( event )
local spell = self:GetAbility()
self.sapDamage = spell:GetSpecialValueFor( "creep_sap_damage" )
self:StartIntervalThink( 1.0 )
end
--------------------------------------------------------------------------------
function modifier_item_greater_tranquil_boots_sap:OnRefresh( event )
local spell = self:GetAbility()
self.sapDamage = spell:GetSpecialValueFor( "creep_sap_damage" )
end
--------------------------------------------------------------------------------
function modifier_item_greater_tranquil_boots_sap:OnIntervalThink()
if self.sapDamage then
local parent = self:GetParent()
local caster = self:GetCaster()
local spell = self:GetAbility()
local damage = parent:GetMaxHealth() * ( self.sapDamage * 0.01 )
ApplyDamage( {
victim = parent,
attacker = caster,
damage = damage,
damage_type = DAMAGE_TYPE_MAGICAL,
damage_flags = DOTA_DAMAGE_FLAG_HPLOSS,
ability = spell,
} )
end
end
end
]]
---------------------------------------------------------------------------------------------------
modifier_greater_tranquils_tranquilize_debuff = class(ModifierBaseClass)
function modifier_greater_tranquils_tranquilize_debuff:IsHidden()
return false
end
function modifier_greater_tranquils_tranquilize_debuff:IsDebuff()
return true
end
function modifier_greater_tranquils_tranquilize_debuff:IsPurgable()
return true
end
function modifier_greater_tranquils_tranquilize_debuff:OnCreated()
local parent = self:GetParent()
local ability = self:GetAbility()
local attack_slow = -700
local attack_range = -500
if ability and not ability:IsNull() then
attack_slow = ability:GetSpecialValueFor("melee_attack_speed_slow")
attack_range = ability:GetSpecialValueFor("ranged_bonus_attack_range")
end
if parent:IsRangedAttacker() or parent:IsOAABoss() then
attack_slow = 0
end
if not parent:IsRangedAttacker() then
attack_range = 0
end
if IsServer() then
-- Attack Speed Slow is reduced with Status Resistance
self.attack_slow = parent:GetValueChangedByStatusResistance(attack_slow)
else
self.attack_slow = attack_slow
end
self.attack_range = attack_range
end
modifier_greater_tranquils_tranquilize_debuff.OnRefresh = modifier_greater_tranquils_tranquilize_debuff.OnCreated
function modifier_greater_tranquils_tranquilize_debuff:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_ATTACK_RANGE_BONUS,
}
return funcs
end
function modifier_greater_tranquils_tranquilize_debuff:GetModifierAttackSpeedBonus_Constant()
return self.attack_slow
end
function modifier_greater_tranquils_tranquilize_debuff:GetModifierAttackRangeBonus()
return self.attack_range
end
item_greater_tranquil_boots_2 = class(item_greater_tranquil_boots)
item_greater_tranquil_boots_3 = class(item_greater_tranquil_boots)
item_greater_tranquil_boots_4 = class(item_greater_tranquil_boots)
item_greater_tranquil_boots_5 = class(item_greater_tranquil_boots)
--item_tranquil_origin = class(item_greater_tranquil_boots)
|
return function(button_list, stepstype, skin_params)
local ret = {}
local rots = {
Left = 90,
Down = 0,
Up = 180,
Right = 270,
UpLeft = 135,
UpRight = 225,
DownLeft = 45,
DownRight = 315
}
local tap_redir= {}
for i, button in ipairs(button_list) do
ret[i] = Def.ActorFrame {
InitCommand = function(self)
self:rotationz(rots[button] or 0):draworder(notefield_draw_order.explosion)
end,
WidthSetCommand = function(self, param)
param.column:set_layer_fade_type(self, "FieldLayerFadeType_Explosion")
end,
Def.Sprite {
Texture = "Down explosion.png",
InitCommand = function(self)
self:diffusealpha(0)
end,
ColumnJudgmentCommand= function(self, param)
local diffuse = {
TapNoteScore_W1 = { 1.0, 1.0, 1.0, 1 },
TapNoteScore_W2 = { 1.0, 1.0, 0.9, 1 },
TapNoteScore_W3 = { 0.6, 1.0, 0.8, 1 },
TapNoteScore_W4 = { 0.6, 1.0, 1.0, 1 },
TapNoteScore_W5 = { 1.0, 0.6, 1.0, 1 },
HoldNoteScore_Held = { 1.0, 1.0, 0.7, 1 },
}
local exp_color= diffuse[param.tap_note_score or param.hold_note_score]
if exp_color then
self:stoptweening()
:diffuse(exp_color)
:sleep(0.1)
:decelerate(0.4)
:diffusealpha(0)
end
end
}
}
end
return ret
end
|
if (SERVER) then
AddCSLuaFile()
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
end
if ( CLIENT ) then
SWEP.BobScale = 0
SWEP.SwayScale = 0
SWEP.DrawAmmo = true
SWEP.DrawCrosshair = false
SWEP.ViewModelFOV = 50
SWEP.ViewModelFlip = false
SWEP.CSMuzzleFlashes = true
end
SWEP.Author = "No More Room In Hell"
SWEP.Contact = ""
SWEP.Purpose = ""
SWEP.Instructions = ""
SWEP.Base = "weapon_base"
SWEP.Spawnable = false
SWEP.AdminSpawnable = false
SWEP.Primary.Sound = Sound( "Weapon_AK47.Single" )
SWEP.Primary.Recoil = 1.5
SWEP.Primary.Damage = 40
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.02
SWEP.Primary.Delay = 0.15
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 = false
SWEP.Secondary.Ammo = "none"
SWEP.Melee = {}
SWEP.Melee.Damage = 10
SWEP.Melee.Delay = 1
SWEP.animTable = {}
SWEP.DeployTime = 1
if (CLIENT) then
local matBeam = Material( "effects/lamp_beam" )
local GLOW_MATERIAL = Material("sprites/glow04_noz.vmt")
function SWEP:PostDrawViewModel()
local vm = self.Owner:GetViewModel()
local at = vm:LookupAttachment("nmrih_trace_start")
local atpos = vm:GetAttachment(at)
if (!self.nextRecord or self.nextRecord < CurTime()) then
self.trailPos.insert(atpos.Pos + atpos.Ang:Forward() + atpos.Ang:Up() + atpos.Ang:Right())
self.nextRecord = CurTime() + .03
end
render.SetMaterial( matBeam )
cam.IgnoreZ()
cam.Start3D(EyePos(), EyeAngles())
render.StartBeam( 4 )
render.AddBeam(atpos.Pos + atpos.Ang:Forward() + atpos.Ang:Up() + atpos.Ang:Right(), 8, 1, Color( 255, 255, 255, 255) )
render.AddBeam(self.trailPos[0], 4, 1, Color(255, 255, 255, 255) )
render.AddBeam(self.trailPos[1], 2, 1, Color( 255, 255, 255, 255) )
render.AddBeam(self.trailPos[2], 1, 1, Color( 255, 255, 255, 255) )
render.AddBeam(self.trailPos[3], 0, 1, Color( 255, 255, 255, 255) )
render.EndBeam()
cam.End3D()
end
local posOutput = Vector(0, 0, 0)
local posTarget = Vector(0, 0, 0)
local angOutput = Angle(0, 0, 0)
local angTarget = Angle(0, 0, 0)
local oldAimVec = Vector(0 ,0, 0)
local viewMoveMul = .01
local curStep = 0
local sin, cos = math.sin, math.cos
local clamp = math.Clamp
local function fTime() return FrameTime()*20 end
local function int(delta, from, to)
local intType = type(from)
if intType == "Angle" then
from = util_NormalizeAngles(from)
to = util_NormalizeAngles(to)
end
local out = from + (to-from)*delta
return out
end
local bobPos = Vector()
local swayPos = Vector()
local lateBobPos = Vector()
local restPos = Vector()
local swayLimit = 5
SWEP.aimAngle = Angle()
SWEP.oldAimAngle = Angle()
SWEP.aimDiff = Angle()
SWEP.ironMul = 1
function SWEP:GetViewModelPosition( pos, ang )
local owner = self.Owner
local EP, EA, FT = EyePos(), EyeAngles(), FrameTime()
local PA = owner:GetViewPunchAngles()
local vel = clamp(owner:GetVelocity():Length2D()/owner:GetWalkSpeed(), 0, 1.5)
local rest = 1 - clamp(owner:GetVelocity():Length2D()/20, 0, 1)
posOutput = Vector(0, 0, 0)
curStep = curStep + (vel/math.pi)*(fTime()*2)
local ws = owner:GetWalkSpeed()
self.aimAngle = owner:EyeAngles()
self.aimDiff = self.aimAngle - self.oldAimAngle
for i = 1, 3 do
if (360 - math.abs(self.aimDiff[i]) < 180) then
print(1)
if (self.aimDiff[i] < 0) then
self.aimDiff[i] = self.aimDiff[i] + 360
else
self.aimDiff[i] = self.aimDiff[i] - 360
end
end
end
self.oldAimAngle = self.aimAngle
self.ironMul = int(.1, self.ironMul, (!self.Owner:OnGround() or self:GetCharge() or self:GetSprint()) and (!self.Owner:OnGround() and 0 or .1) or 1)
self.aimDiff = self.aimDiff
local Right = EA:Right()
local Up = EA:Up()
local Forward = EA:Forward()
bobPos[1] = -sin(curStep/2)*vel
bobPos[2] = sin(curStep/4)*vel*1.5
bobPos[3] = sin(curStep)/1.5*vel
restPos[3] = sin(CurTime()*2)*4
restPos[1] = cos(CurTime()*1)*3
swayPos[1] = clamp(int(.1, swayPos[1], self.aimDiff[2]), -swayLimit, swayLimit)
swayPos[3] = clamp(int(.1, swayPos[3], -self.aimDiff[1]), -swayLimit, swayLimit)
for i = 1, 3 do
self.aimDiff[i] = clamp(self.aimDiff[i], -swayLimit, swayLimit)
end
posTarget = bobPos*5*self.ironMul + restPos*rest*self.ironMul + swayPos*10*self.ironMul
posOutput = LerpVector(.05, posOutput, posTarget)
angTarget = self.aimDiff*self.ironMul
angOutput = LerpAngle(.1, angOutput, angTarget)
ang:RotateAroundAxis(ang:Right(), angOutput[1])
ang:RotateAroundAxis(ang:Up(), angOutput[2])
ang:RotateAroundAxis(ang:Forward(), angOutput[3])
pos = pos + posOutput.x * Right
pos = pos + posOutput.y * Forward
pos = pos + posOutput.z * Up
return pos, ang
end
function SWEP:FireAnimationEvent(pos,ang,event)
local eventNum = eventTable[event]
if (eventNum) then
return true
else
print(event)
end
end
end
function SWEP:SetupDataTables()
self:NetworkVar("Float", 2, "Spread")
self:NetworkVar("Float", 1, "NextCharge")
self:NetworkVar("Float", 0, "NextMelee")
self:NetworkVar("Bool", 5, "Attack")
self:NetworkVar("Bool", 4, "Charge")
self:NetworkVar("Bool", 3, "Melee")
self:NetworkVar("Bool", 2, "Holster")
self:NetworkVar("Bool", 1, "Sprint")
self:NetworkVar("Bool", 0, "Reloading")
end
function SWEP:GetAttackAnimation(empty)
return table.Random(self.animTable[ANIM_FIRE][(self:GetCharge() and STATUS_CHARGE or STATUS_NORMAL)])
end
function SWEP:GetSprintAnimation()
return self.animTable[ANIM_SPRINT]
end
function SWEP:GetMeleeAnimation()
return table.Random(self.animTable[ANIM_MELEE])
end
function SWEP:GetChargeAnimation()
return table.Random(self.animTable[ANIM_CHARGE])
end
function SWEP:GetHolsterAnimation()
return self.animTable[ANIM_HOLSTER]
end
function SWEP:GetDeployAnimation()
return self.animTable[ANIM_DEPLOY]
end
function SWEP:GetIdleAnimation()
return self.animTable[ANIM_IDLE][STATUS_NORMAL]
end
function SWEP:Initialize()
if ( SERVER ) then
self:SetNPCMinBurst( 30 )
self:SetNPCMaxBurst( 30 )
self:SetNPCFireRate( 0.01 )
else
self.emitter = ParticleEmitter(Vector(0, 0, 0))
self.trailPos = {
curPos = 0,
[0] = Vector(0, 0, 0),
[1] = Vector(0, 0, 0),
[2] = Vector(0, 0, 0),
[3] = Vector(0, 0, 0),
}
function self.trailPos.insert(vec)
for i = 0, 2 do
self.trailPos[i+1] = self.trailPos[i]
end
self.trailPos[0] = vec
end
end
self:SetWeaponHoldType(self.HoldType)
end
function SWEP:Deploy()
self:PlaySequence(self:GetDeployAnimation())
self:SetNextPrimaryFire(CurTime() + (self.DeployTime or 1))
return true
end
function SWEP:Holster(nextWeapon)
self:SetReloading(false)
self:SetSprint(false)
self:SetMelee(false)
if (self.goHolster) then
self.goHolster = nil
return true
end
self:PlaySequence(self:GetHolsterAnimation())
self:SetHolster(true)
self.nextWeapon = nextWeapon
self.holsterDelay = CurTime() + (self.HolsterTime or .7)
return false
end
function SWEP:Think()
local owner = self.Owner
local vel = owner:GetVelocity():Length()
if (self:GetAttack()) then
if (owner:KeyDown(IN_ATTACK)) then
if (!self:GetCharge() and self:GetNextCharge() < CurTime()) then
self:StartCharge()
end
else
if (self:GetCharge()) then
self:ChargeAttack()
else
self:PrimaryAttack(true)
end
end
end
if (self:GetHolster() == true) then
if (self.holsterDelay and self.holsterDelay < CurTime()) then
owner:ConCommand("use " .. self.nextWeapon:GetClass())
self.goHolster = true
self.holsterDelay = nil
self:SetHolster(false)
end
end
if (owner:OnGround() and owner:KeyDown(IN_SPEED) and vel > owner:GetWalkSpeed()*1.01) then
if (!self:GetSprint()) then
self:GoSprint(true)
end
else
if (self:GetSprint()) then
self:GoSprint(false)
end
end
end
function SWEP:Reload(call)
end
function SWEP:GoSprint(bool)
print(bool)
if (self:GetMelee() != true) then
self:SetAttack(false)
self:SetNextCharge(CurTime())
self:PlaySequence(bool and self:GetSprintAnimation() or self:GetIdleAnimation())
self:SetSprint(bool)
end
end
function SWEP:CanPrimaryAttack()
if (self:GetSprint() == true) then
return false
end
return true
end
function SWEP:CanMeleeAttack()
return (self:GetSprint() != true and self:GetCharge() != true
and self:GetNextMelee() < CurTime())
end
function SWEP:GetPrimaryDelay()
return self.Primary.Delay
end
function SWEP:CanMeleeAttack()
return (self:GetSprint() != true and self:GetNextMelee() < CurTime())
end
function SWEP:MeleeAttack()
if (!self:CanMeleeAttack()) then
return
end
self:SetMelee(true)
timer.Simple(self.MeleeRecoverTime or .7, function()
if (self and IsValid(self)) then
self:SetMelee(false)
end
end)
self:PlaySequence(self:GetIdleAnimation())
timer.Simple(0, function()
self:PlaySequence(self:GetMeleeAnimation())
end)
self:SetNextMelee(CurTime() + self.Melee.Delay)
self:SetNextSecondaryFire(CurTime() + self.Melee.Delay)
end
function SWEP:StartCharge()
self:SetCharge(true)
self:PlaySequence(self:GetIdleAnimation())
timer.Simple(0, function()
self:PlaySequence(self:GetChargeAnimation())
end)
end
function SWEP:PerformAttack()
self.Owner:LagCompensation( true )
-- get the local angle
-- and for 1, 3 and does the trace attack.
-- for the win
-- I like this keyboard so much
self.Owner:LagCompensation( false )
end
function SWEP:ChargeAttack()
self:SetAttack(false)
self:PlaySequence(self:GetIdleAnimation())
timer.Simple(0, function()
print(self:GetAttackAnimation())
self:PlaySequence(self:GetAttackAnimation())
self:SetCharge(false)
end)
end
function SWEP:PrimaryAttack(bool)
self:SetNextCharge(CurTime() + .2)
self:SetAttack(true)
if (bool != true) then
return
end
if (!IsFirstTimePredicted()) then
return
end
if (self.Owner:KeyDown(IN_USE)) then
self:MeleeAttack()
return
end
if (!self:CanPrimaryAttack()) then return end
self.Weapon:SetNextSecondaryFire(CurTime() + self:GetPrimaryDelay())
self.Weapon:SetNextPrimaryFire(CurTime() + self:GetPrimaryDelay())
self:SetAttack(false)
self:PlaySequence(self:GetIdleAnimation())
timer.Simple(0, function()
self:PlaySequence(self:GetAttackAnimation())
end)
end
function SWEP:PlaySequence(name)
if (type(name):lower() == "table") then
name = table.Random(name)
end
local vm = self.Owner:GetViewModel()
local seq = vm:LookupSequence(name)
vm:SetCycle(0)
vm:SendViewModelMatchingSequence(seq)
vm:SetPlaybackRate(1)
end
function SWEP:GetSpread()
return
end
function SWEP:SecondaryAttack()
end
function SWEP:DrawHUD()
end
function SWEP:OnRestore()
self:SetSprint(false)
end
|
mapPanel = modules.game_interface.getMapPanel()
gameRootPanel = modules.game_interface.gameBottomPanel
gameLeftPanel = modules.game_interface.getLeftPanel()
gameTopMenu = modules.client_topmenu.getTopMenu()
function currentViewMode()
return modules.game_interface.currentViewMode
end
healthCircle = nil
manaCircle = nil
expCircle = nil
skillCircle = nil
g_ui.loadUI('game_healthcircle')
healthCircleFront = nil
manaCircleFront = nil
expCircleFront = nil
skillCircleFront = nil
optionPanel = nil
isHealthCircle = not g_settings.getBoolean('healthcircle_hpcircle')
isManaCircle = not g_settings.getBoolean('healthcircle_mpcircle')
isExpCircle = g_settings.getBoolean('healthcircle_expcircle')
isSkillCircle = g_settings.getBoolean('healthcircle_skillcircle')
skillType = g_settings.getString('healthcircle_skilltype')
skillsLoaded = false
distanceFromCenter = g_settings.getNumber('healthcircle_distfromcenter')
opacityCircle = g_settings.getNumber('healthcircle_opacity', 0.7)
if not (skillType == 'magic' or skillType == 'fist' or skillType == 'club' or skillType == 'sword' or skillType == 'axe' or skillType == 'distance' or skillType == 'shielding' or skillType == 'fishing') then
skillType = 'magic'
end
function init()
healthCircle = g_ui.createWidget('HealthCircle', mapPanel)
manaCircle = g_ui.createWidget('ManaCircle', mapPanel)
expCircle = g_ui.createWidget('ExpCircle', mapPanel)
skillCircle = g_ui.createWidget('SkillCircle', mapPanel)
healthCircleFront = g_ui.createWidget('HealthCircleFront', mapPanel)
manaCircleFront = g_ui.createWidget('ManaCircleFront', mapPanel)
expCircleFront = g_ui.createWidget('ExpCircleFront', mapPanel)
skillCircleFront = g_ui.createWidget('SkillCircleFront', mapPanel)
whenMapResizeChange()
initOnHpAndMpChange()
initOnGeometryChange()
initOnLoginChange()
if not isHealthCircle then
healthCircle:setVisible(false)
healthCircleFront:setVisible(false)
end
if not isManaCircle then
manaCircle:setVisible(false)
manaCircleFront:setVisible(false)
end
if not isExpCircle then
expCircle:setVisible(false)
expCircleFront:setVisible(false)
end
if not isSkillCircle then
skillCircle:setVisible(false)
skillCircleFront:setVisible(false)
end
--Add option window in options module
addToOptionsModule()
end
function terminate()
healthCircle:destroy()
healthCircle = nil
manaCircle:destroy()
manaCircle = nil
expCircle:destroy()
expCircle = nil
skillCircle:destroy()
skillCircle = nil
healthCircleFront:destroy()
healthCircleFront = nil
manaCircleFront:destroy()
manaCircleFront = nil
expCircleFront:destroy()
expCircleFront = nil
skillCircleFront:destroy()
skillCircleFront = nil
terminateOnHpAndMpChange()
terminateOnGeometryChange()
terminateOnLoginChange()
--Delete from options module
destroyOptionsModule()
end
-------------------------------------------------
--Scripts----------------------------------------
-------------------------------------------------
function initOnHpAndMpChange()
connect(LocalPlayer, { onHealthChange = whenHealthChange,
onManaChange = whenManaChange,
onSkillChange = whenSkillsChange,
onMagicLevelChange = whenSkillsChange,
onLevelChange = whenSkillsChange })
end
function terminateOnHpAndMpChange()
disconnect(LocalPlayer, { onHealthChange = whenHealthChange,
onManaChange = whenManaChange,
onSkillChange = whenSkillsChange,
onMagicLevelChange = whenSkillsChange,
onLevelChange = whenSkillsChange })
end
function initOnGeometryChange()
connect(mapPanel, { onGeometryChange = whenMapResizeChange })
end
function terminateOnGeometryChange()
disconnect(mapPanel, { onGeometryChange = whenMapResizeChange })
end
function initOnLoginChange()
connect(g_game, { onGameStart = whenMapResizeChange })
end
function terminateOnLoginChange()
disconnect(g_game, { onGameStart = whenMapResizeChange })
end
function whenHealthChange()
if g_game.isOnline() then
local healthPercent = math.floor(g_game.getLocalPlayer():getHealthPercent())
local Yhppc = math.floor(208 * (1 - (healthPercent / 100)))
local rect = { x = 0, y = Yhppc, width = 63, height = 208 }
healthCircleFront:setImageClip(rect)
if healthPercent > 92 then
healthCircleFront:setImageColor("#00BC00")
elseif healthPercent > 60 then
healthCircleFront:setImageColor("#50A150")
elseif healthPercent > 30 then
healthCircleFront:setImageColor("#A1A100")
elseif healthPercent > 8 then
healthCircleFront:setImageColor("#BF0A0A")
elseif healthPercent > 3 then
healthCircleFront:setImageColor("#910F0F")
else
healthCircleFront:setImageColor("#850C0C")
end
healthCircleFront:setY(healthCircle:getY() + Yhppc)
end
end
function whenManaChange()
if g_game.isOnline() then
local manaPercent = math.floor(g_game.getLocalPlayer():getMaxMana() - (g_game.getLocalPlayer():getMaxMana() - g_game.getLocalPlayer():getMana())) * 100 / g_game.getLocalPlayer():getMaxMana()
local Ymppc = math.floor(208 * (1 - (manaPercent / 100)))
local rect = { x = 0, y = Ymppc, width = 63, height = 208 }
manaCircleFront:setImageClip(rect)
manaCircleFront:setY(manaCircle:getY() + Ymppc)
end
end
function whenSkillsChange()
if g_game.isOnline() then
if isExpCircle then
local player = g_game.getLocalPlayer()
local Xexpc = math.floor(208 * (1 - player:getLevelPercent() / 100))
local rect = { x = -1 * Xexpc, y = 0, width = 208, height = 63 }
expCircleFront:setImageClip(rect)
expCircleFront:setX(expCircle:getX() - Xexpc)
end
if isSkillCircle then
local player = g_game.getLocalPlayer()
Xskillpc = 0
if skillType == 'magic' then
Xskillpc = math.floor(208 * (1 - player:getMagicLevelPercent() / 100))
skillCircleFront:setImageColor('#00ffcc')
elseif skillType == 'fist' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(0) / 100))
skillCircleFront:setImageColor('#9900cc')
elseif skillType == 'club' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(1) / 100))
skillCircleFront:setImageColor('#cc3399')
elseif skillType == 'sword' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(2) / 100))
skillCircleFront:setImageColor('#FF7F00')
elseif skillType == 'axe' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(3) / 100))
skillCircleFront:setImageColor('#696969')
elseif skillType == 'distance' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(4) / 100))
skillCircleFront:setImageColor('#A62A2A')
elseif skillType == 'shielding' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(5) / 100))
skillCircleFront:setImageColor('#663300')
elseif skillType == 'fishing' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(6) / 100))
skillCircleFront:setImageColor('#ffff33')
end
local rect = { x = -1 * Xskillpc, y = 0, width = 208, height = 63 }
skillCircleFront:setImageClip(rect)
skillCircleFront:setX(expCircle:getX() - Xskillpc)
end
end
end
function whenMapResizeChange()
if g_game.isOnline() then
local barDistance = 90
if not (math.floor(mapPanel:getHeight() / 2 * 0.2) < 100) then --0.381
barDistance = math.floor(mapPanel:getHeight() / 2 * 0.2)
end
if currentViewMode() == 2 then
healthCircleFront:setX(math.floor(mapPanel:getWidth() / 2 - barDistance - healthCircle:getWidth()) - distanceFromCenter)
manaCircleFront:setX(math.floor(mapPanel:getWidth() / 2 + barDistance) + distanceFromCenter)
healthCircle:setX(math.floor(mapPanel:getWidth() / 2 - barDistance - healthCircle:getWidth()) - distanceFromCenter)
manaCircle:setX(math.floor((mapPanel:getWidth() / 2 + barDistance)) + distanceFromCenter)
healthCircle:setY(mapPanel:getHeight() / 2 - healthCircle:getHeight() / 2 + 0)
manaCircle:setY(mapPanel:getHeight() / 2 - manaCircle:getHeight() / 2 + 0)
if isExpCircle then
expCircleFront:setY(math.floor(mapPanel:getHeight() / 2 - barDistance - expCircle:getHeight()) - distanceFromCenter)
expCircle:setX(math.floor(mapPanel:getWidth() / 2 - expCircle:getWidth() / 2))
expCircle:setY(math.floor(mapPanel:getHeight() / 2 - barDistance - expCircle:getHeight()) - distanceFromCenter)
end
if isSkillCircle then
skillCircleFront:setY(math.floor(mapPanel:getHeight() / 2 + barDistance) + distanceFromCenter)
skillCircle:setX(math.floor(mapPanel:getWidth() / 2 - skillCircle:getWidth() / 2))
skillCircle:setY(math.floor(mapPanel:getHeight() / 2 + barDistance) + distanceFromCenter)
end
else
healthCircleFront:setX(mapPanel:getX() + mapPanel:getWidth() / 2 - healthCircle:getWidth() - barDistance - distanceFromCenter)
manaCircleFront:setX(mapPanel:getX() + mapPanel:getWidth() / 2 + barDistance + distanceFromCenter)
healthCircle:setX(mapPanel:getX() + mapPanel:getWidth() / 2 - healthCircle:getWidth() - barDistance - distanceFromCenter)
manaCircle:setX(mapPanel:getX() + mapPanel:getWidth() / 2 + barDistance + distanceFromCenter)
healthCircle:setY(mapPanel:getY() + mapPanel:getHeight() / 2 - healthCircle:getHeight() / 2)
manaCircle:setY(mapPanel:getY() + mapPanel:getHeight() / 2 - manaCircle:getHeight() / 2)
if isExpCircle then
expCircleFront:setY(mapPanel:getY() + mapPanel:getHeight() / 2 - expCircle:getHeight() - barDistance - distanceFromCenter)
expCircle:setX(mapPanel:getX() + mapPanel:getWidth() / 2 - expCircle:getWidth() / 2)
expCircle:setY(mapPanel:getY() + mapPanel:getHeight() / 2 - expCircle:getHeight() - barDistance - distanceFromCenter)
end
if isSkillCircle then
skillCircleFront:setY(mapPanel:getY() + mapPanel:getHeight() / 2 + barDistance + distanceFromCenter)
skillCircle:setX(mapPanel:getX() + mapPanel:getWidth() / 2 - skillCircle:getWidth() / 2)
skillCircle:setY(mapPanel:getY() + mapPanel:getHeight() / 2 + barDistance + distanceFromCenter)
end
end
whenHealthChange()
whenManaChange()
if isExpCircle or isSkillCircle then
whenSkillsChange()
end
end
end
-------------------------------------------------
--Controls---------------------------------------
-------------------------------------------------
function setHealthCircle(value)
value = toboolean(value)
isHealthCircle = value
if value then
healthCircle:setVisible(true)
healthCircleFront:setVisible(true)
whenMapResizeChange()
else
healthCircle:setVisible(false)
healthCircleFront:setVisible(false)
end
g_settings.set('healthcircle_hpcircle', not value)
end
function setManaCircle(value)
value = toboolean(value)
isManaCircle = value
if value then
manaCircle:setVisible(true)
manaCircleFront:setVisible(true)
whenMapResizeChange()
else
manaCircle:setVisible(false)
manaCircleFront:setVisible(false)
end
g_settings.set('healthcircle_mpcircle', not value)
end
function setExpCircle(value)
value = toboolean(value)
isExpCircle = value
if value then
expCircle:setVisible(true)
expCircleFront:setVisible(true)
whenMapResizeChange()
else
expCircle:setVisible(false)
expCircleFront:setVisible(false)
end
g_settings.set('healthcircle_expcircle', value)
end
function setSkillCircle(value)
value = toboolean(value)
isSkillCircle = value
if value then
skillCircle:setVisible(true)
skillCircleFront:setVisible(true)
whenMapResizeChange()
else
skillCircle:setVisible(false)
skillCircleFront:setVisible(false)
end
g_settings.set('healthcircle_skillcircle', value)
end
function setSkillType(skill)
if not skillsLoaded then
return
end
if skill == 'magic' or skill == 'fist' or skill == 'club' or skill == 'sword' or skill == 'axe' or skill == 'distance' or skill == 'shielding' or skill == 'fishing' then
skillType = skill
whenMapResizeChange()
g_settings.set('healthcircle_skilltype', skill)
else
if not skillType then
skillType = 'magic'
whenMapResizeChange()
g_settings.set('healthcircle_skilltype', 'magic')
end
end
end
function setDistanceFromCenter(value)
distanceFromCenter = value
whenMapResizeChange()
g_settings.set('healthcircle_distfromcenter', value)
end
function setCircleOpacity(value)
healthCircle:setOpacity(value)
healthCircleFront:setOpacity(value)
manaCircle:setOpacity(value)
manaCircleFront:setOpacity(value)
expCircle:setOpacity(value)
expCircleFront:setOpacity(value)
skillCircle:setOpacity(value)
skillCircleFront:setOpacity(value)
g_settings.set('healthcircle_opacity', value)
end
-------------------------------------------------
--Option Settings--------------------------------
-------------------------------------------------
optionPanel = nil
healthCheckBox = nil
manaCheckBox = nil
experienceCheckBox = nil
skillCheckBox = nil
chooseSkillComboBox = nil
distFromCenLabel = nil
distFromCenScrollbar = nil
opacityLabel = nil
opacityScrollbar = nil
function addToOptionsModule()
--Add to options module
optionPanel = g_ui.loadUI('option_healthcircle')
modules.client_options.addTab(tr('Hp Mp Circle'), optionPanel, '/game_healthcircle/img_game_healthcircle/hp_mp_circle')
--UI values
healthCheckBox = optionPanel:recursiveGetChildById('healthCheckBox')
manaCheckBox = optionPanel:recursiveGetChildById('manaCheckBox')
experienceCheckBox = optionPanel:recursiveGetChildById('experienceCheckBox')
skillCheckBox = optionPanel:recursiveGetChildById('skillCheckBox')
chooseSkillComboBox = optionPanel:recursiveGetChildById('chooseSkillComboBox')
distFromCenLabel = optionPanel:recursiveGetChildById('distFromCenLabel')
distFromCenScrollbar = optionPanel:recursiveGetChildById('distFromCenScrollbar')
opacityLabel = optionPanel:recursiveGetChildById('opacityLabel')
opacityScrollbar = optionPanel:recursiveGetChildById('opacityScrollbar')
--ComboBox start values
chooseSkillComboBox:addOption('magic')
chooseSkillComboBox:addOption('fist')
chooseSkillComboBox:addOption('club')
chooseSkillComboBox:addOption('sword')
chooseSkillComboBox:addOption('axe')
chooseSkillComboBox:addOption('distance')
chooseSkillComboBox:addOption('shielding')
chooseSkillComboBox:addOption('fishing')
--Set values
healthCheckBox:setChecked(isHealthCircle)
manaCheckBox:setChecked(isManaCircle)
experienceCheckBox:setChecked(isExpCircle)
skillCheckBox:setChecked(isSkillCircle)
chooseSkillComboBox:setOption(skillType)
--Prevent skill overwritten before initialize
skillsLoaded = true
distFromCenLabel:setText('Distance: ' .. distanceFromCenter)
distFromCenScrollbar:setValue(distanceFromCenter)
opacityLabel:setText('Opacity: ' .. opacityCircle)
opacityScrollbar:setValue(opacityCircle * 100)
end
function destroyOptionsModule()
healthCheckBox = nil
manaCheckBox = nil
experienceCheckBox = nil
skillCheckBox = nil
chooseSkillComboBox = nil
distFromCenLabel = nil
distFromCenScrollbar = nil
opacityLabel = nil
opacityScrollbar = nil
modules.client_options.removeTab('Hp Mp Circle')
optionPanel = nil
end
|
STRINGS.TOTOORIAST = {}
STRINGS.NAMES.TOTOORIASTAFF1 = "托托莉的法杖Lv1 破棍"
STRINGS.RECIPE_DESC.TOTOORIASTAFF1 = "cosplay经常会用到的破棍"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.TOTOORIASTAFF1 = "感觉就像拿着一根塑料棍"
STRINGS.NAMES.TOTOORIASTAFF2 = "托托莉的法杖Lv2 工具"
STRINGS.RECIPE_DESC.TOTOORIASTAFF2 = "集斧头矿锄砍刀锤子铲子于一身"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.TOTOORIASTAFF2 = "再也不用带一身的工具了"
STRINGS.NAMES.TOTOORIASTAFF3 = "托托莉的法杖Lv3 加速"
STRINGS.RECIPE_DESC.TOTOORIASTAFF3 = "还能和步行手杖一样的加速"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.TOTOORIASTAFF3 = "值得一年四季都拿在手上"
STRINGS.NAMES.TOTOORIASTAFF4 = "托托莉的法杖Lv4 冰冻"
STRINGS.RECIPE_DESC.TOTOORIASTAFF4 = "远程攻击,会冻住,能灭火"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.TOTOORIASTAFF4 = "冻不住自己,冻不住时间......"
STRINGS.NAMES.TOTOORIASTAFF5GREEN = "托托莉的法杖Lv5 绿"
STRINGS.RECIPE_DESC.TOTOORIASTAFF5GREEN = "三分之一的概率复制一个物品(仅限可制造物品)"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.TOTOORIASTAFF5GREEN = "很贵的,要小心用才行"
STRINGS.NAMES.TOTOORIASTAFF5ORANGE = "托托莉的法杖Lv5 橙"
STRINGS.RECIPE_DESC.TOTOORIASTAFF5ORANGE = "顺风,瞬移"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.TOTOORIASTAFF5ORANGE = "拿起来就感觉身体变轻了"
STRINGS.NAMES.TOTOORIASTAFF5YELLOW = "托托莉的法杖Lv5 黄"
STRINGS.RECIPE_DESC.TOTOORIASTAFF5YELLOW = "永久的光照,不需要装备上"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.TOTOORIASTAFF5YELLOW = "会发光的法杖才叫法杖。就差不能变大了......"
STRINGS.NAMES.totooria = "托托莉"
STRINGS.CHARACTER_TITLES.totooria = "托托莉.赫尔蒙德"
STRINGS.CHARACTER_NAMES.totooria = "托托莉"
STRINGS.CHARACTER_DESCRIPTIONS.totooria = "*喜欢读书\n*拥有特别的生存技能\n*自带可升级的法杖"
STRINGS.CHARACTER_QUOTES.totooria = "不知道自己在寻找着什么"
STRINGS.TTRSTRINGS = {
[1] = "等级提升啦!",
[2] = "获得特技[友善]",
[3] = "获得特技[大厨]",
[4] = "获得特技[巧手]",
[5] = "获得特技[学者]",
[6] = "现在有 ",
[7] = " 个技能点",
[8] = "按 K 查看加点方向",
[9] = "等级太低了,不能重置技能点",
[10] = "技能点重置了!",
[11] = "失去特技[巧手]",
[12] = "失去特技[大厨]",
[13] = "失去特技[友善]",
[14] = "失去特技[学者]",
[15] = "现在是 Lv",
[16] = " 有 ",
[17] = "等级 ",
[18] = "Lv",
[19] = "幸运加成 ",
[20] = "%",
[21] = "攻击加成 ",
[22] = "移速加成 ",
[23] = "血量加成 ",
[24] = "幸运提升了 10%",
[25] = "按 J 查看加点明细",
[26] = "没有技能点了",
[27] = "移速提升了 2.5%",
[28] = "攻击力提升了 5%",
[29] = "血量提升了 8%",
[30] = "按上键增加幸运 10.0%",
[31] = "按左键增加攻击 5.00%",
[32] = "按下键增加移速 2.50%",
[33] = "按右键增加血量 6.25",
[34] = "剩余技能点 ",
[35] = "那不能复制!"
}
|
Log = XLAF.Public.Log
MgrAds = XLAF.Public.MgrAds
MgrAssetBundle = XLAF.Public.MgrAssetBundle
MgrAudio = XLAF.Public.MgrAudio
MgrBackdoor = XLAF.Public.MgrBackdoor
MgrCoroutine = XLAF.Public.MgrCoroutine
MgrData = XLAF.Public.MgrData
MgrFPS = XLAF.Public.MgrFPS
MgrLevel = XLAF.Public.MgrLevel
MgrLoading = XLAF.Public.MgrLoading
MgrMultiLanguage = XLAF.Public.MgrMultiLanguage
MgrPopup = XLAF.Public.MgrPopup
MgrScene = XLAF.Public.MgrScene
MgrTextureSheet = XLAF.Public.MgrTextureSheet
ModCompress = XLAF.Public.ModCompress
ModDispatcher = XLAF.Public.ModDispatcher
ModEncryption = XLAF.Public.ModEncryption
ModUIUtils = XLAF.Public.ModUIUtils
ModUtils = XLAF.Public.ModUtils
SceneObject = XLAF.Public.SceneObject
Storyboard = XLAF.Public.Storyboard
XLAF_Event = XLAF.Public.XLAF_Event
XLAF_UIEvent = XLAF.Public.XLAF_UIEvent
XLAFEventTriggerListener = XLAF.Public.XLAFEventTriggerListener
XLAFMain = XLAF.Public.XLAFMain
BackdoorDialog = XLAF.Private.BackdoorDialog
SceneParams = XLAF.Private.SceneParams
|
local mod = DBM:NewMod(2036, "DBM-Party-BfA", 1, 968)
local L = mod:GetLocalizedStrings()
mod:SetRevision("2019043053001")
mod:SetCreatureID(122965)
mod:SetEncounterID(2085)
mod:SetZone()
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_AURA_APPLIED 250585",
"SPELL_CAST_START 250258",
"SPELL_CAST_SUCCESS 250368 259572 250241",
"SPELL_PERIODIC_DAMAGE 250585",
"SPELL_PERIODIC_MISSED 250585",
"UNIT_DIED"
)
--ability.id = 250258 and type = "begincast" or (ability.id = 250368 or ability.id = 259572 or ability.id = 250241) and type = "cast" or target.id = 125977 and type = "death"
--TODO, stench says it's interruptable but cannot verify this. When I determine what to do with it, improve warning
local warnPhase2 = mod:NewPhaseAnnounce(2, 2, nil, nil, nil, nil, nil, 2)
local warnTotemsLeft = mod:NewAddsLeftAnnounce(250190, 2, 250192)
--local warnNoxiousStench = mod:NewSpellAnnounce(250368, 3)
local specWarnLeap = mod:NewSpecialWarningDodge(250258, nil, nil, nil, 2, 2)
local specWarnNoxiousStench = mod:NewSpecialWarningInterrupt(250368, "HasInterrupt", nil, nil, 1, 2)
local specWarnGTFO = mod:NewSpecialWarningGTFO(250585, nil, nil, nil, 1, 8)
local timerLeapCD = mod:NewCDTimer(6, 250258, nil, nil, nil, 3)--6 uness delayed by stentch, then 8
local timerNoxiousStenchCD = mod:NewCDTimer(18.2, 250368, nil, nil, nil, 4, nil, DBM_CORE_INTERRUPT_ICON..DBM_CORE_DISEASE_ICON)
mod.vb.totemRemaining = 3
mod.vb.phase = 1
function mod:OnCombatStart(delay)
self.vb.totemRemaining = 3
self.vb.phase = 1
timerLeapCD:Start(2-delay)
timerNoxiousStenchCD:Start(6-delay)
end
function mod:SPELL_AURA_APPLIED(args)
local spellId = args.spellId
if spellId == 250585 and args:IsPlayer() and self:AntiSpam(3, 1) then
specWarnGTFO:Show(args.spellName)
specWarnGTFO:Play("watchfeet")
end
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 195254 then
specWarnLeap:Show()
specWarnLeap:Play("watchstep")
timerLeapCD:Start()
end
end
function mod:SPELL_CAST_SUCCESS(args)
local spellId = args.spellId
if spellId == 250368 or spellId == 259572 then
if self:CheckInterruptFilter(args.sourceGUID, false, true) then
specWarnNoxiousStench:Show(args.sourceName)
specWarnNoxiousStench:Play("kickcast")
end
if self.vb.phase == 2 then
timerNoxiousStenchCD:Start(18.2)
else
timerNoxiousStenchCD:Start(20.6)
timerLeapCD:AddTime(2)--Consistent with early alpha, might use more complex code if this becomes inconsistent
end
elseif spellId == 250241 then
self.vb.phase = 2
timerNoxiousStenchCD:Stop()
timerLeapCD:Stop()
warnPhase2:Show()
warnPhase2:Play("ptwo")
end
end
function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId, spellName)
if spellId == 250585 and destGUID == UnitGUID("player") and self:AntiSpam(3, 1) then
specWarnGTFO:Show(spellName)
specWarnGTFO:Play("watchfeet")
end
end
mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE
function mod:UNIT_DIED(args)
local cid = self:GetCIDFromGUID(args.destGUID)
if cid == 125977 then--Reanimation Totem
self.vb.totemRemaining = self.vb.totemRemaining - 1
if self.vb.totemRemaining > 0 then
warnTotemsLeft:Show(self.vb.totemRemaining)
end
end
end
--[[
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, spellId)
if spellId == 257939 then
end
end
--]]
|
Locales['es'] = {
['invoices'] = 'facturas',
['received_invoice'] = 'has ~r~recibido~s~ una multa',
['paid_invoice'] = 'has ~g~pagado~s~ una multa de ~r~€%s~s~',
['received_payment'] = 'has ~g~recibido~s~ un pago de ~g~€%s~s~',
['player_not_online'] = 'el jugador no está conectado',
['no_money'] = 'you do not have enough money to pay this bill',
['target_no_money'] = 'the player ~r~does not~s~ have enough money to pay the bill!',
}
|
return {
{
StatKey = 'CommonAttackWarhammer',
Group = 'Base',
Stat = 'Attack',
Min = '2',
Max = '8',
Likelihood = '',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'CommonAttackWarhammer',
Group = 'Bonus1',
Stat = 'CritChance',
Min = '2',
Max = '6',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'CommonAttackWarhammer',
Group = 'Bonus1',
Stat = 'CDR',
Min = '2',
Max = '6',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'UncommonAttackWarhammer',
Group = 'Base',
Stat = 'Attack',
Min = '8',
Max = '15',
Likelihood = '',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'UncommonAttackWarhammer',
Group = 'Bonus1',
Stat = 'CritChance',
Min = '6',
Max = '10',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'UncommonAttackWarhammer',
Group = 'Bonus1',
Stat = 'Haste',
Min = '6',
Max = '10',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'UncommonAttackWarhammer',
Group = 'Bonus2',
Stat = 'Attack',
Min = '6',
Max = '10',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'UncommonAttackWarhammer',
Group = 'Bonus2',
Stat = 'CritChance',
Min = '6',
Max = '10',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Base',
Stat = 'Attack',
Min = '15',
Max = '22',
Likelihood = '',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Bonus1',
Stat = 'Attack',
Min = '10',
Max = '14',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Bonus1',
Stat = 'Haste',
Min = '10',
Max = '14',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Bonus1',
Stat = 'CritChance',
Min = '10',
Max = '14',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Bonus2',
Stat = 'CritChance',
Min = '10',
Max = '14',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Bonus2',
Stat = 'Haste',
Min = '10',
Max = '14',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Bonus2',
Stat = 'CDR',
Min = '10',
Max = '14',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Bonus3',
Stat = 'Attack',
Min = '10',
Max = '14',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Bonus3',
Stat = 'Haste',
Min = '10',
Max = '14',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
{
StatKey = 'RareAttackWarhammer',
Group = 'Bonus3',
Stat = 'CritChance',
Min = '10',
Max = '14',
Likelihood = '100',
['Author Notes (will be ignored by script)'] = '',
},
}
|
local name, ns = ...
local path = 'Interface\\AddOns\\AbuEssentials\\Textures\\'
--[[
[1] = path..'Font\\Atarian.ttf',
[2] = path..'Font\\Defused.ttf',
[3] = path..'Font\\AccPrec.ttf',
[4] = path..'Font\\ExpresswayFree.ttf',
--]]
-- Settings for this addon
-- Hiding blizzard power auras:
ns.Config.HidePowa[135286] = true -- Teeth n claw druid
ns.Config.HidePowa[93622] = true -- Mangle
ns.Config.EnableMailModule = true -- Enable take all mail button
ns.Config.Tooltip.Enable = true -- Enable tooltip skinning
ns.Config.Tooltip.ShowTitle = false -- Show player title
ns.Config.Tooltip.RoleIcon = true -- Show a role icon
ns.Config.Tooltip.ShowGuildRanks = true -- Show guild rank of a player
ns.Config.Tooltip.FontSize = 13 -- Fontsize
ns.Config.Tooltip.Position = {'BOTTOMRIGHT', UIParent, 'BOTTOMRIGHT', -57, 190}
-- THings to do when visiting a vendor, hold shift to ignore all.
ns.Config.Vendor.AutoRepair = true -- Repair automagically when visiting a vendor
ns.Config.Vendor.SellGreyCrap = true -- Sells ALL grey stuff
ns.Config.Vendor.BuyEssentials = true -- Restock a set items for your character, like Tome of clear mind
ns.Config.SkinMinimap = true -- Skin the minimap
ns.Config.PopBubbles = true -- Remove border around speech bubbles
-- Global setting for all abu addons. Mainly colors, textures, fonts etc.
ns.GlobalConfig.Colors.Frame = { 0.5, 0.5, 0.4 } -- Colors to skin the blizzard things.
ns.GlobalConfig.Colors.Border = { 0.9, 0.9, 0.8 } -- Colors for button borders
ns.GlobalConfig.Colors.Interrupt = { .9, .8, .2 }
ns.GlobalConfig.Fonts.Damage = path..'Font\\Defused.ttf'
ns.GlobalConfig.Fonts.Normal = path..'Font\\ExpresswayFree.ttf'
ns.GlobalConfig.Fonts.Actionbar = path..'Font\\AccPrec.ttf'
ns.GlobalConfig.Fonts.Fancy = path..'Font\\Atarian.ttf'
ns.GlobalConfig.Statusbar.Normal = path..'statusbarTex.tga'
ns.GlobalConfig.Statusbar.Light = path.."tex.tga"
ns.GlobalConfig.IconTextures.Normal = path..'Border\\textureNormal'
ns.GlobalConfig.IconTextures.Background = path..'Border\\textureBackground'
ns.GlobalConfig.IconTextures.Highlight = path..'Border\\textureHighlight'
ns.GlobalConfig.IconTextures.Checked = path..'Border\\textureChecked'
ns.GlobalConfig.IconTextures.Pushed = path..'Border\\texturePushed'
ns.GlobalConfig.IconTextures.Shadow = path..'Border\\textureShadow'
ns.GlobalConfig.IconTextures.White = path..'Border\\textureWhite'
ns.GlobalConfig.IconTextures.Debuff = path..'Border\\textureDebuff'
ns.GlobalConfig.IconTextures.Flash = nil
|
--交差する魂
--Exchanging Souls
--scripted by TOP & Lyris & mercury233
function c100272003.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(100272003,0))
e1:SetCategory(CATEGORY_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CANNOT_INACTIVATE+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CANNOT_NEGATE)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER)
e1:SetCountLimit(1,100272003+EFFECT_COUNT_CODE_OATH)
e1:SetCondition(c100272003.sumcon)
e1:SetTarget(c100272003.sumtg)
e1:SetOperation(c100272003.sumop)
c:RegisterEffect(e1)
end
function c100272003.sumcon(e,tp,eg,ep,ev,re,r,rp)
local ph=Duel.GetCurrentPhase()
return (ph==PHASE_MAIN1 or ph==PHASE_MAIN2)
end
function c100272003.sumfilter(c,ec)
if not c:IsRace(RACE_DIVINE) then return false end
local e1=Effect.CreateEffect(ec)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_ADD_EXTRA_TRIBUTE)
e1:SetRange(LOCATION_HAND)
e1:SetTargetRange(0,LOCATION_MZONE)
e1:SetValue(POS_FACEUP_ATTACK+POS_FACEDOWN_DEFENSE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
c:RegisterEffect(e1)
local res=c:IsSummonable(true,nil,1)
e1:Reset()
return res
end
function c100272003.sumtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c100272003.sumfilter,tp,LOCATION_HAND,0,1,nil,e:GetHandler()) end
Duel.SetOperationInfo(0,CATEGORY_SUMMON,nil,1,0,0)
end
function c100272003.sumop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SUMMON)
local tc=Duel.SelectMatchingCard(tp,c100272003.sumfilter,tp,LOCATION_HAND,0,1,1,nil,c):GetFirst()
if tc then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_ADD_EXTRA_TRIBUTE)
e1:SetRange(LOCATION_HAND)
e1:SetTargetRange(0,LOCATION_MZONE)
e1:SetValue(POS_FACEUP_ATTACK+POS_FACEDOWN_DEFENSE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
Duel.Summon(tp,tc,true,nil,1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_CHAIN_END)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetOperation(c100272003.limitop)
e2:SetLabelObject(tc)
Duel.RegisterEffect(e2,tp)
end
end
function c100272003.cfilter(c,tp)
return c:GetPreviousControler()==1-tp
end
function c100272003.limitop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=e:GetLabelObject()
local g=tc:GetMaterial()
if g and g:IsExists(c100272003.cfilter,1,nil,tp) then
--can't activate effects
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_CHAINING)
e2:SetCondition(c100272003.regcon)
e2:SetOperation(c100272003.regop)
e2:SetReset(RESET_PHASE+PHASE_END,2)
Duel.RegisterEffect(e2,tp)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e3:SetCode(EFFECT_CANNOT_ACTIVATE)
e3:SetTargetRange(1,0)
e3:SetCondition(c100272003.actcon)
e3:SetValue(c100272003.aclimit)
e3:SetReset(RESET_PHASE+PHASE_END,2)
Duel.RegisterEffect(e3,tp)
end
e:Reset()
end
function c100272003.regcon(e,tp,eg,ep,ev,re,r,rp)
return ep==tp and not re:GetHandler():IsRace(RACE_DIVINE)
end
function c100272003.regop(e,tp,eg,ep,ev,re,r,rp)
Duel.RegisterFlagEffect(tp,100272003,RESET_PHASE+PHASE_END,2,0,1)
end
function c100272003.actcon(e)
local tp=e:GetHandlerPlayer()
return Duel.GetFlagEffect(tp,100272003)>0
end
function c100272003.aclimit(e,re,tp)
return not re:GetHandler():IsRace(RACE_DIVINE)
end
|
--[[
TheNexusAvenger
Displays the player list during the active round.
Does not handle the end of rounds.
--]]
local STAT_TEXT_ASPECT_RATIO = 1.8
local USERNAME_SIZE_ASPECT_RATIO = 8
local LEADERBOARD_ENTRY_HEIGHT_RELATIVE = 0.035
local MINIMUM_LEADERSTAT_HEIGHT = 24
local MAX_SCREEN_WIDTH_RELATIVE = 0.2
local TRIANGLE_ASPECT_RATIO = 0.2
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local StarterGui = game:GetService("StarterGui")
StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.PlayerList,false)
local ReplicatedStorageProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ReplicatedStorage"))
local CurrentRoundState = ReplicatedStorageProject:GetResource("State.CurrentRound")
local RoundPlayerlist = ReplicatedStorageProject:GetResource("UI.PlayerList.RoundPlayerlist")
--Connect creating the uesr interface.
CurrentRoundState:ConnectTo("CurrentRound",{
Start = function(self,CurrentRound)
--Wait for the round to start.
while CurrentRound.State == "LOADING" do
CurrentRound:GetPropertyChangedSignal("State"):Wait()
end
if not self:IsActive() then return end
--Get the visible stats.
local Stats = {}
for _,StatData in pairs(CurrentRound.RoundStats) do
if StatData.ShowInLeaderstats then
table.insert(Stats,StatData)
end
end
--Create the playerlist.
local PlayerListContainer = Instance.new("ScreenGui")
PlayerListContainer.Name = "PlayerList"
PlayerListContainer.ResetOnSpawn = false
PlayerListContainer.Parent = Players.LocalPlayer:WaitForChild("PlayerGui")
self.CurrentPlayerListContainer = PlayerListContainer
local PlayerListAdorn = Instance.new("Frame")
PlayerListAdorn.Size = UDim2.new(0.3,0,0.075,0)
PlayerListAdorn.Position = UDim2.new(1,0,0,0)
PlayerListAdorn.BackgroundTransparency = 1
PlayerListAdorn.Parent = PlayerListContainer
local Playerlist = RoundPlayerlist.new(CurrentRound.Players,CurrentRound.EliminatedPlayerStats)
Playerlist.Stats = Stats
Playerlist.TeamColors = CurrentRound.TeamColors
Playerlist.Parent = PlayerListAdorn
self.CurrentPlayerlist = Playerlist
--[[
Updates the size of the adorn.
--]]
local function UpdateAdornSize()
--Determine the sizes of the leaderstats.
local ScreenSize = PlayerListContainer.AbsoluteSize
local LeaderstatsEntrySizeY = ScreenSize.Y * LEADERBOARD_ENTRY_HEIGHT_RELATIVE
local StatsWidth,UsernameWidth = LeaderstatsEntrySizeY * Playerlist.TotalStats * STAT_TEXT_ASPECT_RATIO,LeaderstatsEntrySizeY * USERNAME_SIZE_ASPECT_RATIO
local TotalWidth = StatsWidth + UsernameWidth
local MaxWidth = ScreenSize.X * MAX_SCREEN_WIDTH_RELATIVE
local SizeMultiplier = math.min(MaxWidth/TotalWidth,1)
if SizeMultiplier * LeaderstatsEntrySizeY < MINIMUM_LEADERSTAT_HEIGHT then
SizeMultiplier = MINIMUM_LEADERSTAT_HEIGHT/LeaderstatsEntrySizeY
end
PlayerListAdorn.Size = UDim2.new(0,TotalWidth * SizeMultiplier,0,LeaderstatsEntrySizeY * SizeMultiplier)
PlayerListAdorn.AnchorPoint = Vector2.new(1 - ((TRIANGLE_ASPECT_RATIO * LeaderstatsEntrySizeY)/TotalWidth),0)
PlayerListAdorn.Visible = (TotalWidth * SizeMultiplier <= ScreenSize.X * 2/5)
end
--Connect the size-related events.
Playerlist:GetPropertyChangedSignal("TotalStats"):Connect(UpdateAdornSize)
PlayerListContainer:GetPropertyChangedSignal("AbsoluteSize"):Connect(UpdateAdornSize)
UpdateAdornSize()
--Connect the round events.
CurrentRound:GetPropertyChangedSignal("TeamColors"):Connect(function()
Playerlist.TeamColors = CurrentRound.TeamColors
end)
--Wait for the round to end and destroy the player list.
while CurrentRoundState.CurrentRound == CurrentRound and CurrentRound.State ~= "ENDED" do
CurrentRound:GetPropertyChangedSignal("State"):Wait()
end
if not self:IsActive() then return end
self:Clear()
end,
Clear = function(self)
if self.CurrentPlayerListContainer then
self.CurrentPlayerListContainer:Destroy()
self.CurrentPlayerListContainer = nil
end
if self.CurrentPlayerlist then
self.CurrentPlayerlist:Destroy()
self.CurrentPlayerlist = nil
end
end,
})
|
return {'anschluss','anschluss','ansicht','ansichtkaart','ansjovis','ansjovisfilet','ansjovisvangst','ansi','ans','anse','ansems','ansink','ansing','ansari','ansjovissen','ansichten','ansichtkaarten','ansjovisfilets','ans','anses','ansichtkaartje','ansichtkaartjes'}
|
AddCSLuaFile()
SWEP.Base = "weapon_gwbase"
SWEP.Name = "Tumble"
SWEP.AbilitySound = "WeaponFrag.Roll"
SWEP.AbilityRange = 500
SWEP.AbilityShowTargetHalos = true
SWEP.AbilityDuration = 3
SWEP.AbilityCastTime = 0.5
SWEP.AbilityDescription = "Looks like somebody forgot to tie their shoe laces.\n\nAll Seekers within $AbilityRange will collapse and tumble forward."
function SWEP:Ability()
local targets = self:GetSeekersInRange(self.AbilityRange, true)
-- dont use ability if no target was found
if #targets == 0 then
return GW_ABILTY_CAST_ERROR_NO_TARGET
end
if not SERVER then return end
for _, target in pairs(targets) do
local effectdata = EffectData()
effectdata:SetEntity(self:GetOwner())
effectdata:SetOrigin(target:GetPos() + target:GetVelocity() / 2)
effectdata:SetMagnitude(self.AbilityCastTime)
util.Effect("gw_tumble", effectdata, true, true)
timer.Simple(self.AbilityCastTime, function()
if IsValid(target) and target:Alive() then
target:GWStartRagdoll(Vector(0, 0, 50), 9)
end
end)
timer.Simple(self.AbilityDuration, function()
if IsValid(target) then
target:GWEndRagdoll()
end
end)
end
end
|
local bullets = require "org-bullets"
bullets.setup {
symbols = { "◉", "○", "✸", "✿" }
-- or a function that receives the defaults and returns a list
-- symbols = function(default_list)
-- table.insert(default_list, "♥")
-- return default_list
-- end,
}
|
function register_carpet(name, recipe, desc, texture, group)
minetest.register_node(":carpet:"..name, {
description = desc,
tiles = {texture},
paramtype = "light",
drawtype = "nodebox",
groups = group,
node_box = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, -0.5+0.0625, 0.5}
},
})
minetest.register_craft({
output = 'carpet:'..name..' 32',
recipe = {
{recipe, recipe},
}
})
end
register_carpet("black_wool", "wool:black", "Black Carpet", "wool_black.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("blue_wool", "wool:blue", "Blue Carpet", "wool_blue.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("brown_wool", "wool:brown", "Brown Carpet", "wool_brown.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("cyan_wool", "wool:cyan", "Cyan Carpet", "wool_cyan.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("dark_green_wool", "wool:dark_green", "Dark Green Carpet", "wool_dark_green.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("dark_grey_wool", "wool:dark_grey", "Dark Grey Carpet", "wool_dark_grey.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("green_wool", "wool:green", "Green Carpet", "wool_green.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("grey_wool", "wool:grey", "Grey Carpet", "wool_grey.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("magenta_wool", "wool:magenta", "Magenta Carpet", "wool_magenta.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("orange_wool", "wool:orange", "Orange Carpet", "wool_orange.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("pink_wool", "wool:pink", "Pink Carpet", "wool_pink.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("red_wool", "wool:red", "Red Carpet", "wool_red.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("violet_wool", "wool:violet", "Violet Carpet", "wool_violet.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("white_wool", "wool:white", "White Carpet", "wool_white.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
register_carpet("yellow_wool", "wool:yellow", "Yellow Carpet", "wool_yellow.png", {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1})
|
#!/usr/bin/env lua
-- Run the Nelua compiler.
os.exit(require'nelua.runner'.run(arg))
|
--This provides wrappers to prevent themes that used functions that are now unavailable from crashing.
Scoring={}
setmetatable(Scoring,{__index=function() return function() lua.ReportScriptError("Lua scoring unimplemented") end end})
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "ai_translations.lua" )
AddCSLuaFile( "sh_anim.lua" )
AddCSLuaFile( "shared.lua" )
include( "ai_translations.lua" )
include( "sh_anim.lua" )
include( "shared.lua" )
SWEP.Weight = 5 -- Decides whether we should switch from/to this
SWEP.AutoSwitchTo = true -- Auto switch to if we pick it up
SWEP.AutoSwitchFrom = true -- Auto switch from if you pick up a better weapon
--[[---------------------------------------------------------
Name: OnRestore
Desc: The game has just been reloaded. This is usually the right place
to call the GetNW* functions to restore the script's values.
-----------------------------------------------------------]]
function SWEP:OnRestore()
end
--[[---------------------------------------------------------
Name: AcceptInput
Desc: Accepts input, return true to override/accept input
-----------------------------------------------------------]]
function SWEP:AcceptInput( name, activator, caller, data )
return false
end
--[[---------------------------------------------------------
Name: KeyValue
Desc: Called when a keyvalue is added to us
-----------------------------------------------------------]]
function SWEP:KeyValue( key, value )
end
--[[---------------------------------------------------------
Name: Equip
Desc: A player or NPC has picked the weapon up
-----------------------------------------------------------]]
function SWEP:Equip( newOwner )
end
--[[---------------------------------------------------------
Name: EquipAmmo
Desc: The player has picked up the weapon and has taken the ammo from it
The weapon will be removed immidiately after this call.
-----------------------------------------------------------]]
function SWEP:EquipAmmo( newOwner )
end
--[[---------------------------------------------------------
Name: OnDrop
Desc: Weapon was dropped
-----------------------------------------------------------]]
function SWEP:OnDrop()
end
--[[---------------------------------------------------------
Name: ShouldDropOnDie
Desc: Should this weapon be dropped when its owner dies?
-----------------------------------------------------------]]
function SWEP:ShouldDropOnDie()
return true
end
--[[---------------------------------------------------------
Name: GetCapabilities
Desc: For NPCs, returns what they should try to do with it.
-----------------------------------------------------------]]
function SWEP:GetCapabilities()
return CAP_WEAPON_RANGE_ATTACK1
end
--[[---------------------------------------------------------
Name: NPCShoot_Secondary
Desc: NPC tried to fire secondary attack
-----------------------------------------------------------]]
function SWEP:NPCShoot_Secondary( shootPos, shootDir )
self:SecondaryAttack()
end
--[[---------------------------------------------------------
Name: NPCShoot_Secondary
Desc: NPC tried to fire primary attack
-----------------------------------------------------------]]
function SWEP:NPCShoot_Primary( shootPos, shootDir )
self:PrimaryAttack()
end
-- These tell the NPC how to use the weapon
AccessorFunc( SWEP, "fNPCMinBurst", "NPCMinBurst" )
AccessorFunc( SWEP, "fNPCMaxBurst", "NPCMaxBurst" )
AccessorFunc( SWEP, "fNPCFireRate", "NPCFireRate" )
AccessorFunc( SWEP, "fNPCMinRestTime", "NPCMinRest" )
AccessorFunc( SWEP, "fNPCMaxRestTime", "NPCMaxRest" )
|
-- vim: ft=lua ts=2 sw=2
-- (seanssel @ 06/2019)
local path = (...):gsub("%.init$", ""):match("%.?(.-)$") .. "."
-- Syntactic Sugar {{{
local function rine(val) -- Return (val) If it's Not Empty (non-zero-length)
return (val and #val>0) and val
end
local function rit(a) -- Return (a) If it's Table
return (type(a) == "table") and a
end
local noop = function() end
local esc = function(s) return string.gsub(s, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%" .. "%1") end
local str = tostring
local char = string.char
local opts = rit(htmlparser_opts) or {} -- needed for silent/noerr/noout/nonl directives, also needed to be defined before `require` in such case
local prn = opts.silent and noop or function(l,f,...)
local fd = (l=="i") and "stdout" or "stderr"
local t = (" [%s] "):format(l:upper())
io[fd]
:write('[HTMLParser]'..t..f:format(...)
..(opts.nonl or "\n")
)
end
local err = opts.noerr and noop or function(f,...) prn("e",f,...) end
local out = opts.noout and noop or function(f,...) prn("i",f,...) end
local line = debug and function(lvl) return debug.getinfo(lvl or 2).currentline end or noop
local dbg = opts.debug and function(f,...) prn("d",f:gsub("#LINE#",str(line(3))),...) end or noop
-- }}}
-- Requires {{{
local ElementNode = require (path .. "ElementNode")
local voidelements = require (path .. "voidelements")
--}}}
local HtmlParser = {}
local function parse(text,limit) -- {{{
local opts = rine(opts) -- use top-level opts-table (the one, defined before requiring the module), if exists
or rit(htmlparser_opts) -- or defined after requiring (but before calling `parse`)
or {} -- fallback otherwise
opts.looplimit = opts.looplimit or htmlparser_looplimit
local text = str(text)
local limit = limit or opts.looplimit or 1000
local tpl = false
if not opts.keep_comments then -- Strip (or not) comments {{{
text = text:gsub("<!--.--->","") -- Many chances commented code will have syntax errors, that'll lead to parser failures
end -- }}}
local tpr={}
if not opts.keep_danger_placeholders then -- {{{ little speedup by cost of potential parsing breakages
-- search unused "invalid" bytes {{{
local busy,i={},0;
repeat -- {{{
local cc = char(i)
if not(text:match(cc)) then -- {{{
if not(tpr["<"]) or not(tpr[">"]) then -- {{{
if not(busy[i]) then -- {{{
if not(tpr["<"]) then -- {{{
tpr["<"] = cc;
elseif not(tpr[">"]) then
tpr[">"] = cc;
end -- }}}
busy[i] = true
dbg("c:{%s}||cc:{%d}||tpr[c]:{%s}",str(c),cc:byte(),str(tpr[c]))
dbg("busy[i]:{%s},i:{%d}",str(busy[i]),i)
dbg("[FindPH]:#LINE# Success! || i=%d",i)
else -- if !busy
dbg("[FindPH]:#LINE# Busy! || i=%d",i)
end -- if !busy -- }}}
dbg("c:{%s}||cc:{%d}||tpr[c]:{%s}",c,cc:byte(),str(tpr[c]))
dbg("%s",str(busy[i]))
else -- if < or >
dbg("[FindPH]:#LINE# Done!",i)
break
end -- if < or > -- }}}
else -- text!match(cc)
dbg("[FindPH]:#LINE# Text contains this byte! || i=%d",i)
end -- text!match(cc) -- }}}
local skip=1
if i==31 then
skip=96 -- ASCII
end
i=i+skip
until (i==255) -- }}}
i=nil
--- }}}
if not(tpr["<"]) or not(tpr[">"]) then
err("Impossible to find at least two unused byte codes in this HTML-code. We need it to escape bracket-contained placeholders inside tags.")
err("Consider enabling 'keep_danger_placeholders' option (to silence this error, if parser wasn't failed with current HTML-code) or manually replace few random bytes, to free up the codes.")
else
dbg("[FindPH]:#LINE# Found! || '<'=%d, '>'=%d",tpr["<"]:byte(),tpr[">"]:byte())
end
-- dbg("tpr[>] || tpr[] || #busy%d")
-- g {{{
local function g(id,...)
local arg={...}
local orig=arg[id]
arg[id]=arg[id]:gsub("(.)",tpr)
if arg[id] ~= orig then
tpl=true
dbg("[g]:#LINE# orig: %s", str(orig))
dbg("[g]:#LINE# replaced: %s",str(arg[id]))
end
dbg("[g]:#LINE# called, id: %s, arg[id]: %s, args { "..(("{%s}, "):rep(#arg):gsub(", $","")).." }",id,arg[id],...)
dbg("[g]:#LINE# concat(arg): %s",table.concat(arg))
return table.concat(arg)
end
-- g }}}
-- tpl-placeholders and attributes {{{
text=text
:gsub(
"(=[%s]-)".. -- only match attr.values, and not random strings between two random apostrophs
"(%b'')",
function(...)return g(2,...)end
)
:gsub(
"(=[%s]-)".. -- same for "
'(%b"")',
function(...)return g(2,...)end
) -- Escape "<"/">" inside attr.values (see issue #50)
:gsub(
"(<".. -- Match "<",
(opts.tpl_skip_pattern or "[^!]").. -- with exclusion pattern (for example, to ignore comments, which aren't template placeholders, but can legally contain "<"/">" inside.
")([^>]+)".. -- If matched, we want to escape '<'s if we meet them inside tag
"(>)",
function(...)return g(2,...)end
)
:gsub(
"("..
(tpr["<"] or "__FAILED__").. -- Here we search for "<", we escaped in previous gsub (and don't break things if we have no escaping replacement)
")("..
(opts.tpl_marker_pattern or "[^%w%s]").. -- Capture templating symbol
")([%g%s]-)".. -- match placeholder's content
"(%2)(>)".. -- placeholder's tail
"([^>]*>)", -- remainings
function(...)return g(5,...)end
)
-- }}}
end -- }}}
local index = 0
local root = ElementNode:new(index, str(text))
local node, descend, tpos, opentags = root, true, 1, {}
while true do -- MainLoop {{{
if index == limit then -- {{{
err("Main loop reached loop limit (%d). Consider either increasing it or checking HTML-code for syntax errors", limit)
break
end -- }}}
-- openstart/tpos Definitions {{{
local openstart, name
openstart, tpos, name = root._text:find(
"<" .. -- an uncaptured starting "<"
"([%w-]+)" .. -- name = the first word, directly following the "<"
"[^>]*>", -- include, but not capture everything up to the next ">"
tpos)
dbg("[MainLoop]:#LINE# openstart=%s || tpos=%s || name=%s",str(openstart),str(tpos),str(name))
-- }}}
if not name then break end
-- Some more vars {{{
index = index + 1
local tag = ElementNode:new(index, str(name), (node or {}), descend, openstart, tpos)
node = tag
local tagloop
local tagst, apos = tag:gettext(), 1
-- }}}
while true do -- TagLoop {{{
if tagloop == limit then -- {{{
err("Tag parsing loop reached loop limit (%d). Consider either increasing it or checking HTML-code for syntax errors", limit)
break
end -- }}}
-- Attrs {{{
local start, k, eq, quote, v, zsp
start, apos, k, zsp, eq, zsp, quote = tagst:find(
"%s+" .. -- some uncaptured space
"([^%s=/>]+)" .. -- k = an unspaced string up to an optional "=" or the "/" or ">"
"([%s]-)".. -- zero or more spaces
"(=?)" .. -- eq = the optional; "=", else ""
"([%s]-)".. -- zero or more spaces
[=[(['"]?)]=], -- quote = an optional "'" or '"' following the "=", or ""
apos)
dbg("[TagLoop]:#LINE# start=%s || apos=%s || k=%s || zsp='%s' || eq='%s', quote=[%s]",str(start),str(apos),str(k),str(zsp),str(eq),str(quote))
-- }}}
if not k or k == "/>" or k == ">" then break end
-- Pattern {{{
if eq == "=" then
local pattern = "=([^%s>]*)"
if quote ~= "" then
pattern = quote .. "([^" .. quote .. "]*)" .. quote
end
start, apos, v = tagst:find(pattern, apos)
dbg("[TagLoop]:#LINE# start=%s || apos=%s || v=%s || pattern=%s",str(start),str(apos),str(v),str(pattern))
end
-- }}}
v=v or ""
if tpl then -- {{{
for rk,rv in pairs(tpr) do
v = v:gsub(rv,rk)
dbg("[TagLoop]:#LINE# rv=%s || rk=%s",str(rv),str(rk))
end
end -- }}}
dbg("[TagLoop]:#LINE# k=%s || v=%s",str(k),str(v))
tag:addattribute(k, v)
tagloop = (tagloop or 0) + 1
end
-- }}}
if voidelements[tag.name:lower()] then -- {{{
descend = false
tag:close()
else
opentags[tag.name] = opentags[tag.name] or {}
table.insert(opentags[tag.name], tag)
end
-- }}}
local closeend = tpos
local closingloop
while true do -- TagCloseLoop {{{
if closingloop == limit then
err("Tag closing loop reached loop limit (%d). Consider either increasing it or checking HTML-code for syntax errors", limit)
break
end
local closestart, closing, closename
closestart, closeend, closing, closename = root._text:find("[^<]*<(/?)([%w-]+)", closeend)
dbg("[TagCloseLoop]:#LINE# closestart=%s || closeend=%s || closing=%s || closename=%s",str(closestart),str(closeend),str(closing),str(closename))
if not closing or closing == "" then break end
tag = table.remove(opentags[closename] or {}) or tag -- kludges for the cases of closing void or non-opened tags
closestart = root._text:find("<", closestart)
dbg("[TagCloseLoop]:#LINE# closestart=%s",str(closestart))
tag:close(closestart, closeend + 1)
node = tag.parent
descend = true
closingloop = (closingloop or 0) + 1
end -- }}}
end -- }}}
if tpl then -- {{{
dbg("tpl")
for k,v in pairs(tpr) do
root._text = root._text:gsub(v,k)
end
end -- }}}
return root
end -- }}}
HtmlParser.parse = parse
return HtmlParser
|
local addonName, RIC = ...
-- POPUP MENU CODE BELOW
local PopupDepth
local function PopupClick(self, arg1, arg2, checked)
if type(self.value)=="table" then
self.value[arg1]=not self.value[arg1]
self.checked=self.value[arg1]
if arg2 then
arg2(self.value,arg1,checked)
end
elseif type(self.value)=="function" then
self.value(arg1,arg2)
end
end
local function PopupAddItem(self,text,disabled,value,arg1,arg2)
local c=self._Frame._GPIPRIVAT_Items.count+1
self._Frame._GPIPRIVAT_Items.count=c
if not self._Frame._GPIPRIVAT_Items[c] then
self._Frame._GPIPRIVAT_Items[c]={}
end
local t=self._Frame._GPIPRIVAT_Items[c]
t.text=text or ""
t.disabled=disabled or false
t.value=value
t.arg1=arg1
t.arg2=arg2
t.MenuDepth=PopupDepth
end
local function PopupAddSubMenu(self,text,value)
if text~=nil and text~="" then
PopupAddItem(self,text,"MENU",value)
PopupDepth=value
else
PopupDepth=nil
end
end
local PopupLastWipeName
local function PopupWipe(self,WipeName)
self._Frame._GPIPRIVAT_Items.count=0
PopupDepth=nil
if UIDROPDOWNMENU_OPEN_MENU == self._Frame then
ToggleDropDownMenu(nil, nil, self._Frame, self._where, self._x, self._y)
if WipeName == PopupLastWipeName then
return false
end
end
PopupLastWipeName=WipeName
return true
end
local function PopupCreate(frame, level, menuList)
if level==nil then return end
local info = UIDropDownMenu_CreateInfo()
for i=1,frame._GPIPRIVAT_Items.count do
local val=frame._GPIPRIVAT_Items[i]
if val.MenuDepth==menuList then
if val.disabled=="MENU" then
info.text=val.text
info.notCheckable = true
info.disabled=false
info.value=nil
info.arg1=nil
info.arg2=nil
info.func=nil
info.hasArrow=true
info.menuList=val.value
--info.isNotRadio=true
else
info.text=val.text
if type(val.value)=="table" then
info.checked=val.value[val.arg1] or false
info.notCheckable = false
else
info.notCheckable = true
end
info.disabled=(val.disabled==true or val.text=="" )
info.keepShownOnClick=(val.disabled=="keep")
info.value=val.value
info.arg1=val.arg1
if type(val.value)=="table" then
info.arg2=frame._GPIPRIVAT_TableCallback
elseif type(val.value)=="function" then
info.arg2=val.arg2
end
info.func=PopupClick
info.hasArrow=false
info.menuList=nil
--info.isNotRadio=true
end
UIDropDownMenu_AddButton(info,level)
end
end
end
local function PopupShow(self,where,x,y)
where=where or "cursor"
if UIDROPDOWNMENU_OPEN_MENU ~= self._Frame then
UIDropDownMenu_Initialize(self._Frame, PopupCreate, "MENU")
end
ToggleDropDownMenu(nil, nil, self._Frame, where, x,y)
self._where=where
self._x=x
self._y=y
end
function RIC.CreateContextPopup(TableCallback)
local popup={}
popup._Frame=CreateFrame("Frame", nil, UIParent, "UIDropDownMenuTemplate")
popup._Frame._GPIPRIVAT_TableCallback=TableCallback
popup._Frame._GPIPRIVAT_Items={}
popup._Frame._GPIPRIVAT_Items.count=0
popup.AddItem=PopupAddItem
popup.SubMenu=PopupAddSubMenu
popup.Show=PopupShow
popup.Wipe=PopupWipe
return popup
end
|
local JSON = require('json')
function jsonResponse (opts)
opts = opts or {}
return function (req, res, nxt)
function res:json (tbl)
if not res:getHeader('Content-Type') then
res:setHeader('Content-Type', 'application/json')
end
res:finish(JSON.stringify(tbl, opts))
end
nxt()
end
end
return jsonResponse
|
local ffi = require "ffi"
local C = ffi.C
require "resty.openssl.include.ossl_typ"
require "resty.openssl.include.stack"
local OPENSSL_10 = require("resty.openssl.version").OPENSSL_10
local OPENSSL_11_OR_LATER = require("resty.openssl.version").OPENSSL_11_OR_LATER
local OPENSSL_30 = require("resty.openssl.version").OPENSSL_30
local BORINGSSL_110 = require("resty.openssl.version").BORINGSSL_110
ffi.cdef [[
X509_STORE *X509_STORE_new(void);
void X509_STORE_free(X509_STORE *v);
/* int X509_STORE_lock(X509_STORE *ctx);
int X509_STORE_unlock(X509_STORE *ctx);
int X509_STORE_up_ref(X509_STORE *v);
// STACK_OF(X509_OBJECT)
OPENSSL_STACK *X509_STORE_get0_objects(X509_STORE *v);*/
int X509_STORE_add_cert(X509_STORE *ctx, X509 *x);
int X509_STORE_add_crl(X509_STORE *ctx, X509_CRL *x);
int X509_STORE_load_locations(X509_STORE *ctx,
const char *file, const char *dir);
int X509_STORE_set_default_paths(X509_STORE *ctx);
X509_STORE_CTX *X509_STORE_CTX_new(void);
void X509_STORE_CTX_free(X509_STORE_CTX *ctx);
// STACK_OF(X509)
int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store,
X509 *x509, OPENSSL_STACK *chain);
int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx);
int X509_STORE_set_flags(X509_STORE *ctx, unsigned long flags);
]]
local _M = {}
if OPENSSL_10 or BORINGSSL_110 then
ffi.cdef [[
// STACK_OF(X509)
OPENSSL_STACK *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx);
]];
_M.X509_STORE_CTX_get0_chain = C.X509_STORE_CTX_get_chain
elseif OPENSSL_11_OR_LATER then
ffi.cdef [[
// STACK_OF(X509)
OPENSSL_STACK *X509_STORE_CTX_get0_chain(X509_STORE_CTX *ctx);
]];
_M.X509_STORE_CTX_get0_chain = C.X509_STORE_CTX_get0_chain
end
if OPENSSL_30 then
ffi.cdef [[
X509_STORE_CTX *X509_STORE_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
int X509_STORE_set_default_paths_ex(X509_STORE *ctx, OSSL_LIB_CTX *libctx,
const char *propq);
/* int X509_STORE_load_file_ex(X509_STORE *ctx, const char *file,
OSSL_LIB_CTX *libctx, const char *propq);
int X509_STORE_load_store_ex(X509_STORE *ctx, const char *uri,
OSSL_LIB_CTX *libctx, const char *propq); */
int X509_STORE_load_locations_ex(X509_STORE *ctx, const char *file,
const char *dir, OSSL_LIB_CTX *libctx,
const char *propq);
]]
_M.X509_STORE_set_default_paths = function(...) return C.X509_STORE_set_default_paths_ex(...) end
_M.X509_STORE_load_locations = function(...) return C.X509_STORE_load_locations_ex(...) end
else
_M.X509_STORE_set_default_paths = function(s) return C.X509_STORE_set_default_paths(s) end
_M.X509_STORE_load_locations = function(s, file, dir) return C.X509_STORE_load_locations(s, file, dir) end
end
return _M
|
-- This file is subject to copyright - contact swampservers@gmail.com for more information.
-- INSTALL: CINEMA
local Player = FindMetaTable('Player')
local Entity = FindMetaTable('Entity')
SS_MaterialCache = {}
function SS_GetMaterial(nam)
SS_MaterialCache[nam] = SS_MaterialCache[nam] or Material(nam)
return SS_MaterialCache[nam]
end
function SS_PreRender(item)
if item.cfg.imgur then
local imat = ImgurMaterial({
id = item.cfg.imgur.url,
owner = item.owner,
pos = IsValid(item.owner) and item.owner:IsPlayer() and item.owner:GetPos(),
stretch = true,
shader = "VertexLitGeneric",
params = [[{["$alphatest"]=1}]]
})
render.MaterialOverride(imat)
--render.OverrideDepthEnable(true,true)
else
local mat = item.cfg.material or item.material
if mat then
render.MaterialOverride(SS_GetMaterial(mat))
end
end
local col = item.cfg.color or item.color
if col then
render.SetColorModulation(col.x, col.y, col.z)
end
end
function SS_PostRender()
render.SetColorModulation(1, 1, 1)
render.MaterialOverride()
--render.OverrideDepthEnable(false)
end
hook.Add("PrePlayerDraw", "SS_BoneMods", function(ply)
-- will be "false" if the model is not mounted yet
local mounted_model = require_workshop_model(ply:GetModel()) and ply:GetModel()
if not ply:Alive() then return true end
if ply.SS_PlayermodelModsLastModel ~= mounted_model then
ply.SS_PlayermodelModsClean = false
--seems to have issues if you apply the bone mods as soon as the model changes...
--timer.Simple(1, function() if IsValid(ply) then ply.SS_PlayermodelModsClean = false end end)
end
if not ply.SS_PlayermodelModsClean then
ply.SS_PlayermodelModsClean = SS_ApplyBoneMods(ply, ply:SS_GetActivePlayermodelMods())
ply.SS_PlayermodelModsLastModel = mounted_model
end
SS_ApplyMaterialMods(ply, ply:SS_GetActivePlayermodelMods())
end)
local function AddScaleRecursive(ent, b, scn, recurse, safety)
if safety[b] then
error("BONE LOOP!")
end
safety[b] = true
local sco = ent:GetManipulateBoneScale(b)
sco.x = sco.x * scn.x
sco.y = sco.y * scn.y
sco.z = sco.z * scn.z
if ent:GetModel() == "models/milaco/minecraft_pm/minecraft_pm.mdl" then
sco.x = math.min(sco.x, 1)
sco.y = math.min(sco.y, 1)
sco.z = math.min(sco.z, 1)
end
ent:ManipulateBoneScale(b, sco)
if recurse then
for i, v in ipairs(ent:GetChildBones(b)) do
AddScaleRecursive(ent, v, scn, recurse, safety)
end
end
end
--only bone scale right now...
--if you do pos/angles, must do a combination override to make it work with emotes, vape arm etc
function SS_ApplyBoneMods(ent, mods)
for x = 0, (ent:GetBoneCount() - 1) do
ent:ManipulateBoneScale(x, Vector(1, 1, 1))
ent:ManipulateBonePosition(x, Vector(0, 0, 0))
end
if ent:GetModel() == HumanTeamModel or ent:GetModel() == PonyTeamModel then return end
local pone = isPonyModel(ent:GetModel())
local suffix = pone and "_p" or "_h"
--if pelvis has no children, its not ready!
local pelvis = ent:LookupBone(pone and "LrigPelvis" or "ValveBiped.Bip01_Pelvis")
if pelvis then
if #ent:GetChildBones(pelvis) == 0 then return false end
end
for _, item in ipairs(mods) do
if item.bonemod then
local bn = item.cfg["bone" .. suffix] or (pone and "LrigScull" or "ValveBiped.Bip01_Head1")
local x = ent:LookupBone(bn)
if x then
if (item.configurable or {}).scale then
local scn = item.cfg["scale" .. suffix] or Vector(1, 1, 1.5)
AddScaleRecursive(ent, x, scn, item.cfg["scale_children" .. suffix], {})
end
if (item.configurable or {}).pos then
local psn = item.cfg["pos" .. suffix] or Vector(10, 0, 0)
--don't allow moving the root bone
if ent:GetBoneParent(x) == -1 then
psn.x = 0
psn.y = 0
end
local pso = ent:GetManipulateBonePosition(x)
pso = pso + psn
ent:ManipulateBonePosition(x, pso)
end
end
end
end
--clamp the amount of stacking
for x = 0, (ent:GetBoneCount() - 1) do
local old = ent:GetManipulateBoneScale(x)
local mn = 0.125 --0.5*0.5*0.5
local mx = 3.375 --1.5*1.5*1.5
if ent.GetNetData and ent:GetNetData('OF') ~= nil then
mx = 1.5
end
old.x = math.Clamp(old.x, mn, mx)
old.y = math.Clamp(old.y, mn, mx)
old.z = math.Clamp(old.z, mn, mx)
ent:ManipulateBoneScale(x, old)
old = ent:GetManipulateBonePosition(x)
old.x = math.Clamp(old.x, -8, 8)
old.y = math.Clamp(old.y, -8, 8)
old.z = math.Clamp(old.z, -8, 8)
ent:ManipulateBonePosition(x, old)
end
return true
end
function SS_ApplyMaterialMods(ent, mods)
ent:SetSubMaterial()
if SS_PPM_SetSubMaterials then
SS_PPM_SetSubMaterials(ent)
end
if ent:GetModel() == HumanTeamModel or ent:GetModel() == PonyTeamModel then return end
for _, item in ipairs(mods) do
if item.materialmod then
local col = item.cfg.color or Vector(1, 1, 1)
local mat = ImgurMaterial({
id = (item.cfg.imgur or {}).url or "EG84dgp.png",
owner = ent,
pos = IsValid(ent) and ent:IsPlayer() and ent:GetPos(),
stretch = true,
shader = "VertexLitGeneric",
params = string.format('{["$color2"]="[%f %f %f]"}', col.x, col.y, col.z)
})
ent:SetSubMaterial(item.cfg.submaterial or 0, "!" .. mat:GetName())
end
end
end
local EntityGetModel = Entity.GetModel
-- Entity.SS_True_LookupAttachment = Entity.SS_True_LookupAttachment or Entity.LookupAttachment
-- Entity.SS_True_LookupBone = Entity.SS_True_LookupBone or Entity.LookupBone
-- function Entity:LookupAttachment(id)
-- local mdl = EntityGetModel(self)
-- if self.LookupAttachmentCacheModel ~= mdl then
-- self.LookupAttachmentCache={}
-- end
-- if not self.LookupAttachmentCache[id] then self.LookupAttachmentCache[id] = Entity.SS_True_LookupAttachment(self, id) end
-- return self.LookupAttachmentCache[id]
-- end
-- function Entity:LookupBone(id)
-- local mdl = EntityGetModel(self)
-- if self.LookupBoneCacheModel ~= mdl then
-- self.LookupBoneCache={}
-- end
-- if not self.LookupBoneCache[id] then self.LookupBoneCache[id] = Entity.SS_True_LookupBone(self, id) end
-- return self.LookupBoneCache[id]
-- end
-- function SWITCHH()
-- Entity.LookupAttachment = Entity.SS_True_LookupAttachment
-- Entity.LookupBone = Entity.SS_True_LookupBone
-- end
--TODO: add "defaultcfg" as a standard field in items rather than this hack!
--TODO this is lag causin
function SS_DrawWornCSModel(item, mdl, ent, dontactually)
local pone = isPonyModel(EntityGetModel(ent))
local attach = item.wear.attach
local scale = item.wear.scale
local translate = item.wear.translate
local rotate = item.wear.rotate
if pone and item.wear.pony then
attach = item.wear.pony.attach or attach
scale = item.wear.pony.scale or scale
translate = item.wear.pony.translate or translate
rotate = item.wear.pony.rotate or rotate
end
local cfgk = pone and "wear_p" or "wear_h"
if item.cfg[cfgk] then
attach = item.cfg[cfgk].attach or attach
scale = item.cfg[cfgk].scale or scale
translate = item.cfg[cfgk].pos or translate
rotate = item.cfg[cfgk].ang or rotate
end
local pos, ang
if attach == "eyes" then
local fn = FrameNumber()
if ent.attachcacheframe ~= fn then
ent.attachcacheframe = fn
local attach_id = ent:LookupAttachment("eyes")
if attach_id then
local attacht = ent:GetAttachment(attach_id)
if attacht then
ent.attachcache = attacht
pos = attacht.Pos
ang = attacht.Ang
end
end
else
local attacht = ent.attachcache
if attacht then
pos = attacht.Pos
ang = attacht.Ang
end
end
else
local bone_id = ent:LookupBone(SS_Attachments[attach][pone and 2 or 1])
if bone_id then
pos, ang = ent:GetBonePosition(bone_id)
end
end
if not pos then
pos = ent:GetPos()
ang = ent:GetAngles()
end
pos, ang = LocalToWorld(translate, rotate, pos, ang)
if mdl.scaleapplied ~= scale then
mdl.scaleapplied = scale
if isnumber(scale) then
mdl.matrix = Matrix({
{scale, 0, 0, 0},
{0, scale, 0, 0},
{0, 0, scale, 0},
{0, 0, 0, 1}
})
else
mdl.matrix = Matrix({
{scale.x, 0, 0, 0},
{0, scale.y, 0, 0},
{0, 0, scale.z, 0},
{0, 0, 0, 1}
})
end
mdl:EnableMatrix("RenderMultiply", mdl.matrix)
end
mdl:SetPos(pos)
mdl:SetAngles(ang)
mdl:SetupBones()
if not dontactually then
SS_PreRender(item, ent)
mdl:DrawModel()
SS_PostRender()
end
end
hook.Add("DrawOpaqueAccessories", 'SS_DrawPlayerAccessories', function(ply)
if ply.SS_Items == nil and ply.SS_ShownItems == nil then return end
if not ply:Alive() then return end
if EyePos():DistToSqr(ply:GetPos()) > 2000000 then return end
-- and (GetConVar('thirdperson') and GetConVar('thirdperson'):GetInt() == 0)
--if ply == LocalPlayer() and GetViewEntity():GetClass() == 'player' then return end
if GAMEMODE.FolderName == "fatkid" and ply:Team() ~= TEAM_HUMAN then return end
--in SPADES, the renderboost.lua is disabled!
for _, prop in ipairs(ply:SS_GetCSModels()) do
SS_DrawWornCSModel(prop.item, prop.mdl, ply)
end
end)
SS_GibProps = {}
hook.Add('CreateClientsideRagdoll', 'SS_CreateClientsideRagdoll', function(ply, rag)
if IsValid(ply) and ply:IsPlayer() then
--print(rag:GetPhysicsObjectNum(0):GetVelocity())
local counter = 0
for k, v in pairs(SS_CSModels[ply] or {}) do
counter = counter + 1
if counter > 8 then return end
vm = v.mdl
local gib = GibClientProp(vm:GetModel(), vm:GetPos(), vm:GetAngles(), ply:GetVelocity(), 1, 6)
if vm.matrix then
gib:EnableMatrix("RenderMultiply", vm.matrix)
end
gib.csmodel = v
gib:SetNoDraw(true)
table.insert(SS_GibProps, gib)
end
end
end)
concommand.Add("ps_proptest", function()
for j, itm in pairs(SS_Items) do
local mdl = itm.model
local gib = GibClientProp(mdl, LocalPlayer():EyePos(), Angle(0, 0, 0), LocalPlayer():GetVelocity(), 1, 6)
gib = gib:GetPhysicsObject():GetMesh()
local mins = nil
local maxs = nil
for k, v in pairs(gib) do
local p = v.pos
if mins then
mins = Vector(math.min(mins.x, p.x), math.min(mins.y, p.y), math.min(mins.z, p.z))
maxs = Vector(math.max(maxs.x, p.x), math.max(maxs.y, p.y), math.max(maxs.z, p.z))
else
mins = p
maxs = p
end
end
print(mdl)
maxs = (maxs - mins)
print("Vector(" .. tostring(math.Round(maxs.x, 0)) .. ", " .. tostring(math.Round(maxs.y, 0)) .. ", " .. tostring(math.Round(maxs.z, 0)) .. ")")
end
end)
hook.Add("PostDrawOpaqueRenderables", "SS_RenderGibs", function(depth, sky)
if sky or depth then return end
local nextgibs = {}
while #SS_GibProps > 0 do
local gib = table.remove(SS_GibProps)
if IsValid(gib) then
SS_PreRender(gib.csmodel.item)
gib:DrawModel()
SS_PostRender()
table.insert(nextgibs, gib)
end
end
SS_GibProps = nextgibs
end)
SS_CSModels = SS_CSModels or {}
hook.Add('Think', 'SS_Cleanup', function()
for ply, mdls in pairs(SS_CSModels) do
if not IsValid(ply) then
for k, v in pairs(mdls) do
v.mdl:Remove()
end
SS_CSModels[ply] = nil
end
end
end)
--makes a CSModel for a worn item
function SS_CreateWornCSModel(item)
if item.wear == nil then return end
return SS_CreateCSModel(item)
end
--makes a CSModel for a product or item
function SS_CreateCSModel(item)
local mdlname = item.model or item.cfg.model
if mdlname == nil then return end
local mdl = ClientsideModel(mdlname, RENDERGROUP_OPAQUE)
if IsValid(mdl) then
mdl:SetNoDraw(true)
return mdl
end
end
function Player:SS_ClearCSModels()
for k, v in pairs(SS_CSModels[self] or {}) do
v.mdl:Remove()
end
SS_CSModels[self] = nil
end
function Player:SS_GetCSModels()
if SS_CSModels[self] == nil then
SS_CSModels[self] = {}
for k, item in pairs(self.SS_ShownItems or {}) do
local mdl = SS_CreateWornCSModel(item)
if mdl then
table.insert(SS_CSModels[self], {
mdl = mdl,
item = item
})
end
end
end
return SS_CSModels[self]
end
function Player:SS_GetActivePlayermodelMods()
local mods = {}
for k, item in pairs(self.SS_ShownItems or {}) do
if item.playermodelmod then
table.insert(mods, item)
end
end
return mods
end
-- function Player:SS_GetActiveMaterialMods()
-- --{[5]="https://i.imgur.com/Ue1qUPf.jpg"}
-- return {}
-- end
-- function thinga()
-- TTT1 = FindMetaTable("Entity")
-- TTT2 = FindMetaTable("Player")
-- TTT2.SetMaterial = function(a, b)
-- TTT1.SetMaterial(a, b)
-- print(a, b)
-- end
-- end
|
Test = require('connecttest')
require('cardinalities')
local events = require('events')
local mobile_session = require('mobile_session')
local mobile = require('mobile_connection')
local tcp = require('tcp_connection')
local file_connection = require('file_connection')
local module = require('testbase')
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
---------------------------------------------------------------------------------------------
-----------------------------Required Shared Libraries---------------------------------------
---------------------------------------------------------------------------------------------
require('user_modules/AppTypes')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local policyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local integerParameter = require('user_modules/shared_testcases/testCasesForIntegerParameter')
local stringParameter = require('user_modules/shared_testcases/testCasesForStringParameter')
local arraySoftButtonsParameter = require('user_modules/shared_testcases/testCasesForArraySoftButtonsParameter')
local arrayTTSChunks = require('user_modules/shared_testcases/testCasesForArrayTTSChunksParameter')
---------------------------------------------------------------------------------------------
------------------------------------ Common Variables ---------------------------------------
---------------------------------------------------------------------------------------------
APIName = "Speak" -- set request name
strMaxLengthFileName255 = string.rep("a", 251) .. ".png" -- set max length file name
local storagePath = config.pathToSDL .. "storage/" .. config.application1.registerAppInterfaceParams.fullAppID .. "_" .. config.deviceMAC .. "/"
--Debug = {"graphic", "value"} --use to print request before sending to SDL.
Debug = {} -- empty {}: script will do not print request on console screen.
---------------------------------------------------------------------------------------------
-------------------------- Overwrite These Functions For This Script-------------------------
---------------------------------------------------------------------------------------------
--Specific functions for this script
--1. createRequest()
--2. verify_SUCCESS_Case(Request)
---------------------------------------------------------------------------------------------
local function ExpectOnHMIStatusWithAudioStateChanged(self, HMILevel, timeout, times)
--valid values for times parameter:
--nil => times = 2
--4: for duplicate request
if HMILevel == nil then HMILevel = "FULL" end
if timeout == nil then timeout = 10000 end
if times == nil then times = 2 end
if commonFunctions:isMediaApp() then
--mobile side: OnHMIStatus notification
EXPECT_NOTIFICATION("OnHMIStatus",
{systemContext = "MAIN", hmiLevel = HMILevel, audioStreamingState = "ATTENUATED"},
{systemContext = "MAIN", hmiLevel = HMILevel, audioStreamingState = "AUDIBLE"})
:Times(times)
:Timeout(timeout)
else
--mobile side: OnHMIStatus notification
EXPECT_NOTIFICATION("OnHMIStatus",
{systemContext = "MAIN", hmiLevel = HMILevel, audioStreamingState = "NOT_AUDIBLE"},
{systemContext = "MAIN", hmiLevel = HMILevel, audioStreamingState = "NOT_AUDIBLE"})
:Times(times)
:Timeout(timeout)
end
end
--Create default request
function Test:createRequest()
return {
ttsChunks =
{
{
text ="a",
type ="TEXT"
}
}
}
end
--This function sends a request from mobile and verify result on HMI and mobile for SUCCESS resultCode cases.
function Test:verify_SUCCESS_Case(Request, HMILevel)
--mobile side: sending the request
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect TTS.Speak request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendResponse(SpeakId, "TTS.Speak", "SUCCESS", { })
self.hmiConnection:SendNotification("TTS.Stopped")
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self, HMILevel)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
end
---------------------------------------------------------------------------------------------
-------------------------------------------Preconditions-------------------------------------
---------------------------------------------------------------------------------------------
--Print new line to separate Preconditions
commonFunctions:newTestCasesGroup("Preconditions")
--Delete app_info.dat, logs and policy table
commonSteps:DeleteLogsFileAndPolicyTable()
--1. Activate application
commonSteps:ActivationApp()
--2. Update policy to allow request
--TODO: Will be updated after policy flow implementation
policyTable:precondition_updatePolicy_AllowFunctionInHmiLeves({"FULL", "LIMITED"})
-----------------------------------------------------------------------------------------------
-------------------------------------------TEST BLOCK I----------------------------------------
--------------------------------Check normal cases of Mobile request---------------------------
-----------------------------------------------------------------------------------------------
--Requirement id in JAMA:
--SDLAQ-CRS-54 (Speak_Request_v2_0)
--SDLAQ-CRS-55 (Speak_Response_v2_0)
--SDLAQ-CRS-505 (INVALID_DATA)
--SDLAQ-CRS-504 (SUCCESS)
--Verification criteria: Speak request notifies the user via TTS engine with some information that the app provides to HMI. After TTS has prompted, the response with SUCCESS resultCode is returned to mobile app.
--List of parameters:
--1. ttsChunks: type=TTSChunk, minsize="1", maxsize="100", array="true"
-----------------------------------------------------------------------------------------------
--Common Test cases check all parameters with lower bound and upper bound
--1. All parameters are lower bound
--2. All parameters are upper bound
--Skip these test cases because this API only has one parameter and these test cases will be checked in Lower/Upper bounds of this parameter.
-----------------------------------------------------------------------------------------------
--Parameter 1: ttsChunks: type=TTSChunk, minsize="1", maxsize="100", array="true"
-----------------------------------------------------------------------------------------------
--List of test cases for softButtons type parameter:
--1. IsMissed
--2. IsEmpty
--3. IsWrongType
--4. IsLowerBound
--5. IsUpperBound
--6. IsOutLowerBound
--7. IsOutUpperBound
--8. Check children parameters:
--text: minlength="0" maxlength="500" type="String"
--type: type="SpeechCapabilities": "TEXT", "SAPI_PHONEMES", "LHPLUS_PHONEMES", "PRE_RECORDED", "SILENCE", "FILE"
-----------------------------------------------------------------------------------------------
local Request = Test:createRequest()
local Boundary = {1, 100}
arrayTTSChunks:verify_TTSChunks_Parameter(Request, {"ttsChunks"}, Boundary, true)
----------------------------------------------------------------------------------------------
----------------------------------------TEST BLOCK II-----------------------------------------
-----------------------------Check special cases of Mobile request----------------------------
----------------------------------------------------------------------------------------------
--Begin Test case SpecialRequestChecks
--Description: Check special requests
--Requirement id in JAMA:
--SDLAQ-CRS-54 (Speak_Request_v2_0)
--SDLAQ-CRS-55 (Speak_Response_v2_0)
--SDLAQ-CRS-505 (INVALID_DATA)
--SDLAQ-CRS-504 (SUCCESS)
--SDLAQ-CRS-509 (REJECTED)
--SDLAQ-CRS-510 (ABORTED)
--SDLAQ-CRS-512 (DISALLOWED)
--SDLAQ-CRS-1027 (UNSUPPORTED_RESOURCE)
--SDLAQ-CRS-1030 (WARNINGS)
--Verification criteria: Speak request notifies the user via TTS engine with some information that the app provides to HMI. After TTS has prompted, the response with SUCCESS resultCode is returned to mobile app.
local function SpecialRequestChecks()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("TestCaseGroupForMobileNegativeCases")
--Begin Test case NegativeRequestCheck.1
--Description: Invalid JSON
--Requirement id in JAMA: SDLAQ-CRS-505
--Verification criteria: The request with wrong JSON syntax is sent, the response with INVALID_DATA result code is returned.
--local Payload = '{"ttsChunks":{{"text":"a","type":"TEXT"}}}' -- valid JSON
local Payload = '{"ttsChunks";{{"text":"a","type":"TEXT"}}}'
commonTestCases:VerifyInvalidJsonRequest(14, Payload) --SpeakID = 14
--End Test case NegativeRequestCheck.1
--Begin Test case NegativeRequestCheck.2
--Description: CorrelationId check( duplicate value)
--ToDo: Update after fixed ATF defect: APPLINK-13101 ATF sends string in notification with escaped slash character
function Test:Speak_CorrelationID_IsDuplicated()
--mobile side: sending Speak request
local cid = self.mobileSession:SendRPC("Speak",
{
ttsChunks =
{
{
text ="a",
type ="TEXT"
}
}
})
self.mobileSession.correlationId = cid
--request from mobile side
local msg =
{
serviceType = 7,
frameInfo = 0,
rpcType = 0,
rpcFunctionId = 14,
rpcCorrelationId = self.mobileSession.correlationId,
payload = '{"ttsChunks":[{"text":"a","type":"TEXT"}]}'
}
--hmi side: expect TTS.Speak request
EXPECT_HMICALL("TTS.Speak", { ttsChunks = {{text ="a", type ="TEXT"}}} )
:Do(function(exp,data)
local function speakResponse(RequestId)
self.hmiConnection:SendResponse(RequestId, "TTS.Speak", "SUCCESS", { })
self.hmiConnection:SendNotification("TTS.Stopped")
end
if exp.occurences == 1 then
self.mobileSession:Send(msg)
SpeakId1 = data.id
RUN_AFTER(function() speakResponse(SpeakId1) end, 1000)
elseif
exp.occurences == 2 then
SpeakId2 = data.id
RUN_AFTER(function() speakResponse(SpeakId2) end, 1000)
end
self.hmiConnection:SendNotification("TTS.Started")
end)
:Times(2)
ExpectOnHMIStatusWithAudioStateChanged(self, "FULL", nil, 4)
--response on mobile side
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS"})
:Times(2)
end
--End Test case NegativeRequestCheck.2
--Begin Test case NegativeRequestCheck.3
--Description: Fake parameters check
--Requirement id in JAMA: APPLINK-4518
--Verification criteria: According to xml tests by Ford team all fake params should be ignored by SDL
--Begin Test case NegativeRequestCheck.3.1
--Description: Fake parameters is not from any API
function Test:Speak_FakeParams_IsNotFromAnyAPI()
--mobile side: sending Speak request
local Request = {
fakeParam = "abc",
ttsChunks =
{
{
fakeParam = "abc",
text ="a",
type ="TEXT"
}
}
}
local cid = self.mobileSession:SendRPC("Speak", Request)
Request.fakeParam = nil
Request.ttsChunks[1].fakeParam = nil
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:ValidIf(function(_,data)
if data.params.fakeParam or
data.params.ttsChunks[1].fakeParam then
Print(" SDL re-sends fakeParam parameters to HMI")
return false
else
return true
end
end)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendResponse(SpeakId, "TTS.Speak", "SUCCESS", { })
self.hmiConnection:SendNotification("TTS.Stopped")
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
end
--End Test case NegativeRequestCheck.3.1
-----------------------------------------------------------------------------------------
--Begin Test case NegativeRequestCheck.3.2
--Description: Fake parameters is not from another API
function Test:Speak_FakeParams_ParameterIsFromAnotherAPI()
--mobile side: sending Speak request
local param = {
syncFileName = "abc",
ttsChunks =
{
{
syncFileName = "abc",
text ="a",
type ="TEXT"
}
}
}
local cid = self.mobileSession:SendRPC("Speak", param)
param.syncFileName = nil
param.ttsChunks[1].syncFileName = nil
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", param)
:ValidIf(function(_,data)
if data.params.syncFileName or
data.params.ttsChunks[1].syncFileName then
Print(" SDL re-sends syncFileName parameters to HMI")
return false
else
return true
end
end)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendResponse(SpeakId, "TTS.Speak", "SUCCESS", { })
self.hmiConnection:SendNotification("TTS.Stopped")
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
end
--End Test case NegativeRequestCheck.3.2
-----------------------------------------------------------------------------------------
--End Test case NegativeRequestCheck.3
--Begin Test case NegativeRequestCheck.4
--Description: All parameters missing
commonTestCases:VerifyRequestIsMissedAllParameters()
--End Test case NegativeRequestCheck.4
-----------------------------------------------------------------------------------------
end
SpecialRequestChecks()
--End Test case NegativeRequestCheck
-----------------------------------------------------------------------------------------------
-------------------------------------------TEST BLOCK III--------------------------------------
----------------------------------Check normal cases of HMI response---------------------------
-----------------------------------------------------------------------------------------------
--Requirement id in JAMA:
--SDLAQ-CRS-55 (Speak_Response)
--SDLAQ-CRS-505 (INVALID_DATA)
--SDLAQ-CRS-504 (SUCCESS)
--SDLAQ-CRS-509 (REJECTED)
--SDLAQ-CRS-510 (ABORTED)
--SDLAQ-CRS-512 (DISALLOWED)
--SDLAQ-CRS-1027 (UNSUPPORTED_RESOURCE)
--SDLAQ-CRS-1030 (WARNINGS)
--SDLAQ-CRS-388 (APPLICATION_NOT_REGISTERED)
--SDLAQ-CRS-385 (TOO_MANY_PENDING_REQUESTS)
--SDLAQ-CRS-384 (OUT_OF_MEMORY)
--SDLAQ-CRS-391 (GENERIC_ERROR)
--APPLINK-14765: SDL must cut off the fake parameters from requests, responses and notifications received from HMI (INVALID response => GENERIC_ERROR resultCode)
--APPLINK-14551: SDL behavior: cases when SDL must transfer "info" parameter via corresponding RPC to mobile app
--Verification Criteria: The response contains 2 mandatory parameters "success" and "resultCode", "info" is sent if there is any additional information about the resultCode
--Common Test cases for Response
--1. Check all mandatory parameters are missed
--2. Check all parameters are missed
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("TestCaseGroupForCommonTestCaseForResponse")
--[=[ToDo: update according to APPLINK-13101
Test[APIName.."_Response_MissingMandatoryParameters_GENERIC_ERROR"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{}}')
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_MissingAllParameters_GENERIC_ERROR"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
self.hmiConnection:Send('{}')
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
]=]
-----------------------------------------------------------------------------------------------
--Parameter 1: resultCode
-----------------------------------------------------------------------------------------------
--List of test cases:
--1. IsMissed
--2. IsValidValue
--3. IsNotExist
--4. IsEmpty
--5. IsWrongType
--6. IsInvalidCharacter - \n, \t
-----------------------------------------------------------------------------------------------
local function verify_resultCode_parameter()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("TestCaseGroupForResultCodeParameter")
-----------------------------------------------------------------------------------------
--1. IsMissed
Test[APIName.."_Response_resultCode_IsMissed_GENERIC_ERROR_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak"}}')
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
--TODO: update after resolving APPLINK-14765
-- EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA"})
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_resultCode_IsMissed_GENERIC_ERROR_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","error":{"data":{"method":"TTS.Speak"},"code":22,"message":"The unknown issue occurred"}}')
self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","error":{"data":{"method":"TTS.Speak"},"message":"The unknown issue occurred"}}')
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
--TODO: update after resolving APPLINK-14765
-- EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA"})
end
-----------------------------------------------------------------------------------------
--2. IsValidValue
local resultCodes = {
{resultCode = "SUCCESS", success = true},
{resultCode = "INVALID_DATA", success = false},
{resultCode = "REJECTED", success = false},
{resultCode = "ABORTED", success = false},
{resultCode = "DISALLOWED", success = false},
{resultCode = "UNSUPPORTED_RESOURCE", success = false},
{resultCode = "OUT_OF_MEMORY", success = false},
{resultCode = "TOO_MANY_PENDING_REQUESTS", success = false},
{resultCode = "APPLICATION_NOT_REGISTERED", success = false},
{resultCode = "GENERIC_ERROR", success = false},
{resultCode = "WARNINGS", success = true}
}
for i =1, #resultCodes do
Test[APIName.."_Response_resultCode_IsValidValue_" .. resultCodes[i].resultCode .."_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
self.hmiConnection:SendResponse(data.id, data.method, resultCodes[i].resultCode, {})
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
if
resultCodes[i].resultCode == "UNSUPPORTED_RESOURCE" then
resultCodes[i].resultCode = "WARNINGS"
resultCodes[i].success = true
end
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = resultCodes[i].success, resultCode = resultCodes[i].resultCode})
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_resultCode_IsValidValue_" .. resultCodes[i].resultCode .."_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
self.hmiConnection:SendError(data.id, data.method, resultCodes[i].resultCode, "info")
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
if
resultCodes[i].resultCode == "UNSUPPORTED_RESOURCE" then
resultCodes[i].resultCode = "WARNINGS"
resultCodes[i].success = true
end
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = resultCodes[i].success, resultCode = resultCodes[i].resultCode, info = "info"})
end
-----------------------------------------------------------------------------------------
end
-----------------------------------------------------------------------------------------
--3. IsNotExist
--4. IsEmpty
--5. IsWrongType
--6. IsInvalidCharacter - \n, \t
local testData = {
{value = "ANY", name = "IsNotExist"},
{value = "", name = "IsEmpty"},
{value = 123, name = "IsWrongType"},
{value = "a\nb", name = "IsInvalidCharacter_NewLine"},
{value = "a\tb", name = "IsInvalidCharacter_Tab"}}
for i =1, #testData do
Test[APIName.."_Response_resultCode_" .. testData[i].name .."_SendResponse_GENERIC_ERROR"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
self.hmiConnection:SendResponse(data.id, data.method, testData[i].value, {})
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
--TODO: update after resolving APPLINK-14765
-- EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA"})
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_resultCode_" .. testData[i].name .."_SendError_GENERIC_ERROR"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
self.hmiConnection:SendError(data.id, data.method, testData[i].value)
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
--TODO: update after resolving APPLINK-14765
-- EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA"})
end
-----------------------------------------------------------------------------------------
end
-----------------------------------------------------------------------------------------
end
verify_resultCode_parameter()
-----------------------------------------------------------------------------------------------
--Parameter 2: method
-----------------------------------------------------------------------------------------------
--List of test cases:
--1. IsMissed
--2. IsValidResponse
--3. IsNotValidResponse
--4. IsOtherResponse
--5. IsEmpty
--6. IsWrongType
--7. IsInvalidCharacter - \n, \t
-----------------------------------------------------------------------------------------------
local function verify_method_parameter()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("TestCaseGroupForMethodParameter")
--1. IsMissed
Test[APIName.."_Response_method_IsMissed_GENERIC_ERROR_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"code":0}}')
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
Test[APIName.."_Response_method_IsMissed_GENERIC_ERROR_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","error":{"data":{"method":"TTS.Speak"},"code":22,"message":"The unknown issue occurred"}}')
self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","error":{"data":{},"code":22,"message":"The unknown issue occurred"}}')
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
--2. IsValidResponse: Covered by many test cases
--3. IsNotValidResponse
--4. IsOtherResponse
--5. IsEmpty
--6. IsWrongType
--7. IsInvalidCharacter - \n, \t, spaces
local Methods = {
{method = "ANY", name = "IsNotValidResponse"},
{method = "GetCapabilities", name = "IsOtherResponse"},
{method = "", name = "IsEmpty"},
{method = 123, name = "IsWrongType"},
{method = "a\nb", name = "IsInvalidCharacter_NewLine"},
{method = "a\tb", name = "IsInvalidCharacter_Tab"},
{method = " ", name = "IsSpaces"},
}
for i =1, #Methods do
Test[APIName.."_Response_method_" .. Methods[i].name .."_GENERIC_ERROR_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
self.hmiConnection:SendResponse(data.id, Methods[i].method, "SUCCESS", {})
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_method_" .. Methods[i].name .."_GENERIC_ERROR_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:SendError(data.id, data.method, "UNSUPPORTED_RESOURCE", "info")
self.hmiConnection:SendError(data.id, Methods[i].method, "UNSUPPORTED_RESOURCE", "info")
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
end
-----------------------------------------------------------------------------------------
end
verify_method_parameter()
-----------------------------------------------------------------------------------------------
--Parameter 3: info
-----------------------------------------------------------------------------------------------
--List of test cases:
--1. IsMissed
--2. IsLowerBound
--3. IsUpperBound
--4. IsOutUpperBound
--5. IsEmpty/IsOutLowerBound
--6. IsWrongType
--7. InvalidCharacter - \n, \t
-----------------------------------------------------------------------------------------------
local function verify_info_parameter()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("TestCaseGroupForInfoParameter")
-----------------------------------------------------------------------------------------
--1. IsMissed
Test[APIName.."_Response_info_IsMissed_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS"})
:ValidIf (function(_,data)
if data.payload.info then
Print(" SDL resends info parameter to mobile app. info = \"" .. data.payload.info .. "\"")
return false
else
return true
end
end)
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_info_IsMissed_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending the response
self.hmiConnection:SendError(data.id, data.method, "GENERIC_ERROR")
end)
--mobile side: expect the response
--TODO: update after resolving APPLINK-14765
-- EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA"})
end
-----------------------------------------------------------------------------------------
--2. IsLowerBound
--3. IsUpperBound
local testData = {
{value = "a", name = "IsLowerBound"},
{value = commonFunctions:createString(1000), name = "IsUpperBound"}}
for i =1, #testData do
Test[APIName.."_Response_info_" .. testData[i].name .."_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending the response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {info = testData[i].value})
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", info = testData[i].value})
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_info_" .. testData[i].name .."_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending the response
self.hmiConnection:SendError(data.id, data.method, "GENERIC_ERROR", testData[i].value)
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = testData[i].value})
end
-----------------------------------------------------------------------------------------
end
-----------------------------------------------------------------------------------------
--TODO: update after resolving APPLINK-14551
-- --4. IsOutUpperBound
-- Test[APIName.."_Response_info_IsOutUpperBound_SendResponse"] = function(self)
-- local infoMaxLength = commonFunctions:createString(1000)
-- --mobile side: sending the request
-- local Request = self:createRequest()
-- local cid = self.mobileSession:SendRPC("Speak", Request)
-- --hmi side: expect the request
-- EXPECT_HMICALL("TTS.Speak", Request)
-- :Do(function(_,data)
-- --hmi side: sending the response
-- self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {info = infoMaxLength .. "1"})
-- end)
-- --mobile side: expect the response
-- EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", info = infoMaxLength})
-- end
-- -----------------------------------------------------------------------------------------
-- Test[APIName.."_Response_info_IsOutUpperBound_SendError"] = function(self)
-- local infoMaxLength = commonFunctions:createString(1000)
-- --mobile side: sending the request
-- local Request = self:createRequest()
-- local cid = self.mobileSession:SendRPC("Speak", Request)
-- --hmi side: expect the request
-- EXPECT_HMICALL("TTS.Speak", Request)
-- :Do(function(_,data)
-- --hmi side: sending the response
-- self.hmiConnection:SendError(data.id, data.method, "GENERIC_ERROR", infoMaxLength .."1")
-- end)
-- --mobile side: expect the response
-- EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = infoMaxLength})
-- end
-----------------------------------------------------------------------------------------
--5. IsEmpty/IsOutLowerBound
--6. IsWrongType
--7. InvalidCharacter - \n, \t
--TODO: update after resolving APPLINK-14551
-- local testData = {
-- {value = "", name = "IsEmpty_IsOutLowerBound"},
-- {value = 123, name = "IsWrongType"},
-- {value = "a\nb", name = "IsInvalidCharacter_NewLine"},
-- {value = "a\tb", name = "IsInvalidCharacter_Tab"}}
-- for i =1, #testData do
-- Test[APIName.."_Response_info_" .. testData[i].name .."_SendResponse"] = function(self)
-- --mobile side: sending the request
-- local Request = self:createRequest()
-- local cid = self.mobileSession:SendRPC("Speak", Request)
-- --hmi side: expect the request
-- EXPECT_HMICALL("TTS.Speak", Request)
-- :Do(function(_,data)
-- --hmi side: sending the response
-- self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {info = testData[i].value})
-- end)
-- --mobile side: expect the response
-- EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS"})
-- :ValidIf (function(_,data)
-- if data.payload.info then
-- commonFunctions:printError(" SDL resends info parameter to mobile app. info = \"" .. data.payload.info .. "\"")
-- return false
-- else
-- return true
-- end
-- end)
-- end
-- -----------------------------------------------------------------------------------------
-- Test[APIName.."_Response_info_" .. testData[i].name .."_SendError"] = function(self)
-- --mobile side: sending the request
-- local Request = self:createRequest()
-- local cid = self.mobileSession:SendRPC("Speak", Request)
-- --hmi side: expect the request
-- EXPECT_HMICALL("TTS.Speak", Request)
-- :Do(function(_,data)
-- --hmi side: sending the response
-- self.hmiConnection:SendError(data.id, data.method, "GENERIC_ERROR", testData[i].value)
-- end)
-- --mobile side: expect the response
-- EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
-- :ValidIf (function(_,data)
-- if data.payload.info then
-- commonFunctions:printError(" SDL resends info parameter to mobile app. info = \"" .. data.payload.info .. "\"")
-- return false
-- else
-- return true
-- end
-- end)
-- end
-- -----------------------------------------------------------------------------------------
-- end
-----------------------------------------------------------------------------------------
end
verify_info_parameter()
-----------------------------------------------------------------------------------------------
--Parameter 4: correlationID
-----------------------------------------------------------------------------------------------
--List of test cases:
--1. IsMissed
--2. IsNonexistent
--3. IsWrongType
--4. IsNegative
-----------------------------------------------------------------------------------------------
local function verify_correlationID_parameter()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("TestCaseGroupForCorrelationIDParameter")
-----------------------------------------------------------------------------------------
--1. IsMissed
Test[APIName.."_Response_CorrelationID_IsMissed_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
self.hmiConnection:Send('{"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_CorrelationID_IsMissed_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending the response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","error":{"code":0,"message":"error message","data":{"method":"TTS.Speak"}}}')
self.hmiConnection:Send('{"jsonrpc":"2.0","error":{"code":0,"message":"error message","data":{"method":"TTS.Speak"}}}')
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
--2. IsNonexistent
Test[APIName.."_Response_CorrelationID_IsNonexistent_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
self.hmiConnection:Send('{"id":'..tostring(5555)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_CorrelationID_IsNonexistent_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending the response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","error":{"code":0,"message":"error message","data":{"method":"TTS.Speak"}}}')
self.hmiConnection:Send('{"id":'..tostring(5555)..',"jsonrpc":"2.0","error":{"code":0,"message":"error message","data":{"method":"TTS.Speak"}}}')
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
--3. IsWrongType
Test[APIName.."_Response_CorrelationID_IsWrongType_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {info = "info message"})
self.hmiConnection:SendResponse(tostring(data.id), data.method, "SUCCESS", {info = "info message"})
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_CorrelationID_IsWrongType_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending the response
--self.hmiConnection:SendError(data.id, data.method, "REJECTED", "error message")
self.hmiConnection:SendError(tostring(data.id), data.method, "REJECTED", "error message")
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
--4. IsNegative
Test[APIName.."_Response_CorrelationID_IsNegative_SendResponse"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendNotification("TTS.Stopped")
--hmi side: sending the response
--self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {info = "info message"})
self.hmiConnection:SendResponse(-1, data.method, "SUCCESS", {info = "info message"})
end
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
Test[APIName.."_Response_CorrelationID_IsNegative_SendError"] = function(self)
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending the response
--self.hmiConnection:SendError(data.id, data.method, "REJECTED", "error message")
self.hmiConnection:SendError(-1, data.method, "REJECTED", "error message")
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
-----------------------------------------------------------------------------------------
end
verify_correlationID_parameter()
----------------------------------------------------------------------------------------------
-----------------------------------------TEST BLOCK IV----------------------------------------
------------------------------Check special cases of HMI response-----------------------------
----------------------------------------------------------------------------------------------
--Begin Test case SpecialResponseChecks
--Description: Check all negative response cases
--Requirement id in JAMA:
--SDLAQ-CRS-55 (Speak_Response_v2_0)
--SDLAQ-CRS-505 (INVALID_DATA)
--SDLAQ-CRS-504 (SUCCESS)
--SDLAQ-CRS-509 (REJECTED)
--SDLAQ-CRS-510 (ABORTED)
--SDLAQ-CRS-512 (DISALLOWED)
--SDLAQ-CRS-1027 (UNSUPPORTED_RESOURCE)
--SDLAQ-CRS-1030 (WARNINGS)
local function SpecialResponseChecks()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("TestCaseGroupForHMINegativeCases")
----------------------------------------------------------------------------------------------
--Begin Test case SpecialResponseChecks.1
--Description: Invalid JSON
--Requirement id in JAMA: SDLAQ-CRS-58
--Verification criteria: The response contains 2 mandatory parameters "success" and "resultCode", "info" is sent if there is any additional information about the resultCode.
--[[ToDo: Update when APPLINK resolving APPLINK-14776 SDL behavior in case HMI sends invalid message or message with fake parameters
function Test:Speak_Response_IsInvalidJson_GENERIC_ERROR()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending the response
--":" is changed by ";" after {"id"
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
self.hmiConnection:Send('{"id";'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR" })
:Timeout(12000)
end
]]
--End Test case SpecialResponseChecks.1
--Begin Test case SpecialResponseChecks.2
--Description: Check processing response with fake parameters
--Verification criteria: When expected HMI function is received, send responses from HMI with fake parameter
--Begin Test case SpecialResponseChecks.2.1
--Description: Parameter is not from API
function Test:Speak_Response_FakeParams_IsNotFromAnyAPI_SUCCESS()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(exp,data)
--hmi side: sending the response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {fake = "fake"})
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
:ValidIf (function(_,data)
if data.payload.fake then
commonFunctions:printError(" SDL resend fake parameter to mobile app ")
return false
else
return true
end
end)
end
--End Test case SpecialResponseChecks.2.1
--Begin Test case SpecialResponseChecks.2.2
--Description: Parameter is not from another API
function Test:Speak_Response_FakeParams_IsFromAnotherAPI_SUCCESS()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(exp,data)
--hmi side: sending the response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {sliderPosition = 5})
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
:ValidIf (function(_,data)
if data.payload.sliderPosition then
commonFunctions:printError(" SDL resend fake parameter to mobile app ")
return false
else
return true
end
end)
end
--End Test case SpecialResponseChecks.2.2
--End Test case SpecialResponseChecks.2
--Begin SpecialResponseChecks.3
--Description: Check processing response without all parameters
--[[ToDo: Update when APPLINK resolving APPLINK-14776 SDL behavior in case HMI sends invalid message or message with fake parameters
function Test:Speak_Response_IsMissedAllPArameters_GENERIC_ERROR()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending TTS.Speak response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
self.hmiConnection:Send('{}')
end)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(13000)
end
]]
--End SpecialResponseChecks.3
--Begin Test case SpecialResponseChecks.4
--Description: Request without responses from HMI
--Requirement id in JAMA: SDLAQ-CRS-500
--Verification criteria: GENERIC_ERROR comes as a result code in response when all other codes aren't applicable or the unknown issue occured.
function Test:Speak_NoResponse_GENERIC_ERROR()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR"})
:Timeout(12000)
end
--End SpecialResponseChecks.4
--Begin Test case SpecialResponseChecks.5
--Description: Invalid structure of response
--Requirement id in JAMA: SDLAQ-CRS-58
--Verification criteria: The response contains 2 mandatory parameters "success" and "resultCode", "info" is sent if there is any additional information about the resultCode
--ToDo: Update when APPLINK resolving APPLINK-14776 SDL behavior in case HMI sends invalid message or message with fake parameters
function Test:Speak_Response_IsInvalidStructure_GENERIC_ERROR()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
--hmi side: sending the response
--self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0","result":{"method":"TTS.Speak", "code":0}}')
self.hmiConnection:Send('{"id":'..tostring(data.id)..',"jsonrpc":"2.0", "code":0, "result":{"method":"TTS.Speak"}}')
end)
--mobile side: expect response
--TODO update according to APPLINK-14765
-- EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA"})
:Timeout(12000)
end
--End Test case SpecialResponseChecks.5
--Begin Test case SpecialResponseChecks.6
--Description: Several response to one request
--Requirement id in JAMA: SDLAQ-CRS-58
--Verification criteria: The response contains 2 mandatory parameters "success" and "resultCode", "info" is sent if there is any additional information about the resultCode.
--Begin Test case SpecialResponseChecks.6.1
--Description: Several response to one request
function Test:Speak_Response_SeveralResponseToOneRequest()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(exp,data)
--hmi side: sending the response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS"})
end
--End Test case SpecialResponseChecks.6.1
--Begin Test case SpecialResponseChecks.6.2
--Description: Several response to one request
function Test:Speak_Response_SeveralResponse_WithConstractionsOfResult()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect the request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(exp,data)
--hmi side: sending the response
self.hmiConnection:SendResponse(data.id, data.method, "INVALID_DATA", {})
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect response
EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA"})
end
--End Test case SpecialResponseChecks.6.2
-----------------------------------------------------------------------------------------
--End Test case SpecialResponseChecks.6
end
SpecialResponseChecks()
--End Test case SpecialResponseChecks
-----------------------------------------------------------------------------------------------
-------------------------------------------TEST BLOCK V----------------------------------------
-------------------------------------Checks All Result Codes-----------------------------------
-----------------------------------------------------------------------------------------------
--Begin Test case ResultCodeChecks
--Description: Check all resultCodes
--Requirement id in JAMA:
--1. SUCCESS: SDLAQ-CRS-504
--2. INVALID_DATA: SDLAQ-CRS-505
--3. OUT_OF_MEMORY: SDLAQ-CRS-506
--4. TOO_MANY_PENDING_REQUESTS: SDLAQ-CRS-507
--5. APPLICATION_NOT_REGISTERED: SDLAQ-CRS-508
--6. REJECTED: SDLAQ-CRS-509
--7. ABORTED: SDLAQ-CRS-510
--8. GENERIC_ERROR: SDLAQ-CRS-511
--9. DISALLOWED: SDLAQ-CRS-512
--10. UNSUPPORTED_RESOURCE: SDLAQ-CRS-1027
--11. WARNINGS: SDLAQ-CRS-1030
local function ResultCodeChecks()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("TestCaseGroupForAllResultCodesVerification")
----------------------------------------------------------------------------------------------
--Check resultCode SUCCESS. It is checked by other test cases.
--Check resultCode INVALID_DATA. It is checked by other test cases.
--Check resultCode REJECTED, UNSUPPORTED_RESOURCE, ABORTED, WARNINGS: Covered by test case resultCode_IsValidValue
--Check resultCode GENERIC_ERROR. It is covered in Test:Speak_NoResponse
--Check resultCode OUT_OF_MEMORY. ToDo: Wait until requirement is clarified
--Check resultCode TOO_MANY_PENDING_REQUESTS. It is moved to other script.
-----------------------------------------------------------------------------------------
--Begin Test case ResultCodeChecks.1
--Description: Check resultCode APPLICATION_NOT_REGISTERED: SDLAQ-CRS-508
--Requirement id in JAMA: SDLAQ-CRS-508
--Verification criteria: SDL sends APPLICATION_NOT_REGISTERED code when the app sends a request within the same connection before RegisterAppInterface has been performed yet.
commonTestCases:verifyResultCode_APPLICATION_NOT_REGISTERED()
--End Test case ResultCodeChecks.1
-----------------------------------------------------------------------------------------
--Begin Test case ResultCodeChecks.2
--Description: Check resultCode DISALLOWED: SDLAQ-CRS-512
--Requirement id in JAMA: SDLAQ-CRS-512
--Verification criteria:
--1. SDL must return "resultCode: DISALLOWED, success:false" to the RPC in case this RPC is omitted in the PolicyTable group(s) assigned to the app that requests this RPC.
--2. SDL must return "resultCode: DISALLOWED, success:false" to the RPC in case this RPC is included to the PolicyTable group(s) assigned to the app that requests this RPC and the group has not yet received user's consents.
--[[TODO debug after resolving APPLINK-13101
--Begin Test case ResultCodeChecks.2.1
--Description: 1. SDL must return "resultCode: DISALLOWED, success:false" to the RPC in case this RPC is omitted in the PolicyTable group(s) assigned to the app that requests this RPC.
policyTable:checkPolicyWhenAPIIsNotExist()
--End Test case ResultCodeChecks.2.1
--Begin Test case ResultCodeChecks.2.2
--Description: 2. SDL must return "resultCode: DISALLOWED, success:false" to the RPC in case this RPC is included to the PolicyTable group(s) assigned to the app that requests this RPC and the group has not yet received user's consents.
policyTable:checkPolicyWhenUserDisallowed({"FULL", "LIMITED"})
--End Test case ResultCodeChecks.2.2
]]
--End Test case ResultCodeChecks.2
-----------------------------------------------------------------------------------------
end
ResultCodeChecks()
--End Test case ResultCodeChecks
----------------------------------------------------------------------------------------------
-----------------------------------------TEST BLOCK VI----------------------------------------
-------------------------Sequence with emulating of user's action(s)--------------------------
----------------------------------------------------------------------------------------------
--Begin Test suit SequenceChecks
--Description: TC's checks SDL behavior by processing
-- different request sequence with timeout
-- with emulating of user's actions
local function SequenceChecks()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("TestCaseGroupForSequenceChecks")
----------------------------------------------------------------------------------------------
--Begin Test case SequenceChecks.1
--Description: Check for manual test case TC_Speak_01
--Requirement id in JAMA: SDLAQ-TC-120
--Verification criteria: Call Speak request from mobile app on HMI
function Test:Speak_TC_Speak_01()
--verify type = TEXT
local Request = {
ttsChunks =
{
{text ="Text1", type ="TEXT"},
{text ="Text2", type ="TEXT"},
{text ="Text3", type ="TEXT"},
}
}
self:verify_SUCCESS_Case(Request)
--verify type = TEXT, text = " ": it is covered by verify_String_Parameter_WithOut_Madatory_Check (7. IsInvalidCharacters: "\n", "\t", " ")
end
--End Test case SequenceChecks.1
-----------------------------------------------------------------------------------------
--Begin Test case SequenceChecks.2
--Description:
--Check for manual test case TC_Speak_02:
--Requirement id in JAMA: SDLAQ-TC-777
--Verification criteria: Call Speak request from mobile app on HMI and check TTS.OnResetTimeout notification received from HMI
function Test:Speak_TC_Speak_02_Step1()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect TTS.Speak request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendResponse(SpeakId, "TTS.Speak", "SUCCESS", { })
self.hmiConnection:SendNotification("TTS.Stopped")
end
local function SendOnResetTimeout()
self.hmiConnection:SendNotification("TTS.OnResetTimeout", {appID = self.applications["Test Application"], methodName = "TTS.Speak"})
end
--send TTS.OnResetTimeout notification after 9 seconds
RUN_AFTER(SendOnResetTimeout, 9000)
--send TTS.Speak response after 9 seconds after reset timeout
RUN_AFTER(speakResponse, 18000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self, "FULL", 20000)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
:Timeout(20000)
end
function Test:Speak_TC_Speak_02_Step2()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect TTS.Speak request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
self.hmiConnection:SendResponse(SpeakId, "TTS.Speak", "SUCCESS", { })
self.hmiConnection:SendNotification("TTS.Stopped")
end
local function SendOnResetTimeout()
self.hmiConnection:SendNotification("TTS.OnResetTimeout", {appID = self.applications["Test Application"], methodName = "TTS.Speak"})
end
--send TTS.OnResetTimeout notification after 9 seconds
RUN_AFTER(SendOnResetTimeout, 9000)
--send TTS.OnResetTimeout notification after 9 seconds
RUN_AFTER(SendOnResetTimeout, 18000)
--send TTS.OnResetTimeout notification after 9 seconds
RUN_AFTER(SendOnResetTimeout, 24000)
--send TTS.Speak response after 9 seconds after reset timeout
RUN_AFTER(speakResponse, 33000)
end)
--mobile side: expect OnHashChange notification
ExpectOnHMIStatusWithAudioStateChanged(self, "FULL", 35000)
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
:Timeout(35000)
end
--End Test case SequenceChecks.2
-----------------------------------------------------------------------------------------
--Begin Test case SequenceChecks.3
--Description: Check for manual test case TC_Speak_03
--Requirement id in JAMA: SDLAQ-TC-778
--Verification criteria: Call Speak request from mobile app on HMI and check TTS.OnResetTimeout notification received from HMI
function Test:Speak_TC_Speak_03()
--mobile side: sending the request
local Request = self:createRequest()
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect TTS.Speak request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function SendOnResetTimeout()
self.hmiConnection:SendNotification("TTS.OnResetTimeout", {appID = self.applications["Test Application"], methodName = "TTS.Speak"})
end
--send TTS.OnResetTimeout notification after 9 seconds
RUN_AFTER(SendOnResetTimeout, 9000)
end)
--mobile side: expect OnHashChange notification
if commonFunctions:isMediaApp() then
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "ATTENUATED"})
else
EXPECT_NOTIFICATION("OnHMIStatus", {})
:Times(0)
end
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR" })
:Timeout(22000)
end
function Test:PostCondition()
self.hmiConnection:SendNotification("TTS.Stopped")
--mobile side: expect OnHashChange notification
if commonFunctions:isMediaApp() then
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "AUDIBLE"})
else
EXPECT_NOTIFICATION("OnHMIStatus")
:Times(0)
end
end
--End Test case SequenceChecks.3
-----------------------------------------------------------------------------------------
--Begin Test case SequenceChecks.4
--Description: Check for manual test case TC_Speak_04
--Requirement id in JAMA: SDLAQ-TC-1085
--Verification criteria: This test case is check that Speak response with "success"="false" when ResultCode is "ABORTED"
function Test:Speak_TC_Speak_04()
local Request = {
ttsChunks =
{
{text ="Text1", type ="TEXT"},
{text ="Text2", type ="TEXT"},
{text ="Text3", type ="TEXT"},
}
}
--mobile side: sending the request
local cid = self.mobileSession:SendRPC("Speak", Request)
--hmi side: expect TTS.Speak request
EXPECT_HMICALL("TTS.Speak", Request)
:Do(function(_,data)
self.hmiConnection:SendNotification("TTS.Started")
SpeakId = data.id
local function speakResponse()
--HMI sends TTS.Speak: ABORTED
self.hmiConnection:SendResponse(SpeakId, "TTS.Speak", "ABORTED", { })
--HMI sends TTS.Stopped
self.hmiConnection:SendNotification("TTS.Stopped")
--HMI sends VR.Started
self.hmiConnection:SendNotification("VR.Started")
--HMI sends UI.OnSystemContext
self.hmiConnection:SendNotification("UI.OnSystemContext",{ appID = self.applications["Test Application"], systemContext = "VRSESSION" })
end
--HMI sends response and notifications
RUN_AFTER(speakResponse, 1000)
end)
--mobile side: expect OnHashChange notification
if commonFunctions:isMediaApp() then
EXPECT_NOTIFICATION("OnHMIStatus",
{systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "ATTENUATED"},
{systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "AUDIBLE"},
{systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "NOT_AUDIBLE"},
{systemContext = "VRSESSION", hmiLevel = "FULL", audioStreamingState = "NOT_AUDIBLE"})
:Times(4)
else
EXPECT_NOTIFICATION("OnHMIStatus",
{systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "NOT_AUDIBLE"},
{systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "NOT_AUDIBLE"},
{systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "NOT_AUDIBLE"},
{systemContext = "VRSESSION", hmiLevel = "FULL", audioStreamingState = "NOT_AUDIBLE"})
:Times(4)
end
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = false, resultCode = "ABORTED" })
end
function Test:PostCondition()
--HMI sends VR.Started
self.hmiConnection:SendNotification("VR.Stopped")
--HMI sends UI.OnSystemContext
self.hmiConnection:SendNotification("UI.OnSystemContext",{ appID = self.applications["Test Application"], systemContext = "MAIN" })
--mobile side: expect OnHashChange notification
if commonFunctions:isMediaApp() then
EXPECT_NOTIFICATION("OnHMIStatus",
{systemContext = "VRSESSION", hmiLevel = "FULL", audioStreamingState = "AUDIBLE"},
{systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "AUDIBLE"})
:Times(2)
else
EXPECT_NOTIFICATION("OnHMIStatus",
{systemContext = "VRSESSION", hmiLevel = "FULL", audioStreamingState = "NOT_AUDIBLE"},
{systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "NOT_AUDIBLE"})
:Times(0)
end
end
--End Test case SequenceChecks.4
-----------------------------------------------------------------------------------------
end
SequenceChecks()
--End Test suit SequenceChecks
----------------------------------------------------------------------------------------------
-----------------------------------------TEST BLOCK VII---------------------------------------
--------------------------------------Different HMIStatus-------------------------------------
----------------------------------------------------------------------------------------------
--SDLAQ-CRS-778: HMI Status Requirements for Speak
--SDL rejects Speak request with REJECTED resultCode when current HMI level is NONE or BACKGROUND.
--SDL doesn't reject Speak request when current HMI is FULL.
--SDL doesn't reject Speak request when current HMI is LIMITED.
--Verify resultCode in NONE, LIMITED, BACKGROUND hmi level
commonTestCases:verifyDifferentHMIStatus("DISALLOWED", "SUCCESS", "DISALLOWED")
---------------------------------------------------------------------------------------------
-------------------------------------------Postcondition-------------------------------------
---------------------------------------------------------------------------------------------
--Print new line to separate Postconditions
commonFunctions:newTestCasesGroup("Postconditions")
--Restore sdl_preloaded_pt.json
policyTable:Restore_preloaded_pt()
return Test
|
return {
source = {
type = 'dist',
-- https://sourcery.mentor.com/GNUToolchain/subscription3130?lite=MIPS
location = 'https://sourcery.mentor.com/GNUToolchain/package10395/public/mips-linux-gnu/mips-2012.03-63-mips-linux-gnu-i686-pc-linux-gnu.tar.bz2',
sha256sum = '0a2d92bbca2926479662affcc4dcb644ddca7d8d50ec17ed3b99d7025a552530',
md5sum = '44970134eea6f6ab754a7bbe6e2805d6',
basename = 'mips-2012.03'
},
build = {
arch = 'mips',
system = 'mips-linux-gnu',
cpu = '24kf',
cflags = '-EL -march=24kf -mtune=24kf -Wa,-mips32r2',
toolchain = false
},
install = 'toolchain'
}
|
Config = {
Command = 'notificationsettings',
}
|
--- Some design choices:
--
-- - only cache in SHM, since it is a single string value, adding lua-land
-- lru caches seems just a waste of memory
-- - 404 expected if custom_id isn't found, makes it harder to spot errors
-- when configured with a bad path...
-- - 200 expected if custom_id is found and a jwt is returned
-- - JWT validates exp only! downstream is doing validation!
-- endpoint returns 200 for ok, everything else should result in a 500 from Kong with the error messages logged in Kong logs.
local plugin_name = ({...})[1]:match("^kong%.plugins%.([^%.]+)") -- Grab pluginname from module name
-- Constants
local NOT_FOUND_TOKEN = -1 -- value MUST be illegal as a JWT string, but thruthy
local SHM_PREFIX = "[" .. plugin_name .. "]:"
local EMPTY = require("pl.tablex").readonly({})
local SCHEME_ID, HOST_ID, PORT_ID, PATH_ID, QUERY_ID = 1,2,3,4,5
local FORBIDDEN = 403
-- Modules
local json_decode = require("cjson.safe").decode
local resty_lock = require "resty.lock"
local http = require "resty.http"
-- Locals
local ngx_req_set_header = ngx.req.set_header
local ngx_decode_base64 = ngx.decode_base64
local string_rep = string.rep
local conf_cache -- cache for prepared conf, implementation below
local ngx_now = ngx.now
local ngx_log = ngx.log
local ngx_ERR = ngx.ERR
local ngx_WARN = ngx.WARN
-- load the base plugin object and create a subclass
local plugin = require("kong.plugins.base_plugin"):extend()
-- set the plugin priority, which determines plugin execution order
-- See: https://docs.konghq.com/1.0.x/plugin-development/custom-logic/#plugins-execution-order
plugin.PRIORITY = 940 -- run after auth plugins and acl, but before rate-limiting
--plugin.PRIORITY = 850 -- run after rate-limiting
-- constructor
function plugin:new()
plugin.super.new(self, plugin_name)
end
-- Fetches JWT from remote server.
-- @param conf plugin configuration
-- @param id the custom_id for which to find the JWT
-- @return jwt, or nil if not found, or nil+err in case of error
local function fetch_jwt(conf, id)
local client = http.new()
client:set_timeout(conf.timeout)
local url_elements = conf.url_elements
assert(client:connect(url_elements[HOST_ID], url_elements[PORT_ID]))
if url_elements[SCHEME_ID] == "https" then
assert(client:ssl_handshake())
end
local res, err = client:request {
method = "GET",
path = url_elements[PATH_ID] .. url_elements[QUERY_ID] .. id,
}
if not res then
client:close()
error("failed sending request: " .. tostring(err))
end
local body = res:read_body()
local status = res.status
local ok
ok, err = client:set_keepalive(conf.keepalive)
if not ok then
client:close()
ngx_log(ngx_WARN, "failed setting keepalive: ", err)
end
if status < 200 or status > 299 then
-- an unexpected response
return nil, ("bad status code received '%s', expected 2xx. Body: %s"):format(tostring(status), body or "")
end
-- we received a 2xx
local jwt
local json = json_decode(body)
if (conf.response_key or "") == "" then
-- no object just a json string value
if type(json) ~= "string" then
return nil, "expected json string value, got: " .. tostring(json)
end
jwt = json
else
-- json object
if type(json) ~= "table" then
return nil, "expected json object, got: " .. tostring(json)
end
jwt = json[conf.response_key]
if type(jwt) ~= "string" then
return nil, ("expected json object to have a string value named " ..
"'%s', got: %s"):format(conf.response_key, tostring(jwt))
end
end
return jwt
end
-- base 64 decode
-- @param input String to base64 decode
-- @return Base64 decoded string
local function base64_decode(input)
local remainder = #input % 4
if remainder > 0 then
local padlen = 4 - remainder
input = input .. string_rep("=", padlen)
end
input = input:gsub("-", "+"):gsub("_", "/")
return ngx_decode_base64(input)
end
local parse_err = function(err)
return "invalid jwt" .. (err and (": " .. err) or "")
end
-- Returns the ttl for this JWT token.
-- @param jwt the JWT to parse
-- @return ttl in seconds, or nil+err
local function parse_jwt_ttl(conf, jwt)
local err = nil
local s = jwt:find(".",1, true) -- first dot
if not s then error(parse_err(err)) end
local e = jwt:find(".", s + 1, true) -- second dot
if not s then error(parse_err(err)) end
local data
data = jwt:sub(s + 1, e - 1)
data, err = base64_decode(data)
if not data then error(parse_err(err)) end
local claims
claims, err = json_decode(data)
if not claims then error(parse_err(err)) end
local exp
exp = claims.exp
if not exp then error(parse_err("missing 'exp' claim")) end
local ttl = (tonumber(exp) or 0) - ngx_now() + conf.skew
if ttl <= 0 then return nil, parse_err("expired") end
return ttl
end
-- Runs a function inside a lock.
-- Ensures only one runs at a time for the given key.
-- @param conf plugin configuration
-- @param key the key to identify the lock
-- @param f function to run, MUST return max 2 values!
local function run_in_lock(conf, key, f)
local lock, ok, err
-- create lock
lock, err = resty_lock:new(conf.shm)
if not lock then
return nil, "failed to create lock: " .. tostring(err)
end
-- acquire lock
ok, err = lock:lock("[lock]"..key)
if not ok then
return nil, "failed to acquire lock: " .. tostring(err)
end
-- execute function
local r_ok, r_result, r_err = pcall(f)
-- release lock
ok, err = lock:unlock()
if not ok then
return nil, "failed to release lock: " .. tostring(err)
end
if not r_ok then
-- was a hard error, so 'result' holds the error, re-throw outside lock
error(r_result)
end
return r_result, r_err -- either success or a soft error
end
-- Gets the JWT from cache, or goes fetch it remotely otherwise.
-- @param conf plugin configuration
-- @param id the custom_id for which to find the JWT
-- @return jwt, or nil if not found, or nil+err in case of error
local function get_jwt(conf, id)
local shm = ngx.shared[conf.shm]
local key = conf.shm_key_prefix .. id
if not shm then
error(("shm by name '%s' not found"):format(tostring(conf.shm)))
end
local jwt, err = shm:get(key)
if err then
error("failed to get shm value: " .. tostring(err))
elseif jwt then
return jwt ~= NOT_FOUND_TOKEN and jwt or nil -- return cached result
end
-- not cached, so go and look it up
jwt, err = run_in_lock(conf, key, function()
-- we acquired a lock by now, so first check whether we by
-- now have a cached value
local jwt, err = shm:get(key)
if err then
error("failed to get shm value: " .. tostring(err))
elseif jwt then
return jwt -- return cached result, do NOT resolve the NOT_FOUND_TOKEN
end
-- still nothing, so actually go and fetch it
return fetch_jwt(conf, id)
end)
if err then
return nil, err
end
if jwt == NOT_FOUND_TOKEN then
-- we got this inside the lock, when we retried, so some other worker/request
-- put it in the cache, nothing more for us to do since it is already in the
-- cache and we do not want to override the ttl as set by the first worker
return nil
end
local ttl
if not jwt then
-- no JWT, so do negative caching
jwt = NOT_FOUND_TOKEN
ttl = conf.negative_ttl
else
-- got a JWT, go check the ttl
ttl, err = parse_jwt_ttl(conf, jwt)
if not ttl then
return nil, err -- we failed to parse the JWT
end
end
-- Store JWT in cache for future use
local ok
ok, err = shm:set(key, jwt, ttl)
if not ok then
-- log error, since this is non-fatal
ngx_log(ngx_ERR, "Failed to store JWT in cache: ", err)
end
return jwt ~= NOT_FOUND_TOKEN and jwt or nil
end
-- convert plugin config.
-- Do conversions once here to prevent doing it on every call
local function prepare_conf(conf)
local result = {}
-- copy the table
for k,v in pairs(conf) do
result[k] = v
end
-- convert ttl to seconds
result.negative_ttl = conf.negative_ttl/1000
-- parse url
local url_elements = http:parse_uri(conf.url, false)
-- prepare query element
local query = url_elements[QUERY_ID]
if query == "" then query = nil end
query = query and "?" .. query .. "&" .. conf.query_key .. "="
or "?" .. conf.query_key .. "="
url_elements[QUERY_ID] = query
result.url_elements = url_elements
-- create shm-key prefix
result.shm_key_prefix = SHM_PREFIX .. conf.url .. ":"
-- store it in the cache
conf_cache[conf] = result
return result
end
conf_cache = setmetatable({}, {
__mode = "k",
__index = function(self, conf)
-- the prepared conf table isn't found, create it now and cache it
local new_conf = prepare_conf(conf)
self[conf] = new_conf
return new_conf
end
})
function plugin:access(conf)
plugin.super.access(self)
conf = conf_cache[conf]
local id = (ngx.ctx.authenticated_consumer or EMPTY).custom_id
if id then
local jwt, err = get_jwt(conf, id)
if err then
ngx_log(ngx_ERR, "jwt-fetcher error: ", err)
else
-- we have a valid JWT
ngx_req_set_header("Authorization", "Bearer " .. jwt)
return -- all is well
end
end
kong.response.exit(FORBIDDEN, { message = "You cannot consume this service" })
end
-- return our plugin object
return plugin
|
local tostring, tonumber, select, type, getmetatable, setmetatable, rawget = tostring, tonumber, select, type, getmetatable, setmetatable, rawget
local bit = require('bit')
local band, bor, lshift = bit.band, bit.bor, bit.lshift
local Types = require('types')
local Any, Array = Types.Any, Types.Array
local Auxiliary = {pattern = function (input, p, drop)
local r = input.stream:pattern(p)
if not r then
return false
end
local success, res = input:collect(#r - (drop or 0))
return success, (res:concat())
end, apply = function (input, ruleRef, fallback, ...)
ruleRef = input.grammar[ruleRef]
if not ruleRef then
if not fallback then
return false
end
ruleRef = type(fallback) == 'string' and input.grammar[fallback] or fallback
end
if ... then
return input:applyWithArgs(ruleRef, ...)
else
return input:apply(ruleRef)
end
end}
return Auxiliary
|
local fs = require('efmls-configs.fs')
local linter = 'psalm'
local args = '--no-progress --no-cache --output-format=emacs ${INPUT}'
local command = string.format('%s %s', fs.executable(linter, fs.Scope.COMPOSER), args)
return {
prefix = linter,
lintCommand = command,
lintStdin = false,
lintFormats = { '%.%#:%l:%c:%trror - %m on %.%#', '%.%#:%l:%c:%tarning - %m on %.%#' },
rootMarkers = { 'psalm.xml', 'composer.json' },
}
|
local utils = require "go-tools.utils"
local M = {}
local gomodifytags = "gomodifytags"
local function modify(...)
local fname = vim.fn.expand "%"
local struct_name = require("go-tools.utils.treesitter").get_current_struct()
if not struct_name then
utils.log "Struct not found"
return
end
local cmd = { gomodifytags, "-format", "json", "-file", fname, "-struct", struct_name, "-w" }
local arg = { ... }
for _, v in ipairs(arg) do
table.insert(cmd, v)
end
if #arg == 1 and arg[1] ~= "clear-tags" then
table.insert(cmd, "json")
end
require("go-tools.runner").run(gomodifytags, function()
vim.fn.jobstart(cmd, {
on_stdout = function(_, data, _)
data = require("go-tools.utils").handle_job_data(data)
if not data then
return
end
local tagged = vim.fn.json_decode(data)
if tagged.errors ~= nil or tagged.lines == nil or tagged["start"] == nil or tagged["start"] == 0 then
utils.log("Failed to set tags" .. vim.inspect(tagged))
end
vim.api.nvim_buf_set_lines(0, tagged["start"] - 1, tagged["start"] - 1 + #tagged.lines, false, tagged.lines)
vim.cmd "write"
end,
})
end)
end
function M.add(...)
local cmd = { "-add-tags" }
local arg = { ... }
for _, v in ipairs(arg) do
table.insert(cmd, v)
end
modify(unpack(cmd))
end
function M.remove(...)
local cmd = { "-remove-tags" }
local arg = { ... }
for _, v in ipairs(arg) do
table.insert(cmd, v)
end
modify(unpack(cmd))
end
function M.clear()
modify(unpack { "-clear-tags" })
end
return M
|
--
-- Copyright (C) 2022 Masatoshi Fukunaga
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
local find = string.find
local isa = require('isa')
local is_boolean = isa.boolean
local is_table = isa.table
local is_string = isa.string
local new_header = require('reflex.header').new
local status = require('reflex.status')
--- merge
--- @param dst any
--- @param src table
--- @return table
local function merge(dst, src)
if not is_table(dst) then
dst = {}
end
for k, v in pairs(src) do
if is_table(v) then
dst[k] = merge(dst[k], v)
else
dst[k] = v
end
end
return dst
end
--- response1xx2xx
--- @param res reflex.Response
--- @param code integer
--- @param body table
--- @param tomerge boolean
--- @return integer
local function response1xx2xx(res, code, body, tomerge)
if body ~= nil then
if not is_table(body) then
error('body must be table', 3)
elseif tomerge ~= nil and not is_boolean(tomerge) then
error('tomerge must be boolean', 3)
elseif not tomerge then
res.body = body
else
res.body = merge(res.body, body)
end
end
res.status = code
return code
end
--- response3xx
--- @param res reflex.Response
--- @param code integer
--- @param uri string
--- @return integer
local function response3xx(res, code, uri)
if not is_string(uri) or #uri == 0 or find(uri, '%s') then
error('uri must be non-empty string with no spaces', 3)
end
res.header:set('Location', uri)
res.status = code
return code
end
--- response4xx5xx
--- @param res reflex.Response
--- @param code integer
--- @param err any
--- @return integer
local function response4xx5xx(res, code, err)
if not is_table(res.body) then
res.body = {}
end
res.body.error = {
code = code,
status = status[code],
message = err,
}
res.status = code
return code
end
--- @class reflex.Response
--- @field status integer
--- @field header Header
--- @field body table
--- @field json boolean
local Response = {}
--- init
--- @return reflex.Response
function Response:init()
self.header = new_header()
self.body = {}
return self
end
--- continue
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:continue(body, tomerge)
return response1xx2xx(self, 100, body, tomerge)
end
--- switching_protocols
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:switching_protocols(body, tomerge)
return response1xx2xx(self, 101, body, tomerge)
end
--- processing
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:processing(body, tomerge)
return response1xx2xx(self, 102, body, tomerge)
end
--- ok
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:ok(body, tomerge)
return response1xx2xx(self, 200, body, tomerge)
end
--- created
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:created(body, tomerge)
return response1xx2xx(self, 201, body, tomerge)
end
--- accepted
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:accepted(body, tomerge)
return response1xx2xx(self, 202, body, tomerge)
end
--- non_authoritative_information
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:non_authoritative_information(body, tomerge)
return response1xx2xx(self, 203, body, tomerge)
end
--- no_content
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:no_content(body, tomerge)
return response1xx2xx(self, 204, body, tomerge)
end
--- reset_content
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:reset_content(body, tomerge)
return response1xx2xx(self, 205, body, tomerge)
end
--- partial_content
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:partial_content(body, tomerge)
return response1xx2xx(self, 206, body, tomerge)
end
--- multi_status
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:multi_status(body, tomerge)
return response1xx2xx(self, 207, body, tomerge)
end
--- already_reported
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:already_reported(body, tomerge)
return response1xx2xx(self, 208, body, tomerge)
end
--- im_used
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:im_used(body, tomerge)
return response1xx2xx(self, 226, body, tomerge)
end
--- multiple_choices
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:multiple_choices(body, tomerge)
return response1xx2xx(self, 300, body, tomerge)
end
--- moved_permanently
--- @param uri string
--- @return integer
function Response:moved_permanently(uri)
return response3xx(self, 301, uri)
end
--- found
--- @param uri string
--- @return integer
function Response:found(uri)
return response3xx(self, 302, uri)
end
--- see_other
--- @param uri string
--- @return integer
function Response:see_other(uri)
return response3xx(self, 303, uri)
end
--- not_modified
--- @param body table
--- @param tomerge boolean
--- @return integer
function Response:not_modified(body, tomerge)
return response1xx2xx(self, 304, body, tomerge)
end
--- use_proxy
--- @param uri string
--- @return integer
function Response:use_proxy(uri)
return response3xx(self, 305, uri)
end
--- temporary_redirect
--- @param uri string
--- @return integer
function Response:temporary_redirect(uri)
return response3xx(self, 307, uri)
end
--- permanent_redirect
--- @param uri string
--- @return integer
function Response:permanent_redirect(uri)
return response3xx(self, 308, uri)
end
--- bad_request
--- @param err any
--- @return integer
function Response:bad_request(err)
return response4xx5xx(self, 400, err)
end
--- unauthorized
--- @param err any
--- @return integer
function Response:unauthorized(err)
return response4xx5xx(self, 401, err)
end
--- payment_required
--- @param err any
--- @return integer
function Response:payment_required(err)
return response4xx5xx(self, 402, err)
end
--- forbidden
--- @param err any
--- @return integer
function Response:forbidden(err)
return response4xx5xx(self, 403, err)
end
--- not_found
--- @param err any
--- @return integer
function Response:not_found(err)
return response4xx5xx(self, 404, err)
end
--- method_not_allowed
--- @param err any
--- @return integer
function Response:method_not_allowed(err)
return response4xx5xx(self, 405, err)
end
--- not_acceptable
--- @param err any
--- @return integer
function Response:not_acceptable(err)
return response4xx5xx(self, 406, err)
end
--- proxy_authentication_required
--- @param err any
--- @return integer
function Response:proxy_authentication_required(err)
return response4xx5xx(self, 407, err)
end
--- request_timeout
--- @param err any
--- @return integer
function Response:request_timeout(err)
return response4xx5xx(self, 408, err)
end
--- conflict
--- @param err any
--- @return integer
function Response:conflict(err)
return response4xx5xx(self, 409, err)
end
--- gone
--- @param err any
--- @return integer
function Response:gone(err)
return response4xx5xx(self, 410, err)
end
--- length_required
--- @param err any
--- @return integer
function Response:length_required(err)
return response4xx5xx(self, 411, err)
end
--- precondition_failed
--- @param err any
--- @return integer
function Response:precondition_failed(err)
return response4xx5xx(self, 412, err)
end
--- request_entity_too_large
--- @param err any
--- @return integer
function Response:request_entity_too_large(err)
return response4xx5xx(self, 413, err)
end
--- request_uri_too_long
--- @param err any
--- @return integer
function Response:request_uri_too_long(err)
return response4xx5xx(self, 414, err)
end
--- unsupported_media_type
--- @param err any
--- @return integer
function Response:unsupported_media_type(err)
return response4xx5xx(self, 415, err)
end
--- requested_range_not_satisfiable
--- @param err any
--- @return integer
function Response:requested_range_not_satisfiable(err)
return response4xx5xx(self, 416, err)
end
--- expectation_failed
--- @param err any
--- @return integer
function Response:expectation_failed(err)
return response4xx5xx(self, 417, err)
end
--- unprocessable_entity
--- @param err any
--- @return integer
function Response:unprocessable_entity(err)
return response4xx5xx(self, 422, err)
end
--- locked
--- @param err any
--- @return integer
function Response:locked(err)
return response4xx5xx(self, 423, err)
end
--- failed_dependency
--- @param err any
--- @return integer
function Response:failed_dependency(err)
return response4xx5xx(self, 424, err)
end
--- upgrade_required
--- @param err any
--- @return integer
function Response:upgrade_required(err)
return response4xx5xx(self, 426, err)
end
--- precondition_required
--- @param err any
--- @return integer
function Response:precondition_required(err)
return response4xx5xx(self, 428, err)
end
--- too_many_requests
--- @param err any
--- @return integer
function Response:too_many_requests(err)
return response4xx5xx(self, 429, err)
end
--- request_header_fields_too_large
--- @param err any
--- @return integer
function Response:request_header_fields_too_large(err)
return response4xx5xx(self, 431, err)
end
--- unavailable_for_legal_reasons
--- @param err any
--- @return integer
function Response:unavailable_for_legal_reasons(err)
return response4xx5xx(self, 451, err)
end
--- internal_server_error
--- @param err any
--- @return integer
function Response:internal_server_error(err)
return response4xx5xx(self, 500, err)
end
--- not_implemented
--- @param err any
--- @return integer
function Response:not_implemented(err)
return response4xx5xx(self, 501, err)
end
--- bad_gateway
--- @param err any
--- @return integer
function Response:bad_gateway(err)
return response4xx5xx(self, 502, err)
end
--- service_unavailable
--- @param err any
--- @return integer
function Response:service_unavailable(err)
return response4xx5xx(self, 503, err)
end
--- gateway_timeout
--- @param err any
--- @return integer
function Response:gateway_timeout(err)
return response4xx5xx(self, 504, err)
end
--- http_version_not_supported
--- @param err any
--- @return integer
function Response:http_version_not_supported(err)
return response4xx5xx(self, 505, err)
end
--- variant_also_negotiates
--- @param err any
--- @return integer
function Response:variant_also_negotiates(err)
return response4xx5xx(self, 506, err)
end
--- insufficient_storage
--- @param err any
--- @return integer
function Response:insufficient_storage(err)
return response4xx5xx(self, 507, err)
end
--- loop_detected
--- @param err any
--- @return integer
function Response:loop_detected(err)
return response4xx5xx(self, 508, err)
end
--- not_extended
--- @param err any
--- @return integer
function Response:not_extended(err)
return response4xx5xx(self, 510, err)
end
--- network_authentication_required
--- @param err any
--- @return integer
function Response:network_authentication_required(err)
return response4xx5xx(self, 511, err)
end
return {
new = require('metamodule').new(Response),
}
|
-- Generated by CSharp.lua Compiler
local System = System
local SharedRails
local SystemIO
local SystemNumerics
local SystemXml
local ArrayTrackNode
local ListSharedTrain
local ListTrackSwitch
local ListTrackSegment
local DictInt32RailcarModel
System.import(function (out)
SharedRails = out.SharedRails
SystemIO = System.IO
SystemNumerics = System.Numerics
SystemXml = System.Xml
ArrayTrackNode = System.Array(SharedRails.TrackNode)
ListSharedTrain = System.List(SharedRails.SharedTrain)
ListTrackSwitch = System.List(SharedRails.TrackSwitch)
ListTrackSegment = System.List(SharedRails.TrackSegment)
DictInt32RailcarModel = System.Dictionary(System.Int32, SharedRails.RailcarModel)
end)
System.namespace("SharedRails", function (namespace)
namespace.class("SharedRailManager", function (namespace)
local LoadTracks, LoadModels, __ctor__
__ctor__ = function (this)
this.Segments = ListTrackSegment()
this.Switches = ListTrackSwitch()
this.Trains = ListSharedTrain()
end
LoadTracks = function (this, path)
local lines = SystemIO.File.ReadAllLines(path)
local meta = lines:get(0):Split(" ", 0)
local nodeCount = System.Int32.Parse(meta:get(0))
local segmentCount = System.Int32.Parse(meta:get(1))
this.Nodes = ArrayTrackNode:new(nodeCount)
for i = 1, nodeCount do
local nodeData = lines:get(i):Split(" ", 0)
local switchType = System.Int32.Parse(nodeData:get(3))
if switchType > 0 then
this.Nodes:set(i - 1, SharedRails.TrackSwitch(i - 1, SystemNumerics.Vector3(System.Single.Parse(nodeData:get(0)), System.Single.Parse(nodeData:get(1)), System.Single.Parse(nodeData:get(2))), switchType - 1))
else
this.Nodes:set(i - 1, SharedRails.TrackNode(i - 1, SystemNumerics.Vector3(System.Single.Parse(nodeData:get(0)), System.Single.Parse(nodeData:get(1)), System.Single.Parse(nodeData:get(2)))))
end
end
for i = nodeCount + 1, nodeCount + segmentCount do
local segment = lines:get(i):Split(" ", 0)
local trackSegment = SharedRails.TrackSegment(#this.Segments)
for j = 0, #segment - 1 - 1 do
local n1 = this.Nodes:get(System.Int32.Parse(segment:get(j)) - 1)
local n2 = this.Nodes:get(System.Int32.Parse(segment:get(j + 1)) - 1)
trackSegment.Nodes:Add(n1)
if System.is(n1, SharedRails.TrackSwitch) then
local s1 = System.cast(SharedRails.TrackSwitch, n1)
if s1.SwitchDirection == 0 --[[Direction.Forward]] then
if not this.Switches:Contains(s1) then
this.Switches:Add(s1)
end
s1.SwitchNodes:Add(n2)
if s1.ToNode == nil then
s1.ToNode = n2
end
else
s1.ToNode = n2
end
else
n1.ToNode = n2
end
if System.is(n2, SharedRails.TrackSwitch) then
local s2 = System.cast(SharedRails.TrackSwitch, n2)
if s2.SwitchDirection == 1 --[[Direction.Backward]] then
this.Switches:Add(s2)
s2.SwitchNodes:Add(n1)
if s2.FromNode == nil then
s2.FromNode = n1
end
else
s2.FromNode = n1
end
else
n2.FromNode = n1
end
n1.Segment = trackSegment
end
this.Segments:Add(trackSegment)
end
end
LoadModels = function (this, path)
local document = SystemXml.XmlDocument()
document:Load(path)
this.Models = DictInt32RailcarModel()
for i = 1, document:getFirstChild():getChildNodes():getCount() do
local item = System.cast(SystemXml.XmlElement, document:getFirstChild():getChildNodes():get(i))
local id = System.Int32.Parse(item:GetAttribute("id"))
this.Models:set(id, SharedRails.RailcarModel(item:GetAttribute("name"), id, System.Boolean.Parse(item:GetAttribute("engine")), System.Single.Parse(item:GetAttribute("height")), System.Single.Parse(item:GetAttribute("wheel-offset")), System.Single.Parse(item:GetAttribute("rear-offset")), System.Single.Parse(item:GetAttribute("front-offset"))))
end
end
return {
LoadTracks = LoadTracks,
LoadModels = LoadModels,
__ctor__ = __ctor__,
__metadata__ = function (out)
return {
properties = {
{ "Models", 0x6, System.Dictionary(System.Int32, out.SharedRails.RailcarModel) },
{ "Nodes", 0x6, System.Array(out.SharedRails.TrackNode) },
{ "Segments", 0x6, System.List(out.SharedRails.TrackSegment) },
{ "Switches", 0x6, System.List(out.SharedRails.TrackSwitch) },
{ "Trains", 0x6, System.List(out.SharedRails.SharedTrain) }
},
methods = {
{ ".ctor", 0x6, nil },
{ "LoadModels", 0x106, LoadModels, System.String },
{ "LoadTracks", 0x106, LoadTracks, System.String }
},
class = { 0x6 }
}
end
}
end)
end)
|
--[=[
Only the caste ID is required, all others have defaults (though default x,y,z exists only when cursor is visible)
Includes portions of Rubble's announce.lua and expwent's unit-info-viewer.lua
Calls create-unit.lua to spawn the actual creature
Runs modtools if DFHack is 0.43.03-r1 or later, otherwise mod's included version
References to modtools/create-unit are commented out until that script is updated.
--]=]
local utils=require 'utils'
validArgs = validArgs or utils.invert({
'help',
'caste',
'wyrm',
'miner',
'location',
'friendly',
'unfriendly',
'custom'
})
local args = utils.processArgs({...}, validArgs)
if args.help then
print([[scripts/tesb-wake.lua
arguments:
-help
Print this help message
-caste
Specify the type of awakened stone
This parameter is required
-wyrm
Spawn a wyrm instead of an awakened stone
A "friendly" Wyrm is one that is less likely to be berserk
-location [ x y z ]
The location to spawn the awakened stone
Will default to the cursor location, if the cursor is displayed
-miner
Unit ID of creature causing the spawn
If miner has the caste's favor syndrome, the creature spawns Tame
If miner is omitted, "Something" without favor awakens the creature
-friendly
If flag is present, the awakened stone will be Tame
-unfriendly
If flag is present, the awakened stone will be a wild animal
-custom
Override DFHack version check and use tesb-create-unit
Note: -friendly and -unfriendly override the miner's favor status
]])
return
end
function Announce(caste_id,unit_id,is_friendly,is_wyrm,xyz) -- Create an in-game announcement that a stone has awakened
-- Rubble's Announcement command, customized by Dirst for The Earth Strikes Back mod
--[[
Rubble Announcement DFHack Command
Copyright 2013-2014 Milo Christiansen
This software is provided 'as-is', without any express or implied warranty. In
no event will the authors be held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software for any purpose, including
commercial applications, and to alter it and redistribute it freely, subject to
the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim
that you wrote the original software. If you use this software in a product, an
acknowledgment in the product documentation would be appreciated but is not
required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
]]
if not dfhack.isMapLoaded() then
dfhack.printerr('Error: Map is not loaded.')
return
end
local caste_name = string.upper(string.sub(caste_id,1,1))..string.lower(string.sub(caste_id,2,-1))
if caste_name == "Rock_salt" then -- Special handling for two-word stone
caste_name = "Rock Salt"
end
local unit_name
if not unit_id then
unit_name = "Something" -- The player activated the script in an interactive window.
else
unit_name = dfhack.TranslateName(dfhack.units.getVisibleName(df.unit.find(tonumber(unit_id))))
end
if is_wyrm then
text = unit_name.." has released a newly-hatched "..caste_name.." Wyrm!"
color_id = "COLOR_RED"
else
if is_friendly == true then
text = unit_name.." has awakened a creature of Living "..caste_name
color_id = "COLOR_WHITE"
else
text = unit_name.." has incurred the wrath of an Awakened "..caste_name
color_id = "COLOR_RED"
end
end
local color = _G[color_id]
if xyz then dfhack.gui.makeAnnouncement(179,{false,false,false,true},xyz2pos(tonumber(xyz[1] or -3000), tonumber(xyz[2] or 0), tonumber(xyz[3] or 0)),text, color,1)
else dfhack.gui.makeAnnouncement(179,{false,false,false,true},xyz2pos(-3000,-3000,-3000),text, color,1) end
print(text)
end
function IsItFriendly(caste,miner,is_friendly,is_unfriendly)
-- is_unfriendly overrides is_friendly which overrides miner's status
-- The default is false if nothing was specified
local verdict = false
if is_unfriendly then -- Command line flag
verdict = false
elseif is_friendly then -- Command line flag
verdict = true
elseif miner then
local miner_unit = df.unit.find(tonumber(miner))
local syndrome_list = miner_unit.syndromes.active
if caste == "ROCK_SALT" then caste = "rock salt" end -- Special handling for two-word stone
local favor_syndrome_name = string.lower(caste).." favor"
for index,syndrome in ipairs(syndrome_list) do
local syndrome_info = df.syndrome.find(syndrome.type)
if syndrome_info.syn_name == favor_syndrome_name then -- Unit has the appropriate "favor" syndrome
verdict = true
break
end
end
end
return verdict
end
function CreateUnitWrapper(RaceName, CasteName, Location, TameUnit)
--[[
CreateUnit wrapper
Amostubal - combine the finding of race_ID and caste_ID then call the CreateUnit.
returns the unit Id.
RaceName is the race name ex. TESB_PET_ROCK
CasteName is past from the args and should be the caste name.
TameUnit is a true false expression, where true triggers running createUnit.domesticate.
--]]
local createUnit = dfhack.script_environment('modtools/create-unit')
local race
local raceIndex
local casteIndex
local unitId
for i,v in ipairs(df.global.world.raws.creatures.all) do
if v.creature_id == RaceName then
raceIndex = i
race=v
break
end
end
for i,v in ipairs(race.caste) do
if v.caste_id == CasteName then
casteIndex = i
break
end
end
unitId=createUnit.createUnit(raceIndex, casteIndex, Location)
if domesticate then domesticate(unitId) end
-- cleanup its name, to get rid of units having arena numbers.
local unit = df.unit.find(unitId)
unit.name.has_name = false
unit.name.first_name = ""
if unit.status.current_soul then
unit.status.current_soul.name.has_name = false
end
return unitId
end
local argFriendly
argFriendly = IsItFriendly(args.caste,args.miner,args.friendly,args.unfriendly)
Announce(args.caste,args.miner,argFriendly,args.wyrm,args.location)
--[[
Amostubal - start of my rewrite. The old script was too verbose and used
archaic calls to create units. Switched to better calls to make the script
less verbose while increasing readability.
CreateUnitWrapper is a local function to gather the proper tags and call the
appropriate scripts inside of the modtools/create-unit.
--]]
-- the local holders of ID and Unit, changes with each creature created.
local thisUnitID
local thisUnit
--[[
This section spawns 0 to 2 Pet Rocks alongside the Awakened Stone or Wyrm.
The castes of Pet Rocks are in the same order as those of large creature.
--]]
if math.random(0,2) == 2 then
thisUnitID = CreateUnitWrapper("TESB_PET_ROCK", args.caste, args.location, true)
end
if math.random(0,3) == 3 then
thisUnitID = CreateUnitWrapper("TESB_PET_ROCK", args.caste, args.location, true)
end
if args.wyrm then
thisUnitID = CreateUnitWrapper("TESB_WYRM", args.caste, args.location, false)
thisUnit = df.unit.find(tonumber(thisUnitID))
thisUnit.flags1.marauder = true
if argFriendly then -- A "friendly" Wyrm is just less likely to be berserk
if math.random(0,9)==9 then thisUnit.mood = 7 end
else -- not a "friendly" wyrm.
if math.random(0,3)==3 then thisUnit.mood = 7 end
end
else -- its an awakened stone!
thisUnitID = CreateUnitWrapper("TESB_AWAKENED_STONE", args.caste, args.location, argFriendly)
if not argFriendly then -- its not friendly so we need to make it mad.
thisUnit = df.unit.find(tonumber(thisUnitID))
thisUnit.flags1.marauder = true
if math.random(0,9) == 9 then thisUnit.mood = 7 end -- One in ten chance of being berserk
end
end
|
--------------------------------------------------------------------
scn = mock_edit.createEditorCanvasScene()
--------------------------------------------------------------------
CLASS: StyleSheetPreview ( mock_edit.EditorEntity )
:MODEL{}
function StyleSheetPreview:onLoad()
self:addSibling( mock_edit.CanvasGrid() )
self:addSibling( mock_edit.CanvasNavigate() )
self:attach( mock.InputScript{ device = scn.inputDevice } )
self:attach( mock.DrawScript{ priority = 1000 } )
self.styleSheet = false
self.textLabel = self:attach( mock.TextLabel() )
self.textLabel:setSize( 200, 200 )
self.textLabel:setText( 'hello!' )
self:setVisible( false )
end
function StyleSheetPreview:open( path )
self.styleSheet = mock.loadAsset( path )
if self.styleSheet then
self.textLabel:setStyleSheet( path )
end
self:setVisible( true )
updateCanvas()
return self.styleSheet
end
function StyleSheetPreview:save( path )
if not self.styleSheet then return end
mock.serializeToFile( self.styleSheet, path )
end
function StyleSheetPreview:close()
self.styleSheet = false
self:setVisible( false )
end
function StyleSheetPreview:setPreviewText( t )
self.textLabel:setText( t )
updateCanvas()
end
function StyleSheetPreview:setAlignment( a )
self.textLabel:setAlignment( a )
updateCanvas()
end
local getBuiltinShader = MOAIShaderMgr. getShader
local DECK2D_TEX_ONLY_SHADER = MOAIShaderMgr. DECK2D_TEX_ONLY_SHADER
local DECK2D_SHADER = MOAIShaderMgr. DECK2D_SHADER
local FONT_SHADER = MOAIShaderMgr. FONT_SHADER
function StyleSheetPreview:setShader( s )
if s == 'tex' then
self.textLabel.box:setShader( getBuiltinShader( DECK2D_SHADER ) )
else
self.textLabel.box:setShader( getBuiltinShader( FONT_SHADER ) )
end
end
----
function StyleSheetPreview:addStyle()
return self.styleSheet:addStyle()
end
function StyleSheetPreview:removeStyle( s )
return self.styleSheet:removeStyle( s )
end
function StyleSheetPreview:cloneStyle( s )
return self.styleSheet:cloneStyle( s )
end
function StyleSheetPreview:renameStyle( s, name )
s.name = name
end
function StyleSheetPreview:updateStyles()
self.styleSheet:updateStyles()
self.textLabel.box:setYFlip( false ) --hacking to force re-layout
updateCanvas()
end
--------------------------------------------------------------------
preview = scn:addEntity( StyleSheetPreview() )
|
author 'Prefech'
description 'Prefech_ALPR (https://prefech.com/)'
version '1.0.2'
-- Config
shared_script 'config/config.lua'
-- Client Scripts
client_scripts {
'client/main.lua',
'config/cameras.lua'
}
-- Server Scripts
server_scripts {
'server/main.lua'
}
game 'gta5'
fx_version 'cerulean'
|
local vector = require"library/vector"
local is_keyDown = love.keyboard.isDown
return core.SystemConstructor("MoveControlSystem",function(...)
return {
filter = core.tiny.requireAll(
"MoveComponent",
"MoveControlComponent"
),
process = function(self,entity,dt)
local vx,vy = 0,0
if is_keyDown("w") then
vy = -entity.speed
end
if is_keyDown("s") then
vy = entity.speed
end
if is_keyDown("a") then
vx = -entity.speed
end
if is_keyDown("d") then
vx = entity.speed
end
entity.velocity.x,entity.velocity.y = vector.normalize(vx,vy)
end
}
end)
|
PLUGIN.name = "Flash window"
PLUGIN.author = "STEAM_0:1:29606990"
PLUGIN.description = ""
if (SERVER) then return end
ix.option.Add("flashWindow", ix.type.bool, true, {
category = "chat"
})
function PLUGIN:InitPostEntity()
if (ix.option.Get("flashWindow", true) and system.IsWindows() and !system.HasFocus()) then
system.FlashWindow()
end
end
PLUGIN.MessageReceived = PLUGIN.InitPostEntity
|
-- Editors:
-- AtroCty
-- Hewdraw
-- Firetoad
-- Yahnich, 23.03.2017
-- #1 Talent - Giving gold on lasthits
--function modifier_special_bonus_imba_kunkka_1:DeclareFunctions()
-- local decFuncs =
-- {
-- MODIFIER_EVENT_ON_DEATH
-- }
-- return decFuncs
--end
--function modifier_special_bonus_imba_kunkka_1:OnDeath( params )
-- if (params.attacker:GetTeam() == self:GetCaster():GetTeam()) and (params.attacker == self:GetParent()) and (params.attacker ~= params.unit) and (params.attacker:HasTalent("special_bonus_imba_kunkka_1")) then
-- local custom_gold_bonus = tonumber(CustomNetTables:GetTableValue("game_options", "bounty_multiplier")["1"])
-- local gold = params.attacker:FindTalentValue("special_bonus_imba_kunkka_1") * (custom_gold_bonus / 100)
-- SendOverheadEventMessage( self:GetCaster():GetOwner(), OVERHEAD_ALERT_GOLD , self:GetParent(), gold, self:GetCaster() )
-- params.attacker:ModifyGold(gold, false, 0)
-- end
--end
-------------------------------------------
-- EBB & FLOW
-------------------------------------------
imba_kunkka_ebb_and_flow = class({})
LinkLuaModifier("modifier_imba_ebb_and_flow_thinker", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_ebb_and_flow_tide_low", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_ebb_and_flow_tide_red", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_ebb_and_flow_tide_flood", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_ebb_and_flow_tide_high", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_ebb_and_flow_tide_wave", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_ebb_and_flow_tsunami", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
function imba_kunkka_ebb_and_flow:GetAbilityTextureName()
return "kunkka_ebb_and_flow"
end
function imba_kunkka_ebb_and_flow:GetIntrinsicModifierName()
return "modifier_imba_ebb_and_flow_thinker"
end
function imba_kunkka_ebb_and_flow:IsNetherWardStealable() return false end
function imba_kunkka_ebb_and_flow:IsInnateAbility()
return true
end
function imba_kunkka_ebb_and_flow:IsStealable()
return false
end
-- Remove current Tide
function imba_kunkka_ebb_and_flow:RemoveTide()
local caster = self:GetCaster()
if caster:HasModifier("modifier_imba_ebb_and_flow_tsunami") then caster:RemoveModifierByName("modifier_imba_ebb_and_flow_tsunami") end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_low") then caster:RemoveModifierByName("modifier_imba_ebb_and_flow_tide_low") end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_red") then caster:RemoveModifierByName("modifier_imba_ebb_and_flow_tide_red") end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_flood") then caster:RemoveModifierByName("modifier_imba_ebb_and_flow_tide_flood") end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_high") then caster:RemoveModifierByName("modifier_imba_ebb_and_flow_tide_high") end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_wave") then caster:RemoveModifierByName("modifier_imba_ebb_and_flow_tide_wave") end
end
function imba_kunkka_ebb_and_flow:GetCooldown( nLevel )
local cooldown = self.BaseClass.GetCooldown( self, nLevel )
return cooldown
end
-- Re-roll buff
function imba_kunkka_ebb_and_flow:OnSpellStart()
if IsServer() then
local caster = self:GetCaster()
local modifier = caster:FindModifierByName("modifier_imba_ebb_and_flow_thinker")
self:RemoveTide()
modifier.tsunami_check = 0
end
end
function imba_kunkka_ebb_and_flow:GetAbilityTextureName()
local caster = self:GetCaster()
if caster:HasModifier("modifier_imba_ebb_and_flow_tsunami") then return "kunnka_tide_tsunami" end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_low") then return "kunnka_tide_low" end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_red") then return "kunnka_tide_red" end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_flood") then return "kunnka_tide_flood" end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_high") then return "kunnka_tide_high" end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_wave") then return "kunnka_tide_wave" end
return "kunkka_ebb_and_flow"
end
modifier_imba_ebb_and_flow_thinker = class({})
-- State defining
function modifier_imba_ebb_and_flow_thinker:RemoveOnDeath()
return false
end
function modifier_imba_ebb_and_flow_thinker:IsPurgable()
return false
end
function modifier_imba_ebb_and_flow_thinker:IsHidden()
return true
end
-- Cooldown checker
function modifier_imba_ebb_and_flow_thinker:OnCreated()
if IsServer() then
self.tide_counter = 1
self:StartIntervalThink(0.1)
end
end
function modifier_imba_ebb_and_flow_thinker:OnIntervalThink()
if IsServer() then
local caster = self:GetCaster()
local ability = self:GetAbility()
-- Tsunami-Tide Chance
-- 0 = not rolled yet, 1 = Tsunami, 2 = regular tide
self.tsunami_check = self.tsunami_check or 0
if self.tsunami_check == 0 then
local tsunami_chance = ability:GetTalentSpecialValueFor("tsunami_chance")
if tsunami_chance >= RandomInt(1, 100) then
self.tsunami_check = 1
else
self.tsunami_check = 2
self:NextTide()
end
end
local current_tide_modifier
if self.tsunami_check == 1 then
current_tide_modifier = "modifier_imba_ebb_and_flow_tsunami"
else
current_tide_modifier = self:GetCurrentTide(self.tide_counter)
end
-- Check if caster should have the next tide
if ability:IsCooldownReady() and not caster:HasModifier(current_tide_modifier) then
caster:AddNewModifier(caster, ability, current_tide_modifier, {})
end
end
end
modifier_imba_ebb_and_flow_tide_low = class({})
function modifier_imba_ebb_and_flow_tide_low:IsHidden()
return false
end
function modifier_imba_ebb_and_flow_tide_low:IsDebuff()
return false
end
function modifier_imba_ebb_and_flow_tide_low:GetTexture()
return "kunnka_tide_low"
end
modifier_imba_ebb_and_flow_tide_red = class({})
function modifier_imba_ebb_and_flow_tide_red:IsHidden()
return false
end
function modifier_imba_ebb_and_flow_tide_red:IsDebuff()
return false
end
function modifier_imba_ebb_and_flow_tide_red:GetTexture()
return "kunnka_tide_red"
end
modifier_imba_ebb_and_flow_tide_flood = class({})
function modifier_imba_ebb_and_flow_tide_flood:IsHidden()
return false
end
function modifier_imba_ebb_and_flow_tide_flood:IsDebuff()
return false
end
function modifier_imba_ebb_and_flow_tide_flood:GetTexture()
return "kunnka_tide_flood"
end
modifier_imba_ebb_and_flow_tide_high = class({})
function modifier_imba_ebb_and_flow_tide_high:IsHidden()
return false
end
function modifier_imba_ebb_and_flow_tide_high:IsDebuff()
return false
end
function modifier_imba_ebb_and_flow_tide_high:GetTexture()
return "kunnka_tide_high"
end
modifier_imba_ebb_and_flow_tide_wave = class({})
function modifier_imba_ebb_and_flow_tide_wave:IsHidden()
return false
end
function modifier_imba_ebb_and_flow_tide_wave:IsDebuff()
return false
end
function modifier_imba_ebb_and_flow_tide_wave:GetTexture()
return "kunnka_tide_wave"
end
modifier_imba_ebb_and_flow_tsunami = class({})
function modifier_imba_ebb_and_flow_tsunami:IsHidden()
return false
end
function modifier_imba_ebb_and_flow_tsunami:IsDebuff()
return false
end
function modifier_imba_ebb_and_flow_tsunami:GetTexture()
return "kunnka_tide_tsunami"
end
-- Flexible list of all possible tides (excluding tsunami)
function modifier_imba_ebb_and_flow_thinker:GetCurrentTide( index )
local tide_list
-- #1 Talent: Add Tsunami to Ebb & Flow cycle
if self:GetCaster():HasTalent("special_bonus_imba_kunkka_1") then
tide_list = {
"modifier_imba_ebb_and_flow_tide_low",
"modifier_imba_ebb_and_flow_tide_red",
"modifier_imba_ebb_and_flow_tide_flood",
"modifier_imba_ebb_and_flow_tide_high",
"modifier_imba_ebb_and_flow_tide_wave",
"modifier_imba_ebb_and_flow_tsunami"
}
else
tide_list = {
"modifier_imba_ebb_and_flow_tide_low",
"modifier_imba_ebb_and_flow_tide_red",
"modifier_imba_ebb_and_flow_tide_flood",
"modifier_imba_ebb_and_flow_tide_high",
"modifier_imba_ebb_and_flow_tide_wave"
}
end
tide_list['tide_count'] = #tide_list
return tide_list[index]
end
-- Sets the current Tide-counter
function modifier_imba_ebb_and_flow_thinker:NextTide()
if ( self.tide_counter >= self:GetCurrentTide('tide_count') ) then
self.tide_counter = 1
else
self.tide_counter = self.tide_counter + 1
end
end
-------------------------------------------
-- TORRENT
-------------------------------------------
imba_kunkka_torrent = class({})
LinkLuaModifier("modifier_imba_torrent_handler", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_torrent_cast", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_torrent_slow_tide", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_torrent_slow", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_sec_torrent_slow", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_torrent_phase", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_kunkka_torrent_talent_thinker", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
function imba_kunkka_torrent:GetAbilityTextureName()
return "kunkka_torrent"
end
function imba_kunkka_torrent:GetIntrinsicModifierName()
return "modifier_imba_torrent_handler"
end
-- For vanilla Torrent Storm
function imba_kunkka_torrent:OnUpgrade()
if self:GetCaster():HasAbility("kunkka_torrent") then
self:GetCaster():FindAbilityByName("kunkka_torrent"):SetLevel(self:GetLevel())
end
end
function imba_kunkka_torrent:OnSpellStart()
if IsServer() then
local caster = self:GetCaster()
local target = self:GetCursorPosition()
-- Parameters
local vision_duration = 4
local first_delay = self:GetSpecialValueFor("launch_delay")
local radius = self:GetTalentSpecialValueFor("radius")
local slow_duration = self:GetSpecialValueFor("slow_duration")
local stun_duration = self:GetSpecialValueFor("stun_duration")
local damage = self:GetSpecialValueFor("damage")
local sec_torrent_count = self:GetSpecialValueFor("sec_torrent_count")
local sec_torrent_stun = self:GetSpecialValueFor("sec_torrent_stun")
local sec_torrent_damage = self:GetTalentSpecialValueFor("sec_torrent_damage")
local sec_torrent_slow_duration = self:GetSpecialValueFor("sec_torrent_slow_duration")
local tick_count = self:GetSpecialValueFor("tick_count")
local torrent_height = self:GetSpecialValueFor("torrent_height")
-- Check buffs by Ebb and Flow, and set on Cooldown after cast to give a new buff
local tsunami = caster:HasModifier("modifier_imba_ebb_and_flow_tsunami")
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_flood") or tsunami then
damage = damage + self:GetSpecialValueFor("tide_flood_damage")
end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_high") or tsunami then
radius = radius + self:GetSpecialValueFor("tide_high_radius")
end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_wave") or tsunami then
first_delay = first_delay / 2
end
local extra_slow = false
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_red") or tsunami then
extra_slow = true
end
-- In case the ability is stolen don't cast the next tide
if caster:HasAbility("imba_kunkka_ebb_and_flow") then
local ability_tide = caster:FindAbilityByName("imba_kunkka_ebb_and_flow")
ability_tide:CastAbility()
end
-- Calculates the damage to deal per tick
local tick_interval = stun_duration / tick_count
local damage_tick = damage / tick_count
vision_duration = vision_duration + (sec_torrent_count * 2)
-- Set slow duration (After stun)
slow_duration = slow_duration + stun_duration
sec_torrent_slow_duration = sec_torrent_slow_duration + sec_torrent_stun
self:CreateVisibilityNode(target, radius, vision_duration)
local bubbles_pfx = ParticleManager:CreateParticleForTeam("particles/hero/kunkka/torrent_bubbles.vpcf", PATTACH_ABSORIGIN, caster, caster:GetTeam())
ParticleManager:SetParticleControl(bubbles_pfx, 0, target)
ParticleManager:SetParticleControl(bubbles_pfx, 1, Vector(radius,0,0))
local bubbles_sec_pfc
EmitSoundOnLocationForAllies(target, "Ability.pre.Torrent", caster)
-- #4 Talent: Secondary Torrents appear at random intervals inside the radius of Main Torrent
if caster:HasTalent("special_bonus_imba_kunkka_4") then
local thinker = CreateModifierThinker(caster, self, "modifier_imba_kunkka_torrent_talent_thinker",
{duration = (first_delay + sec_torrent_count),
pos_x = target.x,
pos_y = target.y,
pos_z = target.z,
affected_radius = radius,
sec_torrent_radius = self:GetSpecialValueFor("sec_torrent_radius"),
sec_torrent_stun = sec_torrent_stun,
sec_torrent_count = sec_torrent_count,
sec_torrent_damage = sec_torrent_damage,
sec_torrent_slow_duration = sec_torrent_slow_duration,
tick_count = tick_count,
torrent_height = torrent_height}, target, caster:GetTeamNumber(), false)
end
-- Setting these as variables due to Rubick error stuff
local target_team = self:GetAbilityTargetTeam()
local target_type = self:GetAbilityTargetType()
local target_flags = self:GetAbilityTargetFlags()
local damage_type = self:GetAbilityDamageType()
local sec_torrent_radius = self:GetSpecialValueFor("sec_torrent_radius")
-- Cast for each count
for torrent_count = 0, sec_torrent_count, 1
do
local delay = first_delay + (torrent_count * 2)
-- Start after the delay
Timers:CreateTimer(delay, function()
-- Parameters for secoundary Torrents
if torrent_count > 0 then
damage_tick = sec_torrent_damage / tick_count
stun_duration = sec_torrent_stun
torrent_height = torrent_height / 1.5
radius = sec_torrent_radius
end
-- Destroy initial bubble-particle & create secoundary visible for both teams
if torrent_count == 0 then
ParticleManager:DestroyParticle(bubbles_pfx, false)
ParticleManager:ReleaseParticleIndex(bubbles_pfx)
bubbles_sec_pfc = ParticleManager:CreateParticleForTeam("particles/hero/kunkka/torrent_bubbles.vpcf", PATTACH_ABSORIGIN, caster, caster:GetTeam())
ParticleManager:SetParticleControl(bubbles_sec_pfc, 0, target)
ParticleManager:SetParticleControl(bubbles_sec_pfc, 1, Vector(radius,0,0))
end
-- Destroy bubbles if it was the last torrent
if torrent_count == sec_torrent_count then
ParticleManager:DestroyParticle(bubbles_sec_pfc, false)
ParticleManager:ReleaseParticleIndex(bubbles_sec_pfc)
end
-- Finds affected enemies
local enemies = FindUnitsInRadius(caster:GetTeam(), target, nil, radius, target_team, target_type, target_flags, 0, false)
-- Torrent response if an enemy was hit 30%
if (#enemies > 0) and (caster:GetName() == "npc_dota_hero_kunkka") then
if math.random(1,10) < 3 then
caster:EmitSound("kunkka_kunk_ability_torrent_0"..math.random(1,4))
end
end
-- Iterate through affected enemies
for _,enemy in pairs(enemies) do
-- Deals the initial damage
ApplyDamage({victim = enemy, attacker = caster, ability = self, damage = damage_tick, damage_type = damage_type})
local current_ticks = 0
local randomness_x = 0
local randomness_y = 0
-- Calculates the knockback position (for Tsunami)
local torrent_border = ( enemy:GetAbsOrigin() - target ):Normalized() * ( radius + 100 )
local distance_from_center = ( enemy:GetAbsOrigin() - target ):Length2D()
if not ( tsunami and torrent_count == 0 ) then
distance_from_center = 0
else
-- Some randomness to tsunami-torrent for smoother animation
randomness_x = math.random() * math.random(-30,30)
randomness_y = math.random() * math.random(-30,30)
end
-- Knocks the target up
local knockback =
{
should_stun = 1,
knockback_duration = stun_duration,
duration = stun_duration,
knockback_distance = distance_from_center,
knockback_height = torrent_height,
center_x = (target + torrent_border).x + randomness_x,
center_y = (target + torrent_border).y + randomness_y,
center_z = (target + torrent_border).z
}
-- Apply knockback on enemies hit
enemy:RemoveModifierByName("modifier_knockback")
enemy:AddNewModifier(caster, self, "modifier_knockback", knockback):SetDuration(stun_duration, true)
enemy:AddNewModifier(caster, self, "modifier_imba_torrent_phase", {duration = stun_duration})
-- Deals tick damage tick_count times
Timers:CreateTimer(function()
if current_ticks < tick_count then
ApplyDamage({victim = enemy, attacker = caster, ability = self, damage = damage_tick, damage_type = damage_type})
current_ticks = current_ticks + 1
return tick_interval
end
end)
-- Applies the slow
if torrent_count == 0 then
enemy:AddNewModifier(caster, self, "modifier_imba_torrent_slow", {duration = slow_duration * (1 - enemy:GetStatusResistance())})
if extra_slow then
enemy:AddNewModifier(caster, self, "modifier_imba_torrent_slow_tide", {duration = slow_duration * (1 - enemy:GetStatusResistance())})
end
else
enemy:AddNewModifier(caster, self, "modifier_imba_sec_torrent_slow", {duration = sec_torrent_slow_duration * (1 - enemy:GetStatusResistance())})
end
end
-- Creates the post-ability sound effect
EmitSoundOnLocationWithCaster(target, "Ability.Torrent", caster)
-- Draws the particle
local particle = "particles/hero/kunkka/torrent_splash.vpcf"
local torrent_fx = ParticleManager:CreateParticle(particle, PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControl(torrent_fx, 0, target)
ParticleManager:SetParticleControl(torrent_fx, 1, Vector(radius,0,0))
ParticleManager:ReleaseParticleIndex(torrent_fx)
-- SUPER DUPER HYPER torrent animation if tsunami
if torrent_count == 0 and tsunami then
local torrent_tsunami_fx = ParticleManager:CreateParticle("particles/econ/items/kunkka/kunkka_weapon_whaleblade/kunkka_spell_torrent_whaleblade_tail.vpcf", PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControl(torrent_tsunami_fx, 0, target)
ParticleManager:ReleaseParticleIndex(torrent_tsunami_fx)
local count_mini = math.floor(radius / 35)
for i = 0, count_mini, 1
do
Timers:CreateTimer(math.random(80)*0.01, function()
local radius_mini = math.random(50)+15
local angle = (360 / count_mini) * i
local border = radius - radius_mini
local mini_target = target + Vector( math.cos(angle) * border , math.sin(angle) * border , 0 )
local torrent_fx_mini = ParticleManager:CreateParticle(particle, PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControl(torrent_fx_mini, 0, mini_target)
ParticleManager:SetParticleControl(torrent_fx_mini, 1, Vector(radius_mini,0,0))
ParticleManager:ReleaseParticleIndex(torrent_fx_mini)
end)
end
end
end)
end
end
end
function imba_kunkka_torrent:IsHiddenWhenStolen()
return false
end
function imba_kunkka_torrent:GetAOERadius()
local caster = self:GetCaster()
local radius = self:GetTalentSpecialValueFor("radius")
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_high") or caster:HasModifier("modifier_imba_ebb_and_flow_tsunami") then
radius = radius + self:GetSpecialValueFor("tide_high_radius")
end
return radius
end
function imba_kunkka_torrent:GetCastRange( location , target)
local caster = self:GetCaster()
local range = self.BaseClass.GetCastRange(self,location,target)
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_low") or caster:HasModifier("modifier_imba_ebb_and_flow_tsunami") then
range = range + self:GetSpecialValueFor("tide_low_range")
end
return range
end
-----------------------------------
-- MODIFIER_IMBA_TORRENT_HANDLER --
-----------------------------------
modifier_imba_torrent_handler = class({})
function modifier_imba_torrent_handler:IsHidden() return true end
function modifier_imba_torrent_handler:OnIntervalThink()
if not IsServer() then return end
if self:GetAbility():GetAutoCastState() and self:GetAbility():IsFullyCastable() and not self:GetAbility():IsInAbilityPhase() and not self:GetCaster():IsHexed() and not self:GetCaster():IsNightmared() and not self:GetCaster():IsOutOfGame() and not self:GetCaster():IsSilenced() and not self:GetCaster():IsStunned() and not self:GetCaster():IsChanneling() then
self:GetCaster():SetCursorPosition(self:GetCaster():GetAbsOrigin())
self:GetAbility():CastAbility()
end
end
function modifier_imba_torrent_handler:DeclareFunctions()
local decFuncs = {MODIFIER_EVENT_ON_ORDER, MODIFIER_PROPERTY_IGNORE_CAST_ANGLE, MODIFIER_PROPERTY_DISABLE_TURNING}
return decFuncs
end
function modifier_imba_torrent_handler:OnOrder(keys)
if not IsServer() or keys.unit ~= self:GetParent() then return end
if keys.ability == self:GetAbility() then
if keys.order_type == DOTA_UNIT_ORDER_CAST_POSITION and (keys.new_pos - self:GetCaster():GetAbsOrigin()):Length2D() <= self:GetAbility():GetCastRange(self:GetCaster():GetCursorPosition(), self:GetCaster()) + self:GetCaster():GetCastRangeBonus() then
self.bActive = true
else
self.bActive = false
end
else
self.bActive = false
end
end
function modifier_imba_torrent_handler:GetModifierIgnoreCastAngle()
if not IsServer() or self.bActive == false then return end
return 1
end
function modifier_imba_torrent_handler:GetModifierDisableTurning()
if not IsServer() or self.bActive == false then return end
return 1
end
modifier_imba_torrent_phase = class({})
function modifier_imba_torrent_phase:CheckState()
local state = {[MODIFIER_STATE_NO_UNIT_COLLISION] = true}
return state
end
function modifier_imba_torrent_phase:IsHidden()
return true
end
function modifier_imba_torrent_phase:IsDebuff()
return true
end
modifier_imba_torrent_slow_tide = class({})
function modifier_imba_torrent_slow_tide:IsHidden()
return true
end
function modifier_imba_torrent_slow_tide:IsDebuff()
return true
end
function modifier_imba_torrent_slow_tide:IsPurgable()
return true
end
modifier_imba_torrent_slow = class({})
function modifier_imba_torrent_slow:DeclareFunctions()
local decFuncs =
{
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE
}
return decFuncs
end
function modifier_imba_torrent_slow:GetModifierMoveSpeedBonus_Percentage( )
local ability = self:GetAbility()
local slow = ability:GetSpecialValueFor("main_slow")
if self:GetParent():HasModifier("modifier_imba_torrent_slow_tide")then
slow = slow + ability:GetSpecialValueFor("tide_red_slow")
end
return slow * (-1)
end
function modifier_imba_torrent_slow:IsHidden()
return false
end
function modifier_imba_torrent_slow:IsDebuff()
return true
end
function modifier_imba_torrent_slow:IsPurgable()
return true
end
modifier_imba_sec_torrent_slow = class({})
function modifier_imba_sec_torrent_slow:DeclareFunctions()
local decFuncs =
{
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE
}
return decFuncs
end
function modifier_imba_sec_torrent_slow:GetModifierMoveSpeedBonus_Percentage( )
return ( self:GetAbility():GetSpecialValueFor("sec_torrent_slow") * (-1) )
end
function modifier_imba_sec_torrent_slow:IsHidden()
return false
end
function modifier_imba_sec_torrent_slow:IsDebuff()
return true
end
function modifier_imba_sec_torrent_slow:IsPurgable()
return true
end
-- Modifier for casting torrent without showing cast direction
-- Modifier is added in the OrderFilter in imba.lua !
modifier_imba_torrent_cast = class({})
function modifier_imba_torrent_cast:DeclareFunctions()
local decFuncs =
{
MODIFIER_PROPERTY_IGNORE_CAST_ANGLE,
MODIFIER_PROPERTY_DISABLE_TURNING
}
return decFuncs
end
function modifier_imba_torrent_cast:GetModifierIgnoreCastAngle( params )
return 1
end
function modifier_imba_torrent_cast:GetModifierDisableTurning( params )
return 1
end
function modifier_imba_torrent_cast:IsHidden()
return false
end
-- Do a stop order after finish casting to prevent turning to the destination point
function modifier_imba_torrent_cast:OnDestroy( params )
if IsServer() then
local stopOrder =
{
UnitIndex = self:GetCaster():entindex(),
OrderType = DOTA_UNIT_ORDER_STOP
}
ExecuteOrderFromTable( stopOrder )
end
end
modifier_imba_kunkka_torrent_talent_thinker = class({})
function modifier_imba_kunkka_torrent_talent_thinker:IsHidden()
return false
end
function modifier_imba_kunkka_torrent_talent_thinker:IsPurgable()
return false
end
function modifier_imba_kunkka_torrent_talent_thinker:OnCreated(keys)
if IsServer() then
-- Ability properties
self.caster = self:GetCaster()
self.ability = self:GetAbility()
self.min_interval = self.caster:FindTalentValue("special_bonus_imba_kunkka_4","min_interval") * 10
self.max_interval = self.caster:FindTalentValue("special_bonus_imba_kunkka_4") * 10
self.tick = (math.random() + math.random(self.min_interval, self.max_interval)) / 10
-- Parameters
-- fuck you vectors
self.pos = Vector(keys.pos_x,keys.pos_y,keys.pos_z)
self.affected_radius = keys.affected_radius
self.sec_torrent_radius = keys.sec_torrent_radius
self.sec_torrent_stun = keys.sec_torrent_stun
self.sec_torrent_count = keys.sec_torrent_count
self.sec_torrent_damage = keys.sec_torrent_damage
self.sec_torrent_slow_duration = keys.sec_torrent_slow_duration
self.tick_count = keys.tick_count
self.torrent_height = keys.torrent_height
-- Ability specials
self:StartIntervalThink(self.tick)
end
end
function modifier_imba_kunkka_torrent_talent_thinker:OnIntervalThink()
if IsServer() then
local interval = (math.random() + math.random(self.min_interval, ((self:GetRemainingTime()+self.tick) * 10))) / 10
-- Re-roll the interval
self.tick = (math.random() + math.random(self.min_interval, self.max_interval)) / 10
Timers:CreateTimer(interval, function()
-- Parameters for secoundary Torrents
local random_radius = math.random(0, self.affected_radius)
local random_vector = self.pos + RandomVector(random_radius)
damage_tick = self.sec_torrent_damage / self.tick_count
stun_duration = self.sec_torrent_stun
torrent_height = self.torrent_height / 1.5
radius = self.sec_torrent_radius
tick_interval = stun_duration / self.tick_count
-- Finds affected enemies
local enemies = FindUnitsInRadius(self.caster:GetTeam(), random_vector, nil, radius, self.ability:GetAbilityTargetTeam(), self.ability:GetAbilityTargetType(), self.ability:GetAbilityTargetFlags(), 0, false)
-- Torrent response if an enemy was hit 30%
if (#enemies > 0) and (self.caster:GetName() == "npc_dota_hero_kunkka") then
if math.random(1,10) < 3 then
self.caster:EmitSound("kunkka_kunk_ability_torrent_0"..math.random(1,4))
end
end
-- Iterate through affected enemies
for _,enemy in pairs(enemies) do
-- Deals the initial damage
ApplyDamage({victim = enemy, attacker = self.caster, ability = self.ability, damage = damage_tick, damage_type = self.ability:GetAbilityDamageType()})
local current_ticks = 0
local randomness_x = 0
local randomness_y = 0
-- Calculates the knockback position (for Tsunami)
local torrent_border = ( enemy:GetAbsOrigin() - random_vector ):Normalized() * ( radius + 100 )
local distance_from_center = ( enemy:GetAbsOrigin() - random_vector ):Length2D()
if not ( tsunami and torrent_count == 0 ) then
distance_from_center = 0
else
-- Some randomness to tsunami-torrent for smoother animation
randomness_x = math.random() * math.random(-30,30)
randomness_y = math.random() * math.random(-30,30)
end
-- Knocks the target up
local knockback =
{
should_stun = 1,
knockback_duration = stun_duration,
duration = stun_duration,
knockback_distance = distance_from_center,
knockback_height = torrent_height,
center_x = (random_vector + torrent_border).x + randomness_x,
center_y = (random_vector + torrent_border).y + randomness_y,
center_z = (random_vector + torrent_border).z
}
-- Apply knockback on enemies hit
enemy:RemoveModifierByName("modifier_knockback")
enemy:AddNewModifier(self.caster, self.ability, "modifier_knockback", knockback)
enemy:AddNewModifier(self.caster, self.ability, "modifier_imba_torrent_phase", {duration = stun_duration})
-- Deals tick damage tick_count times
Timers:CreateTimer(function()
-- TODO: tick count can be nil for some reason
if tick_count ~= nil and current_ticks < tick_count then
ApplyDamage({victim = enemy, attacker = self.caster, ability = self.ability, damage = damage_tick, damage_type = self.ability:GetAbilityDamageType()})
current_ticks = current_ticks + 1
return tick_interval
end
end)
enemy:AddNewModifier(self.caster, self.ability, "modifier_imba_sec_torrent_slow", {duration = self.sec_torrent_slow_duration * (1 - enemy:GetStatusResistance())})
end
-- Creates the post-ability sound effect
EmitSoundOnLocationWithCaster(random_vector, "Ability.Torrent", caster)
-- Draws the particle
local particle = "particles/hero/kunkka/torrent_splash.vpcf"
local torrent_fx = ParticleManager:CreateParticle(particle, PATTACH_CUSTOMORIGIN, self.caster)
ParticleManager:SetParticleControl(torrent_fx, 0, random_vector)
ParticleManager:SetParticleControl(torrent_fx, 1, Vector(radius,0,0))
ParticleManager:ReleaseParticleIndex(torrent_fx)
end)
end
end
-------------------------------------------
-- TIDEBRINGER
-------------------------------------------
imba_kunkka_tidebringer = class({})
LinkLuaModifier("modifier_imba_tidebringer", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_tidebringer_sword_particle", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_tidebringer_manual", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_tidebringer_slow", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_tidebringer_cleave_hit_target", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
function imba_kunkka_tidebringer:GetAbilityTextureName()
return "kunkka_tidebringer"
end
function imba_kunkka_tidebringer:GetIntrinsicModifierName()
return "modifier_imba_tidebringer"
end
function imba_kunkka_tidebringer:GetCastRange(location, target)
return self:GetCaster():Script_GetAttackRange()
end
function imba_kunkka_tidebringer:IsStealable()
return false
end
function imba_kunkka_tidebringer:OnSpellStart()
if IsServer() then
-- Force attack the target
local caster = self:GetCaster()
caster:MoveToTargetToAttack(self:GetCursorTarget())
caster:AddNewModifier(caster, self, "modifier_imba_tidebringer_manual", {})
-- If manually casted, reset CD, CD getting applied on hit
self:EndCooldown()
end
end
function imba_kunkka_tidebringer:OnUpgrade()
if IsServer() then
self:GetCaster():RemoveModifierByName("modifier_imba_tidebringer")
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_tidebringer", {})
-- Toggles the autocast when first leveled
local caster_tidebringer = self:GetCaster():FindAbilityByName("imba_kunkka_tidebringer")
if caster_tidebringer and caster_tidebringer:GetLevel() == 1 then
caster_tidebringer:ToggleAutoCast()
end
end
end
function imba_kunkka_tidebringer:GetCooldown( nLevel )
local cooldown = self.BaseClass.GetCooldown( self, nLevel )
local caster = self:GetCaster()
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_wave") or caster:HasModifier("modifier_imba_ebb_and_flow_tsunami") or (caster:HasTalent("special_bonus_imba_kunkka_2") and caster:HasModifier("modifier_imba_ghostship_rum")) then
cooldown = 0
end
return cooldown
end
modifier_imba_tidebringer_sword_particle = class({})
function modifier_imba_tidebringer_sword_particle:IsHidden()
return true
end
function modifier_imba_tidebringer_sword_particle:RemoveOnDeath()
return false
end
function modifier_imba_tidebringer_sword_particle:IsPurgable()
return false
end
function modifier_imba_tidebringer_sword_particle:OnDestroy()
if IsServer() then
local caster = self:GetCaster()
local ability = self:GetAbility()
local cooldown = ability:GetCooldown(ability:GetLevel()-1)
caster:EmitSound("Hero_Kunkka.Tidebringer.Attack")
ParticleManager:DestroyParticle(caster.tidebringer_weapon_pfx, true)
ParticleManager:ReleaseParticleIndex(caster.tidebringer_weapon_pfx)
caster.tidebringer_weapon_pfx = 0
end
end
function modifier_imba_tidebringer_sword_particle:OnCreated()
if IsServer() then
local caster = self:GetCaster()
local ability = self:GetAbility()
caster.tidebringer_weapon_pfx = caster.tidebringer_weapon_pfx or 0
if caster.tidebringer_weapon_pfx == 0 then
EmitSoundOn("Hero_Kunkaa.Tidebringer", caster)
caster.tidebringer_weapon_pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_kunkka/kunkka_weapon_tidebringer.vpcf", PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControlEnt(caster.tidebringer_weapon_pfx, 0, caster, PATTACH_POINT_FOLLOW, "attach_tidebringer", caster:GetAbsOrigin(), true)
ParticleManager:SetParticleControlEnt(caster.tidebringer_weapon_pfx, 2, caster, PATTACH_POINT_FOLLOW, "attach_sword", caster:GetAbsOrigin(), true)
end
end
end
modifier_imba_tidebringer_manual = class({})
function modifier_imba_tidebringer_manual:IsHidden()
return false
end
modifier_imba_tidebringer = class({})
function modifier_imba_tidebringer:DeclareFunctions()
return {
MODIFIER_EVENT_ON_ATTACK_LANDED,
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_EVENT_ON_ATTACK_START,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE
}
end
function modifier_imba_tidebringer:OnCreated()
local caster = self:GetCaster()
local ability = self:GetAbility()
if IsServer() then
if (not caster:HasModifier("modifier_imba_tidebringer_sword_particle")) and ability:IsCooldownReady() then
caster:AddNewModifier(caster, ability, "modifier_imba_tidebringer_sword_particle", {})
end
end
end
function modifier_imba_tidebringer:OnRefresh()
local caster = self:GetCaster()
local ability = self:GetAbility()
if IsServer() then
if ( not caster:HasModifier("modifier_imba_tidebringer_sword_particle")) and ability:IsCooldownReady() then
caster:AddNewModifier(caster, ability, "modifier_imba_tidebringer_sword_particle", {})
end
end
end
function modifier_imba_tidebringer:OnAttackStart( params )
if self:GetAbility() then
local parent = self:GetParent()
local target = params.target
if (parent == params.attacker) and (target:GetTeamNumber() ~= parent:GetTeamNumber()) and (target.IsCreep or target.IsHero) then
if not target:IsBuilding() then
local ability = self:GetAbility()
self.sound_triggered = false
-- Check buffs by Ebb and Flow, and set on Cooldown after cast to give a new buff
self.tide_index = 0
if parent:HasModifier("modifier_imba_ebb_and_flow_tsunami") then self.tide_index = 1 end
if parent:HasModifier("modifier_imba_ebb_and_flow_tide_low") then self.tide_index = 2 end
if parent:HasModifier("modifier_imba_ebb_and_flow_tide_red") then self.tide_index = 3 end
if parent:HasModifier("modifier_imba_ebb_and_flow_tide_flood") then self.tide_index = 4 end
if parent:HasModifier("modifier_imba_ebb_and_flow_tide_high") then self.tide_index = 5 end
if parent:HasModifier("modifier_imba_ebb_and_flow_tide_wave") then self.tide_index = 6 end
if ability:IsCooldownReady() and not (parent:PassivesDisabled()) then
if ability:GetAutoCastState() or parent:HasModifier("modifier_imba_tidebringer_manual") then
self.pass_attack = true
self.bonus_damage = ability:GetSpecialValueFor("bonus_damage")
if (self.tide_index == 4) or (self.tide_index == 1) then
self.bonus_damage = self.bonus_damage + ability:GetSpecialValueFor("tide_flood_damage")
end
else
self.pass_attack = false
self.bonus_damage = 0
end
end
end
end
end
end
function modifier_imba_tidebringer:OnAttackLanded( params )
local ability = self:GetAbility()
if self:GetAbility() then
local parent = self:GetParent()
local tidebringer_bonus_damage = self.bonus_damage
if params.attacker == parent and ( not parent:IsIllusion() ) and self.pass_attack then
self.pass_attack = false
self.bonus_damage = 0
-- If you get break during attack-swing
if parent:PassivesDisabled() then
return 0
end
local range = self:GetAbility():GetSpecialValueFor("range")
local radius_start = self:GetAbility():GetSpecialValueFor("radius_start")
local radius_end = self:GetAbility():GetSpecialValueFor("radius_end")
parent:RemoveModifierByName("modifier_imba_tidebringer_sword_particle")
if (self.tide_index == 2) or (self.tide_index == 1) then
range = range + ability:GetSpecialValueFor("tide_low_range")
end
if (self.tide_index == 5) or (self.tide_index == 1) then
radius_start = radius_start + ability:GetSpecialValueFor("tide_high_radius")
radius_end = radius_end + ability:GetSpecialValueFor("tide_high_radius")
end
-- Torrent animation if Tsunami
if self.tide_index == 1 then
self.torrent_radius = radius_end * ( math.sqrt( math.pow((radius_end - radius_start), 2) + math.pow(range, 2)) + radius_start - radius_end) / range
self.position_center = parent:GetAbsOrigin() + parent:GetForwardVector() * self.torrent_radius
local torrent_fx_mini = ParticleManager:CreateParticle("particles/hero/kunkka/torrent_splash.vpcf", PATTACH_CUSTOMORIGIN, parent)
ParticleManager:SetParticleControl(torrent_fx_mini, 0, self.position_center)
ParticleManager:SetParticleControl(torrent_fx_mini, 1, Vector(self.torrent_radius,0,0))
end
local target = params.target
if target ~= nil and target:GetTeamNumber() ~= self:GetParent():GetTeamNumber() then
self:TidebringerEffects( target, ability )
-- Calculate bonus damage to be used for cleave
local cleaveDamage = params.damage * (ability:GetTalentSpecialValueFor("cleave_damage") / 100)
local enemies_to_cleave = FindUnitsInCone(self:GetParent():GetTeamNumber(),CalculateDirection(params.target, self:GetParent()),self:GetParent():GetAbsOrigin(), radius_start, radius_end, range, nil, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, FIND_ANY_ORDER, false)
-- #7 Talent: Tidebringer will always hit enemies with Torrent debuff
if parent:HasTalent("special_bonus_imba_kunkka_7") then
local enemies = FindUnitsInRadius(self:GetParent():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, 0, false)
local hit_enemy = false
for _,enemy in pairs (enemies) do
if enemy:HasModifier("modifier_imba_torrent_slow") or enemy:HasModifier("modifier_imba_torrent_slow_tide") or enemy:HasModifier("modifier_imba_sec_torrent_slow") or enemy:HasModifier("modifier_imba_torrent_phase") then
hit_enemy = true
-- Prevent the enemy from being hit again if it's already hit once by Tidebringer.
for _,enemy_hit in pairs (enemies_to_cleave) do
if enemy == enemy_hit then
hit_enemy = false
end
end
if hit_enemy then
-- Play hit particle
local tidebringer_hit_fx = ParticleManager:CreateParticle("particles/units/heroes/hero_kunkka/kunkka_spell_tidebringer.vpcf", PATTACH_CUSTOMORIGIN, self:GetParent())
ParticleManager:SetParticleControlEnt(tidebringer_hit_fx, 0, enemy, PATTACH_POINT_FOLLOW, "attach_hitloc", enemy:GetAbsOrigin(), true)
ParticleManager:SetParticleControlEnt(tidebringer_hit_fx, 1, enemy, PATTACH_POINT_FOLLOW, "attach_hitloc", enemy:GetAbsOrigin(), true)
ParticleManager:SetParticleControlEnt(tidebringer_hit_fx, 2, enemy, PATTACH_POINT_FOLLOW, "attach_hitloc", enemy:GetAbsOrigin(), true)
-- Deal the cleave damage
ApplyDamage({attacker = self:GetParent(), victim = enemy, ability = ability, damage = cleaveDamage, damage_type = DAMAGE_TYPE_PHYSICAL})
end
end
end
end
-- #7 Talent: If the enemy is the target itself, Tidebringer also hits him, dealing what damage that should be done, true Cleave damage
if parent:HasTalent("special_bonus_imba_kunkka_7") then
if params.target:HasModifier("modifier_imba_torrent_slow") or params.target:HasModifier("modifier_imba_torrent_slow_tide") or params.target:HasModifier("modifier_imba_sec_torrent_slow") or params.target:HasModifier("modifier_imba_torrent_phase") then
for _,enemy_to_hit in pairs (enemies_to_cleave) do
-- Play hit particle
local tidebringer_hit_fx = ParticleManager:CreateParticle("particles/units/heroes/hero_kunkka/kunkka_spell_tidebringer.vpcf", PATTACH_CUSTOMORIGIN, self:GetParent())
ParticleManager:SetParticleControlEnt(tidebringer_hit_fx, 0, enemy_to_hit, PATTACH_POINT_FOLLOW, "attach_hitloc", enemy_to_hit:GetAbsOrigin(), true)
ParticleManager:SetParticleControlEnt(tidebringer_hit_fx, 1, enemy_to_hit, PATTACH_POINT_FOLLOW, "attach_hitloc", enemy_to_hit:GetAbsOrigin(), true)
ParticleManager:SetParticleControlEnt(tidebringer_hit_fx, 2, enemy_to_hit, PATTACH_POINT_FOLLOW, "attach_hitloc", enemy_to_hit:GetAbsOrigin(), true)
target_cleaved = enemy_to_hit:AddNewModifier(self:GetParent(),ability,"modifier_imba_tidebringer_cleave_hit_target",{duration = 0.01})
if target_cleaved then
target_cleaved.cleave_damage = cleaveDamage
end
end
else
DoCleaveAttack( params.attacker, params.target, ability, cleaveDamage, radius_start, radius_end, range, "particles/units/heroes/hero_kunkka/kunkka_spell_tidebringer.vpcf" )
end
else
DoCleaveAttack( params.attacker, params.target, ability, cleaveDamage, radius_start, radius_end, range, "particles/units/heroes/hero_kunkka/kunkka_spell_tidebringer.vpcf" )
end
if not ((self.tide_index == 6) or (self.tide_index == 1)) then
local cooldown = ability:GetCooldown(ability:GetLevel()-1)
ability:UseResources(false, false, true)
Timers:CreateTimer( cooldown, function()
if not parent:HasModifier("modifier_imba_tidebringer_sword_particle") then
parent:AddNewModifier(parent, ability, "modifier_imba_tidebringer_sword_particle", {})
end
--return nil
end)
end
if parent:HasModifier("modifier_imba_tidebringer_manual") then
parent:RemoveModifierByName("modifier_imba_tidebringer_manual")
end
if parent:HasAbility("imba_kunkka_ebb_and_flow") then
local ability_tide = parent:FindAbilityByName("imba_kunkka_ebb_and_flow")
if self.tide_index >= 1 then
ability_tide:CastAbility()
end
cooldown = ability_tide:GetCooldownTimeRemaining() - (self.hitCounter * ability:GetSpecialValueFor("cdr_per_hit"))
ability_tide:EndCooldown()
ability_tide:StartCooldown(cooldown)
self.hitCounter = nil
end
end
end
end
return 0
end
function modifier_imba_tidebringer:GetModifierPreAttack_BonusDamage(params)
self.bonus_damage = self.bonus_damage or 0
return self.bonus_damage
end
function modifier_imba_tidebringer:OnTakeDamage( params )
if IsServer() then
if params.attacker == self:GetParent() and ( bit.band( params.damage_flags , DOTA_DAMAGE_FLAG_IGNORES_PHYSICAL_ARMOR) == DOTA_DAMAGE_FLAG_IGNORES_PHYSICAL_ARMOR) and params.inflictor:GetAbilityName() == "imba_kunkka_tidebringer" then
self:TidebringerEffects( params.unit, params.inflictor )
end
end
end
function modifier_imba_tidebringer:TidebringerEffects( target, ability )
local sound_height = 1000
self.hitCounter = self.hitCounter or 0
self.hitCounter = self.hitCounter + 1
local attacker = self:GetCaster()
if ( self.tide_index == 1 or self.tide_index == 3 ) and not target:IsMagicImmune() then
target:AddNewModifier(attacker, ability, "modifier_imba_tidebringer_slow", {duration = ability:GetSpecialValueFor("tide_red_slow_duration") * (1 - target:GetStatusResistance())})
end
if self.tide_index == 1 then
local location = target:GetAbsOrigin()
local distance_from_center = ( location - self.position_center ):Length2D()
local knocking_up = ((self.torrent_radius / distance_from_center ) * 50) * ( attacker:GetAverageTrueAttackDamage(attacker) / 300) + 40
local knockback =
{
should_stun = 1,
knockback_duration = ability:GetSpecialValueFor("tsunami_stun"),
duration = ability:GetSpecialValueFor("tsunami_stun"),
knockback_distance = 0,
knockback_height = knocking_up,
center_x = location.x,
center_y = location.y,
center_z = location.z
}
target:EmitSound("Hero_Kunkka.TidebringerDamage")
if (knocking_up > sound_height) and not self.sound_triggered then
EmitSoundOn("Kunkka.ShootingStar", target)
self.sound_triggered = true
end
-- Apply knockback on enemies hit
target:RemoveModifierByName("modifier_knockback")
target:AddNewModifier(self:GetParent(), ability, "modifier_knockback", knockback)
end
end
function modifier_imba_tidebringer:IsHidden()
return true
end
function modifier_imba_tidebringer:RemoveOnDeath()
return false
end
function modifier_imba_tidebringer:IsPurgable()
return false
end
modifier_imba_tidebringer_slow = class({})
function modifier_imba_tidebringer_slow:DeclareFunctions()
local decFuncs =
{
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE
}
return decFuncs
end
function modifier_imba_tidebringer_slow:GetModifierMoveSpeedBonus_Percentage( )
return ( self:GetAbility():GetSpecialValueFor("tide_red_slow") * (-1) )
end
function modifier_imba_tidebringer_slow:IsDebuff()
return true
end
function modifier_imba_tidebringer_slow:IsPurgable()
return true
end
function modifier_imba_tidebringer_slow:IsHidden()
return false
end
function modifier_imba_tidebringer_slow:RemoveOnDeath()
return true
end
modifier_imba_tidebringer_cleave_hit_target = class({})
function modifier_imba_tidebringer_cleave_hit_target:IsHidden()
return true
end
function modifier_imba_tidebringer_cleave_hit_target:IsPurgable()
return false
end
function modifier_imba_tidebringer_cleave_hit_target:IsDebuff()
return false
end
function modifier_imba_tidebringer_cleave_hit_target:StatusEffectPriority()
return 20
end
function modifier_imba_tidebringer_cleave_hit_target:OnDestroy()
if IsServer() then
ApplyDamage({attacker = self:GetCaster(), victim = self:GetParent(), ability = self:GetAbility(), damage = self.cleave_damage, damage_type = DAMAGE_TYPE_PHYSICAL})
end
end
function modifier_imba_tidebringer_cleave_hit_target:DeclareFunctions()
return {MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE}
end
function modifier_imba_tidebringer_cleave_hit_target:GetModifierIncomingDamage_Percentage()
return -100
end
-------------------------------------------
-- X MARKS THE SPOT
-------------------------------------------
imba_kunkka_x_marks_the_spot = class({})
LinkLuaModifier("modifier_imba_x_marks_the_spot", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_x_marks_the_spot_return", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_x_marks_the_spot_talent_ms", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
function imba_kunkka_x_marks_the_spot:GetAbilityTextureName()
return "kunkka_x_marks_the_spot"
end
function imba_kunkka_x_marks_the_spot:OnSpellStart()
if IsServer() then
local caster = self:GetCaster()
local target = self:GetCursorTarget()
local duration = self:GetSpecialValueFor("duration") * (1 - target:GetStatusResistance())
local sec_duration = self:GetSpecialValueFor("sec_duration") * (1 - target:GetStatusResistance())
local talent_hits = false
if caster:HasTalent("special_bonus_imba_kunkka_5") then
local radius = caster:FindTalentValue("special_bonus_imba_kunkka_5")
-- Finds affected enemies
local enemies = FindUnitsInRadius(caster:GetTeam(), target:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, 0, 0, false)
for _,enemy in pairs(enemies) do
if enemy ~= target then
talent_hits = true
enemy:AddNewModifier(caster, self, "modifier_imba_x_marks_the_spot", {duration = duration, sec_duration = sec_duration})
self:CreateVisibilityNode(enemy:GetAbsOrigin(), 300, 8)
end
end
end
if caster:GetTeam() == target:GetTeam() then
duration = self:GetSpecialValueFor("allied_duration")
sec_duration = 0
end
self:CreateVisibilityNode(target:GetAbsOrigin(), 300, 8)
if target:TriggerSpellAbsorb(self) then
if talent_hits then caster:AddNewModifier(caster, self, "modifier_imba_x_marks_the_spot_return", {duration = duration}) end
return nil
end
caster:AddNewModifier(caster, self, "modifier_imba_x_marks_the_spot_return", {duration = duration})
target:AddNewModifier(caster, self, "modifier_imba_x_marks_the_spot", {duration = duration, sec_duration = sec_duration})
end
end
function imba_kunkka_x_marks_the_spot:GetAOERadius()
local caster = self:GetCaster()
if caster:HasTalent("special_bonus_imba_kunkka_5") then
return caster:FindTalentValue("special_bonus_imba_kunkka_5")
end
return 0
end
function imba_kunkka_x_marks_the_spot:OnUpgrade()
local ability_handle = self:GetCaster():FindAbilityByName("imba_kunkka_return")
self.positions = self.positions or {}
if ability_handle then
-- Upgrades Return to level 1 and make it inactive, if it hasn't already
if ability_handle:GetLevel() < 1 then
ability_handle:SetLevel(1)
ability_handle:SetActivated(false)
end
end
end
function imba_kunkka_x_marks_the_spot:GetAssociatedSecondaryAbilities()
return "imba_kunkka_return"
end
function imba_kunkka_x_marks_the_spot:IsHiddenWhenStolen()
return false
end
modifier_imba_x_marks_the_spot = class({})
function modifier_imba_x_marks_the_spot:OnCreated( params )
if IsServer() then
local parent = self:GetParent()
local caster = self:GetCaster()
local ability = self:GetAbility()
self.position = parent:GetAbsOrigin()
self.sec_duration = params.sec_duration
-- Positions for Aghanims Boat
self.position_id = params.position_id or 0
if self.position_id == 0 then
table.insert(ability.positions , self.position)
self.position_id = #ability.positions
end
EmitSoundOn("Ability.XMarksTheSpot.Target", caster)
EmitSoundOn("Ability.XMark.Target_Movement", parent)
self.x_pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_kunkka/kunkka_spell_x_spot.vpcf", PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControlEnt(self.x_pfx, 0, parent, PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", parent:GetAbsOrigin(), true)
ParticleManager:SetParticleControlEnt(self.x_pfx, 1, parent, PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", parent:GetAbsOrigin(), true)
end
end
function modifier_imba_x_marks_the_spot:OnDestroy( params )
if IsServer() then
local caster = self:GetCaster()
local parent = self:GetParent()
local ability = self:GetAbility()
local position = self.position
local duration = self.sec_duration or 0
parent:StopSound("Ability.XMark.Target_Movement")
self.sec_duration = 0
EmitSoundOn("Ability.XMarksTheSpot.Return", parent)
ParticleManager:DestroyParticle(self.x_pfx, false)
ParticleManager:ReleaseParticleIndex(self.x_pfx)
-- Response 20%
if (math.random(1,5) < 2) and (caster:GetName() == "npc_dota_hero_kunkka") then
caster:EmitSound("kunkka_kunk_ability_xmark_0"..math.random(1,5))
end
if not ( parent:IsMagicImmune() or parent:IsInvulnerable() ) then
local stopOrder =
{
UnitIndex = parent:entindex(),
OrderType = DOTA_UNIT_ORDER_STOP
}
ExecuteOrderFromTable( stopOrder )
FindClearSpaceForUnit(parent, self.position, true)
if duration > 0 then
parent:AddNewModifier(caster, ability, "modifier_imba_x_marks_the_spot", {duration = duration, sec_duration = 0, position_id = self.position_id})
else
ability.positions[self.position_id] = nil
end
-- #3 Talent: X Marks The Spot Return grants 10% movespeed for allies, 10% movespeed reduction for enemies
if caster:HasTalent("special_bonus_imba_kunkka_3") then
if caster:GetTeamNumber() ~= parent:GetTeamNumber() then
parent:AddNewModifier(caster,ability,"modifier_imba_x_marks_the_spot_talent_ms",{duration = ability:GetTalentSpecialValueFor("duration") * (1 - parent:GetStatusResistance())})
else
parent:AddNewModifier(caster,ability,"modifier_imba_x_marks_the_spot_talent_ms",{duration = ability:GetTalentSpecialValueFor("allied_duration")})
end
end
end
end
end
function modifier_imba_x_marks_the_spot:IsDebuff()
local caster = self:GetCaster()
local parent = self:GetParent()
if caster:GetTeamNumber() ~= parent:GetTeamNumber() then
return true
end
return false
end
function modifier_imba_x_marks_the_spot:IsHidden()
return false
end
function modifier_imba_x_marks_the_spot:GetTexture()
return "kunkka_x_marks_the_spot"
end
function modifier_imba_x_marks_the_spot:IsPurgable()
return false
end
function modifier_imba_x_marks_the_spot:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
modifier_imba_x_marks_the_spot_return = class({})
function modifier_imba_x_marks_the_spot_return:IsHidden()
return true
end
function modifier_imba_x_marks_the_spot_return:GetTexture()
return "kunkka_x_marks_the_spot"
end
function modifier_imba_x_marks_the_spot_return:IsPurgable()
return false
end
function modifier_imba_x_marks_the_spot_return:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
function modifier_imba_x_marks_the_spot_return:OnCreated( params )
if IsServer() then
local ability_handle = self:GetCaster():FindAbilityByName("imba_kunkka_return")
if ability_handle then
ability_handle:SetActivated(true)
self:GetCaster():SwapAbilities("imba_kunkka_x_marks_the_spot", "imba_kunkka_return", false, true)
end
end
end
function modifier_imba_x_marks_the_spot_return:OnDestroy( params )
if IsServer() then
local caster = self:GetCaster()
local parent = self:GetParent()
local ability = self:GetAbility()
if not caster:HasModifier("modifier_imba_x_marks_the_spot_return") and caster:HasAbility("imba_kunkka_return") then
caster:FindAbilityByName("imba_kunkka_return"):SetActivated(false)
caster:SwapAbilities("imba_kunkka_x_marks_the_spot", "imba_kunkka_return", true, false)
end
end
end
modifier_imba_x_marks_the_spot_talent_ms = class({})
function modifier_imba_x_marks_the_spot_talent_ms:IsDebuff()
local caster = self:GetCaster()
local parent = self:GetParent()
if caster:GetTeamNumber() ~= parent:GetTeamNumber() then
return true
end
return false
end
function modifier_imba_x_marks_the_spot_talent_ms:IsHidden()
return false
end
function modifier_imba_x_marks_the_spot_talent_ms:GetTexture()
return "kunkka_x_marks_the_spot"
end
function modifier_imba_x_marks_the_spot_talent_ms:IsPurgable()
return false
end
function modifier_imba_x_marks_the_spot_talent_ms:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
function modifier_imba_x_marks_the_spot_talent_ms:DeclareFunctions()
return {MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE}
end
function modifier_imba_x_marks_the_spot_talent_ms:GetModifierMoveSpeedBonus_Percentage()
local caster = self:GetCaster()
local parent = self:GetParent()
if caster:GetTeamNumber() ~= parent:GetTeamNumber() then
return caster:FindTalentValue("special_bonus_imba_kunkka_3") * (-1)
end
return caster:FindTalentValue("special_bonus_imba_kunkka_3")
end
-------------------------------------------
-- RETURN
-------------------------------------------
imba_kunkka_return = class({})
function imba_kunkka_return:GetAbilityTextureName()
return "kunkka_return"
end
function imba_kunkka_return:IsNetherWardStealable() return false end
function imba_kunkka_return:OnSpellStart()
if IsServer() then
local caster = self:GetCaster()
local targets = FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS + DOTA_UNIT_TARGET_FLAG_DEAD + DOTA_UNIT_TARGET_FLAG_INVULNERABLE, 0, false)
for _,target in pairs(targets) do
if target:HasModifier("modifier_imba_x_marks_the_spot") then
local modifiers = target:FindAllModifiersByName("modifier_imba_x_marks_the_spot")
for _, modifier in pairs( modifiers ) do
if (( modifier:GetCaster() == self:GetCaster() ) and ( (modifier.sec_duration > 0) or (modifier:IsDebuff() == false))) then
modifier:Destroy()
end
end
end
end
for _, modifier in pairs( caster:FindAllModifiersByName("modifier_imba_x_marks_the_spot_return") ) do
modifier:Destroy()
end
end
end
function imba_kunkka_return:IsHiddenWhenStolen()
return false
end
function imba_kunkka_return:IsStealable()
return false
end
function imba_kunkka_return:GetAssociatedPrimaryAbilities()
return "imba_kunkka_x_marks_the_spot"
end
-------------------------------------------
-- GHOSTSHIP
-------------------------------------------
imba_kunkka_ghostship = class({})
LinkLuaModifier("modifier_imba_ghostship_rum", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_ghostship_rum_damage", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_ghostship_tide_slow", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_ghostship_drag", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
function imba_kunkka_ghostship:GetAbilityTextureName()
return "kunkka_ghostship"
end
function imba_kunkka_ghostship:OnSpellStart()
if IsServer() then
-- Preventing projectiles getting stuck in one spot due to potential 0 length vector
if self:GetCursorPosition() == self:GetCaster():GetAbsOrigin() then
self:GetCaster():SetCursorPosition(self:GetCursorPosition() + self:GetCaster():GetForwardVector())
end
local caster = self:GetCaster()
local target = self:GetCursorPosition()
-- Parameters
local scepter = caster:HasScepter()
local damage = self:GetSpecialValueFor("damage")
local speed = self:GetSpecialValueFor("ghostship_speed")
local radius = self:GetSpecialValueFor("ghostship_width")
local start_distance = self:GetSpecialValueFor("start_distance")
local crash_distance = self:GetSpecialValueFor("crash_distance")
local stun_duration = self:GetSpecialValueFor("stun_duration")
local buff_duration = self:GetSpecialValueFor("buff_duration")
local crash_delay = 0
local caster_pos = caster:GetAbsOrigin()
-- Check buffs by Ebb and Flow
local tsunami = caster:HasModifier("modifier_imba_ebb_and_flow_tsunami")
-- Flood Tide
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_flood") or tsunami then
damage = damage + self:GetSpecialValueFor("tide_flood_damage")
end
-- High Tide
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_high") or tsunami then
if scepter then
radius = radius + self:GetSpecialValueFor("scepter_tide_high_radius")
end
radius = radius + self:GetSpecialValueFor("tide_high_radius")
end
-- Wave Tide
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_wave") or tsunami then
speed = speed + self:GetSpecialValueFor("tide_wave_speed")
end
-- Red Tide
local extra_slow = false
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_red") or tsunami then
extra_slow = true
end
-- Tsunami exclusive
if tsunami then
stun_duration = stun_duration + self:GetSpecialValueFor("tsunami_stun")
end
-- Calculate spawn and crash positions
local closest_target = true
local spawn_pos
local boat_direction
local crash_pos
local travel_time
-- Response on cast
if caster:GetName() == "npc_dota_hero_kunkka" then
caster:EmitSound("kunkka_kunk_ability_ghostshp_0"..math.random(1,3))
end
-- Scepter check
if scepter then
local scepter_damage = damage * (self:GetSpecialValueFor("buff_duration") / 100)
-- Wave Tide
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_wave") or tsunami then
crash_delay = self:GetSpecialValueFor("scepter_tide_wave_delay")
else
crash_delay = self:GetSpecialValueFor("scepter_crash_delay")
end
spawn_pos = target
boat_direction = ( target - caster_pos ):Normalized()
crash_pos = target + boat_direction * (start_distance + crash_distance) * (-1)
end
-- In case the ability is stolen don't cast the next tide
if caster:HasAbility("imba_kunkka_ebb_and_flow") and not ( caster:HasModifier("modifier_imba_ebb_and_flow_tide_low") and not scepter ) then
local ability_tide = caster:FindAbilityByName("imba_kunkka_ebb_and_flow")
ability_tide:CastAbility()
end
if not scepter then
boat_direction = ( target - caster_pos ):Normalized()
crash_pos = target
spawn_pos = target + boat_direction * (start_distance + crash_distance) * (-1)
end
travel_time = ((start_distance + crash_distance - radius ) / speed )
local bubbles_pfx
-- Aghanims crushing down
if scepter then
local height = 1000
local ticks = FrameTime()
local travel = 0
local float_boat = spawn_pos + Vector(0,0,height)
local height_ticks = height * ticks / crash_delay * (-1)
self:CreateVisibilityNode(target, radius, crash_delay + 1 )
bubbles_pfx = ParticleManager:CreateParticle("particles/hero/kunkka/torrent_bubbles.vpcf", PATTACH_ABSORIGIN, caster)
ParticleManager:SetParticleControl(bubbles_pfx, 0, target)
ParticleManager:SetParticleControl(bubbles_pfx, 1, Vector(radius,0,0))
Timers:CreateTimer((crash_delay + 1), function()
ParticleManager:DestroyParticle(bubbles_pfx, false)
ParticleManager:ReleaseParticleIndex(bubbles_pfx)
end)
local boat_pfx = ParticleManager:CreateParticle("particles/hero/kunkka/kunkka_ghost_ship.vpcf", PATTACH_ABSORIGIN, caster)
ParticleManager:SetParticleControl(boat_pfx, 0, (spawn_pos - boat_direction * (-1) * crash_distance ) )
Timers:CreateTimer(ticks, function()
float_boat = float_boat + Vector(0,0,height_ticks)
ParticleManager:SetParticleControl(boat_pfx, 3, float_boat )
travel = travel + ticks
if travel > crash_delay then
-- Water Nova on hit + crash sound
local water_fx = ParticleManager:CreateParticle("particles/units/heroes/hero_kunkka/kunkka_boat_splash_end.vpcf", PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControl(water_fx, 3, target)
Timers:CreateTimer(2, function()
ParticleManager:DestroyParticle(water_fx, false)
ParticleManager:ReleaseParticleIndex(water_fx)
end)
-- Stunning and rooting all hit enemies
local enemies = FindUnitsInRadius(caster:GetTeam(), target, nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, self:GetAbilityTargetType(), 0, 0, false)
for k, enemy in pairs(enemies) do
--enemy:AddNewModifier(caster, self, "modifier_stunned", {duration = travel_time})
--enemy:AddNewModifier(caster, self, "modifier_rooted", { duration = travel_time})
-- Deal crash damage to enemies hit
ApplyDamage({victim = enemy, attacker = caster, ability = self, damage = damage, damage_type = self:GetAbilityDamageType()})
end
-- Setting ship underneath the world + deleting it
ParticleManager:SetParticleControl(boat_pfx, 3, ( float_boat - Vector(0,0,500)) )
ParticleManager:DestroyParticle(boat_pfx, false)
ParticleManager:ReleaseParticleIndex(boat_pfx)
return nil
end
return ticks
end)
end
Timers:CreateTimer(crash_delay, function()
self:CreateVisibilityNode(crash_pos, radius, travel_time + 2 )
local boat_velocity
if caster:HasScepter() then
boat_velocity = boat_direction * speed * (-1)
else
boat_velocity = boat_direction * speed
end
-- Spawn the boat
local boat_projectile = {
Ability = self,
EffectName = "particles/units/heroes/hero_kunkka/kunkka_ghost_ship.vpcf",
vSpawnOrigin = spawn_pos,
fDistance = start_distance + crash_distance - radius,
fStartRadius = radius,
fEndRadius = radius,
fExpireTime = GameRules:GetGameTime() + travel_time + 2,
Source = caster,
bHasFrontalCone = false,
bReplaceExisting = false,
bProvidesVision = false,
iUnitTargetTeam = self:GetAbilityTargetTeam(),
iUnitTargetType = self:GetAbilityTargetType(),
vVelocity = boat_velocity,
ExtraData =
{
crash_x = crash_pos.x,
crash_y = crash_pos.y,
crash_z = crash_pos.z,
speed = speed,
radius = radius
}
}
ProjectileManager:CreateLinearProjectile(boat_projectile)
EmitSoundOnLocationWithCaster( spawn_pos, "Ability.Ghostship.bell", caster )
EmitSoundOnLocationWithCaster( spawn_pos, "Ability.Ghostship", caster )
-- Show visual crash point effect to allies only
local crash_pfx = ParticleManager:CreateParticleForTeam("particles/units/heroes/hero_kunkka/kunkka_ghostship_marker.vpcf", PATTACH_ABSORIGIN, caster, caster:GetTeam())
ParticleManager:SetParticleControl(crash_pfx, 0, crash_pos )
-- Destroy particle after the crash
Timers:CreateTimer(travel_time, function()
ParticleManager:DestroyParticle(crash_pfx, false)
ParticleManager:ReleaseParticleIndex(crash_pfx)
-- Fire sound on crash point
EmitSoundOnLocationWithCaster(crash_pos, "Ability.Ghostship.crash", caster)
-- Stun and damage enemies
local enemies = FindUnitsInRadius(caster:GetTeam(), crash_pos, nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, self:GetAbilityTargetType(), 0, 0, false)
if (not (#enemies > 0)) and (caster:GetName() == "npc_dota_hero_kunkka") then
if math.random(1,2) == 1 then
caster:EmitSound("kunkka_kunk_ability_failure_0"..math.random(1,2))
end
end
for k, enemy in pairs(enemies) do
ApplyDamage({victim = enemy, attacker = caster, ability = self, damage = damage, damage_type = self:GetAbilityDamageType()})
if extra_slow then
enemy:AddNewModifier(caster, self, "modifier_imba_ghostship_tide_slow", { duration = stun_duration + self:GetSpecialValueFor("tide_red_slow_duration") * (1 - enemy:GetStatusResistance()) })
end
enemy:AddNewModifier(caster, self, "modifier_stunned", { duration = stun_duration * (1 - enemy:GetStatusResistance()) })
end
end)
end)
end
end
function imba_kunkka_ghostship:IsHiddenWhenStolen()
return false
end
function imba_kunkka_ghostship:GetCastRange( location , target)
local caster = self:GetCaster()
local range = self.BaseClass.GetCastRange(self,location,target)
if caster:HasScepter() then
range = self:GetSpecialValueFor("scepter_cast_range")
end
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_low") or caster:HasModifier("modifier_imba_ebb_and_flow_tsunami") then
range = range + self:GetSpecialValueFor("scepter_tide_low_range")
end
return range
end
function imba_kunkka_ghostship:GetAOERadius()
local caster = self:GetCaster()
if (not caster:HasScepter()) then return 0 end
local radius = self:GetSpecialValueFor("ghostship_width")
if caster:HasModifier("modifier_imba_ebb_and_flow_tide_high") or caster:HasModifier("modifier_imba_ebb_and_flow_tsunami") then
radius = radius + self:GetSpecialValueFor("scepter_high_tide_radius")
end
return radius
end
function imba_kunkka_ghostship:OnProjectileHit_ExtraData(target, location, ExtraData)
if target then
local caster = self:GetCaster()
-- If the target hit is on the same team as the caster, give them the rum buff and do nothing else
if caster:GetTeam() == target:GetTeam() then
local duration = self:GetSpecialValueFor("buff_duration")
target:AddNewModifier(caster, self, "modifier_imba_ghostship_rum", { duration = duration })
-- #4 Talent: Ghostship now drags Kunkka into the target location
if caster:HasTalent("special_bonus_imba_kunkka_6") then
if target == caster then
else
return false
end
else
return false
end
end
-- Rest of this code is for enemy interaction
-- The exact location where the boat is going to finish impact
local crash_pos = Vector(ExtraData.crash_x,ExtraData.crash_y,ExtraData.crash_z)
-- The exact location where the enemy makes contact with the boat
local target_pos = target:GetAbsOrigin()
--
local knockback_origin = target_pos + (target_pos - crash_pos):Normalized() * 100
-- Distnace between target and crash location
local distance = (crash_pos - target_pos ):Length2D()
local duration = ((location - crash_pos ):Length2D() - ExtraData.radius) / ExtraData.speed
if IsNearFountain(target_pos, 1200) or IsNearFountain(crash_pos, 1200) then
duration = 0
end
-- Apply the knockback modifier
local knockback =
{ should_stun = 0,
knockback_duration = duration,
duration = duration,
knockback_distance = distance,
knockback_height = 0,
center_x = knockback_origin.x + (math.random() * math.random(-10,10)),
center_y = knockback_origin.y + (math.random() * math.random(-10,10)),
center_z = knockback_origin.z
}
-- Apply a new modifier to drag
if target == caster then
ghostship_drag = target:AddNewModifier(caster,self,"modifier_imba_ghostship_drag", {duration = duration})
if ghostship_drag then
ghostship_drag.crash_pos = crash_pos
ghostship_drag.direction = (crash_pos - target_pos):Normalized()
ghostship_drag.ship_width = ExtraData.radius
ghostship_drag.ship_speed = ExtraData.speed
end
else
target:RemoveModifierByName("modifier_knockback")
target:AddNewModifier(caster, nil, "modifier_knockback", knockback)
end
end
return false
end
modifier_imba_ghostship_drag = class({})
function modifier_imba_ghostship_drag:IsHidden()
return false
end
function modifier_imba_ghostship_drag:IsPurgable()
return false
end
function modifier_imba_ghostship_drag:IsDebuff()
return false
end
function modifier_imba_ghostship_drag:RemoveOnDeath()
return false
end
function modifier_imba_ghostship_drag:IsMotionController()
return true
end
function modifier_imba_ghostship_drag:StatusEffectPriority()
return 20
end
function modifier_imba_ghostship_drag:CheckState()
local state = {
[MODIFIER_STATE_NO_UNIT_COLLISION] = true,
}
return state
end
function modifier_imba_ghostship_drag:GetMotionControllerPriority()
return DOTA_MOTION_CONTROLLER_PRIORITY_HIGH
end
function modifier_imba_ghostship_drag:OnCreated()
if IsServer() then
self.caster = self:GetCaster()
self.ability = self:GetAbility()
self.tick = FrameTime()
self:StartIntervalThink(self.tick)
end
end
function modifier_imba_ghostship_drag:OnIntervalThink()
-- Check for motion controllers
if self:CheckMotionControllers() then
else
self:Destroy()
return nil
end
self:GetDragged()
end
function modifier_imba_ghostship_drag:GetDragged()
if IsServer() then
self.current_loc = self.caster:GetAbsOrigin()
self.new_loc = self.current_loc + self.direction * self.ship_speed * self.tick
self.distance = (self.crash_pos - self.current_loc):Length2D()
Timers:CreateTimer(self.tick, function()
if not self:IsNull() then
self.next_loc = self.caster:GetAbsOrigin()
self.distance_between_ship = (self.next_loc - self.current_loc):Length2D()
-- If Kunkka exits the Ghost ship, remove the drag force.
if self.distance_between_ship > (self.ship_width/2) then
self:Destroy()
end
end
end)
-- If the distance is more than 20, set Kunkka to the new dragged location
if self.distance > 20 then
self.caster:SetAbsOrigin(self.new_loc)
else
self.caster:SetAbsOrigin(self.crash_pos)
self.caster:SetUnitOnClearGround()
self:Destroy()
end
end
end
function modifier_imba_ghostship_drag:OnDestroy()
if IsServer() then
if self.caster:HasModifier("modifier_item_forcestaff_active") or self.caster:HasModifier("modifier_item_hurricane_pike_active") or self.caster:HasModifier("modifier_item_hurricane_pike_active_alternate") then
else
self.caster:SetUnitOnClearGround()
end
end
end
modifier_imba_ghostship_rum = class({})
function modifier_imba_ghostship_rum:GetModifierMoveSpeedBonus_Percentage()
return self:GetAbility():GetSpecialValueFor("rum_speed")
end
-- Setting up the damage counter
function modifier_imba_ghostship_rum:OnCreated()
if IsServer() then
self.damage_counter = 0
end
end
function modifier_imba_ghostship_rum:GetCustomIncomingDamagePct()
return self:GetAbility():GetSpecialValueFor("rum_reduce_pct") * (-1)
end
function modifier_imba_ghostship_rum:DeclareFunctions()
local decFuncs =
{
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_EVENT_ON_TAKEDAMAGE,
}
return decFuncs
end
function modifier_imba_ghostship_rum:OnTakeDamage( params )
if IsServer() then
if params.unit == self:GetParent() then
local rum_reduction = (100 - self:GetAbility():GetSpecialValueFor("rum_reduce_pct"))/100
local gen_reduction = (100 + params.unit:GetIncomingDamagePct())/100
local prevented_damage = params.damage / rum_reduction - params.damage
self.damage_counter = self.damage_counter + prevented_damage
end
end
end
function modifier_imba_ghostship_rum:OnDestroy()
if IsServer() then
local caster = self:GetCaster()
local ability = self:GetAbility()
if not caster:HasTalent("special_bonus_imba_kunkka_8") then
self:GetParent():AddNewModifier(caster, ability, "modifier_imba_ghostship_rum_damage", { duration = ability:GetSpecialValueFor("damage_duration"), stored_damage = self.damage_counter })
end
self.damage_counter = 0
end
end
function modifier_imba_ghostship_rum:GetStatusEffectName()
return "particles/status_fx/status_effect_rum.vpcf"
end
function modifier_imba_ghostship_rum:StatusEffectPriority()
return 10
end
function modifier_imba_ghostship_rum:GetTexture()
return "kunkka_ghostship"
end
function modifier_imba_ghostship_rum:IsHidden()
return false
end
function modifier_imba_ghostship_rum:IsPurgable()
return false
end
function modifier_imba_ghostship_rum:IsDebuff( )
return false
end
modifier_imba_ghostship_rum_damage = class({})
function modifier_imba_ghostship_rum_damage:GetCustomIncomingDamagePct()
return self:GetAbility():GetSpecialValueFor("rum_reduce_pct")
end
function modifier_imba_ghostship_rum_damage:IsHidden()
return false
end
function modifier_imba_ghostship_rum_damage:GetTexture()
return "kunkka_ghostship"
end
function modifier_imba_ghostship_rum_damage:IsPurgable()
return false
end
function modifier_imba_ghostship_rum_damage:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
function modifier_imba_ghostship_rum_damage:IsDebuff( )
return true
end
function modifier_imba_ghostship_rum_damage:OnCreated( params )
if IsServer() then
local ability = self:GetAbility()
local parent = self:GetParent()
local damage_duration = ability:GetSpecialValueFor("damage_duration")
local damage_interval = ability:GetSpecialValueFor("damage_interval")
local ticks = damage_duration / damage_interval
local damage_amount = params.stored_damage / ticks
local current_tick = 0
Timers:CreateTimer(damage_interval, function()
-- If the target has died, do nothing
if parent:IsAlive() then
-- Nonlethal HP removal
local target_hp = parent:GetHealth()
if target_hp - damage_amount < 1 then
parent:SetHealth(1)
else
parent:SetHealth(target_hp - damage_amount)
end
current_tick = current_tick + 1
if current_tick >= ticks then
return nil
else
return damage_interval
end
else
return nil
end
end)
end
end
modifier_imba_ghostship_tide_slow = class({})
function modifier_imba_ghostship_tide_slow:DeclareFunctions()
local decFuncs =
{
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE
}
return decFuncs
end
function modifier_imba_ghostship_tide_slow:GetModifierMoveSpeedBonus_Percentage( )
return ( self:GetAbility():GetSpecialValueFor("tide_red_slow") * (-1) )
end
function modifier_imba_ghostship_tide_slow:IsDebuff()
return true
end
function modifier_imba_ghostship_tide_slow:IsPurgable()
return true
end
function modifier_imba_ghostship_tide_slow:IsHidden()
return false
end
function modifier_imba_ghostship_tide_slow:RemoveOnDeath()
return true
end
---------------------
-- TALENT HANDLERS --
---------------------
LinkLuaModifier("modifier_special_bonus_imba_kunkka_1", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_kunkka_2", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_kunkka_3", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_kunkka_4", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_kunkka_6", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_kunkka_8", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_kunkka_9", "components/abilities/heroes/hero_kunkka", LUA_MODIFIER_MOTION_NONE)
modifier_special_bonus_imba_kunkka_1 = modifier_special_bonus_imba_kunkka_1 or class({})
modifier_special_bonus_imba_kunkka_2 = modifier_special_bonus_imba_kunkka_2 or class({})
modifier_special_bonus_imba_kunkka_3 = modifier_special_bonus_imba_kunkka_3 or class({})
modifier_special_bonus_imba_kunkka_4 = modifier_special_bonus_imba_kunkka_4 or class({})
modifier_special_bonus_imba_kunkka_6 = modifier_special_bonus_imba_kunkka_6 or class({})
modifier_special_bonus_imba_kunkka_8 = modifier_special_bonus_imba_kunkka_8 or class({})
modifier_special_bonus_imba_kunkka_9 = modifier_special_bonus_imba_kunkka_9 or class({})
function modifier_special_bonus_imba_kunkka_1:IsHidden() return true end
function modifier_special_bonus_imba_kunkka_1:IsPurgable() return false end
function modifier_special_bonus_imba_kunkka_1:RemoveOnDeath() return false end
function modifier_special_bonus_imba_kunkka_2:IsHidden() return true end
function modifier_special_bonus_imba_kunkka_2:IsPurgable() return false end
function modifier_special_bonus_imba_kunkka_2:RemoveOnDeath() return false end
function modifier_special_bonus_imba_kunkka_3:IsHidden() return true end
function modifier_special_bonus_imba_kunkka_3:IsPurgable() return false end
function modifier_special_bonus_imba_kunkka_3:RemoveOnDeath() return false end
function modifier_special_bonus_imba_kunkka_4:IsHidden() return true end
function modifier_special_bonus_imba_kunkka_4:IsPurgable() return false end
function modifier_special_bonus_imba_kunkka_4:RemoveOnDeath() return false end
function modifier_special_bonus_imba_kunkka_6:IsHidden() return true end
function modifier_special_bonus_imba_kunkka_6:IsPurgable() return false end
function modifier_special_bonus_imba_kunkka_6:RemoveOnDeath() return false end
function modifier_special_bonus_imba_kunkka_8:IsHidden() return true end
function modifier_special_bonus_imba_kunkka_8:IsPurgable() return false end
function modifier_special_bonus_imba_kunkka_8:RemoveOnDeath() return false end
function modifier_special_bonus_imba_kunkka_9:IsHidden() return true end
function modifier_special_bonus_imba_kunkka_9:IsPurgable() return false end
function modifier_special_bonus_imba_kunkka_9:RemoveOnDeath() return false end
|
local ObjDecode = {}
function ObjDecode:GetSource(sourceObj)
if type(sourceObj) == 'string' then
return sourceObj
elseif sourceObj:IsA('ModuleScript') then
return sourceObj.Source
elseif sourceObj:IsA('ValueBase') then
return sourceObj.Value
end
end
function ObjDecode:DecodeLine(line)
local split = string.split(line, ' ')
local _type = split[1]
table.remove(split,1)
local _data = split
if _type == 'f' then
_data = {}
for i,value in ipairs(split) do
if value ~= '' and value ~= '\n' then
table.insert(_data, string.split(value,'/'))
end
end
end
return _type, _data
end
function ObjDecode:Decode(sourceObj)
local data = {}
local source = ObjDecode:GetSource(sourceObj)
assert(source, 'Failed To Load Source!',sourceObj)
local lines = string.split(source,'\n')
for i,line in ipairs(lines) do
if type(line) == 'string' then
local lineType, lineValues = ObjDecode:DecodeLine(line)
data[lineType] = data[lineType] or {}
table.insert(data[lineType],{
string = line,
line = i,
values = lineValues or {}
})
end
end
print('Lines:',#lines)
-- for _type,values in pairs(data) do
-- print('Type:',_type)
-- if _type == 'v' or _type == 'f' then
-- for i,v in ipairs(values) do
-- print(i,v.line,v.string,unpack(v.values))
-- end
-- end
-- end
return data
end
return ObjDecode
|
-- ALF buffer module
--
-- This module contains a buffered array of ALF objects. When the buffer is full (max number of entries
-- or max payload size accepted by the collector), it is eventually converted to a JSON payload and moved a
-- queue of payloads to be sent to the server. "Eventually", because to prevent the sending queue from growing
-- too much and crashing the Lua VM, its size is limited (in bytes). If the sending queue is currently bloated
-- and reached its size limit, then the buffer is NOT added to it, and simply discarded. ALFs will be lost.
--
-- So to resume:
-- One buffer of ALFs (gets flushed once it reaches the max size)
-- One queue of pending, ready-to-be-sent batches which are JSON payloads (which also has a max size, in bytes)
--
-- 1. The sending queue keeps sending batches one by one, and if batches are acknowledged by the collector,
-- the batch is considered saved and is discarded.
-- 2. If the batch is invalid (bad ALF formatting) according to the collector, it is discarded and won't be retried.
-- 3. If the connection to the collector could not be made, the batch will not be discarded so it can be retried.
-- 4. The sending queue keeps sending batches as long as it has some pending for sending. If the connection failed (3.),
-- the sending queue will use a retry policy timer which is incremented everytime the collector did not answer.
-- 5. We run a 'delayed timer' in case no call is received for a while to still flush the buffer and have 'real-time' analytics.
--
-- @see alf_serializer.lua
-- @see handler.lua
local json = require "cjson"
local http = require "resty_http"
local table_getn = table.getn
local ngx_now = ngx.now
local ngx_log = ngx.log
local ngx_log_ERR = ngx.ERR
local ngx_timer_at = ngx.timer.at
local table_insert = table.insert
local table_concat = table.concat
local table_remove = table.remove
local string_sub = string.sub
local string_len = string.len
local string_rep = string.rep
local string_format = string.format
local math_pow = math.pow
local math_min = math.min
local setmetatable = setmetatable
local MB = 1024 * 1024
local MAX_COLLECTOR_PAYLOAD_SIZE = 500 * MB
local EMPTY_ARRAY_PLACEHOLDER = "__empty_array_placeholder__"
-- Define an exponential retry policy for all workers.
-- The policy will give a delay that grows everytime
-- Galileo fails to respond. As soon as Galileo responds,
-- the delay is reset to its base.
local dict = ngx.shared.cache
local RETRY_INDEX_KEY = "mashape_analytics_retry_index"
local RETRY_BASE_DELAY = 1 -- seconds
local RETRY_MAX_DELAY = 60 -- seconds
local buffer_mt = {}
buffer_mt.__index = buffer_mt
buffer_mt.MAX_COLLECTOR_PAYLOAD_SIZE = MAX_COLLECTOR_PAYLOAD_SIZE
-- A handler for delayed batch sending. When no call has been made for X seconds
-- (X being conf.delay), we send the batch to keep analytics as close to real-time
-- as possible.
local delayed_send_handler
delayed_send_handler = function(premature, buffer)
if premature then return end
if ngx_now() - buffer.latest_call < buffer.auto_flush_delay then
-- If the latest call was received during the wait delay, abort the delayed send and
-- report it for X more seconds.
local ok, err = ngx_timer_at(buffer.auto_flush_delay, delayed_send_handler, buffer)
if not ok then
buffer.lock_delayed = false -- re-enable creation of a delayed-timer for this buffer
ngx_log(ngx_log_ERR, "[mashape-analytics] failed to create delayed batch sending timer: ", err)
end
else
-- Buffer is not full but it's been too long without an API call, let's flush it
-- and send the data to analytics.
buffer:flush()
buffer.lock_delayed = false
buffer.send_batch(nil, buffer)
end
end
-- Instanciate a new buffer with configuration and properties
function buffer_mt.new(conf)
local buffer = {
max_entries = conf.batch_size,
auto_flush_delay = conf.delay,
host = conf.host,
port = conf.port,
path = conf.path,
max_sending_queue_size = conf.max_sending_queue_size * MB,
entries = {}, -- current buffer as an array of strings (serialized ALFs)
entries_size = 0, -- current entries size in bytes (total)
sending_queue = {}, -- array of constructed payloads (batches of ALFs) to be sent
sending_queue_size = 0, -- current sending queue size in bytes
lock_sending = false, -- lock if currently sending its data
lock_delayed = false, -- lock if a delayed timer is already set for this buffer
latest_call = nil -- date at which a request was last made to this API (for the delayed timer to know if it needs to trigger)
}
return setmetatable(buffer, buffer_mt)
end
-- Add an ALF (already serialized) to the buffer
-- If the buffer is full (max entries or size in bytes), convert the buffer
-- to a JSON payload and place it in an array to be sent, then trigger a sending.
-- If the buffer is not full, start a delayed timer in case no call is received
-- for a while.
function buffer_mt:add_alf(alf)
-- Keep track of the latest call for the delayed timer
self.latest_call = ngx_now()
local str = json.encode(alf)
str = str:gsub("\""..EMPTY_ARRAY_PLACEHOLDER.."\"", ""):gsub("\\/", "/")
-- Check what would be the size of the buffer
local next_n_entries = table_getn(self.entries) + 1
local alf_size = string_len(str)
-- If the alf_size exceeds the payload limit by itself, we have a big problem
if alf_size > buffer_mt.MAX_COLLECTOR_PAYLOAD_SIZE then
ngx_log(ngx_log_ERR, string_format("[mashape-analytics] ALF size exceeds the maximum size (%sMB) accepted by the collector. Dropping it.", buffer_mt.MAX_COLLECTOR_PAYLOAD_SIZE / MB))
return
end
-- If size or entries exceed the max limits
local full = next_n_entries > self.max_entries or (self:get_size() + alf_size) > buffer_mt.MAX_COLLECTOR_PAYLOAD_SIZE
if full then
self:flush()
-- Batch size reached, let's send the data
local ok, err = ngx_timer_at(0, self.send_batch, self)
if not ok then
ngx_log(ngx_log_ERR, "[mashape-analytics] failed to create batch sending timer: ", err)
end
elseif not self.lock_delayed then
-- Batch size not yet reached.
-- Set a timer sending the data only in case nothing happens for awhile or if the batch_size is taking
-- too much time to reach the limit and trigger the flush.
local ok, err = ngx_timer_at(self.auto_flush_delay, delayed_send_handler, self)
if ok then
self.lock_delayed = true -- Make sure only one delayed timer is ever pending for a given buffer
else
ngx_log(ngx_log_ERR, "[mashape-analytics] failed to create delayed batch sending timer: ", err)
end
end
-- Insert in entries
table_insert(self.entries, str)
-- Update current buffer size
self.entries_size = self.entries_size + alf_size
end
-- Build a JSON payload of the current buffer.
function buffer_mt:payload_string()
return "["..table_concat(self.entries, ",").."]"
end
-- Get the size of the current buffer if it was to be converted to a JSON payload
function buffer_mt:get_size()
local commas = string_rep(",", table_getn(self.entries) - 1)
return string_len(commas.."[]") + self.entries_size
end
-- Flush the buffer
-- 1. Make sure the batch is not too big for the configured max_sending_queue_size
-- 2. Make sure the current sending queue doesn't exceed its size limit
-- 2b. Convert its content into a JSON payload
-- 2c. Add the payload to the queue of payloads to be sent
-- 3. Empty the buffer and reset the current buffer size
function buffer_mt:flush()
local batch_size = self:get_size()
if batch_size > self.max_sending_queue_size then
ngx_log(ngx.NOTICE, string_format("[mashape-analytics] batch was bigger (%s bytes) than the configured max_sending_queue_size (%s bytes). Dropping it (%s ALFs)", batch_size, self.max_sending_queue_size, table_getn(self.entries)))
elseif self.sending_queue_size + batch_size <= self.max_sending_queue_size then
self.sending_queue_size = self.sending_queue_size + batch_size
table_insert(self.sending_queue, {
payload = self:payload_string(),
n_entries = table_getn(self.entries),
size = batch_size
})
else
ngx_log(ngx.NOTICE, string_format("[mashape-analytics] buffer reached its maximum max_sending_queue_size. (%s) ALFs, (%s) bytes dropped.", table_getn(self.entries), batch_size))
end
self.entries = {}
self.entries_size = 0
end
-- Send the oldest payload (batch of ALFs) from the queue to the collector.
-- The payload will be removed if the collector acknowledged the batch.
-- If the queue still has payloads to be sent, keep on sending them.
-- If the connection to the collector fails, use the retry policy.
function buffer_mt.send_batch(premature, self)
if premature or self.lock_sending then return end
self.lock_sending = true -- simple lock
if table_getn(self.sending_queue) < 1 then
return
end
-- Let's send the oldest batch in our queue
local batch_to_send = table_remove(self.sending_queue, 1)
local retry
local client = http:new()
client:set_timeout(30000) -- 30 sec
local ok, err = client:connect(self.host, self.port)
if ok then
local res, err = client:request({path = self.path, body = batch_to_send.payload})
if not res then
retry = true
ngx_log(ngx_log_ERR, string_format("[mashape-analytics] failed to send batch (%s ALFs %s bytes): %s", batch_to_send.n_entries, batch_to_send.size, err))
else
res.body = string_sub(res.body, 1, -2) -- remove trailing line jump for logs
if res.status == 200 then
ngx_log(ngx.DEBUG, string_format("[mashape-analytics] successfully saved the batch. (%s)", res.body))
elseif res.status == 207 then
ngx_log(ngx_log_ERR, string_format("[mashape-analytics] collector could not save all ALFs from the batch. (%s)", res.body))
elseif res.status == 400 then
ngx_log(ngx_log_ERR, string_format("[mashape-analytics] collector refused the batch (%s ALFs %s bytes). Dropping batch. Status: (%s) Error: (%s)", batch_to_send.n_entries, batch_to_send.size, res.status, res.body))
else
retry = true
ngx_log(ngx_log_ERR, string_format("[mashape-analytics] collector could not save the batch (%s ALFs %s bytes). Status: (%s) Error: (%s)", batch_to_send.n_entries, batch_to_send.size, res.status, res.body))
end
end
-- close connection, or put it into the connection pool
if not res or res.headers["connection"] == "close" then
ok, err = client:close()
if not ok then
ngx_log(ngx_log_ERR, "[mashape-analytics] failed to close socket: ", err)
end
else
client:set_keepalive()
end
else
retry = true
ngx_log(ngx_log_ERR, "[mashape-analytics] failed to connect to the collector: ", err)
end
local next_batch_delay = 0 -- default delay for the next batch sending
if retry then
-- could not reach the collector, need to retry
table_insert(self.sending_queue, 1, batch_to_send)
local ok, err = dict:add(RETRY_INDEX_KEY, 0)
if not ok and err ~= "exists" then
ngx_log(ngx_log_ERR, "[mashape-analytics] cannot prepare retry policy: ", err)
end
local index, err = dict:incr(RETRY_INDEX_KEY, 1)
if err then
ngx_log(ngx_log_ERR, "[mashape-analytics] cannot increment retry policy index: ", err)
elseif index then
next_batch_delay = math_min(math_pow(index, 2) * RETRY_BASE_DELAY, RETRY_MAX_DELAY)
end
ngx_log(ngx.NOTICE, string_format("[mashape-analytics] batch was queued for retry. Next retry in: %s seconds", next_batch_delay))
else
-- batch acknowledged by the collector
self.sending_queue_size = self.sending_queue_size - batch_to_send.size
-- reset retry policy
local ok, err = dict:set(RETRY_INDEX_KEY, 0)
if not ok then
ngx_log(ngx_log_ERR, "[mashape-analytics] cannot reset retry policy index: ", err)
end
end
self.lock_sending = false
-- Keep sendind data if the queue is not yet emptied
if table_getn(self.sending_queue) > 0 then
local ok, err = ngx_timer_at(next_batch_delay, self.send_batch, self)
if not ok then
ngx_log(ngx_log_ERR, "[mashape-analytics] failed to create batch retry timer: ", err)
end
end
end
return buffer_mt
|
#!/usr/bin/env tjost
--[[
* Copyright (c) 2015 Hanspeter Portner (dev@open-music-kontrollers.ch)
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the Artistic License 2.0 as published by
* The Perl Foundation.
*
* This source 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
* Artistic License 2.0 for more details.
*
* You should have received a copy of the Artistic License 2.0
* along the source as a COPYING file. If not, obtain it from
* http://www.perlfoundation.org/artistic_license_2_0.
--]]
message = tjost.plugin({name='dump'})
methods = {
-- responders
['/jack/client/registration'] = function(time, client, flag)
--TODO
end,
['/jack/port/registration'] = function(time, port, flag)
--TODO
end,
['/jack/port/connect'] = function(time, port_a, port_b, flag)
--TODO
end,
['/jack/port/rename'] = function(time, port_old, port_new)
--TODO
end,
['/jack/graph/order'] = function(time)
--TODO
end,
-- callbacks
['/jack/ports'] = function(time, ...)
--TODO
end,
['/jack/connections'] = function(time, port, ...)
--TODO
end
}
uplink = tjost.plugin({name='uplink'}, function(time, path, fmt, ...)
message(time, path, fmt, ...)
local cb = methods[path]
if cb then
cb(time, ...)
end
end)
send = tjost.plugin({name='send'}, uplink)
|
return function()
local FDK = require(script.Parent.Parent.src.FDK)
FDK:wrapEnvironment(getfenv())
local EventClass = import("org.robloxevents.Event")
local event = nil
describe("Event", function()
it("should be ok", function()
expect(EventClass).to.be.ok()
end)
it("should create a Event correctly", function()
expect(function()
event = EventClass(true)
end).never.to.throw()
end)
it("should connect with no errors", function()
expect(function()
event:connect(function()
end)
end).never.to.throw()
end)
it("should wait with errors", function()
expect(function()
event:wait()
end).to.throw()
end)
it("should fire with no errors", function()
expect(function()
event:fire()
end).never.to.throw()
end)
describe("Connection", function()
local connection
it("should create a connection properly", function()
expect(function()
connection = event:connect(function()
end)
end).never.to.throw()
expect(connection).to.be.ok()
end)
it("should disconnect properly", function()
expect(function()
connection:disconnect()
end).never.to.throw()
end)
end)
it("should disconnect all correctly", function()
expect(function()
event:disconnectAll()
end).never.to.throw()
end)
it("should destroy correctly", function()
expect(function()
event:destroy()
end).never.to.throw()
end)
end)
end
|
-- This file split up into the mods covered
-- Industrial Mod by RAPHAEL
minetest.register_craft({
output = "fakeblocks:industrial_white_brick",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "industrial:white_brick", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:industrial_white_brick", {
description = "Fake White Brick",
tiles = {"industrial_white_brick.png"},
inventory_image = minetest.inventorycube("industrial_white_brick.png"),
is_ground_content = true,
walkable = false,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:industrial_asphalt",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "industrial:asphalt", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:industrial_asphalt", {
description = "Fake Industrial asphalt",
tiles = {"industrial_asphalt.png"},
inventory_image = minetest.inventorycube("industrial_asphalt.png"),
walkable = false,
is_ground_content = true,
groups = {cracky=3, stone=1},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:industrial_steelgray",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "industrial:steel_gray", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:industrial_steelgray", {
description = "Fake steel gray",
tiles = {"industrial_steelgray.png"},
inventory_image = minetest.inventorycube("industrial_steelgray.png"),
walkable = false,
is_ground_content = true,
groups = {snappy=1,bendy=2,cracky=1,melty=2,level=2},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:industrial_cement",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "industrial:cement", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:industrial_cement", {
description = "Fake industrial cement",
tiles = {"industrial_cement.png"},
inventory_image = minetest.inventorycube("industrial_cement.png"),
walkable = false,
is_ground_content = true,
groups = {cracky=3, stone=1},
sounds = default.node_sound_stone_defaults(),
})
-- end Industrial Mod
-- Moreblocks Mod by ??
minetest.register_craft({
output = "fakeblocks:moreblocks_stonebrick",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:stonebrick", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_stonebrick", {
description = "Fake Stone Bricks",
tiles = {"moreblocks_stonebrick.png"},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_circlestonebrick",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:circlestonebrick", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_circlestonebrick", {
description = "Fake Circle Stone Bricks",
tiles = {"moreblocks_circlestonebrick.png"},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_stonesquare",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:stonesquare", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_stonesquare", {
description = "Fake Stonesquare",
tiles = {"moreblocks_stonesquare.png"},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_splitstonesquare",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:splitstonesquare", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_splitstonesquare", {
description = "Fake Split Stonesquare",
tiles = {"moreblocks_splitstonesquare_top.png", "moreblocks_splitstonesquare.png"},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_emptybookshelf",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:emptybookshelf", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_emptybookshelf", {
description = "Fake Empty bookshelf",
tiles = {"default_wood.png", "default_wood.png", "moreblocks_emptybookshelf.png"},
walkable = false,
is_ground_content = true,
groups = {snappy=2,choppy=3,oddly_breakable_by_hand=2,flammable=3},
sounds = default.node_sound_wood_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_ironstonebrick",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:ironstonebrick", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_ironstonebrick", {
description = "Fake Iron Stone Bricks",
tiles = {"moreblocks_ironstonebrick.png"},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_plankstone",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:plankstone", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_plankstone", {
description = "Fake Plankstone",
tiles = {
"moreblocks_plankstone.png",
"moreblocks_plankstone.png",
"moreblocks_plankstone.png",
"moreblocks_plankstone.png",
"moreblocks_plankstone_2.png",
"moreblocks_plankstone_2.png",
},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_coalchecker",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:coalchecker", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_coalchecker", {
description = "Fake Coal Checker",
tiles = {
"moreblocks_coalchecker.png",
"moreblocks_coalchecker.png",
"moreblocks_coalchecker.png",
"moreblocks_coalchecker.png",
"moreblocks_coalchecker_2.png",
"moreblocks_coalchecker_2.png",
},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_ironchecker",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:ironchecker", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_ironchecker", {
description = "Fake Iron Checker",
tiles = {
"moreblocks_ironchecker.png",
"moreblocks_ironchecker.png",
"moreblocks_ironchecker.png",
"moreblocks_ironchecker.png",
"moreblocks_ironchecker_2.png",
"moreblocks_ironchecker_2.png",
},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_ironglass",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:ironglass", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
}
})
minetest.register_node("fakeblocks:moreblocks_ironglass", {
description = "Fake Iron Glass",
drawtype = "glasslike",
tiles = {"moreblocks_ironglass.png"},
inventory_image = minetest.inventorycube("moreblocks_ironglass.png"),
paramtype = "light",
sunlight_propagates = true,
walkable = false,
is_ground_content = true,
groups = {snappy=2,cracky=3,oddly_breakable_by_hand=3},
sounds = default.node_sound_glass_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_coalstone",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:coalstone", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:moreblocks_coalstone", {
description = "Fake Coal Stone",
tiles = {"moreblocks_coalstone.png"},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_ironstone",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:ironstone", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:moreblocks_ironstone", {
description = "Fake Iron Stone",
tiles = {"moreblocks_ironstone.png"},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_cactusbrick",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:cactusbrick", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:moreblocks_cactusbrick", {
description = "Fake cactus brick",
tiles = {"moreblocks_cactusbrick.png"},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:moreblocks_cactuschecker",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "moreblocks:cactuschecker", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:moreblocks_cactuschecker", {
description = "Fake cactus Checker",
tiles = {
"moreblocks_cactuschecker.png",
"moreblocks_cactuschecker.png",
"moreblocks_cactuschecker.png",
"moreblocks_cactuschecker.png",
"moreblocks_cactuschecker_2.png",
"moreblocks_cactuschecker_2.png",
},
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
-- End moreblocks Mod
-- Start Various Mod by RAPHAEL
minetest.register_craft({
output = "fakeblocks:various_adobe",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "various:adobe", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:various_adobe", {
description = "Fake Adobe Block",
tiles = {"various_adobe.png"},
inventory_image = minetest.inventorycube("various_adobe.png"),
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:various_thatch",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "various:thatch", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:various_thatch", {
description = "Fake Thatch Block",
tiles = {"various_thatch.png"},
inventory_image = minetest.inventorycube("various_thatch.png"),
walkable = false,
is_ground_content = true,
groups = {snappy=3,flammable=2},
sounds = default.node_sound_leaves_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:various_woodblock",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "various:woodblock", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:various_woodblock", {
description = "Fake Wood Block",
tiles = {"various_woodblock.png"},
inventory_image = minetest.inventorycube("various_woodblock.png"),
walkable = false,
is_ground_content = true,
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=3,wood=1},
sounds = default.node_sound_wood_defaults(),
})
----
minetest.register_craft({
output = "fakeblocks:various_lawngrass",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "various:lawngrass", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:various_lawngrass", {
description = "Fake Lawn Grass",
tiles = {"various_lawngrass.png", "default_dirt.png", "default_dirt.png^various_lawngrass_side.png"},
inventory_image = minetest.inventorycube("various_lawngrass.png"),
walkable = false,
is_ground_content = true,
groups = {crumbly=3},
sounds = default.node_sound_dirt_defaults({
footstep = {name="default_grass_footstep", gain=0.4},
}),
})
-- End Various Mod
-- Start Obsidian Mod
minetest.register_craft({
output = "fakeblocks:obsidian_obsidian_block",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "obsidian:obsidian_block", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:obsidian_obsidian_block", {
description = "Fake Obsidian block",
tiles = {"obsidian_block.png"},
is_ground_content = true,
groups = {cracky=1},
drop = {
max_items = 1,
items = {
{
items = {'obsidian:obsidian_shard'},
rarity = 1
},
}
},
on_dig = minetest.node_dig,
})
-- End Obsidian Mod
-- Start Default Mod
minetest.register_craft({
output = "fakeblocks:default_sand",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_sand", {
description = "Fake Sand Block",
tiles = {"default_sand.png"},
inventory_image = minetest.inventorycube("default_sand.png"),
walkable = false,
is_ground_content = true,
groups = {crumbly=3, falling_node=1, sand=1},
sounds = default.node_sound_sand_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_dirt",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:dirt", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_dirt", {
description = "Fake Dirt Block",
tiles = {"default_dirt.png"},
inventory_image = minetest.inventorycube("default_dirt.png"),
walkable = false,
is_ground_content = true,
groups = {crumbly=3},
sounds = default.node_sound_dirt_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_desert_sand",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:desert_sand", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_desert_sand", {
description = "Fake Deset Sand Block",
tiles = {"default_desert_sand.png"},
inventory_image = minetest.inventorycube("default_desert_sand.png"),
walkable = false,
is_ground_content = true,
groups = {sand=1, crumbly=3, falling_node=1, sand=1},
sounds = default.node_sound_sand_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_sandstone",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:sandstone", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_sandstone", {
description = "Fake Sandstone Block",
tiles = {"default_sandstone.png"},
inventory_image = minetest.inventorycube("default_sandstone.png"),
walkable = false,
is_ground_content = true,
groups = {crumbly=2,cracky=2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_brick",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:brick", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_brick", {
description = "Fake Brick Block",
tiles = {"default_brick.png"},
inventory_image = minetest.inventorycube("default_brick.png"),
walkable = false,
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_tree",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:tree", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_tree", {
description = "Fake Tree Block",
tiles = {"default_tree.png"},
inventory_image = minetest.inventorycube("default_tree.png"),
walkable = false,
is_ground_content = true,
groups = {tree=1,snappy=1,choppy=2,oddly_breakable_by_hand=1,flammable=2},
sounds = default.node_sound_wood_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_bookshelf",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:bookshelf", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_bookshelf", {
description = "Fake Bookshelf",
tiles = {"default_wood.png", "default_wood.png", "default_bookshelf.png"},
walkable = false,
is_ground_content = true,
groups = {snappy=2,choppy=3,oddly_breakable_by_hand=2,flammable=3},
sounds = default.node_sound_wood_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_stone",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:stone", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_stone", {
description = "Fake Stone Block",
tiles = {"default_stone.png"},
inventory_image = minetest.inventorycube("default_stone.png"),
walkable = false,
is_ground_content = true,
legacy_mineral = true,
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_desert_stone",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:desert_stone", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_desert_stone", {
description = "Fake Desert Stone Block",
tiles = {"default_desert_stone.png"},
inventory_image = minetest.inventorycube("default_desert_stone.png"),
walkable = false,
is_ground_content = true,
legacy_mineral = true,
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_wood",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:wood", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_wood", {
description = "Fake Wood Block",
tiles = {"default_wood.png"},
inventory_image = minetest.inventorycube("default_wood.png"),
walkable = false,
is_ground_content = true,
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=3,wood=1},
sounds = default.node_sound_wood_defaults(),
})
minetest.register_craft({
output = "fakeblocks:default_cobble",
recipe = {
{"default:sand", "default:sand", "default:sand"},
{"default:sand", "default:cobble", "default:sand"},
{"default:sand", "default:sand", "default:sand"},
},
})
minetest.register_node("fakeblocks:default_cobble", {
description = "Fake Cobble Block",
tiles = {"default_cobble.png"},
inventory_image = minetest.inventorycube("default_cobble.png"),
walkable = false,
is_ground_content = true,
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
-- End Default Mod
|
function MainApp(root)
dofile(root .. "/objects/CommonFunctions.lua")
dofile(root .. "/objects/MiningT.lua")
dofile(root .. "/objects/Communicator.lua")
dofile(root .. "/programs/Configuration.lua")
dofile(root .. "/programs/Maintenance.lua")
dofile(root .. "/programs/GoToPosition.lua")
dofile(root .. "/programs/Stairs.lua")
dofile(root .. "/programs/Tunnel.lua")
dofile(root .. "/programs/Quarry.lua")
dofile(root .. "/programs/DiamondQuarry.lua")
dofile(root .. "/GUI/GUIMessages.lua")
dofile(root .. "/GUI/GUIMain.lua")
self = {}
local miningT = MiningT(root)
local objects = (miningT.getData()).getObjects()
local execution = objects.execution
local commonF = miningT.getCommonF()
local guiMessages = GUIMessages()
local guiMain = GUIMain(commonF, guiMessages)
local continue, showMainMenu, showApps = true, true, true
local turtleProcotol = nil
local server = nil
local mainCase =
commonF.switch {
[1] = function(x)
Configuration(miningT)
end,
[2] = function(x)
self.apps(guiMain)
end,
[3] = function(x)
continue = false
end,
default = function(x)
continue = false
end
}
local appsCase =
commonF.switch {
[1] = function(x)
local stairs = Stairs(miningT, guiMessages)
stairs.start()
end,
[2] = function(x)
local tunnel = Tunnel(miningT, guiMessages)
tunnel.start()
end,
[3] = function(x)
local maintenance = Maintenance(miningT, guiMessages)
continue, showMainMenu = maintenance.start()
end,
[4] = function(x)
local gtp = GoToPosition(miningT, guiMessages)
x, y, z = guiMain.goToXYZ()
if (x ~= nil and y > 4 and z ~= nil) then
miningT.down()
gtp.goTo(x, y, z)
end
end,
[5] = function(x)
local quarry = Quarry(miningT, guiMessages)
quarry.start()
end,
[6] = function(x)
local diamondQuarry = DiamondQuarry(miningT, guiMessages)
diamondQuarry.start()
end,
[7] = function(x)
showApps = false
end,
default = function(x)
print("Invalid Option")
end
}
local function continueExecutionIf()
if execution.getExecuting() ~= "" then
if execution.getExecuting() == "Stairs" then
appsCase:case(1)
end
if execution.getExecuting() == "Tunnel" then
appsCase:case(2)
end
if execution.getExecuting() == "Maintenance" then
appsCase:case(3)
end
if execution.getExecuting() == "Quarry" then
appsCase:case(5)
end
if execution.getExecuting() == "DiamondQuarry" then
appsCase:case(6)
end
end
end
local function continueExecution()
while continue do
turtle.select(1)
continueExecutionIf()
if showMainMenu then
mainCase:case(tonumber(guiMain.menu()))
end
end
end
local function stabilishFirstConnection(communicator)
for i = 1, 5 do
local protocolData = communicator.protocolGenerator()
if (protocolData[3]) then
turtleProcotol = protocolData[1]
server = protocolData[2]
return true
end
end
return false
end
local function executeSlaveTask(task, master)
if task.execution == "GoToPosition" then
if next(task.params) ~= nil then
local gtp = GoToPosition(miningT, guiMessages)
local x, y, z = task.params[1], task.params[2], task.params[3]
if (tonumber(x) ~= nil and tonumber(y) ~= nil and tonumber(z) ~= nil) then
if (y > 4) then
miningT.down()
gtp.goTo(x, y, z)
end
print("Finish Task")
Communicator().finishTask(objects.task.getData(), true, server, turtleProcotol)
objects.task.reset()
end
end
--communicator.finishTask(task,false,server,turtleProcotol)
end
if task.execution == "Stairs" then
local stairs = Stairs(miningT, guiMessages, master)
stairs.start()
end
if task.execution == "Tunnel" then
if next(task.params) ~= nil then
local tunnel = Tunnel(miningT, guiMessages, master)
tunnel.start()
end
--communicator.finishTask(task,false,server,turtleProcotol)
end
if task.execution == "Quarry" then
if next(task.params) ~= nil then
local quarry = Quarry(miningT, guiMessages, master)
quarry.start()
end
--communicator.finishTask(task,false,server,turtleProcotol)
end
if task.execution == "DiamondQuarry" then
if next(task.params) ~= nil then
local diamondQuarry = DiamondQuarry(miningT, guiMessages, master)
diamondQuarry.start()
end
--communicator.finishTask(task,false,server,turtleProcotol)
end
end
local function slaveBehavior(communicator)
local task = communicator.waitForTask(turtleProcotol)
guiMessages.showInfoMsg(textutils.serialize(task))
local times = 1
if (task.execution ~= nil and task.execution ~= "") then
local master = {["task"] = task, ["server"] = server, ["protocol"] = turtleProcotol}
objects.task.set(master.task)
miningT.saveAll()
executeSlaveTask(task, master)
else
guiMessages.showErrorMsg("Turtle couldn't find a task to execute")
print("Waiting" .. (3 - times) .. " more times")
if times > 3 then
guiMessages.showInfoMsg("Disabling Ender and Slave Behavior")
objects.turtleInfo.deactivateSlaveBehavior()
objects.storages.disableEnder()
guiMessages.showInfoMsg("Executing Maintenance")
appsCase:case(3)
else
times = times + 1
end
end
end
function self.apps(guiMain)
showApps = true
while continue and showApps do
if showMainMenu then
appsCase:case(tonumber(guiMain.menuApps()))
end
end
end
function self.main()
local r = 0
if (objects.turtleInfo.isSlave()) then
guiMessages.showInfoMsg("Type something to access the turtle configuration")
r = commonF.limitToWrite(1)
if r ~= 0 then
mainCase:case(1)
else
local communicator = Communicator(commonF)
if execution.getExecuting() == "" then
if stabilishFirstConnection(communicator) then
if objects.task.getExecution() ~= nil and objects.task.getExecution() ~= "" then
if (objects.task.isComplete() == true) then
print("Finish Task")
communicator.finishTask(objects.task.getData(), true, server, turtleProcotol)
objects.task.reset()
else
executeSlaveTask(
objects.task.getData(),
{["task"] = objects.task.getData(), ["server"] = server, ["protocol"] = turtleProcotol}
)
end
end
guiMessages.showSuccessMsg("Success on stablishing connection with server")
guiMessages.showInfoMsg("Using protocol: " .. turtleProcotol)
guiMessages.showInfoMsg("Waiting for tasks...")
while (objects.turtleInfo.isSlave()) do
if execution.getExecuting() == "" then
slaveBehavior(communicator)
else
continueExecution()
end
end
else
guiMessages.showErrorMsg("Couldn't find a server, going back to home")
local x, y, z = objects.home.getX(), objects.home.getY(), objects.home.getZ()
local gtp = GoToPosition(miningT, guiMessages)
gtp.backTo(x, y, z)
objects.task.reset()
Data.finalizeExecution()
Data.previousPosIsHome()
guiMessages.showInfoMsg("Executing Maintenance")
appsCase:case(3)
end
else
continueExecution()
end
end
else
guiMessages.showInfoMsg("Type something to access the main menu if there is some execution running")
r = commonF.limitToWrite(2.5)
if r == 0 then
continueExecution()
else
mainCase:case(tonumber(guiMain.menu()))
end
end
end
return self
end
|
local L = BigWigs:NewBossLocale("Dazar, The First King", "zhTW")
if not L then return end
if L then
L.spears_active = "穿刺之矛開始"
end
L = BigWigs:NewBossLocale("King's Rest Trash", "zhTW")
if L then
L.guardian = "活化的守護者"
L.minion = "祖爾之僕"
L.champion = "影裔勇士"
L.shadow_witchdoctor = "影裔巫醫"
L.warrior = "影裔戰士"
L.timalji = "提瑪吉國王"
L.wasi = "瓦希皇后"
L.rahuai = "拉胡艾國王"
L.atu = "守衛隊長阿圖"
L.mbara = "瑪巴拉總管"
L.patla = "帕特拉皇后"
L.raptor = "骷髏狩獵迅猛龍"
L.aakul = "阿庫爾國王"
L.agent = "血誓密探"
L.purification_construct = "淨化的魔像"
L.fluid = "防腐液"
L.interment_construct = "埋葬的魔像"
L.hex_priest = "鬼靈妖術祭司"
L.berserker = "鬼靈狂戰士"
L.spectral_witchdoctor = "鬼靈巫醫"
L.beastmaster = "鬼靈馴獸者"
L.brute = "鬼靈蠻卒"
L.zul = "祖爾之影"
L.casting_on_you = "對你施放%s"
L.casting_on_other = "施放%s:%s"
end
|
return {
Button = require(script.Button),
Toolbar = require(script.Toolbar),
Widget = require(script.Widget),
Contexts = require(script.Contexts),
}
|
-- Do not touch this file !
mrobbery.debug = false -- Leave this value if you don't know what you are doing :)
function mrobbery.f.ReloadConfig()
if file.Exists("museum_robbery/config.txt", "DATA") then
mrobberycfg = {}
mrobberycfg = util.JSONToTable(file.Read("museum_robbery/config.txt", "DATA"))
if player.GetCount() >= 1 then
mrobbery.f.BroadcastCFG()
end
else
file.CreateDir("museum_robbery") -- first initialization here
mrobberycfg = {}
mrobberycfg.language = "FR"
mrobberycfg.timetosteal = 6
mrobberycfg.pricepp = 2000
mrobberycfg.chatcmd = "!mrconfig"
mrobberycfg.maletteoply = true
mrobberycfg.timebet = 20
mrobberycfg.offertime = 15
mrobberycfg.percent = 10
mrobberycfg.maxdisttosteal = 100
mrobberycfg.keytodrop = KEY_G
mrobberycfg.maxcarrypaintings = 4
mrobberycfg.hacktime = 15
mrobberycfg.offeraminperpt = 150
mrobberycfg.timeoffer = 150
mrobberycfg.offermaxperpt = 450
mrobberycfg.reseller_skin = "models/Humans/Group01/male_02.mdl"
mrobberycfg.reseller_nameover = true
mrobberycfg.reseller_name = "Reseller"
mrobberycfg.hackedtime = 60
mrobberycfg.wantedde = true
mrobberycfg.wantedha = true
mrobberycfg.statsenabled = true
mrobberycfg.wantedst = true
mrobberycfg.uselogging = true
mrobberycfg.minmuseumanag = 1
mrobberycfg.losepaintings = true
mrobberycfg.admingroups = {
["superadmin"] = true
}
mrobberycfg.teammu = "Museum Manager"
mrobberycfg.teamro = {
["Citizen"] = true
}
file.Write("museum_robbery/config.txt", util.TableToJSON(mrobberycfg))
print("\tThe config has been loaded for the first time !")
mrobbery.f.ReloadConfig()
end
end
if not mrobberycfg then
mrobbery.f.ReloadConfig()
end
-- Load the config once the file is loaded
function mrobbery.f.SetVarBool(int, bool)
net.Start("MRB:UpdateSpeVar")
net.WriteInt(int, 6)
net.WriteBool(bool)
net.Broadcast()
end
function mrobbery.f.logging(ply, message)
if GAS and GAS.Logging and mrobberycfg.uselogging then
hook.Call("MRB:Core", nil, ply, message)
end
end
function mrobbery.f.Secure(int)
if not isnumber(int) then return end
local lasers = mrobbery.entities.laser
local paintings = mrobbery.entities.paintings
if int == 1 then
if not mrobbery.pgsecured then
mrobbery.pgsecured = true
mrobbery.f.SetVarBool(int, true)
for _, v in pairs(paintings) do
if not IsValid(v) or v:Getstolen() or v:Getoffered() then continue end
v:SetSubMaterial(2, "museum_robbery/sycreations/security_frame/ts_shutter_closed")
end
else
mrobbery.pgsecured = false
mrobbery.f.SetVarBool(int, false)
for _, v in pairs(paintings) do
if not IsValid(v) or v:Getstolen() or v:Getoffered() then continue end
v:SetSubMaterial(2, "museum_robbery/sycreations/security_frame/ts_shutter_open")
end
end
elseif int == 2 then
if not mrobbery.lsenabled then
mrobbery.lsenabled = true
mrobbery.f.SetVarBool(int, true)
for _, v in pairs(lasers) do
if not IsValid(v) then continue end
v:Setlaserstate(true)
end
else
mrobbery.lsenabled = false
mrobbery.f.SetVarBool(int, false)
for _, v in pairs(lasers) do
if not IsValid(v) then continue end
v:Setlaserstate(false)
end
end
end
end
function mrobbery.f.BroadcastCache(ply)
net.Start("MRB:UpdateSpeVar")
net.WriteInt(3, 6)
net.WriteBool(false)
net.WriteTable(mrobbery.cache)
if ply and ply:IsValid() and ply:IsPlayer() then
net.Send(ply)
else
net.Broadcast()
end
end
function mrobbery.f.SmartCacheByPainting(ent)
if not isentity(ent) then
error("Entity passed in function mrobbery.f.SmartCacheByPainting() isn't an entity")
return
end
local checke = false
for _, v in pairs(mrobbery.entities.paintings) do
if v:GetImgurID() == ent:GetImgurID() and v ~= ent then
checke = true
break
end
end
-- We don't want to uncache an picture if she is used on another painting
if not checke then
mrobbery.cache[util.CRC(ent:Getimgururl())] = false -- Uncache
mrobbery.cachetodownload[ent:Getimgururl()] = false -- Uncache
mrobbery.f.BroadcastCache() -- Broadcast the new cache
end
end
function mrobbery.f.MatFromURL(url, ply, ent)
-- We don't want to cache the url if it is already cached
if mrobbery.cache[ent:Getimgurcrc()] ~= true then
mrobbery.cache[ent:Getimgurcrc()] = true
mrobbery.cachetodownload[url] = true
end
net.Start("MRB:DLMAT") -- Sending the instruction to download the material to the clients
net.WriteString(url)
net.WriteEntity(ent)
net.Broadcast()
ent:SetSubMaterial(1, "!" .. ent:Getimgurcrc()) -- We set the material serverside & clientside to prevent an issue already reported on github of garrysmod.
if ply then
mrobbery.f.logging(ply, mrobbery.language[mrobberycfg.language]["change_log_msg"]:format(url))
end
end
function mrobbery.f.FindEnt(ply, maxrange, class)
for _, v in pairs(ents.FindInSphere(ply:GetPos(), maxrange)) do
if v:GetClass() == class then return v end
end
return nil
end
function mrobbery.f.checkgoodent(p, entgood)
local ent = p:GetEyeTrace().Entity
if (ent:GetClass() ~= entgood) then
return mrobbery.f.FindEnt(p, 100.9, entgood)
else
return ent
end
end
function mrobbery.f.IsStringURL(url)
if not isstring(url) or url == "" then return false end
if string.len(url) < 7 then return false end
if not string.match(url:lower(), "(h?t?t?p?s?:?/?/?w?w?w?.?%w+.%w+/)") then return false end
if not string.find(url:lower(), ".png") and not string.find(url:lower(), ".jpg") and not string.find(url:lower(), ".gif") and not string.find(url:lower(), ".jpeg") then return false end
return true
end
function mrobbery.f.AddPaintingsByEntity(ply, ent)
if isentity(ent) and IsValid(ply) then
if not IsValid(ply) or not IsValid(ent) then return end
ply.paintings[#ply.paintings + 1] = true
ply:SetNWInt("mrb_paintings", ply:GetNWInt("mrb_paintings") + 1)
end
end
function mrobbery.f.AddPaintingsByTable(ply, table)
if istable(table) and IsValid(ply) then
for _, _ in pairs(table) do
ply.paintings[#ply.paintings + 1] = true
ply:SetNWInt("mrb_paintings", ply:GetNWInt("mrb_paintings") + 1)
end
end
end
function mrobbery.f.ClearPaintings(ply)
if not IsValid(ply) then return end
ply.paintings = {}
ply:SetNWInt("mrb_paintings", 0)
ply:SetNWBool("mrb_carrying", false)
end
function mrobbery.f.AddMoney(ply, amount)
if not IsValid(ply) or not isnumber(amount) then return end
ply:addMoney(amount)
end
function mrobbery.f.GetPaintings(ply)
if not IsValid(ply) then return {} end
return ply.paintings or {}
end
function mrobbery.f.plyIsAdmin(ply)
if not IsValid(ply) then return end
if mrobberycfg.admingroups[ply:GetUserGroup()] then return true end
return false
end
function mrobbery.f.plyIsRobber(ply)
if not IsValid(ply) then return end
if mrobberycfg.teamro[team.GetName(ply:Team())] then return true end
return false
end
function mrobbery.f.SellPaintings(ply, infos)
if IsValid(ply) then
mrobbery.f.AddMoney(ply, infos.price)
DarkRP.notify(ply, 2, 3, string.format(mrobbery.language[mrobberycfg.language]["paintings_sold"], tostring(DarkRP.formatMoney(table.price))))
ply.paintings[k] = nil
if ply:GetNWInt("mrb_paintings") >= 1 then
ply:SetNWInt("mrb_paintings", ply:GetNWInt("mrb_paintings") - 1)
end
if #mrobbery.f.GetPaintings(ply) == 0 then
ply:SetNWInt("mrb_paintings", 0)
ply:SetNWBool("mrb_carrying", false)
end
end
end
function mrobbery.f.BroadcastCFG(ply)
net.Start("MRB:UpdateSpeVar")
net.WriteInt(6, 6)
net.WriteBool(true)
net.WriteTable(mrobberycfg)
if not ply then
net.Broadcast()
elseif ply:IsPlayer() and ply:IsValid() then
net.Send(ply)
end
end
function mrobbery.f:Debug(value)
if not mrobbery.debug then return end
if isstring(value) or isentity(value) then
print(value)
elseif istable(value) then
PrintTable(value)
end
end
local paintingsclean = {}
local paintingschoosen = {}
function mrobbery.offers:Thinking(ply)
timer.Create("MRB:Offers:Think:" .. ply:SteamID(), mrobberycfg.offertime + mrobberycfg.timebet, 0, function()
if not IsValid(ply) or not ply:IsPlayer() then return end
if (team.GetName(ply:Team()) ~= mrobberycfg.teammu) then return end
mrobbery.f:Debug("debug1")
if #mrobbery.entities.paintings > 0 then
ply.curoffer = {} -- Initialize and/or reset the current offer of the player
paintingsclean = {} -- Reset the table (defined as local at line 5)
for _, v in pairs(mrobbery.entities.paintings) do
if IsValid(v) and v:GetSubMaterial(1) ~= "" and v:Getoffered() ~= true and v:Getimgururl() ~= "" and v:Getstolen() == false and not mrobbery.pgsecured then
paintingsclean[#paintingsclean + 1] = v
end
end
mrobbery.f:Debug("debug2")
-- If there is no paintings with pictures, no offers !
if paintingsclean then
mrobbery.f:Debug("debug3")
local randomnum = math.random(1, #paintingsclean)
local entrand = table.Random(mrobbery.offers.enterprises["Names"])
paintingschoosen = {} -- Reset the table (defined as local at line 6)
for i = 1, randomnum do
local pt = paintingsclean[math.random(1, #paintingsclean)] -- Generate a new random every iteration
local found = false
for _, v in pairs(paintingschoosen) do
mrobbery.f:Debug(v)
-- We don't want to add two times or more the same painting
if v == pt then
mrobbery.f:Debug(v, pt)
found = true
break
end
end
mrobbery.f:Debug(found)
if not found then
paintingschoosen[#paintingschoosen + 1] = pt
end
end
mrobbery.f:Debug(paintingschoosen)
-- We dont want to make an offer without paintings available
if #paintingschoosen > 0 then
mrobbery.f:Debug("debug4")
local ptsnum = #paintingschoosen
local currentoffer = {
entname = entrand, -- Enterprise name
pts = ptsnum, -- Amount of paintings
price = math.random(mrobberycfg.offeraminperpt * ptsnum, mrobberycfg.offermaxperpt * ptsnum), -- The amount what the enterprise will pay
starttime = CurTime(), -- Start time of the offer
paintings = paintingschoosen -- Table of the paintings who are concerned
}
ply.curoffer = currentoffer -- Define the offer on the player for later
net.Start("MRB:Offer")
net.WriteTable(currentoffer)
net.Send(ply)
mrobbery.f.logging(ply, mrobbery.language[mrobberycfg.language]["offer"]:format(entrand, DarkRP.formatMoney(prce)))
end
end
end
end)
end
|
--[[
Copyright (c) 2010-2013 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local functions = {}
local function _nothing_() end
local to_remove = {}
local function update(dt)
for handle in pairs(functions) do
-- handle: {
-- time = <number>,
-- after = <function>,
-- during = <function>,
-- limit = <number>,
-- count = <number>,
-- }
handle.time = handle.time + dt
handle.during(dt, math.max(handle.limit - handle.time, 0))
while handle.time >= handle.limit and handle.count > 0 do
if handle.after(handle.after) == false then
handle.count = 0
break
end
handle.time = handle.time - handle.limit
handle.count = handle.count - 1
end
if handle.count == 0 then
table.insert(to_remove, handle)
end
end
for i = 1, #to_remove do
functions[to_remove[i]] = nil
end
end
local function during(delay, during, after)
local handle = { time = 0, during = during, after = after or _nothing_, limit = delay, count = 1 }
functions[handle] = true
return handle
end
local function after(delay, func)
return during(delay, _nothing_, func)
end
local function every(delay, after, count)
local count = count or math.huge -- exploit below: math.huge - 1 = math.huge
local handle = { time = 0, during = _nothing_, after = after, limit = delay, count = count }
functions[handle] = true
return handle
end
local function active(handle)
return functions[handle]
end
local function cancel(handle)
functions[handle] = nil
end
local function clear()
functions = {}
end
local function script(f)
local co = coroutine.wrap(f)
co(function(t)
after(t, co)
coroutine.yield()
end)
end
return {
update = update,
after = after,
every = every,
active = active,
cancel = cancel,
script = script,
}
|
local PANEL = {}
AccessorFunc( PANEL, "m_bBackground", "PaintBackground", FORCE_BOOL )
AccessorFunc( PANEL, "m_bBackground", "DrawBackground", FORCE_BOOL ) -- deprecated
AccessorFunc( PANEL, "m_bIsMenuComponent", "IsMenu", FORCE_BOOL )
AccessorFunc( PANEL, "m_bDisableTabbing", "TabbingDisabled", FORCE_BOOL )
AccessorFunc( PANEL, "m_bDisabled", "Disabled" )
AccessorFunc( PANEL, "m_bgColor", "BackgroundColor" )
Derma_Hook( PANEL, "Paint", "Paint", "Panel" )
Derma_Hook( PANEL, "ApplySchemeSettings", "Scheme", "Panel" )
Derma_Hook( PANEL, "PerformLayout", "Layout", "Panel" )
function PANEL:Init()
self:SetPaintBackground( true )
-- This turns off the engine drawing
self:SetPaintBackgroundEnabled( false )
self:SetPaintBorderEnabled( false )
end
function PANEL:SetDisabled( bDisabled )
self.m_bDisabled = bDisabled
if ( bDisabled ) then
self:SetAlpha( 75 )
self:SetMouseInputEnabled( false )
else
self:SetAlpha( 255 )
self:SetMouseInputEnabled( true )
end
end
function PANEL:SetEnabled( bEnabled )
self:SetDisabled( !bEnabled )
end
function PANEL:IsEnabled()
return !self:GetDisabled()
end
function PANEL:OnMousePressed( mousecode )
if ( self:IsSelectionCanvas() && !dragndrop.IsDragging() ) then
self:StartBoxSelection()
return
end
if ( self:IsDraggable() ) then
self:MouseCapture( true )
self:DragMousePress( mousecode )
end
end
function PANEL:OnMouseReleased( mousecode )
if ( self:EndBoxSelection() ) then return end
self:MouseCapture( false )
if ( self:DragMouseRelease( mousecode ) ) then
return
end
end
function PANEL:SetHHeight(h)
self.HeaderHeight = h
end
function PANEL:SetHText(text)
self.HText = text
end
function PANEL:Paint(w, h)
draw.RoundedBox(0, 0, 0, w, h, cols.head_panel_outline)
draw.RoundedBox(0, 1, 1, w - 2, h - 2, cols.head_panel_bg)
self.HeaderHeight = self.HeaderHeight or 0
draw.RoundedBox(0, 0, 0, w, self.HeaderHeight, cols.head_panel_head_bg)
draw.RoundedBox(0, 1, self.HeaderHeight / 2, w - 2, self.HeaderHeight * 3 / 4, cols.head_panel_bg)
draw.SimpleText(self.HText, "adminme_section_btn", 10, self.HeaderHeight * 1 / 4, cols.head_panel_text, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
function PANEL:UpdateColours()
end
derma.DefineControl( "am.HeaderPanel", "", PANEL, "Panel" )
|
if not modules then modules = { } end modules ['typo-dha'] = {
version = 1.001,
comment = "companion to typo-dir.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
-- Some analysis by Idris:
--
-- 1. Assuming the reading- vs word-order distinction (bidi-char types) is governing;
-- 2. Assuming that 'ARAB' represents an actual arabic string in raw input order, not word-order;
-- 3. Assuming that 'BARA' represent the correct RL word order;
--
-- Then we have, with input: LATIN ARAB
--
-- \textdir TLT LATIN ARAB => LATIN BARA
-- \textdir TRT LATIN ARAB => LATIN BARA
-- \textdir TRT LRO LATIN ARAB => LATIN ARAB
-- \textdir TLT LRO LATIN ARAB => LATIN ARAB
-- \textdir TLT RLO LATIN ARAB => NITAL ARAB
-- \textdir TRT RLO LATIN ARAB => NITAL ARAB
-- elseif d == "es" then -- European Number Separator
-- elseif d == "et" then -- European Number Terminator
-- elseif d == "cs" then -- Common Number Separator
-- elseif d == "nsm" then -- Non-Spacing Mark
-- elseif d == "bn" then -- Boundary Neutral
-- elseif d == "b" then -- Paragraph Separator
-- elseif d == "s" then -- Segment Separator
-- elseif d == "ws" then -- Whitespace
-- elseif d == "on" then -- Other Neutrals
-- todo : use new dir functions
-- todo : make faster
-- todo : move dir info into nodes
-- todo : swappable tables and floats i.e. start-end overloads (probably loop in builders)
-- I removed the original tracing code and now use the colorful one. If I ever want to change
-- something I will just inject prints for tracing.
local nodes, node = nodes, node
local trace_directions = false trackers.register("typesetters.directions.default", function(v) trace_directions = v end)
local report_directions = logs.reporter("typesetting","text directions")
local nuts = nodes.nuts
local tonut = nuts.tonut
local tonode = nuts.tonode
local getnext = nuts.getnext
local getprev = nuts.getprev
local getchar = nuts.getchar
local getid = nuts.getid
local getsubtype = nuts.getsubtype
local getlist = nuts.getlist
local getfield = nuts.getfield
local getattr = nuts.getattr
local getprop = nuts.getprop
local isglyph = nuts.isglyph -- or ischar
local setfield = nuts.setfield
local setprop = nuts.setprop
local setchar = nuts.setchar
local insert_node_before = nuts.insert_before
local insert_node_after = nuts.insert_after
local remove_node = nuts.remove
local end_of_math = nuts.end_of_math
local nodepool = nuts.pool
local nodecodes = nodes.nodecodes
local skipcodes = nodes.skipcodes
local glyph_code = nodecodes.glyph
local math_code = nodecodes.math
local kern_code = nodecodes.kern
local glue_code = nodecodes.glue
local dir_code = nodecodes.dir
local localpar_code = nodecodes.localpar
local parfillskip_code = skipcodes.parfillskip
local new_textdir = nodepool.textdir
local hasbit = number.hasbit
local formatters = string.formatters
local insert = table.insert
local fonthashes = fonts.hashes
local fontchar = fonthashes.characters
local chardirections = characters.directions
local charmirrors = characters.mirrors
local charclasses = characters.textclasses
local directions = typesetters.directions
local setcolor = directions.setcolor
local getglobal = directions.getglobal
local a_state = attributes.private('state')
local a_directions = attributes.private('directions')
local strip = false
local s_isol = fonts.analyzers.states.isol
local function stopdir(finish)
local n = new_textdir(finish == "TRT" and "-TRT" or "-TLT")
setprop(n,"direction",true)
return n
end
local function startdir(finish)
local n = new_textdir(finish == "TRT" and "+TRT" or "+TLT")
setprop(n,"direction",true)
return n
end
local function nextisright(current)
current = getnext(current)
local character, id = isglyph(current)
if character then
local direction = chardirections[character]
return direction == "r" or direction == "al" or direction == "an"
end
end
local function previsright(current)
current = getprev(current)
local character, id = isglyph(current)
if character then
local direction = chardirections[character]
return direction == "r" or direction == "al" or direction == "an"
end
end
local function process(start)
local head = tonut(start) -- we have a global head
local current = head
local autodir = 0
local embedded = 0
local override = 0
local pardir = 0
local textdir = 0
local done = false
local stack = { }
local top = 0
local obsolete = { }
local rlo = false
local lro = false
local prevattr = false
local fences = { }
while current do
-- no isglyph here as we test for skips first
local id = getid(current)
local next = getnext(current)
if id == math_code then
current = getnext(end_of_math(next))
elseif getprop(current,"direction") then
-- this handles unhbox etc
current = next
else
local attr = getattr(current,a_directions)
if attr and attr > 0 then
if attr ~= prevattr then
if not getglobal(a) then
lro = false
rlo = false
end
prevattr = attr
end
end
if id == glyph_code then
if attr and attr > 0 then
local character, font = isglyph(current)
if character == 0 then
-- skip signals
setprop(current,"direction",true)
else
local direction = chardirections[character]
local reversed = false
if rlo or override > 0 then
if direction == "l" then
direction = "r"
reversed = true
end
elseif lro or override < 0 then
if direction == "r" or direction == "al" then
setprop(current,a_state,s_isol) -- hm
direction = "l"
reversed = true
end
end
if direction == "on" then
local mirror = charmirrors[character]
if mirror and fontchar[font][mirror] then
local class = charclasses[character]
if class == "open" then
if nextisright(current) then
setchar(current,mirror)
setprop(current,"direction","r")
elseif autodir < 0 then
setchar(current,mirror)
setprop(current,"direction","r")
else
mirror = false
setprop(current,"direction","l")
end
local fencedir = autodir == 0 and textdir or autodir
fences[#fences+1] = fencedir
elseif class == "close" and #fences > 0 then
local fencedir = fences[#fences]
fences[#fences] = nil
if fencedir < 0 then
setchar(current,mirror)
setprop(current,"direction","r")
else
setprop(current,"direction","l")
mirror = false
end
elseif autodir < 0 then
setchar(current,mirror)
setprop(current,"direction","r")
else
setprop(current,"direction","l")
mirror = false
end
else
setprop(current,"direction",true)
end
if trace_directions then
setcolor(current,direction,false,mirror)
end
elseif direction == "l" then
if trace_directions then
setcolor(current,"l",reversed)
end
setprop(current,"direction","l")
elseif direction == "r" then
if trace_directions then
setcolor(current,"r",reversed)
end
setprop(current,"direction","r")
elseif direction == "en" then -- european number
if trace_directions then
setcolor(current,"l")
end
setprop(current,"direction","l")
elseif direction == "al" then -- arabic letter
if trace_directions then
setcolor(current,"r")
end
setprop(current,"direction","r")
elseif direction == "an" then -- arabic number
-- needs a better scanner as it can be a float
if trace_directions then
setcolor(current,"l") -- was r
end
setprop(current,"direction","n") -- was r
elseif direction == "lro" then -- Left-to-Right Override -> right becomes left
top = top + 1
stack[top] = { override, embedded }
override = -1
obsolete[#obsolete+1] = current
elseif direction == "rlo" then -- Right-to-Left Override -> left becomes right
top = top + 1
stack[top] = { override, embedded }
override = 1
obsolete[#obsolete+1] = current
elseif direction == "lre" then -- Left-to-Right Embedding -> TLT
top = top + 1
stack[top] = { override, embedded }
embedded = 1
obsolete[#obsolete+1] = current
elseif direction == "rle" then -- Right-to-Left Embedding -> TRT
top = top + 1
stack[top] = { override, embedded }
embedded = -1
obsolete[#obsolete+1] = current
elseif direction == "pdf" then -- Pop Directional Format
if top > 0 then
local s = stack[top]
override = s[1]
embedded = s[2]
top = top - 1
else
override = 0
embedded = 0
end
obsolete[#obsolete+1] = current
elseif trace_directions then
setcolor(current)
setprop(current,"direction",true)
else
setprop(current,"direction",true)
end
end
else
setprop(current,"direction",true)
end
elseif id == glue_code then
if getsubtype(current) == parfillskip_code then
setprop(current,"direction",'!')
else
setprop(current,"direction",'g')
end
elseif id == kern_code then
setprop(current,"direction",'k')
elseif id == dir_code then
local dir = getfield(current,"dir")
if dir == "+TRT" then
autodir = -1
elseif dir == "+TLT" then
autodir = 1
elseif dir == "-TRT" or dir == "-TLT" then
if embedded and embedded~= 0 then
autodir = embedded
else
autodir = 0
end
else
-- message
end
textdir = autodir
setprop(current,"direction",true)
elseif id == localpar_code then
local dir = getfield(current,"dir")
if dir == 'TRT' then
autodir = -1
elseif dir == 'TLT' then
autodir = 1
end
pardir = autodir
textdir = pardir
setprop(current,"direction",true)
else
setprop(current,"direction",true)
end
current = next
end
end
-- todo: track if really needed
-- todo: maybe we need to set the property (as it can be a copied list)
if done and strip then
local n = #obsolete
if n > 0 then
for i=1,n do
remove_node(head,obsolete[i],true)
end
if trace_directions then
report_directions("%s character nodes removed",n)
end
end
end
local state = false
local last = false
local collapse = true
current = head
-- todo: textdir
-- todo: inject before parfillskip
while current do
local id = getid(current)
if id == math_code then
-- todo: this might be tricky nesting
current = getnext(end_of_math(getnext(current)))
else
local cp = getprop(current,"direction")
if cp == "n" then
local swap = state == "r"
if swap then
head = insert_node_before(head,current,startdir("TLT"))
end
setprop(current,"direction",true)
while true do
local n = getnext(current)
if n and getprop(n,"direction") == "n" then
current = n
setprop(current,"direction",true)
else
break
end
end
if swap then
head, current = insert_node_after(head,current,stopdir("TLT"))
end
elseif cp == "l" then
if state ~= "l" then
if state == "r" then
head = insert_node_before(head,last or current,stopdir("TRT"))
end
head = insert_node_before(head,current,startdir("TLT"))
state = "l"
done = true
end
last = false
elseif cp == "r" then
if state ~= "r" then
if state == "l" then
head = insert_node_before(head,last or current,stopdir("TLT"))
end
head = insert_node_before(head,current,startdir("TRT"))
state = "r"
done = true
end
last = false
elseif collapse then
if cp == "k" or cp == "g" then
last = last or current
else
last = false
end
else
if state == "r" then
head = insert_node_before(head,current,stopdir("TRT"))
elseif state == "l" then
head = insert_node_before(head,current,stopdir("TLT"))
end
state = false
last = false
end
setprop(current,"direction",true)
end
local next = getnext(current)
if next then
current = next
else
local sd = (state == "r" and stopdir("TRT")) or (state == "l" and stopdir("TLT"))
if sd then
if id == glue_code and getsubtype(current) == parfillskip_code then
head = insert_node_before(head,current,sd)
else
head = insert_node_after(head,current,sd)
end
end
break
end
end
return tonode(head), done
end
directions.installhandler(interfaces.variables.default,process)
|
RatCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:addItem("crystal_shard", 1, 0, player.ID)
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it..."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
TigerCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
DogCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
DragonCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
SnakeCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
RoosterCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
SheepCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
MonkeyCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
OxCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
HorseCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
PigCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
RabbitCrystalNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
if player.quest["reeves_quest"] == 5 then
player.quest["reeves_quest"] = 6
player:dialogSeq(
{
t,
"The crystal surges with power as you place your hand on it!",
"As you recoil in pain you see a small crystal shard stuck to your palm."
},
0
)
player:addItem("crystal_shard", 1, 0, player.ID)
end
player:dialogSeq({t, "The crystal seems dormant."}, 0)
end),
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
if player.quest["reeves_quest"] >= 4 then
if speech == "calamity" then
if player.quest["reeves_quest"] == 4 then
player.quest["reeves_quest"] = 5
end
player:dialogSeq(
{
t,
"The crystal emits a faint glow. You almost want to touch it."
},
0
)
end
end
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
end),
}
|
table.insert( data.raw["technology"]["uranium-ammo"].effects, { type = "unlock-recipe", recipe = "uranium-shotgun-recipe" } )
--table.insert( data.raw["technology"]["military"].effects, { type = "unlock-recipe", recipe = "empty-shotgun-recipe" } )
|
local shortport = require "shortport"
local stdnse = require "stdnse"
local table = require "table"
local vnc = require "vnc"
description = [[
Queries a VNC server for its protocol version and supported security types.
]]
author = "Patrik Karlsson"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"
categories = {"default", "discovery", "safe"}
---
-- @output
-- PORT STATE SERVICE
-- 5900/tcp open vnc
-- | vnc-info:
-- | Protocol version: 3.889
-- | Security types:
-- | Mac OS X security type (30)
-- |_ Mac OS X security type (35)
--
-- Version 0.2
-- Created 07/07/2010 - v0.1 - created by Patrik Karlsson <patrik@cqure.net>
-- Revised 08/14/2010 - v0.2 - changed so that errors are reported even without debugging
portrule = shortport.port_or_service( {5900, 5901, 5902} , "vnc", "tcp", "open")
action = function(host, port)
local vnc = vnc.VNC:new( host.ip, port.number )
local status, data
local result = {}
status, data = vnc:connect()
if ( not(status) ) then return " \n ERROR: " .. data end
status, data = vnc:handshake()
if ( not(status) ) then return " \n ERROR: " .. data end
status, data = vnc:getSecTypesAsStringTable()
if ( not(status) ) then return " \n ERROR: " .. data end
table.insert(result, ("Protocol version: %s"):format(vnc:getProtocolVersion()) )
if ( data and #data ~= 0 ) then
data.name = "Security types:"
table.insert( result, data )
end
if ( vnc:supportsSecType(vnc.sectypes.NONE) ) then
table.insert(result, "WARNING: Server does not require authentication")
end
return stdnse.format_output(status, result)
end
|
--[[
Benchmarking script to analyse the loading speed by loading metadata directly from RAM memory.
The intent for this code is to show that loading metadata from disk has an insignificant
overhead when retrieving metadata stored in RAM.
]]
require 'paths'
require 'torch'
require 'string'
require 'xlua'
local tnt = require 'torchnet'
torch.setdefaulttensortype('torch.FloatTensor')
torch.manualSeed(2)
--------------------------------------------------------------------------------
-- Load configurations (data, model, criterion, optimState, logger)
--------------------------------------------------------------------------------
local opt = {
dataset = 'ilsvrc2012',
expDir = './cache',
manualSeed = 2,
nThreads = 4,
imageSize = 256,
cropSize = 224,
batchSize = 128,
nsamples = 1000
}
local stats = torch.load(paths.concat(opt.expDir, opt.dataset, 'cache.t7'))
opt.meanstd = {mean = stats.meanstd.mean, std = stats.meanstd.std}
-- convert modules to a specified tensor type
local function cast(x) return x:type(opt.dataType) end
-- number of samples to fetch
local n_samples = opt.nsamples
-----------------------------------------------------------
-- Move metadata from disk to memory
-----------------------------------------------------------
print('Loading data from file to ram ...')
local dbc = require 'dbcollection.manager'
local dbloader = dbc.load(opt.dataset)
local num_classes = dbloader:size('train', 'classes')[1]
local string_ascii = require 'dbcollection.utils.string_ascii'
local ascii2str = string_ascii.convert_ascii_to_str
local function add_path(fname)
local out = {}
for i=1, #fname do
table.insert(out, paths.concat(dbloader.data_dir, fname[i]))
end
return out
end
-- train data
local train_objs_ids = dbloader:object('train')
local train_filenames = add_path(ascii2str(dbloader:get('train', 'image_filenames')))
local train_class_ids = train_objs_ids:select(2,2):long()
-- val data
local val_objs_ids = dbloader:object('val')
local val_filenames = add_path(ascii2str(dbloader:get('val', 'image_filenames')))
local val_class_ids = val_objs_ids:select(2,2):long()
local metadata = {
train = {
filename = train_filenames,
class_id = train_class_ids,
size = train_objs_ids:size(1)
},
val = {
filename = val_filenames,
class_id = val_class_ids,
size = val_objs_ids:size(1)
},
}
--------------------------------------------------------------------------------
-- Setup data generator
--------------------------------------------------------------------------------
local function getIterator(mode)
return tnt.ParallelDatasetIterator{
nthread = opt.nThreads,
ordered=true,
init = function(threadid)
require 'torch'
require 'torchnet'
require 'image'
t = require 'transforms'
torch.manualSeed(threadid+opt.manualSeed)
end,
closure = function()
local data = metadata[mode]
local function fetch_data(idx)
-- get random image from the list
local idx = torch.random(1, data.size)
return {image.load(data.filename[idx], 3, 'float'), data.class_id[idx]}
end
-- setup dataset iterator
local list_dataset = tnt.ListDataset{
list = torch.range(1, data.size):long(),
load = function(idx)
local data = fetch_data(idx)
return {
input = data[1],
target = data[2],
}
end
}
return list_dataset
:shuffle()
:transform{
input = mode == 'train' and
tnt.transform.compose{
t.Fix(),
t.Scale(opt.imageSize),
t.RandomCrop(opt.cropSize),
t.ColorNormalize({mean = opt.meanstd.mean, std = opt.meanstd.std}),
t.HorizontalFlip(0.5),
t.ColorJitter({
brightness = 0.4,
contrast = 0.4,
saturation = 0.4,
})
}
or mode == 'val' and
tnt.transform.compose{
t.Fix(),
t.Scale(opt.imageSize),
t.CenterCrop(opt.cropSize),
t.ColorNormalize({mean = opt.meanstd.mean, std = opt.meanstd.std})
}
}
:batch(opt.batchSize, 'include-last')
end,
}
end
--------------------------------------------------------------------------------
-- Setup timer
--------------------------------------------------------------------------------
local dataTimer = torch.Timer()
-----------------------------------------------------------
-- Iterate over n samples (train + val)
-----------------------------------------------------------
for _, mode in pairs({'train', 'val'}) do
print('\n************************************************')
print('Benchmarking loading metadata from disk: ' .. mode)
print('************************************************\n')
-- get data iterator
local iterator = getIterator(mode)
local sample_time = {}
for i=1, n_samples do
xlua.progress(i, n_samples)
dataTimer:reset()
local sample = iterator()
table.insert(sample_time, dataTimer:time().real)
collectgarbage()
end
-- display timings info for the set
print(('> Average data loading time (batchsize=%d): %0.5f'):format(opt.batchSize, torch.DoubleTensor(sample_time):mean()))
print(('> Min data loading time (batchsize=%d): %0.5f'):format(opt.batchSize, torch.DoubleTensor(sample_time):min()))
print(('> Max data loading time (batchsize=%d): %0.5f'):format(opt.batchSize, torch.DoubleTensor(sample_time):max()))
print(('> Total data loading time (batchsize=%d): %0.5f'):format(opt.batchSize, torch.DoubleTensor(sample_time):sum()))
end
print('\n==> Script complete.')
|
MPVController = { global_config = {} }
function MPVController:is_muted()
return (tonumber(mp.get_property('volume')) == 0)
end
function MPVController:get_current_timestamp()
local current_timestamp = (mp.get_property('time-pos', -1))
if type(current_timestamp) == "string" then
current_timestamp = tonumber(current_timestamp)
end
return current_timestamp
end
function MPVController:seek(timestamp)
mp.command('seek '.. timestamp .. ' absolute')
self.global_config.code_seek_just_performed = true
end
function MPVController:set_volume(volume)
mp.command('set volume '..volume)
end
function MPVController:toggle_mute()
local volume = mp.get_property('volume')
if tonumber(volume) > 0 then
self.global_config.original_volume = tonumber(volume)
self:set_volume(0)
else
self:set_volume(self.global_config.original_volume)
end
end
function MPVController:new(o)
o = o or { global_config = {} }
setmetatable(o, self)
self.__index = MPVController
return o
end
return MPVController
|
--[[
base.lua
Copyright (c) 2020 Daniel Buckley
--]]
-- Reference to quests index file
quests_index_file = "quests/index.lua"
-- Define character elements
function mk_element(n, ap, at, ba, bs, bh)
return {Name=n, ArmorPercent=ap, ArmorTurns=at, BaseAttack=ba, BaseSpeed=bs, BaseHealth=bh}
end
elements = {}
elements[0] = mk_element("Basic", 15, 50, 13, 13, 28)
elements[1] = mk_element("Earth", 35, 60, 22, 14, 70)
elements[2] = mk_element("Air", 30, 60, 17, 22, 49)
elements[3] = mk_element("Fire", 30, 60, 17, 17, 62)
elements[4] = mk_element("Water", 35, 60, 14, 20, 56)
elements[5] = mk_element("Mystic", 50, 150, 26, 26, 78)
elements[6] = mk_element("Alpha", 40, 25, 29, 29, 84)
-- Define character ranks
function mk_rank(n, ab, sb, hb)
return {Name=n, AttackBoost=ab, SpeedBoost=sb, HealthBoost=hb}
end
ranks = {}
ranks[0] = mk_rank("F", 0, 0, 0)
ranks[1] = mk_rank("E", 3, 3, 8)
ranks[2] = mk_rank("D", 8, 8, 10)
ranks[3] = mk_rank("C", 15, 15, 15)
ranks[4] = mk_rank("B", 30, 30, 25)
ranks[5] = mk_rank("A", 45, 45, 40)
ranks[6] = mk_rank("Z", 60, 60, 50)
-- Define character statuses
function mk_status(n, e, el, st)
return {Name=n, Effect=e, EffectLength=el, StatusType=st}
end
num_statuses = 14
statuses = {}
statuses[0] = mk_status("Burn", "Damages character 1% of their maximum health every turn for 15 turns.", 15, 0)
statuses[1] = mk_status("Poison", "Damages character 3% of their maximum health every turn for 15 turns.", 15, 0)
statuses[2] = mk_status("Enlightened", "The character becomes enlightened, and can heal itself for 5 turns.", 5, 0)
statuses[3] = mk_status("Guarding", "The character is protected from any damage for 3 turns.", 3, 0)
statuses[4] = mk_status("Mystified", "The character becomes mystified by its enemy and cannot attack.", 5, 1)
statuses[5] = mk_status("Enraged", "The character becomes enraged and is forced to attack only with its weapon.", 5, 1)
statuses[6] = mk_status("Weightless", "The user becomes weightless and floats up, making it impossible to use close-range weapons.", 1, 1)
statuses[7] = mk_status("Claustrophobic", "The character is trapped in a tight space, making it impossible to use long-range weapons.", 1, 1)
statuses[8] = mk_status("Frozen", "The character is trapped in ice and is forced to pass its turn.", 5, 1)
statuses[9] = mk_status("Amnesiac", "The character has temporary amnesia, and cannot remember how to use its special ability.", 1, 1)
statuses[10] = mk_status("Shattered Armor", "Removes the effect of armor from the character.", 1, 2)
statuses[11] = mk_status("Unworthy", "This character is deemed unworthy by its enemy. It is damaged by 50% of its maximum health, removed of armor, and forced to pass its turn.", 1, 3)
statuses[12] = mk_status("Protecting", "The character is protected from any damage for 1 turn.", 1, 3)
statuses[13] = mk_status("Frenzy", "Raises the characters attack and speed by 80% and heals for 40% of damage dealt with a weapon in the previous turn.", 0, 3)
-- Define weapons
function mk_weapon(ci, c, h, w, r, dt, n, e, str, cis, is)
return {CollectionIndex=ci, Category=c, Handling=h, Weight=w, Range=r, DamageType=dt, Name=n, Element=e, Strength=str, CanInflictStatus=cis, InflictedStatus=is}
end
num_weapons = 56
weapons = {}
-- Basic Weapons
weapons[0] = mk_weapon(0, 1, 1, 0, 1, 0, "Slingshot", 0, 10, false, 0)
weapons[1] = mk_weapon(1, 2, 0, 1, 0, 0, "Sword", 0, 23, false, 0)
weapons[2] = mk_weapon(2, 3, 1, 0, 2, 0, "Bow", 0, 18, false, 0)
weapons[3] = mk_weapon(3, 2, 0, 0, 0, 0, "Dagger", 0, 15, false, 0)
weapons[4] = mk_weapon(4, 2, 1, 2, 0, 0, "Katana", 0, 25, false, 0)
weapons[5] = mk_weapon(5, 4, 1, 0, 1, 0, "Javelin", 0, 27, false, 0)
weapons[6] = mk_weapon(6, 2, 1, 1, 0, 1, "Cursed Blade", 0, 35, false, 0)
weapons[7] = mk_weapon(7, 7, 1, 0, 1, 1, "Beginner's Elemental Staff", 0, 37, true, 4)
-- Earth Weapons
weapons[8] = mk_weapon(0, 2, 0, 1, 0, 0, "Dull Wolf Katana", 1, 45, false, 0)
weapons[9] = mk_weapon(1, 4, 1, 1, 1, 0, "Ancient Spear", 1, 49, true, 1)
weapons[10] = mk_weapon(2, 5, 0, 1, 0, 0, "Bone Club", 1, 54, false, 0)
weapons[11] = mk_weapon(3, 3, 1, 0, 1, 0, "Marksman's Crossbow", 1, 60, false, 0)
weapons[12] = mk_weapon(4, 2, 1, 1, 0, 0, "Earthen Scythe", 1, 67, true, 7)
weapons[13] = mk_weapon(5, 2, 1, 2, 0, 0, "Tungsten Katana", 1, 71, false, 0)
weapons[14] = mk_weapon(6, 7, 1, 0, 1, 1, "Staff of the Wolf's Eye", 1, 75, false, 0)
weapons[15] = mk_weapon(7, 2, 1, 2, 0, 0, "Wolf's Eye Katana", 1, 80, true, 4)
-- Air Weapons
weapons[16] = mk_weapon(0, 3, 0, 0, 0, 0, "Tattered Eagle Bow", 2, 45, true, 6)
weapons[17] = mk_weapon(1, 2, 0, 0, 0, 0, "Sky Blade", 2, 51, false, 0)
weapons[18] = mk_weapon(2, 1, 1, 0, 1, 0, "Reinforced Slingshot", 2, 56, false, 0)
weapons[19] = mk_weapon(3, 3, 1, 1, 2, 1, "Poisoned Bow", 2, 60, true, 1)
weapons[20] = mk_weapon(4, 2, 0, 0, 0, 0, "Lightening Sword", 2, 64, true, 6)
weapons[21] = mk_weapon(5, 4, 1, 1, 1, 1, "Spear of Shattering", 2, 69, true, 10)
weapons[22] = mk_weapon(6, 7, 1, 0, 1, 1, "Staff of the Eagle's Talon", 2, 75, false, 0)
weapons[23] = mk_weapon(7, 3, 1, 2, 2, 0, "Spirit Eagle Bow", 2, 80, true, 4)
-- Fire Weapons
weapons[24] = mk_weapon(0, 2, 0, 0, 0, 0, "Dull Dragon Sword", 3, 45, true, 0)
weapons[25] = mk_weapon(1, 3, 1, 0, 2, 0, "Flaming Bow", 3, 53, true, 0)
weapons[26] = mk_weapon(2, 2, 0, 0, 0, 0, "Scorching Dagger", 3, 49, true, 0)
weapons[27] = mk_weapon(3, 2, 0, 1, 0, 0, "Volcanic Sword", 3, 57, true, 0)
weapons[28] = mk_weapon(4, 2, 0, 2, 0, 0, "Infernal Axe", 3, 68, false, 0)
weapons[29] = mk_weapon(5, 6, 1, 2, 0, 0, "Lava Hammer", 3, 72, false, 0)
weapons[30] = mk_weapon(6, 7, 1, 0, 1, 1, "Staff of the Dragon's Horn", 3, 75, false, 0)
weapons[31] = mk_weapon(7, 2, 1, 1, 0, 0, "Dragon Claw Sword", 3, 80, true, 4)
-- Water Weapons
weapons[32] = mk_weapon(0, 3, 1, 0, 2, 0, "Tattered Sea Serpent Bow", 4, 45, false, 0)
weapons[33] = mk_weapon(1, 2, 1, 1, 0, 0, "Ice Scimitar", 4, 50, false, 0)
weapons[34] = mk_weapon(2, 3, 1, 0, 2, 0, "Frozen Bow", 4, 53, true, 8)
weapons[35] = mk_weapon(3, 4, 1, 0, 0, 0, "Icicle Spear", 4, 61, false, 0)
weapons[36] = mk_weapon(4, 2, 0, 0, 0, 0, "Coral Bayonet", 4, 66, false, 0)
weapons[37] = mk_weapon(5, 5, 0, 2, 0, 1, "Subzero Mace", 4, 71, true, 8)
weapons[38] = mk_weapon(6, 7, 1, 0, 1, 1, "Staff of the Serpent's Fang", 4, 75, false, 0)
weapons[39] = mk_weapon(7, 3, 1, 0, 2, 0, "Sea Serpent Bow", 4, 80, true, 4)
-- Mystic Weapons
weapons[40] = mk_weapon(0, 0, 0, 0, 0, 0, "", 5, 45, false, 0)
weapons[41] = mk_weapon(1, 0, 0, 0, 0, 0, "", 5, 50, false, 0)
weapons[42] = mk_weapon(2, 0, 0, 0, 0, 0, "", 5, 55, false, 0)
weapons[43] = mk_weapon(3, 0, 0, 0, 0, 0, "", 5, 60, false, 0)
weapons[44] = mk_weapon(4, 0, 0, 0, 0, 0, "", 5, 65, false, 0)
weapons[45] = mk_weapon(5, 0, 0, 0, 0, 0, "", 5, 70, false, 0)
weapons[46] = mk_weapon(6, 7, 0, 0, 0, 0, "Elemental Staff", 5, 75, false, 0)
weapons[47] = mk_weapon(7, 0, 0, 0, 0, 0, "", 5, 80, true, 4)
-- Alpha Weapons
weapons[48] = mk_weapon(0, 7, 1, 0, 1, 1, "Staff of Simplicity", 6, 85, false, 0)
weapons[49] = mk_weapon(1, 7, 1, 1, 1, 1, "Staff of Sky", 6, 90, true, 6)
weapons[50] = mk_weapon(2, 7, 1, 1, 1, 1, "Staff of Land", 6, 90, true, 7)
weapons[51] = mk_weapon(3, 7, 1, 1, 1, 1, "Staff of Flame", 6, 90, true, 0)
weapons[52] = mk_weapon(4, 7, 1, 1, 1, 1, "Staff of Sea", 6, 90, false, 0)
weapons[53] = mk_weapon(5, 7, 1, 1, 1, 1, "Staff of Mastery", 6, 90, false, 0)
weapons[54] = mk_weapon(6, 7, 1, 1, 1, 1, "Staff of Rage", 6, 95, true, 5)
weapons[55] = mk_weapon(7, 7, 1, 2, 1, 1, "Staff of Creation", 6, 100, true, 11)
-- Define passive abilities
function mk_passive_ability(n, e)
return {Name=n, Effect=e}
end
passive_abilities = {}
-- Basic
passive_abilities[0] = mk_passive_ability("Firm Resolve", "When Health drops below 50%, the Attack stat is doubled.")
-- Earth
passive_abilities[1] = mk_passive_ability("Fighter", "Power of close-range attacks increase by 30% when battling in Earth terrain.")
-- Air
passive_abilities[2] = mk_passive_ability("Sniper", "Power of long-range attacks increase by 30% when battling in Air terrain.")
-- Fire
passive_abilities[3] = mk_passive_ability("Temper", "Attack is increased by 10% when battling in Fire terrain.")
-- Water
passive_abilities[4] = mk_passive_ability("Swift Swimmer", "Speed is increased by 10% when battling in Water terrain.")
-- Mystic
passive_abilities[5] = mk_passive_ability("Passive - Mystic", "")
-- Alpha
passive_abilities[6] = mk_passive_ability("Divine Nature", "When Health drops to 15%, the Character gains the Enlightened status.")
-- Define special abilties
function mk_special_ability(n, e, c, w, el)
return {Name=n, Effect=e, CostToLearn=c, WeaponReqs=w, ElementSupport=el}
end
num_special_abilities = 19
special_abilities = {}
special_abilities[0] = mk_special_ability("Protect", "Protects character from any damage.", 0, 0, 63)
special_abilities[1] = mk_special_ability("Recovery", "Recover 25% of maximum health.", 0, 0, 63)
special_abilities[2] = mk_special_ability("Tricky Mirror", "Transfers the current inflicted status (if one) to the enemy.", 0, 0, 63)
special_abilities[3] = mk_special_ability("Revenge", "The lower the user's current health is, the greater the damage.", 0, 0, 63)
special_abilities[4] = mk_special_ability("Deadly Accuracy", "The user deals massive damage by using its long-range weapon.", 0, 1, 63)
special_abilities[5] = mk_special_ability("Flaming Vortex", "The user conjures a flaming vortex that damages and burns the target.", 0, 0, 4)
special_abilities[6] = mk_special_ability("Inferno", "The user creates a powerful inferno to damage the enemy.", 0, 0, 4)
special_abilities[7] = mk_special_ability("Hurricane", "The user conjures a hurricane which lifts up and damages the opponent.", 0, 0, 10)
special_abilities[8] = mk_special_ability("Whirlpool", "The user conjures a whirlpool which damages the enemy.", 0, 0, 2)
special_abilities[9] = mk_special_ability("Landslide", "The user conjures a landslide which damages and traps the enemy.", 0, 0, 16)
special_abilities[10] = mk_special_ability("Extinguish", "If the enemy is of the Fire element, this attack doubles in damage.", 0, 0, 18)
special_abilities[11] = mk_special_ability("Scald", "The user douses the enemy with scalding hot water.", 0, 0, 2)
special_abilities[12] = mk_special_ability("Speedster", "The faster the user is, the higher the damage.", 0, 0, 63)
special_abilities[13] = mk_special_ability("Power Trick", "This special ability uses the enemy's attack stat against them.", 0, 0, 63)
special_abilities[14] = mk_special_ability("Platinum Power Play", "The user deals massive damage by using its close-range weapon.", 0, 2, 63)
special_abilities[15] = mk_special_ability("Guard Stance", "The user guards themselves to avoid any damage.", 0, 0, 16)
special_abilities[16] = mk_special_ability("Honor Amongst Thieves", "If the character and the enemy are of the same element, both characters will restore 10% of their health. However, if they are not of the same element, the character that uses this ability will steal 10% of the enemy's health(damage does not bypass armor).", 0, 0, 63)
special_abilities[17] = mk_special_ability("Good Samaritan", "Heals the status of an enemy, if any.", 0, 0, 63)
special_abilities[18] = mk_special_ability("Call To Arms", "Self-inflicts 'Frenzy' status for a variable amount of turns. The amount of turns depends on the strength of the currently attached weapon.", 0, 0, 63)
-- Returns requested character element
function GetElement(n)
return elements[n]
end
-- Returns requested character rank
function GetRank(n)
return ranks[n]
end
-- Returns requested status
function GetStatus(n)
return statuses[n]
end
-- Returns requested weapon
function GetWeapon(n)
return weapons[n]
end
-- Returns requested passive ability
function GetPassiveAbility(n)
return passive_abilities[n]
end
-- Returns requested special ability
function GetSpecialAbility(n)
return special_abilities[n]
end
-- Returns requested item
function GetItem(n)
return items[n]
end
|
local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_DROWNDAMAGE)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_BUBBLES)
local condition = Condition(CONDITION_DROWN)
condition:setParameter(CONDITION_PARAM_DELAYED, 1)
condition:addDamage(50, 5000, -20)
local area = createCombatArea(AREA_CROSS6X6)
combat:setArea(area)
combat:setCondition(condition)
function onCastSpell(creature, var)
return combat:execute(creature, var)
end
|
module(..., package.seeall)
local localStorage = require 'gameLogic.localStorage'
function new(health, mana, soundEffect)
local group = display.newGroup()
local imageGroup = display.newGroup()
local textGroup = display.newGroup()
local menuIsOpened = false
local potionsBox = display.newImageRect("images/mainStackbar.png", 60, 30)
potionsBox.anchorX, potionsBox.anchorY = 0, 0
potionsBox.x = display.contentWidth - 70
potionsBox.y = 1
group:insert(potionsBox)
imageGroup:insert(potionsBox)
local selectItemImage
local currentSelectedItem
local lastSelectedItem
local imageSize = 60
local potionsMenu = display.newGroup()
local potionsTable = {
{"images/buttons/buttonMana.png", 190, 30, 100, "mana"},
{"images/buttons/buttonPotion.png", 250, 30, 50, "health1"},
{"images/buttons/buttonSpotion.png", 190, 90, 100, "health2"},
{"images/buttons/buttonEpotion.png", 250, 90, 200, "health3"},
{"images/buttons/buttonUpotion.png", 250, 150, 100, "health4"},
}
local function getNumbersOfPotions()
local redPot1, redPot2, redPot3, redPot4, bluePot
redPot1 = localStorage.get("redPot1")
redPot2 = localStorage.get("redPot2")
redPot3 = localStorage.get("redPot3")
redPot4 = localStorage.get("redPot4")
bluePot = localStorage.get("bluePot")
return {bluePot, redPot1, redPot2, redPot3, redPot4}
end
local function drawPotionsTable()
for i = 1, #potionsTable, 1 do
local potionImage = display.newImageRect(potionsTable[i][1], imageSize, imageSize)
potionImage.anchorX, potionImage.anchorY = 0, 0
potionImage.x = potionsTable[i][2]
potionImage.y = potionsTable[i][3]
imageGroup:insert(potionImage)
potionImage.isVisible = false
end
end
local function drawNumberTextOnPotionsTable(t)
for i=1, #potionsTable, 1 do
local numberOfPotions = display.newText(t[i], potionsTable[i][2]+44, potionsTable[i][3]+36, "Impact", 10)
textGroup:insert(numberOfPotions)
end
textGroup.isVisible = false
end
local function checkTouchPosition(x,y)
if selectItemImage and textGroup and imageGroup then
for i=1, #potionsTable, 1 do
if x >= potionsTable[i][2] and x < potionsTable[i][2]+imageSize and y >= potionsTable[i][3] and y < potionsTable[i][3]+imageSize then
selectItemImage.isVisible = true
selectItemImage.x = potionsTable[i][2]
selectItemImage.y = potionsTable[i][3]
currentSelectedItem = i
if lastSelectedItem == nil or (currentSelectedItem ~= lastSelectedItem) then
lastSelectedItem = currentSelectedItem
soundEffect:play("choose")
end
break
end
end
end
end
local function showPotionsTable()
for i=1, imageGroup.numChildren, 1 do
imageGroup[i].isVisible = true
menuIsOpened = true
if selectItemImage then
selectItemImage:removeSelf()
selectItemImage = nil
end
selectItemImage = display.newImageRect("images/mainSelectitem.png", 60, 60)
selectItemImage.anchorX, selectItemImage.anchorY = 0, 0
selectItemImage.isVisible = false
end
textGroup.isVisible = true
end
local function hidePotionsTable()
for i=2, imageGroup.numChildren, 1 do
imageGroup[i].isVisible = false
menuIsOpened = false
if selectItemImage then
selectItemImage:removeSelf()
selectItemImage = nil
end
currentSelectedItem = nil
lastSelectedItem = nil
end
textGroup.isVisible = false
end
local hidePotionsTableTimer
local function refreshTimer()
if hidePotionsTableTimer then
timer.cancel(hidePotionsTableTimer)
end
hidePotionsTableTimer = timer.performWithDelay(1000, function() hidePotionsTable() end)
end
local function restore(i)
local restoreType, restoreAmount
if i and not health:isDead() then
restoreType = potionsTable[i][5]
restoreAmount = potionsTable[i][4]
if restoreType == "mana" then
local currentBluePot = localStorage.get("bluePot") - 1
if currentBluePot >= 0 then
mana:addMpBy(restoreAmount)
localStorage.saveWithKey("bluePot", currentBluePot)
textGroup[1].text = currentBluePot
soundEffect:play("useitem")
end
elseif restoreType == "health1" then
local currentRedPot1 = localStorage.get("redPot1") - 1
if currentRedPot1 >= 0 then
health:addHpBy(restoreAmount, restoreType)
localStorage.saveWithKey("redPot1", currentRedPot1)
textGroup[2].text = currentRedPot1
soundEffect:play("useitem")
end
elseif restoreType == "health2" then
local currentRedPot2 = localStorage.get("redPot2") - 1
if currentRedPot2 >= 0 then
health:addHpBy(restoreAmount, restoreType)
localStorage.saveWithKey("redPot2", currentRedPot2)
textGroup[3].text = currentRedPot2
soundEffect:play("useitem")
end
elseif restoreType == "health3" then
local currentRedPot3 = localStorage.get("redPot3") - 1
if currentRedPot3 >= 0 then
health:addHpBy(restoreAmount, restoreType)
localStorage.saveWithKey("redPot3", currentRedPot3)
textGroup[4].text = currentRedPot3
soundEffect:play("useitem")
end
elseif restoreType == "health4" then
local currentRedPot4 = localStorage.get("redPot4") - 1
if currentRedPot4 >= 0 then
health:addHpBy(health:getMaxHealth(), restoreType)
localStorage.saveWithKey("redpot4", currentRedPot4)
textGroup[5].text = currentRedPot4
soundEffect:play("useitem")
end
end
end
end
local function selectPotionsListener(event)
checkTouchPosition(event.x, event.y)
if event.phase == "began" then
showPotionsTable()
refreshTimer()
elseif event.phase == "moved" then
refreshTimer()
elseif event.phase == "cancelled" then
hidePotionsTable()
elseif event.phase == "ended" and menuIsOpened then
restore(currentSelectedItem)
hidePotionsTable()
end
end
local inBagPotionsNumber = getNumbersOfPotions()
drawPotionsTable()
drawNumberTextOnPotionsTable(inBagPotionsNumber)
imageGroup:addEventListener("touch", selectPotionsListener)
group:insert(imageGroup)
group:insert(textGroup)
return group
end
|
local mod = DBM:NewMod(1469, "DBM-Party-Legion", 10, 707)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 17077 $"):sub(12, -3))
mod:SetCreatureID(95887)
mod:SetEncounterID(1817)
mod:SetZone()
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_START 193443 194942",
"SPELL_PERIODIC_DAMAGE 194945",
"SPELL_PERIODIC_MISSED 194945"
)
--TODO, maybe voice for mirrors to bounce beam back into boss? But how do you say this short
local warnGaze = mod:NewSpellAnnounce(194942, 2)
local specWarnFocused = mod:NewSpecialWarningSpell(194289, nil, nil, nil, 2, 2)
local specWarnGazeGTFO = mod:NewSpecialWarningMove(194945, nil, nil, nil, 1, 2)
local timerGazeCD = mod:NewCDTimer(19.4, 194942, nil, nil, nil, 3)
function mod:OnCombatStart(delay)
timerGazeCD:Start(11.8-delay)
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 193443 then--194289 backup if energize stops working.
timerGazeCD:Stop()
specWarnFocused:Show()
specWarnFocused:Play("specialsoon")
elseif spellId == 194942 then
warnGaze:Show()
timerGazeCD:Start()
end
end
function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
if spellId == 194945 and destGUID == UnitGUID("player") and self:AntiSpam(2, 1) then
specWarnGazeGTFO:Show()
specWarnGazeGTFO:Play("runaway")
end
end
mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE
|
local PLUGIN = PLUGIN
PLUGIN.name = "Door System"
PLUGIN.description = "Adds a simply configurable door system."
PLUGIN.author = "Skay™#2752"
--[[ DOOR SYSTEM TEMPLATE
["mapname"] = { -- use status in console
{
id = 3965, -- Map Creation ID of the door
name = "Yo CP's come in boys.", -- Display name of the door
access = 1 -- Access of the door
},
}
]]
ix.util.Include("cl_hooks.lua")
ix.util.Include("sv_hooks.lua")
ix.util.Include("sh_entity.lua")
PLUGIN.access = {
[1] = {
name = "Universal Access 1",
color= Color(0, 100, 255),
checkAccess = function(ply)
return ( ply:Team() == FACTION_MPF or ply:Team() == FACTION_OTA )
end,
snd = "buttons/combine_button2.wav"
},
[2] = {
name = "Universal Access 2",
color = Color(30, 220, 200),
checkAccess = function(ply)
return ( ply:Team() == FACTION_OTA )
end,
snd = "buttons/combine_button7.wav"
},
[3] = {
name = "Universal Access 3", -- Name of the door access to be displayed
color = Color(255, 0, 0), -- Color of the display
checkAccess = function(ply)
return ( ply:Team() == FACTION_OTA )
end, -- Factions that are allowed to use the door
snd = "buttons/combine_button1.wav" -- Sound on opening the door
},
}
PLUGIN.doors = {
["rp_city17_conflictstudios"] = {
{
id = 3965, -- Map Creation ID of the door
name = "Yo CP's come in boys.", -- Display name of the door
access = 1 -- Access of the door
},
{
id = 3966,
name = "cat",
access = 1
},
{
id = 4110,
name = "drugs",
access = 2
}
},
["rp_nc_d47_v2"] = {
{
id = 2380,
name = "hi",
access = 1
}
}
}
concommand.Add("printtable", function(ply)
PrintTable(PLUGIN.doors)
for k, v in pairs(PLUGIN.doors) do
print(k.." - k")
for _, a in pairs(v) do
timer.Simple(5, function()
PrintTable(v)
end)
end
end
end)
|
local random = require 'lqc.random'
local byte = require 'lqc.generators.byte'
local r = require 'lqc.report'
local property = require 'lqc.property'
local lqc = require 'lqc.quickcheck'
local function is_byte(value)
return type(value) == 'number'
and value % 1 == 0
and value >= 0x00
and value <= 0xff
end
local function do_setup()
random.seed()
lqc.init(100, 100)
lqc.properties = {}
r.report = function() end
end
describe('byte generator module', function()
before_each(do_setup)
describe('pick function', function()
it('should pick a byte', function()
local spy_check = spy.new(function(x) return is_byte(x) end)
property 'byte() should pick a byte' {
generators = { byte() },
check = spy_check
}
lqc.check()
assert.spy(spy_check).was.called(lqc.numtests)
end)
end)
describe('shrink function', function()
it('should converge to 0', function()
local shrunk_values
r.report_failed_property = function(_, _, shrunk_vals)
shrunk_values = shrunk_vals[1]
end
property 'byte() should converge to 0' {
generators = { byte() },
check = function(x)
return not is_byte(x) -- always fails!
end
}
for _ = 1, 100 do
shrunk_values = nil
lqc.check()
assert.equal(0, shrunk_values)
end
end)
end)
end)
|
function love.conf(t)
t.title = "Mari0 SE"
t.author = "Maurice"
t.identity = "mari0_se"
t.modules.physics = false
t.version = "0.10.1"
end
|
require "import"
import "android.widget.*"
import "android.view.*"
import "android.app.*"
local classes = require "android"
import "clayout"
import "mlayout"
import "autotheme"
activity.Title = "Java API浏览器"
activity.setTheme(autotheme())
function adapter(t)
local ls = ArrayList()
for k, v in ipairs(t) do
ls.add(v)
end
return ArrayAdapter(activity, android.R.layout.simple_list_item_1, ls)
end
import "android.content.*"
cm = activity.getSystemService(activity.CLIPBOARD_SERVICE)
function copy(str)
local cd = ClipData.newPlainText("label", str)
cm.setPrimaryClip(cd)
Toast.makeText(activity, "已复制到剪切板", 1000).show()
end
dlg = Dialog(activity, autotheme())
dlg.setContentView(loadlayout(mlayout))
curr_class = nil
curt_adapter = nil
activity.setContentView(clayout)
clist.setAdapter(adapter(classes))
clist.onItemClick = function(l, v)
local s = tostring(v.Text)
local class = luajava.bindClass(s)
curr_class = class
local t = {}
local fs = {}
local ms = {}
local es = {}
local ss = {}
local gs = {}
local super = class.getSuperclass()
super = super and " extends " .. tostring(super.getName()) or ""
table.insert(t, tostring(class) .. super)
table.insert(t, "构建方法")
local cs = class.getConstructors()
for n = 0, #cs - 1 do
table.insert(t, tostring(cs[n]))
end
curr_ms = class.getMethods()
for n = 0, #curr_ms - 1 do
local str = tostring(curr_ms[n])
table.insert(ms, str)
local e1 = str:match("%.setOn(%a+)Listener")
local s1, s2 = str:match("%.set(%a+)(%([%a$%.]+%))")
local g1, g2 = str:match("([%a$%.]+) [%a$%.]+%.get(%a+)%(%)")
if e1 then
table.insert(es, "on" .. e1)
elseif s1 then
table.insert(ss, s1 .. s2)
end
if g1 then
table.insert(gs, string.format("(%s)%s", g1, g2))
end
end
table.insert(t, "公有事件")
for k, v in ipairs(es) do
table.insert(t, v)
end
table.insert(t, "公有getter")
for k, v in ipairs(gs) do
table.insert(t, v)
end
table.insert(t, "公有setter")
for k, v in ipairs(ss) do
table.insert(t, v)
end
curr_fs = class.getFields()
table.insert(t, "公有字段")
for n = 0, #curr_fs - 1 do
table.insert(t, tostring(curr_fs[n]))
end
table.insert(t, "公有方法")
for k, v in ipairs(ms) do
table.insert(t, v)
end
dlg.Title = tostring(s)
curt_adapter = adapter(t)
mlist.setAdapter(curt_adapter)
dlg.show()
end
clist.onItemLongClick = function(l, v)
local s = tostring(v.Text)
copy(s)
return true
end
mlist.onItemLongClick = function(l, v)
local s = tostring(v.Text)
if s:find("%(") then
s = s:match("(%w+)%(")
else
s = s:match("(%w+)$")
end
copy(s)
return true
end
medit.addTextChangedListener {
onTextChanged = function(c)
local s = tostring(c)
if #s == 0 then
mlist.setAdapter(curt_adapter)
return true
end
local class = curr_class
local t = {}
local fs = curr_fs
table.insert(t, "公有字段")
for n = 0, #fs - 1 do
if fs[n].Name:find(s, 1, true) then
table.insert(t, tostring(fs[n]))
end
end
local ms = curr_ms
table.insert(t, "公有方法")
for n = 0, #ms - 1 do
if ms[n].Name:find(s, 1, true) then
table.insert(t, tostring(ms[n]))
end
end
mlist.setAdapter(adapter(t))
end
}
edit.addTextChangedListener {
onTextChanged = function(c)
local s = tostring(c)
if #s == 0 then
clist.setAdapter(adapter(classes))
end
local t = {}
for k, v in ipairs(classes) do
if v:find(s, 1, true) then
table.insert(t, v)
end
end
clist.setAdapter(adapter(t))
end
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.