content stringlengths 5 1.05M |
|---|
spawnpoint 'a_m_y_cyclist_01' { x = -1037.89, y = -2738.01, z = 20.17 } |
local t = require "taptest"
local flyweightstore = require "flyweightstore"
local function diff( a, b ) return a ~= b end
t( type( flyweightstore() ), "function" )
local fly = flyweightstore()
t( type( fly( 1 )), "table" )
t( fly( 1 ), fly( 2 ), diff )
t( type( fly( 1, nil, 0/0, 3 ) ), "table" )
t( fly( 1, nil, 0/0, 3 ), fly( 1, nil, 0/0, 3 ) )
t( fly( 1, nil, 0/0, 3 ), fly( 1, nil, 0/0 ), diff )
t( fly( 1, nil, 0/0, 3 ), fly( 1, nil ), diff )
t( fly( 1, nil, 0/0, 3 ), fly( 1 ), diff )
t( fly( 1, nil, 0/0, 3 ), fly( 1, nil, 0/0, 2 ), diff )
t( fly( 1, nil, 0/0, 3 ), fly( 1, nil, 0, 3 ), diff )
t( fly( 1, nil, 0/0, 3 ), fly( 1, '', 0/0, 3 ), diff )
t( fly( 1, nil, 0/0, 3 ), fly( 4, nil, 0/0, 3 ), diff )
-- Multiple store
local alt = flyweightstore()
t( type( alt( 1, nil, 0/0, 3 )), "table" )
t( alt( 1, nil, 0/0, 3 ), alt( 1, nil, 0/0, 3 ) )
t( alt( 1, nil, 0/0, 3 ), fly( 1, nil, 0/0, 3 ), diff )
-- Garbage collection test
-- Check if the current lua version supports garbage collection metamethod
local has_gc_meta
setmetatable( {}, { __gc = function() has_gc_meta = true end } )
collectgarbage( "collect" )
local function skipon51( a, b )
if has_gc_meta then return a == b end
return true, "skipped"
end
local gccount = 0
local x = fly( true, false )
x = setmetatable( x, { __gc = function( t ) gccount = gccount + 1 end } )
-- No collection if some reference is still around
collectgarbage( "collect" )
t( gccount, 0, skipon51 )
-- Automatic collection
x = nil
collectgarbage( "collect" )
t( gccount, 1, skipon51 )
t()
|
local DemoAddon = {}
local GeminiGUI
function DemoAddon:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function DemoAddon:Init()
Apollo.RegisterAddon(self, false, "", {"Gemini:GUI-1.0"})
end
function DemoAddon:OnDependencyError(strDep, strError)
return false
end
function DemoAddon:OnLoad()
GeminiGUI = Apollo.GetPackage("Gemini:GUI-1.0").tPackage
self.wndMain = GeminiGUI:Create(self:CreateMainWindow()):GetInstance(self)
self.wndMain:Show(false)
self.wndTree = self.wndMain:FindChild("Tree")
self.wndPanelContainer = self.wndMain:FindChild("PanelContainer")
self.wndDatachronToggle = self:CreateDatachronToggleWindow()
end
------------------------------------------------------------------------------------------------------------
-- Toggle Button Functions
------------------------------------------------------------------------------------------------------------
function DemoAddon:CreateDatachronToggleWindow()
-- create a window and position it above the inventory invoke button
local tWndDef = {
WidgetType = "PushButton",
Base = "CRB_CraftingCircuitSprites:btnCircuit_Glass_GreenOrange",
AnchorPoints = { "InventoryInvoke_Left", "InventoryInvoke_Top", "InventoryInvoke_Left", "InventoryInvoke_Top" }, -- using the edge anchors from the inventory invoke window
AnchorOffsets = { 5, -45, 55, -5 },
Pixies = {
{
AnchorPoints = "CENTER",
AnchorOffsets = {-23,-25,27,25},
Sprite = "ClientSprites:sprItem_NewQuest",
},
},
Events = {
ButtonSignal = function(self)
self.wndMain:Show(true)
end
},
}
return GeminiGUI:Create(tWndDef):GetInstance(self)
end
------------------------------------------------------------------------------------------------------------
-- Tree Control Functions
------------------------------------------------------------------------------------------------------------
local tTreeNodeHandles = {}
local function PopulateTreeControl(oAddon, wndHandler, wndControl)
local tData = {
["Panel1"] = "P1",
["PanelGroup1"] = { ["Panel2"] = "P2", ["Panel3"] = "P3" },
["UnknownPanel"] = "qwerty",
}
for k,v in pairs(tData) do
local hParent = 0
hParent = wndControl:AddNode(hParent, k, nil, v)
tTreeNodeHandles[v] = hParent
if type(v) == "table" then
for k2, v2 in pairs(v) do
local hNode = wndControl:AddNode(hParent, k2, nil, v2)
tTreeNodeHandles[v2] = hNode
end
end
end
end
function DemoAddon:OnTreeSelectionChanged(wndHandler, wndControl, hSelected, hOldSelected)
if hSelected == hOldSelected then return end
-- clear the panel container
self.wndPanelContainer:DestroyChildren()
if self.wndCurrentPanel ~= nil and self.wndCurrentPanel:IsValid() then
self.wndCurrentPanel:Destroy() -- ensure the current panel is destroyed
end
local strPanelId = wndControl:GetNodeData(hSelected)
if type(strPanelId) ~= "string" then return end
if strPanelId == "P1" then
self:ShowPanel(self.CreatePanel1)
elseif strPanelId == "P2" then
self:ShowPanel(self.CreatePanel2)
elseif strPanelId == "P3" then
self:ShowPanel(self.CreatePanel3)
else
self:ShowPanel(self.CreateUnknownPanel)
end
end
------------------------------------------------------------------------------------------------------------
-- Panel3 Functions
------------------------------------------------------------------------------------------------------------
local karItemQualityColor = {
[Item.CodeEnumItemQuality.Inferior] = "ItemQuality_Inferior",
[Item.CodeEnumItemQuality.Average] = "ItemQuality_Average",
[Item.CodeEnumItemQuality.Good] = "ItemQuality_Good",
[Item.CodeEnumItemQuality.Excellent] = "ItemQuality_Excellent",
[Item.CodeEnumItemQuality.Superb] = "ItemQuality_Superb",
[Item.CodeEnumItemQuality.Legendary] = "ItemQuality_Legendary",
[Item.CodeEnumItemQuality.Artifact] = "ItemQuality_Artifact",
}
local function PopulatePanel3Grid(oAddon, wndHandler, wndControl)
local tGridData = {}
local unitPlayer = GameLib.GetPlayerUnit()
for _, itemEquipped in pairs(unitPlayer:GetEquippedItems()) do
local nQuality = itemEquipped:GetItemQuality() or 1
local tItem = {
Icon = itemEquipped:GetIcon(),
Name = itemEquipped:GetName(),
Type = itemEquipped:GetItemTypeName(),
crQuality = karItemQualityColor[nQuality],
Quality = nQuality,
}
table.insert(tGridData, tItem)
end
for idx, tRow in ipairs(tGridData) do
local iCurrRow = wndControl:AddRow("")
wndControl:SetCellData(iCurrRow, 1, tRow.Quality)
wndControl:SetCellImage(iCurrRow, 1, "WhiteFill")
wndControl:SetCellImageColor(iCurrRow, 1, tRow.crQuality)
wndControl:SetCellImage(iCurrRow, 2, tRow.Icon)
wndControl:SetCellText(iCurrRow, 3, tRow.Name)
wndControl:SetCellText(iCurrRow, 4, tRow.Type)
end
end
function DemoAddon:CreatePanel3()
return {
AnchorFill = true,
Sprite = "CRB_Basekit:kitBase_HoloBlue_InsetSimple",
Children = {
{
WidgetType = "Grid",
AnchorFill = true,
RowHeight = 32,
Columns = {
{ Name = "Qual", Width = 32, DT_VCENTER = true },
{ Name = "Icon", Width = 32, DT_VCENTER = true, SimpleSort = false, },
{ Name = "Name", Width = 260, DT_VCENTER = true },
{ Name = "Type", Width = 275, DT_VCENTER = true },
},
Events = {
WindowLoad = PopulatePanel3Grid
},
},
},
}
end
------------------------------------------------------------------------------------------------------------
-- Panel2 Functions
------------------------------------------------------------------------------------------------------------
local function ShowMessageBox(strMessage)
local tWndDef = {
AnchorFill = true,
Sprite = "BlackFill",
BGOpacity = 0.8,
SwallowMouseClicks = true,
NewWindowDepth = true,
Overlapped = true,
Children = {
{
Name = "MessageContainer",
AnchorCenter = {400, 160},
Template = "CRB_NormalFramedThin",
Border = true,
UseTemplateBG = true,
Picture = true,
Moveable = true,
Overlapped = true,
IgnoreMouse = true,
Children = {
{
Name = "Message",
Text = strMessage,
Anchor = "FILL",
AnchorOffsets = {10,10,-10,-50},
Template = "CRB_InnerWindow",
Border = true,
UseTemplateBG = true,
IgnoreMouse = true,
DT_CENTER = true,
DT_VCENTER = true,
DT_WORDBREAK = true,
},
{
WidgetType = "PushButton",
Base = "CRB_Basekit:kitBtn_List_MetalNoEdge",
AnchorPoints = {0.5,1,0.5,1},
AnchorOffsets = {-70,-50,70,-10},
Text = "Ok",
Font = "Thick",
DT_CENTER = true,
DT_VCENTER = true,
TextThemeColor = "white",
Events = {
ButtonSignal = function(self, wndHandler, wndControl)
local wnd = wndControl:GetParent():GetParent()
wnd:Destroy()
end
},
},
},
},
},
}
GeminiGUI:Create(tWndDef):GetInstance()
end
function DemoAddon:CreatePanel2()
return {
AnchorFill = true,
Sprite = "CRB_Basekit:kitBase_HoloBlue_InsetSimple",
Children = {
{
WidgetType = "PushButton",
Text = "Ooooo... Click Me!",
Anchor = "CENTER",
AnchorOffsets = {-150,40,150,70},
Events = {
ButtonSignal = function()
ShowMessageBox("Hai there! I'm a modal message box.")
end,
},
},
},
Pixies = {
{
Text = "Panel 2",
Font = "CRB_Pixel",
TextColor = "white",
AnchorPoints = "TOPRIGHT",
AnchorOffsets = {-100,10,-10,30},
DT_RIGHT = true,
},
},
}
end
------------------------------------------------------------------------------------------------------------
-- Panel1 Functions
------------------------------------------------------------------------------------------------------------
function DemoAddon:CreatePanel1()
return {
AnchorFill = true,
Sprite = "CRB_Basekit:kitBase_HoloBlue_InsetSimple",
Children = {
{
WidgetType = "PushButton",
Text = "Click Me To Go To Panel 3",
Anchor = "CENTER",
AnchorOffsets = {-150,40,150,70},
Events = {
ButtonSignal = function(self)
if tTreeNodeHandles["P3"] ~= nil then
local nOldNode = self.wndTree:GetSelectedNode()
self.wndTree:SelectNode(tTreeNodeHandles["P3"])
self:OnTreeSelectionChanged(self.wndTree, self.wndTree, tTreeNodeHandles["P3"], nOldNode)
end
end,
},
},
},
Pixies = {
{
Text = "Look at Panel 3",
Font = "CRB_FloaterGigantic_O",
TextColor = "white",
AnchorFill = true,
DT_VCENTER = true,
DT_CENTER = true,
},
{
Text = "Panel 1",
Font = "CRB_Pixel",
TextColor = "white",
AnchorPoints = "TOPRIGHT",
AnchorOffsets = {-100,10,-10,30},
DT_RIGHT = true,
},
},
}
end
------------------------------------------------------------------------------------------------------------
-- UnknownPanel Functions
------------------------------------------------------------------------------------------------------------
function DemoAddon:CreateUnknownPanel()
return {
AnchorFill = true,
Sprite = "WhiteFill",
BGColor = "xkcdAzure",
Border = true,
Pixies = {
{
Text = "Unknown Panel Selected",
Font = "CRB_FloaterGigantic_O",
TextColor = "white",
Rotation = -45,
AnchorFill = true,
DT_VCENTER = true,
DT_CENTER = true,
},
{
Text = "Unknown Panel",
Font = "CRB_Pixel",
TextColor = "white",
AnchorPoints = "TOPRIGHT",
AnchorOffsets = {-100,10,-10,30},
DT_RIGHT = true,
},
},
}
end
------------------------------------------------------------------------------------------------------------
-- Panel Setup Functions
------------------------------------------------------------------------------------------------------------
function DemoAddon:ShowPanel(fnCreatePanel)
if type(fnCreatePanel) ~= "function" then
return
end
-- create the panel definition table
local tPanelDef = fnCreatePanel(self)
if tPanelDef ~= nil then
-- create the panel and add it to the panel container
self.wndCurrentPanel = GeminiGUI:Create(tPanelDef):GetInstance(self, self.wndPanelContainer)
self.wndCurrentPanel:Show(true)
end
end
------------------------------------------------------------------------------------------------------------
-- Main Window Functions
------------------------------------------------------------------------------------------------------------
function DemoAddon:CreateMainWindow()
local tWndDefinition = {
Name = "DemoAddonMainWindow",
Template = "CRB_TooltipSimple",
UseTemplateBG = true,
Picture = true,
Moveable = true,
Border = true,
AnchorCenter = {900, 660},
Pixies = {
{
Line = true,
AnchorPoints = "HFILL", -- will be translated to {0,0,1,0},
AnchorOffsets = {0,30,0,30},
Color = "white",
},
{
Sprite = "Collections_TEMP:sprCollections_TEMP_DatacubeOn",
AnchorPoints = "BOTTOMRIGHT", -- will be translated to {1,1,1,1},
AnchorOffsets = {-220, -110, -25, -10 },
},
{
Text = "GeminiGUI-1.0 Example Addon",
Font = "CRB_HeaderHuge",
TextColor = "xkcdYellow",
AnchorPoints = "HFILL",
DT_CENTER = true,
DT_VCENTER = true,
AnchorOffsets = {0,0,0,20},
},
},
Children = {
{
WidgetType = "PushButton",
AnchorPoints = "TOPRIGHT", -- will be translated to { 1, 0, 1, 0 }
AnchorOffsets = { -17, -3, 3, 17 },
Base = "CRB_Basekit:kitBtn_Holo_Close",
NoClip = true,
Events = {
ButtonSignal = function(_, wndHandler, wndControl) -- anonymous function for an event handler
wndControl:GetParent():Close()
end,
},
},
{ -- Tree Control
Name = "Tree", -- Set a name for the widget so we can find it with FindChild() (see OnLoad)
WidgetType = "TreeControl",
AnchorPoints = {0,0,0,1}, -- If AnchorPoints is not provided, defaults to "TOPLEFT" or {0,0,0,0}
AnchorOffsets = {20,50,220,-20},
VScroll = true,
AutoHideScroll = true,
Events = {
WindowLoad = PopulateTreeControl, -- Use a local function
TreeSelectionChanged = "OnTreeSelectionChanged", -- Use a function on the addon (since addon is the event handler host for this window)
},
},
{
Name = "PanelContainer",
AnchorPoints = "FILL", -- will be translated to { 0, 0, 1, 1 }
AnchorOffsets = {230,50,-20,-20},
},
},
}
return tWndDefinition
end
------------------------------------------------------------------------------------------------------------
-- Addon Instantiation
------------------------------------------------------------------------------------------------------------
local DemoAddonInst = DemoAddon:new()
DemoAddonInst:Init()
|
-- common grenade projectile code
AddCSLuaFile()
ENT.Type = "anim"
ENT.Model = Model("models/weapons/w_eq_flashbang_thrown.mdl")
AccessorFunc( ENT, "thrower", "Thrower")
function ENT:SetupDataTables()
self:NetworkVar("Float", 0, "ExplodeTime")
end
function ENT:Initialize()
self:SetModel(self.Model)
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_BBOX)
self:SetCollisionGroup(COLLISION_GROUP_PROJECTILE)
if SERVER then
self:SetExplodeTime(0)
end
end
function ENT:SetDetonateTimer(length)
self:SetDetonateExact( CurTime() + length )
end
function ENT:SetDetonateExact(t)
self:SetExplodeTime(t or CurTime())
end
function ENT:Explode(tr)
if SERVER then
local pull = ents.Create( "gw_ability_wall" )
if not IsValid( pull ) then self:Remove() return end
pull:SetPos( self:GetPos() + Vector(0, 0, 75) )
pull:Spawn()
pull:Activate()
pull:EmitSound("ambient/levels/labs/electric_explosion1.wav", 200)
SafeRemoveEntityDelayed( pull, 5)
self:Remove()
end
end
function ENT:Think()
local etime = self:GetExplodeTime() or 0
if etime ~= 0 and etime < CurTime() then
-- if thrower disconnects before grenade explodes, just don't explode
if SERVER and not IsValid(self:GetThrower()) then
self:Remove()
etime = 0
return
end
self:Explode()
end
end
|
local cjson = require("cjson")
local io = io
local ngx = ngx
local table = table
local type = type
local next = next
local pcall = pcall
local M = {}
require("foxcaves.module_helper").setmodenv()
function M.register_shutdown(func)
if not ngx.ctx.shutdown_funcs then
ngx.ctx.shutdown_funcs = {}
end
table.insert(ngx.ctx.shutdown_funcs, func)
end
function M.__on_shutdown()
if not ngx.ctx.shutdown_funcs then
return
end
for _, v in next, ngx.ctx.shutdown_funcs do
v()
end
ngx.ctx.shutdown_funcs = nil
end
local repTbl = {
["&"] = "&",
["<"] = "<",
[">"] = ">",
}
function M.escape_html(str)
if (not str) or type(str) ~= "string" then
return str
end
str = str:gsub("[&<>]", repTbl)
return str
end
function M.get_body_data()
ngx.req.read_body()
local data = ngx.req.get_body_data()
if not data then
local f = ngx.req.get_body_file()
if not f then
return
end
local fh, _ = io.open(f, "r")
data = fh:read("*a")
fh:close()
end
return data
end
function M.get_post_args()
local ctype = ngx.var.http_content_type
if ctype and ctype:lower() == "application/json" then
local data = M.get_body_data()
local ok, res = pcall(cjson.decode, data)
if not ok then
return {}
end
return res or {}
end
ngx.req.read_body()
return ngx.req.get_post_args() or {}
end
function M.api_error(error, code)
return { error = error }, (code or 400)
end
function M.explode(div,str) -- credit: http://richard.warburton.it
local pos, arr = 0, {}
-- for each divider found
for st, sp in function() return str:find(div,pos,true) end do
table.insert(arr,str:sub(pos,st-1)) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr, str:sub(pos)) -- Attach chars right of last divider
return arr
end
function M.is_falsy_or_null(v)
return (not v) or v == ngx.null
end
function M.shorten_string(str, len)
local curlen = str:len()
if curlen <= len then
return str, curlen
end
return str:sub(1, len), len
end
return M
|
-- include useful files
u_execDependencyScript("ohvrvanilla", "base", "vittorio romeo", "utils.lua")
u_execDependencyScript("ohvrvanilla", "base", "vittorio romeo", "common.lua")
u_execDependencyScript("ohvrvanilla", "base", "vittorio romeo", "commonpatterns.lua")
extra = 0
level = 1
incrementTime = 5
achievementUnlocked = false
hardAchievementUnlocked = false
-- onLoad is an hardcoded function that is called when the level is started/restarted
function onLoad()
e_messageAddImportant("level: "..(extra + 1).." / time: "..incrementTime, 170)
end
-- onStep is an hardcoded function that is called when the level timeline is empty
-- onStep should contain your pattern spawning logic
function onStep()
rWallEx(getRandomSide(), extra)
t_wait(getPerfectDelayDM(THICKNESS) * 6)
end
-- onInit is an hardcoded function that is called when the level is first loaded
function onInit()
l_setSpeedMult(2.25)
l_setSpeedInc(0.0)
l_setRotationSpeed(0.0)
l_setRotationSpeedMax(0.0)
l_setRotationSpeedInc(0.0)
l_setDelayMult(1.0)
l_setDelayInc(0.0)
l_setFastSpin(0.0)
l_setSides(4)
l_setSidesMin(0)
l_setSidesMax(0)
l_setIncTime(5)
l_setPulseMin(75)
l_setPulseMax(91)
l_setPulseSpeed(2)
l_setPulseSpeedR(1)
l_setPulseDelayMax(0.8275)
l_setBeatPulseMax(17)
l_setBeatPulseDelayMax(24.8275) -- BPM is 145
l_addTracked("level", "level")
l_enableRndSideChanges(false)
end
-- onIncrement is an hardcoded function that is called when the level difficulty is incremented
function onIncrement()
a_playSound("beep.ogg")
extra = extra + 1
level = extra + 1
incrementTime = incrementTime + 2
if not achievementUnlocked and level == 7 and u_getDifficultyMult() >= 1 then
steam_unlockAchievement("a5_commando")
achievementUnlocked = true
end
if not hardAchievementUnlocked and level == 6 and u_getDifficultyMult() > 1 then
steam_unlockAchievement("a29_commando_hard")
hardAchievementUnlocked = true
end
l_setSides(l_getSides() + 2)
l_setIncTime(incrementTime)
e_messageAddImportant("level: "..(extra + 1).." / time: "..incrementTime, 170)
end
-- onUnload is an hardcoded function that is called when the level is closed/restarted
function onUnload()
end
-- onUpdate is an hardcoded function that is called every frame
function onUpdate(mFrameTime)
end
|
local addonName, wc = ...
--公共函数
--输出,自动解定身减速,考虑延迟,弃用
function dps_old(cost, mana)
if not wc.strongControl and wc.enoughMana(mana) and (wc.needUnroot() or wc.ableShift() and not wc.enoughEnergywithNextTick(cost)) then
SetCVar('autoUnshift', 1)
else
SetCVar('autoUnshift', 0)
end
end
--输出,自动解定身减速,考虑延迟和能量延迟
function dps(cost, mana)
if not wc.strongControl and wc.enoughMana(mana) and (wc.needUnroot() or wc.ableShift() and not wc.enoughEnergywithNextTickwithDelay(cost)) then
SetCVar('autoUnshift', 1)
else
SetCVar('autoUnshift', 0)
end
end
--dpsp加到默认dps,原先dps弃用
function dpsp(cost, mana)
dps(cost, mana)
end
--输出,自动解定身减速,不考虑延迟
function dpsx(cost, mana)
if not wc.strongControl and wc.enoughMana(mana) and (wc.needUnroot() or not wc.getShiftGCD() and not wc.enoughEnergywithNextTick(cost)) then
SetCVar('autoUnshift', 1)
else
SetCVar('autoUnshift', 0)
end
end
--输出,自动解定身减速,考虑延迟,省蓝
function dpsl(cost, mana)
if not wc.strongControl and wc.enoughMana(mana) and (wc.needUnroot() or wc.ableShift() and not wc.enoughEnergy(cost-20)) then
SetCVar('autoUnshift', 1)
else
SetCVar('autoUnshift', 0)
end
end
--变身
function shift(r, e, m)
r = r or 200
e = e or 200
if not wc.strongControl and wc.enoughMana(m) and not wc.getShiftGCD() and (wc.needUnroot() or wc.getRage() < r and wc.getEnergy() < e) then
SetCVar('autoUnshift', 1)
else
SetCVar('autoUnshift', 0)
end
end
--吃蓝,考虑延迟
function manapot(cost, name)
if not wc.ableShift() or wc.enoughEnergywithNextTick(cost) or wc.strongControl or (UnitPowerMax('player', 0) - UnitPower('player', 0)) < 3000 or GetItemCooldown(GetItemInfoInstant(name)) > 0 or GetItemCount(name) == 0 then
SetCVar('autoUnshift', 0)
else
SELECTED_CHAT_FRAME:AddMessage('吃蓝啦!')
SetCVar('autoUnshift', 1)
end
end
--老款吃蓝,不考虑延迟
function manapotx(cost, name)
if wc.getShiftGCD() or wc.enoughEnergywithNextTick(cost) or wc.strongControl or (UnitPowerMax('player', 0) - UnitPower('player', 0)) < 3000 or GetItemCooldown(GetItemInfoInstant(name)) > 0 or GetItemCount(name) == 0 then
SetCVar('autoUnshift', 0)
else
SetCVar('autoUnshift', 1)
end
end
--吃红
--9634巨熊形态
function hppot()
local u,n = IsUsableSpell(9634)
if wc.getShiftGCD() or wc.strongControl or not u
then SetCVar('autoUnshift', 0)
else
SetCVar('autoUnshift', 1)
end
end
--结束
function wcEnd()
SetCVar('autoUnshift', 1)
UIErrorsFrame:Clear()
end
|
local KUI, E, L, V, P, G = unpack(select(2, ...))
local KS = KUI:GetModule("KuiSkins")
local S = E:GetModule("Skins")
-- Cache global variables
-- Lua functions
local _G = _G
local select = select
-- WoW API
-- Global variables that we don't cache, list them here for the mikk's Find Globals script
-- GLOBALS:
local function styleDebugTools()
if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.debug ~= true or E.private.KlixUI.skins.blizzard.debug ~= true then return end
local r, g, b = unpack(E["media"].rgbvaluecolor)
local EventTraceFrame = _G["EventTraceFrame"]
EventTraceFrame:Styling()
-- Table Attribute Display
local function reskinTableAttribute(frame)
frame:Styling()
end
reskinTableAttribute(TableAttributeDisplay)
hooksecurefunc(TableInspectorMixin, "InspectTable", function(self)
reskinTableAttribute(self)
end)
end
S:AddCallbackForAddon("Blizzard_DebugTools", "KuiDebugTools", styleDebugTools) |
-- lua-lru, LRU cache in Lua
-- Copyright (c) 2015 Boris Nagaev
-- See the LICENSE file for terms of use.
local cut
local setNewest
local del
local makeFreeSpace
local mynext
local lru = {}
lru.__index = lru
lru.__pairs = function()
return mynext, nil, nil
end
function lru.new(max_size, max_bytes)
local self = setmetatable({}, lru)
self._size = 0
self._bytes_used = 0
self._map = {}
self._VALUE = 1
self._PREV = 2
self._NEXT = 3
self._KEY = 4
self._BYTES = 5
self._newest = nil
self._oldest = nil
self._removed_tuple = nil
cut = function(tuple)
local tuple_prev = tuple[self._PREV]
local tuple_next = tuple[self._NEXT]
tuple[self._PREV] = nil
tuple[self._NEXT] = nil
if tuple_prev and tuple_next then
tuple_prev[self._NEXT] = tuple_next
tuple_next[self._PREV] = tuple_prev
elseif tuple_prev then
-- tuple is the oldest element
tuple_prev[self._NEXT] = nil
self._oldest = tuple_prev
elseif tuple_next then
-- tuple is the newest element
tuple_next[self._PREV] = nil
self._newest = tuple_next
else
-- tuple is the only element
self._newest = nil
self._oldest = nil
end
end
setNewest = function(tuple)
if not self._newest then
self._newest = tuple
self._oldest = tuple
else
tuple[self._NEXT] = self._newest
self._newest[self._PREV] = tuple
self._newest = tuple
end
end
del = function(key, tuple)
self._map[key] = nil
cut(tuple)
self._size = self._size - 1
self._bytes_used = self._bytes_used - (tuple[self._BYTES] or 0)
self._removed_tuple = tuple
end
makeFreeSpace = function(bytes)
while self._size + 1 > max_size or
(max_bytes and self._bytes_used + bytes > max_bytes)
do
assert(self._oldest, "not enough storage for cache")
del(self._oldest[self._KEY], self._oldest)
end
end
mynext = function(_, prev_key)
local tuple
if prev_key then
tuple = self._map[prev_key][self._NEXT]
else
tuple = self._newest
end
if tuple then
return tuple[self._KEY], tuple[self._VALUE]
else
return nil
end
end
return self
end
function lru:get(_, key)
local tuple = self._map[key]
if not tuple then
return nil
end
cut(tuple)
setNewest(tuple)
return tuple[self._VALUE]
end
function lru:set(_, key, value, bytes)
local tuple = self._map[key]
if tuple then
del(key, tuple)
end
if value ~= nil then
-- the value is not removed
bytes = self._max_bytes and (bytes or #value) or 0
makeFreeSpace(bytes)
local tuple1 = self._removed_tuple or {}
self._map[key] = tuple1
tuple1[self._VALUE] = value
tuple1[self._KEY] = key
tuple1[self._BYTES] = self._max_bytes and bytes
self._size = self._size + 1
self._bytes_used = self._bytes_used + bytes
setNewest(tuple1)
else
assert(key ~= nil, "Key may not be nil")
end
self._removed_tuple = nil
end
function lru:delete(_, key)
return self:set(_, key, nil)
end
return lru
|
-- Copyright (C) 2017 Deyan Dobromirov
-- Signal processing functionalities library
if not debug.getinfo(3) then
print("This is a module to load with `local signals = require('signals')`.")
os.exit(1)
end
local tonumber = tonumber
local tostring = tostring
local type = type
local setmetatable = setmetatable
local math = math
local bit = bit
local signals = {}
local metaSignals = {}
local common = require("common")
local complex = require("complex")
local revArr = common.tableArrReverse
local byteSTR = common.bytesGetString
local byteUINT = common.bytesGetNumber
local byteMirr = common.binaryMirror
local isNumber = common.isNumber
local isNil = common.isNil
local logStatus = common.logStatus
local toBool = common.toBool
local isTable = common.isTable
local getSign = common.getSign
local binaryIsPower = common.binaryIsPower
local binaryNextBaseTwo = common.binaryNextBaseTwo
local tableArrTransfer = common.tableArrTransfer
local randomSetSeed = common.randomSetSeed
local randomGetNumber = common.randomGetNumber
local getPick = common.getPick
local binaryNeededBits = common.binaryNeededBits
local binaryMirror = common.binaryMirror
local isFunction = common.isFunction
local logConcat = common.logConcat
local logString = common.logString
local stringPadL = common.stringPadL
local stringPadR = common.stringPadR
local getDerivative = common.getDerivative
local tableClear = common.tableClear
local getClamp = common.getClamp
local getMargin = common.getMargin
local getAngNorm = common.getAngNorm
-- This holds header and format definition location
metaSignals["WAVE_HEADER"] = {
{
Name = "HEADER",
{"sGroupID" , 4, byteSTR , "char/4"},
{"dwFileLength", 4, byteUINT, "uint" },
{"sRiffType" , 4, byteSTR , "char/4"}
},
{
Name = "FORMAT",
{"sGroupID" , 4, byteSTR , "char/4" },
{"dwChunkSize" , 4, byteUINT, "uint" },
{"wFormatTag" , 2, byteUINT, "ushort" },
{"wChannels" , 2, byteUINT, "ushort" },
{"dwSamplesPerSec" , 4, byteUINT, "uint" },
{"dwAvgBytesPerSec", 4, byteUINT, "uint" }, -- sampleRate * blockAlign
{"wBlockAlign" , 2, byteUINT, "ushort" },
{"dwBitsPerSample" , 2, byteUINT, "uint" }
},
{
Name = "DATA",
{"sGroupID" , 4, byteSTR , "char/4"},
{"dwChunkSize" , 4, byteUINT, "uint" }
}
}
metaSignals["REALNUM_UNIT"] = complex.getNew(1, 0)
metaSignals["IMAGINE_UNIT"] = complex.getNew(0, 1)
metaSignals["COMPLEX_VEXP"] = complex.getNew(math.exp(1))
metaSignals["WIN_FLATTOP"] = {0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368}
metaSignals["WIN_NUTTALL"] = {0.36358190, 0.48917750, 0.136599500, 0.010641100}
metaSignals["WIN_BLKHARR"] = {0.35875000, 0.48829000, 0.141280000, 0.011680000}
metaSignals["DFT_PHASEFCT"] = {__top = 0}
-- Read an audio WAVE file giving the path /sN/
function signals.readWave(sN)
local fW, sE = io.open(tostring(sN or ""), "rb")
if(not fW) then return logStatus("signals.readWave: "..sE) end
local wData, hWave = {}, metaSignals["WAVE_HEADER"]
for I = 1, #hWave do local tdtPar = hWave[I]
wData[tdtPar.Name] = {}
local curChunk = wData[tdtPar.Name]
for J = 1, #tdtPar do local par = tdtPar[J]
local nam, arr, foo, typ = par[1], par[2], par[3], par[4]
curChunk[nam] = {}; local arrChunk = curChunk[nam]
for K = 1, arr do arrChunk[K] = fW:read(1):byte() end
if(typ == "uint" or typ == "ushort") then revArr(arrChunk) end
if(foo) then curChunk[nam] = foo(arrChunk, arr) end
end
end; local gID
gID = wData["HEADER"]["sGroupID"]
if(gID ~= "RIFF") then return logStatus("signals.readWave: Header mismatch <"..gID..">") end
gID = wData["HEADER"]["sRiffType"]
if(gID ~= "WAVE") then return logStatus("signals.readWave: Header not wave <"..gID..">") end
gID = wData["FORMAT"]["sGroupID"]
if(gID ~= "fmt ") then return logStatus("signals.readWave: Format invalid <"..gID..">") end
gID = wData["DATA"]["sGroupID"]
if(gID ~= "data") then return logStatus("signals.readWave: Data invalid <"..gID..">") end
local smpData = {}
local smpByte = (wData["FORMAT"]["dwBitsPerSample"] / 8)
local smpAll = wData["DATA"]["dwChunkSize"] / (smpByte * wData["FORMAT"]["wChannels"])
local totCnan = wData["FORMAT"]["wChannels"]
local curChan, isEOF = 1, false
wData["FORMAT"]["fDuration"] = smpAll / wData["FORMAT"]["dwSamplesPerSec"]
wData["FORMAT"]["fBitRate"] = smpAll * totCnan * wData["FORMAT"]["dwBitsPerSample"]
wData["FORMAT"]["fBitRate"] = wData["FORMAT"]["fBitRate"] / wData["FORMAT"]["fDuration"]
wData["FORMAT"]["fDataFill"] = 100 * (wData["DATA"]["dwChunkSize"] / wData["HEADER"]["dwFileLength"])
wData["DATA"]["dwSamplesPerChan"] = smpAll
while(not isEOF and smpAll > 0) do
if(curChan > totCnan) then curChan = 1 end
if(not smpData[curChan]) then smpData[curChan] = {__top = 1} end
local arrChan = smpData[curChan]
arrChan[arrChan.__top] = {}
local smpTop = arrChan[arrChan.__top]
for K = 1, smpByte do
local smp = fW:read(1)
if(not smp) then
logStatus("signals.readWave: Reached EOF for channel <"..curChan.."> sample <"..arrChan.__top..">")
isEOF = true; arrChan[arrChan.__top] = nil; break
end
smpTop[K] = smp:byte()
end
if(not isEOF) then
if(smpByte == 1) then
arrChan[arrChan.__top] = (byteUINT(smpTop) - 128) / 128
elseif(smpByte == 2) then -- Two bytes per sample
arrChan[arrChan.__top] = (byteUINT(smpTop) - 32760) / 32760
end
if(curChan == 1) then smpAll = smpAll - 1 end
arrChan.__top = arrChan.__top + 1
curChan = curChan + 1
else
logStatus("signals.readWave: Reached EOF before chunk size <"..smpAll..">")
smpAll = -1
end
end; fW:close()
return wData, smpData
end
-- Generate ramp signal
function signals.getRamp(nS, nE, nD)
local tS, iD = {}, 1; for dD = nS, nE, nD do
tS[iD] = dD; iD = iD + 1 end; return tS
end
-- Generate periodical signal
function signals.setWave(tD, fW, nW, tT, nT, tS, nA, nB)
local nA, nB = (tonumber(nA) or 1), (tonumber(nB) or 1)
local nT, iD = (tonumber(nT) or 0), 1; while(tT[iD]) do
local vS = (tS and tS[iD]); vS = (vS and tS[iD] or 0)
tD[iD] = nA*vS + nB*fW(nW * tT[iD] + nT); iD = (iD+1)
end; return tD
end
-- Weights the signal trough the given window
function signals.setWeight(tD, tS, tW, tA, tB)
local bW, bA, bB = isNumber(tW), isNumber(tA), isNumber(tB)
local iD = 1; while(tS[iD]) do
local mW = (bW and tW or (tW and tonumber(tW[iD]) or 1))
local mA = (bA and tA or (tA and tonumber(tA[iD]) or 0))
local mB = (bB and tB or (tB and tonumber(tB[iD]) or 1))
tD[iD] = tS[iD] * mW + mA * mB; iD = (iD+1)
end; return tD
end
function signals.convCircleToLineFrq(nW)
return (nW / (2 * math.pi))
end
function signals.convLineToCircleFrq(nF)
return (2 * math.pi * nF)
end
function signals.convPeriodToLineFrq(nT)
return (1 / nT)
end
function signals.convLineFrqToPeriod(nF)
return (1 / nF)
end
-- Extend the signal by making a copy
function signals.getExtendBaseTwo(tS)
local nL, tO = #tS, {}; if(binaryIsPower(nL)) then
tableArrTransfer(tO, tS); return tO end
local nT = binaryNextBaseTwo(nL)
for iD = 1, nT do local vS = tS[iD]
if(vS) then tO[iD] = vS else tO[iD] = 0 end end; return tO
end
-- Extend the signal without making a copy
function signals.setExtendBaseTwo(tS) local nL = #tS
if(binaryIsPower(nL)) then return tS end
local nS, nE = (nL+1), binaryNextBaseTwo(nL)
for iD = nS, nE do tS[iD] = 0 end; return tS
end
-- Blackman window of length N
function signals.winBlackman(nN)
local nK = (2 * math.pi / (nN-1))
local tW, nN = {}, (nN-1)
for iD = 1, (nN+1) do local nP = nK*(iD-1)
tW[iD] = 0.42 - 0.5*math.cos(nP) + 0.08*math.cos(2*nP)
end; return tW
end
-- Hamming window of length N
function signals.winHamming(nN)
local tW, nN = {}, (nN-1)
local nK = (2 * math.pi / nN)
for iD = 1, (nN+1) do
tW[iD] = 0.54 - 0.46 * math.cos(nK * (iD - 1))
end; return tW
end
-- Gauss window of length N
function signals.winGauss(nN, vA)
local nA = getPick(vA, vA, 2.5)
local tW, nN = {}, (nN - 1)
local N2, nK = (nN / 2), (2*nA / (nN-1))
for iD = 1, (nN+1) do
local pN = nK*(iD - N2 - 1)
tW[iD] = math.exp(-0.5 * pN^2)
end; return tW
end
-- Barthann window of length N
function signals.winBarthann(nN)
local tW, nN = {}, (nN-1)
for iD = 1, (nN+1) do
local pN = (((iD-1) / nN) - 0.5)
tW[iD] = 0.62 - 0.48*math.abs(pN) + 0.38*math.cos(2*math.pi*pN)
end; return tW
end
-- Sinewave window of length N
function signals.winSine(nN)
local tW, nN = {}, (nN-1)
local nK = math.pi/nN
for iD = 1, (nN+1) do
tW[iD] = math.sin(nK*(iD-1))
end; return tW
end
-- Parabolic window of length N
function signals.winParabolic(nN)
local tW, nN = {}, (nN-1)
local nK = nN/2
for iD = 1, (nN+1) do
tW[iD] = 1-(((iD-1)-nK)/nK)^2
end; return tW
end
-- Hanning window of length N
function signals.winHann(nN)
local tW, nN = {}, (nN - 1)
local nK = (2 * math.pi / nN)
for iD = 1, (nN+1) do
local pN = (((iD-1) / nN) - 0.5)
tW[iD] = 0.5*(1-math.cos(nK*(iD-1)))
end; return tW
end
-- Flattop window of length N
function signals.winFlattop(nN,...)
local tP, tA = {...}, metaSignals["WIN_FLATTOP"]
for iD = 1, 5 do local vP = tP[iD]
tP[iD] = getPick(vP, vP, tA[iD]) end
local nN, tW = (nN - 1), {}
local nK = ((2 * math.pi) / nN)
for iD = 1, (nN+1) do local nM, nS = tP[1], 1
for iK = 2, 5 do nS = -nS
nM = nM + nS * tP[iK] * math.cos(nK * (iK-1) * (iD-1))
end; tW[iD] = nM
end; return tW
end
-- Triangle window of length N
function signals.winTriangle(nN)
local tW, nK, nS, nE = {}, 2/(nN-1), 1, nN
tW[nS], tW[nE] = 0, 0
nS, nE = (nS + 1), (nE - 1)
while(nS <= nE) do
tW[nS] = tW[nS-1] + nK
tW[nE] = tW[nE+1] + nK
nS, nE = (nS + 1), (nE - 1)
end; return tW
end
-- Nuttall window of length N
function signals.winNuttall(nN,...)
local tP, tA = {...}, metaSignals["WIN_NUTTALL"]
for iD = 1, 4 do local vP = tP[iD]
tP[iD] = getPick(vP, vP, tA[iD]) end
local nN, tW = (nN - 1), {}
local nK = ((2 * math.pi) / nN)
for iD = 1, (nN+1) do
local nM, nS = tP[1], 1
for iK = 2, 4 do nS = -nS
nM = nM + nS * tP[iK] * math.cos(nK * (iK-1) * (iD-1))
end; tW[iD] = nM
end; return tW
end
-- Blackman-Harris window of length N
function signals.winBlackHarris(nN,...)
local tP, tA = {...}, metaSignals["WIN_BLKHARR"]
for iD = 1, 4 do local vP = tP[iD]
tP[iD] = getPick(vP, vP, tA[iD]) end
local nN, tW = (nN - 1), {}
local nK = ((2 * math.pi) / nN)
for iD = 1, (nN+1) do
local nM, nS = tP[1], 1
for iK = 2, 4 do nS = -nS
nM = nM + nS * tP[iK] * math.cos(nK * (iK-1) * (iD-1))
end; tW[iD] = nM
end; return tW
end
-- Exponential/Poisson window of length N
function signals.winPoisson(nN, nD)
local nD, tW = (nD or 8.69), {}
local nT, nN = (2*nD)/(8.69*nN), (nN-1)
local N2 = (nN/2); for iD = 1, (nN+1) do
tW[iD] = math.exp(-nT*math.abs((iD-1)-N2))
end; return tW
end
-- Calculates the DFT phase factor single time
function signals.getPhaseFactorDFT(nK, nN)
if(nK == 0) then
return metaSignals["REALNUM_UNIT"]:getNew() end
local cE = metaSignals["COMPLEX_VEXP"]
local cI = metaSignals["IMAGINE_UNIT"]
local cK = cI:getNew(-2 * math.pi * nK, 0)
return cE:getPow(cK:Mul(cI):Div(2^nN, 0))
end
-- Removes the DFT phase factor for realtime
function signals.remPhaseFactorDFT(bG)
local tW = metaSignals["DFT_PHASEFCT"]
for iK, vV in pairs(tW) do tW[iK] = nil end
tW.__top = 0; if(bG) then
collectgarbage() end; return tW
end
-- Caches the DFT phase factor for realtime
function signals.setPhaseFactorDFT(nN)
local tW = signals.remPhaseFactorDFT()
local gW = signals.getPhaseFactorDFT
local nR = binaryNeededBits(nN-1)
for iD = 1, (nN/2) do tW[iD] = gW(iD-1, nR) end
tW.__top = #tW; return tW
end
-- Converts from phase number and butterfly count to index
local function convIndexDFT(iP, iA, N2)
local nT = (2^(iP - 1))
local nI = ((iA / nT) * N2)
return (math.floor(nI % N2) + 1)
end
function signals.getForwardDFT(tS)
local cZ = complex.getNew()
local aW = metaSignals["DFT_PHASEFCT"]
local tF = signals.getExtendBaseTwo(tS)
local nN, iM, tA, bW = #tF, 1, {}, (aW.__top > 0)
local tW = getPick(bW, aW, {})
for iD = 1, nN do tF[iD] = cZ:getNew(tF[iD]) end
local nR, N2 = binaryNeededBits(nN-1), (nN / 2)
for iD = 1, nN do tA[iD] = cZ:getNew()
local mID = (binaryMirror(iD-1, nR) + 1)
tA[iD]:Set(tF[mID]); if(not bW and iD <= N2) then
tW[iD] = signals.getPhaseFactorDFT(iD-1, nR) end
end; local cT = cZ:getNew()
for iP = 1, nR do -- Generation of tF in phase iP
for iK = 1, nN do -- Write down the cached phase factor
cT:Set(tW[convIndexDFT(iP, bit.band(iK-1, iM-1), N2)])
if(bit.band(iM, iK-1) ~= 0) then local iL = iK - iM
tF[iK]:Set(tA[iL]):Sub(cT:Mul(tA[iK]))
else local iL = iK + iM
tF[iK]:Set(tA[iK]):Add(cT:Mul(tA[iL]))
end -- One butterfly is completed
end; for iD = 1, nN do tA[iD]:Set(tF[iD]) end
iM = bit.lshift(iM, 1)
end; return tA
end
-- https://stevenmiller888.github.io/mind-how-to-build-a-neural-network/
-- Column /A/ is for activation
-- Column /V/ is the activated value
-- newNeuralNet: Class neural network manager
local metaNeuralNet = {}
metaNeuralNet.__index = metaNeuralNet
metaNeuralNet.__type = "signals.neuralnet"
metaNeuralNet.__metatable = metaNeuralNet.__type
metaNeuralNet.__tostring = function(oNet) return oNet:getString() end
local function newNeuralNet(sName)
local self = {}; setmetatable(self, metaNeuralNet)
local mtData, mID, mName = {}, 1, tostring(sName or "NET")
local mfAct, mfOut, mtSum = nil, nil, {}; randomSetSeed()
local mfTran = function(nX) return nX end
function self:upLast(tE)
local iD = (mID - 1); tableClear(mtSum)
local tX = mtData[iD]; if(isNil(tX)) then
return logStatus("newNeuralNet/upLast: Missing next #"..tostring(vL), self) end
local tP = mtData[iD-1]; if(isNil(tP)) then
return logStatus("newNeuralNet/upLast: Missing prev #"..tostring(vL), self) end
for kE = 1, #tX.W do
mtSum[kE] = getDerivative(tX.A[kE], mfAct) * (tE[kE] - tX.V[kE])
for kI = 1, #tP.V do tX.D[kE][kI] = 0 end
for kI = 1, #tP.V do
tX.D[kE][kI] = tX.D[kE][kI] + (mtSum[kE] / tP.V[kI])
end
end; return self
end
-- Determine the delta hidden sum
function self:upRest()
local iD = (mID-1)
local tC = mtData[iD]; if(isNil(tC)) then
return logStatus("newNeuralNet/upRest: Missing curr #"..tostring(vL), self) end
local tX = mtData[iD-1]; if(isNil(tX)) then
return logStatus("newNeuralNet/upRest: Missing next #"..tostring(vL), self) end
local tP = mtData[iD-2]; if(isNil(tP)) then
return logStatus("newNeuralNet/upRest: Missing prev #"..tostring(vL), self) end
while(tX and tP) do
for iS = 1, #mtSum do
for iX = 1, #tX.V do for iP = 1, #tP.V do
print("tX.D["..iX.."]["..iP.."]", tX.A[iX], getDerivative(tX.A[iX], mfAct), tX.V[iX])
tX.D[iX][iP] = tX.D[iX][iP] + (mtSum[iS] / tC.W[iS][iX] * getDerivative(tX.A[iX], mfAct)) / (tP.A[iP] * #mtSum)
end end
end; iD = iD - 1
tC, tX, tP = mtData[iD], mtData[iD-1], mtData[iD-2];
end; return self
end
function self:resDelta()
local iD = 2; while(iD < mID) do
local dD = mtData[iD].D
for iK = 1, #dD do local tD = dD[iK]
for iN = 1, #tD do tD[iN] = 0 end
end; iD = iD + 1
end; return self
end
function self:appDelta()
local iD = 2; while(iD < mID) do
local dD, dW = mtData[iD].D, mtData[iD].W
for iK = 1, #dD do local tD, tW = dD[iK], dW[iK]
for iN = 1, #tD do tW[iN] = tW[iN] + tD[iN] end
end; iD = iD + 1
end; return self
end
function self:addLayer(...)
local tArg = {...}; nArg = #tArg;
mtData[mID] = {}; mtData[mID].V = {}; mtData[mID].A = {}
if(mID > 1) then mtData[mID].W, mtData[mID].D = {}, {} end
for k = 1, #tArg do
if(not isTable(tArg[k])) then
return logStatus("newNeuralNet.addLayer: Weight #"..tostring(k).." not table", self) end
mtData[mID].V[k], mtData[mID].A[k] = 0, 0
if(mID > 1) then mtData[mID].W[k], mtData[mID].D[k] = {}, {}
for i = 1, #(mtData[mID-1].V) do mtData[mID].D[k][i] = 0
mtData[mID].W[k][i] = (tArg[k][i] or randomGetNumber()) end
end
end; mID = mID + 1; return self
end
function self:getString()
return ("["..metaNeuralNet.__type.."]: "..mName)
end
function self:remLayer()
mtData[mID] = nil; mID = (mID - 1); return self
end
function self:Process()
for iK = 2, (mID-1) do
local tNL, tPL = mtData[iK], mtData[iK-1]
for nID = 1, #tNL.A do tNL.A[nID], tNL.V[nID] = 0, 0
for pID = 1, #tPL.V do tNL.A[nID] = tNL.A[nID] + tNL.W[nID][pID] * tPL.V[pID]
end; tNL.V[nID] = mfAct(tNL.A[nID])
end
end; return self
end
function self:getOut(bOv)
if(mID < 2) then return {} end
local tV, vO = mtData[mID-1].V
if(bOv and mfOut) then vO = mfOut(tV)
else vO = {}; for k = 1, #tV do table.insert(vO, tV[k]) end
end; return vO
end
function self:setValue(...)
local tArg = {...}; nArg = #tArg
local tVal, tAct = mtData[1].V, mtData[1].A
for k = 1, #tVal do
local nV = tonumber(tArg[k] or 0)
tVal[k] = nV; tAct[k] = nV
end
return self
end
function self:setActive(fA, fD, fO)
if(isFunction(fA)) then mfAct = fA
local bS, aR = pcall(mfAct, 0)
if(not bS) then mfAct = logStatus("newNeuralNet.setActive(dif): Fail "..tostring(aR), self) end
else mfAct = logStatus("newNeuralNet.setActive(act): Skip", self) end
if(isFunction(fO)) then mfOut = fO
local bS, aR = pcall(mfOut, 0)
if(not bS) then mfOut = logStatus("newNeuralNet.setActive(out): Fail "..tostring(aR), self) end
else mfOut = logStatus("newNeuralNet.setActive(out): Skip", self) end
return self
end
function self:getWeightLayer(vLay)
local tW, mW = {}, mtData[iLay].W
for k = 1, #mW do tW[k] = {}
signals.setWeight(tW[k], mW[k])
end; return tW
end
function self:getValueLayer(vLay)
local iLay = math.floor(tonumber(vLay) or 0)
local tL = mtData[iLay]; if(isNil(tL)) then
return logStatus("newNeuralNet.getValueLayer: Missing layer #"..tostring(vLay), self) end
local tV, vV = {}, tL.V; for k = 1, #vV do tV[k] = vV[k]; end; return tV
end -- https://stevenmiller888.github.io/mind-how-to-build-a-neural-network/
function self:Train(tT, vN, bL)
if(bL) then logStatus("Training ") end
local nN = getClamp(tonumber(vN) or 0, 1)
for iI = 1, nN do
for iT = 1, #tT do self:resDelta()
self:setValue(unpack(tT[iT][1])):Process()
self:upLast(tT[iT][2]):upRest():appDelta()
end; if(bL) then logString(".") end
end; if(bL) then logStatus(" done !") end; return self
end
function self:getNeuronsCnt()
local nC = 0; for k = 2, (mID-1) do
nC = nC + #mtData[k].V
end return nC
end
function self:getWeightsCnt()
local nC = 0; for k = 2, (mID-1) do
local mW = mtData[k].W
nC = nC + #mW * #(mW[1])
end return nC
end
function self:getType() return metaNeuralNet.__type end
function self:Dump(vL)
local sT = self:getType()
local iL = math.floor(tonumber(vL) or sT:len())
local dL = math.floor(getClamp(iL/5,1))
logStatus("["..self:getType().."] Properties:")
logStatus(" Name : "..mName)
logStatus(" Layers : "..(mID-1))
logStatus(" Neurons : "..self:getNeuronsCnt())
logStatus(" Weights : "..self:getWeightsCnt())
logStatus(" Interanal weights and and values status:")
logConcat(stringPadL("V[1]",iL," ")..stringPadR("(1)",dL).." -> ",", ", unpack(mtData[1].V))
logConcat(stringPadL("A[1]",iL," ")..stringPadR("(1)",dL).." -> ",", ", unpack(mtData[1].A))
for k = 2, (mID-1) do local mW = mtData[k].W; for i = 1, #mW do
logConcat(stringPadL("W["..(k-1).."->"..k.."]",iL," ")..stringPadR("("..i..")",dL).." -> ",", ", unpack(mtData[k].W[i]))
logConcat(stringPadL("D["..(k-1).."->"..k.."]",iL," ")..stringPadR("("..i..")",dL).." -> ",", ", unpack(mtData[k].D[i]))
end
logConcat(stringPadL("A["..k.."]",iL," ")..stringPadR("("..(k-1)..")",dL).." -> ",", ", unpack(mtData[k].A))
logConcat(stringPadL("V["..k.."]",iL," ")..stringPadR("("..(k-1)..")",dL).." -> ",", ", unpack(mtData[k].V))
end; return self
end; return self
end
--[[
* newControl: Class state processing manager
* nTo > Controller sampling time in seconds
* arPar > Parameter array {Kp, Ti, Td, satD, satU}
]]
local metaControl = {}
metaControl.__index = metaControl
metaControl.__type = "signals.control"
metaControl.__metatable = metaControl.__type
metaControl.__tostring = function(oControl) return oControl:getString() end
local function newControl(nTo, sName)
local mTo = (tonumber(nTo) or 0); if(mTo <= 0) then -- Sampling time [s]
return logStatus(nil, "newControl: Sampling time <"..tostring(nTo).."> invalid") end
local self = {}; setmetatable(self, metaControl) -- Place to store the methods
local mfAbs = math and math.abs -- Function used for error absolute
local mfSgn = getSign -- Function used for error sign
local mErrO, mErrN = 0, 0 -- Error state values
local mvCon, meInt = 0, true -- Control value and integral enabled
local mvP, mvI, mvD = 0, 0, 0 -- Term values
local mkP, mkI, mkD = 0, 0, 0 -- P, I and D term gains
local mpP, mpI, mpD = 1, 1, 1 -- Raise the error to power of that much
local mbCmb, mbInv, mSatD, mSatU = true, false -- Saturation limits and settings
local mName, mType, mUser = (sName and tostring(sName) or "N/A"), "", {}
function self:getTerm(kV,eV,pV) return (kV*mfSgn(eV)*mfAbs(eV)^pV) end
function self:Dump() return logStatus(self:getString(), self) end
function self:getGains() return mkP, mkI, mkD end
function self:getTerms() return mvP, mvI, mvD end
function self:setEnIntegral(bEn) meInt = toBool(bEn); return self end
function self:getEnIntegral() return meInt end
function self:getError() return mErrO, mErrN end
function self:getControl() return mvCon end
function self:getUser() return mUser end
function self:getType() return mType end
function self:getPeriod() return mTo end
function self:setPower(pP, pI, pD)
mpP, mpI, mpD = (tonumber(pP) or 0), (tonumber(pI) or 0), (tonumber(pD) or 0); return self end
function self:setClamp(sD, sU) mSatD, mSatU = (tonumber(sD) or 0), (tonumber(sU) or 0); return self end
function self:setStruct(bCmb, bInv) mbCmb, mbInv = toBool(bCmb), toBool(bInv); return self end
function self:Reset()
mErrO, mErrN = 0, 0
mvP, mvI, mvD = 0, 0, 0
mvCon, meInt = 0, true
return self
end
function self:Process(vRef,vOut)
mErrO = mErrN -- Refresh error state sample
mErrN = (mbInv and (vOut-vRef) or (vRef-vOut))
if(mkP > 0) then -- P-Term
mvP = self:getTerm(mkP, mErrN, mpP) end
if((mkI > 0) and (mErrN ~= 0) and meInt) then -- I-Term
mvI = self:getTerm(mkI, mErrN + mErrO, mpI) + mvI end
if((mkD ~= 0) and (mErrN ~= mErrO)) then -- D-Term
mvD = self:getTerm(mkD, mErrN - mErrO, mpD) end
mvCon = mvP + mvI + mvD -- Calculate the control signal
if(mSatD and mSatU) then -- Apply anti-windup effect
if (mvCon < mSatD) then mvCon, meInt = mSatD, false
elseif(mvCon > mSatU) then mvCon, meInt = mSatU, false
else meInt = true end
end; return self
end
function self:getString()
local sInfo = (mType ~= "") and (mType.."-") or mType
sInfo = "["..sInfo..metaControl.__type.."] Properties:\n"
sInfo = sInfo.." Name : "..mName.." ["..tostring(mTo).."]s\n"
sInfo = sInfo.." Param: {"..tostring(mUser[1])..", "..tostring(mUser[2])..", "
sInfo = sInfo..tostring(mUser[3])..", "..tostring(mUser[4])..", "..tostring(mUser[5]).."}\n"
sInfo = sInfo.." Gains: {P="..tostring(mkP)..", I="..tostring(mkI)..", D="..tostring(mkD).."}\n"
sInfo = sInfo.." Power: {P="..tostring(mpP)..", I="..tostring(mpI)..", D="..tostring(mpD).."}\n"
sInfo = sInfo.." Limit: {D="..tostring(mSatD)..",U="..tostring(mSatU).."}\n"
sInfo = sInfo.." Error: {"..tostring(mErrO)..", "..tostring(mErrN).."}\n"
sInfo = sInfo.." Value: ["..tostring(mvCon).."] {P="..tostring(mvP)
sInfo = sInfo..", I="..tostring(mvI)..", D="..tostring(mvD).."}\n"; return sInfo
end
function self:Setup(arParam)
if(type(arParam) ~= "table") then
return logStatus("newControl.Setup: Params table <"..type(arParam).."> invalid") end
if(arParam[1] and (tonumber(arParam[1] or 0) > 0)) then
mkP = (tonumber(arParam[1] or 0))
else return logStatus("newControl.Setup: P-gain <"..tostring(arParam[1]).."> invalid") end
if(arParam[2] and (tonumber(arParam[2] or 0) > 0)) then
mkI = (mTo / (2 * (tonumber(arParam[2] or 0)))) -- Discrete integral approximation
if(mbCmb) then mkI = mkI * mkP end
else logStatus("newControl.Setup: I-gain <"..tostring(arParam[2]).."> skipped") end
if(arParam[3] and (tonumber(arParam[3] or 0) ~= 0)) then
mkD = (tonumber(arParam[3] or 0) * mTo) -- Discrete derivative approximation
if(mbCmb) then mkD = mkD * mkP end
else logStatus("newControl.Setup: D-gain <"..tostring(arParam[3]).."> skipped") end
if(arParam[4] and arParam[5] and ((tonumber(arParam[4]) or 0) < (tonumber(arParam[5]) or 0))) then
mSatD, mSatU = (tonumber(arParam[4]) or 0), (tonumber(arParam[5]) or 0)
else logStatus("newControl.Setup: Saturation skipped <"..tostring(arParam[4]).."<"..tostring(arParam[5]).."> skipped") end
mType = ((mkP > 0) and "P" or "")..((mkI > 0) and "I" or "")..((mkD > 0) and "D" or "")
for ID = 1, 5, 1 do mUser[ID] = arParam[ID] end; return self -- Init multiple states using the table
end
function self:Mul(nMul)
local Mul = (tonumber(nMul) or 0)
if(Mul <= 0) then return self end
for ID = 1, 5, 1 do mUser[ID] = mUser[ID] * Mul end
self:Setup(mUser); return self -- Init multiple states using the table
end
return self
end
-- https://www.mathworks.com/help/simulink/slref/discretefilter.html
local metaPlant = {}
metaPlant.__index = metaPlant
metaPlant.__type = "signals.plant"
metaPlant.__metatable = metaPlant.__type
metaPlant.__tostring = function(oPlant) return oPlant:getString() end
local function newPlant(nTo, tNum, tDen, sName)
local mOrd = #tDen; if(mOrd < #tNum) then
return logStatus("Plant physically impossible") end
if(tDen[1] == 0) then
return logStatus("Plant denominator invalid") end
local self, mTo = {}, (tonumber(nTo) or 0); setmetatable(self, metaPlant)
if(mTo <= 0) then return logStatus("Plant sampling time <"..tostring(nTo).."> invalid") end
local mName, mOut = tostring(sName or "Plant plant"), nil
local mSta, mDen, mNum = {}, {}, {}
for ik = 1, mOrd, 1 do mSta[ik] = 0 end
for iK = 1, mOrd, 1 do mDen[iK] = (tonumber(tDen[iK]) or 0) end
for iK = 1, mOrd, 1 do mNum[iK] = (tonumber(tNum[iK]) or 0) end
for iK = 1, (mOrd - #tNum), 1 do table.insert(mNum,1,0); mNum[#mNum] = nil end
function self:Scale()
local nK = mDen[1]
for iK = 1, mOrd do
mNum[iK] = (mNum[iK] / nK)
mDen[iK] = (mDen[iK] / nK)
end; return self
end
function self:getString()
local sInfo = "["..metaPlant.__type.."] Properties:\n"
sInfo = sInfo.." Name : "..mName.."^"..tostring(mOrd).." ["..tostring(mTo).."]s\n"
sInfo = sInfo.." Numenator : {"..table.concat(mNum,", ").."}\n"
sInfo = sInfo.." Denumenator: {"..table.concat(mDen,", ").."}\n"
sInfo = sInfo.." States : {"..table.concat(mSta,", ").."}\n"; return sInfo
end
function self:Dump() return logStatus(self:getString(), self) end
function self:getOutput() return mOut end
function self:getBeta()
local nOut, iK = 0, mOrd
while(iK > 0) do
nOut = nOut + (mNum[iK] or 0) * mSta[iK]
iK = iK - 1 -- Get next state
end; return nOut
end
function self:getAlpha()
local nOut, iK = 0, mOrd
while(iK > 1) do
nOut = nOut - (mDen[iK] or 0) * mSta[iK]
iK = iK - 1 -- Get next state
end; return nOut
end
function self:putState(vX)
local iK, nX = mOrd, (tonumber(vX) or 0)
while(iK > 0 and mSta[iK]) do
mSta[iK] = (mSta[iK-1] or 0); iK = iK - 1 -- Get next state
end; mSta[1] = nX; return self
end
function self:Process(vU)
local nU, nA = (tonumber(vU) or 0), self:getAlpha()
self:putState((nU + nA) / mDen[1]); mOut = self:getBeta(); return self
end
function self:Reset()
for iK = 1, #mSta, 1 do mSta[iK] = 0 end; mOut = 0; return self
end
return self
end
local metaWiper = {}
metaWiper.__index = metaWiper
metaWiper.__type = "signals.wiper"
metaWiper.__metatable = metaWiper.__type
metaWiper.__tostring = function(oWiper) return oWiper:getString() end
local function newWiper(nR, nF, nP, nD)
local mT = 0 -- Holds the time value
local mP = (tonumber(nP) or 0)
local mD = (tonumber(nD) or 0)
local mR = math.abs(tonumber(nR) or 0)
local mF = math.abs(tonumber(nF) or 0)
local mO, mW = complex.getNew(), (2 * math.pi * mF)
local mV = mO:getNew():Euler(mR, complex.toRad(mP))
local mN -- Next wiper attached to the tip of the prevoious
local self = {}; setmetatable(self, metaWiper)
function self:getNew(...) return newWiper(...) end
function self:getVec() return mV:getNew() end
function self:getOrg() return mO:getNew() end
function self:setOrg(...) mO:Set(...); return self end
function self:getPos() return mO:getAdd(mV) end
function self:setNext(...) mN = self:getNew(...); return self end
function self:addNext(...) self:setNext(...); return mN end
function self:getAbs() return mR end
function self:getNext() return mN end
function self:getFreq() return mF end
function self:getPhase() return mP end
function self:getDelta() return mD end
function self:Reverse(bN)
mP = mP + (bN and -180 or 180)
mV:Euler(mR, complex.toRad(mP)); return self
end
function self:Dump(bC)
logStatus(self:getString())
local oF, sC = self:getNext(), " "
if(bC) then while(oF) do
logStatus(sC..oF:getString())
oF = oF:getNext()
end; end; return self
end
function self:setDelta(nD)
mD = (tonumber(nD) or 0); return self
end
function self:setAbs(nR)
mR = math.abs(tonumber(nR) or 0)
mV:Euler(mR, complex.toRad(mP)); return self
end
function self:setPhase(nP, nA)
mP = getAngNorm((tonumber(nP) or 0) + (tonumber(nA) or 0))
mV:Euler(mR, complex.toRad(mP)); return self
end
function self:getString()
local sR, sF = self:getAbs(), self:getFreq()
local sP, sD = self:getPhase(), self:getDelta()
local sT = table.concat({sR, sF, sP, sD}, ",")
return ("["..metaWiper.__type.."]{"..sT.."}")
end
function self:setFreq(nF)
mF = math.abs(tonumber(nF) or 0); return self
end
function self:Update()
mT = mT + mD; mV:RotRad(mW * mD)
if(mN) then mN:Update() end; return self
end
function self:Draw(sKey, clDrw)
local vT = mO:getAdd(mV)
mO:Action(sKey, vT, clDrw);
if(mN) then mN:setOrg(vT):Draw(sKey, clDrw) end
return self
end
function self:getCount()
local nC, wC = 0, self
while(wC) do nC, wC = (nC + 1), wC:getNext() end
return nC
end
function self:getStage(nS)
local nS = getClamp(math.floor(tonumber(nS) or 0), 0)
local wC, ID = self, 1 -- Returns the wiper stage
while(ID <= nS and wC) do
wC, ID = wC:getNext(), (ID + 1) end; return wC
end
function self:getTip()
local wC, vT = self, mO:getNew()
while(wC) do -- Iterate as a list of pointers
vT:Add(wC:getVec())
wC = wC:getNext()
end; return vT
end
function self:getCopy()
local sR, sF = self:getAbs(), self:getFreq()
local sP, sD = self:getPhase(), self:getDelta()
return self:getNew(sR, sF, sP, sD)
end
function self:toSquare(nN, nP)
local nN, wC = getClamp(math.floor(tonumber(nN) or 0),0), self
self:setAbs(self:getAbs() * (4 / math.pi)):setPhase(nP)
local sR, sF = self:getAbs(), self:getFreq()
local sP, sD = self:getPhase(), self:getDelta()
for k = 2, nN do local n = (2 * k - 1)
local a = (1 / n)
wC = wC:addNext(a*sR, n*sF, sP, sD)
end; return self
end
function self:toTriangle(nN, nP)
local nN, wC = getClamp(math.floor(tonumber(nN) or 0),0), self
self:setAbs(self:getAbs() * (8 / math.pi^2)):setPhase(nP, 90)
local sR, sF = self:getAbs(), self:getFreq()
local sP, sD = self:getPhase(), self:getDelta()
for k = 1, nN-1 do
local n = (2 * k + 1)
local a = ((-1)^k)*(1/n^2)
wC = wC:addNext(a*sR, n*sF, sP, sD)
end; return self
end
function self:toSaw(nN, nP)
local nN, oF = getClamp(math.floor(tonumber(nN) or 0),0), self
self:setAbs(self:getAbs() / math.pi):setPhase(nP)
local sR, sF = self:getAbs(), self:getFreq()
local sP, sD = self:getPhase(), self:getDelta()
for k = 2, nN do local a = (((-1)^k) / k)
oF = oF:addNext(a*sR, k*sF, sP, sD)
end; return self
end
function self:toRand(nN, nP)
local nN, oF = getClamp(math.floor(tonumber(nN) or 0),0), self
local sR, sF = self:getAbs(), self:getFreq()
local sP, sD = self:getPhase(), self:getDelta(); self:setPhase(nP)
for k = 2, nN do
local a, b = common.randomGetNumber(), common.randomGetNumber()
local c, d = common.randomGetNumber(), common.randomGetNumber()
local r = math.exp((-0.618)*k*a)
oF = oF:addNext(r*sR, k*sF*b, sP*c, sD*d)
end; return self
end
return self
end
function signals.New(sType, ...)
local sType = "signals."..tostring(sType or "")
if(sType == metaControl.__type) then return newControl(...) end
if(sType == metaPlant.__type) then return newPlant(...) end
if(sType == metaNeuralNet.__type) then return newNeuralNet(...) end
if(sType == metaWiper.__type) then return newWiper(...) end
end
return signals
|
object_static_structure_general_waypoint_personal_white = object_static_structure_general_shared_waypoint_personal_white:new {
}
ObjectTemplates:addTemplate(object_static_structure_general_waypoint_personal_white, "object/static/structure/general/waypoint_personal_white.iff")
|
-- -*- mode: lua; tab-width: 2; indent-tabs-mode: 1; st-rulers: [70] -*-
-- vim: ts=4 sw=4 ft=lua noet
---------------------------------------------------------------------
-- @author Daniel Barney <daniel@pagodabox.com>
-- @copyright 2014, Pagoda Box, Inc.
-- @doc
--
-- @end
-- Created : 30 Jan 2015 by Daniel Barney <daniel@pagodabox.com>
---------------------------------------------------------------------
return function(data,id,is_alive)
for idx,is_alive in pairs(is_alive) do
if is_alive then
return {data[idx % #data +1 ]},{}
end
end
-- it should never get here. how could no servers ever be alive?
return {},{}
end |
local openssl = require'openssl'
local csr,bio,ssl = openssl.csr,openssl.bio, openssl.ssl
local sslctx = require'sslctx'
_,_,opensslv = openssl.version(true)
host = arg[1] or "127.0.0.1"; --only ip
port = arg[2] or "8383";
loop = arg[3] and tonumber(arg[3]) or 100
local params = {
mode = "server",
protocol = "tlsv1",
key = "luasec/certs/serverAkey.pem",
certificate = "luasec/certs/serverA.pem",
cafile = "luasec/certs/rootA.pem",
verify = ssl.peer + ssl.fail,
options = {"all", "no_sslv2"},
}
local certstore
if opensslv > 0x10002000 then
certstore = openssl.x509.store:new()
local cas = require'root_ca'
for i=1,#cas do
local cert = assert(openssl.x509.read(cas[i]))
assert(certstore:add(cert))
end
end
local ctx = assert(sslctx.new(params))
if certstore then
ctx:cert_store(certstore)
end
ctx:verify_mode(ssl.peer,function(arg)
--[[
--do some check
for k,v in pairs(arg) do
print(k,v)
end
--]]
return true --return false will fail ssh handshake
end)
print(string.format('Listen at %s:%s with %s',host,port,tostring(ctx)))
ctx:set_cert_verify(function(arg)
--do some check
--[[
for k,v in pairs(arg) do
print(k,v)
end
--]]
return true --return false will fail ssh handshake
end)
function ssl_mode()
local srv = assert(ctx:bio(host..':'..port,true))
local i = 0
if srv then
print('listen BIO:',srv)
assert(srv:accept(true),'Error in accept BIO') -- make real listen
while i<loop do
local cli = assert(srv:accept(),'Error in ssl connection') --bio tcp
assert(cli:handshake(),'handshake fail')
repeat
d = cli:read()
if d then
cli:write(d)
end
until not d
cli:close()
cli = nil
collectgarbage()
i = i + 1
end
srv:close()
end
end
ssl_mode()
debug.traceback()
print(openssl.error(true))
|
local API = {}
local table_insert = table.insert
local ipairs = ipairs
local type = type
local tostring = tostring
local cjson = require("cjson")
local utils = require("orange.utils.utils")
local orange_db = require("orange.store.orange_db")
local redirect_db = require("orange.plugins.redirect.redirect_db")
API["/redirect/enable"] = {
POST = function(store)
return function(req, res, next)
local enable = req.body.enable
if enable == "1" then enable = true else enable = false end
local result = false
local redirect_enable = "0"
if enable then redirect_enable = "1" end
local update_result = redirect_db.replace_meta_value(store,"redirect.enable", redirect_enable )
--[[
store:update({
sql = "replace into meta SET `key`=?, `value`=?",
params = { "redirect.enable", redirect_enable }
})
--]]
if update_result then
local success, err, forcible = orange_db.set("redirect.enable", enable)
result = success
else
result = false
end
if result then
res:json({
success = true,
msg = (enable == true and "开启redirect成功" or "关闭redirect成功")
})
else
res:json({
success = false,
msg = (enable == true and "开启redirect失败" or "关闭redirect失败")
})
end
end
end
}
API["/redirect/fetch_config"] = {
-- fetch data from db
GET = function(store)
return function(req, res, next)
local success, data = false, {}
-- 查找enable
local enable, err1 = redirect_db.select_meta_value(store,"redirect.enable")
--[[
store:query({
sql = "select `value` from meta where `key`=?",
params = { "redirect.enable" }
}--]]
if err1 then
return res:json({
success = false,
msg = "get enable error"
})
end
if enable and type(enable) == "table" and #enable == 1 and enable[1].value == "1" then
data.enable = true
else
data.enable = false
end
-- 查找rules
local rules, err2 = redirect_db.select_redirect_rules(store)
--[[
store:query({
sql = "select `value` from redirect order by id asc"
})
--]]
if err2 then
return res:json({
success = false,
msg = "get rules error"
})
end
if rules and type(rules) == "table" and #rules > 0 then
local format_rules = {}
for i, v in ipairs(rules) do
if type(v.value) == "table" then
table_insert(format_rules, v.value)
else
table_insert(format_rules, cjson.decode(v.value))
end
end
data.rules = format_rules
success = true
else
success = true
data.rules = {}
end
res:json({
success = success,
data = data
})
end
end,
}
API["/redirect/sync"] = {
-- update the local cache to data stored in db
POST = function(store)
return function(req, res, next)
local success, data = false, {}
-- 查找enable
local enable, err1 = redirect_db.select_meta_value(store,"redirect.enable")
--[[
store:query({
sql = "select `value` from meta where `key`=?",
params = { "redirect.enable" }
})
--]]
if err1 then
return res:json({
success = false,
msg = "get enable error"
})
end
if enable and type(enable) == "table" and #enable == 1 and enable[1].value == "1" then
data.enable = true
else
data.enable = false
end
-- 查找rules
local rules, err2 = redirect_db.select_redirect_rules(store)
--[[
store:query({
sql = "select `value` from redirect order by id asc"
})
--]]
if err2 then
return res:json({
success = false,
msg = "get rules error"
})
end
if rules and type(rules) == "table" and #rules > 0 then
local format_rules = {}
for i, v in ipairs(rules) do
if type(v.value) == 'table' then
table_insert(format_rules, v.value)
else
table_insert(format_rules, cjson.decode(v.value))
end
end
data.rules = format_rules
else
data.rules = {}
end
local ss, err3, forcible = orange_db.set("redirect.enable", data.enable)
if not ss or err3 then
return res:json({
success = false,
msg = "update local enable error"
})
end
ss, err3, forcible = orange_db.set_json("redirect.rules", data.rules)
if not ss or err3 then
return res:json({
success = false,
msg = "update local rules error"
})
end
res:json({
success = true,
msg = "ok"
})
end
end,
}
API["/redirect/configs"] = {
GET = function(store)
return function(req, res, next)
local data = {}
data.enable = orange_db.get("redirect.enable")
data.rules = orange_db.get_json("redirect.rules")
res:json({
success = true,
data = data
})
end
end,
-- new
PUT = function(store)
return function(req, res, next)
local rule = req.body.rule
rule = cjson.decode(rule)
rule.id = utils.new_id()
rule.time = utils.now()
local success = false
-- 插入到mysql
local insert_result = redirect_db.insert_redirect_rules(store,rule.id,rule)
--[[
store:insert({
sql = "insert into redirect(`key`, `value`) values(?,?)",
params = { rule.id, cjson.encode(rule) }
})
--]]
-- 插入成功,则更新本地缓存
if insert_result then
local redirect_rules = orange_db.get_json("redirect.rules") or {}
table_insert(redirect_rules, rule)
local s, err, forcible = orange_db.set_json("redirect.rules", redirect_rules)
if s then
success = true
else
ngx.log(ngx.ERR, "save redirect rules locally error: ", err)
end
else
success = false
end
res:json({
success = success,
msg = success and "ok" or "failed"
})
end
end,
DELETE = function(store)
return function(req, res, next)
local rule_id = tostring(req.body.rule_id)
if not rule_id or rule_id == "" then
return res:json({
success = false,
msg = "error param: rule id shoule not be null."
})
end
local delete_result = redirect_db.delete_redirect_rules(store,rule_id)
--[[
store:delete({
sql = "delete from redirect where `key`=?",
params = { rule_id }
})
--]]
if delete_result then
local old_rules = orange_db.get_json("redirect.rules") or {}
local new_rules = {}
for i, v in ipairs(old_rules) do
if v.id ~= rule_id then
table_insert(new_rules, v)
end
end
local success, err, forcible = orange_db.set_json("redirect.rules", new_rules)
if err or forcible then
ngx.log(ngx.ERR, "update local rules error when deleting:", err, ":", forcible)
return res:json({
success = false,
msg = "update local rules error when deleting"
})
end
res:json({
success = success,
msg = success and "ok" or "failed"
})
else
res:json({
success = false,
msg = "delete rule from db error"
})
end
end
end,
-- modify
POST = function(store)
return function(req, res, next)
local rule = req.body.rule
rule = cjson.decode(rule)
local update_result = redirect_db.update_redirect_rules(store,rule.id,rule)
--[[
store:delete({
sql = "update redirect set `value`=? where `key`=?",
params = { cjson.encode(rule), rule.id }
})
--]]
if update_result then
local old_rules = orange_db.get_json("redirect.rules") or {}
local new_rules = {}
for i, v in ipairs(old_rules) do
if v.id == rule.id then
rule.time = utils.now()
table_insert(new_rules, rule)
else
table_insert(new_rules, v)
end
end
local success, err, forcible = orange_db.set_json("redirect.rules", new_rules)
if err or forcible then
ngx.log(ngx.ERR, "update local rules error when modifing:", err, ":", forcible)
return res:json({
success = false,
msg = "update local rules error when modifing"
})
end
res:json({
success = success,
msg = success and "ok" or "failed"
})
else
res:json({
success = false,
msg = "update rule to db error"
})
end
end
end
}
return API
|
RegisterCommandSuggestion({ 'me', 'do' }, 'Provide information or an action for others around you.', {
{ name = 'action/information', help = 'The action or information to disclose.' }
})
RegisterCommandSuggestion({ 'ooc', 'global' }, 'Send a global out of character message.', {
{ name = 'message', help = 'The message you would like to send.' }
})
RegisterCommandSuggestion({ 'pm', 'dm', 'message' }, 'Send a private message.', {
{ name = 'player', help = 'The player\'s server id.' },
{ name = 'message', help = 'The message you would like to send them.' },
})
RegisterCommandSuggestion({ 'ad', 'advert' }, 'Send an advert message.', {
{ name = 'message', help = 'The message you would like to advert.' },
})
RegisterCommandSuggestion({ 'darkweb' }, 'Send an anonymous darweb message.', {
{ name = 'message', help = 'The message you would like to send on the darkweb.' },
})
RegisterCommandSuggestion({ 'twt', 'tweet', 'twitter' }, 'Send a tweet.', {
{ name = 'message', help = 'The message you would like to tweet.' },
})
RegisterCommandSuggestion({ 'rt', 'retweet' }, 'Retweet the last tweet.')
RegisterCommandSuggestion({ 'dv', 'delveh' }, 'Delete the nearest vehicle.')
RegisterCommandSuggestion('duty', 'Toggle on/off duty.')
RegisterCommandSuggestion('offduty', 'Disable patrolman duties.')
RegisterCommandSuggestion('onduty', 'Enable patrolman duties.')
RegisterCommandSuggestion({ 'clean', 'wash' }, 'Clean the vehicle you\'re near.')
RegisterCommandSuggestion({ 'fix', 'repair' }, 'Fix the vehicle you\'re near.')
RegisterCommandSuggestion('hood', 'Open the hood of the vehicle you\'re near.')
RegisterCommandSuggestion('trunk', 'Open the trunk of the vehicle you\'re near.')
RegisterCommandSuggestion('door', 'Open a door of the vehicle you\'re near.', {
{ name = 'number', help = 'The number of the door to open. 1 is driver\'s, 2 is passenger\'s, etc.' }
})
RegisterCommandSuggestion('taserlaser', 'Toggle your taser\'s laser. Best experienced in first-person because bullets shoot from the camera.')
RegisterCommandSuggestion({ 'heal', 'health' }, 'Set your health.', {
{ name = 'amount', help = '0 = none (dead), 1 = some, 2 = under half, 3 = over half, 4 = almost max, 5 = max.' }
})
RegisterCommandSuggestion({ 'armour', 'armor' }, 'Set your armour.', {
{ name = 'amount', help = '0 = none, 1 = some, 2 = under half, 3 = over half, 4 = almost max, 5 = max.' }
})
RegisterCommandSuggestion({ 'globalme', 'gme', 'globaldo', 'gdo' }, 'Provide information or an action for players further away.', {
{ name = 'message', help = 'The message you would like to send.' }
}) |
require("mod.ffhp_matome.data.chip")
require("mod.ffhp_matome.data.theme")
|
return {
sourceName = 'luacheck',
command = 'luacheck',
debounce = 100,
args = { '--codes', '--no-color', '--quiet', '-' },
offsetLine = 0,
offsetColumn = 0,
formatLines = 1,
formatPattern = {
[[^.*:(\d+):(\d+):\s\(([W|E])\d+\)\s(.*)(\r|\n)*$]],
{ line = 1, column = 2, security = 3, message = { '[luacheck] ', 4 } },
},
securities = { E = 'error', W = 'warning' },
rootPatterns = { '.luacheckrc' },
}
|
return function(lumiere,mui)
local eztask = lumiere:depend "eztask"
local lmath = lumiere:depend "lmath"
local class = lumiere:depend "class"
local gel = lumiere:depend "gel"
local radio_button=gel.class.element:extend()
function radio_button:__tostring()
return "radio_button"
end
function radio_button:new()
radio_button.super.new(self)
self.marked = eztask.property.new(false)
self.update_appearance = eztask.signal.new()
self:set("active",true)
:set("size",lmath.udim2.new(
0,mui.layout.radio_button.unselected.frame.sprite_size.x,
0,mui.layout.radio_button.unselected.frame.sprite_size.y
))
self.frame=gel.new("image_element")
:set("name","frame")
:set("visible",true)
:set("size",lmath.udim2.new(
0,mui.layout.radio_button.unselected.frame.sprite_size.x,
0,mui.layout.radio_button.unselected.frame.sprite_size.y
))
:set("background_opacity",0)
:set("rect_offset",mui.layout.radio_button.unselected.frame.rect_offset)
:set("image",mui.layout.texture)
:set("image_color",mui.layout.radio_button.unselected.frame.color)
:set("image_opacity",mui.layout.radio_button.unselected.frame.opacity)
:set("parent",self)
self.mark=gel.new("image_element")
:set("name","mark")
:set("visible",true)
:set("anchor_point",lmath.vector2.new(0.5,0.5))
:set("position",lmath.udim2.new(0.5,0,0.5,0))
:set("size",lmath.udim2.new(
0,mui.layout.radio_button.unselected.mark.sprite_size.x,
0,mui.layout.radio_button.unselected.mark.sprite_size.y
))
:set("background_opacity",0)
:set("rect_offset",mui.layout.radio_button.unselected.mark.rect_offset)
:set("image",mui.layout.texture)
:set("image_color",mui.layout.radio_button.unselected.mark.color)
:set("image_opacity",mui.layout.radio_button.unselected.mark.opacity)
:set("parent",self.frame)
self.label=gel.new("text_element")
:set("visible",true)
:set("size",lmath.udim2.new(
1,-mui.layout.radio_button.unselected.frame.sprite_size.x-5,
0,mui.layout.radio_button.unselected.frame.sprite_size.y
))
:set("anchor_point",lmath.vector2.new(0,0.5))
:set("position",lmath.udim2.new(
0,mui.layout.radio_button.unselected.frame.sprite_size.x+5,
0.5,0
))
:set("background_opacity",0)
:set("text","Radio Button")
:set("font",mui.layout.font.regular)
:set("text_x_alignment",gel.enum.alignment.x.left)
:set("text_y_alignment",gel.enum.alignment.y.center)
:set("text_size",mui.layout.radio_button.unselected.label.text_size)
:set("text_color",mui.layout.radio_button.unselected.label.text_color)
:set("text_opacity",mui.layout.radio_button.unselected.label.text_opacity)
:set("parent",self.frame)
self.text = self.label.text
self.text_color = self.label.text_color
self.text_opacity = self.label.text_opacity
self.text_size = self.label.text_size
self.font = self.label.font
self.text_x_alignment = self.label.text_x_alignment
self.text_y_alignment = self.label.text_y_alignment
self.text_wrapped = self.label.text_wrapped
self.multiline = self.label.multiline
self.update_appearance:attach(function()
if self.marked.value then
self.frame:set("rect_offset",mui.layout.radio_button.selected.frame.rect_offset)
:set("image_color",mui.layout.radio_button.selected.frame.color)
:set("image_opacity",mui.layout.radio_button.selected.frame.opacity)
self.mark:set("rect_offset",mui.layout.radio_button.selected.mark.rect_offset)
:set("image_color",mui.layout.radio_button.selected.mark.color)
:set("image_opacity",mui.layout.radio_button.selected.mark.opacity)
self.label:set("text_size",mui.layout.radio_button.selected.label.text_size)
:set("text_color",mui.layout.radio_button.selected.label.text_color)
:set("text_opacity",mui.layout.radio_button.selected.label.text_opacity)
if self.parent.value then
for _,neighbor in pairs(self.parent.value.children) do
if neighbor:is(radio_button) and neighbor~=self then
neighbor.marked.value=false
end
end
end
else
self.frame:set("rect_offset",mui.layout.radio_button.unselected.frame.rect_offset)
:set("image_color",mui.layout.radio_button.unselected.frame.color)
:set("image_opacity",mui.layout.radio_button.unselected.frame.opacity)
self.mark:set("rect_offset",mui.layout.radio_button.unselected.mark.rect_offset)
:set("image_color",mui.layout.radio_button.unselected.mark.color)
:set("image_opacity",mui.layout.radio_button.unselected.mark.opacity)
self.label:set("text_size",mui.layout.radio_button.unselected.label.text_size)
:set("text_color",mui.layout.radio_button.unselected.label.text_color)
:set("text_opacity",mui.layout.radio_button.unselected.label.text_opacity)
end
end)
self.marked:attach(self.update_appearance)
self.selected:attach(function(_,selected)
if selected then
self.marked.value=not self.marked.value
end
end)
end
function radio_button:delete()
radio_button.super.delete(self)
self.marked:detach()
end
return radio_button
end |
data:extend ({
-- Special
--teleport-effect
{
type = "explosion",
name = "pre-teleport-effect",
flags = {"not-on-map"},
animations =
{
{
filename = "__morebobs__/graphics/entity/teleport/teleport-effect.png",
priority = "extra-high",
width = 48,
height = 64,
frame_count = 1,
line_length = 10,
--shift = {-0.56, -0.96},
animation_speed = 0.5
}
},
},
--teleport-effect
{
type = "explosion",
name = "teleport-effect",
flags = {"not-on-map"},
animations =
{
{
filename = "__morebobs__/graphics/entity/teleport/teleport-effect.png",
priority = "extra-high",
width = 48,
height = 64,
frame_count = 100,
line_length = 10,
--shift = {-0.56, -0.96},
animation_speed = 0.5
}
},
light = {intensity = 1, size = 50},
sound =
{
aggregation =
{
max_count = 1,
remove = true
},
variations =
{
{
filename = "__base__/sound/fight/old/laser.ogg",
volume = 0.8
},
}
},
},
-- tank-assembly
{
type = "assembling-machine",
name = "tank-assembling-machine",
icons =
{
{ icon = "__morebobs__/graphics/icons/tank/tank-assembling-machine.png" },
{ icon = "__morebobs__/graphics/icons/tank/tier-s.png" }
},
icon_size = 32,
flags = {"placeable-neutral","placeable-player", "player-creation"},
minable = {hardness = 0.2, mining_time = 0.5, result = "tank-assembling-machine"},
max_health = 400,
corpse = "big-remnants",
dying_explosion = "medium-explosion",
alert_icon_shift = util.by_pixel(-3, -12),
resistances =
{
{
type = "fire",
percent = 70
}
},
fluid_boxes =
{
{
production_type = "input",
pipe_picture = assembler3pipepictures(),
pipe_covers = pipecoverspictures(),
base_area = 10,
base_level = -1,
pipe_connections = {{ type="input", position = {0, -2} }},
secondary_draw_orders = { north = -1 }
},
{
production_type = "output",
pipe_picture = assembler3pipepictures(),
pipe_covers = pipecoverspictures(),
base_area = 10,
base_level = 1,
pipe_connections = {{ type="output", position = {0, 2} }},
secondary_draw_orders = { north = -1 }
},
off_when_no_fluid_recipe = true
},
open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 },
close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 },
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
working_sound =
{
sound =
{
{
filename = "__base__/sound/assembling-machine-t3-1.ogg",
volume = 0.8
},
{
filename = "__base__/sound/assembling-machine-t3-2.ogg",
volume = 0.8
},
},
idle_sound = { filename = "__base__/sound/idle1.ogg", volume = 0.6 },
apparent_volume = 1.5,
},
collision_box = {{-1.2, -1.2}, {1.2, 1.2}},
selection_box = {{-1.5, -1.5}, {1.5, 1.5}},
drawing_box = {{-1.5, -1.7}, {1.5, 1.5}},
fast_replaceable_group = "assembling-machine",
animation =
{
layers =
{
{
filename = "__base__/graphics/entity/assembling-machine-3/assembling-machine-3.png",
priority = "high",
width = 108,
height = 119,
frame_count = 32,
line_length = 8,
shift = util.by_pixel(0, -0.5),
hr_version = {
filename = "__base__/graphics/entity/assembling-machine-3/hr-assembling-machine-3.png",
priority = "high",
width = 214,
height = 237,
frame_count = 32,
line_length = 8,
shift = util.by_pixel(0, -0.75),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/assembling-machine-3/assembling-machine-3-shadow.png",
priority = "high",
width = 130,
height = 82,
frame_count = 32,
line_length = 8,
draw_as_shadow = true,
shift = util.by_pixel(28, 4),
hr_version = {
filename = "__base__/graphics/entity/assembling-machine-3/hr-assembling-machine-3-shadow.png",
priority = "high",
width = 260,
height = 162,
frame_count = 32,
line_length = 8,
draw_as_shadow = true,
shift = util.by_pixel(28, 4),
scale = 0.5
}
},
},
},
crafting_categories = {"tank-crafting", "tank-ammo-component"},
crafting_speed = 1,
energy_source =
{
type = "electric",
usage_priority = "secondary-input",
emissions = 0.05 / 3.5
},
energy_usage = "175kW",
ingredient_count = 6,
module_specification =
{
module_slots = 4
},
allowed_effects = {"consumption", "speed", "productivity", "pollution"}
},
-- -- munition maker
-- {
-- type = "assembling-machine",
-- name = "tank-ammo-assembling-machine",
-- icon = "__morebobs__/graphics/icons/tank-ammo-assembling-machine.png",
-- icon_size = 32,
-- flags = {"placeable-neutral","placeable-player", "player-creation"},
-- minable = {hardness = 0.2, mining_time = 0.5, result = "tank-ammo-assembling-machine"},
-- max_health = 150,
-- corpse = "big-remnants",
-- dying_explosion = "medium-explosion",
-- resistances =
-- {
-- {
-- type = "fire",
-- percent = 95
-- }
-- },
-- open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 },
-- close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 },
-- working_sound =
-- {
-- sound =
-- {
-- {
-- filename = "__base__/sound/assembling-machine-t3-1.ogg",
-- volume = 0.8
-- },
-- {
-- filename = "__base__/sound/assembling-machine-t3-2.ogg",
-- volume = 0.8
-- },
-- },
-- idle_sound = { filename = "__base__/sound/idle1.ogg", volume = 0.6 },
-- apparent_volume = 1.5,
-- },
-- collision_box = {{-1.2, -1.2}, {1.2, 1.2}},
-- selection_box = {{-1.5, -1.5}, {1.5, 1.5}},
-- fast_replaceable_group = "assembling-machine",
-- animation =
-- {
-- filename = "__morebobs__/graphics/entity/tank-assembling-machine/tank-assembling-machine.png",
-- priority = "high",
-- width = 142,
-- height = 113,
-- frame_count = 32,
-- line_length = 8,
-- shift = {0.84, -0.09}
-- },
-- crafting_categories = {"tank-ammo-component"},
-- crafting_speed = 1.00,
-- energy_source =
-- {
-- type = "electric",
-- usage_priority = "secondary-input",
-- emissions = 0.05 / 3.5
-- },
-- energy_usage = "175kW",
-- ingredient_count = 6,
-- module_slots = 1,
-- allowed_effects = {"consumption", "speed", "productivity", "pollution"}
-- },
-- tank-flame-thrower-explosion
{
type = "flame-thrower-explosion",
name = "tank-flame-thrower-explosion",
flags = {"not-on-map"},
animation_speed = 1,
animations =
{
{
filename = "__base__/graphics/entity/flamethrower-fire-stream/flamethrower-explosion.png",
priority = "extra-high",
width = 64,
height = 64,
frame_count = 64,
scale = 1.5,
line_length = 8
}
},
light = {intensity = 0.4, size = 16},
slow_down_factor = 0.98,
smoke = "smoke-fast",
smoke_count = 1,
smoke_slow_down_factor = 0.95,
damage =
{
amount = 1.50,
type = "fire"
}
},
-- massive-scorchmark
{
type = "corpse",
name = "massive-scorchmark",
icon = "__base__/graphics/icons/small-scorchmark.png",
icon_size = data.raw["corpse"]["small-scorchmark"].icon_size,
flags = {"placeable-neutral", "not-on-map", "placeable-off-grid"},
collision_box = {{-1.5, -1.5}, {1.5, 1.5}},
collision_mask = {"doodad-layer", "not-colliding-with-itself"},
selection_box = {{-1, -1}, {1, 1}},
selectable_in_game = false,
time_before_removed = 60 * 60 * 10, -- 10 minutes
final_render_layer = "ground-patch-higher2",
subgroup = "remnants",
order="d[remnants]-b[scorchmark]-a[small]",
animation =
{
width = 110,
height = 90,
scale = 5,
frame_count = 1,
direction_count = 1,
filename = "__base__/graphics/entity/scorchmark/small-scorchmark.png",
variation_count = 3
},
ground_patch =
{
sheet =
{
width = 110,
height = 90,
scale = 5,
frame_count = 1,
direction_count = 1,
x = 110 * 2,
filename = "__base__/graphics/entity/scorchmark/small-scorchmark.png",
variation_count = 3
}
},
ground_patch_higher =
{
sheet =
{
width = 110,
height = 90,
scale = 5,
frame_count = 1,
direction_count = 1,
x = 110,
filename = "__base__/graphics/entity/scorchmark/small-scorchmark.png",
variation_count = 3
}
}
},
-- land-mine-poison
{
type = "land-mine",
name = "land-mine-poison",
icon = "__base__/graphics/icons/land-mine.png",
icon_size = data.raw["land-mine"]["land-mine"].icon_size,
flags =
{
"placeable-player",
"placeable-enemy",
"player-creation",
"placeable-off-grid",
"not-on-map"
},
minable = {mining_time = 1, result = "land-mine"},
mined_sound = { filename = "__core__/sound/deconstruct-small.ogg" },
max_health = 15,
corpse = "small-remnants",
collision_box = {{-0.4,-0.4}, {0.4, 0.4}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
dying_explosion = "explosion-hit",
picture_safe =
{
filename = "__base__/graphics/entity/land-mine/land-mine.png",
priority = "medium",
width = 32,
height = 32
},
picture_set =
{
filename = "__base__/graphics/entity/land-mine/land-mine-set.png",
priority = "medium",
width = 32,
height = 32
},
trigger_radius = 3.5,
ammo_category = "landmine",
action =
{
type = "direct",
action_delivery =
{
type = "instant",
source_effects =
{
{
type = "nested-result",
affects_target = true,
action =
{
type = "area",
radius = 6,
collision_mask = { "player-layer" },
action_delivery =
{
type = "instant",
target_effects =
{
type = "damage",
damage = { amount = 300, type = "poison"}
}
}
},
},
{
type = "create-entity",
entity_name = "poison-cloud-2"
},
{
type = "damage",
damage = { amount = 50, type = "explosion"}
}
}
}
},
},
-- poison-cloud-2
{
type = "smoke-with-trigger",
name = "poison-cloud-2",
flags = {"not-on-map"},
show_when_smoke_off = true,
animation =
{
filename = "__base__/graphics/entity/cloud/cloud-45-frames.png",
flags = { "compressed" },
priority = "low",
width = 256,
height = 256,
frame_count = 45,
animation_speed = 0.5,
line_length = 7,
scale = 5,
},
slow_down_factor = 0,
affected_by_wind = false,
cyclic = true,
duration = 60 * 20,
fade_away_duration = 2 * 60,
spread_duration = 10,
color = { r = 0.718, g = 0.761, b = 0.200 },
action =
{
type = "direct",
action_delivery =
{
type = "instant",
target_effects =
{
type = "nested-result",
action =
{
type = "area",
radius = 18,
entity_flags = {"breaths-air"},
action_delivery =
{
type = "instant",
target_effects =
{
type = "damage",
damage = { amount = 20, type = "poison"}
}
}
}
}
}
},
action_cooldown = 30
},
-- Iron wall
{
type = "wall",
name = "iron-wall",
icon = "__morebobs__/graphics/icons/tank/iron-wall.png",
icon_size = 32,
flags = {"placeable-neutral", "player-creation"},
collision_box = {{-0.29, -0.29}, {0.29, 0.29}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
minable = {mining_time = 0.5, result = "iron-wall"},
fast_replaceable_group = "wall",
max_health = 550,
repair_speed_modifier = 2,
corpse = "wall-remnants",
repair_sound = { filename = "__base__/sound/manual-repair-simple.ogg" },
mined_sound = { filename = "__base__/sound/deconstruct-bricks.ogg" },
vehicle_impact_sound = { filename = "__base__/sound/car-stone-impact.ogg", volume = 1.0 },
-- this kind of code can be used for having walls mirror the effect
-- there can be multiple reaction items
--attack_reaction =
--{
--{
---- how far the mirroring works
--range = 2,
---- what kind of damage triggers the mirroring
---- if not present then anything triggers the mirroring
--damage_type = "physical",
---- caused damage will be multiplied by this and added to the subsequent damages
--reaction_modifier = 0.1,
--action =
--{
--type = "direct",
--action_delivery =
--{
--type = "instant",
--target_effects =
--{
--type = "damage",
---- always use at least 0.1 damage
--damage = {amount = 0.1, type = "physical"}
--}
--}
--},
--}
--},
connected_gate_visualization =
{
filename = "__core__/graphics/arrows/underground-lines.png",
priority = "high",
width = 64,
height = 64,
scale = 0.5
},
resistances =
{
{
type = "physical",
decrease = 9,
percent = 60
},
{
type = "impact",
decrease = 85,
percent = 100
},
{
type = "explosion",
decrease = 30,
percent = 90
},
{
type = "fire",
decrease = 50,
percent = 100
},
{
type = "laser",
decrease = 50,
percent = 100
}
},
pictures =
{
single =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-single.png",
priority = "extra-high",
width = 22,
height = 42,
shift = {0, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-single-shadow.png",
priority = "extra-high",
width = 47,
height = 32,
shift = {0.359375, 0.5},
draw_as_shadow = true
}
}
},
straight_vertical =
{
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-straight-vertical-1.png",
priority = "extra-high",
width = 22,
height = 42,
shift = {0, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-straight-vertical-shadow.png",
priority = "extra-high",
width = 47,
height = 60,
shift = {0.390625, 0.625},
draw_as_shadow = true
}
}
},
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-straight-vertical-2.png",
priority = "extra-high",
width = 22,
height = 42,
shift = {0, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-straight-vertical-shadow.png",
priority = "extra-high",
width = 47,
height = 60,
shift = {0.390625, 0.625},
draw_as_shadow = true
}
}
},
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-straight-vertical-3.png",
priority = "extra-high",
width = 22,
height = 42,
shift = {0, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-straight-vertical-shadow.png",
priority = "extra-high",
width = 47,
height = 60,
shift = {0.390625, 0.625},
draw_as_shadow = true
}
}
}
},
straight_horizontal =
{
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-straight-horizontal-1.png",
priority = "extra-high",
width = 32,
height = 42,
shift = {0, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-straight-horizontal-shadow.png",
priority = "extra-high",
width = 59,
height = 32,
shift = {0.421875, 0.5},
draw_as_shadow = true
}
}
},
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-straight-horizontal-2.png",
priority = "extra-high",
width = 32,
height = 42,
shift = {0, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-straight-horizontal-shadow.png",
priority = "extra-high",
width = 59,
height = 32,
shift = {0.421875, 0.5},
draw_as_shadow = true
}
}
},
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-straight-horizontal-3.png",
priority = "extra-high",
width = 32,
height = 42,
shift = {0, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-straight-horizontal-shadow.png",
priority = "extra-high",
width = 59,
height = 32,
shift = {0.421875, 0.5},
draw_as_shadow = true
}
}
}
},
corner_right_down =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-corner-right-down.png",
priority = "extra-high",
width = 27,
height = 42,
shift = {0.078125, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-corner-right-down-shadow.png",
priority = "extra-high",
width = 53,
height = 61,
shift = {0.484375, 0.640625},
draw_as_shadow = true
}
}
},
corner_left_down =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-corner-left-down.png",
priority = "extra-high",
width = 27,
height = 42,
shift = {-0.078125, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-corner-left-down-shadow.png",
priority = "extra-high",
width = 53,
height = 60,
shift = {0.328125, 0.640625},
draw_as_shadow = true
}
}
},
t_up =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-t-down.png",
priority = "extra-high",
width = 32,
height = 42,
shift = {0, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-t-down-shadow.png",
priority = "extra-high",
width = 71,
height = 61,
shift = {0.546875, 0.640625},
draw_as_shadow = true
}
}
},
ending_right =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-ending-right.png",
priority = "extra-high",
width = 27,
height = 42,
shift = {0.078125, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-ending-right-shadow.png",
priority = "extra-high",
width = 53,
height = 32,
shift = {0.484375, 0.5},
draw_as_shadow = true
}
}
},
ending_left =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-wall/wall-ending-left.png",
priority = "extra-high",
width = 27,
height = 42,
shift = {-0.078125, -0.15625}
},
{
filename = "__base__/graphics/entity/stone-wall/wall-ending-left-shadow.png",
priority = "extra-high",
width = 53,
height = 32,
shift = {0.328125, 0.5},
draw_as_shadow = true
}
}
}
},
wall_diode_green = util.conditional_return(not data.is_demo,
{
filename = "__base__/graphics/entity/gate/wall-diode-green.png",
width = 21,
height = 22,
shift = {0, -0.78125}
}),
wall_diode_green_light = util.conditional_return(not data.is_demo,
{
minimum_darkness = 0.3,
color = {g=1},
shift = {0, -0.78125},
size = 1,
intensity = 0.3
}),
wall_diode_red = util.conditional_return(not data.is_demo,
{
filename = "__base__/graphics/entity/gate/wall-diode-red.png",
width = 21,
height = 22,
shift = {0, -0.78125}
}),
wall_diode_red_light = util.conditional_return(not data.is_demo,
{
minimum_darkness = 0.3,
color = {r=1},
shift = {0, -0.78125},
size = 1,
intensity = 0.3
}),
circuit_wire_connection_point = circuit_connector_definitions["gate"].points,
circuit_connector_sprites = circuit_connector_definitions["gate"].sprites,
circuit_wire_max_distance = default_circuit_wire_max_distance,
default_output_signal = data.is_demo and {type = "virtual", name = "signal-green"} or {type = "virtual", name = "signal-G"}
},
{
type = "gate",
name = "iron-gate",
icon = "__morebobs__/graphics/icons/tank/iron-gate.png",
icon_size = 32,
flags = {"placeable-neutral","placeable-player", "player-creation"},
fast_replaceable_group = "wall",
minable = {hardness = 0.2, mining_time = 0.5, result = "iron-gate"},
max_health = 550,
corpse = "small-remnants",
collision_box = {{-0.29, -0.29}, {0.29, 0.29}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
opening_speed = 0.08,
activation_distance = 3,
timeout_to_close = 5,
resistances =
{
{
type = "physical",
decrease = 3,
percent = 20
},
{
type = "impact",
decrease = 45,
percent = 60
},
{
type = "explosion",
decrease = 10,
percent = 30
},
{
type = "fire",
percent = 100
},
{
type = "laser",
percent = 70
}
},
vertical_animation =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/gate-vertical.png",
line_length = 8,
width = 21,
height = 60,
frame_count = 16,
shift = {0.015625, -0.40625}
},
{
filename = "__base__/graphics/entity/gate/gate-vertical-shadow.png",
line_length = 8,
width = 41,
height = 50,
frame_count = 16,
shift = {0.328125, 0.3},
draw_as_shadow = true
}
}
},
horizontal_animation =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/gate-horizontal.png",
line_length = 8,
width = 32,
height = 36,
frame_count = 16,
shift = {0, -0.21875}
},
{
filename = "__base__/graphics/entity/gate/gate-horizontal-shadow.png",
line_length = 8,
width = 62,
height = 28,
frame_count = 16,
shift = {0.4375, 0.46875},
draw_as_shadow = true
}
}
},
vertical_base =
{
layers =
{
{
filename = "__base__/graphics/entity/gate/gate-base-vertical.png",
width = 32,
height = 32
},
{
filename = "__base__/graphics/entity/gate/gate-base-vertical-mask.png",
width = 32,
height = 32,
apply_runtime_tint = true
}
}
},
horizontal_rail_animation_left =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/gate-rail-horizontal-left.png",
line_length = 8,
width = 32,
height = 47,
frame_count = 16,
shift = {0, -0.140625 + 0.125}
},
{
filename = "__base__/graphics/entity/gate/gate-rail-horizontal-shadow-left.png",
line_length = 8,
width = 73,
height = 27,
frame_count = 16,
shift = {0.078125, 0.171875 + 0.125},
draw_as_shadow = true
}
}
},
horizontal_rail_animation_right =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/gate-rail-horizontal-right.png",
line_length = 8,
width = 32,
height = 43,
frame_count = 16,
shift = {0, -0.203125 + 0.125}
},
{
filename = "__base__/graphics/entity/gate/gate-rail-horizontal-shadow-right.png",
line_length = 8,
width = 73,
height = 28,
frame_count = 16,
shift = {0.60938, 0.2875 + 0.125},
draw_as_shadow = true
}
}
},
vertical_rail_animation_left =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/gate-rail-vertical-left.png",
line_length = 8,
width = 22,
height = 54,
frame_count = 16,
shift = {0, -0.46875}
},
{
filename = "__base__/graphics/entity/gate/gate-rail-vertical-shadow-left.png",
line_length = 8,
width = 47,
height = 48,
frame_count = 16,
shift = {0.27, -0.16125 + 0.5},
draw_as_shadow = true
}
}
},
vertical_rail_animation_right =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/gate-rail-vertical-right.png",
line_length = 8,
width = 22,
height = 55,
frame_count = 16,
shift = {0, -0.453125}
},
{
filename = "__base__/graphics/entity/gate/gate-rail-vertical-shadow-right.png",
line_length = 8,
width = 47,
height = 47,
frame_count = 16,
shift = {0.27, 0.803125 - 0.5},
draw_as_shadow = true
}
}
},
vertical_rail_base =
{
filename = "__base__/graphics/entity/gate/gate-rail-base-vertical.png",
line_length = 8,
width = 64,
height = 64,
frame_count = 16,
shift = {0, 0},
},
horizontal_rail_base =
{
filename = "__base__/graphics/entity/gate/gate-rail-base-horizontal.png",
line_length = 8,
width = 64,
height = 45,
frame_count = 16,
shift = {0, -0.015625 + 0.125},
},
vertical_rail_base_mask =
{
filename = "__base__/graphics/entity/gate/gate-rail-base-mask-vertical.png",
width = 63,
height = 39,
shift = {0.015625, -0.015625},
apply_runtime_tint = true
},
horizontal_rail_base_mask =
{
filename = "__base__/graphics/entity/gate/gate-rail-base-mask-horizontal.png",
width = 53,
height = 45,
shift = {0.015625, -0.015625 + 0.125},
apply_runtime_tint = true
},
horizontal_base =
{
layers =
{
{
filename = "__base__/graphics/entity/gate/gate-base-horizontal.png",
width = 32,
height = 23,
shift = {0, 0.125}
},
{
filename = "__base__/graphics/entity/gate/gate-base-horizontal-mask.png",
width = 32,
height = 23,
apply_runtime_tint = true,
shift = {0, 0.125}
}
}
},
wall_patch =
{
north =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/wall-patch-north.png",
width = 22,
height = 35,
shift = {0, -0.62 + 1}
},
{
filename = "__base__/graphics/entity/gate/wall-patch-north-shadow.png",
width = 46,
height = 31,
shift = {0.3, 0.20 + 1},
draw_as_shadow = true
}
}
},
east =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/wall-patch-east.png",
width = 11,
height = 40,
shift = {0.328125 - 1, -0.109375}
},
{
filename = "__base__/graphics/entity/gate/wall-patch-east-shadow.png",
width = 38,
height = 32,
shift = {0.8125 - 1, 0.46875},
draw_as_shadow = true
}
}
},
south =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/wall-patch-south.png",
width = 22,
height = 40,
shift = {0, -0.125}
},
{
filename = "__base__/graphics/entity/gate/wall-patch-south-shadow.png",
width = 48,
height = 25,
shift = {0.3, 0.95},
draw_as_shadow = true
}
}
},
west =
{
layers =
{
{
filename = "__morebobs__/graphics/entity/iron-gate/wall-patch-west.png",
width = 11,
height = 40,
shift = {-0.328125 + 1, -0.109375}
},
{
filename = "__base__/graphics/entity/gate/wall-patch-west-shadow.png",
width = 46,
height = 32,
shift = {0.1875 + 1, 0.46875},
draw_as_shadow = true
}
}
}
},
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
open_sound =
{
variations = { filename = "__base__/sound/gate1.ogg", volume = 0.5 },
aggregation =
{
max_count = 1,
remove = true
}
},
close_sound =
{
variations = { filename = "__base__/sound/gate1.ogg", volume = 0.5 },
aggregation =
{
max_count = 1,
remove = true
}
}
},
-- Bullet hit sound
{
type = "explosion",
name = "auto-cannon-hit",
flags = {"not-on-map"},
animations =
{
{
filename = "__base__/graphics/entity/explosion-gunshot/explosion-gunshot.png",
priority = "extra-high",
width = 34,
height = 38,
frame_count = 13,
animation_speed = 1.5,
shift = {0, 0}
}
},
rotate = true,
light = {intensity = 1, size = 10},
smoke = "smoke-fast",
smoke_count = 1,
smoke_slow_down_factor = 1,
sound =
{
filename = "__morebobs__/sounds/fight/auto-cannon-hit.ogg",
volume = 1.0
}
},
})
|
QhunUnitHealth.TargetOfTargetUnitFrame = {}
QhunUnitHealth.TargetOfTargetUnitFrame.__index = QhunUnitHealth.TargetOfTargetUnitFrame
function QhunUnitHealth.TargetOfTargetUnitFrame.new(uiInstance)
-- call super class
local instance =
QhunUnitHealth.AbstractUnitFrame.new(
uiInstance,
"targettarget",
{
"UNIT_TARGET"
},
TargetFrameToTHealthBar,
TargetFrameToTManaBar
)
-- bind current values
setmetatable(instance, QhunUnitHealth.TargetOfTargetUnitFrame)
-- create the visible frame
instance._healthFrame = instance:createFrame("HEALTH")
instance._powerFrame = instance:createFrame("POWER")
return instance
end
-- set inheritance
setmetatable(QhunUnitHealth.TargetOfTargetUnitFrame, {__index = QhunUnitHealth.AbstractUnitFrame})
--[[
PUBLIC FUNCTIONS
]]
-- update the player resource frame
function QhunUnitHealth.TargetOfTargetUnitFrame:update(...)
self:genericUpdate("targettarget")
end
-- get the current storage options for the TargetOfTargetUnitFrame
function QhunUnitHealth.TargetOfTargetUnitFrame:getOptions()
return QhunUnitHealth.Storage:get("TARGET_OF_TARGET")
end
-- is the tot frame enabled
function QhunUnitHealth.TargetOfTargetUnitFrame:isEnabled()
return QhunUnitHealth.Storage:get("TARGET_OF_TARGET_ENABLED")
end |
local TalentPlanner = {}
--[[
TODO:
actual character points on TalentFrame
]]--
TalentPlanner.options = {
learningEnabled = true,
allowVirtualBuild = false, -- allows the planner to remove points actually assigned for planning purposes
state = false,
assumedLevel = 60
}
TalentPlanner.data = {}
TalentPlanner.hooked = {}
TalentPlanner.current = {}
TalentPlanner.ui = {}
TalentPlanner.exporters = {}
TalentPlanner.importers = {}
SARF_TP = TalentPlanner
function TalentPlanner:GetQueueTotal(tab, id)
local amount = 0
local first = nil
local last = nil
for k, v in ipairs(self.current) do
if (v[1] == tab and v[2] == id) then
amount = amount + 1
if type(first) ~= "number" or first > k then first = k end
if type(last) ~= "number" or last < k then last = k end
end
end
return amount, first, last
end
function TalentPlanner:PatchTalentButtonIfNeeded(name, parent)
local virtualRank = _G[name]
if not virtualRank then
local fs = TalentPlanner.frame:CreateFontString("FontString", name, parent)
fs:SetFont("Fonts\\FRIZQT__.TTF", 11, "OUTLINE, MONOCHROME")
fs:SetPoint("CENTER",parent:GetName(),"BOTTOMRIGHT", 0, 0)
virtualRank = fs
end
return virtualRank
end
function TalentPlanner:SimpleHookCall(globalName, ...)
if type(self.hooked[globalName]) == "function" then
return self.hooked[globalName](select(1, ...))
end
return false, globalName .. " was not a hooked function"
end
function TalentPlanner:SimpleHook(globalName, func)
if type(func) ~= "function" then return false, "given function was not, actually, a function but instead " .. type(func) end
local globalFunc = _G[globalName]
if type(globalFunc) ~= "function" then return false, globalName .. " is not a function" end
if self.hooked[globalName] == func then
return false, globalName .. " was already hooked the specified function"
end
if self.hooked[globalName] then return false, globalName .. " was already hooked" end
self.hooked[globalName] = globalFunc
_G[globalName] = func
return true
end
function TalentPlanner:ShouldOverride()
return TalentPlanner.data.overrideEnabled and TalentPlanner.options.state
end
function TalentPlanner:PatchTalentAPI()
self:SimpleHook("TalentFrame_OnShow", function(self)
TalentPlanner.data.overrideEnabled = true
return TalentPlanner:SimpleHookCall("TalentFrame_OnShow", self)
end)
self:SimpleHook("TalentFrame_OnHide", function(self)
TalentPlanner.data.overrideEnabled = false
return TalentPlanner:SimpleHookCall("TalentFrame_OnHide", self)
end)
self:SimpleHook("GetTalentTabInfo", function(tab)
local a,b,c,d,e,f,g,h,i,j,k = TalentPlanner:SimpleHookCall("GetTalentTabInfo", tab)
if TalentPlanner:ShouldOverride() then
c = TalentPlanner:GetPointsSpentInTab(tab)
end
return a,b,c,d,e,f,g,h,i,j,k
end)
self:SimpleHook("GetTalentPrereqs", function(tab, id)
local arr = {TalentPlanner.hooked["GetTalentPrereqs"](tab, id)}
if TalentPlanner:ShouldOverride() then
for i = 1, #arr, 3 do
local rank, maxRank = select(5, GetTalentInfo(arr[i], arr[i+1]))
if rank == maxRank then
arr[i+2] = true
end
end
end
return unpack(arr)
end)
TalentPlanner:SimpleHook("GetTalentInfo", function(tab, id)
local a,b,c,d,e,f,g,h,i,j,k = TalentPlanner.hooked["GetTalentInfo"](tab, id)
--TalentPlanner:Print("GetTalentInfo(" .. tab .. ", ".. id ..") => " .. dumpValue({a,b,c,d,e,f,g,h,i,j,k}, 1, true))
if TalentPlanner:ShouldOverride() then
if TalentPlanner.current.virtual then
e = TalentPlanner:GetQueueTotal(tab, id)
else
-- non-virtual build means it is based on your current build and is, in fact, possible to apply.
e = e + TalentPlanner:GetQueueTotal(tab, id)
end
end
return a,b,c,d,e,f,g,h,i,j,k
end)
TalentPlanner:SimpleHook("UnitCharacterPoints", function(unit)
local a,b,c,d,e,f,g,h,i,j,k = TalentPlanner.hooked["UnitCharacterPoints"](unit)
if TalentPlanner:ShouldOverride() then
a = TalentPlanner:GetPointsLeft(TalentPlanner.options.assumedLevel)
end
return a,b,c,d,e,f,g,h,i,j,k
end)
end
function TalentPlanner:CreateTalentList(useHooked)
local GetTalentInfoFunc = GetTalentInfo
if useHooked then
GetTalentInfoFunc = function(a, b) return self:CallHookedGlobal("GetTalentInfo", a, b) end
end
local talentList = {}
for tab = 1, 3 do
local tabList = {}
local tabRanks = 0
local tierStructure = {}
local reversePosition = {}
local tierRanks = {}
for talent = 1, MAX_NUM_TALENTS or 20 do
local name, _, t, c, rank, maxRank = GetTalentInfoFunc(tab, talent)
if not name then break end
tierRanks[t] = (tierRanks[t] or 0) + rank
tabRanks = tabRanks + rank
if not tierStructure[t] then tierStructure[t] = {} end
reversePosition[talent] = { t, c}
tierStructure[t][c] = talent
table.insert(tabList, { name = name, tier = c, column = c, rank = rank, maxRank = maxRank })
end
tabList.tab = tab
tabList.ranks = tabRanks
tabList.tierRanks = tierRanks
tabList.tierStructure = tierStructure
tabList.reversePosition = reversePosition
table.insert(talentList, tabList)
end
return talentList
end
function TalentPlanner:Virtualize(build)
if not build.virtual then
local total = 1
for tab = 1, 3 do
for talent = 1, MAX_NUM_TALENTS or 20 do
local name, _, _, _, rank, maxRank = self.hooked["GetTalentInfo"](tab, talent)
if not name then break end
while rank > 0 do
table.insert(build, total, { tab, talent})
rank = rank - 1
total = total + 1
end
end
end
build.virtual = true
end
end
-- function TalentPlanner:Devirtualize(build) build.virtual = false end
function TalentPlanner:RemovePointFrom(tab, id)
local name, _, _, _, rank, maxRank = GetTalentInfo(tab, id)
if rank <= 0 then return end
local amount, first, last = self:GetQueueTotal(tab, id)
if amount <= 0 then
if self.options.allowVirtualBuild then
if not self.current.isVirtual then
self:Virtualize(self.current)
self:RemovePointFrom(tab, id)
return
end
else
return false, "can not reduce below actual talent"
end
end
-- Last talent point spent, no checks needs to be made
if last == #self.current then
table.remove(self.current, last)
else
-- le sigh
local talentList = self:CreateTalentList()
local tabInfo = talentList[tab]
local position = tabInfo.reversePosition[id]
local currentTier = position[1] or 1
local nextTierPoints = tabInfo.tierRanks[currentTier + 1] or 0
local accumulatedPointsUpToAndIncluding = 0
for i = 1, currentTier do
accumulatedPointsUpToAndIncluding = accumulatedPointsUpToAndIncluding + tabInfo.tierRanks[i]
end
local accumulatedPointsAbove = 0
for i = currentTier + 1, 20 do
local points = tabInfo.tierRanks[i]
if not points then break end
accumulatedPointsAbove = accumulatedPointsAbove + points
end
if accumulatedPointsAbove > 0 and (accumulatedPointsUpToAndIncluding - 1) < (currentTier + 1) * 5 then
return false, "can not remove, build would become invalid"
end
local _, _, t, c, rank, maxRank = self.hooked["GetTalentInfo"](tab, id)
-- LE SIIIIIIIIIGH
for i = 1, MAX_NUM_TALENTS or 20 do
local name, _, _, _, r = GetTalentInfo(tab, i)
if not name then break end
if (r > 0) then
local response = {GetTalentPrereqs(tab, i)}
for j = 1, #response, 3 do
if response[j] == t and response[j+1] == c then
return false, "is prerequisite for other talent"
end
end
end
end
end
TalentFrame_Update()
return true
end
function TalentPlanner:GetPointsSpentInTab(tab)
local total = 0
for id = 1, 20 do
local name, _, _, _, rank = GetTalentInfo(tab, id)
if not name then break end
total = total + (rank or 0)
end
return total
end
function TalentPlanner:GetPointsSpentTotal()
local total = 0
for tab = 1, 3 do
total = total + self:GetPointsSpentInTab(tab)
end
return total
end
function TalentPlanner:GetPointsLeft(assumedLevel)
return (assumedLevel or (UnitLevel("player") - 10)) - self:GetPointsSpentTotal()
end
function TalentPlanner:AddPointIn(tab, id)
local name, iconTexture, tier, column, rank, maxRank, isExceptional, available = GetTalentInfo(tab, id)
if not name then return false end
if(rank < maxRank) and self:GetPointsLeft(60) > 0 then
table.insert(self.current, { tab, id })
TalentFrame_Update()
return true
end
return false
end
function TalentPlanner:TalentFrameTalentButton_OnClick(button, mouseButton)
if button:IsEnabled() and TalentPlanner:ShouldOverride() then
local id = button:GetID()
local tab = PanelTemplates_GetSelectedTab(TalentFrame)
if (mouseButton == "RightButton") then
TalentPlanner:RemovePointFrom(tab, id)
else
TalentPlanner:AddPointIn(tab, id)
end
end
end
function TalentPlanner:Reset()
local queue = self.current
if TalentPlanner.options.state then
if #self.current > 0 then
while(#queue > 0) do table.remove(queue, 1) end
for k, v in pairs(queue) do queue[k] = nil end
else
TalentPlanner.options.state = false
end
else
TalentPlanner.options.state = true
end
TalentFrame_Update()
end
function TalentPlanner:CreateButton(n, text, x, onClick)
local applyButton = _G[n] or CreateFrame("Button", n, TalentFrame, "UIPanelButtonTemplate")
applyButton:SetText(text)
--applyButton:SetFrameStrata("NORMAL")
applyButton:SetWidth(60)
applyButton:SetHeight(18)
applyButton:SetScript("OnClick", onClick)
applyButton:SetPoint("CENTER","TalentFrame","TOPLEFT", x, -420)
end
function TalentPlanner:PatchTalentButtons()
local i = 1
local n = "TalentFrameTalent"..i
local button = _G[n]
local func = function(button, mouseButton) return TalentPlanner:TalentFrameTalentButton_OnClick(button, mouseButton) end
local handler = "OnClick"
while button do
if not TalentPlanner.hooked[n] then TalentPlanner.hooked[n] = {} end
if not TalentPlanner.hooked[n][handler] then
TalentPlanner.hooked[n][handler] = button:GetScript(handler)
button:SetScript(handler, func)
end
i = i + 1
n = "TalentFrameTalent"..i
button = _G[n]
end
end
function TalentPlanner:CallHookedGlobal(name, ...)
local func = self.hooked[name]
if type(func) ~= "function" then
func = _G[name]
end
return func(select(1, ...))
end
function TalentPlanner:TalentFrame_Update()
self:CallHookedGlobal("TalentFrame_Update")
-- apply part
local applyState = true
local resetState = true
if self.current.virtual then
-- TODO: create fontString that shows ("virtual build") preferably with tooltip ("diverged from actual current build, can not be applied")
applyState = false
end
if #self.current <= 0 then
applyState = false
resetState = false
end
if applyState then
TalentFrameApplyButton:Enable()
else
TalentFrameApplyButton:Disable()
end
if TalentPlanner.options.state then
if #self.current > 0 then
TalentFrameResetButton:SetText("Reset")
else
TalentFrameResetButton:SetText("Stop")
end
else
TalentFrameResetButton:SetText("Start")
end
TalentFrameResetButton:Enable()
end
function TalentPlanner:Colourize(text, colour)
local colourText = colour
if colour == "RED" then colourText = "FFEF1212" end
if colour == "GREEN" then colourText = "FF12EF12" end
if colour == "BLUE" then colourText = "FF1212EF" end
if colour == "LIGHTBLUE" then colourText = "FF5252EF" end
if colour == "RB" then colourText = "FFEF12EF" end
if colour == "YELLOW" then colourText = "FFEFEF12" end
if colour == "CYAN" then colourText = "FF12EFEF" end
if colour == "WHITE" then colourText = "FFFFFFEF" end
return "|c" .. colourText .. text .. "|r"
end
function TalentPlanner:Print(msg)
ChatFrame1:AddMessage(self:Colourize("TP", "GREEN") .. ": " .. tostring(msg), 1, 1, 0)
end
function TalentPlanner:Apply()
local talentPoints = self:CallHookedGlobal("UnitCharacterPoints", "player");
local queue = self.current
if (not self.current.virtual and talentPoints >= 0 or TalentPlanner.options.learningEnabled) and #queue > 0 then
local entry = table.remove(queue, 1)
local name, _, _, _, rank, maxRank, _, available = self:CallHookedGlobal("GetTalentInfo", entry[1], entry[2])
local nameRankStr = name
if(maxRank > 1) then nameRankStr = nameRankStr .. " (" .. (rank+1) .. "/" .. maxRank .. ")" end
if rank >= maxRank or not available then
TalentPlanner:Print("Attempting to learn " .. nameRankStr .. " but it is unlikely to work...")
else
TalentPlanner:Print("Attempting to learn " .. nameRankStr)
end
if TalentPlanner.options.learningEnabled then
LearnTalent(entry[1], entry[2])
local _, _, _, _, newRank = self:CallHookedGlobal("GetTalentInfo", entry[1], entry[2]);
if newRank > rank then
local extra = ""
if maxRank > 1 then
extra = extra .. string.format(" (%d / %d)", newRank, maxRank)
end
TalentPlanner:Print("Learnt " .. nameRankStr .. extra)
end
end
end
end
function TalentPlanner:TalentUILoaded()
self:Print("Patching TalentUILoaded")
self:PatchTalentAPI()
pcall(function() TalentPlanner.frame:UnregisterEvent("ADDON_LOADED") end)
self:PatchTalentButtons()
local hookGlobal = {"TalentFrame_Update"}
for k, n in ipairs(hookGlobal) do
if type(TalentPlanner[n]) == "function" and not TalentPlanner.hooked[n] then
TalentPlanner.hooked[n] = _G[n]
_G[n] = function() return TalentPlanner[n](TalentPlanner) end
end
end
if not self.ui.TalentFrameApplyButton then
self.ui.TalentFrameApplyButton = self:CreateButton("TalentFrameApplyButton", "Apply", 45, function() return TalentPlanner:Apply() end)
end
if not self.ui.TalentFrameResetButton then
self.ui.TalentFrameResetButton = self:CreateButton("TalentFrameResetButton", "Start", 105, function() return TalentPlanner:Reset() end)
end
end
getString = function(k)
if type(k) == "boolean" then if(k) then return "true" else return "false" end end
return tostring(k)
end
dumpValue = function(str, level, noNewLine)
if type(str) ~= "table" then return getString(str) end
if type(level) ~= "number" then level = 1 end
local q = ""
local nl = "\n"
if noNewLine then nl = ", " end
for i = 1, level do q = q .. "{" end
for k, v in ipairs(str) do
q = q .. " " .. getString(k) .. " => " .. dumpValue(v, level + 1, noNewLine) .. nl
end
for i = 1, level do q = q .. "}" end
return q
end
TalentPlanner.ADDON_LOADED = function(addon)
if(addon == "Blizzard_TalentUI") then
TalentPlanner:TalentUILoaded()
end
end
TalentPlanner.frame = CreateFrame("Frame")
TalentPlanner.frame:SetScript("OnEvent", function(frame, ...)
local event = select(1, ...)
if type(TalentPlanner[event]) == "function" then TalentPlanner[event](select(2, ...)) end
end)
if TalentFrameTalent_OnClick or IsAddOnLoaded("Blizzard_TalentUI") then
TalentPlanner:TalentUILoaded()
else
TalentPlanner.frame:RegisterEvent("ADDON_LOADED")
end
function TalentPlanner:ExporterWoWHeadClassic()
local megaStr = ""
for tab = 1, 3 do
if not map[tab] then map[tab] = {} end
local actual = {}
for id = 1, 20 do
local name, _, tier, column, rank = GetTalentInfo(tab, id)
if not name then break end
if not actual[tier] then actual[tier] = {} end
actual[tier][column] = rank
end
local tier = 1
local tabStr = ""
while actual[tier] do
for i = 1, 10 do
if not actual[tier][i] then break end
tabStr = tabStr .. actual[tier][i]
end
tier = tier + 1
end
if megaStr:len() > 0 then megaStr = megaStr.."-" end
megaStr = megaStr .. tabStr
end
return "https://classic.wowhead.com/talent-calc/hunter/" .. megaStr
end
|
local null_ls = requirePlugin("null-ls")
if not null_ls then
return
end
local formatting = null_ls.builtins.formatting
local diagnostics = null_ls.builtins.diagnostics
local code_actions = null_ls.builtins.code_actions
null_ls.setup({
debug = true,
sources = {
-- frontend
-- diagnostics.eslint_d,
-- code_actions.eslint_d,
-- diagnostics.eslint.with({
-- prefer_local = "node_modules/.bin",
-- }),
-- code_actions.eslint.with({
-- prefer_local = "node_modules/.bin",
-- }),
-- diagnostics.markdownlint,
-- markdownlint-cli2
-- diagnostics.markdownlint.with({
-- prefer_local = "node_modules/.bin",
-- command = "markdownlint-cli2",
-- args = { "$FILENAME", "#node_modules" },
-- }),
--
-- formatting.prettier,
formatting.prettier.with({
-- 比默认少了 markdown
filetypes = {
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"vue",
"css",
"scss",
"less",
"html",
"json",
"yaml",
"graphql",
},
prefer_local = "node_modules/.bin",
}),
-- lua
formatting.stylua,
},
-- #{m}: message
-- #{s}: source name (defaults to null-ls if not specified)
-- #{c}: code (if available)
diagnostics_format = "[#{s}] #{m}",
on_attach = function(_)
vim.cmd([[ command! Format execute 'lua vim.lsp.buf.formatting()']])
-- if client.resolved_capabilities.document_formatting then
-- vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()")
-- end
end,
})
|
local function unityLuaSearcher(name)
if _G["__gamemodules_lua__" .. name] ~= nil then
return assert(load(_G["__gamemodules_lua__" .. name].text))
end
end
table.insert(package.searchers, 2, unityLuaSearcher)
|
local ai_controller = {}
function ai_controller:load(world, movables)
self.world = world
self.movables = movables
self.player = movables[1]
self.frequency = 15
self.counter = 0
end
function ai_controller:update(dt)
self.counter = self.counter + 1
if self.counter > self.frequency then
self.counter = 0
for i = 1, #self.movables do
if self.movables[i].ai then
self.movables[i].ai:act(self.player)
end
end
end
end
return ai_controller |
--------------------------------
-- @module TransitionProgress
-- @extend TransitionScene
-- @parent_module cc
--------------------------------
--
-- @function [parent=#TransitionProgress] create
-- @param self
-- @param #float t
-- @param #cc.Scene scene
-- @return TransitionProgress#TransitionProgress ret (return value: cc.TransitionProgress)
return nil
|
local HOTKEY = "F4"
local TOGGLE_CMD = "togglets"
local TEXTURE_FILENAME = "img/arrow_ts.png"
local MAX_DIST = 60
local g_Root = getRootElement()
local g_ResRoot = getResourceRootElement(getThisResource())
local g_Me = getLocalPlayer()
local g_SmoothList = {} -- {player = rrz}
local g_AllPlayers = {}
local g_FinishedPlayers = {}
local g_LastSmoothSeconds = 0
local g_BeginValidSeconds = nil
local g_Enabled = false -- Manual override
local g_Allowed = true -- Map override
local g_Hidden = false -- Black screen override
local g_Tex, g_TexW, g_TexH
addEvent("onClientMapStarting", true)
addEvent("onClientMapStopping", true)
addEvent("onClientPlayerFinish", true)
addEvent("onClientScreenFadedOut", true)
addEvent("onClientScreenFadedIn", true)
local function TsRender()
-- Ensure map allows it, and player not dead, and in a vehicle and not spectating
local vehicle = getPedOccupiedVehicle(g_Me)
if(not g_Allowed or isPedDead(g_Me) or g_FinishedPlayers[g_Me]
or not vehicle or getCameraTarget() ~= vehicle) then
g_BeginValidSeconds = nil
return
end
-- Ensure at least 1 second since g_BeginValidSeconds was set
local timeSeconds = getTickCount()/1000
if(not g_BeginValidSeconds) then
g_BeginValidSeconds = timeSeconds
end
if timeSeconds - g_BeginValidSeconds < 1 then return end
-- No draw if faded out or not enabled
if(g_Hidden or not g_Enabled) then return end
-- Calc smoothing vars
local delta = timeSeconds - g_LastSmoothSeconds
g_LastSmoothSeconds = timeSeconds
local timeslice = math.clamp(0,delta*14,1)
-- Get screen dimensions
local screenX,screenY = guiGetScreenSize()
local halfScreenX = screenX * 0.5
local halfScreenY = screenY * 0.5
-- Get my pos and rot
local mx, my, mz = getElementPosition(g_Me)
local _, _, mrz = getCameraRot()
local myDim = getElementDimension(g_Me)
-- To radians
mrz = math.rad(-mrz)
-- For each 'other player'
for player, _ in pairs(g_AllPlayers) do
local isDead = isPedDead(player)
local dim = getElementDimension(player)
if(player ~= g_Me and not isDead and not g_FinishedPlayers[player] and dim == myDim) then
-- Get other pos
local ox, oy, oz = getElementPosition(player)
-- Only draw marker if other player it is close enough, and not on screen
local alpha = 1 - getDistanceBetweenPoints3D(mx, my, mz, ox, oy, oz) / MAX_DIST
local onScreen = getScreenFromWorldPosition(ox, oy, oz)
if onScreen or alpha <= 0 then
-- If no draw, reset smooth position
g_SmoothList[player] = nil
else
-- Calc arrow color
local r,g,b = 255,220,210
local team = getPlayerTeam(player)
if team then
r,g,b = getTeamColor(team)
end
-- Calc draw scale
local scalex = alpha * 0.5 + 0.5
local scaley = alpha * 0.25 + 0.75
-- Calc dir to
local dx = ox - mx
local dy = oy - my
-- Calc rotz to
local drz = math.atan2(dx,dy)
-- Calc relative rotz to
local rrz = drz - mrz
-- Add smoothing to the relative rotz
local smooth = g_SmoothList[player] or rrz
smooth = math.wrapdifference(-math.pi, smooth, rrz, math.pi)
if math.abs(smooth-rrz) > 1.57 then
smooth = rrz -- Instant jump if more than 1/4 of a circle to go
end
smooth = math.lerp( smooth, rrz, timeslice )
g_SmoothList[player] = smooth
rrz = smooth
-- Calc on screen pos for relative rotz
local sx = math.sin(rrz)
local sy = math.cos(rrz)
-- Draw at edge of screen
local X1 = halfScreenX
local Y1 = halfScreenY
local X2 = sx * halfScreenX + halfScreenX
local Y2 = -sy * halfScreenY + halfScreenY
local X
local Y
if(math.abs(sx) > math.abs(sy)) then
-- Left or right
if X2 < X1 then
-- Left
X = 32
Y = Y1+ (Y2-Y1)* (X-X1) / (X2-X1)
else
-- right
X = screenX-32
Y = Y1+ (Y2-Y1)* (X-X1) / (X2-X1)
end
else
-- Top or bottom
if Y2 < Y1 then
-- Top
Y = 32
X = X1+ (X2-X1)* (Y-Y1) / (Y2 - Y1)
else
-- bottom
Y = screenY-32
X = X1+ (X2-X1)* (Y-Y1) / (Y2 - Y1)
end
end
local clr = tocolor(r, g, b, 255*alpha)
local w, h = g_TexW*scalex, g_TexH*scaley
local x, y = X - w/2, Y - h/2
dxDrawImage(x, y, w, h, g_Tex, 180 + rrz * 180 / math.pi, 0, 0, clr, false)
end
end
end
end
local function TsMapStarting(mapinfo)
if(mapinfo.modename == "Destruction derby" or mapinfo.modename == "Freeroam") then
g_Allowed = false
else
g_Allowed = true
end
g_FinishedPlayers = {}
end
local function TsMapStopping()
g_Allowed = false
end
local function TsPlayerFinish()
g_FinishedPlayers[source] = true
end
local function TsScreenFadeOut()
g_Hidden = true
end
local function TsScreenFadeIn()
g_Hidden = false
end
local function TsPlayerJoin()
g_AllPlayers[source] = true
end
local function TsPlayerQuit()
g_FinishedPlayers[source] = nil
g_AllPlayers[source] = nil
g_SmoothList[source] = nil
end
function TsEnable()
if(g_Enabled) then return end
g_Enabled = true
g_Tex = dxCreateTexture(TEXTURE_FILENAME)
if(g_Tex) then
g_TexW, g_TexH = dxGetMaterialSize(g_Tex)
end
addEventHandler("onClientRender", g_Root, TsRender)
end
function TsDisable()
if(not g_Enabled) then return end
g_Enabled = false
if(g_Tex) then
destroyElement(g_Tex)
end
removeEventHandler("onClientRender", g_Root, TsRender)
end
local function TsToggle()
if(g_Enabled) then
TsDisable()
else
TsEnable()
end
if(g_Enabled) then
outputChatBox("Traffic Sensor is now enabled", 0, 255, 0)
else
outputChatBox("Traffic Sensor is now disabled", 255, 0, 0)
end
end
local function TsInit()
for i, player in ipairs(getElementsByType("player")) do
g_AllPlayers[player] = true
end
addEventHandler("onClientMapStarting", g_Root, TsMapStarting)
addEventHandler("onClientMapStopping", g_Root, TsMapStopping)
addEventHandler("onClientPlayerFinish", g_Root, TsPlayerFinish)
addEventHandler("onClientPlayerJoin", g_Root, TsPlayerJoin)
addEventHandler("onClientPlayerQuit", g_Root, TsPlayerQuit)
addEventHandler("onClientScreenFadedOut", g_Root, TsScreenFadeOut)
addEventHandler("onClientScreenFadedIn", g_Root, TsScreenFadeIn)
addCommandHandler(TOGGLE_CMD, TsToggle, false, false)
bindKey(HOTKEY, "down", TOGGLE_CMD)
end
addEventHandler("onClientResourceStart", g_ResRoot, TsInit)
|
local present, gitsigns = pcall(require, 'gitsigns')
if not present then
require('vima.utils').notify_missing('gitsigns.nvim')
return
end
local on_attach = function(bufnr)
require('vima.plugins.which-key').setup_gitsigns_mappings(gitsigns, bufnr)
end
gitsigns.setup({
on_attach = on_attach,
signs = {
add = {
hl = 'GitSignsAdd',
text = '▎',
numhl = 'GitSignsAddNr',
linehl = 'GitSignsAddLn',
},
change = {
hl = 'GitSignsChange',
text = '▎',
numhl = 'GitSignsChangeNr',
linehl = 'GitSignsChangeLn',
},
delete = {
hl = 'GitSignsDelete',
text = '契',
numhl = 'GitSignsDeleteNr',
linehl = 'GitSignsDeleteLn',
},
topdelete = {
hl = 'GitSignsDelete',
text = '契',
numhl = 'GitSignsDeleteNr',
linehl = 'GitSignsDeleteLn',
},
changedelete = {
hl = 'GitSignsChange',
text = '▎',
numhl = 'GitSignsChangeNr',
linehl = 'GitSignsChangeLn',
},
},
current_line_blame = false,
current_line_blame_formatter_opts = {
relative_time = true,
},
preview_config = {
border = 'rounded',
},
})
|
local configs = require 'nvim_lsp/configs'
local util = require 'nvim_lsp/util'
local name = "rnix"
local function make_installer()
local P = util.path.join
local install_dir = P{util.base_install_dir, name}
local bin = P{install_dir, "bin", "rnix-lsp"}
local cmd = {bin}
local X = {}
function X.install()
local install_info = X.info()
if install_info.is_installed then
print(name, "is already installed")
return
end
if not (util.has_bins("cargo")) then
error('Need "cargo" to install this.')
return
end
local install_cmd = "cargo install rnix-lsp --root=" .. install_info.install_dir .. " rnix-lsp"
vim.fn.system(install_cmd)
end
function X.info()
return {
is_installed = util.path.exists(bin);
install_dir = install_dir;
cmd = cmd;
}
end
function X.configure(config)
local install_info = X.info()
if install_info.is_installed then
config.cmd = cmd
end
end
return X
end
local installer = make_installer()
configs[name] = {
default_config = {
cmd = {"rnix-lsp"};
filetypes = {"nix"};
root_dir = function(fname)
return util.find_git_ancestor(fname) or vim.loop.os_homedir()
end;
settings = {
};
on_new_config = function(config)
installer.configure(config)
end;
init_options = {
};
};
docs = {
description = [[
https://github.com/nix-community/rnix-lsp
A language server for Nix providing basic completion and formatting via nixpkgs-fmt.
To install manually, run `cargo install rnix-lsp`. If you are using nix, rnix-lsp is in nixpkgs.
This server accepts configuration via the `settings` key.
]];
default_config = {
root_dir = "vim's starting directory";
};
};
};
configs[name].install = installer.install
configs[name].install_info = installer.info
|
--# selene: allow(unused_variable)
---@diagnostic disable: unused-local
-- This sub-module provides access to the current location set configuration settings in the system's dynamic store.
---@class hs.network.configuration
local M = {}
hs.network.configuration = M
-- Returns the name of the computeras specified in the Sharing Preferences, and its string encoding
--
-- Parameters:
-- * None
--
-- Returns:
-- * name - the computer name
-- * encoding - the encoding type
--
-- Notes:
-- * You can also retrieve this information as key-value pairs with `hs.network.configuration:contents("Setup:/System")`
function M:computerName() end
-- Returns the name of the user currently logged into the system, including the users id and primary group id
--
-- Parameters:
-- * None
--
-- Returns:
-- * name - the user name
-- * uid - the user ID for the user
-- * gid - the user's primary group ID
--
-- Notes:
-- * You can also retrieve this information as key-value pairs with `hs.network.configuration:contents("State:/Users/ConsoleUser")`
function M:consoleUser() end
-- Return the contents of the store for the specified keys or keys matching the specified pattern(s)
--
-- Parameters:
-- * keys - a string or table of strings containing the keys or patterns of keys, if `pattern` is true. Defaults to all keys.
-- * pattern - a boolean indicating wether or not the string(s) provided are to be considered regular expression patterns (true) or literal strings to match (false). Defaults to false.
--
-- Returns:
-- * a table of key-value pairs from the dynamic store which match the specified keys or key patterns.
--
-- Notes:
-- * if no parameters are provided, then all key-value pairs in the dynamic store are returned.
function M:contents(keys, pattern, ...) end
-- Return the DHCP information for the specified service or the primary service if no parameter is specified.
--
-- Parameters:
-- * serviceID - an optional string contining the service ID of the interface for which to return DHCP info. If this parameter is not provided, then the default (primary) service is queried.
--
-- Returns:
-- * a table containing DHCP information including lease time and DHCP options
--
-- Notes:
-- * a list of possible Service ID's can be retrieved with `hs.network.configuration:contents("Setup:/Network/Global/IPv4")`
-- * generates an error if the service ID is invalid or was not assigned an IP address via DHCP.
function M:dhcpInfo(serviceID, ...) end
-- Returns the current local host name for the computer
--
-- Parameters:
-- * None
--
-- Returns:
-- * name - the local host name
--
-- Notes:
-- * You can also retrieve this information as key-value pairs with `hs.network.configuration:contents("Setup:/System")`
function M:hostname() end
-- Return the keys in the dynamic store which match the specified pattern
--
-- Parameters:
-- * keypattern - a regular expression specifying which keys to return (defaults to ".*", or all keys)
--
-- Returns:
-- * a table of keys from the dynamic store.
function M:keys(keypattern, ...) end
-- Returns the current location identifier
--
-- Parameters:
-- * None
--
-- Returns:
-- * location - the UUID for the currently active network location
--
-- Notes:
-- * You can also retrieve this information as key-value pairs with `hs.network.configuration:contents("Setup:")`
-- * If you have different locations defined in the Network preferences panel, this can be used to determine the currently active location.
function M:location() end
-- Returns all configured locations
--
-- Parameters:
-- * None
--
-- Returns:
-- * a table of key-value pairs mapping location UUIDs to their names
--
function M:locations() end
-- Specify the key(s) or key pattern(s) to monitor for changes.
--
-- Parameters:
-- * keys - a string or table of strings containing the keys or patterns of keys, if `pattern` is true. Defaults to all keys.
-- * pattern - a boolean indicating wether or not the string(s) provided are to be considered regular expression patterns (true) or literal strings to match (false). Defaults to false.
--
-- Returns:
-- * the store Object
--
-- Notes:
-- * if no parameters are provided, then all key-value pairs in the dynamic store are monitored for changes.
function M:monitorKeys(keys, pattern, ...) end
-- Opens a session to the dynamic store maintained by the System Configuration server.
--
-- Parameters:
-- * None
--
-- Returns:
-- * the storeObject
function M.open() end
-- Returns information about the currently active proxies, if any
--
-- Parameters:
-- * None
--
-- Returns:
-- * a table of key-value pairs describing the current proxies in effect, both globally, and scoped to specific interfaces.
--
-- Notes:
-- * You can also retrieve this information as key-value pairs with `hs.network.configuration:contents("State:/Network/Global/Proxies")`
function M:proxies() end
-- Set or remove the callback function for a store object
--
-- Parameters:
-- * a function or nil to set or remove the store object callback function
--
-- Returns:
-- * the store object
--
-- Notes:
-- * The callback function will be invoked each time a monitored key changes value and the callback function should accept two parameters: the storeObject itself, and an array of the keys which contain values that have changed.
-- * This method just sets the callback function. You specify which keys to watch with [hs.network.configuration:monitorKeys](#monitorKeys) and start or stop the watcher with [hs.network.configuration:start](#start) or [hs.network.configuartion:stop](#stop)
function M:setCallback(fn, ...) end
-- Switches to a new location
--
-- Parameters:
-- * location - string containing name or UUID of new location
--
-- Returns:
-- * bool - true if the location was successfully changed, false if there was an error
---@return boolean
function M:setLocation(location, ...) end
-- Starts watching the store object for changes to the monitored keys and invokes the callback function (if any) when a change occurs.
--
-- Parameters:
-- * None
--
-- Returns:
-- * the store object
--
-- Notes:
-- * The callback function should be specified with [hs.network.configuration:setCallback](#setCallback) and the keys to monitor should be specified with [hs.network.configuration:monitorKeys](#monitorKeys).
function M:start() end
-- Stops watching the store object for changes.
--
-- Parameters:
-- * None
--
-- Returns:
-- * the store object
function M:stop() end
|
config = {}
function reload_config()
local path = load('lspconfig').util.root_pattern("nvim.lua")(fn.expand('%:p'))
if path then
config = loadfile(path..'/nvim.lua')()
end
end
function merge_config(root, tbl)
return table.merge(tbl, config[root] or {})
end
reload_config()
|
--[[
Made for 0.9.21
Copyright (C) 2012 Vatten
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.
]]
HedgewarsScriptLoad("/Scripts/Locale.lua")
HedgewarsScriptLoad("/Scripts/Utils.lua")
HedgewarsScriptLoad("/Scripts/Tracker.lua")
function int_sqrt(num)
local temp=num
while(temp*temp-div(temp,2)>num)
do
temp=div((temp+div(num,temp)),2)
end
return math.abs(temp)
end
function norm(xx,yy)
--to fix overflows
if(((math.abs(xx)^2)+(math.abs(yy)^2))>2^26)
then
local bitr=2^13
return int_sqrt((div(math.abs(xx),bitr)^2)+(div(math.abs(yy),bitr)^2))*bitr
else
return int_sqrt((math.abs(xx)^2)+(math.abs(yy)^2))
end
end
function positive(num)
if(num<0)
then
return -1
else
return 1
end
end
function EndTurn()
SetState(CurrentHedgehog,bor(GetState(CurrentHedgehog),gstAttacked))
--3 sec espace time
TurnTimeLeft = GetAwayTime*10*3
end
--for sundaland
local turnhog=0
local teams_ok = {}
local wepcode_teams={}
local swapweps=false
--variables for seeing if you have swaped around on a weapon
local australianSpecial=false
local africanSpecial=0
local africaspecial2=0
local samericanSpecial=false
local namericanSpecial=1
local sniper_s_in_use=false
local kergulenSpecial=1
local shotgun_s=false
local europe_s=0
local VampOn=0
local austmine=nil
local inpara=false
local asianflame=0
local visualcircle=nil
local temp_val=0
--for sabotage
local disallowattack=0
local disable_moving={}
local disableRand=0
--local disableoffsetai=0
local onsabotageai=false
local continent = {}
local generalinfo="- "..loc("Per team weapons").."|- 10 "..loc("weaponschemes").."|- "..loc("Unique new weapons").."| |"..loc("Select continent first round with the Weapon Menu or by").." (["..loc("switch").."/"..loc("tab").."]="..loc("Increase")..",["..loc("presice").."/"..loc("left shift").."]="..loc("Decrease")..") "..loc("on Skip").."|"..loc("Some weapons have a second option. Find them with").." ["..loc("switch").."/"..loc("tab").."]"
local weapontexts = {
loc("Green lipstick bullet: [Poisonous, deals no damage]"),
loc("REMOVED"),
loc("Anno 1032: [The explosion will make a strong push ~ Wide range, wont affect hogs close to the target]"),
loc("Dust storm: [Deals 15 damage to all enemies in the circle]"),
loc("Cricket time: [Drop a fireable mine! ~ Will work if fired close to your hog & far away from enemy ~ 1 sec]"),
loc("Drop a bomb: [Drop some heroic wind that will turn into a bomb on impact]"),
loc("Penguin roar: [Deal 15 damage + 15% of your hogs health to all hogs around you and get 2/3 back]"),
loc("Disguise as a Rockhopper Penguin: [Swap place with a random enemy hog in the circle]"),
loc("REMOVED"),
loc("Lonely Cries: [Rise the water if no hog is in the circle and deal 7 damage to all enemy hogs]"),
loc("Hedgehog projectile: [Fire your hog like a Sticky Bomb]"),
loc("Napalm rocket: [Fire a bomb with napalm!]"),
loc("Eagle Eye: [Blink to the impact ~ One shot]"),
loc("Medicine: [Fire some exploding medicine that will heal all hogs effected by the explosion]"),
loc("Sabotage/Flare: [Sabotage all hogs in the circle and deal ~1 dmg OR Fire a cluster up into the air]")
}
local weaponsets =
{
{loc("North America"),loc("Area")..": 24,709,000 km2, "..loc("Population")..": 529,000,000",loc("- Will give you an airstrike every fifth turn.").."|"..loc("Special Weapons:").."|"..loc("Shotgun")..": "..weapontexts[13].."|"..loc("Sniper Rifle")..": "..weapontexts[1],amSniperRifle,
{{amShotgun,100},{amDEagle,100},{amLaserSight,4},{amSniperRifle,100},{amCake,1},{amAirAttack,2},{amSwitch,5}}},
{loc("South America"),loc("Area")..": 17,840,000 km2, "..loc("Population")..": 387,000,000",loc("Special Weapons:").."|"..loc("GasBomb")..": "..weapontexts[3],amGasBomb,
{{amBirdy,100},{amHellishBomb,1},{amBee,100},{amGasBomb,100},{amFlamethrower,100},{amNapalm,1},{amExtraDamage,3}}},
{loc("Europe"),loc("Area")..": 10,180,000 km2, "..loc("Population")..": 740,000,000",loc("Special Weapons:").."|"..loc("Molotov")..": "..weapontexts[14],amBazooka,
{{amBazooka,100},{amGrenade,100},{amMortar,100},{amMolotov,100},{amVampiric,3},{amPiano,1},{amResurrector,2},{amJetpack,4}}},
{loc("Africa"),loc("Area")..": 30,222,000 km2, "..loc("Population")..": 1,033,000,000",loc("Special Weapons:").."|"..loc("Seduction")..": "..weapontexts[4].."|"..loc("Sticky Mine")..": "..weapontexts[11].."|"..loc("Sticky Mine")..": "..weapontexts[12],amSMine,
{{amSMine,100},{amWatermelon,1},{amDrillStrike,1},{amDrill,100},{amInvulnerable,4},{amSeduction,100},{amLandGun,2}}},
{loc("Asia"),loc("Area")..": 44,579,000 km2, "..loc("Population")..": 3,880,000,000",loc("- Will give you a parachute every second turn.").."|"..loc("Special Weapons:").."|"..loc("Parachute")..": "..weapontexts[6],amRope,
{{amRope,100},{amFirePunch,100},{amParachute,1},{amKnife,2},{amDynamite,1}}},
{loc("Australia"),loc("Area")..": 8,468,000 km2, "..loc("Population")..": 31,000,000",loc("Special Weapons:").."|"..loc("Baseballbat")..": "..weapontexts[5],amBaseballBat,
{{amBaseballBat,100},{amMine,100},{amLowGravity,4},{amBlowTorch,100},{amRCPlane,2},{amTeleport,3}}},
{loc("Antarctica"),loc("Area")..": 14,000,000 km2, "..loc("Population")..": ~1,000",loc("Antarctic summer: - Will give you one girder/mudball and two sineguns/portals every fourth turn."),amIceGun,
{{amSnowball,2},{amIceGun,2},{amPickHammer,100},{amSineGun,4},{amGirder,2},{amExtraTime,2},{amPortalGun,2}}},
{loc("Kerguelen"),loc("Area")..": 1,100,000 km2, "..loc("Population")..": ~100",loc("Special Weapons:").."|"..loc("Hammer")..": "..weapontexts[7].."|"..loc("Hammer")..": "..weapontexts[8].." ("..loc("Duration")..": 2)|"..loc("Hammer")..": "..weapontexts[10].."|"..loc("Hammer")..": "..weapontexts[15],amHammer,
{{amHammer,100},{amMineStrike,2},{amBallgun,1}}},
{loc("Zealandia"),loc("Area")..": 3,500,000 km2, "..loc("Population")..": 5,000,000",loc("- Will Get 1-3 random weapons") .. "|" .. loc("- Massive weapon bonus on first turn"),amInvulnerable,
{{amBazooka,1},{amGrenade,1},{amBlowTorch,1},{amSwitch,100},{amRope,1},{amDrill,1},{amDEagle,1},{amPickHammer,1},{amFirePunch,1},{amWhip,1},{amMortar,1},{amSnowball,1},{amExtraTime,1},{amInvulnerable,1},{amVampiric,1},{amFlamethrower,1},{amBee,1},{amClusterBomb,1},{amTeleport,1},{amLowGravity,1},{amJetpack,1},{amGirder,1},{amLandGun,1},{amBirdy,1}}},
{loc("Sundaland"),loc("Area")..": 1,850,000 km2, "..loc("Population")..": 290,000,000",loc("- You will recieve 2-4 weapons on each kill! (Even on own hogs)"),amTardis,
{{amClusterBomb,3},{amTardis,4},{amWhip,100},{amKamikaze,4}}}
}
local weaponsetssounds=
{
{sndShotgunFire,sndCover},
{sndEggBreak,sndLaugh},
{sndExplosion,sndEnemyDown},
{sndMelonImpact,sndCoward},
{sndRopeAttach,sndComeonthen},
{sndBaseballBat,sndNooo},
{sndSineGun,sndOops},
{sndPiano5,sndStupid},
{sndSplash,sndFirstBlood},
{sndWarp,sndSameTeam}
}
--weapontype,ammo,?,duration,*times your choice,affect on random team (should be placed with 1,0,1,0,1 on the 6th option for better randomness)
local weapons_dmg = {
{amKamikaze, 0, 1, 0, 1, 0},
{amSineGun, 0, 1, 0, 1, 1},
{amBazooka, 0, 1, 0, 1, 0},
{amMineStrike, 0, 1, 5, 1, 2},
{amGrenade, 0, 1, 0, 1, 0},
{amPiano, 0, 1, 5, 1, 0},
{amClusterBomb, 0, 1, 0, 1, 0},
{amBee, 0, 1, 0, 1, 0},
{amShotgun, 0, 0, 0, 1, 1},
{amMine, 0, 1, 0, 1, 0},
{amSniperRifle, 0, 1, 0, 1, 1},
{amDEagle, 0, 1, 0, 1, 0},
{amDynamite, 0, 1, 5, 1, 1},
{amFirePunch, 0, 1, 0, 1, 0},
{amHellishBomb, 0, 1, 5, 1, 2},
{amWhip, 0, 1, 0, 1, 0},
{amNapalm, 0, 1, 5, 1, 2},
{amPickHammer, 0, 1, 0, 1, 0},
{amBaseballBat, 0, 1, 0, 1, 1},
{amMortar, 0, 1, 0, 1, 0},
{amCake, 0, 1, 4, 1, 2},
{amSeduction, 0, 0, 0, 1, 0},
{amWatermelon, 0, 1, 5, 1, 2},
{amDrill, 0, 1, 0, 1, 0},
{amBallgun, 0, 1, 5, 1, 2},
{amMolotov, 0, 1, 0, 1, 0},
{amBirdy, 0, 1, 0, 1, 0},
{amBlowTorch, 0, 1, 0, 1, 0},
{amRCPlane, 0, 1, 5, 1, 2},
{amGasBomb, 0, 0, 0, 1, 0},
{amAirAttack, 0, 1, 4, 1, 1},
{amFlamethrower, 0, 1, 0, 1, 0},
{amSMine, 0, 1, 0, 1, 1},
{amHammer, 0, 1, 0, 1, 0},
{amDrillStrike, 0, 1, 4, 1, 2},
{amSnowball, 0, 1, 0, 1, 0}
}
local weapons_supp = {
{amParachute, 0, 1, 0, 1, 0},
{amGirder, 0, 1, 0, 1, 0},
{amSwitch, 0, 1, 0, 1, 0},
{amLowGravity, 0, 1, 0, 1, 0},
{amExtraDamage, 0, 1, 2, 1, 0},
{amRope, 0, 1, 0, 1, 1},
{amInvulnerable, 0, 1, 0, 1, 0},
{amExtraTime, 0, 1, 0, 1, 0},
{amLaserSight, 0, 1, 0, 1, 0},
{amVampiric, 0, 1, 0, 1, 0},
{amJetpack, 0, 1, 0, 1, 1},
{amPortalGun, 0, 1, 2, 1, 1},
{amResurrector, 0, 1, 3, 1, 0},
{amTeleport, 0, 1, 0, 1, 0},
{amLandGun, 0, 1, 0, 1, 0},
{amTardis, 0, 1, 0, 1, 0},
{amIceGun, 0, 1, 0, 1, 0},
{amKnife, 0, 1, 0, 1, 0}
}
--will check after borders and stuff
function validate_weapon(hog,weapon,amount)
if(MapHasBorder() == false or (MapHasBorder() == true and weapon ~= amAirAttack and weapon ~= amMineStrike and weapon ~= amNapalm and weapon ~= amDrillStrike and weapon ~= amPiano))
then
if(amount==1)
then
AddAmmo(hog, weapon)
else
AddAmmo(hog, weapon,amount)
end
end
end
function RemoveWeapon(hog,weapon)
if(GetAmmoCount(hog, weapon)<100)
then
AddAmmo(hog,weapon,GetAmmoCount(hog, weapon)-1)
end
end
--reset all weapons for a team
function cleanweps(hog)
local i=1
--+1 for skip +1 for freezer
while(i<=table.maxn(weapons_supp)+table.maxn(weapons_dmg)+2)
do
AddAmmo(hog,i,0)
i=i+1
end
AddAmmo(hog,amSkip,100)
end
--get the weapons from a weaponset
function load_weaponset(hog, num)
for v,w in pairs(weaponsets[num][5])
do
validate_weapon(hog, w[1],w[2])
end
end
--list up all weapons from the icons for each continent
function load_continent_selection(hog)
if(GetHogLevel(hog)==0)
then
for v,w in pairs(weaponsets)
do
validate_weapon(hog, weaponsets[v][4],1)
end
AddAmmo(hog,amSwitch) --random continent
--for the computers
else
--europe
validate_weapon(hog, weaponsets[3][4],1)
--north america
validate_weapon(hog, weaponsets[1][4],1)
end
end
--shows the continent info
function show_continent_info(continent,time,generalinf)
local geninftext=""
local ns=false
if(time==-1)
then
time=0
ns=true
end
if(generalinf)
then
geninftext="| |"..loc("General information")..": |"..generalinfo
end
ShowMission(weaponsets[continent][1],weaponsets[continent][2],weaponsets[continent][3]..geninftext, -weaponsets[continent][4], time)
if(ns)
then
HideMission()
end
end
--will show a circle of gears (eye candy)
function visual_gear_explosion(range,xpos,ypos,gear1,gear2)
local degr=0
local lap=30
while(lap<range)
do
while(degr < 6.2831)
do
AddVisualGear(xpos+math.cos(degr+0.1)*(lap+5), ypos+math.sin(degr+0.1)*(lap+5), gear1, 0, false)
if(gear2~=false)
then
AddVisualGear(xpos+math.cos(degr)*lap, ypos+math.sin(degr)*lap, gear2, 0, false)
end
degr=degr+((3.1415*3)*0.125) --1/8 = 0.125
end
lap=lap+30
degr=degr-6.2831
end
end
--zealandia (generates weapons from the weaponinfo above
function get_random_weapon(hog)
if(GetGearType(hog) == gtHedgehog and continent[GetHogTeamName(hog)]==9 and getTeamValue(GetHogTeamName(hog), "rand-done-turn")==nil)
then
cleanweps(hog)
local random_weapon = 0
local old_rand_weap = 0
local rand_weaponset_power = 0
local numberof_weapons_supp=table.maxn(weapons_supp)
local numberof_weapons_dmg=table.maxn(weapons_dmg)
local rand1=math.abs(GetRandom(numberof_weapons_supp)+1)
local rand2=math.abs(GetRandom(numberof_weapons_dmg)+1)
random_weapon = math.abs(GetRandom(table.maxn(weapons_dmg))+1)
while(weapons_dmg[random_weapon][4]>TotalRounds or (MapHasBorder() == true and (weapons_dmg[random_weapon][1]== amAirAttack or weapons_dmg[random_weapon][1] == amMineStrike or weapons_dmg[random_weapon][1] == amNapalm or weapons_dmg[random_weapon][1] == amDrillStrike or weapons_dmg[random_weapon][1] == amPiano)))
do
if(random_weapon>=numberof_weapons_dmg)
then
random_weapon=0
end
random_weapon = random_weapon+1
end
validate_weapon(hog, weapons_dmg[random_weapon][1],1)
rand_weaponset_power=weapons_dmg[random_weapon][6]
old_rand_weap = random_weapon
if(rand_weaponset_power <2)
then
random_weapon = rand1
while(weapons_supp[random_weapon][4]>TotalRounds or rand_weaponset_power+weapons_supp[random_weapon][6]>2)
do
if(random_weapon>=numberof_weapons_supp)
then
random_weapon=0
end
random_weapon = random_weapon+1
end
validate_weapon(hog, weapons_supp[random_weapon][1],1)
rand_weaponset_power=rand_weaponset_power+weapons_supp[random_weapon][6]
end
--check again if the power is enough
if(rand_weaponset_power <1)
then
random_weapon = rand2
while(weapons_dmg[random_weapon][4]>TotalRounds or old_rand_weap == random_weapon or weapons_dmg[random_weapon][6]>0 or (MapHasBorder() == true and (weapons_dmg[random_weapon][1]== amAirAttack or weapons_dmg[random_weapon][1] == amMineStrike or weapons_dmg[random_weapon][1] == amNapalm or weapons_dmg[random_weapon][1] == amDrillStrike or weapons_dmg[random_weapon][1] == amPiano)))
do
if(random_weapon>=numberof_weapons_dmg)
then
random_weapon=0
end
random_weapon = random_weapon+1
end
validate_weapon(hog, weapons_dmg[random_weapon][1],1)
end
setTeamValue(GetHogTeamName(hog), "rand-done-turn", true)
end
end
--sundaland add weps
function get_random_weapon_on_death(hog)
local random_weapon = 0
local old_rand_weap = 0
local rand_weaponset_power = 0
local firstTurn=0
local numberof_weapons_supp=table.maxn(weapons_supp)
local numberof_weapons_dmg=table.maxn(weapons_dmg)
local rand1=GetRandom(numberof_weapons_supp)+1
local rand2=GetRandom(numberof_weapons_dmg)+1
local rand3=GetRandom(numberof_weapons_dmg)+1
random_weapon = GetRandom(numberof_weapons_dmg)+1
if(TotalRounds<0)
then
firstTurn=-TotalRounds
end
while(weapons_dmg[random_weapon][4]>(TotalRounds+firstTurn) or (MapHasBorder() == true and (weapons_dmg[random_weapon][1]== amAirAttack or weapons_dmg[random_weapon][1] == amMineStrike or weapons_dmg[random_weapon][1] == amNapalm or weapons_dmg[random_weapon][1] == amDrillStrike or weapons_dmg[random_weapon][1] == amPiano)))
do
if(random_weapon>=numberof_weapons_dmg)
then
random_weapon=0
end
random_weapon = random_weapon+1
end
validate_weapon(hog, weapons_dmg[random_weapon][1],1)
rand_weaponset_power=weapons_dmg[random_weapon][6]
old_rand_weap = random_weapon
random_weapon = rand1
while(weapons_supp[random_weapon][4]>(TotalRounds+firstTurn) or rand_weaponset_power+weapons_supp[random_weapon][6]>2)
do
if(random_weapon>=numberof_weapons_supp)
then
random_weapon=0
end
random_weapon = random_weapon+1
end
validate_weapon(hog, weapons_supp[random_weapon][1],1)
rand_weaponset_power=rand_weaponset_power+weapons_supp[random_weapon][6]
--check again if the power is enough
if(rand_weaponset_power <2)
then
random_weapon = rand2
while(weapons_dmg[random_weapon][4]>(TotalRounds+firstTurn) or old_rand_weap == random_weapon or weapons_dmg[random_weapon][6]>0 or (MapHasBorder() == true and (weapons_dmg[random_weapon][1]== amAirAttack or weapons_dmg[random_weapon][1] == amMineStrike or weapons_dmg[random_weapon][1] == amNapalm or weapons_dmg[random_weapon][1] == amDrillStrike or weapons_dmg[random_weapon][1] == amPiano)))
do
if(random_weapon>=numberof_weapons_dmg)
then
random_weapon=0
end
random_weapon = random_weapon+1
end
validate_weapon(hog, weapons_dmg[random_weapon][1],1)
rand_weaponset_power=weapons_dmg[random_weapon][6]
end
if(rand_weaponset_power <1)
then
random_weapon = rand3
while(weapons_dmg[random_weapon][4]>(TotalRounds+firstTurn) or old_rand_weap == random_weapon or weapons_dmg[random_weapon][6]>0 or (MapHasBorder() == true and (weapons_dmg[random_weapon][1]== amAirAttack or weapons_dmg[random_weapon][1] == amMineStrike or weapons_dmg[random_weapon][1] == amNapalm or weapons_dmg[random_weapon][1] == amDrillStrike or weapons_dmg[random_weapon][1] == amPiano)))
do
if(random_weapon>=numberof_weapons_dmg)
then
random_weapon=0
end
random_weapon = random_weapon+1
end
validate_weapon(hog, weapons_dmg[random_weapon][1],1)
end
AddVisualGear(GetX(hog), GetY(hog)-30, vgtEvilTrace,0, false)
PlaySound(sndReinforce,hog)
end
--this will take that hogs settings for the weapons and add them
function setweapons()
cleanweps(CurrentHedgehog)
load_weaponset(CurrentHedgehog,continent[GetHogTeamName(CurrentHedgehog)])
visualstuff=AddVisualGear(GetX(CurrentHedgehog), GetY(CurrentHedgehog)-5, vgtDust,0, false)
v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 = GetVisualGearValues(visualstuff)
SetVisualGearValues(visualstuff, v1, v2, v3, v4, v5, v6, v7, 2, v9, GetClanColor(GetHogClan(CurrentHedgehog)))
show_continent_info(continent[GetHogTeamName(CurrentHedgehog)],0,false)
end
--show health tag (will mostly be used when a hog is damaged)
function show_damage_tag(hog,damage)
healthtag=AddVisualGear(GetX(hog), GetY(hog), vgtHealthTag, damage, false)
v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 = GetVisualGearValues(healthtag)
SetVisualGearValues(healthtag, v1, v2, v3, v4, v5, v6, v7, v8, v9, GetClanColor(GetHogClan(hog)))
end
--will use int_sqrt
function fire_gear(hedgehog,geartype,vx,vy,timer)
local hypo=norm(vx,vy)
return AddGear(div((GetGearRadius(hedgehog)*2*vx),hypo)+GetX(hedgehog), div((GetGearRadius(hedgehog)*2*vy),hypo)+GetY(hedgehog), geartype, 0, vx, vy, timer)
end
--==========================run throw all hog/gear weapons ==========================
--will check if the mine is nicely placed
function weapon_aust_check(hog)
if(GetGearType(hog) == gtHedgehog)
then
if(gearIsInCircle(hog,GetX(CurrentHedgehog), GetY(CurrentHedgehog), 50, false)==true and hog ~= CurrentHedgehog)
then
temp_val=1
end
end
end
--african special on sedunction
function weapon_duststorm(hog)
if(GetGearType(hog) == gtHedgehog)
then
local dmg=15
if(gearIsInCircle(hog,GetX(CurrentHedgehog), GetY(CurrentHedgehog), 250, false)==true and GetHogClan(hog) ~= GetHogClan(CurrentHedgehog))
then
if(GetHealth(hog) > dmg)
then
temp_val=temp_val+div(dmg*VampOn,100)
SetHealth(hog, GetHealth(hog)-dmg)
else
temp_val=temp_val+div(GetHealth(hog)*VampOn,100)
SetHealth(hog, 0)
end
show_damage_tag(hog,dmg)
end
end
end
--kerguelen special on structure
function weapon_scream_pen(hog)
if(GetGearType(hog) == gtHedgehog)
then
if(gearIsInCircle(hog,GetX(CurrentHedgehog), GetY(CurrentHedgehog), 120, false)==true and GetHogClan(hog) ~= GetHogClan(CurrentHedgehog))
then
local dmg=15+GetHealth(CurrentHedgehog)*0.15
if(GetHealth(hog)>dmg)
then
temp_val=temp_val+div(dmg*2,3)+div(dmg*VampOn*2,100*3)
SetHealth(hog, GetHealth(hog)-dmg)
else
temp_val=temp_val+(GetHealth(hog)*0.75)+(GetHealth(CurrentHedgehog)*0.1)+div((GetHealth(hog)+(GetHealth(CurrentHedgehog)*0.15))*VampOn,100)
SetHealth(hog, 0)
end
show_damage_tag(hog,dmg)
AddVisualGear(GetX(hog), GetY(hog), vgtExplosion, 0, false)
AddVisualGear(GetX(CurrentHedgehog), GetY(CurrentHedgehog), vgtSmokeWhite, 0, false)
end
end
end
--kerguelen special swap hog
function weapon_swap_kerg(hog)
if(GetGearType(hog) == gtHedgehog)
then
if(kergulenSpecial ~= -1 and GetHogClan(hog) ~= GetHogClan(CurrentHedgehog) and gearIsInCircle(hog,GetX(CurrentHedgehog), GetY(CurrentHedgehog), 450, false))
then
local thisX=GetX(CurrentHedgehog)
local thisY=GetY(CurrentHedgehog)
SetGearPosition(CurrentHedgehog, GetX(hog), GetY(hog))
SetGearPosition(hog, thisX, thisY)
kergulenSpecial=-1
end
end
end
--kerguelen special will apply sabotage
function weapon_sabotage(hog)
if(GetGearType(hog) == gtHedgehog)
then
if(CurrentHedgehog~=hog and gearIsInCircle(hog,GetX(CurrentHedgehog), GetY(CurrentHedgehog), 80, false))
then
temp_val=1
disable_moving[hog]=true
AddGear(GetX(hog), GetY(hog), gtCluster, 0, 0, 0, 1)
PlaySound(sndNooo,hog)
end
end
end
--south american special (used fire gear)
function weapon_anno_south(hog)
local power_radius_outer=230
local power_radius_inner=45
local power_sa=500000
local hypo=0
if(gearIsInCircle(hog,GetX(temp_val), GetY(temp_val), power_radius_outer, false) and gearIsInCircle(hog,GetX(temp_val), GetY(temp_val), power_radius_inner, false)==false)
then
if(hog == CurrentHedgehog)
then
SetState(CurrentHedgehog, gstMoving)
end
SetGearPosition(hog, GetX(hog),GetY(hog)-3)
hypo=norm(math.abs(GetX(hog)-GetX(temp_val)),math.abs(GetY(hog)-GetY(temp_val)))
SetGearVelocity(hog, div((power_radius_outer-hypo)*power_sa*positive(GetX(hog)-GetX(temp_val)),power_radius_outer), div((power_radius_outer-hypo)*power_sa*positive(GetY(hog)-GetY(temp_val)),power_radius_outer))
end
end
--first part on kerguelen special (lonely cries)
function weapon_cries_a(hog)
if(GetGearType(hog) == gtHedgehog and hog ~= CurrentHedgehog and gearIsInCircle(hog,GetX(CurrentHedgehog), GetY(CurrentHedgehog), 500, false))
then
kergulenSpecial=-1
end
end
--second part on kerguelen special (lonely cries)
function weapon_cries_b(hog)
if(GetGearType(hog) == gtHedgehog)
then
local dmg=7
if(GetHogClan(hog) ~= GetHogClan(CurrentHedgehog))
then
if(GetHealth(hog) > dmg)
then
temp_val=temp_val+div(dmg*VampOn,100)
SetHealth(hog, GetHealth(hog)-dmg)
else
temp_val=temp_val+div(GetHealth(hog)*VampOn,100)
SetHealth(hog, 0)
end
show_damage_tag(hog,dmg)
AddVisualGear(GetX(hog), GetY(hog)-30, vgtEvilTrace, 0, false)
end
end
end
--north american special on sniper
function weapon_lipstick(hog)
if(GetGearType(hog) == gtHedgehog)
then
if(gearIsInCircle(temp_val,GetX(hog), GetY(hog), 20, false))
then
SetEffect(hog, hePoisoned, 1)
PlaySound(sndBump)
end
end
end
--european special on molotov (used fire gear)
function weapon_health(hog)
if(GetGearType(hog) == gtHedgehog)
then
if(gearIsInCircle(temp_val,GetX(hog), GetY(hog), 100, false))
then
SetHealth(hog, GetHealth(hog)+25+(div(25*VampOn,100)))
SetEffect(hog, hePoisoned, false)
end
end
end
--for sundaland
function find_other_hog_in_team(hog)
if(GetGearType(hog) == gtHedgehog)
then
if(GetHogTeamName(turnhog)==GetHogTeamName(hog))
then
turnhog=hog
end
end
end
--============================================================================
--set each weapons settings
function onAmmoStoreInit()
SetAmmo(amSkip, 9, 0, 0, 0)
for v,w in pairs(weapons_dmg)
do
SetAmmo(w[1], w[2], w[3], w[4], w[5])
end
for v,w in pairs(weapons_supp)
do
SetAmmo(w[1], w[2], w[3], w[4], w[5])
end
end
function onGameStart()
--trackTeams()
ShowMission(loc("Continental supplies"),loc("Let a Continent provide your weapons!"),
generalinfo, -amLowGravity, 0)
end
--what happen when a turn starts
function onNewTurn()
--will refresh the info on each tab weapon
australianSpecial=true
austmine=nil
africanSpecial=0
samericanSpecial=false
africaspecial2=0
kergulenSpecial=1
namericanSpecial=1
asianflame=0
shotgun_s=false
sniper_s_in_use=false
europe_s=0
VampOn=0
temp_val=0
turnhog=CurrentHedgehog
--for sabotage
if(disable_moving[CurrentHedgehog]==true)
then
disallowattack=-100
disableRand=GetRandom(3)+5
end
--when all hogs are "placed"
if(GetCurAmmoType()~=amTeleport)
then
--will run once when the game really starts (after placing hogs and so on
if(teams_ok[GetHogTeamName(CurrentHedgehog)] == nil)
then
AddCaption("["..loc("Select continent!").."]")
load_continent_selection(CurrentHedgehog)
continent[GetHogTeamName(CurrentHedgehog)]=0
swapweps=true
teams_ok[GetHogTeamName(CurrentHedgehog)] = 2
if(disable_moving[CurrentHedgehog]==true)
then
disallowattack=-1000
end
else
--if its not the initialization turn
swapweps=false
if(continent[GetHogTeamName(CurrentHedgehog)]==0)
then
continent[GetHogTeamName(CurrentHedgehog)]=GetRandom(table.maxn(weaponsets))+1
setweapons()
end
show_continent_info(continent[GetHogTeamName(CurrentHedgehog)],-1,true)
--give zeelandia-teams new weapons so they can plan for the next turn
runOnGears(get_random_weapon)
--some specials for some continents (temp_val is from get random weapons)
if(continent[GetHogTeamName(CurrentHedgehog)]==9)
then
setTeamValue(GetHogTeamName(CurrentHedgehog), "rand-done-turn", nil)
elseif(continent[GetHogTeamName(CurrentHedgehog)]==7)
then
if(getTeamValue(GetHogTeamName(CurrentHedgehog), "Antarctica2-turntick")==nil)
then
setTeamValue(GetHogTeamName(CurrentHedgehog), "Antarctica2-turntick", 1)
end
if(getTeamValue(GetHogTeamName(CurrentHedgehog), "Antarctica2-turntick")>=4)
then
AddAmmo(CurrentHedgehog,amPortalGun)
AddAmmo(CurrentHedgehog,amPortalGun)
AddAmmo(CurrentHedgehog,amSineGun)
AddAmmo(CurrentHedgehog,amSineGun)
AddAmmo(CurrentHedgehog,amGirder)
AddAmmo(CurrentHedgehog,amSnowball)
setTeamValue(GetHogTeamName(CurrentHedgehog), "Antarctica2-turntick", 0)
end
setTeamValue(GetHogTeamName(CurrentHedgehog), "Antarctica2-turntick", getTeamValue(GetHogTeamName(CurrentHedgehog), "Antarctica2-turntick")+1)
elseif(continent[GetHogTeamName(CurrentHedgehog)]==5)
then
if(getTeamValue(GetHogTeamName(CurrentHedgehog), "Asia-turntick")==nil)
then
setTeamValue(GetHogTeamName(CurrentHedgehog), "Asia-turntick", 1)
end
if(getTeamValue(GetHogTeamName(CurrentHedgehog), "Asia-turntick")>=2)
then
AddAmmo(CurrentHedgehog,amParachute)
setTeamValue(GetHogTeamName(CurrentHedgehog), "Asia-turntick", 0)
end
setTeamValue(GetHogTeamName(CurrentHedgehog), "Asia-turntick", getTeamValue(GetHogTeamName(CurrentHedgehog), "Asia-turntick")+1)
elseif(continent[GetHogTeamName(CurrentHedgehog)]==1)
then
if(getTeamValue(GetHogTeamName(CurrentHedgehog), "NA-turntick")==nil)
then
setTeamValue(GetHogTeamName(CurrentHedgehog), "NA-turntick", 1)
end
if(getTeamValue(GetHogTeamName(CurrentHedgehog), "NA-turntick")>=5)
then
validate_weapon(CurrentHedgehog,amAirAttack,1)
setTeamValue(GetHogTeamName(CurrentHedgehog), "NA-turntick", 0)
end
setTeamValue(GetHogTeamName(CurrentHedgehog), "NA-turntick", getTeamValue(GetHogTeamName(CurrentHedgehog), "NA-turntick")+1)
end
end
end
end
--what happens when you press "tab" (common button)
function onSwitch()
--place mine (australia)
if(GetCurAmmoType() == amBaseballBat and australianSpecial==true)
then
temp_val=0
runOnGears(weapon_aust_check)
if(temp_val==0)
then
austmine=AddGear(GetX(CurrentHedgehog), GetY(CurrentHedgehog)+5, gtMine, 0, 0, 0, 0)
SetHealth(austmine, 100)
SetTimer(austmine, 1000)
australianSpecial=false
swapweps=false
else
PlaySound(sndDenied)
end
--Asian special
elseif(inpara==1)
then
asiabomb=AddGear(GetX(CurrentHedgehog), GetY(CurrentHedgehog)+3, gtSnowball, 0, 0, 0, 0)
SetGearMessage(asiabomb, 1)
inpara=2
swapweps=false
--africa
elseif(GetCurAmmoType() == amSeduction)
then
if(africanSpecial==0)
then
africanSpecial = 1
AddCaption(weapontexts[4])
else
africanSpecial = 0
AddCaption(loc("NORMAL"))
end
--south america
elseif(GetCurAmmoType() == amGasBomb)
then
if(samericanSpecial==false)
then
samericanSpecial = true
AddCaption(weapontexts[3])
else
samericanSpecial = false
AddCaption(loc("NORMAL"))
end
--africa
elseif(GetCurAmmoType() == amSMine)
then
if(africaspecial2==0)
then
africaspecial2 = 1
AddCaption(weapontexts[11])
elseif(africaspecial2 == 1)
then
africaspecial2 = 2
AddCaption(weapontexts[12])
elseif(africaspecial2 == 2)
then
africaspecial2 = 0
AddCaption(loc("NORMAL"))
end
--north america (sniper)
elseif(GetCurAmmoType() == amSniperRifle and sniper_s_in_use==false)
then
if(namericanSpecial==2)
then
namericanSpecial = 1
AddCaption(loc("NORMAL"))
elseif(namericanSpecial==1)
then
namericanSpecial = 2
AddCaption("#"..weapontexts[1])
end
--north america (shotgun)
elseif(GetCurAmmoType() == amShotgun and shotgun_s~=nil)
then
if(shotgun_s==false)
then
shotgun_s = true
AddCaption(weapontexts[13])
else
shotgun_s = false
AddCaption(loc("NORMAL"))
end
--europe
elseif(GetCurAmmoType() == amMolotov)
then
if(europe_s==0)
then
europe_s = 1
AddCaption(weapontexts[14])
else
europe_s = 0
AddCaption(loc("NORMAL"))
end
--swap forward in the weaponmenu (1.0 style)
elseif(swapweps==true and (GetCurAmmoType() == amSkip or GetCurAmmoType() == amNothing))
then
continent[GetHogTeamName(CurrentHedgehog)]=continent[GetHogTeamName(CurrentHedgehog)]+1
if(continent[GetHogTeamName(CurrentHedgehog)]> table.maxn(weaponsets))
then
continent[GetHogTeamName(CurrentHedgehog)]=1
end
setweapons()
--kerguelen
elseif(GetCurAmmoType() == amHammer)
then
if(kergulenSpecial==6)
then
kergulenSpecial = 1
AddCaption("Normal")
elseif(kergulenSpecial==1)
then
kergulenSpecial = 2
AddCaption("#"..weapontexts[7])
elseif(kergulenSpecial==2 and TotalRounds>=1)
then
kergulenSpecial = 3
AddCaption("##"..weapontexts[8])
elseif(kergulenSpecial==3 or (kergulenSpecial==2 and TotalRounds<1))
then
kergulenSpecial = 5
AddCaption("###"..weapontexts[10])
elseif(kergulenSpecial==5)
then
kergulenSpecial = 6
AddCaption("####"..weapontexts[15])
end
end
end
function onPrecise()
--swap backwards in the weaponmenu (1.0 style)
if(swapweps==true and (GetCurAmmoType() == amSkip or GetCurAmmoType() == amNothing))
then
continent[GetHogTeamName(CurrentHedgehog)]=continent[GetHogTeamName(CurrentHedgehog)]-1
if(continent[GetHogTeamName(CurrentHedgehog)]<=0)
then
continent[GetHogTeamName(CurrentHedgehog)]=table.maxn(weaponsets)
end
setweapons()
end
end
function onGameTick20()
--if you picked a weaponset from the weaponmenu (icon)
if(continent[GetHogTeamName(CurrentHedgehog)]==0)
then
if(GetCurAmmoType()==amSwitch)
then
continent[GetHogTeamName(CurrentHedgehog)]=GetRandom(table.maxn(weaponsets))+1
setweapons()
PlaySound(sndMineTick)
else
for v,w in pairs(weaponsets)
do
if(GetCurAmmoType()==weaponsets[v][4])
then
continent[GetHogTeamName(CurrentHedgehog)]=v
setweapons()
PlaySound(weaponsetssounds[v][1])
PlaySound(weaponsetssounds[v][2],CurrentHedgehog)
end
end
end
end
--show the kerguelen ring
if(kergulenSpecial > 1 and GetCurAmmoType() == amHammer)
then
if(visualcircle==nil)
then
visualcircle=AddVisualGear(GetX(CurrentHedgehog), GetY(CurrentHedgehog), vgtCircle, 0, true)
end
if(kergulenSpecial == 2) --walrus scream
then
SetVisualGearValues(visualcircle, GetX(CurrentHedgehog), GetY(CurrentHedgehog),20, 200, 0, 0, 100, 120, 4, 0xff0000ee)
elseif(kergulenSpecial == 3) --swap hog
then
SetVisualGearValues(visualcircle, GetX(CurrentHedgehog), GetY(CurrentHedgehog),20, 200, 0, 0, 100, 450, 3, 0xffff00ee)
elseif(kergulenSpecial == 5) --cries
then
SetVisualGearValues(visualcircle, GetX(CurrentHedgehog), GetY(CurrentHedgehog),20, 200, 0, 0, 100, 500, 1, 0x0000ffee)
elseif(kergulenSpecial == 6) --sabotage
then
SetVisualGearValues(visualcircle, GetX(CurrentHedgehog), GetY(CurrentHedgehog),20, 200, 0, 0, 100, 80, 10, 0x00ff00ee)
end
elseif(visualcircle~=nil)
then
DeleteVisualGear(visualcircle)
visualcircle=nil
end
--sabotage
if(disable_moving[CurrentHedgehog]==true)
then
if(TurnTimeLeft<=150)
then
disable_moving[CurrentHedgehog]=false
SetInputMask(0xFFFFFFFF)
elseif(disallowattack >= (25*disableRand)+5)
then
temp_val=0
AddGear(GetX(CurrentHedgehog), GetY(CurrentHedgehog)-10, gtCluster, 0, 0, -160000, 40)
disallowattack=0
elseif(disallowattack % 20 == 0 and disallowattack>0)
then
SetInputMask(band(0xFFFFFFFF, bnot(gmLJump + gmHJump)))
AddVisualGear(GetX(CurrentHedgehog), GetY(CurrentHedgehog), vgtSmokeWhite, 0, false)
disallowattack=disallowattack+1
else
SetInputMask(0xFFFFFFFF)
disallowattack=disallowattack+1
end
end
end
--if you used hogswitch or any similar weapon, dont enable any weaponchange
function onAttack()
swapweps=false
--african special
if(africanSpecial == 1 and GetCurAmmoType() == amSeduction and band(GetState(CurrentHedgehog),gstAttacked)==0)
then
--SetState(CurrentHedgehog, gstAttacked)
EndTurn()
temp_val=0
runOnGears(weapon_duststorm)
SetHealth(CurrentHedgehog, GetHealth(CurrentHedgehog)+temp_val)
--visual stuff
visual_gear_explosion(250,GetX(CurrentHedgehog), GetY(CurrentHedgehog),vgtSmoke,vgtSmokeWhite)
PlaySound(sndParachute)
RemoveWeapon(CurrentHedgehog,amSeduction)
--Kerguelen specials
elseif(GetCurAmmoType() == amHammer and kergulenSpecial > 1 and band(GetState(CurrentHedgehog),gstAttacked)==0)
then
--SetState(CurrentHedgehog, gstAttacked)
--scream
if(kergulenSpecial == 2)
then
temp_val=0
runOnGears(weapon_scream_pen)
SetHealth(CurrentHedgehog, GetHealth(CurrentHedgehog)+temp_val)
PlaySound(sndHellish)
--swap
elseif(kergulenSpecial == 3 and TotalRounds>=1)
then
runOnGears(weapon_swap_kerg)
PlaySound(sndPiano3)
--cries
elseif(kergulenSpecial == 5)
then
runOnGears(weapon_cries_a)
if(kergulenSpecial~=-1)
then
AddGear(0, 0, gtWaterUp, 0, 0,0,0)
PlaySound(sndWarp)
PlaySound(sndMolotov)
temp_val=0
runOnGears(weapon_cries_b)
SetHealth(CurrentHedgehog, GetHealth(CurrentHedgehog)+temp_val)
else
HogSay(CurrentHedgehog, loc("Hogs in sight!"), SAY_SAY)
end
--sabotage
elseif(kergulenSpecial == 6)
then
temp_val=0
runOnGears(weapon_sabotage)
if(temp_val==0)
then
PlaySound(sndThrowRelease)
AddGear(GetX(CurrentHedgehog), GetY(CurrentHedgehog)-20, gtCluster, 0, 0, -1000000, 32)
end
end
EndTurn()
DeleteVisualGear(visualcircle)
visualcircle=nil
kergulenSpecial=0
RemoveWeapon(CurrentHedgehog,amHammer)
elseif(GetCurAmmoType() == amVampiric)
then
VampOn=75
end
--Australian special
if(GetGearType(austmine) == gtMine and austmine ~= nil)
then
temp_val=0
runOnGears(weapon_aust_check)
if(gearIsInCircle(austmine,GetX(CurrentHedgehog), GetY(CurrentHedgehog), 30, false)==false or temp_val==1)
then
AddVisualGear(GetX(austmine), GetY(austmine), vgtDust, 0, false)
DeleteGear(austmine)
PlaySound(sndDenied)
end
austmine=nil
end
australianSpecial=false
end
function onGearAdd(gearUid)
swapweps=false
--track the gears im using
if(GetGearType(gearUid) == gtHedgehog or GetGearType(gearUid) == gtMine or GetGearType(gearUid) == gtExplosives)
then
trackGear(gearUid)
end
--remove gasclouds on gasbombspecial
if(GetGearType(gearUid)==gtPoisonCloud and samericanSpecial == true)
then
DeleteGear(gearUid)
elseif(GetGearType(gearUid)==gtSMine)
then
vx,vy=GetGearVelocity(gearUid)
if(africaspecial2 == 1)
then
SetState(CurrentHedgehog, gstHHDriven+gstMoving)
SetGearPosition(CurrentHedgehog, GetX(CurrentHedgehog),GetY(CurrentHedgehog)-3)
SetGearVelocity(CurrentHedgehog, vx, vy)
DeleteGear(gearUid)
elseif(africaspecial2 == 2)
then
fire_gear(CurrentHedgehog,gtNapalmBomb, vx, vy, 0)
DeleteGear(gearUid)
end
elseif(GetGearType(gearUid)==gtSniperRifleShot)
then
sniper_s_in_use=true
if(namericanSpecial~=1)
then
SetHealth(gearUid, 1)
end
elseif(GetGearType(gearUid)==gtShotgunShot)
then
if(shotgun_s==true)
then
AddVisualGear(GetX(gearUid), GetY(gearUid), vgtFeather, 0, false)
AddVisualGear(GetX(gearUid), GetY(gearUid), vgtFeather, 0, false)
AddVisualGear(GetX(gearUid), GetY(gearUid), vgtFeather, 0, false)
PlaySound(sndBirdyLay)
else
shotgun_s=nil
end
elseif(GetGearType(gearUid)==gtMolotov and europe_s==1)
then
vx,vy=GetGearVelocity(gearUid)
e_health=fire_gear(CurrentHedgehog,gtCluster, vx, vy, 1)
SetGearMessage(e_health, 2)
DeleteGear(gearUid)
elseif(GetGearType(gearUid)==gtParachute)
then
inpara=1
end
end
function onGearDelete(gearUid)
if(GetGearType(gearUid) == gtHedgehog or GetGearType(gearUid) == gtMine or GetGearType(gearUid) == gtExplosives)
then
trackDeletion(gearUid)
--sundaland special
if(GetGearType(gearUid) == gtHedgehog and continent[GetHogTeamName(turnhog)]==10)
then
if(turnhog==CurrentHedgehog)
then
runOnGears(find_other_hog_in_team)
end
get_random_weapon_on_death(turnhog)
end
end
--north american lipstick
if(GetGearType(gearUid)==gtSniperRifleShot )
then
sniper_s_in_use=false
if(namericanSpecial==2)
then
temp_val=gearUid
runOnGears(weapon_lipstick)
end
--north american eagle eye
elseif(GetGearType(gearUid)==gtShotgunShot and shotgun_s==true)
then
SetState(CurrentHedgehog, gstMoving)
SetGearPosition(CurrentHedgehog, GetX(gearUid), GetY(gearUid)+7)
PlaySound(sndWarp)
--south american special
elseif(GetGearType(gearUid)==gtGasBomb and samericanSpecial == true)
then
temp_val=gearUid
runOnGears(weapon_anno_south)
AddVisualGear(GetX(gearUid), GetY(gearUid), vgtExplosion, 0, false)
--asian special
elseif(GetGearType(gearUid)==gtSnowball and GetGearMessage(gearUid)==1)
then
AddGear(GetX(gearUid), GetY(gearUid), gtCluster, 0, 0, 0, 22)
--europe special
elseif(GetGearType(gearUid)==gtCluster and GetGearMessage(gearUid)==2)
then
temp_val=gearUid
runOnGears(weapon_health)
visual_gear_explosion(100,GetX(gearUid), GetY(gearUid),vgtSmokeWhite,vgtSmokeWhite)
AddVisualGear(GetX(gearUid), GetY(gearUid), vgtExplosion, 0, false)
PlaySound(sndGraveImpact)
--asia (using para)
elseif(GetGearType(gearUid)==gtParachute)
then
inpara=false
end
end
--[[sources (populations & area):
Own calculations
Some are approximations.]]
|
----------------------------------------------------------
-- Load RayUI Environment
----------------------------------------------------------
RayUI:LoadEnv("Skins")
local S = _Skins
local function LoadSkin()
S:SetBD(GossipFrame)
GossipFrame:DisableDrawLayer("BORDER")
GossipFrameInset:DisableDrawLayer("BORDER")
GossipFrameInsetBg:Hide()
GossipGreetingScrollFrameTop:Hide()
GossipGreetingScrollFrameBottom:Hide()
GossipGreetingScrollFrameMiddle:Hide()
for i = 1, 7 do
select(i, GossipFrame:GetRegions()):Hide()
end
select(19, GossipFrame:GetRegions()):Hide()
GossipGreetingText:SetTextColor(1, 1, 1)
S:ReskinScroll(GossipGreetingScrollFrameScrollBar)
GreetingText:SetTextColor(1, 1, 1)
GreetingText.SetTextColor = R.dummy
S:Reskin(GossipFrameGreetingGoodbyeButton)
S:ReskinClose(GossipFrameCloseButton)
hooksecurefunc("GossipFrameUpdate", function()
for i=1, NUMGOSSIPBUTTONS do
local text = _G["GossipTitleButton" .. i]:GetText()
if text then
text = string.gsub(text, "|cff......", "|cffffffff")
_G["GossipTitleButton" .. i]:SetText(text)
end
end
end)
ItemTextFrame:StripTextures(true)
ItemTextScrollFrameScrollBar:StripTextures()
InboxFrameBg:Hide()
ItemTextPrevPageButton:GetRegions():Hide()
ItemTextNextPageButton:GetRegions():Hide()
ItemTextMaterialTopLeft:SetAlpha(0)
ItemTextMaterialTopRight:SetAlpha(0)
ItemTextMaterialBotLeft:SetAlpha(0)
ItemTextMaterialBotRight:SetAlpha(0)
S:ReskinPortraitFrame(ItemTextFrame, true)
S:ReskinScroll(ItemTextScrollFrameScrollBar)
S:ReskinArrow(ItemTextPrevPageButton, "left")
S:ReskinArrow(ItemTextNextPageButton, "right")
ItemTextPageText:SetTextColor(1, 1, 1)
ItemTextPageText.SetTextColor = R.dummy
NPCFriendshipStatusBar:GetRegions():Hide()
NPCFriendshipStatusBarNotch1:SetColorTexture(0, 0, 0)
NPCFriendshipStatusBarNotch1:Size(1, 16)
NPCFriendshipStatusBarNotch2:SetColorTexture(0, 0, 0)
NPCFriendshipStatusBarNotch2:Size(1, 16)
NPCFriendshipStatusBarNotch3:SetColorTexture(0, 0, 0)
NPCFriendshipStatusBarNotch3:Size(1, 16)
NPCFriendshipStatusBarNotch4:SetColorTexture(0, 0, 0)
NPCFriendshipStatusBarNotch4:Size(1, 16)
select(7, NPCFriendshipStatusBar:GetRegions()):Hide()
NPCFriendshipStatusBar.icon:SetPoint("TOPLEFT", -30, 7)
NPCFriendshipStatusBar.bd = CreateFrame("Frame", nil, NPCFriendshipStatusBar)
NPCFriendshipStatusBar.bd:SetOutside(nil, 1, 1)
NPCFriendshipStatusBar.bd:SetFrameLevel(NPCFriendshipStatusBar:GetFrameLevel() - 1)
S:CreateBD(NPCFriendshipStatusBar.bd, .25)
end
S:AddCallback("Gossip", LoadSkin)
|
-- this test uses the official JSON schema test suite:
-- https://github.com/json-schema-org/JSON-Schema-Test-Suite
local json = require 'cjson'
json.decode_array_with_array_mt(true)
local jsonschema = require 'resty.ljsonschema'
-- the full support of JSON schema in Lua is difficult to achieve in some cases
-- so some tests from the official test suite fail, skip them.
local blacklist do
blacklist = {
-- edge cases, not supported features
['minLength validation'] = {
['one supplementary Unicode code point is not long enough'] = true, -- unicode handling
},
['maxLength validation'] = {
['two supplementary Unicode code points is long enough'] = true, -- unicode handling
},
}
if not ngx then
-- additional blacklisted for Lua/LuaJIT specifically
blacklist['regexes are not anchored by default and are case sensitive'] = {
['recognized members are accounted for'] = true -- regex pattern not supported by plain Lua string.find
}
end
end
local supported = {
-- 'spec/extra/sanity.json',
-- 'spec/extra/empty.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/type.json',
-- objects
'spec/JSON-Schema-Test-Suite/tests/draft4/properties.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/required.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/additionalProperties.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/patternProperties.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/minProperties.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/maxProperties.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/dependencies.json',
'spec/extra/dependencies.json',
-- strings
'spec/JSON-Schema-Test-Suite/tests/draft4/minLength.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/maxLength.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/pattern.json',
-- numbers
'spec/JSON-Schema-Test-Suite/tests/draft4/multipleOf.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/minimum.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/maximum.json',
-- lists
'spec/JSON-Schema-Test-Suite/tests/draft4/items.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/additionalItems.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/minItems.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/maxItems.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/uniqueItems.json',
-- misc
'spec/JSON-Schema-Test-Suite/tests/draft4/enum.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/default.json',
-- compound
'spec/JSON-Schema-Test-Suite/tests/draft4/allOf.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/anyOf.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/oneOf.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/not.json',
-- links/refs
'spec/JSON-Schema-Test-Suite/tests/draft4/ref.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/refRemote.json',
'spec/JSON-Schema-Test-Suite/tests/draft4/definitions.json',
'spec/extra/ref.json',
-- format
'spec/extra/format/date.json',
'spec/extra/format/date-time.json',
'spec/extra/format/time.json',
'spec/extra/format/unknown.json',
-- Lua extensions
'spec/extra/table.json',
'spec/extra/function.lua',
}
local function readjson(path)
if path:match('%.json$') then
local f = assert(io.open(path))
local body = json.decode((assert(f:read('*a'))))
f:close()
return body
elseif path:match('%.lua$') then
return dofile(path)
end
error('cannot read ' .. path)
end
local external_schemas = {
['http://json-schema.org/draft-04/schema'] = require('resty.ljsonschema.metaschema'),
['http://localhost:1234/integer.json'] = readjson('spec/JSON-Schema-Test-Suite/remotes/integer.json'),
['http://localhost:1234/subSchemas.json'] = readjson('spec/JSON-Schema-Test-Suite/remotes/subSchemas.json'),
['http://localhost:1234/folder/folderInteger.json'] = readjson('spec/JSON-Schema-Test-Suite/remotes/folder/folderInteger.json'),
['http://localhost:1234/name.json'] = readjson('spec/JSON-Schema-Test-Suite/remotes/name.json'),
}
local options = {
external_resolver = function(url)
return external_schemas[url]
end,
}
describe("[JSON schema Draft 4]", function()
for _, descriptor in ipairs(supported) do
for _, suite in ipairs(readjson(descriptor)) do
local skipped = blacklist[suite.description] or {}
if skipped ~= true then
describe("["..descriptor.."] "..suite.description .. ":", function()
local schema = suite.schema
local validator
lazy_setup(function()
local val = assert(jsonschema.generate_validator(schema, options))
assert.is_function(val)
validator = val
package.loaded.valcode = jsonschema.generate_validator_code(schema, options)
end)
for _, case in ipairs(suite.tests) do
if not skipped[case.description] then
local prefix = ""
if (suite.description .. ": " .. case.description):find(
"--something to run ONLY--", 1, true) then
prefix = "#only "
end
it(prefix .. case.description, function()
--print("data to validate: ", require("pl.pretty").write(case.data))
if case.valid then
assert.has.no.error(function()
assert(validator(case.data))
end)
else
assert.has.error(function()
assert(validator(case.data))
end)
end
end) -- it
end -- case skipped
end -- for cases
end) -- describe
end -- suite skipped
end -- for suite
end -- for descriptor
end) -- outer describe
|
local t = {}
for line in io.lines() do
table.insert(t, line)
end
s = table.concat(t, '\n') .. '\n'
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Administrator.
--- DateTime: 2020/4/22 18:17
---
function room_init(pid,rid)
rooms[pid] = rid
for key, value in pairs(rooms) do
print(key,value)
end
print("init room ", pid)
end
function player_init(pid,playerdata)
print("init player ", pid)
print(playerdata)
return true
end
function enter_room(pid)
print("player ", pid," enter room")
-- A register room id
<<<<<<< .mine
return "1514ba25-e773-44ec-b916-c4ea4b0ebf9e"
||||||| .r125
return "4ddb5ffd-0bd4-4ad7-b860-a53d3b321747"
=======
return "0cc94e5f-4bac-459f-8150-5aea66dfe334"
>>>>>>> .r128
end
function onmessage(m,x)
hotupdate()
print("on::",m,x)
msgs = msgs + 1
for key, value in pairs(rooms) do
print(key,value)
end
return msgs
end
function hotupdate()
--print(hello)
print("ok hot 888 ...")
end
|
function test()
local a, b = 3301, 5
return a >> b
end
jit("compile", test)
local res = test()
assert(res == 3301 >> 5)
--[[
function <../tests/24_OP_SHR.lua:1,4> (5 instructions at 0x1f47590)
0 params, 3 slots, 0 upvalues, 2 locals, 2 constants, 0 functions
1 [2] LOADK 0 -1 ; 3301
2 [2] LOADK 1 -2 ; 5
3 [3] SHR 2 0 1
4 [3] RETURN 2 2
5 [4] RETURN 0 1
constants (2) for 0x1f47590:
1 3301
2 5
locals (2) for 0x1f47590:
0 a 3 6
1 b 3 6
upvalues (0) for 0x1f47590:
]]
--[[
ra = R(2);
rb = R(0);
rc = R(1);
if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
setivalue(ra, luaV_shiftl(ib, -ic));
} else {
ci->u.l.savedpc = &cl->p->code[3];
luaT_trybinTM(L, rb, rc, ra, TM_SHR);
base = ci->u.l.base;
}
]] |
---@class ToyBoxInfo
C_ToyBoxInfo = {}
---@param itemID number
function C_ToyBoxInfo.ClearFanfare(itemID) end
---@param itemID number
---@return bool needsFanfare
function C_ToyBoxInfo.NeedsFanfare(itemID) end
|
require("config-local").setup({
-- Default configuration (optional)
config_files = { ".nvimrc.lua", ".nvimrc" }, -- Config file patterns to load (lua supported)
-- hashfile = vim.fn.stdpath("data") .. "/config-local-hashfile", -- Where the plugin keeps files data
-- autocommands_create = false, -- Create autocommands (VimEnter, DirectoryChanged)
-- commands_create = false, -- Create commands (ConfigSource, ConfigEdit, ConfigTrust, ConfigIgnore)
-- silent = false, -- Disable plugin messages (Config loaded/ignored)
-- lookup_parents = true, -- Lookup config files in parent directories
})
|
-- Copyright (C) 2017 yushi studio <ywb94@qq.com>
-- Licensed to the public under the GNU General Public License v3.
require "luci.http"
require "luci.dispatcher"
local m, sec, o
local encrypt_methods = {
"table",
"rc4",
"rc4-md5",
"rc4-md5-6",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"aes-128-ctr",
"aes-192-ctr",
"aes-256-ctr",
"bf-cfb",
"camellia-128-cfb",
"camellia-192-cfb",
"camellia-256-cfb",
"cast5-cfb",
"des-cfb",
"idea-cfb",
"rc2-cfb",
"seed-cfb",
"salsa20",
"chacha20",
"chacha20-ietf"
}
local encrypt_methods_ss = {
-- aead
"aes-128-gcm",
"aes-192-gcm",
"aes-256-gcm",
"chacha20-ietf-poly1305",
"xchacha20-ietf-poly1305"
--[[ stream
"table",
"rc4",
"rc4-md5",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"aes-128-ctr",
"aes-192-ctr",
"aes-256-ctr",
"bf-cfb",
"camellia-128-cfb",
"camellia-192-cfb",
"camellia-256-cfb",
"salsa20",
"chacha20",
"chacha20-ietf" ]]
}
local protocol = {
"origin",
"verify_deflate",
"auth_sha1_v4",
"auth_aes128_sha1",
"auth_aes128_md5",
"auth_chain_a"
}
obfs = {
"plain",
"http_simple",
"http_post",
"random_head",
"tls1.2_ticket_auth",
"tls1.2_ticket_fastauth"
}
m = Map("shadowsocksr")
-- [[ Global Setting ]]--
sec = m:section(TypedSection, "server_global", translate("Global Setting"))
sec.anonymous = true
o = sec:option(Flag, "enable_server", translate("Enable Server"))
o.rmempty = false
-- [[ Server Setting ]]--
sec = m:section(TypedSection, "server_config", translate("Server Setting"))
sec.anonymous = true
sec.addremove = true
sec.template = "cbi/tblsection"
sec.extedit = luci.dispatcher.build_url("admin/services/shadowsocksr/server/%s")
function sec.create(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(sec.extedit % sid)
return
end
end
o = sec:option(Flag, "enable", translate("Enable"))
function o.cfgvalue(...)
return Value.cfgvalue(...) or translate("0")
end
o.rmempty = false
o = sec:option(DummyValue, "type", translate("Server Type"))
function o.cfgvalue(...)
return Value.cfgvalue(...) or "ss"
end
o = sec:option(DummyValue, "server_port", translate("Server Port"))
function o.cfgvalue(...)
return Value.cfgvalue(...) or "-"
end
o = sec:option(DummyValue, "username", translate("Username"))
function o.cfgvalue(...)
return Value.cfgvalue(...) or "-"
end
o = sec:option(DummyValue, "encrypt_method", translate("Encrypt Method"))
function o.cfgvalue(...)
local v = Value.cfgvalue(...)
return v and v:upper() or "-"
end
o = sec:option(DummyValue, "encrypt_method_ss", translate("Encrypt Method"))
function o.cfgvalue(...)
local v = Value.cfgvalue(...)
return v and v:upper() or "-"
end
o = sec:option(DummyValue, "protocol", translate("Protocol"))
function o.cfgvalue(...)
return Value.cfgvalue(...) or "-"
end
o = sec:option(DummyValue, "obfs", translate("Obfs"))
function o.cfgvalue(...)
return Value.cfgvalue(...) or "-"
end
return m
|
local files = {
[1] = {
"client",
"https://raw.githubusercontent.com/CoolMan119/HousePost/master/client.lua"
},
[2] = {
"server",
"https://raw.githubusercontent.com/CoolMan119/HousePost/master/server.lua"
}
}
if term.isColor() == false then
print("Sorry, But you need an Advanced PC to run this!")
else
term.setBackgroundColor(colors.red)
term.clear()
term.setCursorPos(18,8)
print("HousePost")
term.setCursorPos(11,10)
print("A Fast, Simple, and Secure OS")
term.setCursorPos(21,16)
term.setBackgroundColor(colors.lightGray)
print("Install")
while true do
local event, side, x, y = os.pullEvent("mouse_click")
if x >= 21 and x < 28 and y == 16 then
term.clear()
shell.run("mkdir", "System")
term.setCursorPos(1,1)
textutils.slowPrint("Installing HousePost...")
local req
local code
local file
for k,v in pairs(files) do
print(v[1])
req = http.get(v[2])
if req ~= nil then
code = req.readAll()
req.close()
else
print("Failed!")
end
file = fs.open(v[1], "w")
file.write(code)
file.close()
end
print("Sucessfully installed HousePost!")
print("Rebooting...")
os.sleep(1)
os.reboot()
|
-- 'Class' representing a floor of a subfactory with individual assembly lines
Floor = {}
function Floor.init(creating_line)
local floor = {
level = 1, -- top floor has a level of 1, it's initialized with Floor.init(nil)
origin_line = nil, -- set below, only if level > 1. The line this subfloor is attached to
defining_line = nil, -- set below, only if level > 1. First line of this subfloor
Line = Collection.init("Line"),
valid = true,
class = "Floor"
}
-- Move given line, if it exists, to the subfloor, and create a new origin line
if creating_line ~= nil then
-- Subfloors have a level that is 1 higher than their creating_line's floor
floor.level = creating_line.parent.level + 1
floor.parent = creating_line.parent
local origin_line = Line.init(nil) -- No need to set a machine in this case
origin_line.subfloor = floor -- Link up the newly created origin_line with its subfloor
floor.origin_line = origin_line -- and vice versa
-- Replace the creating_line on its floor with the newly created origin_line
Floor.replace(creating_line.parent, creating_line, origin_line)
Floor.add(floor, creating_line) -- Add the creating_line to the subfloor in the first spot
floor.defining_line = creating_line -- which makes it the defining_line on this floor
end
return floor
end
function Floor.add(self, object)
object.parent = self
return Collection.add(self[object.class], object)
end
function Floor.insert_at(self, gui_position, object)
object.parent = self
return Collection.insert_at(self[object.class], gui_position, object)
end
function Floor.remove(self, dataset)
-- Remove the subfloor(s) associated to a line recursively, so they don't hang around
if dataset.class == "Line" and dataset.subfloor ~= nil then
for _, line in pairs(Floor.get_in_order(dataset.subfloor, "Line")) do
if line.subfloor then Floor.remove(dataset.subfloor, line) end
end
Collection.remove(self.parent.Floor, dataset.subfloor)
end
-- If the first line of a subfloor is removed, the whole subfloor needs to go
if dataset.class == "Line" and self.level > 1 and dataset.gui_position == 1 then
Floor.remove(self.origin_line.parent, self.origin_line)
end
return Collection.remove(self[dataset.class], dataset)
end
-- Floor deletes itself if it consists of only its mandatory first line
-- That line can't be invalid as the whole subfloor would be removed already at that point
function Floor.remove_if_empty(self)
if self.level > 1 and self.Line.count == 1 then
local origin_line = self.origin_line
Floor.replace(origin_line.parent, origin_line, self.defining_line)
-- No need to remove eventual subfloors to the given floor,
-- as there can't be any if the floor is empty
Subfactory.remove(self.parent, self)
return true
end
return false -- returns whether the floor was deleted or not
end
function Floor.replace(self, dataset, object)
object.parent = self
return Collection.replace(self[dataset.class], dataset, object)
end
function Floor.get(self, class, dataset_id)
return Collection.get(self[class], dataset_id)
end
function Floor.get_in_order(self, class, reverse)
return Collection.get_in_order(self[class], reverse)
end
function Floor.shift(self, dataset, direction)
return Collection.shift(self[dataset.class], dataset, direction)
end
function Floor.shift_to_end(self, dataset, direction)
return Collection.shift_to_end(self[dataset.class], dataset, direction)
end
-- Returns the machines and modules needed to actually build this floor
function Floor.get_component_data(self, component_table)
local components = component_table or {machines={}, modules={}}
local function add_component(table, proto, amount)
local component = table[proto.name]
if component == nil then
table[proto.name] = {proto = proto, amount = amount}
else
component.amount = component.amount + amount
end
end
-- Reaching into global here is a bit annoying, could be done by the generator itself
-- Only items can place entities, not fluids
local item_prototypes = global.all_items.types[global.all_items.map["item"]]
local function add_machine(entity_proto, amount)
if not entity_proto.built_by_item then return end
local item_proto_id = item_prototypes.map[entity_proto.built_by_item]
add_component(components.machines, item_prototypes.items[item_proto_id], amount)
end
-- Doesn't count subfloors when looking at this specific floors. Maybe it should, which
-- would mean the subfactory machine total is equal to the floor total of the top floor
for _, line in pairs(Floor.get_in_order(self, "Line")) do
if line.subfloor == nil then
local ceil_machine_count = math.ceil(line.machine.count)
add_machine(line.machine.proto, ceil_machine_count)
for _, module in pairs(Machine.get_in_order(line.machine, "Module")) do
add_component(components.modules, module.proto, ceil_machine_count * module.amount)
end
local beacon = line.beacon
if beacon and beacon.total_amount then
local ceil_total_amount = math.ceil(beacon.total_amount)
add_machine(beacon.proto, ceil_total_amount)
add_component(components.modules, beacon.module.proto, ceil_total_amount * beacon.module.amount)
end
end
end
return components
end
function Floor.pack(self)
return {
Line = Collection.pack(self.Line),
level = self.level,
class = self.class
}
end
-- This unpack-function differs in that it gets called with the floor already existing
-- This function should thus unpack itself into that floor, instead of creating a new one
function Floor.unpack(packed_self, self)
-- This can't use Collection.unpack for its lines because of its recursive nature
-- It might also be possible and more correct to move some of this functionality
-- to the Line-class, but this works and is more understandable
for _, packed_line in pairs(packed_self.Line.objects) do
if packed_line.subfloor ~= nil then
-- Add the first subfloor line as a line in this floor
local subfloor_line = Line.unpack(packed_line.subfloor.Line.objects[1])
Floor.add(self, subfloor_line)
-- Use that line to create the subfloor, which moves it to the newly created floor
local subfloor = Floor.init(subfloor_line) -- sets origin_ and defining_line
subfloor.origin_line.comment = packed_line.comment -- carry over line comment
Subfactory.add(self.parent, subfloor)
-- Remove the first subfloor line as it has already been created by initializing the subfloor with it
table.remove(packed_line.subfloor.Line.objects, 1)
Floor.unpack(packed_line.subfloor, subfloor)
else -- a normal line just gets unpacked and added straight away
Floor.add(self, Line.unpack(packed_line))
end
end
-- return value is not needed here
end
-- Needs validation: Line
function Floor.validate(self)
self.valid = Collection.validate_datasets(self.Line)
return self.valid
end
-- Needs repair: Line
function Floor.repair(self, player)
-- Unrepairable lines get removed, so the subfactory will always be valid afterwards
Collection.repair_datasets(self.Line, player)
self.valid = true
-- Make this floor remove itself if it's empty after repairs
Floor.remove_if_empty(self)
return true -- make sure this floor is not removed by the calling Collection-function
end |
--- === TextClipboardHistory ===
---
--- Keep a history of the clipboard, only for text entries
---
--- Originally based on [code by VFS](https://github.com/VFS/.hammerspoon/blob/master/tools/clipboard.lua), but with many changes and some contributions and inspiration from [asmagill](https://github.com/asmagill/hammerspoon-config/blob/master/utils/_menus/newClipper.lua).
---
--- Download: [https://github.com/Hammerspoon/Spoons/raw/master/Spoons/TextClipboardHistory.spoon.zip](https://github.com/Hammerspoon/Spoons/raw/master/Spoons/TextClipboardHistory.spoon.zip)
local obj={}
obj.__index = obj
-- Metadata
obj.name = "TextClipboardHistory"
obj.version = "0.5"
obj.author = "Diego Zamboni <diego@zzamboni.org>"
obj.homepage = "https://github.com/Hammerspoon/Spoons"
obj.license = "MIT - https://opensource.org/licenses/MIT"
local getSetting = function(label, default) return hs.settings.get(obj.name.."."..label) or default end
local setSetting = function(label, value) hs.settings.set(obj.name.."."..label, value); return value end
-- Adds higer quality images to be shown in the menubar
-- and the Popup.
local hammerDir = hs.fs.currentDir()
local iconsDir = (hammerDir .. '/Spoons/TextClipboardHistory.spoon/icons/')
--- TextClipboardHistory.frequency
--- Variable
--- Speed in seconds to check for clipboard changes. If you check too frequently, you will degrade performance, if you check sparsely you will loose copies. Defaults to 0.8.
obj.frequency = 0.8
--- TextClipboardHistory.hist_size
--- Variable
--- How many items to keep on history. Defaults to 100
obj.hist_size = 100
--- TextClipboardHistory.honor_ignoredidentifiers
--- Variable
--- If `true`, check the data identifiers set in the pasteboard and ignore entries which match those listed in `TextClipboardHistory.ignoredIdentifiers`. The list of identifiers comes from http://nspasteboard.org. Defaults to `true`
obj.honor_ignoredidentifiers = true
--- TextClipboardHistory.paste_on_select
--- Variable
--- Whether to auto-type the item when selecting it from the menu. Can be toggled on the fly from the chooser. Defaults to `false`.
obj.paste_on_select = getSetting('paste_on_select', false)
--- TextClipboardHistory.logger
--- Variable
--- Logger object used within the Spoon. Can be accessed to set the default log level for the messages coming from the Spoon.
obj.logger = hs.logger.new('TextClipboardHistory')
--- TextClipboardHistory.ignoredIdentifiers
--- Variable
--- Types of clipboard entries to ignore, see http://nspasteboard.org. Code from https://github.com/asmagill/hammerspoon-config/blob/master/utils/_menus/newClipper.lua. Default value (don't modify unless you know what you are doing):
--- ```
--- {
--- ["de.petermaurer.TransientPasteboardType"] = true, -- Transient : Textpander, TextExpander, Butler
--- ["com.typeit4me.clipping"] = true, -- Transient : TypeIt4Me
--- ["Pasteboard generator type"] = true, -- Transient : Typinator
--- ["com.agilebits.onepassword"] = true, -- Confidential : 1Password
--- ["org.nspasteboard.TransientType"] = true, -- Universal, Transient
--- ["org.nspasteboard.ConcealedType"] = true, -- Universal, Concealed
--- ["org.nspasteboard.AutoGeneratedType"] = true, -- Universal, Automatic
--- }
--- ```
obj.ignoredIdentifiers = {
["de.petermaurer.TransientPasteboardType"] = true, -- Transient : Textpander, TextExpander, Butler
["com.typeit4me.clipping"] = true, -- Transient : TypeIt4Me
["Pasteboard generator type"] = true, -- Transient : Typinator
["com.agilebits.onepassword"] = true, -- Confidential : 1Password
["org.nspasteboard.TransientType"] = true, -- Universal, Transient
["org.nspasteboard.ConcealedType"] = true, -- Universal, Concealed
["org.nspasteboard.AutoGeneratedType"] = true, -- Universal, Automatic
}
--- TextClipboardHistory.deduplicate
--- Variable
--- Whether to remove duplicates from the list, keeping only the latest one. Defaults to `true`.
obj.deduplicate = true
--- TextClipboardHistory.show_in_menubar
--- Variable
--- Whether to show a menubar item to open the clipboard history. Defaults to `true`
obj.show_in_menubar = true
--- TextClipboardHistory.menubar_title
--- Variable
--- String to show in the menubar if `TextClipboardHistory.show_in_menubar` is `true`. Defaults to `"\u{1f4ce}"`, which is the [Unicode paperclip character](https://codepoints.net/U+1F4CE)
--obj.menubar_title = "\u{1f4ce}"
-- Edits the default spoon to get nicer looking icons
-- for the menubar, and the chooser interface.
icon = (iconsDir .. 'clip.png')
caution = (iconsDir .. 'caution-white.png')
trash = (iconsDir .. 'trash.png')
check_empty = (iconsDir .. 'check_empty.png')
check_filled = (iconsDir .. 'check_filled.png')
obj.menubar_title = hs.image.imageFromPath(icon):setSize({w=16,h=16})
----------------------------------------------------------------------
-- Internal variable - Chooser/menu object
obj.selectorobj = nil
-- Internal variable - Cache for focused window to work around the current window losing focus after the chooser comes up
obj.prevFocusedWindow = nil
-- Internal variable - Timer object to look for pasteboard changes
obj.timer = nil
local pasteboard = require("hs.pasteboard") -- http://www.hammerspoon.org/docs/hs.pasteboard.html
local hashfn = require("hs.hash").MD5
-- Keep track of last change counter
local last_change = nil;
-- Array to store the clipboard history
local clipboard_history = nil
-- Internal function - persist the current history so it survives across restarts
function _persistHistory()
setSetting("items",clipboard_history)
end
--- TextClipboardHistory:togglePasteOnSelect()
--- Method
--- Toggle the value of `TextClipboardHistory.paste_on_select`
function obj:togglePasteOnSelect()
self.paste_on_select = setSetting("paste_on_select", not self.paste_on_select)
hs.notify.show("TextClipboardHistory", "Paste-on-select is now " .. (self.paste_on_select and "enabled" or "disabled"), "")
end
-- Internal method - process the selected item from the chooser. An item may invoke special actions, defined in the `actions` variable.
function obj:_processSelectedItem(value)
local actions = {
none = function() end,
clear = hs.fnutils.partial(self.clearAll, self),
toggle_paste_on_select = hs.fnutils.partial(self.togglePasteOnSelect, self),
}
if self.prevFocusedWindow ~= nil then
self.prevFocusedWindow:focus()
end
if value and type(value) == "table" then
if value.action and actions[value.action] then
actions[value.action](value)
elseif value.text then
pasteboard.setContents(value.text)
self:pasteboardToClipboard(value.text)
if (self.paste_on_select) then
hs.eventtap.keyStroke({"cmd"}, "v")
end
end
last_change = pasteboard.changeCount()
end
end
--- TextClipboardHistory:clearAll()
--- Method
--- Clears the clipboard and history
function obj:clearAll()
pasteboard.clearContents()
clipboard_history = {}
_persistHistory()
last_change = pasteboard.changeCount()
end
--- TextClipboardHistory:clearLastItem()
--- Method
--- Clears the last added to the history
function obj:clearLastItem()
table.remove(clipboard_history, 1)
_persistHistory()
last_change = pasteboard.changeCount()
end
-- Internal method: deduplicate the given list, and restrict it to the history size limit
function obj:dedupe_and_resize(list)
local res={}
local hashes={}
for i,v in ipairs(list) do
if #res < self.hist_size then
local hash=hashfn(v)
if (not self.deduplicate) or (not hashes[hash]) then
table.insert(res, v)
hashes[hash]=true
end
end
end
return res
end
--- TextClipboardHistory:pasteboardToClipboard(item)
--- Method
--- Add the given string to the history
---
--- Parameters:
--- * item - string to add to the clipboard history
---
--- Returns:
--- * None
function obj:pasteboardToClipboard(item)
table.insert(clipboard_history, 1, item)
clipboard_history = self:dedupe_and_resize(clipboard_history)
_persistHistory() -- updates the saved history
end
-- Internal function - fill in the chooser options, including the control options
function obj:_populateChooser()
menuData = {}
for k,v in pairs(clipboard_history) do
if (type(v) == "string") then
table.insert(menuData, {text=v, subText=""})
end
end
if #menuData == 0 then
table.insert(menuData, { text=" Clipboard is Empty ",
action = 'none',
--image = hs.image.imageFromName('NSCaution')})
image = hs.image.imageFromPath(caution):setSize({w=20,h=20})})
else
table.insert(menuData, { text=" Clear Clipboard History ",
action = 'clear',
--image = hs.image.imageFromName('NSTrashFull') })
image = hs.image.imageFromPath(trash):setSize({w=20,h=20})})
end
table.insert(menuData, {
text="" .. (self.paste_on_select and "Disable" or "Enable") .. " Paste on Select",
action = 'toggle_paste_on_select',
image = (self.paste_on_select and hs.image.imageFromPath(check_empty):setSize({w=20,h=20}) or hs.image.imageFromPath(check_filled):setSize({w=20,h=20}))
})
self.logger.df("Returning menuData = %s", hs.inspect(menuData))
return menuData
end
--- TextClipboardHistory:shouldBeStored()
--- Method
--- Verify whether the pasteboard contents matches one of the values in `TextClipboardHistory.ignoredIdentifiers`
function obj:shouldBeStored()
-- Code from https://github.com/asmagill/hammerspoon-config/blob/master/utils/_menus/newClipper.lua
local goAhead = true
for i,v in ipairs(hs.pasteboard.pasteboardTypes()) do
if self.ignoredIdentifiers[v] then
goAhead = false
break
end
end
if goAhead then
for i,v in ipairs(hs.pasteboard.contentTypes()) do
if self.ignoredIdentifiers[v] then
goAhead = false
break
end
end
end
return goAhead
end
--- TextClipboardHistory:checkAndStorePasteboard()
--- Method
--- If the pasteboard has changed, we add the current item to our history and update the counter
function obj:checkAndStorePasteboard()
now = pasteboard.changeCount()
if (now > last_change) then
if (not self.honor_ignoredidentifiers) or self:shouldBeStored() then
current_clipboard = pasteboard.getContents()
self.logger.df("current_clipboard = %s", tostring(current_clipboard))
if (current_clipboard == nil) and (pasteboard.readImage() ~= nil) then
self.logger.df("Images not yet supported - ignoring image contents in clipboard")
elseif current_clipboard ~= nil then
self.logger.df("Adding %s to clipboard history", current_clipboard)
self:pasteboardToClipboard(current_clipboard)
else
self.logger.df("Ignoring nil clipboard content")
end
else
self.logger.df("Ignoring pasteboard entry because it matches ignoredIdentifiers")
end
last_change = now
end
end
--- TextClipboardHistory:start()
--- Method
--- Start the clipboard history collector
function obj:start()
clipboard_history = self:dedupe_and_resize(getSetting("items", {})) -- If no history is saved on the system, create an empty history
last_change = pasteboard.changeCount() -- keeps track of how many times the pasteboard owner has changed // Indicates a new copy has been made
self.selectorobj = hs.chooser.new(hs.fnutils.partial(self._processSelectedItem, self))
self.selectorobj:choices(hs.fnutils.partial(self._populateChooser, self))
--Checks for changes on the pasteboard. Is it possible to replace with eventtap?
self.timer = hs.timer.new(self.frequency, hs.fnutils.partial(self.checkAndStorePasteboard, self))
self.timer:start()
if self.show_in_menubar then
self.menubaritem = hs.menubar.new()
:setIcon(obj.menubar_title)
:setClickCallback(hs.fnutils.partial(self.toggleClipboard, self))
end
end
--- TextClipboardHistory:showClipboard()
--- Method
--- Display the current clipboard list in a chooser
function obj:showClipboard()
if self.selectorobj ~= nil then
self.selectorobj:refreshChoicesCallback()
self.prevFocusedWindow = hs.window.focusedWindow()
self.selectorobj:show()
else
hs.notify.show("TextClipboardHistory not properly initialized", "Did you call TextClipboardHistory:start()?", "")
end
end
--- TextClipboardHistory:toggleClipboard()
--- Method
--- Show/hide the clipboard list, depending on its current state
function obj:toggleClipboard()
if self.selectorobj:isVisible() then
self.selectorobj:hide()
else
self:showClipboard()
end
end
--- TextClipboardHistory:bindHotkeys(mapping)
--- Method
--- Binds hotkeys for TextClipboardHistory
---
--- Parameters:
--- * mapping - A table containing hotkey objifier/key details for the following items:
--- * show_clipboard - Display the clipboard history chooser
--- * toggle_clipboard - Show/hide the clipboard history chooser
function obj:bindHotkeys(mapping)
local def = {
show_clipboard = hs.fnutils.partial(self.showClipboard, self),
toggle_clipboard = hs.fnutils.partial(self.toggleClipboard, self),
}
hs.spoons.bindHotkeysToSpec(def, mapping)
end
return obj
|
ix.randomitems.tables["event_anomaly_razortree"] = {
{500, {"value_statue_cat"}},
{500, {"value_statue_horse"}},
{500, {"value_statue_lion"}},
{250, {"artifact_mementomori"}},
} |
instrument { name = "Psychological Line" }
period = input (28, "front.period", input.integer, 1)
input_group {
"front.ind.dpo.generalline",
color = input { default = "#96ADBC", type = input.color },
width = input { default = 1, type = input.line_width }
}
input_group {
"front.platform.baseline",
zero_color = input { default = rgba(255,255,255,0.15), type = input.color },
zero_width = input { default = 1, type = input.line_width },
zero_visible = input { default = true, type = input.plot_visibility }
}
input_group {
"front.newind.adx.fill",
fill_up_color = input { default = rgba(37,225,84,0.10), type = input.color },
fill_down_color = input { default = rgba(255,108,88,0.10), type = input.color },
fill_visible = input { default = true, type = input.plot_visibility }
}
psy = sma (iff (conditional (close > close [1]), 1, 0), period) * 100
if fill_visible then
fill (psy, 50, "", psy > 50 and fill_up_color or fill_down_color)
end
if zero_visible then
hline (50, "", zero_color, zero_width)
end
plot (psy, "PSY", color, width)
|
local _, ns = ...
local AceGUI = LibStub("AceGUI-3.0")
ns.backdropTemplate = select(4, GetBuildInfo()) > 90000 and "BackdropTemplate"
ns.typeWidgets = {}
local tremove = table.remove
function ns.Confirm(text, callback)
local root = AceGUI:Create("Window")
root.sizer_se:Hide()
root.sizer_s:Hide()
root.sizer_e:Hide()
root:SetHeight(72)
root:SetWidth(320)
root:SetTitle(text)
root:SetLayout("Flow")
local accept = AceGUI:Create("Button")
accept:SetText("Accept")
accept:SetRelativeWidth(0.5)
accept:SetCallback("OnClick", function()
root:Hide()
root:Release()
callback()
end)
root:AddChild(accept)
local cancel = AceGUI:Create("Button")
cancel:SetText("Cancel")
cancel:SetRelativeWidth(0.5)
cancel:SetCallback("OnClick", function()
root:Hide()
root:Release()
end)
root:AddChild(cancel)
root.frame:Show()
end
function ns.CreateAnchorWidget(region, showOther)
local root = AceGUI:Create("InlineGroup")
root:SetFullWidth(true)
-- TODO make this a table
local points = {}
local toPoints = {[""] = ""}
for _, p in ipairs({
"CENTER",
"TOP", "BOTTOM", "LEFT", "RIGHT",
"TOPLEFT", "TOPRIGHT", "BOTTOMLEFT", "BOTTOMRIGHT",
}) do
points[p] = p
toPoints[p] = p
end
function setAnchors()
root:ReleaseChildren()
if region.anchors then
for i, a in ipairs(region.anchors) do
local g = AceGUI:Create("SimpleGroup")
g:SetFullWidth(true)
g:SetLayout("Flow")
local from = AceGUI:Create("Dropdown")
from:SetLabel("From")
from:SetWidth(140)
from:SetList(points)
from:SetValue(a.from)
from:SetCallback("OnValueChanged", function(w, msg, v)
a.from = v
ToshUnitFrames:SendMessage("TUF_FRAMES_UPDATED")
end)
g:AddChild(from)
if showOther then
local other = AceGUI:Create("EditBox")
other:SetLabel("Other Frame")
other:SetWidth(120)
other:SetText(a.otherFrame)
other:SetCallback("OnEnterPressed", function(w, msg, v)
if v == "" then a.otherFrame = nil
elseif not _G[v] then return
else a.otherFrame = v
end
ToshUnitFrames:SendMessage("TUF_FRAMES_UPDATED")
end)
g:AddChild(other)
end
local to = AceGUI:Create("Dropdown")
to:SetLabel("To")
to:SetWidth(140)
to:SetList(toPoints)
to:SetValue(a.to)
to:SetCallback("OnValueChanged", function(w, msg, v)
a.to = v
ToshUnitFrames:SendMessage("TUF_FRAMES_UPDATED")
end)
g:AddChild(to)
local x = AceGUI:Create("EditBox")
x:SetLabel("X off")
x:SetWidth(60)
x:SetText(a.x)
x:SetCallback("OnEnterPressed", function(w, msg, v)
v = tonumber(v)
if not v then return end
a.x = v
ToshUnitFrames:SendMessage("TUF_FRAMES_UPDATED")
end)
g:AddChild(x)
local y = AceGUI:Create("EditBox")
y:SetLabel("Y off")
y:SetWidth(60)
y:SetText(a.y)
y:SetCallback("OnEnterPressed", function(w, msg, v)
v = tonumber(v)
if not v then return end
a.y = v
ToshUnitFrames:SendMessage("TUF_FRAMES_UPDATED")
end)
g:AddChild(y)
local delete = AceGUI:Create("Button")
delete:SetText("Remove")
delete:SetWidth(90)
delete:SetCallback("OnClick", function()
tremove(region.anchors, i)
ToshUnitFrames:SendMessage("TUF_FRAMES_UPDATED")
setAnchors()
end)
g:AddChild(delete)
root:AddChild(g)
end
end
local addAnchor = AceGUI:Create("Button")
addAnchor:SetText("Add Anchor")
addAnchor:SetWidth(120)
addAnchor:SetCallback("OnClick", function()
region.anchors = region.anchors or {}
region.anchors[#region.anchors+1] = {}
setAnchors()
end)
root:AddChild(addAnchor)
end
setAnchors()
return root
end
function ns.CreateDropdown(region, key, label, list)
local f = AceGUI:Create("Dropdown")
f:SetLabel(label)
f:SetList(list)
f:SetValue(region[key])
f:SetCallback("OnValueChanged", function(w, msg, v)
region[key] = v
ToshUnitFrames:SendMessage("TUF_FRAMES_UPDATED")
end)
return f
end
local function SliderBounds(min, max, value)
if not value then return min, max end
local bound = (max-min) * 0.15
-- if the value is within 15% of either end
-- set the value to the middle:
-- value = (max-min)/2
if value < min+bound then
min = max - value*2
elseif value > max-bound then
max = value*2 - min
end
return min, max
end
function ns.CreateSizeConfig(region)
local root = AceGUI:Create("SimpleGroup")
local width = AceGUI:Create("Slider")
width:SetLabel("Width")
width:SetSliderValues(SliderBounds(0, 500, region.width))
width:SetValue(region.width or 0)
width:SetCallback("OnValueChanged", function(w, msg, v)
region.width = v
ToshUnitFrames:SendMessage("TUF_FRAMES_UPDATED")
end)
width:SetCallback("OnMouseUp", function(w, msg, v)
width:SetSliderValues(SliderBounds(0, 500, v))
end)
root:AddChild(width)
local height = AceGUI:Create("Slider")
height:SetLabel("Height")
height:SetSliderValues(SliderBounds(0, 500, region.height))
height:SetValue(region.height or 0)
height:SetCallback("OnValueChanged", function(w, msg, v)
region.height = v
ToshUnitFrames:SendMessage("TUF_FRAMES_UPDATED")
end)
height:SetCallback("OnMouseUp", function(w, msg, v)
height:SetSliderValues(SliderBounds(0, 500, v))
end)
root:AddChild(height)
return root
end
|
object_tangible_furniture_city_flag_city_04 = object_tangible_furniture_city_shared_flag_city_04:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_city_flag_city_04, "object/tangible/furniture/city/flag_city_04.iff")
|
return {'detachement','detachementscommandant','detacheren','detachering','detacheringsbedrijf','detacheringsbureau','detacheringsovereenkomst','detail','detailfoto','detailhandel','detailhandelaar','detailhandelconcern','detailhandelsactiviteit','detailhandelsbedrijf','detailhandelsconcern','detailhandelsketen','detailhandelsniveau','detailhandelsomzet','detailhandelsonderneming','detailhandelsprijs','detailhandelsschool','detailhandelsverkoop','detailkennis','detailkritiek','detailkwestie','detailleren','detaillering','detaillisme','detaillist','detaillistenvereniging','detaillistisch','detailonderzoek','detailopname','detailplan','detailplanning','detailprijs','detailpunt','detailrijk','detailstudie','detailtekening','detailzaak','detecteren','detectie','detectieapparatuur','detectielus','detectiemethode','detectiepoort','detectiepoortje','detectiesysteem','detective','detectiveachtig','detectivebureau','detectiveroman','detectiveschrijver','detectiveserie','detectivespel','detectiveverhaal','detectivewerk','detector','detente','detentie','detentiecentrum','detentiekamp','detentieruimte','detergens','detergent','determinant','determinatie','determinatief','determinator','determineerklas','determineerklasse','determineren','determinisme','determinist','deterministisch','detineren','detonatie','detonator','detoneren','detox','detriment','detrimente','detectieplaatje','determinatiegraad','detailniveau','detailinformatie','detailontwerp','detectiegrens','detacheringsbasis','detailhandelsbeleid','detailkaart','detailpagina','detailscherm','detailverkoop','detailweergave','detailwerk','detectiekans','detectielimiet','detectiveboek','detentieboot','detailhandelsstructuur','detacheringsrichtlijn','detailvenster','detailscan','detacheerder','detlef','deters','detmers','dethmers','detmar','detacheer','detacheerde','detacheerden','detacheert','detachementen','detacheringen','detacheringsovereenkomsten','detailhandelaars','detailhandelaren','detailhandelsactiviteiten','detailhandelsbedrijven','detailhandelsprijzen','detailkaarten','detailkwesties','detailleer','detailleerde','detailleerden','detailleert','detailleringen','detaillisten','detaillistische','detailprijzen','details','detailtekeningen','detailvragen','detailzaken','detecteer','detecteerde','detecteerden','detecteert','detectiepoorten','detectiesystemen','detectiveromans','detectives','detectiveverhalen','detectoren','determinanten','determinaties','determinatietabellen','determinatieve','determineer','determineerde','determineerden','determineert','determinerend','determinerende','determinismen','deterministen','deterministische','detineerde','detineerden','detineert','detoneer','detoneerde','detoneerden','detoneert','detonaties','detergentia','detailpunten','detailhandels','detailfotos','detailhandelsverkopen','detailopnamen','detailopnames','detailrijke','detailstudies','detailtje','detectielussen','detectiepoortjes','detectiveachtige','detectivebureaus','detectors','detentiecentra','detentiekampen','detentieruimten','detentieruimtes','detenties','detergenten','determineerklassen','detail','detectiveschrijvers','detectieplaatjes','detonators','detlefs','detacheringsbedrijven','detacheringsbureaus','detectiemethoden','detectiveseries','detentieboten','detailplannen','detailpaginas','detectielimieten','detailkaartje','detectiegrenzen','detentiefaciliteiten','detailniveaus','detailkaartjes','detailontwerpen','detectiveboeken','detailhandelsketens','detectiemethodes','detailschermen'} |
local fn = vim.fn
local opt = vim.opt
local map = vim.api.nvim_set_keymap
vim.bo.expandtab = true
vim.bo.shiftwidth = 2
vim.bo.softtabstop = 2
opt.scrolloff = 999
vim.g.mapleader = ","
map("n", "<Leader>w", ":write<CR>", { noremap = true })
map("n", "<Leader>q", ":q<CR>", { noremap = true })
-- map('n', '<Esc>', "<C-\><C-n>", {tnoremap = true})
-- Relative line numbers
opt.relativenumber = true
opt.number = true
local install_path = fn.stdpath("data") .. "/site/pack/paqs/start/paq-nvim"
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({ "git", "clone", "--depth=1", "https://github.com/savq/paq-nvim.git", install_path })
end
-- Package Management
require("paq")({
"savq/paq-nvim", -- Let Paq manage itself
-- Telescope https://github.com/nvim-telescope/telescope.nvim
"BurntSushi/ripgrep",
-- Adding since telescope needs the plenary modules which are not in Lua5.1
"nvim-lua/plenary.nvim",
"nvim-lua/popup.nvim",
"nvim-telescope/telescope.nvim",
{ "nvim-telescope/telescope-fzf-native.nvim", hook = "make" },
"nvim-telescope/telescope-file-browser.nvim",
-- LSP
"neovim/nvim-lspconfig", -- Mind the semi-colons
"williamboman/nvim-lsp-installer",
"nvim-lua/lsp-status.nvim",
"jose-elias-alvarez/null-ls.nvim",
"folke/trouble.nvim",
"hrsh7th/cmp-nvim-lsp",
"hrsh7th/cmp-buffer",
"hrsh7th/cmp-path",
"hrsh7th/cmp-cmdline",
"hrsh7th/nvim-cmp",
-- Luasnipa
"L3MON4D3/LuaSnip",
"saadparwaiz1/cmp_luasnip",
"folke/which-key.nvim",
{ "lervag/vimtex", opt = true }, -- Use braces when passing options
"nvim-treesitter/nvim-treesitter",
"nvim-treesitter/playground",
"mhinz/vim-startify",
"kyazdani42/nvim-web-devicons",
"sbdchd/neoformat",
"nvim-lualine/lualine.nvim",
"EdenEast/nightfox.nvim",
"rebelot/kanagawa.nvim",
"akinsho/toggleterm.nvim",
})
-- require('chandy')
-- TELESCOPE
-- You dont need to set any of these options. These are the default ones. Only
-- the loading is important
local action_layout = require("telescope.actions.layout")
require("telescope").setup({
defaults = {
prompt_prefix = "$ ",
mappings = {
i = {
["<C-r>"] = "which_key",
["<C-p>"] = action_layout.toggle_preview,
},
},
},
pickers = {
find_files = {
hidden = false,
},
mappings = {
i = {
["<C-e>"] = function()
print("bb is cool")
end,
},
},
},
extensions = {
fzf = {
fuzzy = true, -- false will only do exact matching
override_generic_sorter = true, -- override the generic sorter
override_file_sorter = true, -- override the file sorter
case_mode = "smart_case", -- or "ignore_case" or "respect_case"
-- the default case_mode is "smart_case"
},
},
})
-- To get fzf loaded and working with telescope, you need to call
-- load_extension, somewhere after setup function:
require("telescope").load_extension("fzf")
require("telescope").load_extension("file_browser")
map("n", "<Leader>ff", ":Telescope find_files<CR>", { noremap = true })
map("n", "<Leader>fi", ":Telescope git_files<CR>", { noremap = true })
map("n", "<Leader>fg", ":Telescope live_grep<CR>", { noremap = true })
map("n", "<Leader>fb", ":Telescope buffers<CR>", { noremap = true })
map("n", "<Leader>fh", ":Telescope help_tags<CR>", { noremap = true })
map("n", "<Leader>fo", ":Telescope oldfiles<CR>", { noremap = true })
map("n", "<Leader>fl", ":Telescope file_browser<CR>", { noremap = true })
require("nvim-treesitter.configs").setup({
ensure_installed = "maintained",
highlight = {
enable = true, -- false will disable the whole extension
},
indent = {
enable = true,
},
})
opt.foldmethod = "expr"
opt.foldexpr = "nvim_treesitter#foldexpr()"
-- Setup nvim-cmp.
local cmp = require("cmp")
cmp.setup({
snippet = {
-- REQUIRED - you must specify a snippet engine
expand = function(args)
-- vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users.
require("luasnip").lsp_expand(args.body) -- For `luasnip` users.
-- require('snippy').expand_snippet(args.body) -- For `snippy` users.
-- vim.fn["UltiSnips#Anon"](args.body) -- For `ultisnips` users.
end,
},
mapping = {
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-y>"] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping.
["<C-e>"] = cmp.mapping({
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
}),
["<CR>"] = cmp.mapping.confirm({ select = true }),
-- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items.
},
sources = cmp.config.sources({
-- { name = 'nvim_lsp' },
-- { name = 'vsnip' }, -- For vsnip users.
{ name = "luasnip" }, -- For luasnip users.
-- { name = 'ultisnips' }, -- For ultisnips users.
-- { name = 'snippy' }, -- For snippy users.
}, {
{ name = "buffer" },
}),
})
-- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline("/", {
sources = {
{ name = "buffer" },
},
})
-- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline(":", {
sources = cmp.config.sources({
{ name = "path" },
}, {
{ name = "cmdline" },
}),
})
local lsp_installer = require("nvim-lsp-installer")
lsp_installer.on_server_ready(function(server)
local opts = {}
if server.name == "sumneko_lua" then
opts = {
settings = {
Lua = {
diagnostics = {
globals = { "vim", "use" },
},
--workspace = {
-- Make the server aware of Neovim runtime files
--library = {[vim.fn.expand('$VIMRUNTIME/lua')] = true, [vim.fn.expand('$VIMRUNTIME/lua/vim/lsp')] = true}
--}
},
},
}
end
server:setup(opts)
end)
local nvim_lsp = require("lspconfig")
local capabilities = require("cmp_nvim_lsp").update_capabilities(vim.lsp.protocol.make_client_capabilities())
local servers = {
"puppet",
"cmake",
"rust_analyzer",
"tsserver",
"rust_analyzer",
"dockerls",
"ansiblels",
"bashls",
"html",
"yamlls",
}
for _, lsp in ipairs(servers) do
nvim_lsp[lsp].setup({
-- on_attach = on_attach,
flags = {
debounce_text_changes = 150,
},
capabilities = capabilities,
})
end
nvim_lsp.sumneko_lua.setup({
flags = {
debounce_text_changes = 150,
},
capabilities = capabilities,
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = "LuaJIT",
-- Setup your lua path
--path = runtime_path,
},
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = { "vim", "use" },
},
workspace = {
-- Make the server aware of Neovim runtime files
library = vim.api.nvim_get_runtime_file("", true),
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = {
enable = false,
},
},
},
})
map("n", "gk", ":lua vim.lsp.buf.definition()<cr>", { noremap = true })
map("n", "gD", ":lua vim.lsp.buf.declaration()<cr>", { noremap = true })
map("n", "gi", ":lua vim.lsp.buf.implementation()<cr>", { noremap = true })
map("n", "gw", ":lua vim.lsp.buf.document_symbol()<cr>", { noremap = true })
map("n", "gw", ":lua vim.lsp.buf.workspace_symbol()<cr>", { noremap = true })
map("n", "gr", ":lua vim.lsp.buf.references()<cr>", { noremap = true })
map("n", "gt", ":lua vim.lsp.buf.type_definition()<cr>", { noremap = true })
map("n", "K", ":lua vim.lsp.buf.hover()<cr>", { noremap = true })
map("n", "<c-k>", ":lua vim.lsp.buf.signature_help()<cr>", { noremap = true })
map("n", "<leader>af", ":lua vim.lsp.buf.code_action()<cr>", { noremap = true })
local wk = require("which-key")
wk.setup({})
require("lualine").setup()
-- require('nightfox').load("nightfox")
require("lualine").setup({
options = {
-- ... your lualine config
theme = "kanagawa",
},
})
require("kanagawa").setup({
overrides = {},
})
-- setup must be called before loading
vim.cmd("colorscheme kanagawa")
require("trouble").setup({
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
})
map("n", "<leader>xx", "<cmd>Trouble<cr>", { silent = true, noremap = true })
map("n", "<leader>xw", "<cmd>Trouble workspace_diagnostics<cr>", { silent = true, noremap = true })
map("n", "<leader>xd", "<cmd>Trouble document_diagnostics<cr>", { silent = true, noremap = true })
map("n", "<leader>xl", "<cmd>Trouble loclist<cr>", { silent = true, noremap = true })
map("n", "<leader>xq", "<cmd>Trouble quickfix<cr>", { silent = true, noremap = true })
map("n", "gR", "<cmd>Trouble lsp_references<cr>", { silent = true, noremap = true })
-- null-ls
local null_ls = require("null-ls")
null_ls.setup({
sources = {
null_ls.builtins.formatting.stylua,
null_ls.builtins.diagnostics.luacheck,
null_ls.builtins.formatting.eslint,
null_ls.builtins.diagnostics.eslint,
null_ls.builtins.code_actions.eslint,
null_ls.builtins.formatting.prettier,
null_ls.builtins.completion.spell,
null_ls.builtins.formatting.nixfmt,
null_ls.builtins.diagnostics.statix,
null_ls.builtins.code_actions.statix,
null_ls.builtins.formatting.rustfmt,
},
})
|
-- mod_push_appserver_fcm
--
-- Copyright (C) 2017 Thilo Molitor
--
-- This file is MIT/X11 licensed.
--
-- Submodule implementing FCM communication
--
-- imports
-- unlock prosody globals and allow ltn12 to pollute the global space
-- this fixes issue #8 in prosody 0.11, see also https://issues.prosody.im/1033
prosody.unlock_globals()
require "ltn12";
local https = require "ssl.https";
prosody.lock_globals()
local string = require "string";
local t_remove = table.remove;
local datetime = require "util.datetime";
local json = require "util.json";
local pretty = require "pl.pretty";
-- this is the master module
module:depends("push_appserver");
-- configuration
local fcm_key = module:get_option_string("push_appserver_fcm_key", nil); --push api key (no default)
local capath = module:get_option_string("push_appserver_fcm_capath", "/etc/ssl/certs"); --ca path on debian systems
local ciphers = module:get_option_string("push_appserver_fcm_ciphers",
"ECDHE-RSA-AES256-GCM-SHA384:"..
"ECDHE-ECDSA-AES256-GCM-SHA384:"..
"ECDHE-RSA-AES128-GCM-SHA256:"..
"ECDHE-ECDSA-AES128-GCM-SHA256"
); --supported ciphers
local push_ttl = module:get_option_number("push_appserver_fcm_push_ttl", nil); --no ttl (equals 4 weeks)
local push_priority = module:get_option_string("push_appserver_fcm_push_priority", "high"); --high priority pushes (can be "high" or "normal")
local push_endpoint = "https://fcm.googleapis.com/fcm/send";
-- high level network (https) functions
local function send_request(data)
local respbody = {} -- for the response body
prosody.unlock_globals(); -- unlock globals (https.request() tries to access global PROXY)
local result, status_code, headers, status_line = https.request({
method = "POST",
url = push_endpoint,
source = ltn12.source.string(data),
headers = {
["authorization"] = "key="..tostring(fcm_key),
["content-type"] = "application/json",
["content-length"] = tostring(#data)
},
sink = ltn12.sink.table(respbody),
-- luasec tls options
mode = "client",
protocol = "tlsv1_2",
verify = {"peer", "fail_if_no_peer_cert"},
capath = capath,
ciphers = ciphers,
options = {
"no_sslv2",
"no_sslv3",
"no_ticket",
"no_compression",
"cipher_server_preference",
"single_dh_use",
"single_ecdh_use",
},
});
prosody.lock_globals(); -- lock globals again
if not result then return nil, status_code; end -- status_code contains the error message in case of failure
-- return body as string by concatenating table filled by sink
return table.concat(respbody), status_code, status_line, headers;
end
-- handlers
local function fcm_handler(event)
local settings = event.settings;
local data = {
["to"] = tostring(settings["token"]),
["collapse_key"] = "mod_push_appserver_fcm.collapse",
["priority"] = (push_priority=="high" and "high" or "normal"),
["data"] = {},
};
if push_ttl and push_ttl > 0 then data["time_to_live"] = push_ttl; end -- ttl is optional (google's default: 4 weeks)
data = json.encode(data);
module:log("debug", "sending to %s, json string: %s", push_endpoint, data);
local response, status_code, status_line = send_request(data);
if not response then
module:log("error", "Could not send FCM request: %s", tostring(status_code));
return tostring(status_code); -- return error message
end
module:log("debug", "response status code: %s, raw response body: %s", tostring(status_code), response);
if status_code ~= 200 then
local fcm_error = "Unknown FCM error.";
if status_code == 400 then fcm_error="Invalid JSON or unknown fields."; end
if status_code == 401 then fcm_error="There was an error authenticating the sender account."; end
if status_code >= 500 and status_code < 600 then fcm_error="Internal server error, please retry again later."; end
module:log("error", "Got FCM error: %s", fcm_error);
return fcm_error;
end
response = json.decode(response);
module:log("debug", "decoded: %s", pretty.write(response));
-- handle errors
if response.failure > 0 then
module:log("error", "FCM returned %s failures:", tostring(response.failure));
local fcm_error = true;
for k, result in pairs(response.results) do
if result.error and #result.error then
module:log("error", "Got FCM error:", result.error);
fcm_error = tostring(result.error); -- return last error to mod_push_appserver
end
end
return fcm_error;
end
-- handle success
for k, result in pairs(response.results) do
if result.message_id then
module:log("debug", "got FCM message id: '%s'", tostring(result.message_id));
end
end
return false; -- no error occured
end
-- setup
module:hook("incoming-push-to-fcm", fcm_handler);
module:log("info", "Appserver FCM submodule loaded");
function module.unload()
if module.unhook then
module:unhook("incoming-push-to-fcm", fcm_handler);
end
module:log("info", "Appserver FCM submodule unloaded");
end
|
local buyMenu
local lastHouse
AddEvent("OnTranslationReady", function()
buyMenu = Dialog.create(_("buy_house"), _("house_buy_text", _("currency_symbol")), _("buy"), _("cancel"))
end)
AddRemoteEvent("ShowHouseBuyDialog", function(house, id, price)
lastHouse = house
Dialog.setVariable(buyMenu, "price", price)
Dialog.show(buyMenu)
end)
AddEvent("OnDialogSubmit", function(dialog, button)
if dialog == buyMenu then
if button == 1 then
CallRemoteEvent("BuyHouse", lastHouse)
end
end
end) |
-- a timer to dynamically set the awesome window manager background
-- every 1 second.
--
-- the background color is based on the hexadecimal value of the current
-- time mapped to rgb. this algorithm mimics the same effect as this
-- JS version:
--
-- http://colorclock.nogoodatcoding.com/
--
-- which is in turn based on a flash version, here:
--
-- http://thecolourclock.co.uk/
--
-- the below algorithm should produce the same exact colors as the above two
--
-- DEPENDENCIES:
--
-- hsetroot (though it's probably possible to accomplish same using
-- esetroot, feh, or something else)
function num2hex(num)
local hexstr = '0123456789abcdef'
local s = ''
while num > 0 do
local mod = math.floor(math.fmod(num, 16))
s = string.sub(hexstr, mod+1, mod+1) .. s
num = math.floor(num / 16)
end
if s == '' then s = '0' end
return s
end
function addLeadingZero(n)
if(string.len(n) < 2) then return '0' .. n end
return n
end
function timeToHex(n, fact)
n = n*fact
if (n < 0) then
n = 0xFFFFFFFF + n + 1
end
return num2hex( n )
end
-- local over60 = 256/60;
-- local over24 = 256/24;
-- local hext = timer({timeout=1})
-- hext:connect_signal("timeout", function ()
-- local dt = os.date("*t")
-- local h = addLeadingZero(timeToHex(dt.hour, over24))
-- local m = addLeadingZero(timeToHex(dt.min, over60))
-- local s = addLeadingZero(timeToHex(dt.sec, over60))
-- local hex = '"#' .. h .. m .. s .. '"'
-- -- log(hex)
-- awful.util.spawn_with_shell('hsetroot -solid ' .. hex)
-- end)
-- hext:start()
|
PoisonDartTrapNpc = {
click = function(block, npc)
local animation = 1
if (block.blType == BL_PC) then
if block.state == 1 then
return
end
block:sendMinitext("You stepped on a trap!")
if not block:canPK(block) then
return
end
end
block.attacker = npc.owner
removeTrapItem(npc)
npc:delete()
if block:checkIfCast(protections) then
return
end
if block:checkIfCast(venoms) then
return
end
PoisonDartTrapNpc.cast(block)
end,
endAction = function(npc, owner)
removeTrap(npc)
end,
cast = function(block)
local duration = 224000
if (block.blType == BL_PC) then
duration = 224000
end
if (block.blType == BL_MOB) then
duration = 1 + math.random(1500, 30000)
end
if block:hasDuration("poison_dart_trap") then
block:setDuration("poison_dart_trap", 0)
block:setDuration("poison_dart_trap", duration)
else
block:setDuration("poison_dart_trap", duration)
end
block:sendAnimation(11, 5)
end,
while_cast_1500 = function(block)
local damage = block.baseHealth *.01
if (damage > 1000) then
damage = 1000
end
if (damage < 1) then
damage = 1
end
block:sendAnimation(1, 5)
if block.health > damage then
block:sendHealth(damage, 0)
end
end
}
|
description "Ragdoll when Shot (by Scott)"
-- Server
-- Client
client_scripts {
"client.lua",
--"client2.lua",
}
|
--单个玩家的逻辑
local player = {}
player.pid = 0
player.nickName = ""
player.ip = ""
player.sex = ""
player.headimgurl = ""
player.roomId = 0
player.site = 0
player.score = 0
player.totalScore = 0
player.winCount = 0
player.zhongzhuangCount = 0
player.dianpaoCount = 0
player.waitStartGame = 0 --0为等待client发送开始通知,1为开始通知
player.online = true
--local card = {all={}, handed={}, showed={}, rules={}}--all,handed手上的牌(key:id,item:card),showed显示出来的rule牌(key:ruletype,item:{index,id}),rules手上的分类了的rule牌(key:ruletype,item:{index,id}),rule.none(key:index,item:id)
local function hotRequire(file_name)
package.loaded[file_name] = nil
local f = require(file_name)
return f
end
local cardMgr = hotRequire("logic.playerCardManager")
local zhuangIndex = false
local isready = false
local ruleHelp
local R
function player:setRuleHelp(rr)
ruleHelp = rr
cardMgr:setRuleHelp(rr)
end
function player:setR(rr)
R = rr
cardMgr:setR(rr)
end
function player:ready(r)
isready = r
end
function player:zhuang(r)
zhuangIndex = r
end
function player:isReady()
return isready
end
function player:isZhuang()
return zhuangIndex
end
function player:setLocalsite(s)
player.site = s
end
function player:getLocalsite()
return player.site
end
function player:addScore(s)
self.score = self.score + s
self.totalScore = self.totalScore + s
end
function player:getScore()
return player.score
end
function player:getTotalScore()
return player.totalScore
end
function player:initCards(mycards, allcards)
cardMgr:init(mycards, allcards)
end
function player:getHandCards()
return cardMgr:getHandCards()
end
function player:getShowSingleCards()
return cardMgr:getShowSingleCards()
end
function player:getShowRuleCards()
return cardMgr:getShowRuleCards()
end
function player:gameover(winnerPid, winType, isDianpao)
self:ready(false)
self.winCount = self.winCount + (winnerPid == self.pid and 1 or 0)
self.zhongzhuangCount = self.zhongzhuangCount + (winType == R.wintype.hongzhuang and 1 or 0)
if isDianpao then self.dianpaoCount = self.dianpaoCount + 1 end
isready = false
self.waitStartGame = 0
end
--出牌
function player:payCards(rt, cards, othercard)
local res = cardMgr:payCards(rt, cards, othercard)
return res
end
function player:backspacePaycards()
cardMgr:popHistory()
end
function player:dispatchCardTest(isSelfCard, cardSite, card, isSystemCard)
--print("player:dispatchCardTest", self.pid)
if isSelfCard then
return cardMgr:dispatchMyCard(card, isSystemCard)
else
return cardMgr:dispatchOtherCard(player.site, cardSite, card, isSystemCard)
end
end
--[[
function player:testHupai(card)
return cardMgr:testHupai(card)
end
--]]
function player:getHupaiType( addCards )
--print("getHupaiType", self.pid)
local rt = cardMgr:getHupaiType(zhuangIndex, addCards)
return rt
end
function player:getBestHupaiType()
return cardMgr:getBestHupaiType()
end
function player:removeSingleShowCard(cid)
return cardMgr:removeSingleShowCard(cid)
end
function player:checkWufuBaojing()
return cardMgr:checkWufuBaojing()
end
function player:isWufuBaojing()
return cardMgr:isWufuBaojing()
end
function player:neverWufuBaojing(baojing)
return cardMgr:neverWufuBaojing(baojing)
end
function player:canPayCardAfterRule(rule)
return cardMgr:canPayCardAfterRule(rule)
end
function player:choupai(rule, paycard)
return cardMgr:choupai(rule, paycard)
end
function player:canChiWithPay(cards, curPaysite)
return cardMgr:canChiWithPay(cards, player.site, curPaysite)
end
function player:playerStartGame()
self.waitStartGame = 1
self.score = 0
end
function player:isPlayerStartGame()
return self.waitStartGame == 1
end
function player:setOnline(b)
self.online = b
end
function player:getOnline()
return self.online
end
function player:addPengRuleSingleCard(cid)
return cardMgr:addPengRuleSingleCard(cid)
end
function player:getPengRuleSingleCard()
return cardMgr:getPengRuleSingleCard()
end
return player
|
local u_acute_utf8 = string.char(195)..string.char(186) -- C3 BA
local u_acute_latin1 = string.char(250) -- FA
describe("Lua object model:", function()
local lom
before_each(function()
lom = require "lxp.lom"
end)
-- run all tests twice; using plain and threat protected parser
for _, parser in ipairs { "lxp", "lxp.threat"} do
local opts = {
separator = "?",
threat = parser == "lxp.threat" and {} or nil,
}
describe(parser..".parse()", function()
local tests = {
{
root_elem = [[<abc a1="A1" a2="A2">inside tag 'abc'</abc>]],
lom = {
tag="abc",
attr = { "a1", "a2", a1 = "A1", a2 = "A2", },
"inside tag 'abc'",
},
},
{
root_elem = [[<qwerty q1="q1" q2="q2">
<asdf>some text</asdf>
</qwerty>]],
lom = {
tag = "qwerty",
attr = { "q1", "q2", q1 = "q1", q2 = "q2", },
"\n\t",
{
tag = "asdf",
attr = {},
"some text",
},
"\n",
},
},
{
root_elem = [[<ul><li>conteudo 1</li><li>conte]]..u_acute_utf8..[[do 2</li></ul>]],
encoding = "UTF-8",
lom = {
tag = "ul",
attr = {},
{
tag = "li",
attr = {},
"conteudo 1",
},
{
tag = "li",
attr = {},
"conteúdo 2",
},
},
},
{
root_elem = [[<ul><li>Conteudo 1</li><li>Conte]]..u_acute_latin1..[[do 2</li><li>Conteúdo 3</li></ul>]],
encoding = "ISO-8859-1",
doctype = [[<!DOCTYPE test [<!ENTITY uacute "ú">]>]], -- Ok!
lom = {
tag = "ul",
attr = {},
{
tag = "li",
attr = {},
"Conteudo 1",
},
{
tag = "li",
attr = {},
"Conteúdo 2", -- Latin-1 becomes UTF-8
},
{
tag = "li",
attr = {},
"Conteúdo 3", -- entity becomes a UTF-8 character
},
},
},
{
root_elem = [[<ul><li>Conteúdo</li></ul>]],
--doctype = [[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">]], --> ignora as entidades
--doctype = [[<!DOCTYPE html SYSTEM "about:legacy-compat">]], --> ignora as entidades
--doctype = [[<!DOCTYPE html>]], --> undefined entity
--doctype = [[<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">]], --> sintax error
--doctype = [[<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" SYSTEM "http://www.w3.org/TR/html4/strict.dtd">]], --> syntax error
--doctype = [[<!DOCTYPE HTMLlat1 PUBLIC "-//W3C//ENTITIES Latin 1//EN//HTML">]], --> syntax error
--doctype = [[<!DOCTYPE HTMLlat1 PUBLIC "-//W3C//ENTITIES Latin 1 for XHTML//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent">]], --> ignora entidades
--doctype = [[<!DOCTYPE isolat1 PUBLIC "//W3C//ENTITIES Added Latin 1//EN//XML" "http://www.w3.org/2003/entities/2007/isolat1.ent">]], --> ignora entidades
doctype = [[<!DOCTYPE test [<!ENTITY uacute "ú">]>]], -- Ok!
encoding = "UTF-8",
lom = {
tag = "ul",
attr = {},
{
tag = "li",
attr = {},
"Conteúdo", -- entity becomes a UTF-8 character
},
},
},
{
root_elem = [[<expat:abc xmlns:expat="http://expat" a1="A1" expat:a2="A2">inside tag 'abc'</expat:abc>]],
lom = { -- namespace parsing, assumes separator to be set to "?"
tag="http://expat?abc",
attr = { "a1", "http://expat?a2", a1 = "A1", ["http://expat?a2"] = "A2", },
"inside tag 'abc'",
},
},
}
for i, test in pairs(tests) do
local encoding = test.encoding or "ISO-8859-1"
local header = [[<?xml version="1.0" encoding="]]..encoding..[["?>]]..(test.doctype or '')
local doc = header..test.root_elem
it("test case " .. i .. ": string (all at once)", function()
local o = assert(lom.parse(doc, opts))
assert.same(test.lom, o)
end)
it("test case " .. i .. ": iterator", function()
local o = assert(lom.parse(string.gmatch(doc, ".-%>"), opts))
assert.same(test.lom, o)
end)
it("test case " .. i .. ": file", function()
local fn = assert(require("pl.path").tmpname())
finally(function()
os.remove(fn)
end)
assert(require("pl.utils").writefile(fn, doc))
local o = assert(lom.parse(assert(io.open(fn)), opts))
assert.same(test.lom, o)
end)
it("test case " .. i .. ": table", function()
local t = {}
for i = 1, #doc, 10 do
t[#t+1] = doc:sub(i, i+9)
end
local o = assert(lom.parse(t, opts))
assert.same(test.lom, o)
end)
end
end)
end
local input = [[<?xml version="1.0"?>
<a1>
<b1>
<c1>t111</c1>
<c2>t112</c2>
<c1>t113</c1>
</b1>
<b2>
<c1>t121</c1>
<c2>t122</c2>
</b2>
</a1>]]
describe("find_elem()", function()
it("returns element", function()
local output = assert(lom.parse(input))
local c1 = lom.find_elem (output, "c1")
assert (type(c1) == "table")
assert (c1.tag == "c1")
assert (c1[1] == "t111")
end)
end)
describe("list_children()", function()
it("returns all children if no tag specified", function()
local output = assert(lom.parse(input))
local children = {}
-- output[1] is whitespace before tag <b1>, output[2] is the table
-- for <b1>.
for child in lom.list_children(output[2]) do
children[#children+1] = child.tag
end
assert.same({ "c1", "c2", "c1" }, children)
end)
it("returns all matching children if tag specified", function()
local output = assert(lom.parse(input))
local children = {}
-- output[1] is whitespace before tag <b1>, output[2] is the table
-- for <b1>.
for child in lom.list_children(output[2], "c1") do
children[#children+1] = child.tag
end
assert.same({ "c1", "c1" }, children)
children = {}
for child in lom.list_children(output[2], "c2") do
children[#children+1] = child.tag
end
assert.same({ "c2" }, children)
end)
it("returns nothing when run on a text-node", function()
local children = {}
-- test on whitespace, typically before a tag
for child in lom.list_children(" ") do
children[#children+1] = child.tag
end
assert.same({}, children)
end)
end)
end)
|
local VirtualUser = game:GetService("VirtualUser")
game:GetService("Players").LocalPlayer.Idled:connect(function()
VirtualUser:Button2Down(Vector2.new(0,0),workspace.CurrentCamera.CFrame)
wait(1)
VirtualUser:Button2Up(Vector2.new(0,0),workspace.CurrentCamera.CFrame)
end)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:getService("RunService")
local HttpService = game:GetService("HttpService")
local Finity = loadstring(game:HttpGet("http://finity.vip/scripts/finity_lib.lua"))()
local FinityWindow = Finity.new(true,"SpeedGui by iceskiddo @ v3rm | Use [RightControl] to toggle the GUI") -- 'true' means dark mode is enabled
FinityWindow.ChangeToggleKey(Enum.KeyCode.RightControl)
local AutoCategory = FinityWindow:Category("Automation") -- name is the name of the FinityCategory
local Auto = {}
local FarmSector = AutoCategory:Sector("Farm") -- name is the name of the FinityCategory
Auto.Farm = {}
Auto.Farm.Mode = "BindToRenderStep"
Auto.Farm.Enabled = false
Auto.Farm.SteppedConnected = nil
Auto.Farm.FarmPerFrame = 1
Auto.Farm.WaitTime = 0
Auto.Farm.FarmFunction = function()
if Auto.Farm.Enabled then
for i = 0, Auto.Farm.FarmPerFrame do
ReplicatedStorage.Remotes.AddSpeed:FireServer()
end
wait(Auto.Farm.WaitTime)
end
end
FarmSector:Cheat("Dropdown", "Farm Mode", function(Option)
print("Dropdown option changed:", Option)
Auto.Farm.Mode = Option
end, {
options = {
"BindToRenderStep",
"Stepped",
"Loop"
}
})
FarmSector:Cheat("Label", "Farm Speed: BindToRenderStep > Stepped > Loop")
FarmSector:Cheat("Label", "You must use the mode used to farm to disable!")
FarmSector:Cheat("Textbox", "Farm Per Frame", function(Value)
local sucess = pcall(function() Auto.Farm.FarmPerFrame = tonumber(Value) end)
if not sucess then
Auto.Farm.FarmPerFrame = 1
end
end, {
placeholder = "1"
})
FarmSector:Cheat("Label", "More FPF is faster but the chance of Rebirth get")
FarmSector:Cheat("Label", "bugged is very high, so set a reasonable value.")
FarmSector:Cheat("Textbox", "Delay After Event", function(Value)
pcall(function() Auto.Farm.WaitTime = tonumber(Value) end)
if not sucess then
Auto.Farm.WaitTime = 0
end
end, {
placeholder = "1"
})
FarmSector:Cheat("Label", "Because high FPF = more Ping so you need to")
FarmSector:Cheat("Label", "decrease ping to avoid being kicked!")
FarmSector:Cheat("Checkbox", "Farm Enabled", function(enabled)
Auto.Farm.Enabled = enabled
if (Auto.Farm.Enabled) then
if (Auto.Farm.Mode == "BindToRenderStep") then
RunService:BindToRenderStep("Auto.Farm",0, Auto.Farm.FarmFunction)
elseif (Auto.Farm.Mode == "Stepped") then
Auto.Farm.SteppedConnected = RunService.Stepped:Connect(Auto.Farm.FarmFunction)
elseif (Auto.Farm.Mode == "Loop") then
while Auto.Farm.Mode do
Auto.Farm.FarmFunction()
wait()
end
end
else
if (Auto.Farm.Mode == "BindToRenderStep") then
RunService:UnbindFromRenderStep("Auto.Farm")
elseif (Auto.Farm.Mode == "Stepped") then
Auto.Farm.SteppedConnected:Disconnect()
end
end
end, {})
local OrbSector = AutoCategory:Sector("Orb") -- name is the name of the FinityCategory
Auto.Orb = {}
Auto.Orb.Mode = "BindToRenderStep"
Auto.Orb.Enabled = false
Auto.Orb.SteppedConnected = nil
Auto.Orb.FarmFunction = function()
if Auto.Orb.Enabled then
for i,v in pairs(game.Workspace.OrbSpawns:GetChildren()) do
if Auto.Orb.Enabled and (v.Name == "Orb" or v.Name == "Ring") then
if v:GetChildren()["Picked"] ~= nil then v:GetChildren()["Picked"]:Destroy() end
v.Transparency = 1
v.CFrame = game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame
wait()
end
end
end
end
OrbSector:Cheat("Dropdown", "Orb Farm Mode", function(Option)
print("Dropdown option changed:", Option)
Auto.Orb.Mode = Option
end, {
options = {
"BindToRenderStep",
"Stepped",
"Loop"
}
})
OrbSector:Cheat("Label", "Farm Speed: BindToRenderStep > Stepped > Loop")
OrbSector:Cheat("Label", "You must use the mode used to orb farm to disable!")
OrbSector:Cheat("Checkbox", "Orb Farm Enabled", function(enabled)
Auto.Orb.Enabled = enabled
if (Auto.Orb.Enabled) then
if (Auto.Orb.Mode == "BindToRenderStep") then
RunService:BindToRenderStep("Auto.Orb",0, Auto.Orb.FarmFunction)
elseif (Auto.Orb.Mode == "Stepped") then
Auto.Orb.SteppedConnected = RunService.Stepped:Connect(Auto.Orb.FarmFunction)
elseif (Auto.Orb.Mode == "Loop") then
while Auto.Orb.Mode do
Auto.Orb.FarmFunction()
wait()
end
end
else
if (Auto.Orb.Mode == "BindToRenderStep") then
RunService:UnbindFromRenderStep("Auto.Orb")
elseif (Auto.Orb.Mode == "Stepped") then
Auto.Orb.SteppedConnected:Disconnect()
end
end
end, {})
local RebirthSector = AutoCategory:Sector("Rebirth") -- name is the name of the FinityCategory
Auto.Rebirth = {}
Auto.Rebirth.Mode = "BindToRenderStep"
Auto.Rebirth.Enabled = false
Auto.Rebirth.SteppedConnected = nil
Auto.Rebirth.FarmFunction = function()
if Auto.Rebirth.Enabled then
ReplicatedStorage.Remotes.Rebirth:FireServer()
end
end
RebirthSector:Cheat("Dropdown", "Rebirth Mode", function(Option)
print("Dropdown option changed:", Option)
Auto.Rebirth.Mode = Option
end, {
options = {
"BindToRenderStep",
"Loop",
"Stepped"
}
})
RebirthSector:Cheat("Label", "Stable Rate: BindToRenderStep > Loop > Stepped")
RebirthSector:Cheat("Label", "Loop will rebirth slower but less lag than BTRS")
RebirthSector:Cheat("Label", "You must use the mode used to Rebirth to disable!")
RebirthSector:Cheat("Checkbox", "Rebirth Enabled", function(enabled)
Auto.Rebirth.Enabled = enabled
if (Auto.Rebirth.Enabled) then
if (Auto.Rebirth.Mode == "BindToRenderStep") then
RunService:BindToRenderStep("Auto.Rebirth",0, Auto.Rebirth.FarmFunction)
elseif (Auto.Rebirth.Mode == "Stepped") then
Auto.Rebirth.SteppedConnected = RunService.Stepped:Connect(Auto.Rebirth.FarmFunction)
elseif (Auto.Rebirth.Mode == "Loop") then
while Auto.Rebirth.Mode and wait(0.01) do
Auto.Rebirth.FarmFunction()
end
end
else
if (Auto.Rebirth.Mode == "BindToRenderStep") then
RunService:UnbindFromRenderStep("Auto.Rebirth")
elseif (Auto.Rebirth.Mode == "Stepped") then
Auto.Rebirth.SteppedConnected:Disconnect()
end
end
end, {})
local PetsSector = AutoCategory:Sector("Pets - BUGGED") -- name is the name of the FinityCategory
Auto.Pets = {}
Auto.Pets.OpenEgg = {}
Auto.Pets.OpenEgg.Enabled = false
Auto.Pets.OpenEgg.Egg = "EggOne"
Auto.Pets.OpenEgg.AllEggs = {}
Auto.Pets.OpenEgg.FarmFunction = function()
while Auto.Pets.OpenEgg.Enabled and wait(0.01) do
ReplicatedStorage.Remotes.CanBuyEgg:InvokeServer(Auto.Pets.OpenEgg.Egg)
end
end
for i, v in pairs(game.Players.LocalPlayer.PlayerGui.V2:GetChildren()) do
if v:IsA("BillboardGui") then
table.insert(Auto.Pets.OpenEgg.AllEggs, v.Name)
end
end
PetsSector:Cheat("Dropdown", "Egg To Open", function(Option)
print("Dropdown option changed:", Option)
Auto.Pets.OpenEgg.Egg = Option
end, {
options = Auto.Pets.OpenEgg.AllEggs
})
PetsSector:Cheat("Checkbox", "Open Egg Enabled", function(enabled)
Auto.Pets.OpenEgg.Enabled = enabled
if (Auto.Pets.OpenEgg.Enabled) then
Auto.Pets.OpenEgg.FarmFunction()
end
end, {})
Auto.Pets.UpgradeEgg = {}
Auto.Pets.UpgradeEgg.Enabled = false
Auto.Pets.UpgradeEgg.FarmFunction = function()
while Auto.Pets.UpgradeEgg.Enabled and wait(0.1) do
for i, v in pairs(HttpService:JSONDecode(game.Players.LocalPlayer.Pets.Value)) do
ReplicatedStorage.Remotes.UpgradePet:FireServer(v)
end
end
end
PetsSector:Cheat("Checkbox", "Upgrade Pets Enabled", function(enabled)
Auto.Pets.UpgradeEgg.Enabled = enabled
if (Auto.Pets.UpgradeEgg.Enabled) then
Auto.Pets.UpgradeEgg.FarmFunction()
end
end, {})
Auto.Pets.EquipEgg = {}
Auto.Pets.EquipEgg.Enabled = false
Auto.Pets.EquipEgg.FarmFunction = function()
while Auto.Pets.EquipEgg.Enabled and wait(0.1) do
for i, v in pairs(HttpService:JSONDecode(game.Players.LocalPlayer.Pets.Value)) do
ReplicatedStorage.Remotes.PetEquip:FireServer(v)
wait(0.001)
end
end
end
PetsSector:Cheat("Button", "Equip all Pets", function(enabled)
while Auto.Pets.UpgradeEgg.Enabled and wait(0.1) do
for i, v in pairs(HttpService:JSONDecode(game.Players.LocalPlayer.Pets.Value)) do
ReplicatedStorage.Remotes.UpgradePet:FireServer(v)
end
end
end)
PetsSector:Cheat("Label", "It wont show equipped but dont worry still count")
PetsSector:Cheat("Button", "Unequip all Pets", function()
for i, v in pairs(HttpService:JSONDecode(game.Players.LocalPlayer.Pets.Value)) do
ReplicatedStorage.Remotes.PetUnequip:FireServer(v)
end
end)
local MiscSector = AutoCategory:Sector("Miscellaneous") -- name is the name of the FinityCategory
Auto.Misc = {}
Auto.Misc.AutoGGRace = {}
Auto.Misc.AutoGGRace.Enabled = false
Auto.Misc.AutoGGRace.FarmFunction = function()
while Auto.Misc.AutoGGRace.Enabled and wait(0.1) do
if string.find(game.Players.LocalPlayer.PlayerGui.MainUI.RaceNotif.Time.Text,"A RACE IS STARTING, WANT TO JOIN?") then
local orgPos = game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame
ReplicatedStorage.Remotes.RaceTrigger:FireServer()
game.Workspace.RaceEnd.CFrame = game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame
ReplicatedStorage.Remotes.RaceResults:FireServer()
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = orgPos
end
end
end
MiscSector:Cheat("Checkbox", "Race Enabled", function(enabled)
Auto.Misc.AutoGGRace.Enabled = enabled
if (Auto.Misc.AutoGGRace.Enabled) then
Auto.Misc.AutoGGRace.FarmFunction()
end
end, {})
local TpCategory = FinityWindow:Category("Teleports") -- name is the name of the FinityCategory
local DoorSector = TpCategory:Sector("Doors") -- name is the name of the FinityCategory
for i, v in pairs(game.Workspace.Teleports:GetChildren()) do
DoorSector:Cheat("Button", v.Name.." Door", function()
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = v.CFrame
end)
end
|
local IUiElement = require("api.gui.IUiElement")
local TopicWindow = require("api.gui.TopicWindow")
local VisualAIPlanGrid = require("mod.visual_ai.api.gui.VisualAIPlanGrid")
local Draw = require("api.Draw")
local Color = require("mod.extlibs.api.Color")
local UiShadowedText = require("api.gui.UiShadowedText")
local VisualAIBlockCard = class.class("VisualAIBlockCard", IUiElement)
function VisualAIBlockCard:init(text, color, icon, index)
self.text = text
self.color = color
self.icon = icon
self.index = index and tostring(index) or nil
self.dark_color = {Color:new_rgb(color):lighten_by(0.5):to_rgb()}
self.wrapped = {}
self.window = TopicWindow:new(4, 1)
self.selected = true
self.tile_size_px = 48
end
function VisualAIBlockCard:set_selected(selected)
self.selected = selected
end
function VisualAIBlockCard:_rewrap_text()
local offset_x = 0
if self.index then
offset_x = 20
end
local _, wrapped = Draw.wrap_text(self.text, self.width - 40 - 100 - offset_x)
self.wrapped = fun.iter(wrapped):map(function(i) return UiShadowedText:new(i, 14) end):to_list()
end
function VisualAIBlockCard:set_text(text)
self.text = text
self:_rewrap_text()
end
function VisualAIBlockCard:relayout(x, y, width, height)
self.x = x
self.y = y
self.width = width
self.height = height
self.window:relayout(x + 5, y + 2.5, self.width - 10, self.height - 2.5)
self:_rewrap_text()
end
function VisualAIBlockCard:draw()
self.window:draw()
local offset_x = 0
if self.index then
Draw.set_font(20)
Draw.text_shadowed(self.index, self.x + 20, self.y + self.height / 2 - Draw.text_height() / 2)
offset_x = 20
end
VisualAIPlanGrid.draw_tile(self.icon, self.selected and self.color or self.dark_color, self.selected,
self.x + 20 + offset_x, self.y + self.height / 2 - self.tile_size_px / 2, self.tile_size_px, 8)
Draw.set_font(14)
for i, text in ipairs(self.wrapped) do
text:relayout(self.x + 24 + offset_x + self.tile_size_px + 5, self.y + 5 + i * Draw.text_height())
text:draw()
end
if not self.selected then
Draw.set_color(0, 0, 0, 64)
Draw.filled_rect(self.window.x, self.window.y, self.window.width, self.window.height)
end
end
function VisualAIBlockCard:update(dt)
end
return VisualAIBlockCard
|
math.randomseed(tick() * math.random(-100000, 100000))
--[[-------------------------------------------------------------------
---------------------- Information & Licensing ------------------------
-----------------------------------------------------------------------
PROGRAMMER(S): UnlimitedKeeping / Avenze
OWNER(S): UnlimitedKeeping & Frostcloud Studios
DETAILS: Oahu's Advanced Weather functions!
LICENSE: Creative Commons Attribution 4.0 International license
--]]-------------------------------------------------------------------
---------------------------- Variables --------------------------------
-----------------------------------------------------------------------
local functions = {}
local library = {}
local workspace = game:GetService("Workspace")
local players = game:GetService("Players")
local coregui = game:GetService("CoreGui")
local lighting = game:GetService("Lighting")
local replicated = game:GetService("ReplicatedStorage")
local serverscriptservice = game:GetService("ServerScriptService")
local serverstorage = game:GetService("ServerStorage")
local startergui = game:GetService("StarterGui")
local marketplaceservice = game:GetService("MarketplaceService")
local httpservice = game:GetService("HttpService")
local messagingservice = game:GetService("MessagingService")
local tweenservice = game:GetService("TweenService")
-- /*/ Dependencies
local noiseModule = require(script.Parent.TerrainModule)
local globalSeed = _G.Seed
local treeRarity = _G.TreeRarity
local cactusRarity = _G.CactusRarity
-----------------------------------------------------------------------
---------------------------- Functions --------------------------------
-----------------------------------------------------------------------
function functions.getSurfacePosition(posX, posZ)
local origin = Vector3.new(posX, 500, posZ)
local target = Vector3.new(posX, -100, posZ)
local ray = Ray.new(origin, (target - origin).Unit * 750) -- Makes a ray and get's the position on the surface to place the object on
local hit, pos = workspace:FindPartOnRayWithIgnoreList(ray, workspace.Objects:GetChildren(), false, true)
return pos
end
function functions.PlaceTree(posX, posZ, elevation, material)
local rand = math.random(1, (treeRarity + (noiseModule.GetNoise(posX + 816352, posZ + 937623, 750, 750, 1, globalSeed + 195723) * (treeRarity / 2)) + (elevation / 2)) + 180) -- Calculate's the chance a tree will be spawned here
if rand <= 3 then -- If the outcome is 1, this'll place an object. A tree for now
-- Makes a tree
local tree
if material == Enum.Material.Grass then
local randomNumber = math.random(1, 6)
tree = serverstorage.Objects.NormalTrees:GetChildren()[randomNumber]:Clone()
elseif material == Enum.Material.LeafyGrass then
local randomNumber = math.random(1, 6)
tree = serverstorage.Objects.NormalTrees:GetChildren()[randomNumber]:Clone()
end
tree.Parent = workspace.Objects
local surfacePos = functions.getSurfacePosition(posX, posZ)
tree:SetPrimaryPartCFrame(CFrame.new(surfacePos + Vector3.new(0, 17, 0)) * CFrame.Angles(math.rad(math.random(-80, 80) / 10), math.rad(math.random(-3600, 3600) / 10), math.rad(math.random(-80, 80) / 10))) -- Set's the tree's position and rotate's it a bit for realism
-- Makes the tree look unique, that's all this does
tree.Leaves.Color = Color3.fromRGB(math.random(140, 160), math.random(180, 220), math.random(100, 120))
tree.Trunk.Color = Color3.fromRGB(math.random(145, 165), math.random(130, 150), math.random(85, 105))
-- Random sizes
local sizeMultiplier = math.random(800, 1400) / 1000
tree.Leaves.CFrame = tree.Leaves.CFrame * CFrame.new(0, ((tree.Leaves.Size.Y * sizeMultiplier) - tree.Leaves.Size.Y) / 2, 0)
tree.Leaves.Size = tree.Leaves.Size * Vector3.new(1, sizeMultiplier, 1)
end
end
function functions.PlaceCactus(posX, posZ, elevation, material)
local rand = math.random(1, (cactusRarity + (math.abs(noiseModule.GetNoise(posX, posZ, 750, 750, 1, globalSeed + 916521) * (cactusRarity / 2)))) + 50)
if rand == 1 then
local surfacePos = functions.getSurfacePosition(posX, posZ) -- Get's surface position
local cactus = game.ServerStorage.Objects.Cactus:Clone()
cactus.Parent = workspace.Objects
cactus:SetPrimaryPartCFrame(CFrame.new(surfacePos) * CFrame.Angles(math.rad(math.random(-80, 80) / 10), math.rad(math.random(-3600, 3600) / 10), math.rad(math.random(-80, 80) / 10)))
-- Makes the cactus look unique
local cactusColor = math.random(75, 105)
cactus.Cactus.Color = Color3.fromRGB(120, math.random(140, 155), 135)
cactus.Spikes.Color = Color3.fromRGB(cactusColor, cactusColor, cactusColor)
-- Random sizes
local sizeMultiplier = math.random(900, 1400) / 1000
cactus.Cactus.CFrame = cactus.Cactus.CFrame * CFrame.new(0, ((cactus.Cactus.Size.Y * sizeMultiplier) - cactus.Cactus.Size.Y) / 2, 0)
cactus.Spikes.CFrame = cactus.Spikes.CFrame * CFrame.new(0, ((cactus.Spikes.Size.Y * sizeMultiplier) - cactus.Spikes.Size.Y) / 2, 0)
cactus.Cactus.Size = cactus.Cactus.Size * Vector3.new(1, sizeMultiplier, 1)
cactus.Spikes.Size = cactus.Spikes.Size * Vector3.new(1, sizeMultiplier, 1)
end
end
return functions |
----------------------------------
-- Area: Norg
-- NPC: Paleille
-- Type: Item Deliverer
-- !pos -82.667 -5.414 52.421 252
--
-----------------------------------
local ID = require("scripts/zones/Norg/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:showText(npc, ID.text.PALEILLE_DELIVERY_DIALOG);
player:openSendBox();
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
-- Copyright 2006-2014 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Adapted from php.lua by Josh Girvin <josh@jgirvin.com>
-- PHP/Hack LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V
local M = {_NAME = 'hack'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local line_comment = (P('//') + '#') * l.nonnewline^0
local block_comment = '/*' * (l.any - '*/')^0 * P('*/')^-1
local comment = token(l.COMMENT, block_comment + line_comment)
-- Strings.
local sq_str = l.delimited_range("'")
local dq_str = l.delimited_range('"')
local bt_str = l.delimited_range('`')
local heredoc = '<<<' * P(function(input, index)
local _, e, delimiter = input:find('([%a_][%w_]*)[\n\r\f]+', index)
if delimiter then
local _, e = input:find('[\n\r\f]+'..delimiter, e)
return e and e + 1
end
end)
local string = token(l.STRING, sq_str + dq_str + bt_str + heredoc)
-- TODO: interpolated code.
-- Numbers.
local number = token(l.NUMBER, l.float + l.integer)
-- Keywords.
local keyword = token(l.KEYWORD, word_match{
'and', 'array', 'as', 'break', 'case',
'cfunction', 'class', 'const', 'continue', 'declare', 'default',
'die', 'directory', 'do', 'double', 'echo', 'else', 'elseif',
'empty', 'enddeclare', 'endfor', 'endforeach', 'endif',
'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'false',
'for', 'foreach', 'function', 'global', 'if', 'include',
'include_once', 'isset', 'list', 'new', 'null', 'namespace',
'object', 'old_function', 'or', 'parent', 'print',
'require', 'require_once', 'resource', 'return', 'static',
'stdclass', 'switch', 'true', 'unset', 'use', 'var',
'while', 'xor', '__class__', '__file__', '__function__',
'__line__', '__sleep', '__wakeup', 'yield', 'await', 'async'
})
-- Types.
local types = token(l.TYPE, word_match{
'array', 'ArrayAccess', 'Awaitable', 'bool', 'boolean', 'callable',
'contained', 'Continuation', 'double', 'float', 'ImmMap', 'ImmSet',
'ImmVector', 'Indexish', 'int', 'integer', 'Iterable', 'Iterator',
'IteratorAggregate', 'KeyedIterable', 'KeyedIterator', 'KeyedTraversable',
'Map', 'mixed', 'newtype', 'null', 'num', 'object', 'Pair', 'real', 'Set',
'shape', 'string', 'stringish', 'Traversable', 'tuple', 'type',
'Vector', 'void'
})
-- Variables.
local word = (l.alpha + '_' + R('\127\255')) * (l.alnum + '_' + R('\127\255'))^0
local variable = token(l.VARIABLE, '$' * word)
-- Identifiers.
local identifier = token(l.IDENTIFIER, word)
-- Operators.
local operator = token(l.OPERATOR, S('!@%^*&()-+=|/.,;:<>[]{}') + '?' * -P('>'))
-- Classes.
local class_sequence = token(l.KEYWORD, P('class')) * ws^1 *
token(l.CLASS, l.word)
M._rules = {
{'whitespace', ws},
{'class', class_sequence},
{'keyword', keyword},
{'type', types},
{'identifier', identifier},
{'string', string},
{'variable', variable},
{'comment', comment},
{'number', number},
{'operator', operator},
}
-- Embedded in HTML.
local html = l.load('html')
-- Embedded hack.
local hack_start_rule = token('hack_tag', '<?' * ('hh' * l.space)^-1)
local hack_end_rule = token('hack_tag', '?>')
l.embed_lexer(html, M, hack_start_rule, hack_end_rule)
M._tokenstyles = {
hack_tag = l.STYLE_EMBEDDED
}
local _foldsymbols = html._foldsymbols
_foldsymbols._patterns[#_foldsymbols._patterns + 1] = '<%?'
_foldsymbols._patterns[#_foldsymbols._patterns + 1] = '%?>'
_foldsymbols._patterns[#_foldsymbols._patterns + 1] = '//'
_foldsymbols._patterns[#_foldsymbols._patterns + 1] = '#'
_foldsymbols.hack_tag = {['<?'] = 1, ['?>'] = -1}
_foldsymbols[l.COMMENT]['//'] = l.fold_line_comments('//')
_foldsymbols[l.COMMENT]['#'] = l.fold_line_comments('#')
M._foldsymbols = _foldsymbols
return M
|
local pkg = {}
function pkg.serializeTable0(val, name, depth)
depth = depth or 0
local res = {}
if name then
if type(name) == "string" then
table.insert(res, string.rep(" ", depth) .. string.format("[%q]=", name))
elseif type(name) == "number" then
table.insert(res, string.rep(" ", depth) .. string.format("[%d]=", name))
else
assert("not implemented")
end
end
if type(val) == "table" then
table.insert(res, "{\n")
for k, v in pairs(val) do
local tmp = pkg.serializeTable0(v, k, depth + 1)
for _, v in ipairs(tmp) do
table.insert(res, v)
end
table.insert(res, ",\n")
end
table.insert(res, string.rep(" ", depth) .. "}")
elseif type(val) == "number" or type(val) == "boolean" then
table.insert(res, tostring(val))
elseif type(val) == "string" then
table.insert(res, string.format("%q", val))
else
assert("not implmented")
end
return res
end
-- it's faster to push string into table then concat them
function pkg.serializeTable(t)
local s = pkg.serializeTable0(t)
return table.concat(s, "")
end
function pkg.test()
local t = {
"first",
"second",
check = true,
["value"] = 100,
["value2"] = 1000,
["value3"] = 1000.1,
test = {
"first inner",
"second innder",
inner = 1001,
inner2 = "hello,world",
}
}
local s = pkg.serializeTable(t)
local o = assert(loadstring("return " .. s))()
assert(o[1] == t[1])
assert(o[2] == t[2])
assert(o.value3 == t.value3)
assert(o.check == t.check)
assert(o.test.inner == t.test.inner)
assert(o.test[1] == t.test[1])
print("Serialize table is passed")
end
return pkg
|
-- Dirt Monster by PilzAdam
foodchain:register_mob("foodchain:dirt_monster", {
type = "monster",
passive = false,
attack_type = "dogfight",
damage = 2,
hp_min = 3,
hp_max = 27,
armor = 100,
collisionbox = {-0.4, -1, -0.4, 0.4, 0.8, 0.4},
visual = "mesh",
mesh = "mobs_stone_monster.b3d",
textures = {"mobs_dirt_monster.png"
},
blood_texture = "default_dirt.png",
makes_footstep_sound = true,
sounds = {
random = "mobs_dirtmonster",
},
view_range = 15,
walk_velocity = 1,
run_velocity = 3,
jump = true,
drops = {
{name = "default:dirt",
chance = 1, min = 3, max = 5},
},
water_damage = 1,
lava_damage = 5,
light_damage = 2,
animation = {
speed_normal = 15,
speed_run = 15,
stand_start = 0,
stand_end = 14,
walk_start = 15,
walk_end = 38,
run_start = 40,
run_end = 63,
punch_start = 40,
punch_end = 63,
},
})
foodchain:register_spawn("foodchain:dirt_monster", {"default:dirt_with_grass", "ethereal:gray_dirt"}, 5, 0, 7000, 1, 31000)
foodchain:register_egg("foodchain:dirt_monster", "Dirt Monster", "default_dirt.png", 1) |
_ENV=namespace "game"
using_namespace "luaClass"
using_namespace "container"
---@class BattleStatistics
class("BattleStatistics"){
CLASS_DEBUG(false);
}
function BattleStatistics:BattleStatistics(sprite)
self.sprite=sprite
--分数
self.scores=100
--攻击次数
self.attackCount=0
--受击次数
self.hitCount=0
--总伤害
self.totalHurt=0
--受到的伤害
self.totalHittedHurt=0
self.exp=0
end
function BattleStatistics:calculate()
local scores=self.scores-self.attackCount/5-self.hitCount
scores=scores<0 and 0 or scores
local p=(self.totalHurt-self.totalHittedHurt)/self.sprite.maxHp
if p>10 then p=10 end
scores=scores+p*5
self.scores=math.ceil(scores)
end
function BattleStatistics:onResult()
self.sprite.role:addExp(self:getExpValue())
local eqBookSkillStruct=self.sprite.role.addition.eqBookSkillStruct
if eqBookSkillStruct then
local skillName=eqBookSkillStruct.skillName
local level=eqBookSkillStruct.level
if eqBookSkillStruct.type=="skill" then
---@type Skill
local skill=self.sprite.role.skills:get(skillName)
if skill then
if level>skill.maxlevel then
skill.maxlevel=level
end
skill:addExp(self:getExpValue())
else
skill=Skill(skillName,1,level,true)
skill:addExp(self:getExpValue())
self.sprite.role.skills:insert(skillName,skill)
end
elseif eqBookSkillStruct.type=="internalskill" then
local skill=self.sprite.role.internalSkills:get(skillName)
if skill then
if level>skill.maxlevel then
skill.maxlevel=level
end
skill:addExp(self:getExpValue())
else
skill=InternalSkill(skillName,1,level,true)
skill:addExp(self:getExpValue())
self.sprite.role.internalSkills:insert(skillName,skill)
end
end
end
end
function BattleStatistics:getExpValue( )
return math.ceil(self.exp*(self.scores/100+1))
end
function BattleStatistics:toString()
local str=
self.sprite.role.name..":\n"..
"攻击次数:"..self.attackCount.."\n"..
"受击次数:"..self.hitCount.."\n"..
"总伤害:"..math.ceil(self.totalHurt).."\n"..
"评价分数:"..self.scores.."\n"..
"获得经验:"..self:getExpValue().."\n"
return str
end |
require "Scripts/Levels/ILevel"
require "Scripts/Enemies/FireSpinner"
require "Scripts/Enemies/Hopper"
require "Scripts/Enemies/BouncingBomb"
Tutorial =
{
_name = "Tutorial",
_tmxPath = "Levels/Tutorial.tmx",
_rows = 10,
_columns =10,
_heroX = 5,
_heroY = 5,
_enemies = {},
_beatPause = 0.5,
_beatBuffer = 0.1,
}
Tutorial.__index = Tutorial
function Tutorial:Create()
local b = {}
setmetatable(b, Tutorial)
setmetatable(Tutorial, { __index = ILevel})
self:Init()
return b
end
function Tutorial:Init()
self._enemies[1] = FireSpinner:Create(1)
self._enemies[1]:SetPosX(5)
self._enemies[1]:SetPosY(3)
self._enemies[2] = Hopper:Create(2)
self._enemies[2]:SetPosX(3)
self._enemies[2]:SetPosY(3)
self._enemies[3] = BouncingBomb:Create(3)
self._enemies[3]:SetPosX(8)
self._enemies[3]:SetPosY(8)
end
thisLevel = Tutorial:Create() |
--
-- Xbox Series X/S tests
-- Copyright Blizzard Entertainment, Inc
--
local p = premake
local suite = test.declare("scarlett_globals")
local vc2010 = p.vstudio.vc2010
--
-- Setup
--
local wks, prj
function suite.setup()
p.action.set("vs2019")
wks, prj = test.createWorkspace()
end
local function prepare()
kind "WindowedApp"
system "scarlett"
prj = test.getproject(wks, 1)
vc2010.globals(prj)
end
function suite.onDefaultValues()
prepare()
test.capture [[
<PropertyGroup Label="Globals">
<ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid>
<IgnoreWarnCompileDuplicatedFilename>true</IgnoreWarnCompileDuplicatedFilename>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetRuntime>Native</TargetRuntime>
</PropertyGroup>
]]
end
|
----------------------------------------------------------------
-- API Ban Sync - A Simple FiveM Script, Made By Jordan.#2139 --
----------------------------------------------------------------
config = {
APIName = "https://protectthedevs.com", -- The name of your api
apiURL = 'https://protectthedevs.com/api/users/', -- The URL of the API that you would like to use
ThereWasAnIssue = 'Sorry, there was an issue checking against the API... Please restart FiveM and if the issue persists contact the server owner.', -- The message the user recieves if there was an issue with the API
Discord = {
Enabled = true, -- Would you like to enable Discord loggging?
WebHookURL = 'WEBHOOK_URL' -- Your webhook URL (MUST HAVE IF Enabled = true)
},
AdaptiveCards = {
enabled = true, -- Would you like to enable adaptive cards?
Website_Link = 'https://jordan2139.me', -- Your website link
Discord_Link = 'https://jordan2139.me/discord', -- Your discord link
Wait = 10, -- How many seconds should splash page be shown for? (Max is 12)
Header_IMG = 'https://forum.cfx.re/uploads/default/original/3X/a/6/a6ad03c9fb60fa7888424e7c9389402846107c7e.png',
Heading1 = "Welcome to [ServerName]",
Heading2 = "Make sure to join our Discord and check out our website!",
}
} |
-- app.config.custom中的配置会覆盖*.config,可以通过skynet.getenv获取,并且支持值为table,
return {
--[[
db_type = "redis",
db_is_cluster = false,
db_config = {
host = "127.0.0.1",
port = 6000,
auth = "redispwd",
},
]]
--[[
db_type = "redis",
db_is_cluster = true,
db_config = {
startup_nodes = {
{host="127.0.0.1",port=7001},
{host="127.0.0.1",port=7002},
{host="127.0.0.1",port=7003},
},
opt = {
max_connections = 256,
read_slave = true,
auth = nil,
db = 0,
},
},
]]
db_type = "mongodb",
--db_is_cluster = true,
db_config = {
db = skynet.getenv("appid") or "game",
rs = {
{host = "127.0.0.1",port = 26000,username=nil,password=nil,authmod="scram_sha1",authdb="admin"},
}
},
--公告信息
notice_config = require "app.config.notice",
--微信分享地址
weixin_shareurl = require "app.config.weixinshare"
}
|
-- @AlexOp_ was here
local tree
local max_dist = 500
local min_dist = 10
local width, height = 400, 400
local Branch = require(script.Branch)
local Leaf = require(script.Leaf)
local Tree = {}
Tree.__index = Tree
function Tree.new()
local self = setmetatable({
leaves = {},
branches = {}
},Tree)
for i = 1, 500 do
table.insert(self.leaves, Leaf.new(width, height))
end
local pos = Vector3.new(width / 2, 0, 0)
local dir = Vector3.new(0, -1, 0)
local root = Branch.new(nil, pos, dir)
table.insert(self.branches, root)
local current = root
local found = false
while not found do
for i = 1, #self.leaves do
local d = (current.pos - self.leaves[i].pos).Magnitude
if d < max_dist then
found = true
end
end
if not found then
local branch = current:next()
current = branch
table.insert(self.branches, current)
end
end
return self
end
function Tree:grow()
for i = 1, #self.leaves do
local leaf = self.leaves[i]
local closestBranch = nil
local record = max_dist
for j = 1, #self.branches do
local branch = self.branches[j]
local d = (leaf.pos - branch.pos).Magnitude
if d < min_dist then
leaf.reached = true
closestBranch = nil
break
elseif d < record then
closestBranch = branch
record = d
end
end
if closestBranch ~= nil then
local newDir = (leaf.pos - closestBranch.pos).Unit
closestBranch.dir += newDir
closestBranch.count += 1
end
end
for i = #self.leaves-1, 1, -1 do
if self.leaves[i].reached then
table.remove(self.leaves, i)
end
end
for i = 1, #self.branches do
local branch = self.branches[i]
if branch.count > 0 then
branch.dir /= branch.count + 1
table.insert(self.branches, branch:next())
branch:reset()
end
end
end
function Tree:show()
for i = 1, #self.leaves do
self.leaves[i]:show()
end
for i = 1, #self.branches do
self.branches[i]:show()
end
end
tree = Tree.new()
while wait(0.05) do
tree:show()
tree:grow()
end
|
vim.cmd [[packadd packer.nvim]]
local configs = {
clang_format = function() require('plugins/clang-format') end,
cmp = function() require('plugins/cmp') end,
commenter = function() require('plugins/commenter') end,
cokeline = function() require('plugins/cokeline') end,
cpp_enhanced_highlight = function() require('plugins/cpp_enhanced_highlight') end,
fugitive = function() require('plugins/fugitive') end,
goto_preview = function() require('plugins/goto-preview') end,
goyo = function() require('plugins/goyo') end,
incsearch = function() require('plugins/incsearch') end,
indentline = function() require('plugins/indentline') end,
lightline = function() require('plugins/lightline') end,
localvimrc = function() require('plugins/localvimrc') end,
lspconfig = function() require('plugins/lsp') end,
luasnip = function() require('plugins/luasnip') end,
mkdx = function() require('plugins/mkdx') end,
nvim_tree = function() require('plugins/nvim_tree') end,
operator_flashy = function() require('plugins/operator-flashy') end,
quickscope = function() require('plugins/quickscope') end,
startify = function() require('plugins/startify') end,
telescope = function() require('plugins/telescope') end,
template = function() require('plugins/template') end,
terminal_help = function() require('plugins/terminal-help') end,
treesitter = function() require('plugins/treesitter') end,
trouble = function() require('plugins/trouble') end,
vimtex = function() require('plugins/vimtex') end,
vimwiki = function() require('plugins/vimwiki') end,
which_key = function() require('plugins/which-key') end,
}
return require('packer').startup(function(use)
use 'wbthomason/packer.nvim'
use 'lewis6991/impatient.nvim'
-- Keymaps
use({
"folke/which-key.nvim",
event = "VimEnter",
config = configs.which_key,
})
-- General plugins
use 'tpope/vim-repeat' -- Enable repeating supported plugin maps with .
use 'tpope/vim-surround' -- quoting/parenthesizing made simple
use 'tpope/vim-unimpaired' -- Pairs of handy bracket mappings
use 'tpope/vim-dispatch' -- Asynchronous build and test dispatcher
use 'wikitopian/hardmode' -- Disable arrow movement, update to takac/vim-hardtime eventually
use 'nvim-lua/plenary.nvim' -- plenary: full; complete; entire; absolute; unqualified. All the lua functions I don't want to write twice.
-- Colour schemes
use 'junegunn/seoul256.vim'
use 'Irubataru/vim-colors-solarized'
use 'NLKNguyen/papercolor-theme'
use 'chriskempson/base16-vim'
use 'trevordmiller/nova-vim'
use 'dracula/vim'
-- UI and look
use {
'noib3/cokeline.nvim', -- 👃 A neovim bufferline for people with addictive personalities
config = configs.cokeline,
requires = 'kyazdani42/nvim-web-devicons'
}
use { 'itchyny/lightline.vim', config = configs.lightline } -- A light and configurable statusline/tabline plugin for Vim
use {
'haya14busa/vim-operator-flashy', -- Highlight yanked area
config = configs.operator_flashy,
requires = 'kana/vim-operator-user'
}
use { 'Yggdroot/indentLine', config = configs.indentline, ft = { 'python' }} -- A vim plugin to display the indention levels with thin vertical lines
use { 'haya14busa/incsearch.vim', config = configs.incsearch } -- Improved incremental searching for Vim
use { 'junegunn/limelight.vim' } -- Hyperfocus-writing in Vim
use { 'junegunn/goyo.vim', config = configs.goyo } -- Distraction-free writing in Vim
use { 'mhinz/vim-startify', config = configs.startify } -- The fancy start screen for Vim
use { 'mhinz/vim-signify' } -- Show a diff using Vim its sign column
-- LSP
use 'wbthomason/lsp-status.nvim' -- Utility functions for getting diagnostic status and progress messages from LSP servers, for use in the Neovim statusline
use { 'neovim/nvim-lspconfig', config = configs.lspconfig } -- Quickstart configurations for the Nvim LSP client
use 'williamboman/nvim-lsp-installer' -- Companion plugin for nvim-lspconfig that allows you to seamlessly manage LSP servers locally with :LspInstall. With full Windows support!
use 'hrsh7th/cmp-nvim-lsp' -- nvim-cmp source for neovim builtin LSP client
use 'hrsh7th/cmp-nvim-lua' -- nvim-cmp source for nvim lua
use 'hrsh7th/cmp-buffer' -- nvim-cmp source for buffer words
use 'hrsh7th/cmp-path' -- nvim-cmp source for path
use 'hrsh7th/cmp-cmdline' -- nvim-cmp source for vim's cmdline
-- use 'saadparwaiz1/cmp_luasnip' -- luasnip completion source for nvim-cmp
use { 'tzachar/cmp-tabnine', run = './install.sh' } -- TabNine plugin for hrsh7th/nvim-cmp
use {"petertriho/cmp-git", requires = "nvim-lua/plenary.nvim"} -- Git source for nvim-cmp
use 'onsails/lspkind-nvim' -- vscode-like pictograms for neovim lsp completion items
use { 'hrsh7th/nvim-cmp', config = configs.cmp } -- A completion plugin for neovim coded in Lua.tr
use {
'L3MON4D3/LuaSnip', -- Snippet Engine for Neovim written in Lua.
wants = "friendly-snippets",
requires = "rafamadriz/friendly-snippets",
config = configs.luasnip
}
use {
"folke/trouble.nvim", -- 🚦 A pretty diagnostics, references, telescope results, quickfix and location list to help you solve all the trouble your code is causing.
requires = "kyazdani42/nvim-web-devicons",
config = configs.trouble
}
use { "jose-elias-alvarez/null-ls.nvim" } -- Use Neovim as a language server to inject LSP diagnostics, code actions, and more via Lua.
use {
"rmagatti/goto-preview", -- A small Neovim plugin for previewing definitions using floating windows.
config = configs.goto_preview
}
-- Tree sitter
use { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate', config = configs.treesitter}
-- Fuzzy finding
use {
'nvim-telescope/telescope.nvim',
config = configs.telescope,
requires = 'nvim-lua/plenary.nvim',
}
use { "nvim-telescope/telescope-fzf-native.nvim", run = "make" }
-- Additional functionality
use {
'numToStr/Comment.nvim', -- 🧠 💪 // Smart and powerful comment plugin for neovim. Supports commentstring, dot repeat, left-right/up-down motions, hooks, and more
config = configs.commenter
}
use 'xolox/vim-misc' -- A dependency but can't remember of what
use { 'aperezdc/vim-template', config = configs.template, cmd = { 'Template' } } -- Simple templates plugin for Vim
use { 'embear/vim-localvimrc', config = configs.localvimrc } -- Search local vimrc files ('.lvimrc') in the tree (root dir up to current dir) and load them.
use { 'junegunn/vim-easy-align' } -- A Vim alignment plugin
use { 'unblevable/quick-scope', config = configs.quickscope } -- Highlighting for f,F,t,T
use { 'skywind3000/vim-terminal-help', config = configs.terminal_help } -- Small changes make vim/nvim's internal terminal great again
use { 'AndrewRadev/linediff.vim' } -- A vim plugin to perform diffs on blocks of code
use 'skywind3000/asyncrun.vim' -- Run Async Shell Commands in Vim 8.0 / NeoVim and Output to the Quickfix Window
use {
'kyazdani42/nvim-tree.lua', -- A file explorer tree for neovim written in lua
requires = 'kyazdani42/nvim-web-devicons',
config = configs.nvim_tree
}
use { "b0o/mapx.nvim" } -- A better way to create key mappings in Neovim.
use { "windwp/nvim-autopairs", config = function() require('nvim-autopairs').setup{} end, } -- autopairs for neovim written by lua
-- Note taking
use {'vimwiki/vimwiki', config = configs.vimwiki, branch = 'dev'} -- Pesonalized wiki and note taking
-- Git
use { 'tpope/vim-fugitive', config = configs.fugitive } -- The best git plugin
use 'airblade/vim-rooter' -- Changes the vim directory to project root
use 'rhysd/git-messenger.vim' -- Vim and Neovim plugin to reveal the commit messages under the cursor
use { -- Single tabpage interface for easily cycling through diffs for all modified files for any git rev.
'sindrets/diffview.nvim',
requires = 'nvim-lua/plenary.nvim',
}
-- C/C++
use { 'octol/vim-cpp-enhanced-highlight', config = configs.cpp_enhanced_highlight, ft = { 'cpp' } } -- Additional Vim syntax highlighting for C++ (including C++11/14/17)
use { 'preservim/tagbar', ft = { 'cpp' } } -- Vim plugin that displays tags in a window, ordered by scope
use {
'rhysd/vim-clang-format', -- Vim plugin for clang-format
config = configs.clang_format,
ft = { 'hpp', 'cpp', 'c' },
requires = 'kana/vim-operator-user'
}
-- Python
use {
'Chiel92/vim-autoformat', -- Provide easy code formatting in Vim by integrating existing code formatters
ft = { 'python', 'tex', 'html', 'css', 'javascript' }
}
use {'tmhedberg/SimpylFold',ft = { 'python' } } -- No-BS Python code folding for Vim
-- For Clojure
use { 'Olical/conjure', ft = { 'clojure' } } -- Interactive evaluation for Neovim (Clojure, Fennel, Janet, Racket, Hy, MIT Scheme, Guile)
use {
'tpope/vim-sexp-mappings-for-regular-people', -- vim-sexp mappings for regular people
ft = { 'clojure' },
requires = { 'guns/vim-sexp', ft = { 'clojure' } } -- Precision Editing for S-expressions
}
-- use { 'tpope/vim-fireplace', ft = { 'clojure' } } -- Clojure REPL support
-- use { 'guns/vim-clojure-static', ft = { 'clojure' } } -- Meikel Brandmeyer's excellent Clojure runtime files
-- use { 'guns/vim-clojure-highlight', ft = { 'clojure' } } -- Extend builtin syntax highlighting to referred and aliased vars in Clojure buffers
-- use { 'vim-scripts/paredit.vim', ft = { 'clojure' } } -- Paredit Mode: Structured Editing of Lisp S-expressions
-- use { 'venantius/vim-cljfmt', ft = { 'clojure' } } -- A Vim plugin for cljfmt, the Clojure formatting tool.
-- For LaTeX
use { 'lervag/vimtex', config = configs.vimtex, ft = { 'tex' } } -- A modern Vim and neovim filetype plugin for LaTeX files.
use { 'KeitaNakamura/tex-conceal.vim', ft = { 'tex' } } -- This plugin extends the Conceal feature of Vim for LaTeX.
-- For JavaScript / JSON
use { 'pangloss/vim-javascript', ft = { 'javascript' } } -- Vastly improved Javascript indentation and syntax support in Vim.
use { 'Olical/vim-syntax-expand', ft = { 'javascript' } } -- Expand characters to code if not in a comment or string
use { 'elzr/vim-json', ft = { 'json' } } -- A better JSON for Vim: distinct highlighting of keywords vs values, JSON-specific (non-JS) warnings, quote concealing.
use { "b0o/schemastore.nvim" } -- A Neovim Lua plugin providing access to the SchemaStore catalog.
-- For Markdown
use { 'SidOfc/mkdx', ft = { 'markdown' } } -- A vim plugin that adds some nice extra's for working with markdown documents
use({ "npxbr/glow.nvim", cmd = "Glow" }) -- A markdown preview directly in your neovim.
-- Other syntax highlighting
use 'lazywei/vim-matlab' -- A matlab plugin for vim, includes syntax highlighting, correct indention and so on.
use 'rsmenon/vim-mathematica' -- Mathematica syntax highlighting (and more) for vim
use 'vim-scripts/gnuplot.vim' -- Syntax highlighting for Gnuplot
use 'Glench/Vim-Jinja2-Syntax' -- An up-to-date jinja2 syntax file.
use 'jalvesaq/Nvim-R' -- Vim plugin to work with R
use {'tmux-plugins/vim-tmux', ft = { 'tmux' } } -- vim plugin for tmux.conf
end)
|
local BasePlugin = require "kong.plugins.base_plugin"
local singletons = require "kong.singletons"
local constants = require "kong.constants"
local meta = require "kong.meta"
local kong = kong
local server_header = meta._SERVER_TOKENS
local DEFAULT_RESPONSE = {
[300] = "Multiple Choices",
[301] = "Moved Permanently",
[302] = "Found",
[303] = "See Other",
[304] = "Not Modified",
[305] = "Use Proxy",
[306] = "Switch Proxy",
[307] = "Temporary Redirect",
[308] = "Permanent Redirect",
}
local RedirectHandler = BasePlugin:extend()
RedirectHandler.PRIORITY = 2
RedirectHandler.VERSION = "0.2.0"
function RedirectHandler:new()
RedirectHandler.super.new(self, "redirect")
end
function RedirectHandler:access(conf)
RedirectHandler.super.access(self)
local status = conf.status_code
local content = conf.body
local content_type = conf.content_type
if not content then
content = { ["message"] = conf.message or DEFAULT_RESPONSE[status] }
content_type = nil -- reset to the default 'application/json'
end
if not content_type then
content_type = "application/json; charset=utf-8"
end
local headers = {
["Content-Type"] = content_type,
}
if singletons.configuration.enabled_headers[constants.HEADERS.SERVER] then
headers[constants.HEADERS.SERVER] = server_header
end
local location = conf.location
if location then
if conf.append_request_uri_to_location then
location = location .. kong.request.get_path()
end
if conf.append_query_string_to_location then
location = location .. "?" .. kong.request.get_raw_query()
end
headers["Location"] = location
end
-- kong.log.debug("Nginx request URI: [", kong.request.get_path(), "]")
-- kong.log.debug("Nginx query string: [", kong.request.get_raw_query(), "]")
-- kong.log.debug("Computed content: [", content, "]")
-- kong.log.debug("Configured location: [", location, "]")
-- kong.log.debug("Computed response headers: [", headers, "]")
return kong.response.exit(status, content, headers)
end
return RedirectHandler
|
-- Some concepts borrowed from https://github.com/zzamboni/dot-hammerspoon
hyper = {"ctrl", "alt", "cmd", "shift"}
hs.logger.defaultLogLevel="info"
hs.window.animationDuration = 0
hs.loadSpoon("SpoonInstall")
spoon.SpoonInstall.repos.miro = {
url = "https://github.com/miromannino/miro-windows-manager",
desc = "Miro's windows manager"
}
spoon.SpoonInstall.use_syncinstall = true
spoon.SpoonInstall:andUse("MiroWindowsManager",
{
repo = 'miro',
hotkeys = {
up = { hyper, "up" },
right = { hyper, "right" },
down = { hyper, "down" },
left = { hyper, "left" },
fullscreen = { hyper, "f" }
}
}
)
spoon.SpoonInstall:andUse("WindowScreenLeftAndRight",
{
hotkeys = {
screen_left = { hyper, "[" },
screen_right = { hyper, "]" }
}
}
)
spoon.SpoonInstall:andUse("WindowGrid",
{
config = { gridGeometries = { { "8x4" } } },
hotkeys = {show_grid = {hyper, "g"}},
start = true
}
)
-- TODO: does not seem to be working
-- TODO: currently using CheatSheet app instead
spoon.SpoonInstall:andUse("KSheet",
{
-- hotkeys = {
-- toggle = { hyper, "/" }
-- }
}
)
hs.hotkey.bind(hyper, '/', function()
spoon.KSheet:show()
end)
-- Meta {{{1
hs.hotkey.bind(hyper, 'i', function()
hs.hints.windowHints()
end)
hs.hotkey.bind(hyper, 'b', function()
hs.application.launchOrFocus("/Applications/Google Chrome.app")
end)
hs.hotkey.bind(hyper, 'e', function()
hs.application.launchOrFocus('Sublime Text')
end)
hs.hotkey.bind(hyper, 'm', function()
hs.application.launchOrFocus('Google Play Music Desktop Player')
end)
hs.hotkey.bind(hyper, 'r', function()
hs.application.launchOrFocus("/Applications/Microsoft Remote Desktop.app")
end)
hs.hotkey.bind(hyper, 's', function()
hs.application.launchOrFocus("/Applications/Slack.app")
end)
hs.hotkey.bind(hyper, 't', function()
hs.application.launchOrFocus("/Applications/iTerm.app")
end)
hs.hotkey.bind(hyper, 'v', function()
hs.application.launchOrFocus("/Applications/VMware Fusion.app")
end)
-- hs.hotkey.bind(hyper, 'P', function()
-- hs.openPreferences()
-- end)
-- hs.hotkey.bind(hyper, 'R', function()
-- hs.reload()
-- end)
function reloadConfig(files)---- {{{2
doReload = false
for _,file in pairs(files) do
if file:sub(-4) == ".lua" then
hs.reload()
break
end
end
end-- }}}2
function uptime()---- {{{2
local days = hs.execute("uptime | \
grep -o '\\d\\+\\sdays\\?' | grep -o '\\d\\+'")
local seconds = hs.execute("uptime | \
grep -o '\\d\\+\\ssecs\\?' | grep -o '\\d\\+'")
if tonumber(days) then
local minutes = hs.execute("uptime | awk '{print $5}' | \
sed -e 's/[^0-9:].*//' | sed 's/:/*60+/g' | bc")
local minutes = tonumber(minutes) or 0
local seconds = tonumber(seconds) or 0
local days = tonumber(days) or 0
return (days * 24 * 60 + minutes) * 60 + seconds
elseif tonumber(seconds) then
return tonumber(seconds)
else
local minutes = hs.execute("uptime | awk '{print $3}' | \
sed -e 's/[^0-9:].*//' | sed 's/:/*60+/g' | bc")
local minutes = tonumber(minutes) or 0
return minutes * 60
end
end-- }}}2
hs.pathwatcher.new(os.getenv("HOME") ..
"/.hammerspoon/", reloadConfig):start()
if uptime() > 1000 then
-- I don't want the alert when I have just turned on the computer
hs.alert.show("Hammerspoon loaded")
end
-- }}}1
|
local _, T = ...
local L = T.L
local cfgFrame = CreateFrame("Frame", nil, UIParent)
-- Header
local cfgFrameHeader = cfgFrame:CreateFontString("OVERLAY", nil, "GameFontNormalLarge")
cfgFrameHeader:SetPoint("TOPLEFT", 15, -15)
cfgFrameHeader:SetText("Requires Level X")
-- Info text
local cfgDescription = cfgFrame:CreateFontString("OVERLAY", nil, "GameFontHighlightSmall")
cfgDescription:SetPoint("TOPLEFT", 15, -40)
cfgDescription:SetJustifyH("LEFT")
cfgDescription:SetJustifyV("TOP")
cfgDescription:SetWidth("600")
cfgDescription:SetText(L["Description"])
-- Checkbox: Enable Addon
local cfgAddonEnabled = CreateFrame("CheckButton", nil, cfgFrame, "InterfaceOptionsCheckButtonTemplate")
cfgAddonEnabled:SetPoint("TOPLEFT", 20, -140)
cfgAddonEnabled.Text:SetText(L["Enable Addon"])
cfgAddonEnabled:SetScript("OnClick", function(self)
RequiresLevelXConfig["AddonEnabled"] = self:GetChecked()
end)
-- Checkbox: Equippable Items Only
local cfgEquippableOnly = CreateFrame("CheckButton", nil, cfgFrame, "InterfaceOptionsCheckButtonTemplate")
cfgEquippableOnly:SetPoint("TOPLEFT", 20, -170)
cfgEquippableOnly.Text:SetText(L["Equippable Items Only"])
cfgEquippableOnly:SetScript("OnClick", function(self)
RequiresLevelXConfig["EquippableOnly"] = self:GetChecked()
end)
local function RequiresLevelX_cfgInitView()
cfgAddonEnabled:SetChecked(RequiresLevelXConfig["AddonEnabled"] ~= false)
cfgEquippableOnly:SetChecked(RequiresLevelXConfig["EquippableOnly"] ~= false)
end
local function RequiresLevelX_cfgSaveView()
-- Settings are already saved dynamically
end
local function RequiresLevelX_cfgSetDefaults()
ParagonDB["config"] = T.defaults
Paragon_cfgInitView()
end
cfgFrame:Hide()
cfgFrame:SetScript("OnShow", RequiresLevelX_cfgInitView)
cfgFrame.name, cfgFrame.okay, cfgFrame.default = "Requires Level X", RequiresLevelX_cfgSaveView, RequiresLevelX_cfgSetDefaults
InterfaceOptions_AddCategory(cfgFrame)
|
--Made by Skovsbøll#3650
RegisterNetEvent("revive")
AddEventHandler("revive", function()
local plyCoords = GetEntityCoords(GetPlayerPed(-1), true)
ResurrectPed(GetPlayerPed(-1))
SetEntityHealth(GetPlayerPed(-1), 200)
ClearPedTasksImmediately(GetPlayerPed(-1))
SetEntityCoords(GetPlayerPed(-1), plyCoords.x, plyCoords.y, plyCoords.z + 1.0, 0, 0, 0, 0)
end) |
function onUse(cid, item, frompos, item2, topos)
doTransformItem(item.uid,4008)
doPlayerAddItem(cid, 2675, math.random(10))
doDecayItem(item.uid)
return 1
end |
--[[
HarvestHPTracker
by: Chris
Client-side tracking of HP of objects in the world.
Put into a require() script, so that it's easy to
access from anywhere.
--]]
local prop_HarvestManager = script:GetCustomProperty("_HarvestManager")
local mgr = require(prop_HarvestManager)
local API = {}
local damagedObjects = {}
function API.GetNodeMaxHealth(obj)
local data = mgr.GetNodeData(obj)
if data ~= nil then
return data.properties.MaxHealth
else
return nil
end
end
function API.GetNodeHealth(obj)
local damage = damagedObjects[mgr.GetHId(obj)]
if damage == nil then damage = 0 end
local hp = API.GetNodeMaxHealth(obj)
if hp ~= nil then
return math.max(hp - damage, 0)
else
return nil
end
end
function API.ApplyDamage(obj, damage)
local key = mgr.GetHId(obj)
local existingDamage = damagedObjects[key] or 0
if existingDamage == nil then existingDamage = 0 end
damagedObjects[key] = math.min(existingDamage + damage, API.GetNodeMaxHealth(obj))
end
function API.IsDestroyed(obj)
return API.GetNodeHealth(obj) <= 0
end
function OnRespawn(hid, objRef)
damagedObjects[hid] = nil
end
Events.Connect("Harvest-Respawn", OnRespawn)
return API |
-- NOTES:
-- games that rely on custom model shaders are SOL
--
-- for projectile lights, ttl values are arbitrarily
-- large to make the lights survive until projectiles
-- die (see ProjectileDestroyed() for the reason why)
--
-- for "propelled" projectiles (rockets/missiles/etc)
-- ttls should be the actual ttl-values so attached
-- lights die when their "engine" cuts out, but this
-- gets complex (eg. flighttime is not available)
--
-- Explosion() occurs before ProjectileDestroyed(),
-- so for best effect maxDynamic{Map, Model}Lights
-- should be >= 2 (so there is "always" room to add
-- the explosion light while a projectile light has
-- not yet been removed)
-- we work around this by giving explosion lights a
-- (slighly) higher priority than the corresponding
-- projectile lights
local allDynLightDefs = include("LuaRules/Configs/gfx_dynamic_lighting_defs.lua")
local modDynLightDefs = allDynLightDefs[Game.modShortName] or {}
local weaponLightDefs = modDynLightDefs.weaponLightDefs or {}
-- shared synced/unsynced globals
local PROJECTILE_GENERATED_EVENT_ID = 10001
local PROJECTILE_DESTROYED_EVENT_ID = 10002
local PROJECTILE_EXPLOSION_EVENT_ID = 10003
if (gadgetHandler:IsSyncedCode()) then
function gadget:GetInfo()
return {
-- put this gadget in a lower layer than fx_watersplash and exp_no_air_nuke
-- (which both want noGFX) so the short-circuit evaluation in gh:Explosion()
-- does not cut us out
enabled = true,
layer = -1,
}
end
-- register/deregister for the synced Projectile*/Explosion call-ins
function gadget:Initialize()
for weaponDefName, _ in pairs(weaponLightDefs) do
local weaponDef = WeaponDefNames[weaponDefName]
if (weaponDef ~= nil) then
Script.SetWatchWeapon(weaponDef.id, true)
end
end
end
function gadget:Shutdown()
for weaponDefName, _ in pairs(weaponLightDefs) do
local weaponDef = WeaponDefNames[weaponDefName]
if (weaponDef ~= nil) then
Script.SetWatchWeapon(weaponDef.id, false)
end
end
end
function gadget:ProjectileCreated(projectileID, projectileOwnerID, projectileWeaponDefID)
SendToUnsynced(PROJECTILE_GENERATED_EVENT_ID, projectileID, projectileOwnerID, projectileWeaponDefID)
end
function gadget:ProjectileDestroyed(projectileID)
SendToUnsynced(PROJECTILE_DESTROYED_EVENT_ID, projectileID)
end
function gadget:Explosion(weaponDefID, posx, posy, posz, ownerID)
SendToUnsynced(PROJECTILE_EXPLOSION_EVENT_ID, weaponDefID, posx, posy, posz)
return false -- noGFX
end
else
local projectileLightDefs = {} -- indexed by unitDefID
local explosionLightDefs = {} -- indexed by weaponDefID
local projectileLights = {} -- indexed by projectileID
local explosionLights = {} -- indexed by "explosionID"
local unsyncedEventHandlers = {}
local SpringGetProjectilePosition = Spring.GetProjectilePosition
local SpringAddMapLight = Spring.AddMapLight
local SpringAddModelLight = Spring.AddModelLight
local SpringSetMapLightTrackingState = Spring.SetMapLightTrackingState
local SpringSetModelLightTrackingState = Spring.SetModelLightTrackingState
local SpringUpdateMapLight = Spring.UpdateMapLight
local SpringUpdateModelLight = Spring.UpdateModelLight
local function LoadLightDefs()
-- type(v) := {[1] = number, [2] = number, [3] = number}
-- type(s) := number
local function vector_scalar_add(v, s) return {v[1] + s, v[2] + s, v[3] + s} end
local function vector_scalar_mul(v, s) return {v[1] * s, v[2] * s, v[3] * s} end
local function vector_scalar_div(v, s) return {v[1] / s, v[2] / s, v[3] / s} end
for weaponDefName, weaponLightDef in pairs(weaponLightDefs) do
local weaponDef = WeaponDefNames[weaponDefName]
local projectileLightDef = weaponLightDef.projectileLightDef
local explosionLightDef = weaponLightDef.explosionLightDef
if (weaponDef ~= nil) then
projectileLightDefs[weaponDef.id] = projectileLightDef
explosionLightDefs[weaponDef.id] = explosionLightDef
-- NOTE: these rates are not sensible if the decay-type is exponential
if (projectileLightDef ~= nil and projectileLightDef.decayFunctionType ~= nil) then
projectileLightDefs[weaponDef.id].ambientDecayRate = vector_scalar_div(projectileLightDef.ambientColor or {0.0, 0.0, 0.0}, projectileLightDef.ttl or 1.0)
projectileLightDefs[weaponDef.id].diffuseDecayRate = vector_scalar_div(projectileLightDef.diffuseColor or {0.0, 0.0, 0.0}, projectileLightDef.ttl or 1.0)
projectileLightDefs[weaponDef.id].specularDecayRate = vector_scalar_div(projectileLightDef.specularColor or {0.0, 0.0, 0.0}, projectileLightDef.ttl or 1.0)
end
if (explosionLightDef ~= nil and explosionLightDef.decayFunctionType ~= nil) then
explosionLightDefs[weaponDef.id].ambientDecayRate = vector_scalar_div(explosionLightDef.ambientColor or {0.0, 0.0, 0.0}, explosionLightDef.ttl or 1.0)
explosionLightDefs[weaponDef.id].diffuseDecayRate = vector_scalar_div(explosionLightDef.diffuseColor or {0.0, 0.0, 0.0}, explosionLightDef.ttl or 1.0)
explosionLightDefs[weaponDef.id].specularDecayRate = vector_scalar_div(explosionLightDef.specularColor or {0.0, 0.0, 0.0}, explosionLightDef.ttl or 1.0)
end
end
end
end
local function ProjectileCreated(projectileID, projectileOwnerID, projectileWeaponDefID)
local projectileLightDef = projectileLightDefs[projectileWeaponDefID]
if (projectileLightDef == nil) then
return
end
projectileLights[projectileID] = {
[1] = SpringAddMapLight(projectileLightDef),
[2] = SpringAddModelLight(projectileLightDef),
-- [3] = projectileOwnerID,
-- [4] = projectileWeaponDefID,
}
SpringSetMapLightTrackingState(projectileLights[projectileID][1], projectileID, true, false)
SpringSetModelLightTrackingState(projectileLights[projectileID][2], projectileID, true, false)
end
local function ProjectileDestroyed(projectileID)
if (projectileLights[projectileID] == nil) then
return
end
-- set the TTL to 0 upon the projectile's destruction
-- (since all projectile lights start with arbitrarily
-- large values, which ensures we don't have to update
-- ttls manually to keep our lights alive) so the light
-- gets marked for removal
local projectileLightPos = {SpringGetProjectilePosition(projectileID)} -- {ppx, ppy, ppz}
local projectileLightTbl = {position = projectileLightPos, ttl = 0}
-- NOTE: unnecessary (death-dependency system take care of it)
-- SpringSetMapLightTrackingState(projectileLights[projectileID][1], projectileID, false, false)
-- SpringSetModelLightTrackingState(projectileLights[projectileID][2], projectileID, false, false)
SpringUpdateMapLight(projectileLights[projectileID][1], projectileLightTbl)
SpringUpdateModelLight(projectileLights[projectileID][2], projectileLightTbl)
-- get rid of this light
projectileLights[projectileID] = nil
end
local function ProjectileExplosion(weaponDefID, posx, posy, posz)
local explosionLightDef = explosionLightDefs[weaponDefID]
if (explosionLightDef == nil) then
return
end
local explosionLightAlt = explosionLightDef.altitudeOffset or 0.0
local explosionLightPos = {posx, posy + explosionLightAlt, posz}
-- NOTE: explosions are non-tracking, so need to supply position
-- FIXME:? explosion "ID"'s would require bookkeeping in :Update
local explosionLightTbl = {position = explosionLightPos, }
local numExplosions = 1
explosionLights[numExplosions] = {
[1] = SpringAddMapLight(explosionLightDef),
[2] = SpringAddModelLight(explosionLightDef),
}
SpringUpdateMapLight(explosionLights[numExplosions][1], explosionLightTbl)
SpringUpdateModelLight(explosionLights[numExplosions][2], explosionLightTbl)
end
function gadget:GetInfo()
return {
name = "gfx_dynamic_lighting.lua",
desc = "dynamic lighting in the Spring RTS engine",
author = "Kloot",
date = "January 15, 2011",
license = "GPL v2",
enabled = true,
}
end
function gadget:Initialize()
local maxMapLights = Spring.GetConfigInt("MaxDynamicMapLights") or 0
local maxMdlLights = Spring.GetConfigInt("MaxDynamicModelLights") or 0
local enabled = tonumber(Spring.GetModOptions().mo_dynamic) or 1
if (maxMapLights <= 0 and maxMdlLights <= 0 or enabled == 0) then
Spring.Echo("[" .. (self:GetInfo()).name .. "] client has disabled dynamic lighting")
gadgetHandler:RemoveGadget(self)
return
end
unsyncedEventHandlers[PROJECTILE_GENERATED_EVENT_ID] = ProjectileCreated
unsyncedEventHandlers[PROJECTILE_DESTROYED_EVENT_ID] = ProjectileDestroyed
unsyncedEventHandlers[PROJECTILE_EXPLOSION_EVENT_ID] = ProjectileExplosion
-- fill the {projectile, explosion}LightDef tables
LoadLightDefs()
end
function gadget:RecvFromSynced(eventID, arg0, arg1, arg2, arg3)
local eventHandler = unsyncedEventHandlers[eventID]
if (eventHandler ~= nil) then
eventHandler(arg0, arg1, arg2, arg3)
end
end
end
|
-----------------------------------
-- Area: Cloister of Frost
-- Mob: Shiva Prime
-- Involved in Quest: Trial by Ice, Trial Size Trial by Ice
-----------------------------------
mixins = {require("scripts/mixins/job_special")}
-----------------------------------
function onMobSpawn(mob)
tpz.mix.jobSpecial.config(mob, {
specials =
{
{id = 884, hpp = math.random(30,55)}, -- uses Diamond Dust once while near 50% HPP.
},
})
end
function onMobFight(mob, target)
end
function onMobDeath(mob, player, isKiller)
end
|
superblt = false
for _, mod in pairs(BLT and BLT.Mods:Mods() or {}) do
if mod:GetName() == "SuperBLT" and mod:IsEnabled() then
superblt = true
break
end
end
if superblt == false then
if UpdateThisMod then
UpdateThisMod:Add({
mod_id = 'Real Weapon Names',
data = {
modworkshop_id = 19958,
dl_url = 'https://github.com/xDarkWolf/PD2-Real-Weapon-Names/blob/master/RWN.zip?raw=true',
info_url = 'https://raw.githubusercontent.com/xDarkWolf/PD2-Real-Weapon-Names/master/mod.txt'
}
})
end
end |
local combat = Combat()
combat:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_ENERGY)
function onCreateMagicWall(creature, tile)
local item = Game.createItem(Game.getWorldType() == WORLD_TYPE_NO_PVP and ITEM_MAGICWALL_SAFE or ITEM_MAGICWALL, 1, tile)
item:setAttribute(ITEM_ATTRIBUTE_DURATION, math.random(14000, 20000))
end
combat:setCallback(CALLBACK_PARAM_TARGETTILE, "onCreateMagicWall")
local spell = Spell("rune")
function spell.onCastSpell(creature, variant, isHotkey)
return combat:execute(creature, variant)
end
spell:name("Magic Wall Rune")
spell:group("attack")
spell:id(86)
spell:cooldown(2 * 1000)
spell:groupCooldown(2 * 1000)
spell:level(32)
spell:magicLevel(9)
spell:runeId(3180)
spell:charges(3)
spell:isBlocking(true, true)
spell:allowFarUse(true)
spell:register()
|
--- === plugins.finalcutpro.browser.csv ===
---
--- Save Browser to CSV
local require = require
--local log = require "hs.logger".new "index"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local tools = require "cp.tools"
local dialog = require "cp.dialog"
local playErrorSound = tools.playErrorSound
local plugin = {
id = "finalcutpro.browser.csv",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
["finalcutpro.menu.manager"] = "menuManager",
}
}
function plugin.init(deps)
local cmds = deps.fcpxCmds
local list = fcp.libraries.list
local saveBrowserContentsToCSV = function()
fcp:launch(5)
list:show()
if list:isShowing() then
local result = list.contents:toCSV()
if result then
local path = dialog.displayChooseFolder(i18n("selectAFolderToSaveCSV") .. ":")
if path then
tools.writeToFile(path .. "/Browser Contents.csv", result)
end
return
end
end
playErrorSound()
end
--------------------------------------------------------------------------------
-- Command:
--------------------------------------------------------------------------------
cmds:add("saveBrowserContentsToCSV")
:whenActivated(saveBrowserContentsToCSV)
:titled(i18n("saveBrowserContentsToCSV"))
--------------------------------------------------------------------------------
-- Menubar:
--------------------------------------------------------------------------------
local menu = deps.menuManager.browser
menu
:addItems(1001, function()
return {
{ title = i18n("saveBrowserContentsToCSV"),
fn = saveBrowserContentsToCSV,
},
}
end)
end
return plugin
|
local dependency2 = require("dependency2")
local otherfile = require("otherfile")
return {
f1 = function() return dependency2.f2() end,
otherFileFromDependency1 = otherfile.someFunc
} |
setBufferPosY(60480)
lookDown()
turnOnBorders()
turnOffBorders()
print(getBufferBB())
do
clearTrace()
local minx,miny,maxx,maxy = getBufferBB()
print(minx,miny,maxx,maxy)
print((miny+maxy)/2)
print((maxy-miny)/2 - maxy)
end
setBufferName("buffcmdtest.lua")
0
|
ITEM.name = "Pouch"
ITEM.desc = "A small ammo pouch"
ITEM.model = "models/weapons/w_eq_defuser.mdl"
ITEM.price = 10
ITEM.width = 1
ITEM.height = 1
ITEM.invWidth = 2
ITEM.invHeight = 2 |
--------------------------------------------------------------------------
-- This class generates a progress bar. To use do:
--
-- local pb = ProgressBar:new{stream = io.stdout, max = N, barWidth=100}
-- for i = 1, N do
-- pb:progress(i)
-- -- stuff you want to show progress on.
-- end
--
-- The design is to model a football field.
-- The total size is given to the ctor. There is a "+" for every 10%
-- in progress and "|" at 50 and 100%.
--
-- @classmod ProgressBar
require("strict")
------------------------------------------------------------------------
--
-- Copyright (C) 2008-2014 Robert McLay
--
-- 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 dbg = require("Dbg"):dbg()
local M = { barWidth = 50 }
local floor = math.floor
s_symbolT = {}
--------------------------------------------------------------------------
-- Ctor for class
-- @param self ProgressBar object
-- @param t input table
function M.new(self, t)
local tbl = t
local o = {}
setmetatable(o, self)
self.__index = self
o.max = t.max
o.barWidth = t.barWidth or o.barWidth
o.barWidth = math.min(o.barWidth, o.max)
o.stream = t.stream or io.stdout
o.unit = 100/o.barWidth
o.fence = o.unit
o.mark = 10
s_symbolT[10] = "+"
s_symbolT[20] = "+"
s_symbolT[30] = "+"
s_symbolT[40] = "+"
s_symbolT[50] = "|"
s_symbolT[60] = "+"
s_symbolT[70] = "+"
s_symbolT[80] = "+"
s_symbolT[90] = "+"
s_symbolT[100] = "|"
return o
end
--------------------------------------------------------------------------
-- Prints out progress
-- @param self ProgressBar object
-- @param i the index counter.
function M.progress(self,i)
local j = floor(i/self.max*100)
local k = floor((i+1)/self.max*100)
if (j >= self.fence) then
local symbol = "-"
--print (j, k, l)
if ((j <= self.mark and k > self.mark) or ((j == k) and j == self.mark)) then
symbol = s_symbolT[self.mark]
self.mark = self.mark+10
end
self.stream:write(symbol)
self.stream:flush()
self.fence = self.fence + self.unit
end
end
--------------------------------------------------------------------------
-- Reports finish of progress bar.
-- @param self ProgressBar object
function M.fini(self)
self.stream:write("\n")
end
return M
|
local uv = {}
uv.fs = require 'uv.fs'
uv.http = require 'uv.http'
uv.loop = require 'uv.loop'
uv.parallel = require 'uv.parallel'
uv.process = require 'uv.process'
uv.system = require 'uv.system'
uv.timer = require 'uv.timer'
uv.url = require 'uv.url'
return uv
|
-- See LICENSE for terms
-- wtf? fix for this error:
-- Error loading file PackedMods/*****/Code/Script.lua: PackedMods/*****/Code/Script.lua:1: syntax error near '<\1>'
-- make it do nothing instead of breaking something
SupplyGridFragment.RandomElementBreakageOnWorkshiftChange = empty_func
|
--[[----------------------------------------------------------------------------
This file is part of Friday Night Funkin' Rewritten by HTV04
------------------------------------------------------------------------------]]
audio = {
playSound = function(sound)
sound:stop()
sound:play()
end
}
graphics = {
fade = {1}, -- Have to make this a table for "Timer.tween"
isFading = false,
fadeOut = function(duration, func)
if graphics.fadeTimer then
Timer.cancel(graphics.fadeTimer)
end
graphics.isFading = true
graphics.fadeTimer = Timer.tween(
duration,
graphics.fade,
{0},
"linear",
function()
graphics.isFading = false
if func then func() end
end
)
end,
fadeIn = function(duration, func)
if graphics.fadeTimer then
Timer.cancel(graphics.fadeTimer)
end
graphics.isFading = true
graphics.fadeTimer = Timer.tween(
duration,
graphics.fade,
{1},
"linear",
function()
graphics.isFading = false
if func then func() end
end
)
end,
setColor = function(r, g, b, a)
local fade = graphics.fade[1]
love.graphics.setColor(fade * r, fade * g, fade * b, a)
end,
getColor = function()
local r, g, b, a
local fade = graphics.fade[1]
r, g, b, a = love.graphics.getColor()
return r / fade, g / fade, b / fade, a
end
}
input = baton.new {
controls = {
left = {"key:left", "axis:leftx-", "button:dpleft"},
down = {"key:down", "axis:lefty+", "button:dpdown"},
up = {"key:up", "axis:lefty-", "button:dpup"},
right = {"key:right", "axis:leftx+", "button:dpright"},
confirm = {"key:return", "button:a"},
back = {"key:escape", "button:b"},
gameLeft = {"key:a", "key:left", "axis:triggerleft+", "axis:leftx-", "axis:rightx-", "button:dpleft", "button:x"},
gameDown = {"key:s", "key:down", "axis:lefty+", "axis:righty+", "button:leftshoulder", "button:dpdown", "button:a"},
gameUp = {"key:w", "key:up", "axis:lefty-", "axis:righty-", "button:rightshoulder", "button:dpup", "button:y"},
gameRight = {"key:d", "key:right", "axis:triggerright+", "axis:leftx+", "axis:rightx+", "button:dpright", "button:b"},
gameBack = {"key:escape", "button:start"},
},
joystick = love.joystick.getJoysticks()[1]
}
|
local function generate_sources(null_ls)
local sources = {
null_ls.builtins.formatting.prettier,
null_ls.builtins.formatting.rustfmt,
null_ls.builtins.formatting.stylua,
}
if require("language.lsp.which").path_exists("markdownlint") then
table.insert(sources, null_ls.builtins.diagnostics.markdownlint)
end
return sources
end
local M = {}
function M.setup(_, on_attach)
local null_ls = require("null-ls")
null_ls.setup({
on_attach = on_attach,
sources = generate_sources(null_ls),
})
end
return M
|
local assets=
{
Asset("ANIM", "anim/nightmaresword.zip"),
Asset("ANIM", "anim/swap_nightmaresword.zip"),
}
local function onfinished(inst)
inst:Remove()
end
local function onequip(inst, owner)
owner.AnimState:OverrideSymbol("swap_object", "swap_nightmaresword", "swap_nightmaresword")
owner.AnimState:Show("ARM_carry")
owner.AnimState:Hide("ARM_normal")
end
local function onunequip(inst, owner)
owner.AnimState:Hide("ARM_carry")
owner.AnimState:Show("ARM_normal")
end
local function fn(Sim)
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
MakeInventoryPhysics(inst)
inst.AnimState:SetBank("nightmaresword")
inst.AnimState:SetBuild("nightmaresword")
inst.AnimState:PlayAnimation("idle")
inst.AnimState:SetMultColour(1, 1, 1, 0.6)
inst:AddTag("shadow")
inst:AddTag("sharp")
inst:AddComponent("weapon")
inst.components.weapon:SetDamage(TUNING.NIGHTSWORD_DAMAGE)
-------
inst:AddComponent("finiteuses")
inst.components.finiteuses:SetMaxUses(TUNING.NIGHTSWORD_USES)
inst.components.finiteuses:SetUses(TUNING.NIGHTSWORD_USES)
inst.components.finiteuses:SetOnFinished( onfinished )
inst:AddComponent("inspectable")
inst:AddComponent("inventoryitem")
inst:AddComponent("equippable")
inst.components.equippable:SetOnEquip( onequip )
inst.components.equippable:SetOnUnequip( onunequip )
inst.components.equippable.dapperness = TUNING.CRAZINESS_MED
return inst
end
return Prefab( "common/inventory/nightsword", fn, assets)
|
local mt = getmetatable("")
mt.__call = function()
return "works"
end
local str = "test"
assert.Equal("works", str())
mt.__call = nil |
--[[
MIT License
Copyright (c) 2019 nasso <nassomails ~ at ~ gmail {dot} com>
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 cwd = (...):match('(.*lovector).-$') .. "."
local PathBuilder = require(cwd .. "pathbuilder")
local common = require(cwd .. "svg.common")
local renderer = {}
function renderer:empty(svg, options)
local x = tonumber(common.get_attr(self, "x", "0"), 10)
local y = tonumber(common.get_attr(self, "y", "0"), 10)
local width = tonumber(common.get_attr(self, "width", "-1"), 10)
local height = tonumber(common.get_attr(self, "height", "-1"), 10)
local rx = tonumber(common.get_attr(self, "rx", "-1"), 10)
local ry = tonumber(common.get_attr(self, "ry", "-1"), 10)
-- the bad stuff
if width <= 0 or height <= 0 then
return ""
end
-- the rounded stuff
-- they tell us everything at https://www.w3.org/TR/SVG11/shapes.html#RectElementRXAttribute
-- for us, a "properly set" value is >= 0
if rx < 0 and ry < 0 then
rx = 0
ry = 0
elseif rx >= 0 and ry < 0 then
ry = rx
elseif rx < 0 and ry >= 0 then
rx = ry
end
if rx > width / 2 then
rx = width / 2
end
if ry > height / 2 then
ry = height / 2
end
local path = PathBuilder(options)
path:move_to(x + rx, y)
path:line_to(x + width - rx, y)
if rx ~= 0 and ry ~= 0 then
path:elliptical_arc_to(rx, ry, 0, false, true, x + width, y + ry)
end
path:line_to(x + width, y + height - ry)
if rx ~= 0 and ry ~= 0 then
path:elliptical_arc_to(rx, ry, 0, false, true, x + width - rx, y + height)
end
path:line_to(x + rx, y + height)
if rx ~= 0 and ry ~= 0 then
path:elliptical_arc_to(rx, ry, 0, false, true, x, y + height - ry)
end
path:line_to(x, y + ry)
if rx ~= 0 and ry ~= 0 then
path:elliptical_arc_to(rx, ry, 0, false, true, x + rx, y)
end
path:close_path()
svg.graphics:draw_path(path)
end
return renderer
|
--[[
Copyright 2021 Manticore Games, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--]]
--[[
This script raycasts uses box collisions of the vehicle to detect
obstacles and play damage effects.
--]]
-- Internal custom properties
Task.Wait(1)
local VEHICLE = script:FindAncestorByType('Vehicle')
if not Object.IsValid(VEHICLE) or not VEHICLE:IsA('Vehicle') then
--error(script.name .. " should be part of Vehicle object hierarchy.")
end
-- User exposed external properties
local COLLISION_BOXES = script:GetCustomProperty("CollisionBoxes"):WaitForObject()
local SPEED_DAMAGE_THRESHOLD = script:GetCustomProperty("SpeedDamageThreshold")
local DAMAGE_EFFECT_TEMPLATE = script:GetCustomProperty("DamageEffectTemplate")
local MAX_RENDER_DISTANCE = script:GetCustomProperty("MaxRenderDistance")
local DEBUG = script:GetCustomProperty("Debug")
-- Constant variables
local LOCAL_PLAYER = Game.GetLocalPlayer()
local DAMAGE_COOLDOWN = 1
-- Internal variables
local currentPosition = Vector3.New()
local lastSpeed = 0
local boxDamageTimes = {}
local lastDamageTime = time()
function Tick(deltaTime)
if not Object.IsValid(VEHICLE) then return end
if not VEHICLE.driver then return end
if LOCAL_PLAYER ~= VEHICLE.driver then
if (LOCAL_PLAYER:GetWorldPosition() - VEHICLE:GetWorldPosition()).size > MAX_RENDER_DISTANCE then
return
end
end
-- Wait for a while before car can do more damage effect
if time() - lastDamageTime < DAMAGE_COOLDOWN then return end
local speed = VEHICLE:GetVelocity().size
-- Only consider showing damage effect
-- if the vehicle moved past the speed threshold
if lastSpeed - speed > SPEED_DAMAGE_THRESHOLD then
CheckDamage(COLLISION_BOXES)
end
if DEBUG then
DebugRays(COLLISION_BOXES)
end
lastSpeed = speed
-- Check for damage impact every frame
Task.Wait(deltaTime)
end
function CheckDamage()
for _, box in ipairs(COLLISION_BOXES:GetChildren()) do
local ray1Start, ray1End, ray2Start, ray2End = GetBoxPoints(box)
local result1 = World.Raycast(ray1Start, ray1End, {ignorePlayers = true})
local result2 = World.Raycast(ray2Start, ray2End, {ignorePlayers = true})
if result1 and result2 and result1.other ~= VEHICLE and result2.other ~= VEHICLE then
SpawnDamageEffect(box:GetWorldPosition())
break
elseif result1 and result1.other ~= VEHICLE then
SpawnDamageEffect(result1:GetImpactPosition())
break
elseif result2 and result2.other ~= VEHICLE then
SpawnDamageEffect(result2:GetImpactPosition())
break
end
end
end
function DebugRays()
for _, box in ipairs(COLLISION_BOXES:GetChildren()) do
local ray1Start, ray1End, ray2Start, ray2End = GetBoxPoints(box)
CoreDebug.DrawLine(ray1Start, ray1End, {thickness = 5})
CoreDebug.DrawLine(ray2Start, ray2End, {thickness = 5})
end
end
function GetBoxPoints(box)
local bottomLeftBack, upRightFront, bottomRightBack, upLeftFront
local pos = box:GetWorldPosition()
local transform = box:GetWorldTransform()
local scale = box:GetScale() * 50
local fwdVect = transform:GetForwardVector()
local rVect = transform:GetRightVector()
local uVect =transform:GetUpVector()
bottomLeftBack = pos - fwdVect * scale.x - rVect * scale.y - uVect * scale.z
bottomRightBack = pos - fwdVect * scale.x + rVect * scale.y - uVect * scale.z
upRightFront = pos + fwdVect * scale.x + rVect * scale.y + uVect * scale.z
upLeftFront = pos + fwdVect * scale.x - rVect * scale.y + uVect * scale.z
return bottomLeftBack, upRightFront, bottomRightBack, upLeftFront
end
function SpawnDamageEffect(spawnPos)
if DAMAGE_EFFECT_TEMPLATE then
World.SpawnAsset(DAMAGE_EFFECT_TEMPLATE, {position = spawnPos})
end
lastDamageTime = time()
end
for _, child in ipairs(COLLISION_BOXES:GetChildren()) do
child.visibility = Visibility.FORCE_OFF
end |
local usd = {}
usd.vector3 = function(source)
local x, y, z = source:match("^%(([-%d.]+),([-%d.]+),([-%d.]+)%)$")
return Vector3.new(tonumber(x), tonumber(y), tonumber(z))
end
usd.color3 = function(source)
local x, y, z = source:match("^%(([%d.]+),([%d.]+),([%d.]+)%)$")
return Color3.new(tonumber(x), tonumber(y), tonumber(z))
end
usd.brickcolor = function(source)
return BrickColor.new(source)
end
return usd |
-- ホムンクルスタイプ取得
-- ホム選択時の単純な判定用で、細かい判定はHomunculus内へ
function GetHomunculusType(id)
return GetV(V_HOMUNTYPE, id)
end
-- typeやその他の条件を加味して、適切なAIを選択
function CreateHomunculus(id)
local type = GetHomunculusType(id)
local homu = Homunculus
-- ここにホム選択ロジック
if type == FILIR or type == FILIR2 or type == FILIR_H or type == FILIR_H2 then
require(AI_BASE_PATH..'Filir.lua')
homu = Filir -- フィーリルを選択
end
-- newして返す
return homu.new(id)
end
-- main AI()
MyHomu = nil
function AI(myid)
-- ホム初期化
if MyHomu == nil then
MyHomu = CreateHomunculus(myid)
end
-- 処理実行
MyHomu:action()
end
|
CompMod:ChangeAlienTechmapTech(kTechId.Spores, 8, 10)
CompMod:ChangeResearch(kTechId.Spores, kTechId.BioMassSix, kTechId.None, kTechId.AllAliens) |
v1 = vessel.get_interface('srb1')
v2 = vessel.get_interface('srb2')
note = oapi.create_annotation()
note:set_pos (0.3,0.05,0.9,0.95)
note:set_colour ({r=1,g=0.6,b=0.2})
note2 = oapi.create_annotation()
note2:set_pos (0.3,0.8,0.9,1)
note2:set_colour ({r=1,g=0.7,b=0.3})
intro = 'Space physics: Spin stabilisation'
note:set_text (intro)
proc.wait_sysdt(5)
intro = intro..'\n\
The attitude of an object can be stabilised by spinning\
it rapidly around one of its axes of symmetry. In this\
scenario, two rockets are placed in a low orbit. One is\
spinning around its longitudinal axis at 1Hz, the other\
is not.'
note:set_text (intro)
proc.wait_sysdt(10)
intro = intro..'\n\
The spinning rocket maintains its global orientation,\
while the other starts to rotate under the influence of\
gravity gradient torque.'
note:set_text (intro)
proc.wait_sysdt(10);
note:set_text ('Speeding up the simulation time ...')
oapi.set_tacc(100)
proc.wait_simtime(700)
note:set_text ('Note how the rocket in front starts to rotate\
under the influence of the gravity gradient, while the\
spinning rocket behind maintains its attitude with\
respect to the global (non-rotating) frame of reference.')
proc.wait_simtime(2000)
note2:set_text ('(Dipping into Earth\'s shadow ...)')
proc.wait_simtime(4200)
note2:set_text ('')
proc.wait_simtime(4500)
note:set_text ('I am now going to stop the spinning rocket.\
Watch how it also slowly starts to rotate in the inhomogeneous\
gravity field.')
v1:set_angvel({x=0,y=0,z=0})
proc.wait_simtime(5500)
note:set_text ('Now I am spinning up the other rocket.\
As a result, it will maintain the orientation of its\
longitudinal axis.')
v2:set_angvel({x=0,y=0,z=360*RAD})
proc.wait_sysdt(200)
oapi.del_annotation (note) |
-- Tests for moving the hero
nh.parse_config("OPTIONS=number_pad:0");
nh.parse_config("OPTIONS=runmode:teleport");
local POS = { x = 10, y = 05 };
local number_pad = 0;
function initlev()
nh.debug_flags({mongen = false, hunger = false, overwrite_stairs = true });
des.level_flags("noflip");
des.reset_level();
des.level_init({ style = "solidfill", fg = ".", lit = true });
des.teleport_region({ region = {POS.x,POS.y,POS.x,POS.y}, region_islev = true, dir="both" });
des.finalize_level();
for k, v in pairs(nh.stairways()) do
des.terrain(v.x - 1, v.y, ".");
end
end
function ctrl(key)
return string.char(0x1F & string.byte(key));
end
function meta(key)
return string.char(0x80 | string.byte(key));
end
function setup1(param)
des.terrain(POS.x - 2, POS.y, param);
end
function setup2(param)
des.terrain(POS.x + 15, POS.y, param);
end
local basicmoves = {
-- move
h = { dx = -1, dy = 0, number_pad = 0 },
j = { dx = 0, dy = 1, number_pad = 0 },
k = { dx = 0, dy = -1, number_pad = 0 },
l = { dx = 1, dy = 0, number_pad = 0 },
y = { dx = -1, dy = -1, number_pad = 0 },
u = { dx = 1, dy = -1, number_pad = 0 },
b = { dx = -1, dy = 1, number_pad = 0 },
n = { dx = 1, dy = 1, number_pad = 0 },
-- run
H = { x = 2, y = POS.y, number_pad = 0 },
J = { x = POS.x, y = nhc.ROWNO-1, number_pad = 0 },
K = { x = POS.x, y = 0, number_pad = 0 },
L = { x = nhc.COLNO-2, y = POS.y, number_pad = 0 },
Y = { x = POS.x - POS.y, y = 0, number_pad = 0 },
U = { x = POS.x + POS.y, y = 0, number_pad = 0 },
B = { x = 2, y = 13, number_pad = 0 },
N = { x = 25, y = nhc.ROWNO-1, number_pad = 0 },
-- rush
[ctrl("h")] = { x = 2, y = POS.y, number_pad = 0 },
[ctrl("j")] = { x = POS.x, y = nhc.ROWNO-1, number_pad = 0 },
[ctrl("k")] = { x = POS.x, y = 0, number_pad = 0 },
[ctrl("l")] = { x = nhc.COLNO-2, y = POS.y, number_pad = 0 },
[ctrl("y")] = { x = POS.x - POS.y, y = 0, number_pad = 0 },
[ctrl("u")] = { x = POS.x + POS.y, y = 0, number_pad = 0 },
[ctrl("b")] = { x = 2, y = 13, number_pad = 0 },
[ctrl("n")] = { x = 25, y = nhc.ROWNO-1, number_pad = 0 },
-- move, number_pad
["4"] = { dx = -1, dy = 0, number_pad = 1 },
["2"] = { dx = 0, dy = 1, number_pad = 1 },
["8"] = { dx = 0, dy = -1, number_pad = 1 },
["6"] = { dx = 1, dy = 0, number_pad = 1 },
["7"] = { dx = -1, dy = -1, number_pad = 1 },
["9"] = { dx = 1, dy = -1, number_pad = 1 },
["1"] = { dx = -1, dy = 1, number_pad = 1 },
["3"] = { dx = 1, dy = 1, number_pad = 1 },
-- run (or rush), number_pad
[meta("4")] = { x = 2, y = POS.y, number_pad = 1 },
[meta("2")] = { x = POS.x, y = nhc.ROWNO-1, number_pad = 1 },
[meta("8")] = { x = POS.x, y = 0, number_pad = 1 },
[meta("6")] = { x = nhc.COLNO-2, y = POS.y, number_pad = 1 },
[meta("7")] = { x = POS.x - POS.y, y = 0, number_pad = 1 },
[meta("9")] = { x = POS.x + POS.y, y = 0, number_pad = 1 },
[meta("1")] = { x = 2, y = 13, number_pad = 1 },
[meta("3")] = { x = 25, y = nhc.ROWNO-1, number_pad = 1 },
-- check some terrains
{ key = "h", dx = 0, dy = 0, number_pad = 0, setup = setup1, param = " " },
{ key = "h", dx = 0, dy = 0, number_pad = 0, setup = setup1, param = "|" },
{ key = "h", dx = 0, dy = 0, number_pad = 0, setup = setup1, param = "-" },
{ key = "h", dx = 0, dy = 0, number_pad = 0, setup = setup1, param = "F" },
{ key = "h", dx = -1, dy = 0, number_pad = 0, setup = setup1, param = "#" },
{ key = "h", dx = -1, dy = 0, number_pad = 0, setup = setup1, param = "." },
-- run and terrains
{ key = "L", x = POS.x + 15, y = POS.y, number_pad = 0, setup = setup2, param = " " },
{ key = "L", x = POS.x + 15, y = POS.y, number_pad = 0, setup = setup2, param = "|" },
{ key = "L", x = POS.x + 15, y = POS.y, number_pad = 0, setup = setup2, param = "-" },
{ key = "L", x = POS.x + 15, y = POS.y, number_pad = 0, setup = setup2, param = "F" },
{ key = "L", x = POS.x + 15, y = POS.y, number_pad = 0, setup = setup2, param = "L" },
{ key = "L", x = nhc.COLNO - 2, y = POS.y, number_pad = 0, setup = setup2, param = "#" },
{ key = "L", x = nhc.COLNO - 2, y = POS.y, number_pad = 0, setup = setup2, param = "C" },
};
for k, v in pairs(basicmoves) do
initlev();
local key = v.key and v.key or k;
if (v.number_pad ~= nil) then
if (v.number_pad ~= number_pad) then
nh.parse_config("OPTIONS=number_pad:" .. v.number_pad);
number_pad = v.number_pad;
end
end
if (v.setup ~= nil) then
v.setup(v.param);
end
local x = u.ux;
local y = u.uy;
nh.pushkey(key);
nh.doturn(true);
if (v.dx ~= nil) then
if (not ((x == (u.ux - v.dx)) and (y == (u.uy - v.dy)))) then
error(string.format("Move: key '%s' gave (%i,%i), should have been (%i,%i)",
key, u.ux, u.uy, u.ux - v.dx, u.uy - v.dy));
return;
end
elseif (v.x ~= nil) then
if (not (u.ux == v.x and u.uy == v.y)) then
error(string.format("Move: key '%s' gave (%i,%i), should have been (%i,%i)",
key, u.ux, u.uy, v.x, v.y));
return;
end
end
end
initlev();
|
--//////////////////////////////////////////////////////////////////////
--************************
--PlayerTurnEvent
--************************
PlayerTurnEvent = {}
PlayerTurnEvent.__index = PlayerTurnEvent
setmetatable(PlayerTurnEvent, {__index = Event})
function PlayerTurnEvent.new(turnPlayer)
local self = setmetatable(Event.new(), PlayerTurnEvent)
self.name = 'PlayerTurnEvent'
self.done = false
self.turnPlayer = turnPlayer
return self
end
function PlayerTurnEvent:update(input, dt)
print('event - PlayerTurnEvent')
battle.currentBattle:onPlayerTurn(self.turnPlayer)
self.done = true;
end
return PlayerTurnEvent
|
Lottery = {}
Lottery.__index = Lottery
function Lottery.new()
local self = {}
setmetatable(self, Lottery)
-- list of entries in the lottery. Elements are of the form
self._entries = {}
-- total number of lots in the pool
-- Lots can come in decimals as well, like 0.02
self._lotsTotal = 0
return self
end
-- Adds a new entry to the lottery,
-- i.e. a participant with a given number of lots
function Lottery:addEntry(participant, lots)
lots = lots or 1
table.insert(self._entries, {
participant = participant,
lots = lots
})
self._lotsTotal = self._lotsTotal + lots
end
-- Determines the winner of the lottery based on the number of lots that
-- each participant has. Lots and their owners are all lined up, then
-- the RNG determines the position of the winning lot.
function Lottery:getWinner()
if(self._lotsTotal == 0) then return(false) end
-- * 1,000,000, to make sure that lots in decimal form are handled correctly
local rand = math.random(0, self._lotsTotal * 1000000)
local currentLot = 0
for _, entry in pairs(self._entries) do
currentLot = currentLot + entry.lots * 1000000
if(currentLot >= rand) then
return entry.participant
end
end
return false -- should never happen
end
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
local attachChance = 0.3
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:SetCollisionGroup( COLLISION_GROUP_DEBRIS )
self.DoneSim = false
self:DrawShadow( false )
end
function ENT:PhysicsCollide( data, physobj )
if self.DoneSim then return end
if data.HitEntity.GibMod_IsHeadCrab then return end
-- sound
local rand = math.random(1,5)
local sound = "physics/flesh/flesh_squishy_impact_hard1.wav"
if rand >= 1 and rand <= 4 then
sound = "physics/flesh/flesh_squishy_impact_hard"..math.random(1,4)..".wav"
elseif rand == 5 then
sound = "physics/flesh/flesh_bloody_break.wav"
end
self:EmitSound( sound, 100, math.Clamp( math.Clamp( (self:BoundingRadius() * 10), 1, 5000 ) * -1 + 255 + math.random(-5, 5), 50, 255 ) )
-- blood spurt
local effectdata = EffectData()
effectdata:SetOrigin( self:GetPos() )
util.Effect( "BloodImpact", effectdata )
-- decal
local tr = util.TraceLine{ start = self:GetPos(),
endpos = physobj:GetPos() + self:GetPhysicsObject():GetVelocity(),
filter = self.Entity }
util.Decal( "Blood", tr.HitPos + tr.HitNormal, tr.HitPos - tr.HitNormal )
-- weld and sag
if not data.HitEntity:IsPlayer() then
if math.random() > attachChance and not self.IsOrigin then return end
timer.Simple( 0, function() constraint.Weld( self.Entity, data.HitEntity, 0, 0, 0, false, false ) end )
self.DoneSim = true
if self.rope and self.rope:IsValid() then
local originPos = self.originEnt:GetPos()
local height = math.abs(data.HitPos.z - originPos.z)
local dist = originPos:Distance( data.HitPos )
local slack = math.sqrt( (dist ^ 2) - (height ^ 2) )
local newLen = dist + slack
--constraint.RemoveConstraints( self.Entity, "Rope" )
--timer.Simple( 0, function() constraint.Rope( self.Entity, self.originEnt, 0, 0, Vector(0, 0, 0), Vector(0, 0, 0), dist, slack, 1000, 15, "gibmod/bloodstream", false ) end )
self.rope:Fire( "SetSpringLength", newLen, 0 )
self.rope:Fire( "SetLength", newLen, 0 )
end
end
end
function ENT:Think()
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.