repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278 values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15 values |
|---|---|---|---|---|---|
NPLPackages/paracraft | script/kids/3DMapSystemApp/worlds/RegionMonitor.lua | 1 | 2817 | --[[
Title: RegionMonitor
Author(s): Leio
Date: 2009/9/26
Desc:
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemApp/worlds/RegionMonitor.lua");
local regionMonitor = Map3DSystem.App.worlds.RegionMonitor:new();
--regionMonitor:AddEventListener("moveable",function(args)
--commonlib.echo(args);
--end);
--regionMonitor:AddEventListener("sound",function(args)
--commonlib.echo(args);
--end);
regionMonitor:AddEventListener("custom",function(args)
commonlib.echo(args);
end);
------------------------------------------------------------
]]
NPL.load("(gl)script/ide/timer.lua");
local RegionMonitor = commonlib.gettable("Map3DSystem.App.worlds.RegionMonitor");
RegionMonitor.duration = 500;
function RegionMonitor:new(o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self;
o:Init();
return o
end
function RegionMonitor:Pause()
if(self.timer)then
self.timer:Change();
end
end
function RegionMonitor:Resume()
if(self.timer)then
self.timer:Change(0,self.duration);
end
end
function RegionMonitor:Init()
self.events = {};
self.timer = commonlib.Timer:new{callbackFunc = Map3DSystem.App.worlds.RegionMonitor.Timer_CallBackFunc,};
self.timer.monitor = self;
self:Resume();
end
function RegionMonitor.Timer_CallBackFunc(t)
if(t and t.monitor)then
local self = t.monitor;
local x, _, y = ParaScene.GetPlayer():GetPosition();
self:Update(x,y);
end
end
function RegionMonitor:AddEventListener(event_type,func)
self.events[event_type] = {func = func,};
end
function RegionMonitor:DispatchEvent(event_type,args)
local func_table = self.events[event_type];
if(func_table)then
local func = func_table.func;
if(func and type(func) == "function")then
func(args);
end
end
end
function RegionMonitor:Update(x,y)
local event_type,func_table;
for event_type,func_table in pairs(self.events) do
local filter = func_table.filter or self.COLOR_DEFAULT;
--×Ô¶¨Òå±êÇ©
local argb = ParaTerrain.GetRegionValue(event_type, x, y);
local r,g,b,a = _guihelper.DWORD_TO_RGBA(argb);
local att = ParaTerrain.GetAttributeObjectAt(x,y);
local NumOfRegions;
local CurrentRegionName;
local CurrentRegionFilepath;
if(att)then
att:SetField("CurrentRegionName", event_type or "move");
NumOfRegions = att:GetField("NumOfRegions", 0);
CurrentRegionName = att:GetField("CurrentRegionName", "");
CurrentRegionFilepath = att:GetField("CurrentRegionFilepath", "");
end
local args = {event_type = event_type,
argb = argb,
r = r,
g = g,
b = b,
a = a,
NumOfRegions = NumOfRegions,
CurrentRegionName = CurrentRegionName,
CurrentRegionFilepath = CurrentRegionFilepath,
};
self:DispatchEvent(event_type,args)
end
end
| gpl-2.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/metropolis_torso_rifle_walk_4.meta.lua | 2 | 2804 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 0.43000000715255737,
amplification = 140,
light_colors = {
"89 31 168 255",
"48 42 88 255",
"61 16 123 0"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
chamber = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
chamber_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {},
original_poly = {}
},
torso = {
back = {
pos = {
x = -12,
y = -13
},
rotation = 37
},
head = {
pos = {
x = -1,
y = 0
},
rotation = 2
},
legs = {
pos = {
x = -2,
y = 2
},
rotation = 0
},
primary_hand = {
pos = {
x = 6,
y = 16
},
rotation = -4.3160276412963867
},
secondary_hand = {
pos = {
x = 3,
y = 15
},
rotation = -38
},
secondary_shoulder = {
pos = {
x = -9,
y = 17
},
rotation = -141
},
shoulder = {
pos = {
x = 14,
y = -15
},
rotation = -140
},
strafe_facing_offset = 0
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/console_light_2.meta.lua | 6 | 2024 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"95 205 228 255",
"0 211 255 255",
"0 255 255 255",
"0 255 255 255",
"0 255 255 255",
"92 172 172 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
StarChasers/LuPI2 | src/lua/core/internet.lua | 1 | 4352 | local internet = {}
function internet.start()
local component = {}
--Legacy
function component.isHttpEnabled()
return true
end
function component.isTcpEnabled()
return true
end
--Old TCP
function component.connect(address, port)
checkArg(1, address, "string")
checkArg(2, port, "number", "nil")
if not port then
address, port = address:match("(.+):(.+)")
port = tonumber(port)
end
local sfd, reason = net.open(address, port)
local closed = false
return {
finishConnect = function()
if not sfd then
error(reason)
end
return true
end,
read = function(n)
if closed then return nil, "connection lost" end
n = n or 65535
checkArg(1, n, "number")
local data = net.read(sfd, n)
if not data then
closed = true
native.fs_close(sfd)
return nil, "connection lost"
end
return data
end,
write = function(data)
if closed then return nil, "connection lost" end
checkArg(1, data, "string")
local written = net.write(sfd, data)
if not written then
closed = true
native.fs_close(sfd)
return nil, "connection lost"
end
return written
end,
close = function()
closed = true
native.fs_close(sfd)
end
}
end
function component.request(url, post)
checkArg(1, url, "string")
checkArg(2, post, "string", "nil")
local host, uri = url:match("https?://([^/]+)([^#]+)")
if not host then native.log("internet.request host match error: " .. url .. "\n") end
local socket = component.connect(host, 80)
if socket.finishConnect() then
local request
if not post then
request = "GET " .. uri .. " HTTP/1.1\r\nHost: " .. host .. "\r\nConnection: close\r\n\r\n"
else
request = "POST " .. uri .. " HTTP/1.1\r\nHost: " .. host .. "\r\nConnection: close\r\n"
.. "Content-Type: application/x-www-form-urlencoded\r\nUser-Agent: LuPI/1.0\r\n"
.. "Content-Length: " .. math.floor(#post) .. "\r\n\r\n"
.. post .. "\r\n\r\n"
end
socket.write(request)
if native.debug then
native.log("internet.request:\n-- request begin --\n" .. request .. "\n-- request end --")
end
end
local stream = {}
function stream:seek()
return nil, "bad file descriptor"
end
function stream:write()
return nil, "bad file descriptor"
end
function stream:read(n)
if not socket then
return nil, "connection is closed"
end
return socket.read(n)
end
function stream:close()
if socket then
socket.close()
socket = nil
end
end
local connection = modules.buffer.new("rb", stream)
connection.readTimeout = 10
local header = nil
--TODO: GC close
--TODO: Chunked support
local finishConnect = function() --Read header
header = {}
header.status = connection:read("*l"):match("HTTP/.%.. (%d+) (.+)\r")
if native.debug then
native.log("internet.request:\n-- response begin --\n" .. header.status .. "\n")
end
while true do
local line = connection:read("*l")
if not line or line == "" or line == "\r" then
break
end
local k, v = line:match("([^:]+): (.+)\r")
header[k:lower()] = v
if native.debug then
native.log(line)
end
end
if native.debug then
native.log("-- response end --")
end
header["content-length"] = tonumber(header["content-length"])
end
return {
finishConnect = finishConnect,
read = function(n)
if not header then
finishConnect()
end
if not header["content-length"] or header["content-length"] < 1 then
return nil
end
checkArg(1, n, "number", "nil")
n = n or math.min(8192, header["content-length"])
local res = connection:read(n)
header["content-length"] = header["content-length"] - #res
return res
end,
close = function()
connection:close()
end
}
end
modules.component.api.register(nil, "internet", component)
end
return internet
| mit |
pakoito/ToME---t-engine4 | game/engines/default/engine/interface/ActorFOV.lua | 3 | 7761 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
local Map = require "engine.Map"
--- Handles actors field of view
-- When an actor moves it computes a field of view and stores it in self.fov<br/>
-- When an other actor moves it can update the fov of seen actors
module(..., package.seeall, class.make)
_M.__do_distance_map = false
--- Initialises stats with default values if needed
function _M:init(t)
self.distance_map = {}
self.fov = {actors={}, actors_dist={}}
self.fov_computed = false
self.fov_last_x = -1
self.fov_last_y = -1
self.fov_last_turn = -1
self.fov_last_change = -1
end
--- Computes actor's FOV
-- @param radius the FOV radius, defaults to 20
-- @param block the property to look for FOV blocking, defaults to "block_sight"
-- @param apply an apply function that will be called on each seen grids, defaults to nil
-- @param force set to true to force a regeneration even if we did not move
-- @param no_store do not store FOV informations
-- @param cache if true it will use the cache given by the map, for the map actor. It can be used for other actors is they have the same block settings
function _M:computeFOV(radius, block, apply, force, no_store, cache)
-- If we did not move, do not update
if not self.x or not self.y or (not force and self.fov_last_x == self.x and self.fov_last_y == self.y and self.fov_computed) then return end
radius = radius or 20
block = block or "block_sight"
-- Simple FOV compute no storage
if no_store and apply then
local map = game.level.map
core.fov.calc_circle(self.x, self.y, map.w, map.h, radius, function(_, x, y)
if map:checkAllEntities(x, y, block, self) then return true end
end, function(_, x, y, dx, dy, sqdist)
apply(x, y, dx, dy, sqdist)
end, cache and game.level.map._fovcache[block])
-- FOV + storage + fast C code
elseif not no_store and cache and game.level.map._fovcache[block] then
local fov = {actors={}, actors_dist={}}
setmetatable(fov.actors, {__mode='k'})
setmetatable(fov.actors_dist, {__mode='v'})
-- Use the fast C code
local map = game.level.map
core.fov.calc_default_fov(
self.x, self.y,
radius,
block,
game.level.map._fovcache[block],
fov.actors, fov.actors_dist,
map.map, map.w, map.h,
Map.ACTOR,
self.distance_map,
game.turn,
self,
apply
)
table.sort(fov.actors_dist, "__sqdist")
-- print("Computed FOV for", self.uid, self.name, ":: seen ", #fov.actors_dist, "actors closeby")
self.fov = fov
self.fov_last_x = self.x
self.fov_last_y = self.y
self.fov_last_turn = game.turn
self.fov_last_change = game.turn
self.fov_computed = true
elseif not no_store then
local fov = {actors={}, actors_dist={}}
setmetatable(fov.actors, {__mode='k'})
setmetatable(fov.actors_dist, {__mode='v'})
local map = game.level.map
core.fov.calc_circle(self.x, self.y, map.w, map.h, radius, function(_, x, y)
if map:checkAllEntities(x, y, block, self) then return true end
end, function(_, x, y, dx, dy, sqdist)
if apply then apply(x, y, dx, dy, sqdist) end
if self.__do_distance_map then self.distance_map[x + y * game.level.map.w] = game.turn + radius - math.sqrt(sqdist) end
-- Note actors
local a = map(x, y, Map.ACTOR)
if a and a ~= self and not a.dead then
local t = {x=x,y=y, dx=dx, dy=dy, sqdist=sqdist}
fov.actors[a] = t
fov.actors_dist[#fov.actors_dist+1] = a
a.__sqdist = sqdist
a:check("seen_by", self)
a:updateFOV(self, t.sqdist)
end
end, cache and game.level.map._fovcache[block])
-- Sort actors by distance (squared but we do not care)
table.sort(fov.actors_dist, "__sqdist")
-- print("Computed FOV for", self.uid, self.name, ":: seen ", #fov.actors_dist, "actors closeby")
self.fov = fov
self.fov_last_x = self.x
self.fov_last_y = self.y
self.fov_last_turn = game.turn
self.fov_last_change = game.turn
self.fov_computed = true
end
end
--- Computes actor's FOV as a beam
-- @param radius the FOV radius, defaults to 20
-- @param dir the FOV beam direction (1,2,3,4,6,7,8,9)
-- @param angle the FOV beam spread
-- @param block the property to look for FOV blocking, defaults to "block_sight"
-- @param apply an apply function that will be called on each seen grids, defaults to nil
-- @param force set to true to force a regeneration even if we did not move
-- @param no_store do not store FOV informations
-- @param cache if true it will use the cache given by the map, for the map actor. It can be used for other actors is they have the same block settings
function _M:computeFOVBeam(radius, dir, angle, block, apply, force, no_store, cache)
-- If we did not move, do not update
if not force and self.fov_last_x == self.x and self.fov_last_y == self.y and self.fov_computed then return end
radius = radius or 20
dir = dir or 8
angle = angle or 45
block = block or "block_sight"
-- Simple FOV compute no storage
if no_store and apply then
local map = game.level.map
core.fov.calc_beam(self.x, self.y, map.w, map.h, radius, dir, angle, function(_, x, y)
if map:checkAllEntities(x, y, block, self) then return true end
end, function(_, x, y, dx, dy, sqdist)
apply(x, y, dx, dy, sqdist)
end, cache and game.level.map._fovcache[block])
elseif not no_store then
local fov = {actors={}, actors_dist={}}
setmetatable(fov.actors, {__mode='k'})
setmetatable(fov.actors_dist, {__mode='v'})
local map = game.level.map
core.fov.calc_beam(self.x, self.y, map.w, map.h, radius, dir, angle, function(_, x, y)
if map:checkAllEntities(x, y, block, self) then return true end
end, function(_, x, y, dx, dy, sqdist)
if apply then apply(x, y, dx, dy, sqdist) end
if self.__do_distance_map then self.distance_map[x + y * game.level.map.w] = game.turn + radius - math.sqrt(sqdist) end
-- Note actors
local a = map(x, y, Map.ACTOR)
if a and a ~= self and not a.dead then
local t = {x=x,y=y, dx=dx, dy=dy, sqdist=sqdist}
fov.actors[a] = t
fov.actors_dist[#fov.actors_dist+1] = a
a.__sqdist = sqdist
a:check("seen_by", self)
a:updateFOV(self, t.sqdist)
end
end, cache and game.level.map._fovcache[block])
-- Sort actors by distance (squared but we do not care)
table.sort(fov.actors_dist, "__sqdist")
-- print("Computed FOV for", self.uid, self.name, ":: seen ", #fov.actors_dist, "actors closeby")
self.fov = fov
self.fov_last_x = self.x
self.fov_last_y = self.y
self.fov_last_turn = game.turn
self.fov_last_change = game.turn
self.fov_computed = true
end
end
--- Update our fov to include the given actor at the given dist
-- @param a the actor to include
-- @param sqdist the squared distance to that actor
function _M:updateFOV(a, sqdist)
-- If we are from this turn no need to update
if self.fov_last_turn == game.turn then return end
-- Force regen
self.fov_last_x = -1
self.fov_last_y = -1
end
function _M:distanceMap(x, y, v)
if v == nil then
return self.distance_map[x + y * game.level.map.w]
else
self.distance_map[x + y * game.level.map.w] = v
end
end
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Port_Jeuno/npcs/Kochahy-Muwachahy.lua | 1 | 4372 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Kochahy-Muwachahy
-- @zone 246
-- @pos 40 0 6
-- X Grant Signet
-- Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-------------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
package.loaded["scripts/globals/conquestguards"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/zones/Port_Jeuno/TextIDs");
require("scripts/globals/conquestguards");
PlayerCP = 56000; -- Player Conquest Points
CanEquip = 2; -- 1 = Player can equip, 2 = Player can't equip
DONATE_LOW_RANK = 7905;
DONATE_AT_MAXIM = 7955;
DONATE_OVERFLOW = 7956;
DONATE_CRYSTALS = 7957;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
TradeCount = trade:getItemCount();
for Crystal = 1,table.getn(DonateCrys),1 do
TradeCrys = trade:hasItemQty(DonateCrys[Crystal],TradeCount);
if (TradeCrys == true) then
if (player:getRank() == 1) then
player:showText(npc,DONATE_LOW_RANK);
break;
elseif (player:getRankPoints() == 4000) then
player:showText(npc,DONATE_AT_MAXIM);
break;
elseif (DonateCrys[Crystal] == 4102 or DonateCrys[Crystal] == 4103 or
DonateCrys[Crystal] == 4244 or DonateCrys[Crystal] == 4245) then
AddPoints = TradeCount * math.floor(4000 / (player:getRank() * 12 - 16));
else
AddPoints = TradeCount * math.floor(4000 / (player:getRank() * 12 - 12));
end
if (AddPoints + player:getRankPoints() >= 4000) then
PlayerCP = PlayerCP + (AddPoints + player:getRankPoints()) - 4000;
player:setRankPoints(4000);
player:showText(npc,DONATE_OVERFLOW);
else
player:addRankPoints(AddPoints);
player:showText(npc,DONATE_CRYSTALS);
end
player:tradeComplete();
break;
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Menu1 = (player:getNation() * 16) + (3*256) + 65537;
Menu2 = 0;
Menu3 = player:getRank();
Menu4 = 1069547551 + 4194272;
Menu5 = 1069547551;
Menu6 = player:getRank() + (player:getNation() * 32);
Menu7 = PlayerCP;
Menu8 = 0;
player:startEvent(0x7ffb,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
if(player:getNation() == 0) then
Inventory = SandInv;
size = table.getn(SandInv);
elseif(player:getNation() == 1) then
Inventory = BastInv;
size = table.getn(BastInv);
else
Inventory = WindInv;
size = table.getn(WindInv);
end
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == Inventory[Item]) then
CPVerify = 1;
if (PlayerCP >= Inventory[Item + 1]) then
CPVerify = 0;
end
player:updateEvent(CanEquip,CPVerify,Inventory[Item + 2]);
break;
end
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (option == 1) then
duration = (player:getRank() + 3 + 3) * 3600;
if(player:hasStatusEffect(EFFECT_SIGNET) == true) then
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration,0,0); -- Grant Signet
else
player:addStatusEffect(EFFECT_SIGNET,0,0,duration,0,0); -- Grant Signet
end
elseif (option >= 32768 and option <= 32944) then
if(player:getNation() == 0) then size = table.getn(SandInv);
elseif(player:getNation() == 1) then size = table.getn(BastInv);
else size = table.getn(WindInv);
end
for Item = 1,size,3 do
if (option == Inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
PlayerCP = PlayerCP - Inventory[Item + 1];
player:addItem(Inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,Inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,Inventory[Item + 2]);
end
break;
end
end
end
end; | gpl-3.0 |
tarantool/luarocks | src/luarocks/core/dir.lua | 2 | 1287 |
local dir = {}
local require = nil
--------------------------------------------------------------------------------
--- Describe a path in a cross-platform way.
-- Use this function to avoid platform-specific directory
-- separators in other modules. Removes trailing slashes from
-- each component given, to avoid repeated separators.
-- Separators inside strings are kept, to handle URLs containing
-- protocols.
-- @param ... strings representing directories
-- @return string: a string with a platform-specific representation
-- of the path.
function dir.path(...)
local t = {...}
while t[1] == "" do
table.remove(t, 1)
end
return (table.concat(t, "/"):gsub("([^:])/+", "%1/"):gsub("^/+", "/"):gsub("/*$", ""))
end
--- Split protocol and path from an URL or local pathname.
-- URLs should be in the "protocol://path" format.
-- For local pathnames, "file" is returned as the protocol.
-- @param url string: an URL or a local pathname.
-- @return string, string: the protocol, and the pathname without the protocol.
function dir.split_url(url)
assert(type(url) == "string")
local protocol, pathname = url:match("^([^:]*)://(.*)")
if not protocol then
protocol = "file"
pathname = url
end
return protocol, pathname
end
return dir
| mit |
CerNerCompany/Anti-Spam | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| lgpl-2.1 |
salehvw0011/stfbot | plugins/Arabic_Lock.lua | 22 | 1379 | antiarabic = {}-- An empty table for solving multiple kicking problem
do
local function run(msg, matches)
if is_momod(msg) then -- Ignore mods,owner,admins
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_arabic'] then
if data[tostring(msg.to.id)]['settings']['lock_arabic'] == 'yes' then
if is_whitelisted(msg.from.id) then
return
end
if antiarabic[msg.from.id] == true then
return
end
if msg.to.type == 'chat' then
local receiver = get_receiver(msg)
local username = msg.from.username
local name = msg.from.first_name
if username and is_super_group(msg) then
send_large_msg(receiver , "Arabic/Persian is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked/msg deleted")
else
send_large_msg(receiver , "Arabic/Persian is not allowed here\nName: "..name.."["..msg.from.id.."]\nStatus: User kicked/msg deleted")
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (arabic was locked) ")
local chat_id = msg.to.id
local user_id = msg.from.id
kick_user(user_id, chat_id)
end
antiarabic[msg.from.id] = true
end
end
return
end
local function cron()
antiarabic = {}
end
return {
patterns = {
"([\216-\219][\128-\191])"
},
run = run,
cron = cron
}
end
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/blocks/BlockFence.lua | 1 | 1551 | --[[
Title: Fence Based Block
Author(s): LiXizhi
Date: 2013/12/13
Desc:
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/blocks/BlockFence.lua");
local block = commonlib.gettable("MyCompany.Aries.Game.blocks.BlockFence")
-------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/Common/Direction.lua");
local Direction = commonlib.gettable("MyCompany.Aries.Game.Common.Direction")
local ItemClient = commonlib.gettable("MyCompany.Aries.Game.Items.ItemClient");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local TaskManager = commonlib.gettable("MyCompany.Aries.Game.TaskManager")
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local block = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.block"), commonlib.gettable("MyCompany.Aries.Game.blocks.BlockFence"));
-- register
block_types.RegisterBlockClass("BlockFence", block);
function block:ctor()
end
function block:Init()
end
function block:GetMetaDataFromEnv(blockX, blockY, blockZ, side, side_region, camx,camy,camz, lookat_x,lookat_y,lookat_z)
return block._super.GetMetaDataFromEnv(self, blockX, blockY, blockZ);
end
function block:RotateBlockData(blockData, angle, axis)
return self:RotateBlockDataUsingModelFacing(blockData, angle, axis);
end
| gpl-2.0 |
madpilot78/ntopng | scripts/lua/modules/conf_handlers/netplan.lua | 1 | 5547 | --
-- (C) 2013-21 - ntop.org
--
local sys_utils = require("sys_utils")
local ipv4_utils = require("ipv4_utils")
local config = {}
-- ################################################################
local NEDGE_NETPLAN_CONF = "20-nedge.yaml"
local CLOUD_DIRECTORY = "/etc/cloud/cloud.cfg.d"
local CLOUD_DISABLED_FNAME = "99-disable-network-config.cfg"
local start_ethernet_section = true
function config.writeNetworkInterfaceConfig(f, iface, network_conf, dns_config, bridge_ifaces)
if iface == "lo" then
-- nothing to do for loopback interface
return
end
local vlan_raw_iface = nil
local vlan_id = nil
if string.contains(iface, "%.") then
local parts = string.split(iface, "%.")
vlan_raw_iface = parts[1]
vlan_id = parts[2]
end
if bridge_ifaces ~= nil then
f:write(" bridges:\n")
elseif string.find(iface, ":") then
-- This is an alias
local base_iface = split(iface, ":")[1]
if starts(iface, "br") then
-- bridge iface
f:write(" bridges:\n")
else
f:write(" ethernets:\n")
end
iface = base_iface
elseif start_ethernet_section then
f:write(" ethernets:\n")
start_ethernet_section = false
end
if vlan_raw_iface then
-- inside ethernet section, write the raw device
f:write(" ".. vlan_raw_iface ..":\n")
f:write(" addresses: []\n")
-- start a vlan section
f:write(" vlans:\n")
end
f:write(" ".. iface ..":\n")
if network_conf.mode == "static" then
cidr = ipv4_utils.netmask(network_conf.netmask)
f:write(" addresses: [" .. network_conf.ip .."/".. cidr .."]\n")
if not isEmptyString(network_conf.gateway) then
f:write(" gateway4: " .. network_conf.gateway .. "\n")
f:write(" nameservers:\n")
f:write(" addresses: [" .. table.concat({dns_config.global, dns_config.secondary}, ", ") .. "]\n")
end
elseif (network_conf.mode == "dhcp") then
f:write(" addresses: []\n")
f:write(" dhcp4: true\n")
else
-- e.g. vlan-trunk
f:write(" addresses: []\n")
end
if vlan_raw_iface then
f:write(" accept-ra: no\n")
f:write(" id: " .. vlan_id .. "\n")
f:write(" link: " .. vlan_raw_iface .. "\n")
-- end VLAN section and start again the ethernet section
start_ethernet_section = true
elseif bridge_ifaces ~= nil then
f:write(" interfaces: [".. table.concat(bridge_ifaces, ", ") .."]\n")
f:write(" parameters:\n")
f:write(" stp: false\n")
f:write(" forward-delay: 0\n")
end
end
-- ################################################################
function config.openNetworkInterfacesConfigFile()
local f = sys_utils.openFile("/etc/netplan/" .. NEDGE_NETPLAN_CONF, "w")
f:write("network:\n version: 2\n")
start_ethernet_section = true
return f
end
-- ################################################################
function config.closeNetworkInterfacesConfigFile(f)
f:close()
sys_utils.execShellCmd("netplan generate")
end
-- ################################################################
function config.backupNetworkInterfacesFiles(to_backup)
for fname in pairs(to_backup) do
local source = fname
local destination = source .. ".old"
os.rename(source, destination)
traceError(TRACE_WARNING, TRACE_CONSOLE, source .. " has been moved to " .. destination)
end
local cloud_disabled_path = CLOUD_DIRECTORY .. "/" .. CLOUD_DISABLED_FNAME
if ntop.isdir(CLOUD_DIRECTORY) and not ntop.exists(cloud_disabled_path) then
-- disable cloud to prevent future modifications
local f = sys_utils.openFile(cloud_disabled_path, "w")
if f ~= nil then
f:write("network: {config: disabled}\n")
f:close()
end
end
end
-- ################################################################
-- returns true if the interface is already configured in a file which is not managed by nedge
-- In such case, it also returns the list of files which use the interface
function config.isConfiguredInterface(iface)
local files_to_rename = {}
for fname in pairs(ntop.readdir("/etc/netplan")) do
if fname ~= NEDGE_NETPLAN_CONF then
local fpath = "/etc/netplan/".. fname
-- e.g.: "renderer: NetworkManager", "iface: enp1s0"
local res = sys_utils.execCmd("grep \"^\\s*[^#]*\\(" .. iface .. "\\|renderer\\):\" ".. fpath .." >/dev/null 2>/dev/null")
if not isEmptyString(res) then
files_to_rename[fpath] = 1
end
end
end
return not table.empty(files_to_rename), files_to_rename
end
-- ################################################################
function config.dhcpInterfaceGetGateway(iface)
-- it says "do not parse", but there is no script to get this info
local dirs = ntop.readdir("/var/run/systemd/netif/leases/") or {}
for ifid in pairs(dirs) do
local name_line = sys_utils.execShellCmd('grep "NETWORK_FILE=" /run/systemd/netif/links/'.. ifid)
if not isEmptyString(name_line) then
local parts = split(name_line, "-")
local name = split(parts[#parts], ".network")[1]
if name == iface then
local gw = sys_utils.execShellCmd('grep "ROUTER=" /var/run/systemd/netif/leases/' .. ifid .. ' | cut -f2 -d=')
if not isEmptyString(gw) then
gw = split(gw, "\n")[1]
if isIPv4(gw) then
return gw
end
end
end
end
end
return nil
end
-- ################################################################
return config
| gpl-3.0 |
madpilot78/ntopng | scripts/plugins/alerts/network/threshold_cross/checks/network/inner.lua | 1 | 1114 | --
-- (C) 2019-21 - ntop.org
--
local alerts_api = require("alerts_api")
local alert_consts = require("alert_consts")
local checks = require("checks")
local script = {
-- Script category
category = checks.check_categories.network,
default_enabled = false,
default_value = {
operator = "gt",
threshold = 1073741824, -- 1GB
},
-- See below
hooks = {},
gui = {
i18n_title = "alerts_thresholds_config.inner_traffic",
i18n_description = "alerts_thresholds_config.alert_network_inner_description",
i18n_field_unit = checks.field_units.bytes,
input_builder = "threshold_cross",
}
}
-- #################################################################
function script.hooks.min(params)
local value = alerts_api.network_delta_val(script.key, params.granularity, params.entity_info["inner"])
-- Check if the configured threshold is crossed by the value and possibly trigger an alert
alerts_api.checkThresholdAlert(params, alert_consts.alert_types.alert_threshold_cross, value)
end
-- #################################################################
return script
| gpl-3.0 |
madpilot78/ntopng | scripts/plugins/alerts/security/flow_flood/checks/network/flow_flood_victim.lua | 1 | 1227 | --
-- (C) 2019-21 - ntop.org
--
local alerts_api = require("alerts_api")
local alert_consts = require("alert_consts")
local checks = require("checks")
local script = {
-- Script category
category = checks.check_categories.security,
default_enabled = false,
default_value = {
operator = "gt",
threshold = 32768,
},
-- See below
hooks = {},
gui = {
i18n_title = "entity_thresholds.flow_victim_title",
i18n_description = "entity_thresholds.flow_victim_description",
i18n_field_unit = checks.field_units.flow_sec,
input_builder = "threshold_cross",
field_max = 65535,
field_min = 1,
field_operator = "gt";
}
}
-- #################################################################
function script.hooks.min(params)
local value = params.entity_info["hits.flow_flood_victim"] or 0
local victim = nil
if value ~= 0 then
victim = params.alert_entity.entity_val
end
-- Check if the configured threshold is crossed by the value and possibly trigger an alert
alerts_api.checkThresholdAlert(params, alert_consts.alert_types.alert_flow_flood_victim, value, nil, victim)
end
-- #################################################################
return script
| gpl-3.0 |
RyMarq/Zero-K | LuaRules/Configs/StartBoxes/TMA-0 v1_1.lua | 17 | 1371 | return {
[0] = {
startpoints = {
{5816,3768},
},
boxes = {
{
{5571,3441},
{6062,3441},
{6062,4096},
{5571,4096},
},
},
},
[1] = {
startpoints = {
{7700,13189},
},
boxes = {
{
{7373,12943},
{8028,12943},
{8028,13435},
{7373,13435},
},
},
},
[2] = {
startpoints = {
{4260,8684},
},
boxes = {
{
{3932,8356},
{4588,8356},
{4588,9011},
{3932,9011},
},
},
},
[3] = {
startpoints = {
{13025,5980},
},
boxes = {
{
{12780,5734},
{13271,5734},
{13271,6226},
{12780,6226},
},
},
},
[4] = {
startpoints = {
{10158,3359},
},
boxes = {
{
{9830,3113},
{10486,3113},
{10486,3604},
{9830,3604},
},
},
},
[5] = {
startpoints = {
{4424,12206},
},
boxes = {
{
{4096,11960},
{4751,11960},
{4751,12452},
{4096,12452},
},
},
},
[6] = {
startpoints = {
{2949,6717},
},
boxes = {
{
{2621,6390},
{3277,6390},
{3277,7045},
{2621,7045},
},
},
},
[7] = {
startpoints = {
{12370,11633},
},
boxes = {
{
{12124,11305},
{12616,11305},
{12616,11960},
{12124,11960},
},
},
},
[8] = {
startpoints = {
{9011,7864},
},
boxes = {
{
{8684,7537},
{9339,7537},
{9339,8192},
{8684,8192},
},
},
},
}
| gpl-2.0 |
adde88/Nerdpack-Zylla | rotations/warrior/arms.lua | 1 | 12926 | local _, Zylla = ...
local unpack = _G.unpack
local NeP = _G.NeP
local Mythic_Plus = _G.Zylla.Mythic_Plus
local GUI = {
unpack(Zylla.Logo_GUI),
-- Header
{type = 'header', size = 16, text = 'Keybinds', align = 'center'},
{type = 'checkbox', text = 'Left Shift: '..Zylla.ClassColor..'Pause|r', align = 'left', key = 'lshift', default = true},
{type = 'checkbox', text = 'Left Ctrl: '..Zylla.ClassColor..'Heroic Leap|r', align = 'left', key = 'lcontrol', default = true},
{type = 'checkbox', text = 'Left Alt: '..Zylla.ClassColor..'|r', align = 'left', key = 'lalt', default = true},
{type = 'checkbox', text = 'Right Alt: '..Zylla.ClassColor..'|r', align = 'left', key = 'ralt', default = true},
{type = 'spacer'},
{type = 'checkbox', text = 'Enable Chatoverlay', key = 'chat', width = 55, default = true, desc = Zylla.ClassColor..'This will enable some messages as an overlay!|r'},
unpack(Zylla.PayPal_GUI),
{type = 'spacer'},
unpack(Zylla.PayPal_IMG),
{type = 'spacer'}, {type = 'ruler'}, {type = 'spacer'},
--TODO: Targetting: Use, or NOT use?! We'll see....
{type = 'header', size = 16, text = 'Targetting:', align = 'center'},
{type = 'combo', default = 'target', key = 'target', list = Zylla.faketarget, width = 75},
{type = 'spacer'},
{type = 'text', text = Zylla.ClassColor..'Only one can be enabled.\nChose between normal targetting, or hitting the highest/lowest enemy.|r'},
{type = 'spacer'}, {type = 'ruler'}, {type = 'spacer'},
-- Settings
{type = 'header', size = 16, text = 'Class Settings', align = 'center'},
{type = 'spinner', size = 11, text = 'Interrupt at percentage:', key = 'intat', default = 60, step = 5, shiftStep = 10, max = 100, min = 1},
{type = 'checkbox', text = 'Enable DBM Integration', key = 'kDBM', default = true},
{type = 'checkbox', text = 'Enable \'pre-potting\', flasks and Legion-rune', key = 'prepot', default = false},
{type = 'combo', default = '1', key = 'list', list = Zylla.prepots, width = 175},
{type = 'spacer'}, {type = 'spacer'},
{type = 'checkspin',text = 'Light\'s Judgment - Units', key = 'LJ', spin = 4, step = 1, max = 20, check = true, desc = Zylla.ClassColor..'World Spell usable on Argus.|r'},
{type = 'checkbox', text = 'Use Trinket #1', key = 'trinket1', default = false},
{type = 'checkbox', text = 'Use Trinket #2', key = 'trinket2', default = false, desc = Zylla.ClassColor..'Trinkets will be used whenever possible!|r'},
{type = 'spacer'},
{type = 'checkspin', text = 'Kil\'Jaeden\'s Burning Wish - Units', key = 'kj', align = 'left', width = 55, step = 1, shiftStep = 2, spin = 4, max = 20, min = 1, check = true, desc = Zylla.ClassColor..'Legendary will be used only on selected amount of units!|r'},
{type = 'ruler'}, {type = 'spacer'},
-- Survival
{type = 'header', size = 16, text = 'Survival', align = 'center'},
unpack(Zylla.Mythic_GUI),
}
local exeOnLoad = function()
Zylla.ExeOnLoad()
Zylla.AFKCheck()
print('|cffADFF2F ----------------------------------------------------------------------|r')
print('|cffADFF2F --- |rWarrior |cffADFF2FArms |r')
print('|cffADFF2F --- |rRecommended Talents: 1/1 - 2/3 - 3/3 - 4/2 - 5/3 - 6/1 - 7/1')
print('|cffADFF2F ----------------------------------------------------------------------|r')
NeP.Interface:AddToggle({
key = 'xIntRandom',
name = 'Interrupt Anyone',
text = 'Interrupt all nearby enemies, without targeting them.',
icon = 'Interface\\Icons\\inv_ammo_arrow_04',
})
end
local PreCombat = {
-- Pots
{'#127844', 'UI(list)==1&item(127844).usable&item(127844).count>0&UI(kDBM)&UI(prepot)&!buff(Potion of the Old War)&dbm(pull in)<3'}, --XXX: Potion of the Old War
{'#127843', 'UI(list)==2&item(127843).usable&item(127843).count>0&UI(kDBM)&UI(prepot)&!buff(Potion of Deadly Grace)&dbm(pull in)<3'}, --XXX: Potion of Deadly Grace
{'#142117', 'UI(list)==3&item(142117).usable&item(142117).count>0&UI(kDBM)&UI(prepot)&!buff(Potion of Prolonged Power)&dbm(pull in)<3'}, --XXX: Potion of Prolonged Power
-- Flasks
{'#127850', 'ingroup&item(127850).usable&item(127850).count>0&UI(prepot)&!buff(Flask of Ten Thousand Scars)'}, --XXX: Flask of Ten Thousand Scars
{'#127849', 'item(127850).count==0&ingroup&item(127849).usable&item(127849).count>0&UI(prepot)&!buff(Flask of the Countless Armies)'}, --XXX: Flask of the Countless Armies (IF WE DON'T HAVE THOUSAND SCARS FLASKS)
{'#153023', 'ingroup&item(153023).usable&item(153023).count>0&UI(prepot)&!buff(Defiled Augmentation)'}, --XXX: Lightforged Augment Rune
}
local Keybinds = {
-- Pause
{'%pause', 'keybind(lshift)&UI(lshift)'},
{'!Heroic Leap', 'keybind(lcontrol)' , 'cursor.ground'}
}
local Interrupts = {
{'!Pummel'},
{'!Arcane Torrent', 'inMelee&cooldown(Pummel).remains>gcd&!player.lastgcd(Pummel)'},
}
local Survival = {
{'Victory Rush', 'player.health<UI(vr_spin)&UI(vr_check)'},
}
local Cooldowns = {
{'Blood Fury', 'buff(Battle Cry)', 'player'},
{'Berserking', 'buff(Battle Cry)', 'player'},
{'Arcane Torrent', 'buff(Battle Cry)&talent(6,1)&rage.deficit>40', 'player'},
{'Battle Cry', '{player.buff(Bloodlust)||xtime>0}&gcd.remains<0.5&{player.buff(Shattered Defenses)||{cooldown(Colossus Smash).remains>gcd&cooldown(Warbreaker).remains>gcd}}', 'player'},
{'Avatar', 'talent(3,3)&{buff(Bloodlust)||xtime>0}', 'player'},
{'#trinket1', 'UI(trinket1)'},
{'#trinket2', 'UI(trinket2)'},
{'Light\'s Judgment', 'advanced&UI(LJ_check)&range<61&area(15).enemies>=UI(LJ_spin)', 'enemies.ground'},
{'𣎃', 'UI(kj_check)&range<=40&area(10).enemies>=UI(kj_spin)&equipped(144259)'}, --XXX: Kil'jaeden's Burning Wish (Legendary)
}
local Etc = {
{Cooldowns, 'toggle(Cooldowns)'},
--{'Hamstring', 'player.buff(Battle Cry)&talent(6,1)&!target.debuff(Hamstring)'}, --waste of player.rage i would say unless ... it's PvP, maybe?
{'Rend', 'talent(3,2)&target.debuff(Rend).remains<gcd'},
--# The tl;dr of this line is to spam focused player.rage inside battle cry, the added nonsense is to help modeling the difficulty of timing focused player.rage immediately after mortal strike.
--# In game, if focused player.rage is used the same instant as mortal strike, player.rage will be deducted for focused player.rage, the buff is immediately consumed, but it does not buff the damage of mortal strike.
{'Focused Rage', 'player.buff(Battle Cry)&talent(6,1)&player.buff(Focused Rage).stack<3'},
{'Colossus Smash', '!target.debuff(Colossus Smash)'},
{'Warbreaker', 'artifact(Warbreaker).equipped&!target.debuff(Colossus Smash)'},
{'Ravager', 'talent(7,3)'},
{'Overpower', 'player.buff(Overpower!)'}
}
local AoE = {
{'Mortal Strike', 'player.buff(Focused Rage).stack>1'},
{'Execute', 'player.buff(Ayala\'s Stone Heart)'},
{'Colossus Smash', '!player.buff(Shattered Defenses)&!player.buff(Precise Strikes)'},
{'Warbreaker', '!player.buff(Shattered Defenses)'},
{'Whirlwind', 'talent(3,1)&{target.debuff(Colossus Smash)||rage.deficit<50}&{!talent(5,3)||{player.buff(Battle Cry)&talent(6,1)}||player.buff(Cleave)}'},
{'Rend', 'talent(3,2)&target.debuff(Rend).remains<5.5'},
{'Bladestorm'},
{'Cleave'},
{'Execute', 'player.rage>80'},
{'Whirlwind', 'player.rage>30'},
{'Shockwave', 'talent(2,1)'},
{'Storm Bolt', 'talent(2,2)'}
}
local Cleave = {
{'Mortal Strike', 'player.buff(Focused Rage).stack>1'},
{'Execute', 'player.buff(Ayala\'s Stone Heart)'},
{'Colossus Smash', '!player.buff(Shattered Defenses)&!player.buff(Precise Strikes)'},
{'Warbreaker', '!player.buff(Shattered Defenses)'},
{'Focused Rage', '!player.buff(Shattered Defenses)'},
{'Whirlwind', 'talent(3,1)&{target.debuff(Colossus Smash)||rage.deficit<50}&{!talent(5,3)||{player.buff(Battle Cry)&talent(6,1)}||player.buff(Cleave)}'},
{'Rend', 'talent(3,2)&target.debuff(Rend).remains<5.5'},
{'Bladestorm'},
{'Cleave'},
{'Whirlwind', 'player.rage>000||player.buff(Focused Rage).stack=3'},
{'Shockwave', 'talent(2,1)'},
{'Storm Bolt', 'talent(2,2)'}
}
local Execute = {
{'Mortal Strike', 'player.buff(Battle Cry)&player.buff(Focused Rage).stack=3'},
{'Execute', 'player.buff(Battle Cry)&talent(6,1)'},
{'Colossus Smash', '!player.buff(Shattered Defenses)'},
{'Warbreaker', '!player.buff(Shattered Defenses)&player.rage<40'},
{'Execute', 'player.buff(Shattered Defenses)&player.rage>22'},
{'Execute', '!player.buff(Shattered Defenses)&{{equipped(137060)&rage>40}||!equipped(137060)}'},
{'Mortal Strike', 'equipped(137060)'},
{'Execute', '!player.buff(Shattered Defenses)'},
{'Bladestorm'},
}
local ST = {
{'Mortal Strike', 'player.buff(Battle Cry)&player.buff(Focused Rage).stack>0&cooldown(Battle Cry).remains<gcd'},
{'Colossus Smash', '!player.buff(Shattered Defenses)'},
{'Warbreaker', '!player.buff(Shattered Defenses)&cooldown(Mortal Strike).remains<gcd'},
{'Focused Rage', '{{{!player.buff(Focused Rage)&prev_gcd(Mortal Strike)}||!prev_gcd(Mortal Strike)}&player.buff(Focused Rage).stack<3&{player.buff(Shattered Defenses)||cooldown(Colossus Smash).remains>gcd}}&player.rage>60'},
{'Mortal Strike', 'player.buff(Focused Rage).stack>0'},
{'Execute', 'player.buff(Ayala\'s Stone Heart)'},
--Whirlwind instead of Slam if 'Fevor of Battle' is picked
{'Whirlwind', 'talent(3,1)&{{player.buff(Battle Cry)&talent(6,1)}||player.buff(Focused Rage).stack=3||rage.deficit<40}'},
{'Slam', '!talent(3,1)&{{player.buff(Battle Cry)&talent(6,1)}||player.buff(Focused Rage).stack=3||rage.deficit<40}'},
{'Mortal Strike', '!talent(5,3)'},
{'Whirlwind', 'player.area(8).enemies>1||talent(3,1)&player.rage>35'},
{'Slam', '!talent(3,1)&player.area(8).enemies==1&player.rage>22'},
{'Execute', 'equipped(137060)'},
{'Focused Rage', 'equipped(137060)'},
{'Bladestorm'},
}
local xCombat = {
{Interrupts, '@Zylla.InterruptAt(intat)&toggle(interrupts)'},
{Interrupts, '@Zylla.InterruptAt(intat)&toggle(interrupts)&toggle(xIntRandom)', 'enemies'},
{Cooldowns, 'toggle(Cooldowns)&inMelee'},
{Etc, 'inMelee&inFront'},
{Cleave, 'toggle(aoe)&player.area(8).enemies>1&talent(1,3)'},
{AoE, 'toggle(aoe)&player.area(8).enemies>4&!talent(1,3)'},
{Execute, 'inMelee&inFront&health<30&player.area(8).enemies<5'},
{ST, 'inMelee&inFront&health>20'},
}
local inCombat = {
{Keybinds},
{Survival, nil, 'player'},
{xCombat, 'combat&alive&inMelee&inFront', (function() return NeP.DSL:Get("UI")(nil, 'target') end)}, --TODO: TEST! ALOT MORE TESTING!
{Mythic_Plus, 'inMelee'},
}
local outCombat = {
{Keybinds},
{PreCombat, nil, 'player'},
}
NeP.CR:Add(71, {
name = '[|cff'..Zylla.addonColor..'Zylla\'s|r] Warrior - Arms',
ic = inCombat,
ooc = outCombat,
gui = GUI,
gui_st = Zylla.GuiSettings,
ids = Zylla.SpellIDs[Zylla.Class],
wow_ver = Zylla.wow_ver,
nep_ver = Zylla.nep_ver,
load = exeOnLoad
})
--[[
TODO:
Opener:
Charge
Focused Rage -> Colossus Smash
Focused Rage -> Battle Cry
Avatar
Mortal Strike
Focused Rage -> Colossus Smash (Slam if Tactician didn’t proc)
Focused Rage -> Colossus Smash (Slam if Tactician didn’t proc, or if you have Shattered Defenses)
Focused Rage -> Mortal Strike (Slam if Tactician didn’t proc)
Standard Rotation/Priority list:
Above 20%:
Use Colossus Smash and Mortal Strike on cooldown (Don't overwrite Shattered Defenses).
If you get a Colossus Smash proc, do Colossus Smash Focused Rage -> Mortal Strike.
Use slam when above 32 rage and both Colossus Smash and Mortal Strike are on cd.
Use Focused Rage to not avoid ragecapping (about 25 rage from cap).
Below 20%:
Use Colossus Smash on CD (Don't overwrite Shattered Defenses) -> 22 (18 with Dauntless and 3/3 PS) rage
Execute with the Shattered Defenses -> spam Execute when you don’t have Shattered Defenses.
Use Focused Rage if you're about to rage cap (about 25 rage from cap), save Focused Rage stacks for Battle Cry.
Battle Cry Rotation:
Above 20%:
Colossus Smash -> Battle Cry
Focused Rage
Mortal Strike -> Focused Rage
Colossus Smash (Slam if no Colossus Smash) -> Focused Rage
Colossus Smash (Slam if no Colossus Smash, or Shattered Defenses proc) -> Mortal Strike (Colossus Smash if Mortal Strike isn't up and no Shattered Defenses buff, Slam if neither Colossus Smash/Mortal Strike is up)
Below 20%:
Colossus Smash -> Battle Cry
Execute
Focused Rage -> Execute
Focused Rage -> Execute
Focused Rage -> x3 Focused Rage
Mortal Strike (Only use Colossus Smash if the debuff isn’t on the target. 2 Executes are more damage than 1 Colossus Smash + 1 Shattered Defenses Execute)
--]]
| mit |
NPLPackages/paracraft | script/apps/Aries/mcml/pe_avatar.lua | 1 | 49066 | --[[
Title: avatar tag control(override the default mcml avatar tag)
Author(s): WangTian
Date: 2008/3/10
Revised: 2008/3/21 LiXizhi 2008/4/3 LiXizhi (fully implemented with MCML functions)
Desc: pe:avatar is used to render the 3d avatar of a given user or just any avatar.
one can use mouse to rotate and scale the avatar. The inner node of pe:avatar is rendered inside the avatar window.
<verbatim>
<pe:avatar uid = "loggedinuser" style="width:256px;height:256px;"/>
<pe:avatar uid = "loggedinuser" name="avatar" style="width:256px;height:256px;padding:5px">
<pe:if-is-user uid="loggedinuser">
<a type="button" onclick="Map3DSystem.App.CCS.AvatarRegPage.TakeAvatarSnapshot">快照</a>
</pe:if-is-user>
</pe:avatar>
</verbatim>
| *property* | *desc*|
| RenderTargetSize | default to 256 |
| miniscenegraphname| default to pe:name |
| IsActiveRendering | default to true|
| IsInteractive | whether it will receive and responds to mouse event |
| autoRotateSpeed | how many degrees (in radian) to rotate around the Y axis per second. if nil or 0 it will not rotate. common values are 0.12 |
| MaskTexture | mini scene mask texture |
| *method* | *description* |
| TakeSnapshot | take a snapshot of the current avatar. |
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/mcml/pe_avatar.lua");
local pe_avatar = commonlib.gettable("MyCompany.Aries.mcml_controls.pe_avatar");
pe_player.GetCCSParams(nid_number, "self", function(params)
if(params) then
pe_player.ApplyCCSParamsToChar(para_obj, params);
end
end)
-------------------------------------------------------
]]
local string_find = string.find;
NPL.load("(gl)script/kids/3DMapSystemItem/ItemManager.lua");
local ItemManager = commonlib.gettable("Map3DSystem.Item.ItemManager");
local Player = commonlib.gettable("MyCompany.Aries.Player");
local Pet = commonlib.gettable("MyCompany.Aries.Pet");
if(not Map3DSystem.mcml_controls) then Map3DSystem.mcml_controls = {} end
-----------------------------------
-- pe:avatar control
-----------------------------------
local pe_avatar = commonlib.gettable("MyCompany.Aries.mcml_controls.pe_avatar");
function pe_avatar.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout)
local uid = mcmlNode:GetAttributeWithCode("uid");
if(uid == "loggedinuser") then
-- get current user ID as the uid
uid = System.User.nid;
end
if(uid == nil) then
log("error: must specify uid or \"loggedinuser\" for pe:avatar MCML tag\n");
return;
end
local left, top, width, height = parentLayout:GetPreferredRect();
local css = mcmlNode:GetStyle(Map3DSystem.mcml_controls.pe_html.css["pe:filebrowser"], style) or {};
local padding_left, padding_top, padding_bottom, padding_right =
(css["padding-left"] or css["padding"] or 0),(css["padding-top"] or css["padding"] or 0),
(css["padding-bottom"] or css["padding"] or 0),(css["padding-right"] or css["padding"] or 0);
local margin_left, margin_top, margin_bottom, margin_right =
(css["margin-left"] or css["margin"] or 0),(css["margin-top"] or css["margin"] or 0),
(css["margin-bottom"] or css["margin"] or 0),(css["margin-right"] or css["margin"] or 0);
if(css.width) then
if((left + css.width)<width) then
width = left + css.width + margin_left + margin_right
end
end
if(css.height) then
if((top + css.height)<height) then
height = top + css.height + margin_top + margin_bottom
end
end
local myLayout;
if(mcmlNode:GetChildCount()>0) then
myLayout = parentLayout:clone();
myLayout:SetUsedSize(0,0);
myLayout:OffsetPos(padding_left+margin_left, padding_top+margin_top);
myLayout:IncHeight(-padding_bottom-margin_bottom);
myLayout:IncWidth(-padding_right-margin_right);
end
parentLayout:AddObject(width-left, height-top);
left = left + margin_left
top = top + margin_top;
width = width - margin_right;
height = height - margin_bottom;
local IsActiveRendering = mcmlNode:GetBool("IsActiveRendering")
if(IsActiveRendering == nil) then
IsActiveRendering = true
end
local IsInteractive = mcmlNode:GetBool("IsInteractive")
if(IsInteractive == nil) then
IsInteractive = true;
end
local autoRotateSpeed = mcmlNode:GetNumber("autoRotateSpeed")
if(autoRotateSpeed == nil) then
autoRotateSpeed = 0;
end
local IsPortrait = mcmlNode:GetBool("IsPortrait")
if(IsPortrait == nil) then
IsPortrait = false;
end
local IsFacePortrait = mcmlNode:GetBool("IsFacePortrait")
if(IsFacePortrait == nil) then
IsFacePortrait = false;
end
-- create the 3d canvas for avatar display
local instName = mcmlNode:GetInstanceName(rootName);
NPL.load("(gl)script/ide/Canvas3D.lua");
local ctl = CommonCtrl.Canvas3D:new{
name = instName,
alignment = "_lt",
left = left,
top = top,
width = width - left,
height = height - top,
background = mcmlNode:GetString("background") or css.background,
parent = _parent,
IsActiveRendering = IsActiveRendering,
miniscenegraphname = mcmlNode:GetAttributeWithCode("miniscenegraphname") or "pe:name",
RenderTargetSize = mcmlNode:GetNumber("RenderTargetSize") or 256,
IsInteractive = IsInteractive,
autoRotateSpeed = autoRotateSpeed,
};
ctl:Show();
------------------------------------
-- load avatar information
------------------------------------
local assetName;
local appearanceInfo;
-- TODO 2008.4.3: while we are retrieving information from server, shall we display a waiting animation in 3d HERE?
--ctl:ShowModel({
--["IsCharacter"] = true,
--["y"] = 0,
--["x"] = 0,
--["facing"] = -1.57,
--["name"] = "pe:avatar",
--["z"] = 0,
--["AssetFile"] = "character/common/headquest/headquest.x",
--["CCSInfoStr"] = nil,
--});
--
-- get avatar information from uid
--
-- TODO: accept both nid and uid
--- just in case it is an nid
Map3DSystem.App.profiles.ProfileManager.GetUserInfo(uid, "pe:avatar_"..tostring(uid), function(msg)
if(msg and msg.users and msg.users[1]) then
local user = msg.users[1];
local userid = user.userid;
Map3DSystem.App.profiles.ProfileManager.GetMCML(userid, Map3DSystem.App.appkeys["CCS"],
function(uid, app_key, bSucceed, profile)
if(profile and profile.CharParams and profile.CharParams.AssetFile) then
if(ctl) then
ctl:ShowModel({
["IsCharacter"] = true,
["y"] = 0,
["x"] = 0,
["facing"] = -1.57,
["name"] = "pe:avatar",
["z"] = 0,
["AssetFile"] = profile.CharParams.AssetFile,
["CCSInfoStr"] = profile.CharParams.CCSInfoStr,
});
end
else
ctl:ShowModel({
["IsCharacter"] = true,
["y"] = 0,
["x"] = 0,
["facing"] = -1.57,
["name"] = "pe:avatar",
["z"] = 0,
["AssetFile"] = "character/common/headquest/headquest.x",
["CCSInfoStr"] = nil,
});
end
--[[if(profile) then
-- set the camera position to take portait view of avatar
if(IsPortrait == true) then
-- TODO: get the portait shot camera setting from the character or model asset description
-- take the portrait shot of the avatar
if(profile.CharParams.AssetFile == "character/v3/Human/Male/HumanMale.xml") then
ctl:CameraSetLookAtPos(0, 1.4654281139374, 0);
ctl:CameraSetEyePosByAngle(2.7281620502472, 0.31596618890762, 2.5371053218842);
end
if(profile.CharParams.AssetFile == "character/v3/Human/Female/HumanFemale.xml") then
ctl:CameraSetLookAtPos(0, 1.4654281139374, 0);
ctl:CameraSetEyePosByAngle(2.7281620502472, 0.31596618890762, 2.5371053218842);
end
if(string_find(profile.CharParams.AssetFile, "can")) then
ctl:CameraSetLookAtPos(0, 0.9654281139374, 0);
ctl:CameraSetEyePosByAngle(2.7281620502472, 0.31596618890762, 3.5371053218842);
end
ctl:ShowModel({
["IsCharacter"] = true,
["y"] = 0,
["x"] = 0,
["facing"] = 0,
["name"] = "pe:avatar",
["z"] = 0,
["AssetFile"] = profile.CharParams.AssetFile,
["CCSInfoStr"] = profile.CharParams.CCSInfoStr,
});
if(string_find(profile.CharParams.AssetFile, "ElfFemale.xml")) then
ctl:CameraSetLookAtPos(0, 0.75053763389587, 0);
ctl:CameraSetEyePosByAngle(-1.6270221471786, 0.10000000149012, 3.0698845386505);
end
elseif(IsFacePortrait == true) then
-- TODO: get the portait shot camera setting from the character or model asset description
-- take the portrait shot of the avatar
ctl:ShowModel({
["IsCharacter"] = true,
["y"] = 0,
["x"] = 0,
["facing"] = 0,
["name"] = "pe:avatar",
["z"] = 0,
["AssetFile"] = profile.CharParams.AssetFile,
["CCSInfoStr"] = profile.CharParams.CCSInfoStr,
});
if(string_find(profile.CharParams.AssetFile, "ElfFemale.xml")) then
ctl:CameraSetLookAtPos(0, 0.90813940763474, -0.01);
ctl:CameraSetEyePosByAngle(-1.5990210771561, 0.10000523924828, 1.7753294229507);
end
end
end]]
-- set the mask texture
local MaskTexture = mcmlNode:GetAttributeWithCode("MaskTexture")
if(MaskTexture ~= nil and MaskTexture ~= "") then
ctl:SetMaskTexture(MaskTexture);
end
end)
end
end);
-- if user is current user, display some buttons.
if(uid == Map3DSystem.App.profiles.ProfileManager.GetUserID()) then
-- TODO:
end
-- create inner child if any .
if(myLayout) then
local childnode;
for childnode in mcmlNode:next() do
local left, top, width, height = myLayout:GetPreferredRect();
Map3DSystem.mcml_controls.create(rootName, childnode, bindingContext, _parent, left, top, width, height, nil, myLayout)
end
end
end
-- take a snapshot
-- @param filename: where to save the snap shot. default to "Screen Shots/pe_avatar_snapshot.png"
-- we support ".dds", ".jpg", ".png" files. If the file extension is not recognized, ".png" file is used.
-- @param nImageSize: if this is nil or zero, the original size is used. If it is dds, all mip map levels are saved.
function pe_avatar.TakeSnapshot(mcmlNode, pageInstName, filename, nImageSize)
filename = filename or "Screen Shots/pe_avatar_snapshot.png";
nImageSize = nImageSize or 0;
local ctl = mcmlNode:GetControl(pageInstName);
if(ctl and ctl.SaveToFile) then
return ctl:SaveToFile(filename, nImageSize);
end
end
-- pe:player is an Aries specified control that will read local visualized characters first and then fetch from item system information
-----------------------------------
-- pe:player control
-----------------------------------
local pe_player = commonlib.gettable("MyCompany.Aries.mcml_controls.pe_player");
-- mapping from camera name to camera settings.
local CamSetting = {
ElfFemale = {
LookAt = {0, 0.75700056552887, 0},
EyePos = {3.1121213436127, 0.10053723305464, 3.3980791568756},
},
ElfFemaleHead = {
LookAt = {0, 1, 0},
EyePos = {3.1121213436127, 0.10053723305464, 2.6},
},
ElfFemaleFreezed = {
LookAt = {0, 0.82573479413986, 0},
EyePos = {3.36399102211, 0.35200002789497, 3.8270018100739},
},
PurpleDragonEgg = {
LookAt = {0, 0.36514848470688, 0},
EyePos = {2.7000000476837, 0.30000001192093, 2.930297088623},
},
PurpleDragonMinor = {
LookAt = {0, 0.69411826133728, 0},
EyePos = {2.7526597976685, 0.10025001317263, 4.9751110076904},
},
PurpleDragonMajor = {
LookAt = {0, 0.84263616800308, 0},
EyePos = {2.5885643959045, 0.099945321679115, 6.2741990089417},
},
MysteryAcinusTree = {
LookAt = {0, 1.3436055898666, 0},
EyePos = {-1.3432075977325, 0.28798785805702, 10.3661255836487},
},
DragonTotem = {
LookAt = {0, 3.9842195987701, 0},
EyePos = {1.0959913730621, 0.28399962186813, 72.633911132813},
},
DragonBaby = {
LookAt = {0, 0.84263616800308, 0},
EyePos = {2.5885643959045, 0.099945321679115, 6.2741990089417},
},
};
if(pe_player.CamSetting) then
local name, value
for name, value in pairs(CamSetting) do
pe_player.CamSetting[name] = pe_player.CamSetting[name] or value;
end
else
pe_player.CamSetting = CamSetting;
end
-- mapping from asset string to camera name
local CameraNameByAssetMap = {
["TeenElfFemale"] = "ElfFemale",
["TeenElfMale"] = "ElfFemale",
["ElfFemale"] = "ElfFemale",
["ElfFemaleFreezed"] = "ElfFemaleFreezed",
["PurpleDragonMajor"] = "PurpleDragonMajor",
["PurpleDragonMinor"] = "PurpleDragonMinor",
["PurpleDragonEgg"] = "PurpleDragonEgg",
["MysteryAcinusTree"] = "MysteryAcinusTree",
["DragonTotem"] = "DragonTotem",
["DragonBaby"] = "DragonBaby",
}
local function GetFacialInfoStringFromEquips(facial_plus_cartoonface)
if(type(facial_plus_cartoonface) == "string") then
local facial, cartoonface = string.match(facial_plus_cartoonface, "^([^@]-)@([^@]-)@$");
if(facial and cartoonface) then
return facial;
end
end
return "0#1#0#1#1#";
end
local function GetCartoonfaceInfoStringFromEquips(facial_plus_cartoonface)
if(type(facial_plus_cartoonface) == "string") then
local facial, cartoonface = string.match(facial_plus_cartoonface, "^([^@]-)@([^@]-)@$");
if(facial and cartoonface) then
return cartoonface;
end
end
return "0#F#0#0#0#0#0#F#0#0#0#0#0#F#0#0#0#0#0#F#0#0#0#0#0#F#0#0#0#0#0#F#0#0#0#0#0#F#0#0#0#0#";
end
local function GetTeenGSID(gsid, isFemale)
if(gsid <= 0) then
return 0;
end
local isUniSex = false;
local gsItem = ItemManager.GetGlobalStoreItemInMemory(gsid)
if(gsItem) then
-- 187 is_unisex_teen(C)
if(gsItem.template.stats[187] == 1) then
isUniSex = true;
end
end
if(isUniSex == true) then
gsid = gsid + 30000;
else
if(isFemale) then
gsid = gsid + 40000;
else
gsid = gsid + 30000;
end
end
return gsid;
end
local need_replace_equip_positions = {2,5,7,8};
local function GetCharacterSlotInfoStringFromEquips(equips, object)
--"0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#1008#1009#1003#1010#1021#0#0#0#0#0#";
if(object == "self") then
if(System.options.version == "teen") then
local isFemale = false;
if(equips[25] == 982) then
isFemale = true;
end
return GetTeenGSID(equips[2], isFemale).."#0#0#0#0#0#0#0#0#0#"..GetTeenGSID(equips[11], isFemale).."#"..GetTeenGSID(equips[10], isFemale).."#0#0#"..GetTeenGSID(equips[1], isFemale).."#0#"..GetTeenGSID(equips[5], isFemale).."#"..GetTeenGSID(equips[6], isFemale).."#"..GetTeenGSID(equips[9], isFemale).."#"..GetTeenGSID(equips[7], isFemale).."#"..GetTeenGSID(equips[4], isFemale).."#"..GetTeenGSID(equips[8], isFemale).."#0#0#0#0#";
else
local i;
local replace_equips = {};
commonlib.mincopy(replace_equips, equips);
for i = 1,#need_replace_equip_positions do
local position = need_replace_equip_positions[i];
if(replace_equips[position]) then
local gsid = replace_equips[position];
local gsItem = ItemManager.GetGlobalStoreItemInMemory(gsid)
if(gsItem) then
-- Replacement_GSID
local replacement_gsid = gsItem.template.stats[53];
if(replacement_gsid) then
replace_equips[position] = replacement_gsid;
end
end
end
end
return replace_equips[2].."#0#0#0#0#0#0#0#0#0#"..replace_equips[11].."#"..replace_equips[10].."#0#0#"..replace_equips[1].."#0#"..replace_equips[5].."#"..replace_equips[6].."#"..replace_equips[9].."#"..replace_equips[7].."#"..replace_equips[4].."#"..replace_equips[8].."#0#0#0#0#";
end
elseif(object == "mount") then
return "0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#"..equips[41].."#"..equips[42].."#"..equips[43].."#"..equips[44].."#";
elseif(object == "follow") then
return "";
end
end
-- get ccs params of a given nid.
-- @param nid: number or string, where number is preferred. if nil it is current player
-- @param object: "self", "follow", "mount"
-- @param func_callback: function(params) end
function pe_player.GetCCSParams(nid, object, func_callback)
nid = tonumber(nid or System.User.nid);
object = object or "self";
Map3DSystem.Item.ItemManager.GetEquips(nid, function(msg)
if(msg and msg.equips and msg.equips[1] and msg.equips[1].gsids) then
local equips = {};
local i;
for i = 1, 44 do
equips[i] = 0;
end
local equipstr = msg.equips[1].gsids;
local gsid;
local i = 0;
for gsid in string.gmatch(equipstr, "[^,]+") do
i = i + 1;
equips[i] = tonumber(gsid);
end
local assetfile;
local replaceable_r1;
if(object == "self") then
assetfile = Player.GetAvaterAssetFileByID(equips[25]);
elseif(object == "mount") then
local gsid = equips[31];
if(gsid ~= 0) then
if(nid == Map3DSystem.App.profiles.ProfileManager.GetNID()) then
-- check if the mount pet is at home
local item
if(nid == System.App.profiles.ProfileManager.GetNID()) then
-- my mount
local ItemManager = System.Item.ItemManager;
item = ItemManager.GetMyMountPetItem();
else
-- OPC mount
item = ItemManager.GetOPCMountPetItem(nid);
end
if(item and item.guid > 0 and (System.options.version=="kids")) then
gsid = item.gsid;
local mountPetStage = item:GetAssetFileIndex();
assetfile = ItemManager.GetAssetFileFromGSIDAndIndex(item.gsid, item:GetAssetFileIndex());
local basecolor_gsid = equips[40];
if(mountPetStage == 1) then -- egg
if(basecolor_gsid == 11009) then
--replaceable_r1 = "character/v3/PurpleDragonEgg/SkinColor01.dds";
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor01.dds";
elseif(basecolor_gsid == 11010) then
--replaceable_r1 = "character/v3/PurpleDragonEgg/SkinColor02.dds";
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor02.dds";
elseif(basecolor_gsid == 11011) then
--replaceable_r1 = "character/v3/PurpleDragonEgg/SkinColor03.dds";
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor03.dds";
elseif(basecolor_gsid == 11012) then
--replaceable_r1 = "character/v3/PurpleDragonEgg/SkinColor04.dds";
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor04.dds";
end
elseif(mountPetStage == 2) then -- minor
if(basecolor_gsid == 11009) then
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor01.dds";
elseif(basecolor_gsid == 11010) then
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor02.dds";
elseif(basecolor_gsid == 11011) then
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor03.dds";
elseif(basecolor_gsid == 11012) then
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor04.dds";
end
elseif(mountPetStage == 3) then -- major
if(basecolor_gsid == 11009) then
replaceable_r1 = "character/v3/PurpleDragonMajor/Female/SkinColor01.dds";
elseif(basecolor_gsid == 11010) then
replaceable_r1 = "character/v3/PurpleDragonMajor/Female/SkinColor02.dds";
elseif(basecolor_gsid == 11011) then
replaceable_r1 = "character/v3/PurpleDragonMajor/Female/SkinColor03.dds";
elseif(basecolor_gsid == 11012) then
replaceable_r1 = "character/v3/PurpleDragonMajor/Female/SkinColor04.dds";
end
end
else
return;
end
else
return;
end
end
elseif(object == "follow") then
local gsid = equips[32];
if(gsid == 0) then
return
end
local gsItem = ItemManager.GetGlobalStoreItemInMemory(gsid)
if(gsItem) then
assetfile = gsItem.assetfile;
end
end
-- get ccs string
local facial_info_string = GetFacialInfoStringFromEquips(equips);
local cartoonface_info_string = GetCartoonfaceInfoStringFromEquips(equips);
local characterslot_info_string = GetCharacterSlotInfoStringFromEquips(equips, object);
if(func_callback) then
func_callback({facial_info_string=facial_info_string, cartoonface_info_string=cartoonface_info_string, characterslot_info_string=characterslot_info_string, replaceable_r1=replaceable_r1, assetfile=assetfile});
end
else
if(func_callback) then
func_callback();
end
end
end);
end
-- Apply CCS params to character
-- @param obj: the ParaObject of the character
function pe_player.ApplyCCSParamsToChar(obj, params)
if(not params) then return end
if(params.assetfile and obj:GetPrimaryAsset():GetKeyName()~= params.assetfile) then
local asset = ParaAsset.LoadParaX("", params.assetfile);
obj:ToCharacter():ResetBaseModel(asset);
end
if(params.replaceable_r1) then
obj:SetReplaceableTexture(1, ParaAsset.LoadTexture("", params.replaceable_r1, 1));
end
if(obj:ToCharacter():IsCustomModel() == true) then
local facial_info_string = params.facial_info_string;
local cartoonface_info_string = params.cartoonface_info_string;
local characterslot_info_string = params.characterslot_info_string;
Map3DSystem.UI.CCS.Predefined.ApplyFacialInfoString(obj, facial_info_string);
Map3DSystem.UI.CCS.DB.ApplyCartoonfaceInfoString(obj, cartoonface_info_string);
local sInfo = characterslot_info_string;
local playerChar;
-- get player character
if(obj ~= nil and obj:IsValid() == true) then
if(obj:IsCharacter() == true) then
playerChar = obj:ToCharacter();
end
end
if( playerChar ~= nil and playerChar:IsCustomModel() == true ) then
local slot = 0;
local itemID;
for itemID in string.gfind(sInfo, "([^#]+)") do
local gsid = tonumber(itemID);
if(gsid) then
if(slot == 21) then
local gsItem = ItemManager.GetGlobalStoreItemInMemory(gsid);
if(gsItem) then
-- reset the base model to mount pet asset
local bForceAttBack = gsItem.template.stats[13];
if(bForceAttBack == 1) then
slot = 26; -- CS_BACK
playerChar:SetCharacterSlot(21, 0);
else
slot = 21; -- CS_ARIES_CHAR_GLASS
playerChar:SetCharacterSlot(26, 0);
end
end
end
playerChar:SetCharacterSlot(slot, gsid);
end
slot = slot + 1;
end
else
--log("error: attempt to set a non character ccs information or non custom character.\n");
end
end
-- NOTE 2010/8/30: for all characters with hat, hide the hair, hair is included in the hat model
if(obj:ToCharacter():GetCharacterSlotItemID(0) > 1) then -- IT_Head
obj:ToCharacter():SetBodyParams(-1, -1, 0, 0, -1); -- int hairColor, int hairStyle
end
end
-- TODO: this is just a temparory tag for offline mode
function pe_player.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout)
-- get user nid
local nid = mcmlNode:GetAttributeWithCode("nid",nil,true);
if(nid == "loggedinuser") then
-- get current user ID as the uid
nid = Map3DSystem.App.profiles.ProfileManager.GetNID();
end
nid = tonumber(nid);
if(nid == nil) then
log("error: must specify nid or \"loggedinuser\" for pe:player MCML tag\n");
return;
end
-- get display object
local object = mcmlNode:GetAttributeWithCode("object");
if(not object) then
object = "self";
end
---- NOTE by Andy: why object = "npc" can pass the condition
--if(object ~= "self" or object ~= "mount" or object ~= "follow" or object ~= "npc") then
--object = "self";
--end
local left, top, width, height = parentLayout:GetPreferredRect();
local css = mcmlNode:GetStyle(Map3DSystem.mcml_controls.pe_html.css["pe:player"], style) or {};
local padding_left, padding_top, padding_bottom, padding_right =
(css["padding-left"] or css["padding"] or 0),(css["padding-top"] or css["padding"] or 0),
(css["padding-bottom"] or css["padding"] or 0),(css["padding-right"] or css["padding"] or 0);
local margin_left, margin_top, margin_bottom, margin_right =
(css["margin-left"] or css["margin"] or 0),(css["margin-top"] or css["margin"] or 0),
(css["margin-bottom"] or css["margin"] or 0),(css["margin-right"] or css["margin"] or 0);
if(css.width) then
if((left + css.width)<width) then
parentLayout:NewLine();
left, top, width, height = parentLayout:GetPreferredRect();
end
width = left + css.width + margin_left + margin_right
end
if(css.height) then
height = top + css.height + margin_top + margin_bottom
end
local myLayout;
if(mcmlNode:GetChildCount()>0) then
myLayout = parentLayout:clone();
myLayout:SetUsedSize(0,0);
myLayout:OffsetPos(padding_left+margin_left, padding_top+margin_top);
myLayout:IncHeight(-padding_bottom-margin_bottom);
myLayout:IncWidth(-padding_right-margin_right);
end
parentLayout:AddObject(width-left, height-top);
left = left + margin_left
top = top + margin_top;
width = width - margin_right;
height = height - margin_bottom;
local IsActiveRendering = mcmlNode:GetBool("IsActiveRendering")
if(IsActiveRendering == nil) then
IsActiveRendering = true
end
local IsInteractive = mcmlNode:GetBool("IsInteractive")
if(IsInteractive == nil) then
IsInteractive = true;
end
local autoRotateSpeed = mcmlNode:GetNumber("autoRotateSpeed")
if(autoRotateSpeed == nil) then
autoRotateSpeed = 0;
end
local miniSceneName = mcmlNode:GetAttributeWithCode("miniscenegraphname") or "pe:player"..ParaGlobal.GenerateUniqueID();
-- create the 3d canvas for avatar display
local instName = mcmlNode:GetInstanceName(rootName);
NPL.load("(gl)script/ide/Canvas3D.lua");
local ctl = CommonCtrl.Canvas3D:new{
name = instName.."_player",
alignment = "_lt",
left = left,
top = top,
width = width - left,
height = height - top,
background = mcmlNode:GetString("background") or css.background,
parent = _parent,
IsActiveRendering = IsActiveRendering,
miniscenegraphname = miniSceneName,
DefaultRotY = mcmlNode:GetNumber("DefaultRotY"),
RenderTargetSize = mcmlNode:GetNumber("RenderTargetSize") or 256,
IsInteractive = IsInteractive,
autoRotateSpeed = autoRotateSpeed,
};
ctl:Show(true);
Map3DSystem.mcml_controls.pe_player_all = Map3DSystem.mcml_controls.pe_player_all or {};
--table.insert(Map3DSystem.mcml_controls.pe_player_all, instName.."_player")
Map3DSystem.mcml_controls.pe_player_all[instName.."_player"] = miniSceneName;
if(not commonlib.getfield("MyCompany.Aries")) then
log("error: call pe:player outside the Aries project\n");
return;
end
local Pet = MyCompany.Aries.Pet;
local Quest = MyCompany.Aries.Quest;
local player;
local char_asset, mesh_asset, player_name;
if(object == "self") then
player = Pet.GetUserCharacterObj(nid);
if(player and player:GetPrimaryAsset():GetKeyName() == "") then
player = nil;
end
elseif(object == "mount") then
player = Pet.GetUserMountObj(nid);
elseif(object == "follow") then
player = Pet.GetUserFollowObj(nid);
elseif(object == "homelandpet") then
local guid = mcmlNode:GetAttributeWithCode("guid");
if(guid) then
guid = tonumber(guid);
if(nid == Map3DSystem.App.profiles.ProfileManager.GetNID()) then
local name;
local ItemManager = System.Item.ItemManager;
local item = ItemManager.GetItemByGUID(guid);
if(item and item.guid > 0 and item.GetSceneObjectNameInHomeland) then
name = item:GetSceneObjectNameInHomeland();
end
if(name) then
local obj = ParaScene.GetCharacter(name);
if(obj:IsValid() == true) then
player = obj;
end
end
else
local name;
local ItemManager = System.Item.ItemManager;
local item = ItemManager.GetOPCItemByGUID(nid, guid);
if(item and item.guid > 0 and item.GetSceneObjectNameInHomeland) then
name = item:GetSceneObjectNameInHomeland();
end
if(name) then
local obj = ParaScene.GetCharacter(name);
if(obj:IsValid() == true) then
player = obj;
end
end
end
end
elseif(object == "npc") then
-- if npc object, nid means the npc_id
local instance = mcmlNode:GetAttributeWithCode("instance");
if(instance) then
instance = tonumber(instance);
-- singleton npc
if(instance == 0) then
instance = nil;
end
end
player = Quest.NPC.GetNpcCharacterFromIDAndInstance(nid, instance);
if(player) then
if(string_find(player:GetPrimaryAsset():GetKeyName(), "character/common/dummy/")) then
local model = Quest.NPC.GetNpcModelFromIDAndInstance(nid, instance)
player = model;
end
end
if(not player) then
local NPCList = commonlib.gettable("MyCompany.Aries.Quest.NPCList");
local npc_data = NPCList.GetNPCByID(nid);
if(npc_data) then
player_name = npc_data.name or "";
if(not npc_data.skiprender_char) then
char_asset = npc_data.assetfile_char;
elseif(not npc_data.skiprender_mesh) then
mesh_asset = npc_data.assetfile_model
end
end
end
elseif(object == "gameobject") then
-- if game object object, nid means the gameobj_id
player = Quest.GameObject.GetGameObjectCharacterFromIDAndInstance(nid);
if(not player) then
local GameObjectList = commonlib.gettable("MyCompany.Aries.Quest.GameObjectList");
local gameobj_data = GameObjectList.GetGameObjectByID(nid);
if(gameobj_data) then
player_name = gameobj_data.name or "";
if(not gameobj_data.skiprender_char) then
char_asset = gameobj_data.assetfile_char;
elseif(not gameobj_data.skiprender_mesh) then
mesh_asset = gameobj_data.assetfile_model
end
end
end
end
local function PlayAnimIfSickOrDead()
if(object == "mount") then
-- play sick or dead animation if appropriate
local isdead = false;
local issick = false;
local item;
if(nid == System.App.profiles.ProfileManager.GetNID()) then
-- my mount
local ItemManager = System.Item.ItemManager;
item = ItemManager.GetMyMountPetItem();
else
-- OPC mount
local ItemManager = System.Item.ItemManager;
item = ItemManager.GetOPCMountPetItem(nid);
end
if(item and item.guid > 0 and type(item.IsDead) == "function" and type(item.IsSick) == "function") then
isdead = item:IsDead();
issick = item:IsSick();
end
local miniGraph = ParaScene.GetMiniSceneGraph(miniSceneName);
if(miniGraph and miniGraph:IsValid() == true) then
local obj = miniGraph:GetObject(miniSceneName.."_obj");
if(obj and obj:IsValid() == true) then
if(issick) then
local index = item:GetAssetFileIndex();
if(index == 1) then
System.Animation.PlayAnimationFile("character/Animation/v5/xiaolong/PurpleDragonMinor_sick_loop.x", obj);
--System.Animation.PlayAnimationFile("character/Animation/v5/longbaobao/PurpleDragonEgg_sick_loop.x", obj);
elseif(index == 2) then
System.Animation.PlayAnimationFile("character/Animation/v5/xiaolong/PurpleDragonMinor_sick_loop.x", obj);
elseif(index == 3) then
System.Animation.PlayAnimationFile("character/Animation/v5/dalong/PurpleDragoonMajorFemale_sick_loop.x", obj);
end
end
if(isdead) then
local index = item:GetAssetFileIndex();
if(index == 1) then
System.Animation.PlayAnimationFile("character/Animation/v5/xiaolong/PurpleDragonMinor_death_loop.x", obj);
--System.Animation.PlayAnimationFile("character/Animation/v5/longbaobao/PurpleDragonEgg_death_loop.x", obj);
elseif(index == 2) then
System.Animation.PlayAnimationFile("character/Animation/v5/xiaolong/PurpleDragonMinor_death_loop.x", obj);
elseif(index == 3) then
System.Animation.PlayAnimationFile("character/Animation/v5/dalong/PurpleDragoonMajorFemale_death_loop.x", obj);
end
end
end
end
end
end
if( (char_asset or mesh_asset) or (player and player:IsValid()) ) then
-- clone the player apparence information and apply to pe:player
if(ctl) then
local miniscene_obj;
if(char_asset) then
if(type(char_asset) == "string") then
char_asset = ParaAsset.LoadParaX("", char_asset);
end
miniscene_obj = ParaScene.CreateCharacter(miniSceneName.."_obj", char_asset, "", true, 0.35, -1.57, 1);
elseif(mesh_asset) then
if(type(mesh_asset) == "string") then
mesh_asset = ParaAsset.LoadStaticMesh("", mesh_asset);
end
miniscene_obj = ParaScene.CreateMeshPhysicsObject(miniSceneName.."_obj", mesh_asset, 1,1,1, false, "1,0,0,0,1,0,0,0,1,0,0,0");
else
-- clone the object
local function CloneObj(obj)
local ret_obj;
if(obj and obj:IsValid() == true) then
if(obj:IsCharacter()) then
local asset = obj:GetPrimaryAsset();
ret_obj = ParaScene.CreateCharacter(miniSceneName.."_obj", asset, "", true, 0.35, -1.57, 1);
local replaceable_r1 = obj:GetReplaceableTexture(1):GetFileName();
if(replaceable_r1 and replaceable_r1~="") then
-- this fixed a bug of PoliceDog.x rendering
ret_obj:SetReplaceableTexture(1, ParaAsset.LoadTexture("", replaceable_r1, 1));
end
if(obj:ToCharacter():IsCustomModel()) then
local facial_info_string = Map3DSystem.UI.CCS.Predefined.GetFacialInfoString(obj);
local cartoonface_info_string = Map3DSystem.UI.CCS.DB.GetCartoonfaceInfoString(obj);
local characterslot_info_string = Map3DSystem.UI.CCS.Inventory.GetCharacterSlotInfoString(obj);
Map3DSystem.UI.CCS.Predefined.ApplyFacialInfoString(ret_obj, facial_info_string);
Map3DSystem.UI.CCS.DB.ApplyCartoonfaceInfoString(ret_obj, cartoonface_info_string);
Map3DSystem.UI.CCS.Inventory.ApplyCharacterSlotInfoString(ret_obj, characterslot_info_string);
--if(mcmlNode.IsSelfAndForceUseOriginalCCS) then
---- force reload the original ccs info
--local gsid = 0;
--local item = Map3DSystem.Item.ItemManager.GetItemByBagAndPosition(0, 2);
--if(item and item.guid ~= 0) then
--gsid = item.gsid;
--end
--ret_obj:ToCharacter():SetCharacterSlot(0, gsid);
--
--local gsid = 0;
--local item = Map3DSystem.Item.ItemManager.GetItemByBagAndPosition(0, 5);
--if(item and item.guid ~= 0) then
--gsid = item.gsid;
--end
--ret_obj:ToCharacter():SetCharacterSlot(16, gsid);
--
--local gsid = 0;
--local item = Map3DSystem.Item.ItemManager.GetItemByBagAndPosition(0, 6);
--if(item and item.guid ~= 0) then
--gsid = item.gsid;
--end
--ret_obj:ToCharacter():SetCharacterSlot(17, gsid);
--
--local gsid = 0;
--local item = Map3DSystem.Item.ItemManager.GetItemByBagAndPosition(0, 8);
--if(item and item.guid ~= 0) then
--gsid = item.gsid;
--end
--ret_obj:ToCharacter():SetCharacterSlot(21, gsid);
--
--local gsid = 0;
--local item = Map3DSystem.Item.ItemManager.GetItemByBagAndPosition(0, 7);
--if(item and item.guid ~= 0) then
--gsid = item.gsid;
--end
--ret_obj:ToCharacter():SetCharacterSlot(19, gsid);
--end
end
else
local asset = obj:GetPrimaryAsset();
ret_obj = ParaScene.CreateMeshPhysicsObject(miniSceneName.."_obj", asset, 1,1,1, false, "1,0,0,0,1,0,0,0,1,0,0,0");
end
end
return ret_obj;
end
miniscene_obj = CloneObj(player);
end
if(not miniscene_obj) then
return;
end
-- apply camera settings
local camera_name = mcmlNode:GetAttributeWithCode("CameraName");
local camera_setting;
if(camera_name) then
camera_setting = pe_player.CamSetting[camera_name];
ctl.__camera_name = camera_name;
else
local assetfile = miniscene_obj:GetPrimaryAsset():GetKeyName();
local name_, camera_name_
for name_, camera_name_ in pairs(CameraNameByAssetMap) do
if(assetfile:match(name_)) then
camera_setting = pe_player.CamSetting[camera_name_];
break;
end
end
end
ctl:ShowModel(miniscene_obj, camera_setting==nil);
ctl.ClonedObjName = player_name or player.name;
ctl.nid = nid;
PlayAnimIfSickOrDead();
if(camera_setting) then
local LookAt = camera_setting.LookAt;
local EyePos = camera_setting.EyePos;
ctl:CameraSetLookAtPos(LookAt[1], LookAt[2], LookAt[3]);
ctl:CameraSetEyePosByAngle(EyePos[1], EyePos[2], EyePos[3]);
end
-- set the mask texture
local MaskTexture = mcmlNode:GetAttributeWithCode("MaskTexture");
if(ctl and MaskTexture ~= nil and MaskTexture ~= "") then
ctl:SetMaskTexture(MaskTexture);
end
end
else
if(object == "npc") then
-- do nothing to show
-- NPC related pe:player is always shown when the NPC is insight
LOG.std("", "warn", "mcml", "visualize non-insight NPC in pe:avatar tag");
elseif(object == "gameobject") then
-- do nothing to show
-- game object related pe:player is always shown when the game object is insight
LOG.std("", "warn", "mcml", "visualize non-insight gameobject in pe:avatar tag");
else
-- set the mask texture
local MaskTexture = mcmlNode:GetAttributeWithCode("MaskTexture");
local ItemManager = System.Item.ItemManager;
ItemManager.GetItemsInOPCBag(nid, 0, "pe_player", function(msg)
if(msg and msg.items) then
local equips = {};
local i;
for i = 1, 44 do
equips[i] = 0;
end
local i;
for i = 1, 44 do
local item = ItemManager.GetOPCItemByBagAndPosition(nid, 0, i);
if(item and item.guid > 0) then
equips[i] = item.gsid;
end
end
local facial_plus_cartoonface = "";
local item = ItemManager.GetOPCItemByBagAndPosition(nid, 0, 21);
if(item and item.guid > 0) then
facial_plus_cartoonface = item.clientdata;
end
local assetfile;
local replaceable_r1;
if(object == "self") then
assetfile = Player.GetAvaterAssetFileByID(equips[25]);
elseif(object == "mount") then
local gsid = equips[31];
if(gsid ~= 0) then
if(nid == Map3DSystem.App.profiles.ProfileManager.GetNID()) then
-- check if the mount pet is at home
local item
if(nid == System.App.profiles.ProfileManager.GetNID()) then
-- my mount
local ItemManager = System.Item.ItemManager;
item = ItemManager.GetMyMountPetItem();
else
-- OPC mount
item = ItemManager.GetOPCMountPetItem(nid);
end
if(item and item.guid > 0 and (System.options.version=="kids")) then
gsid = item.gsid;
local mountPetStage = item:GetAssetFileIndex();
assetfile = ItemManager.GetAssetFileFromGSIDAndIndex(item.gsid, item:GetAssetFileIndex());
local basecolor_gsid = equips[40];
if(mountPetStage == 1) then -- egg
if(basecolor_gsid == 11009) then
--replaceable_r1 = "character/v3/PurpleDragonEgg/SkinColor01.dds";
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor01.dds";
elseif(basecolor_gsid == 11010) then
--replaceable_r1 = "character/v3/PurpleDragonEgg/SkinColor02.dds";
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor02.dds";
elseif(basecolor_gsid == 11011) then
--replaceable_r1 = "character/v3/PurpleDragonEgg/SkinColor03.dds";
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor03.dds";
elseif(basecolor_gsid == 11012) then
--replaceable_r1 = "character/v3/PurpleDragonEgg/SkinColor04.dds";
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor04.dds";
end
elseif(mountPetStage == 2) then -- minor
if(basecolor_gsid == 11009) then
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor01.dds";
elseif(basecolor_gsid == 11010) then
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor02.dds";
elseif(basecolor_gsid == 11011) then
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor03.dds";
elseif(basecolor_gsid == 11012) then
replaceable_r1 = "character/v3/PurpleDragonMinor/SkinColor04.dds";
end
elseif(mountPetStage == 3) then -- major
if(basecolor_gsid == 11009) then
replaceable_r1 = "character/v3/PurpleDragonMajor/Female/SkinColor01.dds";
elseif(basecolor_gsid == 11010) then
replaceable_r1 = "character/v3/PurpleDragonMajor/Female/SkinColor02.dds";
elseif(basecolor_gsid == 11011) then
replaceable_r1 = "character/v3/PurpleDragonMajor/Female/SkinColor03.dds";
elseif(basecolor_gsid == 11012) then
replaceable_r1 = "character/v3/PurpleDragonMajor/Female/SkinColor04.dds";
end
end
else
return;
end
else
return;
end
end
--local gsItem = ItemManager.GetGlobalStoreItemInMemory(gsid)
--if(gsItem) then
--assetfile = gsItem.assetfile;
--end
elseif(object == "follow") then
local gsid = equips[32];
if(gsid == 0) then
return
end
local gsItem = ItemManager.GetGlobalStoreItemInMemory(gsid)
if(gsItem) then
assetfile = gsItem.assetfile;
end
end
if(ctl) then
local asset = ParaAsset.LoadParaX("", assetfile);
local obj = ParaScene.CreateCharacter(miniSceneName.."_obj", asset, "", true, 0.35, -1.57, 1);
if(replaceable_r1) then
obj:SetReplaceableTexture(1, ParaAsset.LoadTexture("", replaceable_r1, 1));
end
if(obj:ToCharacter():IsCustomModel() == true) then
local facial_info_string = GetFacialInfoStringFromEquips(facial_plus_cartoonface);
local cartoonface_info_string = GetCartoonfaceInfoStringFromEquips(facial_plus_cartoonface);
local characterslot_info_string = GetCharacterSlotInfoStringFromEquips(equips, object);
Map3DSystem.UI.CCS.Predefined.ApplyFacialInfoString(obj, facial_info_string);
Map3DSystem.UI.CCS.DB.ApplyCartoonfaceInfoString(obj, cartoonface_info_string);
--Map3DSystem.UI.CCS.Inventory.ApplyCharacterSlotInfoString(obj, characterslot_info_string);
local sInfo = characterslot_info_string;
local playerChar;
-- get player character
if(obj ~= nil and obj:IsValid() == true) then
if(obj:IsCharacter() == true) then
playerChar = obj:ToCharacter();
end
end
if( playerChar ~= nil and playerChar:IsCustomModel() == true ) then
local slot = 0;
local itemID;
for itemID in string.gfind(sInfo, "([^#]+)") do
local gsid = tonumber(itemID);
if(gsid) then
if(slot == 16) then
local gsItem = ItemManager.GetGlobalStoreItemInMemory(gsid);
if(gsItem) then
local ground_effect_id = gsItem.template.stats[181];
if(ground_effect_id and ground_effect_id > 1000) then
playerChar:SetCharacterSlot(27, ground_effect_id);
else
playerChar:SetCharacterSlot(27, 0);
end
end
end
if(slot == 21) then
local gsItem = ItemManager.GetGlobalStoreItemInMemory(gsid);
if(gsItem) then
-- reset the base model to mount pet asset
local bForceAttBack = gsItem.template.stats[13];
if(bForceAttBack == 1) then
slot = 26; -- CS_BACK
playerChar:SetCharacterSlot(21, 0);
else
slot = 21; -- CS_ARIES_CHAR_GLASS
playerChar:SetCharacterSlot(26, 0);
end
end
end
if(slot ~= 27) then
playerChar:SetCharacterSlot(slot, gsid);
end
--playerChar:SetCharacterSlot(slot, gsid);
end
slot = slot + 1;
end
else
--log("error: attempt to set a non character ccs information or non custom character.\n");
end
end
-- NOTE 2010/8/30: for all characters with hat, hide the hair, hair is included in the hat model
if(obj:ToCharacter():GetCharacterSlotItemID(0) > 1) then -- IT_Head
obj:ToCharacter():SetBodyParams(-1, -1, 0, 0, -1); -- int hairColor, int hairStyle
end
-- apply camera settings
local camera_name = mcmlNode:GetAttributeWithCode("CameraName");
local camera_setting;
if(camera_name) then
camera_setting = pe_player.CamSetting[camera_name];
ctl.__camera_name = camera_name;
elseif(assetfile) then
local name_, _
local char_map = {
"TeenElfFemale",
"TeenElfMale",
"ElfFemale",
"ElfFemaleFreezed",
"PurpleDragonMajor",
"PurpleDragonEgg",
};
for _, name_ in ipairs(char_map) do
if(assetfile:match(name_)) then
local camera_name = CameraNameByAssetMap[name_];
if(camera_name) then
camera_setting = pe_player.CamSetting[camera_name];
end
break;
end
end
end
ctl:ShowModel(obj, camera_setting==nil);
PlayAnimIfSickOrDead();
if(camera_setting) then
local LookAt = camera_setting.LookAt;
local EyePos = camera_setting.EyePos;
ctl:CameraSetLookAtPos(LookAt[1], LookAt[2], LookAt[3]);
ctl:CameraSetEyePosByAngle(EyePos[1], EyePos[2], EyePos[3]);
end
if(ctl and MaskTexture ~= nil and MaskTexture ~= "") then
ctl:SetMaskTexture(MaskTexture);
end
end
end
end);
end
end
-- create inner child if any.
if(myLayout) then
local childnode;
for childnode in mcmlNode:next() do
local left, top, width, height = myLayout:GetPreferredRect();
Map3DSystem.mcml_controls.create(rootName, childnode, bindingContext, _parent, left, top, width, height, nil, myLayout)
end
end
------------------------------------
-- load avatar information
------------------------------------
end
function pe_player.RefreshContainingPageCtrls()
local pe_player_all = Map3DSystem.mcml_controls.pe_player_all or {};
local invalid_pe_player_names = {};
local name, miniscenename;
for name, miniscenename in pairs(pe_player_all) do
local ctl = CommonCtrl.GetControl(name);
if(ctl ~= nil) then
if(not ctl:IsUIValid()) then
-- NOTE: we check ui object for control validity, remove the name from pe_player_all for invalid controls
table.insert(invalid_pe_player_names, name);
else
-- NOTE (Fixed 2011.12.24): there is a chance that the target object is not refreshed according to cloedobjname
-- if it is an OPC character the name could be nid or nid+driver. if the user switch states,
-- the object with previously inserted name will be invalid or changed to mount pet dragon
if(ctl.ClonedObjName) then
-- the refresh page ctrls will only refresh the player if the player is already in the scene
-- otherwise one shoule refresh the pageCtrl to make sure the pe:player gets the latest player info
local function CloneObj(obj)
local ret_obj;
if(obj and obj:IsValid() == true) then
if(obj:IsCharacter()) then
local asset = obj:GetPrimaryAsset();
ret_obj = ParaScene.CreateCharacter("", asset, "", true, 0.35, -1.57, 1);
end
if(obj:ToCharacter():IsCustomModel()) then
local facial_info_string = Map3DSystem.UI.CCS.Predefined.GetFacialInfoString(obj);
local cartoonface_info_string = Map3DSystem.UI.CCS.DB.GetCartoonfaceInfoString(obj);
local characterslot_info_string = Map3DSystem.UI.CCS.Inventory.GetCharacterSlotInfoString(obj);
Map3DSystem.UI.CCS.Predefined.ApplyFacialInfoString(ret_obj, facial_info_string);
Map3DSystem.UI.CCS.DB.ApplyCartoonfaceInfoString(ret_obj, cartoonface_info_string);
Map3DSystem.UI.CCS.Inventory.ApplyCharacterSlotInfoString(ret_obj, characterslot_info_string);
end
end
return ret_obj;
end
-- fixed a bug that switching mount pet will change the appearance.
local player;
if(ctl.nid) then
player = Pet.GetUserCharacterObj(ctl.nid);
else
player = ParaScene.GetCharacter(ctl.ClonedObjName);
end
if(player and player:IsValid()) then
local camera_name = ctl.__camera_name;
local camera_setting;
if(camera_name) then
camera_setting = pe_player.CamSetting[camera_name];
else
local assetfile = player:GetPrimaryAsset():GetKeyName();
local name_, _;
local char_map = {
"ElfFemale",
"TeenElfFemale",
"TeenElfMale",
"ElfFemaleFreezed",
};
for name_, _ in pairs(char_map) do
if(assetfile:match(name_)) then
local camera_name = CameraNameByAssetMap[name_];
if(camera_name) then
camera_setting = pe_player.CamSetting[camera_name];
end
break;
end
end
end
ctl:ShowModel(CloneObj(player), camera_setting==nil);
if(camera_setting) then
local LookAt = camera_setting.LookAt;
local EyePos = camera_setting.EyePos;
ctl:CameraSetLookAtPos(LookAt[1], LookAt[2], LookAt[3]);
ctl:CameraSetEyePosByAngle(EyePos[1], EyePos[2], EyePos[3]);
end
end
end
end
end
end
-- clear the invalid pe:player controls
local i, name;
for i, name in ipairs(invalid_pe_player_names) do
Map3DSystem.mcml_controls.pe_player_all[name] = nil;
end
end | gpl-2.0 |
Lleafll/sws-lleaf | libs/LibBabble-Inventory-3.0/LibStub/tests/test.lua | 86 | 2013 | debugstack = debug.traceback
strmatch = string.match
loadfile("../LibStub.lua")()
local lib, oldMinor = LibStub:NewLibrary("Pants", 1) -- make a new thingy
assert(lib) -- should return the library table
assert(not oldMinor) -- should not return the old minor, since it didn't exist
-- the following is to create data and then be able to check if the same data exists after the fact
function lib:MyMethod()
end
local MyMethod = lib.MyMethod
lib.MyTable = {}
local MyTable = lib.MyTable
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 1) -- try to register a library with the same version, should silently fail
assert(not newLib) -- should not return since out of date
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 0) -- try to register a library with a previous, should silently fail
assert(not newLib) -- should not return since out of date
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 2) -- register a new version
assert(newLib) -- library table
assert(rawequal(newLib, lib)) -- should be the same reference as the previous
assert(newOldMinor == 1) -- should return the minor version of the previous version
assert(rawequal(lib.MyMethod, MyMethod)) -- verify that values were saved
assert(rawequal(lib.MyTable, MyTable)) -- verify that values were saved
local newLib, newOldMinor = LibStub:NewLibrary("Pants", "Blah 3 Blah") -- register a new version with a string minor version (instead of a number)
assert(newLib) -- library table
assert(newOldMinor == 2) -- previous version was 2
local newLib, newOldMinor = LibStub:NewLibrary("Pants", "Blah 4 and please ignore 15 Blah") -- register a new version with a string minor version (instead of a number)
assert(newLib)
assert(newOldMinor == 3) -- previous version was 3 (even though it gave a string)
local newLib, newOldMinor = LibStub:NewLibrary("Pants", 5) -- register a new library, using a normal number instead of a string
assert(newLib)
assert(newOldMinor == 4) -- previous version was 4 (even though it gave a string) | mit |
purebn/ShadowBot | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_mini.lua | 141 | 1054 | --[[
netdiscover_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.netdiscover_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scan for devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.netdiscover_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", true, debug)
luci.controller.luci_diag.netdiscover_common.action_links(m, true)
return m
| gpl-2.0 |
Grocel/wire-extras | lua/wire/uwsvn/client/stringtochars.lua | 2 | 1277 | //-----------------------------------------------------------------------------
// Name: CC_StringToChars
// Desc: Converts a string or a single character into the appropriate character
// codes, can output as a list of codes or a packet for the E-Gate.
//-----------------------------------------------------------------------------
local function CC_StringToChars (player, command, args)
local adj = 0
local out = "%s"
// Output usage
if (#args == 0) then
Msg ("USAGE: stringtochars [PACKET] \"string\"\n Use PACKET to output in expression gate packet form.\n")
return
end
// Select output mode
if (string.upper (args[1]) == "PACKET") then
adj = 1
out = "send(%s)"
end
// Loop through the arguments
for i = 1 + adj, #args do
local fmt = ""
local chars = { string.byte (args[i], 1, string.len (args[i])) }
for j = 1, #chars do
if (string.len (fmt) > 0) then
fmt = fmt .. ", "
end
fmt = fmt .. tostring (chars[j])
end
Msg (string.format ("'%s' = %s\n", args[i], string.format (out, fmt)))
end
end
concommand.Add ('stringtochars', CC_StringToChars)
| apache-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Code/CodeBlocklyGenerator.lua | 1 | 12359 | --[[
Title: CodeBlocklyGenerator
Author(s): leio
Date: 2018/6/17
Desc: the help functions for reading/writing blockly information
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeBlocklyGenerator.lua");
local CodeBlocklyGenerator = commonlib.gettable("MyCompany.Aries.Game.Code.CodeBlocklyGenerator");
links:
blockfactory: https://blockly-demo.appspot.com/static/demos/blockfactory/index.html
define-blocks: https://developers.google.com/blockly/guides/create-custom-blocks/define-blocks
generating-code: https://developers.google.com/blockly/guides/create-custom-blocks/generating-code
operator-precedence: https://developers.google.com/blockly/guides/create-custom-blocks/operator-precedence
-------------------------------------------------------
]]
local CodeBlocklyGenerator = commonlib.inherit(nil,commonlib.gettable("MyCompany.Aries.Game.Code.CodeBlocklyGenerator"));
function CodeBlocklyGenerator:ctor()
self.arg_len = 100; -- the max number of argument, start index is from 0
self.language_names = {
["lua"] = { blockly_namesapce = "Lua", function_name = "func_description", function_provider_name = "func_description_lua_provider", },
["javascript"] = { blockly_namesapce = "JavaScript", function_name = "func_description_js", function_provider_name = "func_description_js_provider", },
["python"] = { blockly_namesapce = "Python", function_name = "func_description_py", function_provider_name = "func_description_py_provider", },
}
end
function CodeBlocklyGenerator:OnInit(categories,all_cmds)
self.categories = categories;
self.all_cmds = all_cmds;
return self;
end
function CodeBlocklyGenerator:GetLanguageName(language)
local config = self:GetLanguageConfig(language);
if(config)then
return config.blockly_namesapce;
end
end
function CodeBlocklyGenerator:GetFunctionName(language)
local config = self:GetLanguageConfig(language);
if(config)then
return config.function_name;
end
end
function CodeBlocklyGenerator:GetFunctionProviderName(language)
local config = self:GetLanguageConfig(language);
if(config)then
return config.function_provider_name;
end
end
function CodeBlocklyGenerator:GetLanguageConfig(language)
if(not language)then
return
end
return self.language_names[language];
end
function CodeBlocklyGenerator:GetCategoryButtons()
return self.categories;
end
function CodeBlocklyGenerator:GetAllCmds()
return self.all_cmds;
end
function CodeBlocklyGenerator:GetKeywords()
local all_cmds = self:GetAllCmds();
local result = {};
local k,v;
for k,v in ipairs(all_cmds) do
if(v.type)then
table.insert(result,v.type);
end
end
local s = NPL.ToJson(result,true);
return s;
end
function CodeBlocklyGenerator:GetBlocklyMenuXml()
local categories = self:GetCategoryButtons()
local all_cmds = self:GetAllCmds();
local s = [[<xml id="toolbox" style="display: none">]];
local k,v;
for k,v in ipairs(categories) do
local c_s = self:GetCategoryStr(v);
s = string.format("%s\n%s",s,c_s);
end
s = string.format("%s\n</xml>",s);
return s;
end
-- create a xml menu
function CodeBlocklyGenerator.WriteBlocklyMenuToXml(filename,categories,all_cmds)
end
function CodeBlocklyGenerator:GetAllVariableTypes()
local all_cmds = self:GetAllCmds();
local variable_type_maps = {};
for __,cmd in ipairs(all_cmds) do
for k = 0,self.arg_len do
local input_arg = cmd["arg".. k];
if(input_arg)then
for __,arg in ipairs(input_arg) do
if(arg.type == "field_variable")then
local variableTypes = arg.variableTypes;
if(variableTypes)then
local type;
for __, type in ipairs(variableTypes) do
variable_type_maps[type] = type;
end
end
end
end
end
end
end
return variable_type_maps;
end
function CodeBlocklyGenerator:GetCategoryStr(category)
local all_cmds = self:GetAllCmds();
if(not category or not all_cmds)then return end
local text = category.text;
local name = category.name;
local colour = category.colour or "#000000";
local custom = category.custom or "";
if(custom and custom ~= "")then
custom = string.format("custom='%s'",custom);
end
local s = string.format("<category name='%s' id='%s' colour='%s' secondaryColour='%s' %s >\n",text,name,colour,colour,custom);
local cmd
local bCreateVarBtn = false;
for __,cmd in ipairs(all_cmds) do
if(category.name == cmd.category and not cmd.hide_in_toolbox)then
if(category.name == "Data" or category.name == "NplMicroRobot.Data" )then
if(not bCreateVarBtn)then
local variable_type_maps = self:GetAllVariableTypes();
local type;
for __,type in pairs(variable_type_maps) do
local callbackKey;
if(type == "")then
callbackKey = "create_variable"
s = string.format("%s<button text='%s %s' type='%s' callbackKey='%s'></button>\n",s,L"创建变量", type, type, callbackKey);
else
callbackKey = "create_variable_" .. type
s = string.format("%s<button text='%s %s' type='%s' callbackKey='%s'></button>\n",s,L"创建变量 类型为:", type, type, callbackKey);
end
end
bCreateVarBtn = true;
end
end
local shadow = self:GetShadowStr(cmd);
s = string.format("%s<block type='%s'>%s</block>\n",s,cmd.type,shadow);
end
end
s = string.format("%s</category>",s);
return s;
end
-- check shadow table in arg0 -- arg9 from cmd
-- see definition here https://github.com/LLK/scratch-blocks/tree/develop/blocks_common
function CodeBlocklyGenerator:GetShadowStr(cmd)
if(not cmd)then
return "";
end
local shadow_configs = {
["math_number"] = "NUM",
["math_integer"] = "NUM",
["math_whole_number"] = "NUM",
["math_positive_number"] = "NUM",
["math_angle"] = "NUM",
["colour_picker"] = "COLOUR",
["matrix"] = "MATRIX",
["text"] = "TEXT",
}
local result = "";
for k = 0,self.arg_len do
local input_arg = cmd["arg".. k];
if(input_arg)then
for k,v in ipairs(input_arg) do
local shadow = v.shadow;
if(shadow and shadow.type)then
local shadow_type = shadow.type;
local value = shadow.value or "";
local filed_name = shadow_configs[shadow_type];
local s;
if(filed_name)then
s = string.format("<value name='%s'><shadow type='%s'><field name='%s'>%s</field></shadow></value>",v.name,shadow_type,filed_name,value);
else
s = string.format("<value name='%s'><shadow type='%s'></shadow></value>",v.name,shadow_type);
end
if(result == "")then
result = s;
else
result = result .. s;
end
end
end
end
end
return result;
end
function CodeBlocklyGenerator:GetBlocklyConfig()
local all_cmds = self:GetAllCmds();
local categories = self:GetCategoryButtons()
local c_map = {};
local k,v;
for k,v in ipairs(categories) do
local name = v.name;
c_map[name] = v;
end
all_cmds = commonlib.deepcopy(all_cmds)
for k,v in ipairs(all_cmds) do
local category = v.category;
if(not v.colour)then
local c_node = c_map[category];
-- set colour
v.colour = c_node.colour;
end
end
local s = NPL.ToJson(all_cmds,true);
return s;
end
function CodeBlocklyGenerator:GetBlocklyCode()
local all_cmds = self:GetAllCmds();
local s = "";
local cmd
for __,cmd in ipairs(all_cmds) do
local language;
for language,__ in pairs(self.language_names) do
local execution_str = self:GetBlockExecutionStr(cmd,language)
if(s == "")then
s = execution_str;
else
s = s .. "\n" .. execution_str;
end
end
end
return s;
end
-- translate a cmd to a full block function
function CodeBlocklyGenerator:GetBlockExecutionStr(cmd,language)
local type = cmd.type;
language = language or "lua";
local body = self:ArgsToStr(cmd,language);
local language_name = self:GetLanguageName(language);
if(language_name)then
local s = string.format([[
Blockly.%s['%s'] = function (block) {
%s
};]],language_name,type,body);
return s;
end
end
-- translate a cmd to a return value of block function
function CodeBlocklyGenerator:ArgsToStr(cmd,language)
local type = cmd.type
language = language or "lua";
local var_lines = "";
local arg_lines = "";
local k,v;
local prefix = type;
prefix = string.gsub(prefix,"%.","_")
-- read 10 args
for k = 0,self.arg_len do
local input_arg = cmd["arg".. k];
if(input_arg)then
for k,v in ipairs(input_arg) do
local _type = v.type;
if(_type and _type ~= "input_dummy")then
local var_str = self:ArgToJsStr_Variable(prefix,v,language)
local arg_str = self:Create_VariableName(prefix,v);
if(var_lines == "")then
var_lines = var_str;
arg_lines = arg_str;
else
var_lines = var_lines .. "\n" .. var_str;
arg_lines = arg_lines .. "," .. arg_str;
end
end
end
end
end
local language_name = self:GetLanguageName(language);
local func_name = self:GetFunctionName(language);
local func_description = cmd[func_name];
if(language == "python" or language == "javascript")then
-- get func_description from lua func_description if python/javascript func_description is nil
func_description = func_description or cmd[self:GetFunctionName("lua")];
end
local func_provider_name = self:GetFunctionProviderName(language);
local func_description_provider = cmd[func_provider_name];
if(func_description_provider)then
return func_description_provider;
end
local s;
if(func_description)then
local output = cmd.output;
if(output and output.type)then
s = string.format([[%s
return ['%s'.format(%s),Blockly.%s.ORDER_ATOMIC];]],var_lines,func_description,arg_lines,language_name);
else
s = string.format([[%s
return '%s\n'.format(%s);]],var_lines,func_description,arg_lines);
end
else
s = 'return ""';
end
return s;
end
-- translate a child item of arg[0-9] to a javascript execution
function CodeBlocklyGenerator:ArgToJsStr_Variable(prefix,arg,language)
local type = arg.type
local name = arg.name
local s;
local language_name = self:GetLanguageName(language);
if(language_name)then
local var_name = self:Create_VariableName(prefix,arg);
if(type == "input_statement")then
s = string.format([[ var %s = Blockly.%s.statementToCode(block, '%s') || '';]],var_name,language_name,name)
elseif(type == "input_value")then
s = string.format([[ var %s = Blockly.%s.valueToCode(block,'%s', Blockly.%s.ORDER_ATOMIC) || '""';]],var_name,language_name,name,language_name)
elseif(type == "field_variable")then
s = string.format([[ var %s = Blockly.%s.variableDB_.getName(block.getFieldValue('%s'), Blockly.Variables.NAME_TYPE) || '""';]],var_name,language_name,name)
elseif(type == "field_variable_getter")then
s = string.format([[ var %s = block.getField('%s').getText();]],var_name,name);
else
s = string.format([[ var %s = block.getFieldValue('%s');]],var_name,name);
end
return s;
end
end
-- create a unique name of variable
function CodeBlocklyGenerator:Create_VariableName(prefix,arg)
local type = arg.type
local name = arg.name
local s = string.format("%s_%s_%s_var",prefix,type,name);
return s;
end
| gpl-2.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/modules/base/luasrc/controller/admin/servicectl.lua | 76 | 1376 | --[[
LuCI - Lua Configuration Interface
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.admin.servicectl", package.seeall)
function index()
entry({"servicectl"}, alias("servicectl", "status")).sysauth = "root"
entry({"servicectl", "status"}, call("action_status")).leaf = true
entry({"servicectl", "restart"}, call("action_restart")).leaf = true
end
function action_status()
local data = nixio.fs.readfile("/var/run/luci-reload-status")
if data then
luci.http.write("/etc/config/")
luci.http.write(data)
else
luci.http.write("finish")
end
end
function action_restart(args)
local uci = require "luci.model.uci".cursor()
if args then
local service
local services = { }
for service in args:gmatch("[%w_-]+") do
services[#services+1] = service
end
local command = uci:apply(services, true)
if nixio.fork() == 0 then
local i = nixio.open("/dev/null", "r")
local o = nixio.open("/dev/null", "w")
nixio.dup(i, nixio.stdin)
nixio.dup(o, nixio.stdout)
i:close()
o:close()
nixio.exec("/bin/sh", unpack(command))
else
luci.http.write("OK")
os.exit(0)
end
end
end
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Selbina/npcs/Lombaria.lua | 1 | 1902 | -----------------------------------
-- Area: Selbina
-- NPC: Lombaria
-- Map Seller NPC
-----------------------------------
package.loaded["scripts/globals/quests"] = nil;
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Selbina/textids");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
mapVar = 0;
if player:hasKeyItem(MAP_OF_THE_SANDORIA_AREA) then
mapVar = mapVar + 4;
end
if player:hasKeyItem(MAP_OF_THE_BASTOK_AREA) then
mapVar = mapVar + 8;
end
if player:hasKeyItem(MAP_OF_THE_WINDURST_AREA) then
mapVar = mapVar + 16;
end
if player:hasKeyItem(MAP_OF_THE_JEUNO_AREA) then
mapVar = mapVar + 32;
end
player:startEvent(0x01f4, mapVar);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
keyItem = option;
gil = 0;
if (csid==0x01f4 and option ~= 1073741824) then
if option == MAP_OF_THE_SANDORIA_AREA then
gil = 200;
elseif option == MAP_OF_THE_BASTOK_AREA then
gil = 200;
elseif option == MAP_OF_THE_WINDURST_AREA then
gil = 200;
elseif option == MAP_OF_THE_JEUNO_AREA then
gil = 600;
end
if (gil > 0 and player:getGil() >= gil) then
player:setGil(player:getGil() - gil);
player:addKeyItem(option);
player:messageSpecial(KEYITEM_OBTAINED,keyItem);
end
end
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/san_dorian_carrot.lua | 1 | 1134 | -----------------------------------------
-- ID: 4389
-- Item: san_dorian_carrot
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility 2
-- Vitality -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,0,4389);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 2);
target:addMod(MOD_VIT, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 2);
target:delMod(MOD_VIT, -4);
end;
| gpl-3.0 |
TerminalShell/zombiesurvival | entities/weapons/weapon_zs_turret/cl_init.lua | 1 | 1342 | include("shared.lua")
SWEP.PrintName = "Gun Turret"
SWEP.Description = "This automated turret requires constant upkeep to be useful.\nPress PRIMARY ATTACK to deploy the turret.\nPress SECONDARY ATTACK and RELOAD to rotate the turret.\nPress USE on a deployed turret to give it some of your SMG ammunition.\nPress USE on a deployed turret with no owner (blue light) to reclaim it."
SWEP.DrawCrosshair = false
SWEP.Slot = 4
SWEP.SlotPos = 0
function SWEP:DrawHUD()
if GetConVarNumber("crosshair") ~= 1 then return end
self:DrawCrosshairDot()
end
function SWEP:Deploy()
self.IdleAnimation = CurTime() + self:SequenceDuration()
return true
end
function SWEP:DrawWorldModel()
end
SWEP.DrawWorldModelTranslucent = SWEP.DrawWorldModel
function SWEP:PrimaryAttack()
end
function SWEP:DrawWeaponSelection(...)
return self:BaseDrawWeaponSelection(...)
end
function SWEP:Think()
if self.Owner:KeyDown(IN_ATTACK2) then
self:RotateGhost(FrameTime() * 60)
end
if self.Owner:KeyDown(IN_RELOAD) then
self:RotateGhost(FrameTime() * -60)
end
end
local nextclick = 0
function SWEP:RotateGhost(amount)
if nextclick <= RealTime() then
surface.PlaySound("npc/headcrab_poison/ph_step4.wav")
nextclick = RealTime() + 0.3
end
RunConsoleCommand("_zs_ghostrotation", math.NormalizeAngle(GetConVarNumber("_zs_ghostrotation") + amount))
end
| gpl-3.0 |
zhutaorun/2DPlatformer-SLua | Assets/StreamingAssets/Lua/LPeg/re.lua | 160 | 6286 | -- $Id: re.lua,v 1.44 2013/03/26 20:11:40 roberto Exp $
-- imported functions and modules
local tonumber, type, print, error = tonumber, type, print, error
local setmetatable = setmetatable
local m = require"lpeg"
-- 'm' will be used to parse expressions, and 'mm' will be used to
-- create expressions; that is, 're' runs on 'm', creating patterns
-- on 'mm'
local mm = m
-- pattern's metatable
local mt = getmetatable(mm.P(0))
-- No more global accesses after this point
local version = _VERSION
if version == "Lua 5.2" then _ENV = nil end
local any = m.P(1)
-- Pre-defined names
local Predef = { nl = m.P"\n" }
local mem
local fmem
local gmem
local function updatelocale ()
mm.locale(Predef)
Predef.a = Predef.alpha
Predef.c = Predef.cntrl
Predef.d = Predef.digit
Predef.g = Predef.graph
Predef.l = Predef.lower
Predef.p = Predef.punct
Predef.s = Predef.space
Predef.u = Predef.upper
Predef.w = Predef.alnum
Predef.x = Predef.xdigit
Predef.A = any - Predef.a
Predef.C = any - Predef.c
Predef.D = any - Predef.d
Predef.G = any - Predef.g
Predef.L = any - Predef.l
Predef.P = any - Predef.p
Predef.S = any - Predef.s
Predef.U = any - Predef.u
Predef.W = any - Predef.w
Predef.X = any - Predef.x
mem = {} -- restart memoization
fmem = {}
gmem = {}
local mt = {__mode = "v"}
setmetatable(mem, mt)
setmetatable(fmem, mt)
setmetatable(gmem, mt)
end
updatelocale()
local I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end)
local function getdef (id, defs)
local c = defs and defs[id]
if not c then error("undefined name: " .. id) end
return c
end
local function patt_error (s, i)
local msg = (#s < i + 20) and s:sub(i)
or s:sub(i,i+20) .. "..."
msg = ("pattern error near '%s'"):format(msg)
error(msg, 2)
end
local function mult (p, n)
local np = mm.P(true)
while n >= 1 do
if n%2 >= 1 then np = np * p end
p = p * p
n = n/2
end
return np
end
local function equalcap (s, i, c)
if type(c) ~= "string" then return nil end
local e = #c + i
if s:sub(i, e - 1) == c then return e else return nil end
end
local S = (Predef.space + "--" * (any - Predef.nl)^0)^0
local name = m.R("AZ", "az", "__") * m.R("AZ", "az", "__", "09")^0
local arrow = S * "<-"
local seq_follow = m.P"/" + ")" + "}" + ":}" + "~}" + "|}" + (name * arrow) + -1
name = m.C(name)
-- a defined name only have meaning in a given environment
local Def = name * m.Carg(1)
local num = m.C(m.R"09"^1) * S / tonumber
local String = "'" * m.C((any - "'")^0) * "'" +
'"' * m.C((any - '"')^0) * '"'
local defined = "%" * Def / function (c,Defs)
local cat = Defs and Defs[c] or Predef[c]
if not cat then error ("name '" .. c .. "' undefined") end
return cat
end
local Range = m.Cs(any * (m.P"-"/"") * (any - "]")) / mm.R
local item = defined + Range + m.C(any)
local Class =
"["
* (m.C(m.P"^"^-1)) -- optional complement symbol
* m.Cf(item * (item - "]")^0, mt.__add) /
function (c, p) return c == "^" and any - p or p end
* "]"
local function adddef (t, k, exp)
if t[k] then
error("'"..k.."' already defined as a rule")
else
t[k] = exp
end
return t
end
local function firstdef (n, r) return adddef({n}, n, r) end
local function NT (n, b)
if not b then
error("rule '"..n.."' used outside a grammar")
else return mm.V(n)
end
end
local exp = m.P{ "Exp",
Exp = S * ( m.V"Grammar"
+ m.Cf(m.V"Seq" * ("/" * S * m.V"Seq")^0, mt.__add) );
Seq = m.Cf(m.Cc(m.P"") * m.V"Prefix"^0 , mt.__mul)
* (#seq_follow + patt_error);
Prefix = "&" * S * m.V"Prefix" / mt.__len
+ "!" * S * m.V"Prefix" / mt.__unm
+ m.V"Suffix";
Suffix = m.Cf(m.V"Primary" * S *
( ( m.P"+" * m.Cc(1, mt.__pow)
+ m.P"*" * m.Cc(0, mt.__pow)
+ m.P"?" * m.Cc(-1, mt.__pow)
+ "^" * ( m.Cg(num * m.Cc(mult))
+ m.Cg(m.C(m.S"+-" * m.R"09"^1) * m.Cc(mt.__pow))
)
+ "->" * S * ( m.Cg((String + num) * m.Cc(mt.__div))
+ m.P"{}" * m.Cc(nil, m.Ct)
+ m.Cg(Def / getdef * m.Cc(mt.__div))
)
+ "=>" * S * m.Cg(Def / getdef * m.Cc(m.Cmt))
) * S
)^0, function (a,b,f) return f(a,b) end );
Primary = "(" * m.V"Exp" * ")"
+ String / mm.P
+ Class
+ defined
+ "{:" * (name * ":" + m.Cc(nil)) * m.V"Exp" * ":}" /
function (n, p) return mm.Cg(p, n) end
+ "=" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end
+ m.P"{}" / mm.Cp
+ "{~" * m.V"Exp" * "~}" / mm.Cs
+ "{|" * m.V"Exp" * "|}" / mm.Ct
+ "{" * m.V"Exp" * "}" / mm.C
+ m.P"." * m.Cc(any)
+ (name * -arrow + "<" * name * ">") * m.Cb("G") / NT;
Definition = name * arrow * m.V"Exp";
Grammar = m.Cg(m.Cc(true), "G") *
m.Cf(m.V"Definition" / firstdef * m.Cg(m.V"Definition")^0,
adddef) / mm.P
}
local pattern = S * m.Cg(m.Cc(false), "G") * exp / mm.P * (-any + patt_error)
local function compile (p, defs)
if mm.type(p) == "pattern" then return p end -- already compiled
local cp = pattern:match(p, 1, defs)
if not cp then error("incorrect pattern", 3) end
return cp
end
local function match (s, p, i)
local cp = mem[p]
if not cp then
cp = compile(p)
mem[p] = cp
end
return cp:match(s, i or 1)
end
local function find (s, p, i)
local cp = fmem[p]
if not cp then
cp = compile(p) / 0
cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) }
fmem[p] = cp
end
local i, e = cp:match(s, i or 1)
if i then return i, e - 1
else return i
end
end
local function gsub (s, p, rep)
local g = gmem[p] or {} -- ensure gmem[p] is not collected while here
gmem[p] = g
local cp = g[rep]
if not cp then
cp = compile(p)
cp = mm.Cs((cp / rep + 1)^0)
g[rep] = cp
end
return cp:match(s)
end
-- exported names
local re = {
compile = compile,
match = match,
find = find,
gsub = gsub,
updatelocale = updatelocale,
}
if version == "Lua 5.1" then _G.re = re end
return re
| mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/maps/vaults/crypt.lua | 3 | 2578 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
setStatusAll{no_teleport=true}
defineTile(' ', "FLOOR")
defineTile('!', "DOOR_VAULT", nil, nil, nil, {room_map={special=false, room=false, can_open=true}})
defineTile('+', "DOOR")
defineTile('X', "HARDWALL")
defineTile('^', "FLOOR", {random_filter={add_levels=5,tome_mod="vault"}}, {random_filter={type="undead"}})
defineTile('u', "FLOOR", {random_filter={}}, {random_filter={type="undead", subtype="vampire", name="lesser vampire"}})
defineTile('v', "FLOOR", {random_filter={add_levels=5,tome_mod="vault"}}, {random_filter={add_levels=5, type="undead", subtype="vampire", name="vampire"}})
defineTile('U', "FLOOR", {random_filter={add_levels=10, tome_mod="gvault"}}, {random_filter={add_levels=10, type="undead", subtype="vampire", name="master vampire"}})
defineTile('V', "FLOOR", {random_filter={add_levels=15, tome_mod="gvault"}}, {random_filter={add_levels=15, type="undead", subtype="vampire", name="elder vampire"}})
defineTile('L', "FLOOR", {random_filter={add_levels=20, tome_mod="gvault"}}, {random_filter={add_levels=20, type="undead", subtype="vampire", name="vampire lord"}})
defineTile('W', "FLOOR", {random_filter={add_levels=15, tome_mod="gvault"}}, {random_filter={add_levels=15, type="undead", subtype="wight", name="grave wight"}})
startx = 0
starty = 6
rotates = {"default", "90", "180", "270", "flipx", "flipy"}
return {
[[XXXXXXXXXXXXXXXXXXXXXXXXXXXXX]],
[[XX^^^X^^^X^^^X^^^XXXXXXXXXXXX]],
[[XX^u^X^v^X^U^X^V^XXXX^WXXXXXX]],
[[XX^ ^X^ ^X^ ^X^ ^XXXX^ WXXXX]],
[[XXX XXX XXX XXX XXXXX^ XXXXXX]],
[[XXX+XXX+XXX+XXX+XXXXX^ LXXXX]],
[[! + XXXXXX]],
[[XXXXX+XXX+XXX+XXX+XXX^ LXXXX]],
[[XXXXX XXX XXX XXX XXX^ XXXXXX]],
[[XXXX^ ^X^ ^X^ ^X^ ^XX^ WXXXX]],
[[XXXX^u^X^v^X^U^X^V^XX^WXXXXXX]],
[[XXXX^^^X^^^X^^^X^^^XXXXXXXXXX]],
[[XXXXXXXXXXXXXXXXXXXXXXXXXXXXX]],
} | gpl-3.0 |
persaianbot/self | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/model/cbi/luci_statistics/netlink.lua | 78 | 2765 | --[[
Luci configuration model for statistics - collectd netlink plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
local devices = luci.sys.net.devices()
m = Map("luci_statistics",
translate("Netlink Plugin Configuration"),
translate(
"The netlink plugin collects extended informations like " ..
"qdisc-, class- and filter-statistics for selected interfaces."
))
-- collectd_netlink config section
s = m:section( NamedSection, "collectd_netlink", "luci_statistics" )
-- collectd_netlink.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_netlink.interfaces (Interface)
interfaces = s:option( MultiValue, "Interfaces", translate("Basic monitoring") )
interfaces.widget = "select"
interfaces.optional = true
interfaces.size = #devices + 1
interfaces:depends( "enable", 1 )
interfaces:value("")
for i, v in ipairs(devices) do
interfaces:value(v)
end
-- collectd_netlink.verboseinterfaces (VerboseInterface)
verboseinterfaces = s:option( MultiValue, "VerboseInterfaces", translate("Verbose monitoring") )
verboseinterfaces.widget = "select"
verboseinterfaces.optional = true
verboseinterfaces.size = #devices + 1
verboseinterfaces:depends( "enable", 1 )
verboseinterfaces:value("")
for i, v in ipairs(devices) do
verboseinterfaces:value(v)
end
-- collectd_netlink.qdiscs (QDisc)
qdiscs = s:option( MultiValue, "QDiscs", translate("Qdisc monitoring") )
qdiscs.widget = "select"
qdiscs.optional = true
qdiscs.size = #devices + 1
qdiscs:depends( "enable", 1 )
qdiscs:value("")
for i, v in ipairs(devices) do
qdiscs:value(v)
end
-- collectd_netlink.classes (Class)
classes = s:option( MultiValue, "Classes", translate("Shaping class monitoring") )
classes.widget = "select"
classes.optional = true
classes.size = #devices + 1
classes:depends( "enable", 1 )
classes:value("")
for i, v in ipairs(devices) do
classes:value(v)
end
-- collectd_netlink.filters (Filter)
filters = s:option( MultiValue, "Filters", translate("Filter class monitoring") )
filters.widget = "select"
filters.optional = true
filters.size = #devices + 1
filters:depends( "enable", 1 )
filters:value("")
for i, v in ipairs(devices) do
filters:value(v)
end
-- collectd_netlink.ignoreselected (IgnoreSelected)
ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") )
ignoreselected.default = 0
ignoreselected:depends( "enable", 1 )
return m
| gpl-2.0 |
NPLPackages/paracraft | script/kids/3DMapSystemApp/Assets/DlgPackage.lua | 1 | 4539 | --[[
Title: create and edit package dialog.
Note: can only be used with asset Manager
Author(s): LiXizhi
Date: 2008/1/31
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemApp/Assets/DlgPackage.lua");
Map3DSystem.App.Assets.ShowCreatePackageDlg()
Map3DSystem.App.Assets.ShowEditPackageDlg(package)
-------------------------------------------------------
]]
-- current package binding context
local bindingContext;
-- show the create package dialog
function Map3DSystem.App.Assets.ShowCreatePackageDlg()
-- create a new package.
local package = Map3DSystem.App.Assets.CreatePackage({text="未命名资源包"});
bindingContext = commonlib.BindingContext:new();
bindingContext:AddBinding(package, "text", "AssetManager.NewAsset#packageName", commonlib.Binding.ControlTypes.ParaUI_editbox, "text")
bindingContext:AddBinding(package, "icon", "AssetManager.NewAsset#textBoxIconPath", commonlib.Binding.ControlTypes.ParaUI_editbox, "text")
bindingContext:AddBinding(package, "Category", "AssetManager.comboBoxCategory", commonlib.Binding.ControlTypes.IDE_dropdownlistbox, "text")
bindingContext:AddBinding(package, "bDisplayInMainBar", "AssetManager.checkBoxShowInMainbar", commonlib.Binding.ControlTypes.IDE_checkbox, "value")
_guihelper.ShowDialogBox("新建资源包", nil, nil, 263, 114,
Map3DSystem.App.Assets.CreateEditPackageDlg,
function(dialogResult)
if(dialogResult == _guihelper.DialogResult.OK) then
bindingContext:UpdateControlsToData();
-- add to package list and update UI controls.
Map3DSystem.App.Assets.AddPackage(package);
Map3DSystem.App.Assets.SelectPackage(package);
Map3DSystem.App.Assets.AssetManager.UpdateComboBoxSelectPkg();
Map3DSystem.App.Assets.AssetManager.RebuildAssetsTreeView();
end
return true;
end)
end
-- show the edit package dialog
function Map3DSystem.App.Assets.ShowEditPackageDlg(package)
bindingContext = commonlib.BindingContext:new();
bindingContext:AddBinding(package, "text", "AssetManager.NewAsset#packageName", commonlib.Binding.ControlTypes.ParaUI_editbox, "text")
bindingContext:AddBinding(package, "icon", "AssetManager.NewAsset#textBoxIconPath", commonlib.Binding.ControlTypes.ParaUI_editbox, "text")
bindingContext:AddBinding(package, "Category", "AssetManager.comboBoxCategory", commonlib.Binding.ControlTypes.IDE_dropdownlistbox, "text")
bindingContext:AddBinding(package, "bDisplayInMainBar", "AssetManager.checkBoxShowInMainbar", commonlib.Binding.ControlTypes.IDE_checkbox, "value")
_guihelper.ShowDialogBox("编辑资源包", nil, nil, 263, 114,
Map3DSystem.App.Assets.CreateEditPackageDlg,
function(dialogResult)
if(dialogResult == _guihelper.DialogResult.OK) then
bindingContext:UpdateControlsToData();
-- add to package list and update UI controls.
Map3DSystem.App.Assets.AssetManager.UpdateComboBoxSelectPkg();
Map3DSystem.App.Assets.AssetManager.UpdateAssetsTreeView();
end
return true;
end)
end
-- create the dialog
function Map3DSystem.App.Assets.CreateEditPackageDlg(_parent)
_this = ParaUI.CreateUIObject("container", "AssetManager.NewAsset", "_fi", 0,0,0,0)
_this.background = "";
_parent:AddChild(_this);
_parent = _this;
_this = ParaUI.CreateUIObject("text", "label4", "_lt", 3, 35, 42, 14)
_this.text = "类型:";
_parent:AddChild(_this);
_this = ParaUI.CreateUIObject("text", "label9", "_lt", 3, 61, 42, 14)
_this.text = "图标:";
_parent:AddChild(_this);
_this = ParaUI.CreateUIObject("text", "label5", "_lt", 3, 6, 70, 14)
_this.text = "资源名称:";
_parent:AddChild(_this);
_this = ParaUI.CreateUIObject("editbox", "packageName", "_mt", 85, 3, 3, 23)
_parent:AddChild(_this);
_this = ParaUI.CreateUIObject("editbox", "textBoxIconPath", "_mt", 85, 58, 3, 23)
_parent:AddChild(_this);
NPL.load("(gl)script/ide/dropdownlistbox.lua");
local ctl = CommonCtrl.dropdownlistbox:new{
name = "AssetManager.comboBoxCategory",
alignment = "_mt",
left = 85,
top = 32,
width = 3,
height = 22,
dropdownheight = 106,
parent = _parent,
text = "",
items = {"Creations.BCS.doors", "Creations.BCS.windows", "Creations.Normals.Trees", },
};
ctl:Show();
NPL.load("(gl)script/ide/CheckBox.lua");
local ctl = CommonCtrl.checkbox:new{
name = "AssetManager.checkBoxShowInMainbar",
alignment = "_lt",
left = 3,
top = 91,
width = 166,
height = 18,
parent = _parent,
isChecked = false,
text = "添加到我的创作工具栏",
};
ctl:Show();
bindingContext:UpdateDataToControls();
end | gpl-2.0 |
rigeirani/sss | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
madpilot78/ntopng | scripts/lua/modules/alert_definitions/other/alert_dropped_alerts.lua | 1 | 1867 | --
-- (C) 2019-21 - ntop.org
--
-- ##############################################
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
local other_alert_keys = require "other_alert_keys"
-- Import the classes library.
local classes = require "classes"
-- Make sure to import the Superclass!
local alert = require "alert"
local alert_entities = require "alert_entities"
-- ##############################################
local alert_dropped_alerts = classes.class(alert)
alert_dropped_alerts.meta = {
alert_key = other_alert_keys.alert_dropped_alerts,
i18n_title = i18n("show_alerts.dropped_alerts"),
icon = "fas fa-fw fa-exclamation-triangle",
entities = {
alert_entities.system,
alert_entities.interface,
},
}
-- ##############################################
function alert_dropped_alerts:init(ifid, num_dropped)
-- Call the parent constructor
self.super:init()
self.alert_type_params = {
ifid = ifid,
num_dropped = num_dropped,
}
end
-- #######################################################
-- @brief Format an alert into a human-readable string
-- @param ifid The integer interface id of the generated alert
-- @param alert The alert description table, including alert data such as the generating entity, timestamp, granularity, type
-- @param alert_type_params Table `alert_type_params` as built in the `:init` method
-- @return A human-readable string
function alert_dropped_alerts.format(ifid, alert, alert_type_params)
return(i18n("alert_messages.iface_alerts_dropped", {
iface = getHumanReadableInterfaceName(alert_type_params.ifid),
num_dropped = alert_type_params.num_dropped,
url = ntop.getHttpPrefix() .. "/lua/if_stats.lua?ifid=" .. alert_type_params.ifid
}))
end
-- #######################################################
return alert_dropped_alerts
| gpl-3.0 |
fegimanam/s | plugins/ingroup.lua | 527 | 44020 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
Grocel/wire-extras | lua/autorun/widgets/rect.lua | 3 | 1632 | ------------------------------------------------- Vertical Line ----------------------------------------------------------
panelWidget["rect"] = {
name = "rect",
realName = "Rectangle",
wireType = 0,
paramTable = { red = {index = 1, default = 120, realName = "Red:", stool = {stype = 1, smin = 1, smax = 255, ntype = 1}},
green = {index = 2, default = 120, realName = "Green:", stool = {stype = 1, smin = 1, smax = 255, ntype = 1}},
blue = {index = 3, default = 120, realName = "Blue:", stool = {stype = 1, smin = 1, smax = 255, ntype = 1}}},
modInit = function (widget)
if widget.paramTable[1] then
widget.red = tonumber(widget.paramTable[1])
else
widget.red = widget.modType.paramTable.red.default
end
if widget.paramTable[2] then
widget.green = tonumber(widget.paramTable[2])
else
widget.green = widget.modType.paramTable.green.default
end
if widget.paramTable[3] then
widget.blue = tonumber(widget.paramTable[3])
else
widget.blue = widget.modType.paramTable.blue.default
end
end,
modDraw = function (ent, widget)
surface.SetDrawColor(widget.red, widget.green, widget.blue, 255)
local x1 = (widget.X * ent.XdrawCoef) + ent.XdrawOffs
local y1 = (widget.Y * ent.YdrawCoef) + ent.YdrawOffs
local w = widget.W * ent.XdrawCoef
local h = widget.H * ent.YdrawCoef
surface.DrawRect(x1, y1, w, h)
end,
modClicked = function (ply, widget, Xpos, Ypos)
end,
modThink = nil,
triggerInput = function (widget, inIndex, value)
end,
inputs = nil,
outputs = nil,
}
| apache-2.0 |
artynet/openwrt-packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/bmx6.lua | 78 | 1115 | #!/usr/bin/lua
local json = require "cjson"
local function interpret_suffix(rate)
local value = string.sub(rate, 1, -2)
local suffix = string.sub(rate, -1)
if suffix == "K" then return tonumber(value) * 10^3 end
if suffix == "M" then return tonumber(value) * 10^6 end
if suffix == "G" then return tonumber(value) * 10^9 end
return rate
end
local function scrape()
local status = json.decode(get_contents("/var/run/bmx6/json/status")).status
local labels = {
version = status.version,
id = status.name,
address = status.primaryIp
}
metric("bmx6_status", "gauge", labels, 1)
local links = json.decode(get_contents("/var/run/bmx6/json/links")).links
local metric_bmx6_rxRate = metric("bmx6_link_rxRate","gauge")
local metric_bmx6_txRate = metric("bmx6_link_txRate","gauge")
for _, link in pairs(links) do
local labels = {
source = status.name,
target = link.name,
dev = link.viaDev
}
metric_bmx6_rxRate(labels, interpret_suffix(link.rxRate))
metric_bmx6_txRate(labels, interpret_suffix(link.txRate))
end
end
return { scrape = scrape }
| gpl-2.0 |
madpilot78/ntopng | scripts/plugins/endpoints/sqlite_alert_endpoint/alert_endpoints/sqlite.lua | 1 | 3263 | --
-- (C) 2021 - ntop.org
--
package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path
require "lua_utils"
local json = require "dkjson"
local alerts_api = require "alerts_api"
local alert_consts = require "alert_consts"
local sqlite = {
name = "SQLite",
builtin = true, -- Whether this endpoint can be configured from the UI. Disabled for the builtin SQLite
endpoint_params = {
-- No params, SQLite is builtin
},
endpoint_template = {
plugin_key = "sqlite_alert_endpoint",
template_name = "sqlite_endpoint.template"
},
recipient_params = {
},
recipient_template = {
plugin_key = "sqlite_alert_endpoint",
template_name = "sqlite_recipient.template"
},
}
sqlite.EXPORT_FREQUENCY = 1
sqlite.prio = 400
-- ##############################################
local function recipient2sendMessageSettings(recipient)
local settings = {
-- builtin
}
return settings
end
-- ##############################################
-- Cache alert store to avoid always allocating new instances
local cached_alert_store = {}
local function get_alert_store(entity_id)
local alert_entity = alert_consts.alertEntityById(entity_id)
if not alert_entity then
return nil
end
local alert_store_name = alert_entity.alert_store_name
if not cached_alert_store[alert_store_name] then
local alert_store = require(alert_store_name.."_alert_store").new()
cached_alert_store[alert_store_name] = alert_store
end
return cached_alert_store[alert_store_name]
end
-- ##############################################
function sqlite.dequeueRecipientAlerts(recipient, budget, high_priority)
local more_available = true
local budget_used = 0
-- Now also check for alerts pushed by checks from Lua
-- Dequeue alerts up to budget
-- Note: in this case budget is the number of sqlite alerts to insert into the queue
while budget_used <= budget and more_available do
local notifications = {}
for i=1, budget do
local notification = ntop.recipient_dequeue(recipient.recipient_id, high_priority)
if notification then
notifications[#notifications + 1] = notification.alert
else
break
end
end
if not notifications or #notifications == 0 then
more_available = false
break
end
for _, json_message in ipairs(notifications) do
local alert = json.decode(json_message)
if alert.action ~= "engage" then
-- Do not store alerts engaged - they're are handled only in-memory
if(alert) then
interface.select(string.format("%d", alert.ifid))
local alert_store = get_alert_store(alert.entity_id)
if alert_store then
alert_store:insert(alert)
end
end
end
end
-- Remove the processed messages from the queue
budget_used = budget_used + #notifications
end
return {success = true, more_available = more_available}
end
-- ##############################################
function sqlite.runTest(recipient)
return false, "Not implemented"
end
-- ##############################################
return sqlite
| gpl-3.0 |
lingchenmsot/OpenObjectRecognition | DeepMask/trainMeters.lua | 3 | 3828 | --[[----------------------------------------------------------------------------
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
Contains the tree metrics used during training/evaluation:
- lossmeter: measure the average loss.
- binarymeter: measure error of predicted objectness score and ground truth
objectness annotation.
- ioumeter: measure iou between infered and ground truth masks.
------------------------------------------------------------------------------]]
--------------------------------------------------------------------------------
-- loss meter
do
local LossMeter = torch.class('LossMeter')
-- init
function LossMeter:__init()
self:reset()
end
-- function: reset
function LossMeter:reset()
self.sum = 0; self.n = 0
end
-- function: add
function LossMeter:add(value,n)
n = n or 1
self.sum = self.sum + value
self.n = self.n + n
end
-- function: value
function LossMeter:value()
return self.sum / self.n
end
end
--------------------------------------------------------------------------------
-- binary meter
do
local BinaryMeter = torch.class('BinaryMeter')
-- init
function BinaryMeter:__init()
self:reset()
end
-- function: reset
function BinaryMeter:reset()
self.acc = 0; self.n = 0
end
-- function: add
function BinaryMeter:add(output, target)
target, output = target:squeeze(), output:squeeze()
assert(output:nElement() == target:nElement(),
'target and output do not match')
local acc = torch.cmul(output,target)
self.acc = self.acc + acc:ge(0):sum()
self.n = self.n + output:size(1)
end
-- function: value
function BinaryMeter:value()
local res = self.acc/self.n
return res*100
end
end
--------------------------------------------------------------------------------
-- iou meter
do
local IouMeter = torch.class('IouMeter')
-- init
function IouMeter:__init(thr,sz)
self.sz = sz
self.iou = torch.Tensor(sz)
self.thr = math.log(thr/(1-thr))
self:reset()
end
-- function: reset
function IouMeter:reset()
self.iou:zero(); self.n = 0
end
-- function: add
function IouMeter:add(output, target)
target, output = target:squeeze():float(), output:squeeze():float()
assert(output:nElement() == target:nElement(),
'target and output do not match')
local batch,h,w = output:size(1),output:size(2),output:size(3)
local nOuts = h*w
local iouptr = self.iou:data()
local int,uni
local pred = output:ge(self.thr)
local pPtr,tPtr = pred:data(), target:data()
for b = 0,batch-1 do
int,uni = 0,0
for i = 0,nOuts-1 do
local id = b*nOuts+i
if pPtr[id] == 1 and tPtr[id] == 1 then int = int + 1 end
if pPtr[id] == 1 or tPtr[id] == 1 then uni = uni + 1 end
end
if uni > 0 then iouptr[self.n+b] = int/uni end
end
self.n = self.n + batch
end
-- function: value
function IouMeter:value(s)
if s then
local res
local nb = math.max(self.iou:ne(0):sum(),1)
local iou = self.iou:narrow(1,1,nb)
if s == 'mean' then
res = iou:mean()
elseif s == 'median' then
res = iou:median():squeeze()
elseif tonumber(s) then
local iouSort, _ = iou:sort()
res = iouSort:ge(tonumber(s)):sum()/nb
elseif s == 'hist' then
res = torch.histc(iou,20)/nb
end
return res*100
else
local value = {}
for _,s in ipairs(self.stats) do
value[s] = self:value(s)
end
return value
end
end
end
| apache-2.0 |
RyMarq/Zero-K | units/hoverminer.lua | 1 | 3188 | return { hoverminer = {
unitname = [[hoverminer]],
name = [[Dampener]],
description = [[Minelaying Hover]],
acceleration = 0.2175,
brakeRate = 2.05,
buildCostMetal = 200,
builder = false,
buildPic = [[hoverminer.png]],
canGuard = true,
canMove = true,
canPatrol = true,
category = [[HOVER]],
corpse = [[DEAD]],
customParams = {
modelradius = [[25]],
},
explodeAs = [[BIG_UNITEX]],
footprintX = 3,
footprintZ = 3,
iconType = [[hoverskirm]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 400,
maxSlope = 18,
maxVelocity = 2.1,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[HOVER3]],
moveState = 0,
noAutoFire = false,
noChaseCategory = [[TERRAFORM SATELLITE SUB]],
objectName = [[hoverminer.s3o]],
selfDestructAs = [[BIG_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:HEAVYHOVERS_ON_GROUND]],
},
},
sightDistance = 484,
turninplace = 0,
turnRate = 500,
workerTime = 0,
weapons = {
{
def = [[MINE]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]],
},
},
weaponDefs = {
MINE = {
name = [[Light Mine]],
accuracy = 1600,
avoidFriendly = false,
avoidNeutral = false,
burnblow = true,
collideEnemy = false,
collideFriendly = false,
collideNeutral = false,
craterBoost = 0,
craterMult = 0,
customParams = {
spawns_name = "wolverine_mine",
spawns_expire = 60,
},
damage = {
default = 20,
planes = 20,
subs = 0.5,
},
explosionGenerator = [[custom:teleport_progress]],
impulseBoost = 0,
impulseFactor = 0,
impactOnly = true,
interceptedByShieldType = 0,
--model = [[logmine.s3o]],
noSelfDamage = true,
range = 300,
reloadtime = 5,
size = 0,
soundHit = [[misc/teleport]],
--soundStart = [[misc/teleport2]],
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 2000,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[hoverminer_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
} }
| gpl-2.0 |
mpwillson/mal | lua/reader.lua | 14 | 3968 | local rex = require('rex_pcre')
local string = require('string')
local table = require('table')
local types = require('types')
local throw, Nil, Symbol, List = types.throw, types.Nil,
types.Symbol, types.List
local M = {}
Reader = {}
function Reader:new(tokens)
local newObj = {tokens = tokens, position = 1}
self.__index = self
return setmetatable(newObj, self)
end
function Reader:next()
self.position = self.position + 1
return self.tokens[self.position-1]
end
function Reader:peek()
return self.tokens[self.position]
end
function M.tokenize(str)
local results = {}
local re_pos = 1
local re = rex.new("[\\s,]*(~@|[\\[\\]{}()'`~^@]|\"(?:\\\\.|[^\\\\\"])*\"|;[^\n]*|[^\\s\\[\\]{}('\"`,;)]*)", rex.flags().EXTENDED)
while true do
local s, e, t = re:exec(str, re_pos)
if not s or s > e then break end
re_pos = e + 1
local val = string.sub(str,t[1],t[2])
if string.sub(val,1,1) ~= ";" then
table.insert(results, val)
end
end
return results
end
function M.read_atom(rdr)
local int_re = rex.new("^-?[0-9]+$")
local float_re = rex.new("^-?[0-9][0-9.]*$")
local token = rdr:next()
if int_re:exec(token) then return tonumber(token)
elseif float_re:exec(token) then return tonumber(token)
elseif string.sub(token,1,1) == '"' then
local sval = string.sub(token,2,string.len(token)-1)
sval = string.gsub(sval, '\\"', '"')
sval = string.gsub(sval, '\\n', '\n')
sval = string.gsub(sval, '\\\\', '\\')
return sval
elseif string.sub(token,1,1) == ':' then
return "\177" .. string.sub(token,2)
elseif token == "nil" then return Nil
elseif token == "true" then return true
elseif token == "false" then return false
else return Symbol:new(token)
end
end
function M.read_sequence(rdr, start, last)
local ast = {}
local token = rdr:next()
if token ~= start then throw("expected '"..start.."'") end
token = rdr:peek()
while token ~= last do
if not token then throw("expected '"..last.."', got EOF") end
table.insert(ast, M.read_form(rdr))
token = rdr:peek()
end
rdr:next()
return ast
end
function M.read_list(rdr)
return types.List:new(M.read_sequence(rdr, '(', ')'))
end
function M.read_vector(rdr)
return types.Vector:new(M.read_sequence(rdr, '[', ']'))
end
function M.read_hash_map(rdr)
local seq = M.read_sequence(rdr, '{', '}')
return types._assoc_BANG(types.HashMap:new(), unpack(seq))
end
function M.read_form(rdr)
local token = rdr:peek()
if "'" == token then
rdr:next()
return List:new({Symbol:new('quote'), M.read_form(rdr)})
elseif '`' == token then
rdr:next()
return List:new({Symbol:new('quasiquote'), M.read_form(rdr)})
elseif '~' == token then
rdr:next()
return List:new({Symbol:new('unquote'), M.read_form(rdr)})
elseif '~@' == token then
rdr:next()
return List:new({Symbol:new('splice-unquote'), M.read_form(rdr)})
elseif '^' == token then
rdr:next()
local meta = M.read_form(rdr)
return List:new({Symbol:new('with-meta'), M.read_form(rdr), meta})
elseif '@' == token then
rdr:next()
return List:new({Symbol:new('deref'), M.read_form(rdr)})
elseif ')' == token then throw("unexpected ')'")
elseif '(' == token then return M.read_list(rdr)
elseif ']' == token then throw("unexpected ']'")
elseif '[' == token then return M.read_vector(rdr)
elseif '}' == token then throw("unexpected '}'")
elseif '{' == token then return M.read_hash_map(rdr)
else return M.read_atom(rdr)
end
end
function M.read_str(str)
local tokens = M.tokenize(str)
if #tokens == 0 then error(nil) end
return M.read_form(Reader:new(tokens))
end
return M
| mpl-2.0 |
madpilot78/ntopng | scripts/lua/country_details.lua | 1 | 2441 | --
-- (C) 2013-21 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local graph_utils = require "graph_utils"
local page_utils = require("page_utils")
local country = _GET["country"]
local page = _GET["page"]
interface.select(ifname)
local ifstats = interface.getStats()
local ifId = ifstats.id
local ts_utils = require("ts_utils")
sendHTTPContentTypeHeader('text/html')
page_utils.set_active_menu_entry(page_utils.menu_entries.countries)
dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua")
if(country == nil) then
print("<div class=\"alert alert alert-danger\"><i class='fas fa-exclamation-triangle fa-lg fa-ntopng-warning'></i> ".. i18n("country_details.country_parameter_missing_message") .. "</div>")
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
return
end
if(not ts_utils.exists("country:traffic", {ifid=ifId, country=country})) then
print("<div class=\"alert alert alert-danger\"><i class='fas fa-exclamation-triangle fa-lg fa-ntopng-warning'></i> " .. i18n("country_details.no_available_stats_for_country",{country=country}) .. "</div>")
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
return
end
--[[
Create Menu Bar with buttons
--]]
local nav_url = ntop.getHttpPrefix().."/lua/country_details.lua?country="..country
local title = i18n("country_details.country") .. ": "..country
page_utils.print_navbar(title, nav_url,
{
{
active = page == "historical" or not page,
page_name = "historical",
label = "<i class='fas fa-lg fa-chart-area'></i>",
},
}
)
--[[
Selectively render information pages
--]]
if page == "historical" then
local schema = _GET["ts_schema"] or "country:traffic"
local selected_epoch = _GET["epoch"] or ""
local url = ntop.getHttpPrefix()..'/lua/country_details.lua?ifid='..ifId..'&country='..country..'&page=historical'
local tags = {
ifid = ifId,
country = country,
}
graph_utils.drawGraphs(ifId, schema, tags, _GET["zoom"], url, selected_epoch, {
timeseries = {
{schema="country:traffic", label=i18n("traffic"), split_directions = true --[[ split RX and TX directions ]]},
{schema="country:score", label=i18n("score"), split_directions = true},
}
})
end
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
| gpl-3.0 |
abasshacker/abbasgh | plugins/google.lua | 336 | 1323 | do
local function googlethat(query)
local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&'
local parameters = 'q='..(URL.escape(query) or '')
-- Do the request
local res, code = https.request(url..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=''
i = 0
for key,val in ipairs(results) do
i = i+1
stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n'
end
return stringresults
end
local function run(msg, matches)
-- comment this line if you want this plugin works in private message.
if not is_chat_msg(msg) then return nil end
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = 'Returns five results from Google. Safe search is enabled by default.',
usage = ' !google [terms]: Searches Google and send results',
patterns = {
'^!google (.*)$',
'^%.[g|G]oogle (.*)$'
},
run = run
}
end
| gpl-2.0 |
Grocel/wire-extras | lua/weapons/gmod_tool/stools/wire_adv_hud_indicator_2.lua | 2 | 5415 | TOOL.Category = "Wire Extras/Visuals/Indicators"
TOOL.Name = "Adv. Hud Indicator 2"
TOOL.Command = nil
TOOL.ConfigName = ""
if ( CLIENT ) then
language.Add( "Tool_wire_adv_hud_indicator_2_name", "Adv. HUD Indicator 2 ! (Wire)" )
language.Add( "Tool_wire_adv_hud_indicator_2_desc", "Spawns an Adv. HUD Indicator 2 for use with the wire system." )
language.Add( "Tool_wire_adv_hud_indicator_2_0", "Primary: Create/Update Hud Indicator Secondary: Hook/Unhook a HUD Indicator" )
language.Add( "Tool_wire_adv_hud_indicator_2_1", "Now use Reload on a vehicle to link this HUD Indicator to it, or on the same HUD Indicator to unlink it" )
language.Add( "Tool_wire_adv_hud_menu_showEditor", "Open the HML Editor" )
language.Add( "undone_gmod_wire_hud_indicator_2", "Undone Wire Adv. HUD Indicator 2" )
end
//--Runs SERVERSIDE--//
function TOOL:LeftClick( trace )
if (CLIENT) then return true end
if trace.Entity:IsPlayer() then return false end
local player = self:GetOwner()
local model = "models/jaanus/wiretool/wiretool_siren.mdl"
local position = trace.HitPos
local material = "models/debug/debugwhite"
local ent = nil
local hmlCode = self:GetClientInfo( "hml_code" )
--Angle and correction--
local angle = trace.HitNormal:Angle()
angle.pitch = angle.pitch + 90
-- If we've clicked an already active SENT...
if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_hud_indicator_2" && trace.Entity.pl == ply ) then
ent = trace.Entity
-- Update code here! FIXME!
else
-- Build the entity, and set its parameters
ent = BuildWireAdvHudIndicator2( player, model, angle, position, material )
if(ent == false) then return false end
end
local const = WireLib.Weld(ent, trace.Entity, trace.PhysicsBone, true)
undo.Create("gmod_wire_hud_indicator_2")
undo.AddEntity( ent )
undo.AddEntity( const )
undo.SetPlayer( player )
undo.Finish()
//-- Now that we have an entity, invoke its owner to send us code!
player:SendLua("HUD2_uploadCode(" .. ent:EntIndex() .. ")")
return true
end
if SERVER then
function BuildWireAdvHudIndicator2( pl, Model, Ang, Pos, material, hml )
local sent = ents.Create( "gmod_wire_hud_indicator_2" )
if( sent:IsValid() ) then
sent:SetModel( Model )
sent:SetMaterial( material )
sent:SetAngles( Ang )
sent:SetPos( Pos )
sent:Spawn()
local phys = sent:GetPhysicsObject()
if ( phys:IsValid() ) then
phys:EnableCollisions(true)
end
//-- Breaks for some reason...?
//--pl:AddCount( "wire_adv_indicators", wire_adv_indicator )
print("<HML>: ", hml )
--sent:RegisterPlayer( pl )
sent:ReloadCode( hml or "" ) //-- DONT SEND NIL HML! --//
return sent
end
Msg("[WW] Got a nil entity!\n")
return false
end
duplicator.RegisterEntityClass("gmod_wire_hud_indicator_2", BuildWireAdvHudIndicator2, "Model", "Ang", "Pos", "material" )
end
function TOOL:RightClick( trace )
if trace.Entity:IsPlayer() then return false end
local player = self:GetOwner()
if (trace.Entity && trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_hud_indicator_2") then
local sent = trace.Entity
sent:ToggleHooked( player )
return true
end
return false
end
// Hook HUD Indicator to vehicle
function TOOL:Reload( trace )
if (!trace.Entity || !trace.Entity:IsValid()) then return false end
if trace.Entity:IsPlayer() then return false end
if (CLIENT) then return true end
local iNum = self:NumObjects()
if (iNum == 0) then
if (trace.Entity:GetClass() != "gmod_wire_hud_indicator_2") then
WireLib.AddNotify(self:GetOwner(), "You must select a HUD Indicator to link first.", NOTIFY_GENERIC, 7)
return false
end
local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone )
self:SetObject( 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal )
self:SetStage(1)
elseif (iNum == 1) then
if (trace.Entity != self:GetEnt(1)) then
if (!string.find(trace.Entity:GetClass(), "prop_vehicle_")) then
WireLib.AddNotify(self:GetOwner(), "HUD Indicators can only be linked to vehicles.", NOTIFY_GENERIC, 7)
self:ClearObjects()
self:SetStage(0)
return false
end
local ent = self:GetEnt(1)
local bool = ent:GetTable():LinkVehicle(trace.Entity)
if (!bool) then
WireLib.AddNotify(self:GetOwner(), "Could not link HUD Indicator!", NOTIFY_GENERIC, 7)
return false
end
WireLib.AddNotify(self:GetOwner(), "HUD Linked!", NOTIFY_GENERIC, 5)
else
// Unlink HUD Indicator from this vehicle
trace.Entity:GetTable():UnLinkVehicle()
WireLib.AddNotify(self:GetOwner(), "HUD UnLinked!", NOTIFY_GENERIC, 5)
end
self:ClearObjects()
self:SetStage(0)
end
return true
end
function TOOL:Holster()
self:ReleaseGhostEntity()
self:GetWeapon():SetNWBool("HUDIndicatorCheckRegister", false)
end
function TOOL.BuildCPanel( panel )
panel:ClearControls()
panel:AddControl("Header", { Text = "#Tool_wire_adv_hud_menu_name", Description = "#Tool_wire_adv_hud_menu_desc" })
panel:AddControl("Label", { Text = "HML is loaded to the entity from whatever is open in the editor."})
panel:AddControl("Button", {
Label = "#Tool_wire_adv_hud_menu_showEditor",
Text = "Open Editor",
Command = "openH2Editor"
})
panel:AddControl("Label", {
Text = ""
})
panel:AddControl("CheckBox", {
Label = "Show stats?",
Command = "HUD2_showStats"
})
end
| apache-2.0 |
pakoito/ToME---t-engine4 | game/engines/default/modules/boot/data/general/npcs/canine.lua | 3 | 2339 | -- ToME - Tales of Middle-Earth
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- last updated: 5:11 PM 1/29/2010
newEntity{
define_as = "BASE_NPC_CANINE",
type = "animal", subtype = "canine",
display = "C", color=colors.WHITE,
level_range = {1, nil}, exp_worth = 1,
ai = "dumb_talented_simple", ai_state = { talent_in=2, },
energy = { mod=1.1 },
combat = { dammod={str=0.6} },
combat_armor = 1, combat_def = 1,
}
newEntity{ base = "BASE_NPC_CANINE",
name = "wolf", color=colors.UMBER, image="npc/canine_w.png",
desc = [[Lean, mean, and shaggy, it stares at you with hungry eyes.]],
rarity = 1,
max_life = resolvers.rngavg(40,70),
combat_armor = 1, combat_def = 3,
combat = { dam=5, atk=15, apr=3 },
}
newEntity{ base = "BASE_NPC_CANINE",
name = "white wolf", color=colors.WHITE, image="npc/canine_ww.png",
desc = [[A large and muscled wolf from the northern wastes. Its breath is cold and icy and its fur coated in frost.]],
rarity = 3,
max_life = resolvers.rngavg(70,100),
combat_armor = 3, combat_def = 4,
combat = { dam=8, atk=15, apr=3 },
}
newEntity{ base = "BASE_NPC_CANINE",
name = "warg", color=colors.BLACK, image="npc/canine_warg.png",
desc = [[It is a large wolf with eyes full of cunning.]],
rarity = 4,
max_life = resolvers.rngavg(60,100),
combat_armor = 5, combat_def = 7,
combat = { dam=10, atk=17, apr=5 },
}
newEntity{ base = "BASE_NPC_CANINE",
name = "fox", color=colors.RED, image="npc/canine_fox.png",
desc = [[The quick brown fox jumps over the lazy dog.]],
rarity = 3,
max_life = resolvers.rngavg(40,50),
combat_armor = 1, combat_def = 3,
combat = { dam=4, atk=10, apr=3 },
}
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Code/CodePyToNplPage.lua | 1 | 2272 | --[[
Title: CodePyToNplPage
Author(s): leio
Date: 2019.9.24
Desc:
checking convert python to npl codes
this conversion is depend on https://github.com/tatfook/PyRuntime
set command line args to test: pytonpl="true"
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodePyToNplPage.lua");
local CodePyToNplPage = commonlib.gettable("MyCompany.Aries.Game.Code.CodePyToNplPage");
CodePyToNplPage.ShowPage();
------------------------------------------------------------
]]
local CodePyToNplPage = commonlib.gettable("MyCompany.Aries.Game.Code.CodePyToNplPage");
CodePyToNplPage.codes = "";
CodePyToNplPage.page = nil;
function CodePyToNplPage.OnInit()
CodePyToNplPage.page = document.GetPageCtrl();
end
function CodePyToNplPage.ShowPage(codes,callback)
CodePyToNplPage.codes = codes;
CodePyToNplPage.callback = callback;
local params = {
url = "script/apps/Aries/Creator/Game/Code/CodePyToNplPage.html",
name = "CodePyToNplPage.ShowPage",
app_key=MyCompany.Aries.app.app_key,
isShowTitleBar = false,
DestroyOnClose = true,
bToggleShowHide = true,
enable_esc_key = true,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = true,
zorder = zorder,
directPosition = true,
align = "_lt",
x = 0,
y = 0,
width = 500,
height = 600,
cancelShowAnimation = true,
}
System.App.Commands.Call("File.MCMLWindowFrame", params);
end
function CodePyToNplPage.OnClose()
CodePyToNplPage.page:CloseWindow(true);
end
function CodePyToNplPage.GetInputText()
return CodePyToNplPage.codes;
end
function CodePyToNplPage.OnConvert()
local py_code_ctrl = CodePyToNplPage.page:FindControl("py_code");
local py_codes = py_code_ctrl:GetText();
local pyruntime = NPL.load("Mod/PyRuntime/Transpiler.lua")
pyruntime:transpile(py_codes, function(res)
local lua_code = res.lua_code;
if(not lua_code)then
local error_msg = res.error_msg;
LOG.std(nil, "error", "CodePyToNplPage", error_msg);
_guihelper.MessageBox(error_msg);
return
end
local npl_code_ctrl = CodePyToNplPage.page:FindControl("npl_code");
npl_code_ctrl:SetText(lua_code)
end)
end
| gpl-2.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/metropolis_torso_pistol_walk_4.meta.lua | 2 | 2812 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 0.43000000715255737,
amplification = 140,
light_colors = {
"89 31 168 255",
"48 42 88 255",
"61 16 123 0"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
chamber = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
chamber_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {},
original_poly = {}
},
torso = {
back = {
pos = {
x = -1,
y = 16
},
rotation = -95.425613403320312
},
head = {
pos = {
x = -1,
y = 1
},
rotation = -3
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 69,
y = -2
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_shoulder = {
pos = {
x = 19,
y = -8
},
rotation = 94.895950317382812
},
shoulder = {
pos = {
x = -22,
y = 0
},
rotation = 87
},
strafe_facing_offset = -90
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
RyMarq/Zero-K | LuaRules/Configs/StartBoxes/Sands of War v2.lua | 8 | 15393 | return {
[0] = {
nameLong = "East",
nameShort = "E",
startpoints = {{3811, 1916}},
boxes = {
{
{4095, 1565},
{4085, 1566},
{4074, 1568},
{4063, 1568},
{4053, 1567},
{4043, 1564},
{4032, 1560},
{4021, 1555},
{4011, 1549},
{4000, 1541},
{3990, 1533},
{3980, 1523},
{3969, 1512},
{3959, 1504},
{3949, 1498},
{3933, 1491},
{3921, 1483},
{3909, 1478},
{3897, 1473},
{3886, 1468},
{3873, 1463},
{3844, 1455},
{3833, 1452},
{3822, 1452},
{3812, 1452},
{3801, 1451},
{3791, 1451},
{3768, 1450},
{3756, 1449},
{3746, 1449},
{3735, 1450},
{3723, 1452},
{3711, 1454},
{3700, 1457},
{3689, 1462},
{3678, 1466},
{3665, 1471},
{3651, 1476},
{3632, 1482},
{3621, 1486},
{3611, 1490},
{3600, 1492},
{3590, 1493},
{3580, 1496},
{3569, 1500},
{3558, 1503},
{3547, 1509},
{3535, 1514},
{3525, 1521},
{3510, 1525},
{3499, 1524},
{3488, 1522},
{3477, 1519},
{3466, 1517},
{3455, 1515},
{3444, 1515},
{3430, 1515},
{3420, 1516},
{3409, 1519},
{3398, 1523},
{3387, 1526},
{3376, 1530},
{3364, 1534},
{3352, 1538},
{3342, 1542},
{3332, 1545},
{3321, 1549},
{3310, 1554},
{3299, 1559},
{3289, 1564},
{3278, 1571},
{3268, 1578},
{3257, 1589},
{3250, 1600},
{3242, 1610},
{3234, 1621},
{3226, 1632},
{3217, 1650},
{3212, 1661},
{3208, 1672},
{3204, 1682},
{3201, 1693},
{3198, 1704},
{3197, 1716},
{3196, 1727},
{3193, 1738},
{3191, 1748},
{3188, 1758},
{3184, 1770},
{3180, 1780},
{3177, 1794},
{3176, 1806},
{3179, 1816},
{3182, 1826},
{3187, 1836},
{3196, 1847},
{3204, 1857},
{3212, 1869},
{3218, 1879},
{3221, 1891},
{3223, 1903},
{3224, 1913},
{3224, 1923},
{3227, 1933},
{3230, 1944},
{3232, 1956},
{3235, 1969},
{3240, 1980},
{3248, 1990},
{3260, 2000},
{3276, 2016},
{3287, 2024},
{3298, 2034},
{3308, 2047},
{3314, 2058},
{3321, 2069},
{3328, 2082},
{3335, 2094},
{3342, 2105},
{3352, 2113},
{3365, 2126},
{3379, 2135},
{3393, 2141},
{3404, 2143},
{3416, 2145},
{3426, 2147},
{3439, 2149},
{3451, 2152},
{3462, 2159},
{3475, 2169},
{3485, 2177},
{3501, 2190},
{3513, 2200},
{3523, 2206},
{3537, 2210},
{3552, 2212},
{3565, 2212},
{3576, 2212},
{3588, 2212},
{3623, 2210},
{3635, 2211},
{3648, 2215},
{3661, 2218},
{3671, 2222},
{3682, 2232},
{3688, 2242},
{3692, 2254},
{3695, 2265},
{3696, 2277},
{3694, 2292},
{3691, 2305},
{3689, 2317},
{3690, 2351},
{3690, 2361},
{3692, 2372},
{3692, 2387},
{3695, 2402},
{3697, 2414},
{3702, 2426},
{3706, 2437},
{3711, 2448},
{3720, 2462},
{3730, 2474},
{3738, 2485},
{3771, 2534},
{3783, 2548},
{3791, 2559},
{3804, 2570},
{3816, 2580},
{3826, 2591},
{3836, 2600},
{3849, 2609},
{3864, 2618},
{3875, 2626},
{3888, 2635},
{3899, 2643},
{3914, 2647},
{3925, 2652},
{3947, 2662},
{3960, 2671},
{3971, 2680},
{3981, 2689},
{3992, 2696},
{4003, 2703},
{4016, 2707},
{4026, 2709},
{4038, 2711},
{4052, 2712},
{4095, 2714},
},
},
},
[1] = {
nameLong = "South-West",
nameShort = "SW",
startpoints = {{315, 3825}},
boxes = {
{
{0, 2886},
{16, 2878},
{26, 2871},
{37, 2865},
{47, 2861},
{58, 2860},
{68, 2862},
{78, 2864},
{88, 2870},
{99, 2878},
{109, 2889},
{119, 2906},
{125, 2916},
{133, 2926},
{145, 2936},
{156, 2945},
{167, 2951},
{177, 2957},
{196, 2973},
{205, 2985},
{212, 2996},
{220, 3006},
{229, 3018},
{239, 3029},
{249, 3037},
{259, 3050},
{268, 3060},
{279, 3068},
{290, 3077},
{300, 3086},
{308, 3097},
{314, 3109},
{320, 3119},
{324, 3129},
{330, 3140},
{335, 3152},
{338, 3162},
{340, 3172},
{341, 3183},
{340, 3194},
{339, 3204},
{339, 3215},
{339, 3225},
{341, 3236},
{346, 3253},
{352, 3265},
{357, 3276},
{361, 3286},
{366, 3306},
{367, 3317},
{367, 3328},
{368, 3339},
{371, 3350},
{377, 3361},
{387, 3372},
{398, 3378},
{408, 3384},
{420, 3385},
{436, 3388},
{447, 3390},
{457, 3390},
{469, 3388},
{479, 3385},
{489, 3379},
{499, 3370},
{511, 3363},
{522, 3360},
{533, 3358},
{543, 3358},
{554, 3362},
{565, 3367},
{575, 3377},
{583, 3387},
{589, 3398},
{594, 3408},
{599, 3418},
{606, 3429},
{616, 3440},
{628, 3447},
{640, 3452},
{660, 3462},
{670, 3471},
{682, 3480},
{693, 3491},
{700, 3501},
{706, 3511},
{712, 3521},
{717, 3533},
{724, 3544},
{735, 3553},
{746, 3562},
{761, 3572},
{771, 3584},
{780, 3596},
{789, 3607},
{794, 3621},
{800, 3632},
{805, 3646},
{811, 3658},
{816, 3668},
{820, 3682},
{822, 3693},
{826, 3703},
{828, 3713},
{829, 3725},
{830, 3736},
{831, 3747},
{832, 3758},
{833, 3768},
{833, 3780},
{832, 3808},
{833, 3818},
{834, 3830},
{836, 3842},
{836, 3853},
{836, 3865},
{834, 3877},
{832, 3888},
{832, 3899},
{834, 3911},
{835, 3922},
{837, 3933},
{838, 3962},
{841, 3976},
{842, 3986},
{843, 3998},
{843, 4009},
{841, 4022},
{839, 4035},
{837, 4046},
{834, 4057},
{832, 4069},
{830, 4079},
{830, 4095},
{0, 4095},
},
},
},
[2] = {
nameLong = "North",
nameShort = "N",
startpoints = {{2042, 138}},
boxes = {
{
{1769, 1},
{1770, 21},
{1770, 33},
{1770, 44},
{1770, 55},
{1763, 156},
{1765, 226},
{1785, 333},
{1795, 413},
{1813, 469},
{1840, 510},
{1884, 565},
{1900, 599},
{1912, 632},
{1914, 680},
{1913, 728},
{1921, 750},
{1938, 771},
{1975, 803},
{2024, 848},
{2087, 914},
{2161, 978},
{2200, 1007},
{2232, 1022},
{2265, 1033},
{2294, 1035},
{2331, 1029},
{2345, 1021},
{2357, 1016},
{2367, 1010},
{2391, 988},
{2400, 978},
{2406, 967},
{2418, 941},
{2421, 930},
{2424, 900},
{2424, 890},
{2423, 879},
{2415, 834},
{2395, 782},
{2379, 746},
{2356, 710},
{2339, 688},
{2323, 664},
{2311, 638},
{2306, 611},
{2304, 572},
{2307, 545},
{2310, 500},
{2317, 447},
{2321, 429},
{2330, 395},
{2342, 371},
{2388, 300},
{2400, 275},
{2410, 250},
{2418, 212},
{2420, 178},
{2419, 143},
{2411, 79},
{2409, 40},
{2412, 0},
},
{
{2539, 1},
{2538, 11},
{2537, 22},
{2536, 32},
{2538, 51},
{2544, 70},
{2555, 91},
{2561, 101},
{2565, 113},
{2569, 123},
{2570, 134},
{2573, 176},
{2575, 197},
{2581, 218},
{2591, 240},
{2599, 252},
{2607, 262},
{2618, 271},
{2628, 280},
{2638, 290},
{2644, 301},
{2648, 312},
{2649, 322},
{2646, 332},
{2639, 342},
{2628, 350},
{2618, 355},
{2608, 365},
{2608, 376},
{2614, 386},
{2624, 393},
{2636, 396},
{2646, 397},
{2666, 397},
{2676, 399},
{2688, 402},
{2699, 405},
{2709, 407},
{2721, 410},
{2732, 411},
{2743, 412},
{2762, 410},
{2775, 409},
{2786, 410},
{2796, 411},
{2807, 415},
{2819, 419},
{2829, 422},
{2841, 427},
{2852, 431},
{2862, 435},
{2872, 437},
{2884, 439},
{2896, 440},
{2908, 440},
{2918, 440},
{2931, 439},
{2942, 438},
{2952, 436},
{2964, 434},
{2975, 430},
{2986, 425},
{2996, 419},
{3014, 410},
{3025, 404},
{3036, 395},
{3047, 385},
{3057, 374},
{3085, 343},
{3096, 333},
{3107, 326},
{3118, 318},
{3128, 309},
{3139, 300},
{3150, 289},
{3161, 280},
{3170, 270},
{3187, 252},
{3202, 228},
{3213, 203},
{3221, 168},
{3226, 120},
{3225, 43},
{3223, 0},
},
},
},
[3] = {
nameLong = "South",
nameShort = "S",
startpoints = {{2307, 3827}},
boxes = {
{
{1895, 4095},
{1894, 4076},
{1892, 4066},
{1889, 4056},
{1884, 4042},
{1880, 4031},
{1876, 4019},
{1857, 3969},
{1853, 3959},
{1847, 3945},
{1844, 3933},
{1843, 3922},
{1842, 3910},
{1842, 3898},
{1844, 3886},
{1848, 3874},
{1863, 3841},
{1864, 3830},
{1866, 3817},
{1866, 3806},
{1868, 3795},
{1869, 3784},
{1872, 3771},
{1877, 3760},
{1882, 3746},
{1887, 3734},
{1887, 3724},
{1886, 3714},
{1884, 3702},
{1882, 3691},
{1881, 3678},
{1882, 3664},
{1884, 3652},
{1910, 3605},
{1915, 3594},
{1920, 3583},
{1924, 3572},
{1931, 3559},
{1935, 3549},
{1940, 3537},
{1943, 3525},
{1945, 3513},
{1948, 3501},
{1962, 3481},
{1972, 3472},
{1986, 3461},
{1999, 3455},
{2012, 3453},
{2027, 3450},
{2040, 3447},
{2052, 3441},
{2065, 3431},
{2078, 3424},
{2093, 3420},
{2106, 3419},
{2116, 3419},
{2130, 3419},
{2141, 3417},
{2154, 3416},
{2164, 3417},
{2180, 3420},
{2191, 3422},
{2205, 3418},
{2215, 3411},
{2226, 3405},
{2238, 3394},
{2249, 3384},
{2262, 3375},
{2274, 3370},
{2286, 3368},
{2298, 3364},
{2311, 3360},
{2323, 3358},
{2336, 3354},
{2348, 3352},
{2372, 3345},
{2384, 3338},
{2394, 3335},
{2405, 3329},
{2415, 3325},
{2427, 3322},
{2438, 3320},
{2448, 3318},
{2458, 3318},
{2470, 3318},
{2480, 3319},
{2516, 3320},
{2526, 3322},
{2537, 3323},
{2548, 3325},
{2559, 3328},
{2569, 3332},
{2581, 3337},
{2594, 3344},
{2605, 3348},
{2618, 3353},
{2630, 3358},
{2644, 3363},
{2654, 3368},
{2669, 3378},
{2679, 3386},
{2690, 3392},
{2700, 3394},
{2711, 3392},
{2723, 3388},
{2733, 3382},
{2746, 3380},
{2758, 3380},
{2769, 3385},
{2780, 3392},
{2788, 3403},
{2795, 3414},
{2803, 3425},
{2809, 3435},
{2819, 3447},
{2839, 3466},
{2850, 3473},
{2861, 3480},
{2871, 3486},
{2882, 3495},
{2892, 3505},
{2904, 3518},
{2914, 3531},
{2924, 3544},
{2933, 3555},
{2942, 3567},
{2954, 3575},
{2975, 3592},
{2985, 3603},
{2995, 3614},
{3003, 3626},
{3008, 3636},
{3013, 3647},
{3027, 3679},
{3033, 3691},
{3039, 3703},
{3043, 3713},
{3045, 3724},
{3047, 3735},
{3048, 3746},
{3050, 3801},
{3051, 3877},
{3053, 3960},
{3055, 4039},
{3054, 4095},
},
},
},
[4] = {
nameLong = "West",
nameShort = "W",
startpoints = {{806, 1591}},
boxes = {
{
{331, 767},
{344, 768},
{356, 769},
{367, 769},
{379, 765},
{390, 760},
{403, 755},
{416, 752},
{427, 748},
{444, 746},
{455, 746},
{466, 747},
{478, 748},
{490, 753},
{503, 758},
{513, 762},
{525, 764},
{547, 772},
{559, 782},
{569, 790},
{580, 801},
{588, 813},
{593, 824},
{596, 836},
{596, 846},
{596, 857},
{597, 868},
{601, 879},
{604, 889},
{622, 914},
{631, 925},
{640, 937},
{651, 946},
{664, 955},
{675, 966},
{685, 980},
{693, 992},
{698, 1004},
{701, 1018},
{711, 1056},
{719, 1094},
{721, 1105},
{721, 1116},
{721, 1127},
{723, 1138},
{726, 1149},
{731, 1159},
{747, 1193},
{756, 1204},
{766, 1215},
{776, 1223},
{788, 1233},
{799, 1241},
{809, 1246},
{851, 1266},
{861, 1271},
{873, 1276},
{887, 1282},
{903, 1288},
{918, 1292},
{931, 1294},
{941, 1296},
{952, 1299},
{962, 1303},
{973, 1309},
{984, 1320},
{995, 1331},
{1003, 1342},
{1007, 1356},
{1010, 1366},
{1010, 1386},
{1012, 1397},
{1017, 1407},
{1023, 1418},
{1031, 1430},
{1039, 1440},
{1046, 1451},
{1071, 1481},
{1080, 1492},
{1091, 1506},
{1102, 1519},
{1111, 1530},
{1118, 1540},
{1134, 1574},
{1143, 1589},
{1149, 1603},
{1154, 1617},
{1156, 1628},
{1160, 1642},
{1159, 1672},
{1158, 1683},
{1156, 1694},
{1153, 1708},
{1135, 1758},
{1126, 1773},
{1118, 1785},
{1107, 1797},
{1057, 1837},
{1042, 1850},
{1032, 1859},
{1020, 1869},
{1007, 1880},
{993, 1891},
{984, 1903},
{973, 1915},
{964, 1926},
{948, 1938},
{935, 1947},
{919, 1955},
{906, 1960},
{895, 1962},
{885, 1964},
{871, 1966},
{861, 1968},
{850, 1968},
{839, 1968},
{827, 1967},
{816, 1964},
{798, 1961},
{781, 1955},
{770, 1950},
{758, 1944},
{747, 1940},
{728, 1933},
{710, 1934},
{699, 1933},
{686, 1934},
{675, 1935},
{663, 1935},
{652, 1935},
{640, 1931},
{628, 1922},
{588, 1904},
{578, 1899},
{571, 1889},
{577, 1876},
{583, 1865},
{585, 1855},
{586, 1844},
{584, 1833},
{574, 1816},
{563, 1807},
{553, 1800},
{542, 1791},
{530, 1781},
{521, 1770},
{516, 1758},
{512, 1747},
{503, 1698},
{501, 1687},
{497, 1675},
{493, 1665},
{485, 1654},
{474, 1643},
{463, 1635},
{449, 1617},
{445, 1606},
{442, 1595},
{438, 1585},
{432, 1573},
{424, 1562},
{415, 1550},
{405, 1538},
{393, 1511},
{387, 1497},
{385, 1487},
{384, 1477},
{380, 1466},
{376, 1456},
{365, 1447},
{354, 1442},
{340, 1434},
{297, 1425},
{287, 1421},
{275, 1417},
{262, 1414},
{252, 1411},
{227, 1404},
{217, 1401},
{207, 1398},
{196, 1395},
{186, 1393},
{176, 1393},
{165, 1394},
{155, 1394},
{144, 1392},
{134, 1385},
{127, 1373},
{128, 1363},
{136, 1352},
{146, 1349},
{156, 1343},
{167, 1332},
{172, 1321},
{171, 1311},
{161, 1290},
{151, 1279},
{140, 1270},
{128, 1262},
{118, 1254},
{109, 1243},
{104, 1231},
{99, 1219},
{97, 1207},
{95, 1196},
{92, 1183},
{90, 1171},
{89, 1142},
{88, 1131},
{84, 1120},
{80, 1109},
{74, 1099},
{67, 1088},
{59, 1077},
{53, 1066},
{50, 1054},
{49, 1043},
{49, 1032},
{58, 995},
{81, 907},
{92, 877},
{100, 866},
{108, 855},
{118, 844},
{128, 833},
{138, 823},
{150, 815},
{161, 809},
{182, 798},
{194, 795},
{207, 792},
{218, 788},
{229, 785},
{241, 780},
{252, 775},
{263, 771},
{274, 769},
{285, 767},
{295, 766},
{318, 766},
},
},
},
}
| gpl-2.0 |
vince06fr/prosody-modules | mod_onions/mod_onions.lua | 4 | 8148 | local prosody = prosody;
local core_process_stanza = prosody.core_process_stanza;
local wrapclient = require "net.server".wrapclient;
local s2s_new_outgoing = require "core.s2smanager".new_outgoing;
local initialize_filters = require "util.filters".initialize;
local st = require "util.stanza";
local portmanager = require "core.portmanager";
local softreq = require "util.dependencies".softreq;
local bit;
pcall(function() bit = require"bit"; end);
bit = bit or softreq"bit32"
if not bit then module:log("error", "No bit module found. Either LuaJIT 2, lua-bitop or Lua 5.2 is required"); end
local band = bit.band;
local rshift = bit.rshift;
local lshift = bit.lshift;
local byte = string.byte;
local c = string.char;
module:depends("s2s");
local proxy_ip = module:get_option("onions_socks5_host") or "127.0.0.1";
local proxy_port = module:get_option("onions_socks5_port") or 9050;
local forbid_else = module:get_option("onions_only") or false;
local torify_all = module:get_option("onions_tor_all") or false;
local onions_map = module:get_option("onions_map") or {};
local sessions = module:shared("sessions");
-- The socks5listener handles connection while still connecting to the proxy,
-- then it hands them over to the normal listener (in mod_s2s)
local socks5listener = { default_port = proxy_port, default_mode = "*a", default_interface = "*" };
local function socks5_connect_sent(conn, data)
local session = sessions[conn];
if #data < 5 then
session.socks5_buffer = data;
return;
end
request_status = byte(data, 2);
if not request_status == 0x00 then
module:log("debug", "Failed to connect to the SOCKS5 proxy. :(");
session:close(false);
return;
end
module:log("debug", "Succesfully connected to SOCKS5 proxy.");
local response = byte(data, 4);
if response == 0x01 then
if #data < 10 then
-- let's try again when we have enough
session.socks5_buffer = data;
return;
end
-- this means the server tells us to connect on an IPv4 address
local ip1 = byte(data, 5);
local ip2 = byte(data, 6);
local ip3 = byte(data, 7);
local ip4 = byte(data, 8);
local port = band(byte(data, 9), lshift(byte(data, 10), 8));
module:log("debug", "Should connect to: "..ip1.."."..ip2.."."..ip3.."."..ip4..":"..port);
if not (ip1 == 0 and ip2 == 0 and ip3 == 0 and ip4 == 0 and port == 0) then
module:log("debug", "The SOCKS5 proxy tells us to connect to a different IP, don't know how. :(");
session:close(false);
return;
end
-- Now the real s2s listener can take over the connection.
local listener = portmanager.get_service("s2s").listener;
module:log("debug", "SOCKS5 done, handing over listening to "..tostring(listener));
session.socks5_handler = nil;
session.socks5_buffer = nil;
local w, log = conn.send, session.log;
local filter = initialize_filters(session);
session.version = 1;
session.sends2s = function (t)
log("debug", "sending (s2s over socks5): %s", (t.top_tag and t:top_tag()) or t:match("^[^>]*>?"));
if t.name then
t = filter("stanzas/out", t);
end
if t then
t = filter("bytes/out", tostring(t));
if t then
return conn:write(tostring(t));
end
end
end
session.open_stream = function ()
session.sends2s(st.stanza("stream:stream", {
xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
["xmlns:stream"]='http://etherx.jabber.org/streams',
from=session.from_host, to=session.to_host, version='1.0', ["xml:lang"]='en'}):top_tag());
end
conn.setlistener(conn, listener);
listener.register_outgoing(conn, session);
listener.onconnect(conn);
end
end
local function socks5_handshake_sent(conn, data)
local session = sessions[conn];
if #data < 2 then
session.socks5_buffer = data;
return;
end
-- version, method
local request_status = byte(data, 2);
module:log("debug", "SOCKS version: "..byte(data, 1));
module:log("debug", "Response: "..request_status);
if not request_status == 0x00 then
module:log("debug", "Failed to connect to the SOCKS5 proxy. :( It seems to require authentication.");
session:close(false);
return;
end
module:log("debug", "Sending connect message.");
-- version 5, connect, (reserved), type: domainname, (length, hostname), port
conn:write(c(5) .. c(1) .. c(0) .. c(3) .. c(#session.socks5_to) .. session.socks5_to);
conn:write(c(rshift(session.socks5_port, 8)) .. c(band(session.socks5_port, 0xff)));
session.socks5_handler = socks5_connect_sent;
end
function socks5listener.onconnect(conn)
module:log("debug", "Connected to SOCKS5 proxy, sending SOCKS5 handshake.");
-- Socks version 5, 1 method, no auth
conn:write(c(5) .. c(1) .. c(0));
sessions[conn].socks5_handler = socks5_handshake_sent;
end
function socks5listener.register_outgoing(conn, session)
session.direction = "outgoing";
sessions[conn] = session;
end
function socks5listener.ondisconnect(conn, err)
sessions[conn] = nil;
end
function socks5listener.onincoming(conn, data)
local session = sessions[conn];
if session.socks5_buffer then
data = session.socks5_buffer .. data;
end
if session.socks5_handler then
session.socks5_handler(conn, data);
end
end
local function connect_socks5(host_session, connect_host, connect_port)
local conn, handler = socket.tcp();
module:log("debug", "Connecting to " .. connect_host .. ":" .. connect_port);
-- this is not necessarily the same as .to_host (it can be that this is from the onions_map)
host_session.socks5_to = connect_host;
host_session.socks5_port = connect_port;
conn:settimeout(0);
local success, err = conn:connect(proxy_ip, proxy_port);
conn = wrapclient(conn, connect_host, connect_port, socks5listener, "*a");
socks5listener.register_outgoing(conn, host_session);
host_session.conn = conn;
end
local bouncy_stanzas = { message = true, presence = true, iq = true };
local function bounce_sendq(session, reason)
local sendq = session.sendq;
if not sendq then return; end
session.log("info", "Sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
local dummy = {
type = "s2sin";
send = function(s)
(session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", traceback());
end;
dummy = true;
};
for i, data in ipairs(sendq) do
local reply = data[2];
if reply and not(reply.attr.xmlns) and bouncy_stanzas[reply.name] then
reply.attr.type = "error";
reply:tag("error", {type = "cancel"})
:tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
if reason then
reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"})
:text("Server-to-server connection failed: "..reason):up();
end
core_process_stanza(dummy, reply);
end
sendq[i] = nil;
end
session.sendq = nil;
end
-- Try to intercept anything to *.onion
local function route_to_onion(event)
local stanza = event.stanza;
local to_host = event.to_host;
local onion_host = nil;
local onion_port = nil;
if not to_host:find(".onion(.?)$") then
if onions_map[to_host] then
if type(onions_map[to_host]) == "string" then
onions_host = onions_map[to_host];
else
onion_host = onions_map[to_host].host;
onion_port = onions_map[to_host].port;
end
elseif forbid_else then
module:log("debug", event.to_host .. " is not an onion. Blocking it.");
return false;
elseif not torify_all then
return;
end
end
module:log("debug", "Onion routing something to ".. to_host);
if hosts[event.from_host].s2sout[to_host] then
return;
end
local host_session = s2s_new_outgoing(event.from_host, to_host);
host_session.bounce_sendq = bounce_sendq;
host_session.sendq = { {tostring(stanza), stanza.attr and stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} };
hosts[event.from_host].s2sout[to_host] = host_session;
connect_socks5(host_session, onion_host or to_host, onion_port or 5269);
return true;
end
module:log("debug", "Onions ready and loaded");
hosts[module.host].events.add_handler("route/remote", route_to_onion, 200);
| mit |
Laterus/Darkstar-Linux-Fork | scripts/zones/Spire_of_Vahzl/Zone.lua | 1 | 1123 | -----------------------------------
--
-- Zone: Spire_of_Vahzl
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil;
require("scripts/zones/Spire_of_Vahzl/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
madpilot78/ntopng | scripts/lua/pod_details.lua | 1 | 2104 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local graph_utils = require "graph_utils"
local page_utils = require("page_utils")
local format_utils = require("format_utils")
local pod = _GET["pod"]
local page = _GET["page"]
interface.select(ifname)
local ifId = getInterfaceId(ifname)
sendHTTPContentTypeHeader('text/html')
page_utils.set_active_menu_entry(page_utils.menu_entries.pods)
dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua")
if not pod or not areContainersTimeseriesEnabled(ifId) then
print("<div class=\"alert alert alert-danger\"><i class='fas fa-exclamation-triangle fa-lg fa-ntopng-warning'></i> " .. i18n("no_data_available") .. "</div>")
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
return
end
--[[
Create Menu Bar with buttons
--]]
local nav_url = ntop.getHttpPrefix().."/lua/pod_details.lua?pod="..pod
local title = i18n("containers_stats.pod") .. ": "..pod
page_utils.print_navbar(title, nav_url,
{
{
active = page == "historical" or not page,
page_name = "historical",
label = "<i class='fas fa-lg fa-chart-area'></i>",
},
}
)
--[[
Selectively render information pages
--]]
if page == "historical" then
local schema = _GET["ts_schema"] or "pod:num_flows"
local selected_epoch = _GET["epoch"] or ""
local url = ntop.getHttpPrefix()..'/lua/pod_details.lua?pod='..pod..'&page=historical'
local tags = {
ifid = ifId,
pod = pod,
}
graph_utils.drawGraphs(ifId, schema, tags, _GET["zoom"], url, selected_epoch, {
timeseries = {
{schema="pod:num_flows", label=i18n("graphs.active_flows")},
{schema="pod:num_containers", label=i18n("containers_stats.containers")},
{schema="pod:rtt", label=i18n("containers_stats.avg_rtt")},
{schema="pod:rtt_variance", label=i18n("containers_stats.avg_rtt_variance")},
}
})
end
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Lower_Jeuno/npcs/Yatniel.lua | 1 | 1030 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Yatniel
-- Type: Standard NPC
-- @zone: 245
-- @pos: -66.817 -7 -126.594
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x272c);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/gfx/particles/lightning.lua | 3 | 2502 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- Make the 2 main forks
local forks = {{}, {}}
local m1 = forks[1]
local m2 = forks[2]
local tiles = math.ceil(math.sqrt(tx*tx+ty*ty))
local tx = tx * engine.Map.tile_w
local ty = ty * engine.Map.tile_h
local breakdir = math.rad(rng.range(-8, 8))
m1.bx = 0
m1.by = 0
m1.thick = 5
m1.dir = math.atan2(ty, tx) + breakdir
m1.size = math.sqrt(tx*tx+ty*ty) / 2
m2.bx = m1.size * math.cos(m1.dir)
m2.by = m1.size * math.sin(m1.dir)
m2.thick = 5
m2.dir = math.atan2(ty, tx) - breakdir
m2.size = math.sqrt(tx*tx+ty*ty) / 2
-- Add more forks
for i = 1, math.min(math.max(3, m1.size / 5), 20) do
local m = rng.percent(50) and forks[1] or forks[2]
if rng.percent(60) then m = rng.table(forks) end
local f = {}
f.thick = 2
f.dir = m.dir + math.rad(rng.range(-30,30))
f.size = rng.range(6, 25)
local br = rng.range(1, m.size)
f.bx = br * math.cos(m.dir) + m.bx
f.by = br * math.sin(m.dir) + m.by
forks[#forks+1] = f
end
-- Populate the lightning based on the forks
return { generator = function()
local f = rng.table(forks)
local a = f.dir
local rad = rng.range(-3,3)
local ra = math.rad(rad)
local r = rng.range(1, f.size)
return {
life = life or 4,
size = f.thick, sizev = 0, sizea = 0,
x = r * math.cos(a) + 3 * math.cos(ra) + f.bx, xv = 0, xa = 0,
y = r * math.sin(a) + 3 * math.sin(ra) + f.by, yv = 0, ya = 0,
dir = 0, dirv = 0, dira = 0,
vel = 0, velv = 0, vela = 0,
r = rng.range(140, 200)/255, rv = 0, ra = 0,
g = rng.range(180, 220)/255, gv = 0, ga = 0,
b = rng.range(220, 240)/255, bv = 0, ba = 0,
a = rng.range(230, 255)/255, av = 0, aa = 0,
}
end, },
function(self)
self.nb = (self.nb or 0) + 1
if self.nb < 4 then
self.ps:emit(230*tiles)
end
end,
4*(nb_particles or 230)*tiles
| gpl-3.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/modules/base/luasrc/sgi/cgi.lua | 87 | 2260 | --[[
LuCI - SGI-Module for CGI
Description:
Server Gateway Interface for CGI
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
exectime = os.clock()
module("luci.sgi.cgi", package.seeall)
local ltn12 = require("luci.ltn12")
require("nixio.util")
require("luci.http")
require("luci.sys")
require("luci.dispatcher")
-- Limited source to avoid endless blocking
local function limitsource(handle, limit)
limit = limit or 0
local BLOCKSIZE = ltn12.BLOCKSIZE
return function()
if limit < 1 then
handle:close()
return nil
else
local read = (limit > BLOCKSIZE) and BLOCKSIZE or limit
limit = limit - read
local chunk = handle:read(read)
if not chunk then handle:close() end
return chunk
end
end
end
function run()
local r = luci.http.Request(
luci.sys.getenv(),
limitsource(io.stdin, tonumber(luci.sys.getenv("CONTENT_LENGTH"))),
ltn12.sink.file(io.stderr)
)
local x = coroutine.create(luci.dispatcher.httpdispatch)
local hcache = ""
local active = true
while coroutine.status(x) ~= "dead" do
local res, id, data1, data2 = coroutine.resume(x, r)
if not res then
print("Status: 500 Internal Server Error")
print("Content-Type: text/plain\n")
print(id)
break;
end
if active then
if id == 1 then
io.write("Status: " .. tostring(data1) .. " " .. data2 .. "\r\n")
elseif id == 2 then
hcache = hcache .. data1 .. ": " .. data2 .. "\r\n"
elseif id == 3 then
io.write(hcache)
io.write("\r\n")
elseif id == 4 then
io.write(tostring(data1 or ""))
elseif id == 5 then
io.flush()
io.close()
active = false
elseif id == 6 then
data1:copyz(nixio.stdout, data2)
data1:close()
end
end
end
end
| gpl-2.0 |
Lleafll/sws-lleaf | libs/AceGUI-3.0/widgets/AceGUIWidget-Slider.lua | 42 | 8139 | --[[-----------------------------------------------------------------------------
Slider Widget
Graphical Slider, like, for Range values.
-------------------------------------------------------------------------------]]
local Type, Version = "Slider", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local min, max, floor = math.min, math.max, math.floor
local tonumber, pairs = tonumber, pairs
-- WoW APIs
local PlaySound = PlaySound
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontHighlightSmall
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function UpdateText(self)
local value = self.value or 0
if self.ispercent then
self.editbox:SetText(("%s%%"):format(floor(value * 1000 + 0.5) / 10))
else
self.editbox:SetText(floor(value * 100 + 0.5) / 100)
end
end
local function UpdateLabels(self)
local min, max = (self.min or 0), (self.max or 100)
if self.ispercent then
self.lowtext:SetFormattedText("%s%%", (min * 100))
self.hightext:SetFormattedText("%s%%", (max * 100))
else
self.lowtext:SetText(min)
self.hightext:SetText(max)
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function Frame_OnMouseDown(frame)
frame.obj.slider:EnableMouseWheel(true)
AceGUI:ClearFocus()
end
local function Slider_OnValueChanged(frame)
local self = frame.obj
if not frame.setup then
local newvalue = frame:GetValue()
if self.step and self.step > 0 then
local min_value = self.min or 0
newvalue = floor((newvalue - min_value) / self.step + 0.5) * self.step + min_value
end
if newvalue ~= self.value and not self.disabled then
self.value = newvalue
self:Fire("OnValueChanged", newvalue)
end
if self.value then
UpdateText(self)
end
end
end
local function Slider_OnMouseUp(frame)
local self = frame.obj
self:Fire("OnMouseUp", self.value)
end
local function Slider_OnMouseWheel(frame, v)
local self = frame.obj
if not self.disabled then
local value = self.value
if v > 0 then
value = min(value + (self.step or 1), self.max)
else
value = max(value - (self.step or 1), self.min)
end
self.slider:SetValue(value)
end
end
local function EditBox_OnEscapePressed(frame)
frame:ClearFocus()
end
local function EditBox_OnEnterPressed(frame)
local self = frame.obj
local value = frame:GetText()
if self.ispercent then
value = value:gsub('%%', '')
value = tonumber(value) / 100
else
value = tonumber(value)
end
if value then
PlaySound("igMainMenuOptionCheckBoxOn")
self.slider:SetValue(value)
self:Fire("OnMouseUp", value)
end
end
local function EditBox_OnEnter(frame)
frame:SetBackdropBorderColor(0.5, 0.5, 0.5, 1)
end
local function EditBox_OnLeave(frame)
frame:SetBackdropBorderColor(0.3, 0.3, 0.3, 0.8)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetWidth(200)
self:SetHeight(44)
self:SetDisabled(false)
self:SetIsPercent(nil)
self:SetSliderValues(0,100,1)
self:SetValue(0)
self.slider:EnableMouseWheel(false)
end,
-- ["OnRelease"] = nil,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.slider:EnableMouse(false)
self.label:SetTextColor(.5, .5, .5)
self.hightext:SetTextColor(.5, .5, .5)
self.lowtext:SetTextColor(.5, .5, .5)
--self.valuetext:SetTextColor(.5, .5, .5)
self.editbox:SetTextColor(.5, .5, .5)
self.editbox:EnableMouse(false)
self.editbox:ClearFocus()
else
self.slider:EnableMouse(true)
self.label:SetTextColor(1, .82, 0)
self.hightext:SetTextColor(1, 1, 1)
self.lowtext:SetTextColor(1, 1, 1)
--self.valuetext:SetTextColor(1, 1, 1)
self.editbox:SetTextColor(1, 1, 1)
self.editbox:EnableMouse(true)
end
end,
["SetValue"] = function(self, value)
self.slider.setup = true
self.slider:SetValue(value)
self.value = value
UpdateText(self)
self.slider.setup = nil
end,
["GetValue"] = function(self)
return self.value
end,
["SetLabel"] = function(self, text)
self.label:SetText(text)
end,
["SetSliderValues"] = function(self, min, max, step)
local frame = self.slider
frame.setup = true
self.min = min
self.max = max
self.step = step
frame:SetMinMaxValues(min or 0,max or 100)
UpdateLabels(self)
frame:SetValueStep(step or 1)
if self.value then
frame:SetValue(self.value)
end
frame.setup = nil
end,
["SetIsPercent"] = function(self, value)
self.ispercent = value
UpdateLabels(self)
UpdateText(self)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local SliderBackdrop = {
bgFile = "Interface\\Buttons\\UI-SliderBar-Background",
edgeFile = "Interface\\Buttons\\UI-SliderBar-Border",
tile = true, tileSize = 8, edgeSize = 8,
insets = { left = 3, right = 3, top = 6, bottom = 6 }
}
local ManualBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\ChatFrame\\ChatFrameBackground",
tile = true, edgeSize = 1, tileSize = 5,
}
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:EnableMouse(true)
frame:SetScript("OnMouseDown", Frame_OnMouseDown)
local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
label:SetPoint("TOPLEFT")
label:SetPoint("TOPRIGHT")
label:SetJustifyH("CENTER")
label:SetHeight(15)
local slider = CreateFrame("Slider", nil, frame)
slider:SetOrientation("HORIZONTAL")
slider:SetHeight(15)
slider:SetHitRectInsets(0, 0, -10, 0)
slider:SetBackdrop(SliderBackdrop)
slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Horizontal")
slider:SetPoint("TOP", label, "BOTTOM")
slider:SetPoint("LEFT", 3, 0)
slider:SetPoint("RIGHT", -3, 0)
slider:SetValue(0)
slider:SetScript("OnValueChanged",Slider_OnValueChanged)
slider:SetScript("OnEnter", Control_OnEnter)
slider:SetScript("OnLeave", Control_OnLeave)
slider:SetScript("OnMouseUp", Slider_OnMouseUp)
slider:SetScript("OnMouseWheel", Slider_OnMouseWheel)
local lowtext = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
lowtext:SetPoint("TOPLEFT", slider, "BOTTOMLEFT", 2, 3)
local hightext = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
hightext:SetPoint("TOPRIGHT", slider, "BOTTOMRIGHT", -2, 3)
local editbox = CreateFrame("EditBox", nil, frame)
editbox:SetAutoFocus(false)
editbox:SetFontObject(GameFontHighlightSmall)
editbox:SetPoint("TOP", slider, "BOTTOM")
editbox:SetHeight(14)
editbox:SetWidth(70)
editbox:SetJustifyH("CENTER")
editbox:EnableMouse(true)
editbox:SetBackdrop(ManualBackdrop)
editbox:SetBackdropColor(0, 0, 0, 0.5)
editbox:SetBackdropBorderColor(0.3, 0.3, 0.30, 0.80)
editbox:SetScript("OnEnter", EditBox_OnEnter)
editbox:SetScript("OnLeave", EditBox_OnLeave)
editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed)
editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed)
local widget = {
label = label,
slider = slider,
lowtext = lowtext,
hightext = hightext,
editbox = editbox,
alignoffset = 25,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
slider.obj, editbox.obj = widget, widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
| mit |
flyzjhz/witi-openwrt | package/ramips/ui/luci-mtk/src/applications/luci-tinyproxy/luasrc/model/cbi/tinyproxy.lua | 80 | 7364 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008-2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("tinyproxy", translate("Tinyproxy"),
translate("Tinyproxy is a small and fast non-caching HTTP(S)-Proxy"))
s = m:section(TypedSection, "tinyproxy", translate("Server Settings"))
s.anonymous = true
s:tab("general", translate("General settings"))
s:tab("privacy", translate("Privacy settings"))
s:tab("filter", translate("Filtering and ACLs"))
s:tab("limits", translate("Server limits"))
o = s:taboption("general", Flag, "enabled", translate("Enable Tinyproxy server"))
o.rmempty = false
function o.write(self, section, value)
if value == "1" then
luci.sys.init.enable("tinyproxy")
else
luci.sys.init.disable("tinyproxy")
end
return Flag.write(self, section, value)
end
o = s:taboption("general", Value, "Port", translate("Listen port"),
translate("Specifies the HTTP port Tinyproxy is listening on for requests"))
o.optional = true
o.datatype = "port"
o.placeholder = 8888
o = s:taboption("general", Value, "Listen", translate("Listen address"),
translate("Specifies the addresses Tinyproxy is listening on for requests"))
o.optional = true
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0"
o = s:taboption("general", Value, "Bind", translate("Bind address"),
translate("Specifies the address Tinyproxy binds to for outbound forwarded requests"))
o.optional = true
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0"
o = s:taboption("general", Value, "DefaultErrorFile", translate("Error page"),
translate("HTML template file to serve when HTTP errors occur"))
o.optional = true
o.default = "/usr/share/tinyproxy/default.html"
o = s:taboption("general", Value, "StatFile", translate("Statistics page"),
translate("HTML template file to serve for stat host requests"))
o.optional = true
o.default = "/usr/share/tinyproxy/stats.html"
o = s:taboption("general", Flag, "Syslog", translate("Use syslog"),
translate("Writes log messages to syslog instead of a log file"))
o = s:taboption("general", Value, "LogFile", translate("Log file"),
translate("Log file to use for dumping messages"))
o.default = "/var/log/tinyproxy.log"
o:depends("Syslog", "")
o = s:taboption("general", ListValue, "LogLevel", translate("Log level"),
translate("Logging verbosity of the Tinyproxy process"))
o:value("Critical")
o:value("Error")
o:value("Warning")
o:value("Notice")
o:value("Connect")
o:value("Info")
o = s:taboption("general", Value, "User", translate("User"),
translate("Specifies the user name the Tinyproxy process is running as"))
o.default = "nobody"
o = s:taboption("general", Value, "Group", translate("Group"),
translate("Specifies the group name the Tinyproxy process is running as"))
o.default = "nogroup"
--
-- Privacy
--
o = s:taboption("privacy", Flag, "XTinyproxy", translate("X-Tinyproxy header"),
translate("Adds an \"X-Tinyproxy\" HTTP header with the client IP address to forwarded requests"))
o = s:taboption("privacy", Value, "ViaProxyName", translate("Via hostname"),
translate("Specifies the Tinyproxy hostname to use in the Via HTTP header"))
o.placeholder = "tinyproxy"
o.datatype = "hostname"
s:taboption("privacy", DynamicList, "Anonymous", translate("Header whitelist"),
translate("Specifies HTTP header names which are allowed to pass-through, all others are discarded. Leave empty to disable header filtering"))
--
-- Filter
--
o = s:taboption("filter", DynamicList, "Allow", translate("Allowed clients"),
translate("List of IP addresses or ranges which are allowed to use the proxy server"))
o.placeholder = "0.0.0.0"
o.datatype = "ipaddr"
o = s:taboption("filter", DynamicList, "ConnectPort", translate("Allowed connect ports"),
translate("List of allowed ports for the CONNECT method. A single value \"0\" allows all ports"))
o.placeholder = 0
o.datatype = "port"
s:taboption("filter", FileUpload, "Filter", translate("Filter file"),
translate("Plaintext file with URLs or domains to filter. One entry per line"))
s:taboption("filter", Flag, "FilterURLs", translate("Filter by URLs"),
translate("By default, filtering is done based on domain names. Enable this to match against URLs instead"))
s:taboption("filter", Flag, "FilterExtended", translate("Filter by RegExp"),
translate("By default, basic POSIX expressions are used for filtering. Enable this to activate extended regular expressions"))
s:taboption("filter", Flag, "FilterCaseSensitive", translate("Filter case-sensitive"),
translate("By default, filter strings are treated as case-insensitive. Enable this to make the matching case-sensitive"))
s:taboption("filter", Flag, "FilterDefaultDeny", translate("Default deny"),
translate("By default, the filter rules act as blacklist. Enable this option to only allow matched URLs or domain names"))
--
-- Limits
--
o = s:taboption("limits", Value, "Timeout", translate("Connection timeout"),
translate("Maximum number of seconds an inactive connection is held open"))
o.optional = true
o.datatype = "uinteger"
o.default = 600
o = s:taboption("limits", Value, "MaxClients", translate("Max. clients"),
translate("Maximum allowed number of concurrently connected clients"))
o.datatype = "uinteger"
o.default = 10
o = s:taboption("limits", Value, "MinSpareServers", translate("Min. spare servers"),
translate("Minimum number of prepared idle processes"))
o.datatype = "uinteger"
o.default = 5
o = s:taboption("limits", Value, "MaxSpareServers", translate("Max. spare servers"),
translate("Maximum number of prepared idle processes"))
o.datatype = "uinteger"
o.default = 10
o = s:taboption("limits", Value, "StartServers", translate("Start spare servers"),
translate("Number of idle processes to start when launching Tinyproxy"))
o.datatype = "uinteger"
o.default = 5
o = s:taboption("limits", Value, "MaxRequestsPerChild", translate("Max. requests per server"),
translate("Maximum allowed number of requests per process. If it is exeeded, the process is restarted. Zero means unlimited."))
o.datatype = "uinteger"
o.default = 0
--
-- Upstream
--
s = m:section(TypedSection, "upstream", translate("Upstream Proxies"),
translate("Upstream proxy rules define proxy servers to use when accessing certain IP addresses or domains."))
s.anonymous = true
s.addremove = true
t = s:option(ListValue, "type", translate("Policy"),
translate("<em>Via proxy</em> routes requests to the given target via the specifed upstream proxy, <em>Reject access</em> disables any upstream proxy for the target"))
t:value("proxy", translate("Via proxy"))
t:value("reject", translate("Reject access"))
ta = s:option(Value, "target", translate("Target host"),
translate("Can be either an IP address or range, a domain name or \".\" for any host without domain"))
ta.rmempty = true
ta.placeholder = "0.0.0.0/0"
ta.datatype = "host"
v = s:option(Value, "via", translate("Via proxy"),
translate("Specifies the upstream proxy to use for accessing the target host. Format is <code>address:port</code>"))
v:depends({type="proxy"})
v.placeholder = "10.0.0.1:8080"
return m
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Macros/MacroKeyPress.lua | 1 | 6982 | --[[
Title: Macro Key Press
Author(s): LiXizhi
Date: 2021/1/4
Desc: a macro for key(s) press.
Use Lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Common/Macros.lua");
-------------------------------------------------------
]]
local MacroPlayer = commonlib.gettable("MyCompany.Aries.Game.Tasks.MacroPlayer");
local Application = commonlib.gettable("System.Windows.Application");
local MouseEvent = commonlib.gettable("System.Windows.MouseEvent");
local Keyboard = commonlib.gettable("System.Windows.Keyboard");
local KeyEvent = commonlib.gettable("System.Windows.KeyEvent");
local InputMethodEvent = commonlib.gettable("System.Windows.InputMethodEvent");
local Macros = commonlib.gettable("MyCompany.Aries.Game.GameLogic.Macros")
-- @param event: key press event object
-- @return string like "ctrl+DIK_C", ""
function Macros.GetButtonTextFromKeyEvent(event)
local buttons = event.keyname or "";
if(event.ctrl_pressed) then
buttons = "ctrl+"..buttons;
end
if(event.alt_pressed) then
buttons = "alt+"..buttons;
end
if(event.shift_pressed) then
buttons = "shift+"..buttons;
end
return buttons;
end
-- @param buttons: nil or a string to append button text.
-- @return string like "ctrl+shift", ""
function Macros.GetButtonTextFromKeyboard(buttons)
buttons = buttons or "";
if(Keyboard:IsCtrlKeyPressed()) then
buttons = "ctrl+"..buttons;
end
if(Keyboard:IsAltKeyPressed()) then
buttons = "alt+"..buttons;
end
if(Keyboard:IsShiftKeyPressed()) then
buttons = "shift+"..buttons;
end
buttons = buttons:gsub("%+$", "")
return buttons;
end
local function SetKeyEventFromButtonText(event, button)
-- mouse_button is a global variable
event.isEmulated= true;
if(button == "DIK_ADD") then
button = "shift+DIK_EQUALS";
elseif(button == "DIK_SUBSTRACT") then
button = "DIK_MINUS";
end
event.keyname = button:match("(DIK_[%w_]+)");
event.shift_pressed = button:match("shift") and true
event.alt_pressed = button:match("alt") and true
event.ctrl_pressed = button:match("ctrl") and true
event.key_sequence = event:GetKeySequence();
end
local nextKeyPressMouseX, nextKeyPressMouseY;
function Macros.GetNextKeyPressWithMouseMove()
return nextKeyPressMouseX, nextKeyPressMouseY
end
function Macros.SetNextKeyPressWithMouseMove(mouseX, mouseY)
nextKeyPressMouseX, nextKeyPressMouseY = mouseX, mouseY
end
-- this macro will force the next key stroke to have a given mouse position.
-- such as some ctrl+C and ctrl+v operations in the scene.
function Macros.NextKeyPressWithMouseMove(angleX, angleY)
nextKeyPressMouseX, nextKeyPressMouseY = Macros.MouseAngleToScreenPos(angleX, angleY);
end
local function AdjustMousePosition_()
if(nextKeyPressMouseX and nextKeyPressMouseY) then
-- mouse_x, mouse_y, mouse_button are global variables
mouse_x, mouse_y = nextKeyPressMouseX, nextKeyPressMouseY;
ParaUI.SetMousePosition(mouse_x, mouse_y);
nextKeyPressMouseX, nextKeyPressMouseY = nil, nil;
end
end
--@param button: string like "C" or "ctrl+C"
function Macros.KeyPress(button)
AdjustMousePosition_();
local event = KeyEvent:init("keyPressEvent")
SetKeyEventFromButtonText(event, button)
local ctx = GameLogic.GetSceneContext()
ctx:handleKeyEvent(event);
MacroPlayer.Focus();
end
-- System.Window's key down event
function Macros.WindowKeyPress(ctrlName, button)
local obj = Application.GetUIObject(ctrlName);
if(obj) then
local window = obj:GetWindow()
if(window and window:testAttribute("WA_WState_Created")) then
window.isEmulatedFocus = true;
window:handleActivateEvent(true)
window.isEmulatedFocus = nil;
local event = KeyEvent:init("keyPressEvent")
SetKeyEventFromButtonText(event, button)
window:HandlePagePressKeyEvent(event);
if(not event:isAccepted()) then
Application:sendEvent(window:focusWidget(), event);
end
MacroPlayer.Focus();
end
end
end
-- System.Window's input method event
function Macros.WindowInputMethod(ctrlName, commitString)
local obj = Application.GetUIObject(ctrlName);
if(obj) then
local window = obj:GetWindow()
if(window and window:testAttribute("WA_WState_Created")) then
window.isEmulatedFocus = true;
window:handleActivateEvent(true)
window.isEmulatedFocus = nil;
local event = InputMethodEvent:new():init(commitString);
Application:sendEvent(window:focusWidget(), event);
MacroPlayer.Focus();
end
end
end
--@param button: string like "C" or "ctrl+C"
function Macros.KeyPressTrigger(button)
if(button and button ~= "") then
local callback = {};
MacroPlayer.SetKeyPressTrigger(button, nil, function()
if(callback.OnFinish) then
callback.OnFinish();
end
end);
return callback;
end
end
function Macros.WindowKeyPressTrigger(ctrlName, button)
if(button and button ~= "") then
-- get final text in editbox
local nOffset = 0;
local targetText = "";
while(true) do
nOffset = nOffset + 1;
local nextMacro = Macros:PeekNextMacro(nOffset)
if(nextMacro and (nextMacro.name == "Idle" or nextMacro.name == "WindowKeyPressTrigger" or nextMacro.name == "WindowInputMethod" or nextMacro.name == "WindowKeyPress")) then
if(nextMacro.name ~= "Idle") then
local nextUIName = nextMacro:GetParams()[1];
if(nextUIName == ctrlName) then
if(nextMacro.name == "WindowKeyPress") then
local text = nextMacro:GetParams()[2];
if(not text or not Macros.IsButtonLetter(text)) then
break;
end
elseif(nextMacro.name == "WindowInputMethod") then
local text = nextMacro:GetParams()[2];
if(text) then
targetText = targetText..text;
else
break;
end
end
else
break;
end
end
else
break;
end
end
if(targetText and targetText ~= "") then
local nOffset = 0;
while(true) do
nOffset = nOffset - 1;
local nextMacro = Macros:PeekNextMacro(nOffset)
if(nextMacro and (nextMacro.name == "Idle" or nextMacro.name == "WindowKeyPressTrigger" or nextMacro.name == "WindowInputMethod" or nextMacro.name == "WindowKeyPress")) then
if(nextMacro.name ~= "Idle") then
local nextUIName = nextMacro:GetParams()[1];
if(nextUIName == ctrlName) then
if(nextMacro.name == "WindowKeyPress") then
local text = nextMacro:GetParams()[2];
if(not text or not Macros.IsButtonLetter(text)) then
break;
end
elseif(nextMacro.name == "WindowInputMethod") then
local text = nextMacro:GetParams()[2];
if(text) then
targetText = text..targetText;
else
break;
end
end
else
break;
end
end
else
break;
end
end
end
local callback = {};
MacroPlayer.SetKeyPressTrigger(button, targetText, function()
if(callback.OnFinish) then
callback.OnFinish();
end
end);
return callback;
end
end
function Macros.SetClipboard(text)
ParaMisc.CopyTextToClipboard(text);
end
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Port_Bastok/npcs/_6k9.lua | 3 | 1083 | -----------------------------------
-- Area: Port Bastok
-- NPC: Door: Arrivals Entrance
-- @zone 236
-- @pos -80 1 -26
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x008C);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/texts/unlock-chronomancer_temporal_warden.lua | 3 | 1987 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return "New Class: #LIGHT_GREEN#Temporal Warden (Chronomancer)",
[[Time isn't a linear thing; it only appears to be. In truth it's a fabric, the very fabric that holds the universe together.
As with all great powers, there are those who seek to manipulate it and pervert it, but there are also those who seek to uphold rather than destroy.
Those who have learned to bend, rather than break, the fabric can keep the balance against dark or power-hungry forces.
You have been taught the ways of chronomancy by a Temporal Warden and can now create new characters with the #LIGHT_GREEN#Temporal Warden class#WHITE#.
Temporal Wardens are warriors proficient in both ranged and hand-to-hand combat.
Class features:#YELLOW#
- Duel-wield a medium sized and a small weapon or attack from afar with your ranged weapon skills
- Manipulate space and time to speed yourself up, create wormholes, or even throw an opponent into the future
- See into the future or even travel into the past#WHITE#
Temporal Wardens use Paradox for their powers. It represents how much damage they've done to the spacetime continuum.
The higher their paradox the greater the effect of their powers but the harder they'll be to control.
]]
| gpl-3.0 |
fyrchik/xlua | exercises/hamming/hamming_spec.lua | 3 | 1320 | local compute = require('hamming').compute
describe('hamming', function ()
it('no difference between identical strands', function ()
assert.are.equals(0, compute('A', 'A'))
end)
it('long identical strands', function ()
assert.are.equals(0, compute('GGACTGA', 'GGACTGA'))
end)
it('complete hamming distance of for single nucleotide strand', function ()
assert.are.equals(1, compute('A', 'G'))
end)
it('complete hamming distance of for small strand', function ()
assert.are.equals(2, compute('AG', 'CT'))
end)
it('small hamming distance', function ()
assert.are.equals(1, compute('AT', 'CT'))
end)
it('small hamming distance in longer strand', function ()
assert.are.equals(1, compute('GGACG', 'GGTCG'))
end)
it('non unique character in first strand', function ()
assert.are.equals(1, compute('AGA', 'AGG'))
end)
it('non unique character in second strand', function ()
assert.are.equals(1, compute('AGG', 'AGA'))
end)
it('large hamming distance', function ()
assert.are.equals(4, compute('GATACA', 'GCATAA'))
end)
it('hamming distance in very long strand', function ()
assert.are.equals(9, compute('GGACGGATTCTG', 'AGGACGGATTCT'))
end)
it('empty strands', function ()
assert.are.equals(0, compute('', ''))
end)
end)
| mit |
RyMarq/Zero-K | units/shieldraid.lua | 1 | 3601 | return { shieldraid = {
unitname = [[shieldraid]],
name = [[Bandit]],
description = [[Medium-Light Raider Bot]],
acceleration = 1.5,
brakeRate = 2.4,
buildCostMetal = 75,
buildPic = [[shieldraid.png]],
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND TOOFAST]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[24 29 24]],
collisionVolumeType = [[cylY]],
corpse = [[DEAD]],
customParams = {
modelradius = [[12]],
},
explodeAs = [[SMALL_UNITEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[walkerraider]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 330,
maxSlope = 36,
maxVelocity = 3,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT2]],
noChaseCategory = [[TERRAFORM FIXEDWING SUB]],
objectName = [[mbot.s3o]],
script = [[shieldraid.lua]],
selfDestructAs = [[SMALL_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:BEAMWEAPON_MUZZLE_RED]],
},
},
sightDistance = 560,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 18,
turnRate = 2500,
upright = true,
weapons = {
{
def = [[LASER]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
LASER = {
name = [[Laser Blaster]],
areaOfEffect = 8,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
light_camera_height = 1200,
light_radius = 120,
},
damage = {
default = 8.15,
subs = 0.4,
},
duration = 0.02,
explosionGenerator = [[custom:BEAMWEAPON_HIT_RED]],
fireStarter = 50,
heightMod = 1,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
leadLimit = 3,
noSelfDamage = true,
range = 245,
reloadtime = 0.1,
rgbColor = [[1 0 0]],
soundHit = [[weapon/laser/lasercannon_hit]],
soundStart = [[weapon/laser/small_laser_fire2]],
soundTrigger = true,
thickness = 2.55,
tolerance = 10000,
turret = true,
weaponType = [[LaserCannon]],
weaponVelocity = 880,
},
},
featureDefs = {
DEAD = {
blocking = false,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[mbot_d.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2b.s3o]],
},
},
} }
| gpl-2.0 |
RyMarq/Zero-K | LuaUI/Fonts/FreeMonoBold_12.lua | 26 | 33818 | -- $Id: FreeMonoBold_12.lua 3171 2008-11-06 09:06:29Z det $
local fontSpecs = {
srcFile = [[Fonts/FreeMonoBold.ttf]],
family = [[FreeMono]],
style = [[Bold]],
yStep = 13,
height = 12,
xTexSize = 256,
yTexSize = 256,
outlineRadius = 1,
outlineWeight = 100,
}
local glyphs = {}
glyphs[32] = { --' '--
num = 32,
adv = 7,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 1, tyn = 1, txp = 4, typ = 4,
}
glyphs[33] = { --'!'--
num = 33,
adv = 7,
oxn = 1, oyn = -2, oxp = 6, oyp = 9,
txn = 14, tyn = 1, txp = 19, typ = 12,
}
glyphs[34] = { --'"'--
num = 34,
adv = 7,
oxn = 0, oyn = 2, oxp = 7, oyp = 9,
txn = 27, tyn = 1, txp = 34, typ = 8,
}
glyphs[35] = { --'#'--
num = 35,
adv = 7,
oxn = -1, oyn = -3, oxp = 8, oyp = 10,
txn = 40, tyn = 1, txp = 49, typ = 14,
}
glyphs[36] = { --'$'--
num = 36,
adv = 7,
oxn = 0, oyn = -3, oxp = 8, oyp = 10,
txn = 53, tyn = 1, txp = 61, typ = 14,
}
glyphs[37] = { --'%'--
num = 37,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 66, tyn = 1, txp = 75, typ = 12,
}
glyphs[38] = { --'&'--
num = 38,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 8,
txn = 79, tyn = 1, txp = 88, typ = 11,
}
glyphs[39] = { --'''--
num = 39,
adv = 7,
oxn = 1, oyn = 2, oxp = 6, oyp = 9,
txn = 92, tyn = 1, txp = 97, typ = 8,
}
glyphs[40] = { --'('--
num = 40,
adv = 7,
oxn = 2, oyn = -3, oxp = 7, oyp = 9,
txn = 105, tyn = 1, txp = 110, typ = 13,
}
glyphs[41] = { --')'--
num = 41,
adv = 7,
oxn = 0, oyn = -3, oxp = 6, oyp = 9,
txn = 118, tyn = 1, txp = 124, typ = 13,
}
glyphs[42] = { --'*'--
num = 42,
adv = 7,
oxn = 0, oyn = 1, oxp = 8, oyp = 9,
txn = 131, tyn = 1, txp = 139, typ = 9,
}
glyphs[43] = { --'+'--
num = 43,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 144, tyn = 1, txp = 153, typ = 10,
}
glyphs[44] = { --','--
num = 44,
adv = 7,
oxn = 0, oyn = -3, oxp = 6, oyp = 3,
txn = 157, tyn = 1, txp = 163, typ = 7,
}
glyphs[45] = { --'-'--
num = 45,
adv = 7,
oxn = -1, oyn = 1, oxp = 8, oyp = 5,
txn = 170, tyn = 1, txp = 179, typ = 5,
}
glyphs[46] = { --'.'--
num = 46,
adv = 7,
oxn = 1, oyn = -2, oxp = 6, oyp = 3,
txn = 183, tyn = 1, txp = 188, typ = 6,
}
glyphs[47] = { --'/'--
num = 47,
adv = 7,
oxn = 0, oyn = -3, oxp = 8, oyp = 10,
txn = 196, tyn = 1, txp = 204, typ = 14,
}
glyphs[48] = { --'0'--
num = 48,
adv = 7,
oxn = 0, oyn = -2, oxp = 8, oyp = 9,
txn = 209, tyn = 1, txp = 217, typ = 12,
}
glyphs[49] = { --'1'--
num = 49,
adv = 7,
oxn = 0, oyn = -1, oxp = 8, oyp = 9,
txn = 222, tyn = 1, txp = 230, typ = 11,
}
glyphs[50] = { --'2'--
num = 50,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 235, tyn = 1, txp = 244, typ = 11,
}
glyphs[51] = { --'3'--
num = 51,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 1, tyn = 17, txp = 10, typ = 28,
}
glyphs[52] = { --'4'--
num = 52,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 14, tyn = 17, txp = 23, typ = 27,
}
glyphs[53] = { --'5'--
num = 53,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 27, tyn = 17, txp = 36, typ = 28,
}
glyphs[54] = { --'6'--
num = 54,
adv = 7,
oxn = 0, oyn = -2, oxp = 8, oyp = 9,
txn = 40, tyn = 17, txp = 48, typ = 28,
}
glyphs[55] = { --'7'--
num = 55,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 53, tyn = 17, txp = 62, typ = 28,
}
glyphs[56] = { --'8'--
num = 56,
adv = 7,
oxn = 0, oyn = -2, oxp = 8, oyp = 9,
txn = 66, tyn = 17, txp = 74, typ = 28,
}
glyphs[57] = { --'9'--
num = 57,
adv = 7,
oxn = 0, oyn = -2, oxp = 8, oyp = 9,
txn = 79, tyn = 17, txp = 87, typ = 28,
}
glyphs[58] = { --':'--
num = 58,
adv = 7,
oxn = 1, oyn = -2, oxp = 6, oyp = 7,
txn = 92, tyn = 17, txp = 97, typ = 26,
}
glyphs[59] = { --';'--
num = 59,
adv = 7,
oxn = 0, oyn = -3, oxp = 6, oyp = 7,
txn = 105, tyn = 17, txp = 111, typ = 27,
}
glyphs[60] = { --'<'--
num = 60,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 118, tyn = 17, txp = 127, typ = 26,
}
glyphs[61] = { --'='--
num = 61,
adv = 7,
oxn = -1, oyn = 0, oxp = 8, oyp = 7,
txn = 131, tyn = 17, txp = 140, typ = 24,
}
glyphs[62] = { --'>'--
num = 62,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 7,
txn = 144, tyn = 17, txp = 153, typ = 25,
}
glyphs[63] = { --'?'--
num = 63,
adv = 7,
oxn = 0, oyn = -2, oxp = 8, oyp = 9,
txn = 157, tyn = 17, txp = 165, typ = 28,
}
glyphs[64] = { --'@'--
num = 64,
adv = 7,
oxn = -1, oyn = -3, oxp = 8, oyp = 9,
txn = 170, tyn = 17, txp = 179, typ = 29,
}
glyphs[65] = { --'A'--
num = 65,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 8,
txn = 183, tyn = 17, txp = 194, typ = 26,
}
glyphs[66] = { --'B'--
num = 66,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 196, tyn = 17, txp = 205, typ = 26,
}
glyphs[67] = { --'C'--
num = 67,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 209, tyn = 17, txp = 218, typ = 28,
}
glyphs[68] = { --'D'--
num = 68,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 222, tyn = 17, txp = 231, typ = 26,
}
glyphs[69] = { --'E'--
num = 69,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 235, tyn = 17, txp = 244, typ = 26,
}
glyphs[70] = { --'F'--
num = 70,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 1, tyn = 33, txp = 10, typ = 42,
}
glyphs[71] = { --'G'--
num = 71,
adv = 7,
oxn = -1, oyn = -2, oxp = 9, oyp = 9,
txn = 14, tyn = 33, txp = 24, typ = 44,
}
glyphs[72] = { --'H'--
num = 72,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 27, tyn = 33, txp = 36, typ = 42,
}
glyphs[73] = { --'I'--
num = 73,
adv = 7,
oxn = 0, oyn = -1, oxp = 8, oyp = 8,
txn = 40, tyn = 33, txp = 48, typ = 42,
}
glyphs[74] = { --'J'--
num = 74,
adv = 7,
oxn = -1, oyn = -2, oxp = 9, oyp = 8,
txn = 53, tyn = 33, txp = 63, typ = 43,
}
glyphs[75] = { --'K'--
num = 75,
adv = 7,
oxn = -1, oyn = -1, oxp = 9, oyp = 8,
txn = 66, tyn = 33, txp = 76, typ = 42,
}
glyphs[76] = { --'L'--
num = 76,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 79, tyn = 33, txp = 88, typ = 42,
}
glyphs[77] = { --'M'--
num = 77,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 9,
txn = 92, tyn = 33, txp = 103, typ = 43,
}
glyphs[78] = { --'N'--
num = 78,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 8,
txn = 105, tyn = 33, txp = 116, typ = 42,
}
glyphs[79] = { --'O'--
num = 79,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 118, tyn = 33, txp = 127, typ = 44,
}
glyphs[80] = { --'P'--
num = 80,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 131, tyn = 33, txp = 140, typ = 42,
}
glyphs[81] = { --'Q'--
num = 81,
adv = 7,
oxn = -1, oyn = -3, oxp = 8, oyp = 9,
txn = 144, tyn = 33, txp = 153, typ = 45,
}
glyphs[82] = { --'R'--
num = 82,
adv = 7,
oxn = -1, oyn = -1, oxp = 9, oyp = 8,
txn = 157, tyn = 33, txp = 167, typ = 42,
}
glyphs[83] = { --'S'--
num = 83,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 170, tyn = 33, txp = 179, typ = 44,
}
glyphs[84] = { --'T'--
num = 84,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 183, tyn = 33, txp = 192, typ = 42,
}
glyphs[85] = { --'U'--
num = 85,
adv = 7,
oxn = -1, oyn = -2, oxp = 9, oyp = 8,
txn = 196, tyn = 33, txp = 206, typ = 43,
}
glyphs[86] = { --'V'--
num = 86,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 8,
txn = 209, tyn = 33, txp = 220, typ = 42,
}
glyphs[87] = { --'W'--
num = 87,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 8,
txn = 222, tyn = 33, txp = 233, typ = 42,
}
glyphs[88] = { --'X'--
num = 88,
adv = 7,
oxn = -1, oyn = -1, oxp = 9, oyp = 8,
txn = 235, tyn = 33, txp = 245, typ = 42,
}
glyphs[89] = { --'Y'--
num = 89,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 1, tyn = 49, txp = 10, typ = 58,
}
glyphs[90] = { --'Z'--
num = 90,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 14, tyn = 49, txp = 23, typ = 58,
}
glyphs[91] = { --'['--
num = 91,
adv = 7,
oxn = 2, oyn = -3, oxp = 7, oyp = 9,
txn = 27, tyn = 49, txp = 32, typ = 61,
}
glyphs[92] = { --'\'--
num = 92,
adv = 7,
oxn = 0, oyn = -3, oxp = 8, oyp = 10,
txn = 40, tyn = 49, txp = 48, typ = 62,
}
glyphs[93] = { --']'--
num = 93,
adv = 7,
oxn = 0, oyn = -3, oxp = 6, oyp = 9,
txn = 53, tyn = 49, txp = 59, typ = 61,
}
glyphs[94] = { --'^'--
num = 94,
adv = 7,
oxn = 0, oyn = 2, oxp = 8, oyp = 9,
txn = 66, tyn = 49, txp = 74, typ = 56,
}
glyphs[95] = { --'_'--
num = 95,
adv = 7,
oxn = -2, oyn = -3, oxp = 9, oyp = 1,
txn = 79, tyn = 49, txp = 90, typ = 53,
}
glyphs[96] = { --'`'--
num = 96,
adv = 7,
oxn = 0, oyn = 4, oxp = 6, oyp = 10,
txn = 92, tyn = 49, txp = 98, typ = 55,
}
glyphs[97] = { --'a'--
num = 97,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 7,
txn = 105, tyn = 49, txp = 114, typ = 58,
}
glyphs[98] = { --'b'--
num = 98,
adv = 7,
oxn = -2, oyn = -2, oxp = 8, oyp = 9,
txn = 118, tyn = 49, txp = 128, typ = 60,
}
glyphs[99] = { --'c'--
num = 99,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 7,
txn = 131, tyn = 49, txp = 140, typ = 58,
}
glyphs[100] = { --'d'--
num = 100,
adv = 7,
oxn = -1, oyn = -2, oxp = 9, oyp = 9,
txn = 144, tyn = 49, txp = 154, typ = 60,
}
glyphs[101] = { --'e'--
num = 101,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 7,
txn = 157, tyn = 49, txp = 166, typ = 58,
}
glyphs[102] = { --'f'--
num = 102,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 170, tyn = 49, txp = 179, typ = 59,
}
glyphs[103] = { --'g'--
num = 103,
adv = 7,
oxn = -1, oyn = -4, oxp = 9, oyp = 7,
txn = 183, tyn = 49, txp = 193, typ = 60,
}
glyphs[104] = { --'h'--
num = 104,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 196, tyn = 49, txp = 205, typ = 59,
}
glyphs[105] = { --'i'--
num = 105,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 209, tyn = 49, txp = 218, typ = 59,
}
glyphs[106] = { --'j'--
num = 106,
adv = 7,
oxn = 0, oyn = -4, oxp = 7, oyp = 9,
txn = 222, tyn = 49, txp = 229, typ = 62,
}
glyphs[107] = { --'k'--
num = 107,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 235, tyn = 49, txp = 244, typ = 59,
}
glyphs[108] = { --'l'--
num = 108,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 1, tyn = 65, txp = 10, typ = 75,
}
glyphs[109] = { --'m'--
num = 109,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 7,
txn = 14, tyn = 65, txp = 25, typ = 73,
}
glyphs[110] = { --'n'--
num = 110,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 7,
txn = 27, tyn = 65, txp = 36, typ = 73,
}
glyphs[111] = { --'o'--
num = 111,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 7,
txn = 40, tyn = 65, txp = 49, typ = 74,
}
glyphs[112] = { --'p'--
num = 112,
adv = 7,
oxn = -2, oyn = -4, oxp = 8, oyp = 7,
txn = 53, tyn = 65, txp = 63, typ = 76,
}
glyphs[113] = { --'q'--
num = 113,
adv = 7,
oxn = -1, oyn = -4, oxp = 9, oyp = 7,
txn = 66, tyn = 65, txp = 76, typ = 76,
}
glyphs[114] = { --'r'--
num = 114,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 7,
txn = 79, tyn = 65, txp = 88, typ = 73,
}
glyphs[115] = { --'s'--
num = 115,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 7,
txn = 92, tyn = 65, txp = 101, typ = 74,
}
glyphs[116] = { --'t'--
num = 116,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 105, tyn = 65, txp = 114, typ = 76,
}
glyphs[117] = { --'u'--
num = 117,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 7,
txn = 118, tyn = 65, txp = 127, typ = 74,
}
glyphs[118] = { --'v'--
num = 118,
adv = 7,
oxn = -1, oyn = -1, oxp = 9, oyp = 7,
txn = 131, tyn = 65, txp = 141, typ = 73,
}
glyphs[119] = { --'w'--
num = 119,
adv = 7,
oxn = -1, oyn = -1, oxp = 9, oyp = 7,
txn = 144, tyn = 65, txp = 154, typ = 73,
}
glyphs[120] = { --'x'--
num = 120,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 7,
txn = 157, tyn = 65, txp = 166, typ = 73,
}
glyphs[121] = { --'y'--
num = 121,
adv = 7,
oxn = -1, oyn = -4, oxp = 8, oyp = 7,
txn = 170, tyn = 65, txp = 179, typ = 76,
}
glyphs[122] = { --'z'--
num = 122,
adv = 7,
oxn = 0, oyn = -1, oxp = 8, oyp = 7,
txn = 183, tyn = 65, txp = 191, typ = 73,
}
glyphs[123] = { --'{'--
num = 123,
adv = 7,
oxn = 1, oyn = -3, oxp = 7, oyp = 9,
txn = 196, tyn = 65, txp = 202, typ = 77,
}
glyphs[124] = { --'|'--
num = 124,
adv = 7,
oxn = 2, oyn = -3, oxp = 6, oyp = 9,
txn = 209, tyn = 65, txp = 213, typ = 77,
}
glyphs[125] = { --'}'--
num = 125,
adv = 7,
oxn = 1, oyn = -3, oxp = 7, oyp = 9,
txn = 222, tyn = 65, txp = 228, typ = 77,
}
glyphs[126] = { --'~'--
num = 126,
adv = 7,
oxn = -1, oyn = 1, oxp = 8, oyp = 6,
txn = 235, tyn = 65, txp = 244, typ = 70,
}
glyphs[127] = { --''--
num = 127,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 1, tyn = 81, txp = 8, typ = 92,
}
glyphs[128] = { --''--
num = 128,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 14, tyn = 81, txp = 21, typ = 92,
}
glyphs[129] = { --''--
num = 129,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 27, tyn = 81, txp = 34, typ = 92,
}
glyphs[130] = { --''--
num = 130,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 40, tyn = 81, txp = 47, typ = 92,
}
glyphs[131] = { --''--
num = 131,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 53, tyn = 81, txp = 60, typ = 92,
}
glyphs[132] = { --''--
num = 132,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 66, tyn = 81, txp = 73, typ = 92,
}
glyphs[133] = { --'
'--
num = 133,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 79, tyn = 81, txp = 86, typ = 92,
}
glyphs[134] = { --''--
num = 134,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 92, tyn = 81, txp = 99, typ = 92,
}
glyphs[135] = { --''--
num = 135,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 105, tyn = 81, txp = 112, typ = 92,
}
glyphs[136] = { --''--
num = 136,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 118, tyn = 81, txp = 125, typ = 92,
}
glyphs[137] = { --''--
num = 137,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 131, tyn = 81, txp = 138, typ = 92,
}
glyphs[138] = { --''--
num = 138,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 144, tyn = 81, txp = 151, typ = 92,
}
glyphs[139] = { --''--
num = 139,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 157, tyn = 81, txp = 164, typ = 92,
}
glyphs[140] = { --''--
num = 140,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 170, tyn = 81, txp = 177, typ = 92,
}
glyphs[141] = { --''--
num = 141,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 183, tyn = 81, txp = 190, typ = 92,
}
glyphs[142] = { --''--
num = 142,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 196, tyn = 81, txp = 203, typ = 92,
}
glyphs[143] = { --''--
num = 143,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 209, tyn = 81, txp = 216, typ = 92,
}
glyphs[144] = { --''--
num = 144,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 222, tyn = 81, txp = 229, typ = 92,
}
glyphs[145] = { --''--
num = 145,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 235, tyn = 81, txp = 242, typ = 92,
}
glyphs[146] = { --''--
num = 146,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 1, tyn = 97, txp = 8, typ = 108,
}
glyphs[147] = { --''--
num = 147,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 14, tyn = 97, txp = 21, typ = 108,
}
glyphs[148] = { --''--
num = 148,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 27, tyn = 97, txp = 34, typ = 108,
}
glyphs[149] = { --''--
num = 149,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 40, tyn = 97, txp = 47, typ = 108,
}
glyphs[150] = { --''--
num = 150,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 53, tyn = 97, txp = 60, typ = 108,
}
glyphs[151] = { --''--
num = 151,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 66, tyn = 97, txp = 73, typ = 108,
}
glyphs[152] = { --''--
num = 152,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 79, tyn = 97, txp = 86, typ = 108,
}
glyphs[153] = { --''--
num = 153,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 92, tyn = 97, txp = 99, typ = 108,
}
glyphs[154] = { --''--
num = 154,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 105, tyn = 97, txp = 112, typ = 108,
}
glyphs[155] = { --''--
num = 155,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 118, tyn = 97, txp = 125, typ = 108,
}
glyphs[156] = { --''--
num = 156,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 131, tyn = 97, txp = 138, typ = 108,
}
glyphs[157] = { --''--
num = 157,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 144, tyn = 97, txp = 151, typ = 108,
}
glyphs[158] = { --''--
num = 158,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 157, tyn = 97, txp = 164, typ = 108,
}
glyphs[159] = { --''--
num = 159,
adv = 7,
oxn = -1, oyn = -1, oxp = 6, oyp = 10,
txn = 170, tyn = 97, txp = 177, typ = 108,
}
glyphs[160] = { --' '--
num = 160,
adv = 7,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 183, tyn = 97, txp = 186, typ = 100,
}
glyphs[161] = { --'¡'--
num = 161,
adv = 7,
oxn = 1, oyn = -4, oxp = 6, oyp = 7,
txn = 196, tyn = 97, txp = 201, typ = 108,
}
glyphs[162] = { --'¢'--
num = 162,
adv = 7,
oxn = 0, oyn = -2, oxp = 7, oyp = 9,
txn = 209, tyn = 97, txp = 216, typ = 108,
}
glyphs[163] = { --'£'--
num = 163,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 222, tyn = 97, txp = 231, typ = 107,
}
glyphs[164] = { --'¤'--
num = 164,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 235, tyn = 97, txp = 244, typ = 106,
}
glyphs[165] = { --'¥'--
num = 165,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 1, tyn = 113, txp = 10, typ = 122,
}
glyphs[166] = { --'¦'--
num = 166,
adv = 7,
oxn = 2, oyn = -3, oxp = 6, oyp = 9,
txn = 14, tyn = 113, txp = 18, typ = 125,
}
glyphs[167] = { --'§'--
num = 167,
adv = 7,
oxn = -1, oyn = -4, oxp = 8, oyp = 8,
txn = 27, tyn = 113, txp = 36, typ = 125,
}
glyphs[168] = { --'¨'--
num = 168,
adv = 7,
oxn = 0, oyn = 5, oxp = 7, oyp = 9,
txn = 40, tyn = 113, txp = 47, typ = 117,
}
glyphs[169] = { --'©'--
num = 169,
adv = 7,
oxn = -2, oyn = -2, oxp = 9, oyp = 9,
txn = 53, tyn = 113, txp = 64, typ = 124,
}
glyphs[170] = { --'ª'--
num = 170,
adv = 7,
oxn = 0, oyn = 1, oxp = 7, oyp = 9,
txn = 66, tyn = 113, txp = 73, typ = 121,
}
glyphs[171] = { --'«'--
num = 171,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 6,
txn = 79, tyn = 113, txp = 88, typ = 120,
}
glyphs[172] = { --'¬'--
num = 172,
adv = 7,
oxn = -1, oyn = 0, oxp = 7, oyp = 7,
txn = 92, tyn = 113, txp = 100, typ = 120,
}
glyphs[173] = { --''--
num = 173,
adv = 7,
oxn = -1, oyn = 1, oxp = 8, oyp = 5,
txn = 105, tyn = 113, txp = 114, typ = 117,
}
glyphs[174] = { --'®'--
num = 174,
adv = 7,
oxn = -2, oyn = -2, oxp = 9, oyp = 9,
txn = 118, tyn = 113, txp = 129, typ = 124,
}
glyphs[175] = { --'¯'--
num = 175,
adv = 7,
oxn = 0, oyn = 5, oxp = 7, oyp = 9,
txn = 131, tyn = 113, txp = 138, typ = 117,
}
glyphs[176] = { --'°'--
num = 176,
adv = 7,
oxn = 0, oyn = 1, oxp = 7, oyp = 9,
txn = 144, tyn = 113, txp = 151, typ = 121,
}
glyphs[177] = { --'±'--
num = 177,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 157, tyn = 113, txp = 166, typ = 123,
}
glyphs[178] = { --'²'--
num = 178,
adv = 7,
oxn = 0, oyn = 1, oxp = 7, oyp = 9,
txn = 170, tyn = 113, txp = 177, typ = 121,
}
glyphs[179] = { --'³'--
num = 179,
adv = 7,
oxn = 0, oyn = 1, oxp = 7, oyp = 9,
txn = 183, tyn = 113, txp = 190, typ = 121,
}
glyphs[180] = { --'´'--
num = 180,
adv = 7,
oxn = 2, oyn = 4, oxp = 7, oyp = 10,
txn = 196, tyn = 113, txp = 201, typ = 119,
}
glyphs[181] = { --'µ'--
num = 181,
adv = 7,
oxn = -1, oyn = -3, oxp = 8, oyp = 7,
txn = 209, tyn = 113, txp = 218, typ = 123,
}
glyphs[182] = { --'¶'--
num = 182,
adv = 7,
oxn = -1, oyn = -4, oxp = 8, oyp = 8,
txn = 222, tyn = 113, txp = 231, typ = 125,
}
glyphs[183] = { --'·'--
num = 183,
adv = 7,
oxn = 1, oyn = 1, oxp = 6, oyp = 6,
txn = 235, tyn = 113, txp = 240, typ = 118,
}
glyphs[184] = { --'¸'--
num = 184,
adv = 7,
oxn = 1, oyn = -4, oxp = 6, oyp = 1,
txn = 1, tyn = 129, txp = 6, typ = 134,
}
glyphs[185] = { --'¹'--
num = 185,
adv = 7,
oxn = 0, oyn = 1, oxp = 7, oyp = 9,
txn = 14, tyn = 129, txp = 21, typ = 137,
}
glyphs[186] = { --'º'--
num = 186,
adv = 7,
oxn = 0, oyn = 1, oxp = 7, oyp = 9,
txn = 27, tyn = 129, txp = 34, typ = 137,
}
glyphs[187] = { --'»'--
num = 187,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 6,
txn = 40, tyn = 129, txp = 49, typ = 136,
}
glyphs[188] = { --'¼'--
num = 188,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 9,
txn = 53, tyn = 129, txp = 64, typ = 139,
}
glyphs[189] = { --'½'--
num = 189,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 9,
txn = 66, tyn = 129, txp = 77, typ = 139,
}
glyphs[190] = { --'¾'--
num = 190,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 9,
txn = 79, tyn = 129, txp = 90, typ = 139,
}
glyphs[191] = { --'¿'--
num = 191,
adv = 7,
oxn = -1, oyn = -5, oxp = 7, oyp = 6,
txn = 92, tyn = 129, txp = 100, typ = 140,
}
glyphs[192] = { --'À'--
num = 192,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 12,
txn = 105, tyn = 129, txp = 116, typ = 142,
}
glyphs[193] = { --'Á'--
num = 193,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 12,
txn = 118, tyn = 129, txp = 129, typ = 142,
}
glyphs[194] = { --'Â'--
num = 194,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 12,
txn = 131, tyn = 129, txp = 142, typ = 142,
}
glyphs[195] = { --'Ã'--
num = 195,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 11,
txn = 144, tyn = 129, txp = 155, typ = 141,
}
glyphs[196] = { --'Ä'--
num = 196,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 11,
txn = 157, tyn = 129, txp = 168, typ = 141,
}
glyphs[197] = { --'Å'--
num = 197,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 12,
txn = 170, tyn = 129, txp = 181, typ = 142,
}
glyphs[198] = { --'Æ'--
num = 198,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 8,
txn = 183, tyn = 129, txp = 194, typ = 138,
}
glyphs[199] = { --'Ç'--
num = 199,
adv = 7,
oxn = -1, oyn = -4, oxp = 8, oyp = 9,
txn = 196, tyn = 129, txp = 205, typ = 142,
}
glyphs[200] = { --'È'--
num = 200,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 12,
txn = 209, tyn = 129, txp = 218, typ = 142,
}
glyphs[201] = { --'É'--
num = 201,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 12,
txn = 222, tyn = 129, txp = 231, typ = 142,
}
glyphs[202] = { --'Ê'--
num = 202,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 12,
txn = 235, tyn = 129, txp = 244, typ = 142,
}
glyphs[203] = { --'Ë'--
num = 203,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 11,
txn = 1, tyn = 145, txp = 10, typ = 157,
}
glyphs[204] = { --'Ì'--
num = 204,
adv = 7,
oxn = 0, oyn = -1, oxp = 8, oyp = 12,
txn = 14, tyn = 145, txp = 22, typ = 158,
}
glyphs[205] = { --'Í'--
num = 205,
adv = 7,
oxn = 0, oyn = -1, oxp = 8, oyp = 12,
txn = 27, tyn = 145, txp = 35, typ = 158,
}
glyphs[206] = { --'Î'--
num = 206,
adv = 7,
oxn = 0, oyn = -1, oxp = 8, oyp = 12,
txn = 40, tyn = 145, txp = 48, typ = 158,
}
glyphs[207] = { --'Ï'--
num = 207,
adv = 7,
oxn = 0, oyn = -1, oxp = 8, oyp = 11,
txn = 53, tyn = 145, txp = 61, typ = 157,
}
glyphs[208] = { --'Ð'--
num = 208,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 66, tyn = 145, txp = 75, typ = 154,
}
glyphs[209] = { --'Ñ'--
num = 209,
adv = 7,
oxn = -2, oyn = -1, oxp = 9, oyp = 11,
txn = 79, tyn = 145, txp = 90, typ = 157,
}
glyphs[210] = { --'Ò'--
num = 210,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 12,
txn = 92, tyn = 145, txp = 101, typ = 159,
}
glyphs[211] = { --'Ó'--
num = 211,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 12,
txn = 105, tyn = 145, txp = 114, typ = 159,
}
glyphs[212] = { --'Ô'--
num = 212,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 12,
txn = 118, tyn = 145, txp = 127, typ = 159,
}
glyphs[213] = { --'Õ'--
num = 213,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 11,
txn = 131, tyn = 145, txp = 140, typ = 158,
}
glyphs[214] = { --'Ö'--
num = 214,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 11,
txn = 144, tyn = 145, txp = 153, typ = 158,
}
glyphs[215] = { --'×'--
num = 215,
adv = 7,
oxn = 0, oyn = -1, oxp = 7, oyp = 7,
txn = 157, tyn = 145, txp = 164, typ = 153,
}
glyphs[216] = { --'Ø'--
num = 216,
adv = 7,
oxn = -1, oyn = -2, oxp = 9, oyp = 9,
txn = 170, tyn = 145, txp = 180, typ = 156,
}
glyphs[217] = { --'Ù'--
num = 217,
adv = 7,
oxn = -1, oyn = -2, oxp = 9, oyp = 12,
txn = 183, tyn = 145, txp = 193, typ = 159,
}
glyphs[218] = { --'Ú'--
num = 218,
adv = 7,
oxn = -1, oyn = -2, oxp = 9, oyp = 12,
txn = 196, tyn = 145, txp = 206, typ = 159,
}
glyphs[219] = { --'Û'--
num = 219,
adv = 7,
oxn = -1, oyn = -2, oxp = 9, oyp = 12,
txn = 209, tyn = 145, txp = 219, typ = 159,
}
glyphs[220] = { --'Ü'--
num = 220,
adv = 7,
oxn = -1, oyn = -2, oxp = 9, oyp = 11,
txn = 222, tyn = 145, txp = 232, typ = 158,
}
glyphs[221] = { --'Ý'--
num = 221,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 12,
txn = 235, tyn = 145, txp = 244, typ = 158,
}
glyphs[222] = { --'Þ'--
num = 222,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 1, tyn = 161, txp = 10, typ = 170,
}
glyphs[223] = { --'ß'--
num = 223,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 14, tyn = 161, txp = 23, typ = 172,
}
glyphs[224] = { --'à'--
num = 224,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 27, tyn = 161, txp = 36, typ = 173,
}
glyphs[225] = { --'á'--
num = 225,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 40, tyn = 161, txp = 49, typ = 173,
}
glyphs[226] = { --'â'--
num = 226,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 53, tyn = 161, txp = 62, typ = 173,
}
glyphs[227] = { --'ã'--
num = 227,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 66, tyn = 161, txp = 75, typ = 172,
}
glyphs[228] = { --'ä'--
num = 228,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 79, tyn = 161, txp = 88, typ = 172,
}
glyphs[229] = { --'å'--
num = 229,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 92, tyn = 161, txp = 101, typ = 173,
}
glyphs[230] = { --'æ'--
num = 230,
adv = 7,
oxn = -2, oyn = -2, oxp = 9, oyp = 7,
txn = 105, tyn = 161, txp = 116, typ = 170,
}
glyphs[231] = { --'ç'--
num = 231,
adv = 7,
oxn = -1, oyn = -4, oxp = 8, oyp = 7,
txn = 118, tyn = 161, txp = 127, typ = 172,
}
glyphs[232] = { --'è'--
num = 232,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 131, tyn = 161, txp = 140, typ = 173,
}
glyphs[233] = { --'é'--
num = 233,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 144, tyn = 161, txp = 153, typ = 173,
}
glyphs[234] = { --'ê'--
num = 234,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 157, tyn = 161, txp = 166, typ = 173,
}
glyphs[235] = { --'ë'--
num = 235,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 170, tyn = 161, txp = 179, typ = 172,
}
glyphs[236] = { --'ì'--
num = 236,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 10,
txn = 183, tyn = 161, txp = 192, typ = 172,
}
glyphs[237] = { --'í'--
num = 237,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 10,
txn = 196, tyn = 161, txp = 205, typ = 172,
}
glyphs[238] = { --'î'--
num = 238,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 10,
txn = 209, tyn = 161, txp = 218, typ = 172,
}
glyphs[239] = { --'ï'--
num = 239,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 222, tyn = 161, txp = 231, typ = 171,
}
glyphs[240] = { --'ð'--
num = 240,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 235, tyn = 161, txp = 244, typ = 172,
}
glyphs[241] = { --'ñ'--
num = 241,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 9,
txn = 1, tyn = 177, txp = 10, typ = 187,
}
glyphs[242] = { --'ò'--
num = 242,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 14, tyn = 177, txp = 23, typ = 189,
}
glyphs[243] = { --'ó'--
num = 243,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 27, tyn = 177, txp = 36, typ = 189,
}
glyphs[244] = { --'ô'--
num = 244,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 40, tyn = 177, txp = 49, typ = 189,
}
glyphs[245] = { --'õ'--
num = 245,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 53, tyn = 177, txp = 62, typ = 188,
}
glyphs[246] = { --'ö'--
num = 246,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 66, tyn = 177, txp = 75, typ = 188,
}
glyphs[247] = { --'÷'--
num = 247,
adv = 7,
oxn = -1, oyn = -1, oxp = 8, oyp = 8,
txn = 79, tyn = 177, txp = 88, typ = 186,
}
glyphs[248] = { --'ø'--
num = 248,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 7,
txn = 92, tyn = 177, txp = 101, typ = 186,
}
glyphs[249] = { --'ù'--
num = 249,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 105, tyn = 177, txp = 114, typ = 189,
}
glyphs[250] = { --'ú'--
num = 250,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 118, tyn = 177, txp = 127, typ = 189,
}
glyphs[251] = { --'û'--
num = 251,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 10,
txn = 131, tyn = 177, txp = 140, typ = 189,
}
glyphs[252] = { --'ü'--
num = 252,
adv = 7,
oxn = -1, oyn = -2, oxp = 8, oyp = 9,
txn = 144, tyn = 177, txp = 153, typ = 188,
}
glyphs[253] = { --'ý'--
num = 253,
adv = 7,
oxn = -1, oyn = -4, oxp = 8, oyp = 10,
txn = 157, tyn = 177, txp = 166, typ = 191,
}
glyphs[254] = { --'þ'--
num = 254,
adv = 7,
oxn = -2, oyn = -4, oxp = 8, oyp = 9,
txn = 170, tyn = 177, txp = 180, typ = 190,
}
glyphs[255] = { --'ÿ'--
num = 255,
adv = 7,
oxn = -1, oyn = -4, oxp = 8, oyp = 9,
txn = 183, tyn = 177, txp = 192, typ = 190,
}
fontSpecs.glyphs = glyphs
return fontSpecs
| gpl-2.0 |
RyMarq/Zero-K | effects/gundam_electric_explosion.lua | 25 | 4463 | -- electric_explosion
return {
["electric_explosion"] = {
dirt = {
count = 4,
ground = true,
properties = {
alphafalloff = 2,
alwaysvisible = true,
color = [[0.2, 0.1, 0.05]],
pos = [[r-10 r10, 0, r-10 r10]],
size = 20,
speed = [[r1.5 r-1.5, 2, r1.5 r-1.5]],
},
},
electric1 = {
air = true,
class = [[heatcloud]],
count = 3,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 1.1,
maxheat = 15,
pos = [[r-2 r2, 5, r-2 r2]],
size = 1,
sizegrowth = 15,
speed = [[0, 1 0, 0]],
texture = [[electnovaexplo]],
},
},
electric2 = {
air = true,
class = [[heatcloud]],
count = 1,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 1.3,
maxheat = 15,
pos = [[r-2 r2, 5, r-2 r2]],
size = 3,
sizegrowth = 25,
speed = [[0, 0, 0]],
texture = [[flare]],
},
},
electricarcs1 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[1.0 1.0 1.0 0.04 0.2 0.5 0.9 0.01 0.1 0.5 0.7 0.01]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.05, 0]],
numparticles = 14,
particlelife = 10,
particlelifespread = 5,
particlesize = 10,
particlesizespread = 0,
particlespeed = 5,
particlespeedspread = 5,
pos = [[0, 2, 0]],
sizegrowth = 1,
sizemod = 1.0,
texture = [[lightening]],
useairlos = false,
},
},
groundflash = {
air = true,
alwaysvisible = true,
circlealpha = 0.6,
circlegrowth = 6,
flashalpha = 0.9,
flashsize = 220,
ground = true,
ttl = 13,
water = true,
color = {
[1] = 0,
[2] = 0.5,
[3] = 1,
},
},
moredots = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[1.0 1.0 1.0 0.05 0.2 0.5 0.9 0.01 0.1 0.1 0.8 0.00]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.1, 0]],
numparticles = 16,
particlelife = 5,
particlelifespread = 16,
particlesize = 25,
particlesizespread = 0,
particlespeed = 10,
particlespeedspread = 3,
pos = [[0, 2, 0]],
sizegrowth = 0.5,
sizemod = 1,
texture = [[randdots]],
useairlos = false,
},
},
whiteglow = {
air = true,
class = [[heatcloud]],
count = 2,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 1.1,
maxheat = 15,
pos = [[0, 5, 0]],
size = 10,
sizegrowth = 20,
speed = [[0, 1 0, 0]],
texture = [[laserend]],
},
},
},
}
| gpl-2.0 |
RyMarq/Zero-K | LuaUI/Widgets/gui_chili_selections_and_cursortip.lua | 1 | 73604 |
function widget:GetInfo()
return {
name = "Chili Selections & CursorTip v2",
desc = "Chili Selection Window and Cursor Tooltip remade.",
author = "GoogleFrog", -- (CarRepairer and jK orginal)
date = "9 February 2017",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true,
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
VFS.Include("LuaRules/Configs/customcmds.h.lua")
include("Widgets/COFCTools/ExportUtilities.lua")
local spGetMouseState = Spring.GetMouseState
local spTraceScreenRay = Spring.TraceScreenRay
local spGetUnitHealth = Spring.GetUnitHealth
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local spGetGameRulesParam = Spring.GetGameRulesParam
local spGetModKeyState = Spring.GetModKeyState
local spSelectUnitArray = Spring.SelectUnitArray
local spGetUnitWeaponState = Spring.GetUnitWeaponState
local spGetUnitCurrentBuildPower = Spring.GetUnitCurrentBuildPower
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spScaledGetMouseState = Spring.ScaledGetMouseState
local GetUnitBuildSpeed = Spring.Utilities.GetUnitBuildSpeed
local GetHumanName = Spring.Utilities.GetHumanName
local GetUnitCost = Spring.Utilities.GetUnitCost
local GetDescription = Spring.Utilities.GetDescription
local strFormat = string.format
local green = '\255\1\255\1'
local red = '\255\255\1\1'
local cyan = '\255\1\255\255'
local white = '\255\255\255\255'
local yellow = '\255\255\255\1'
local selectionTooltip = "\n" .. green .. WG.Translate("interface", "lmb") .. ": " .. WG.Translate("interface", "select") .. "\n" ..
green .. WG.Translate("interface", "rmb") .. ": " .. WG.Translate("interface", "deselect") .. "\n" ..
green .. WG.Translate("interface", "shift") .. "+" .. WG.Translate("interface", "lmb") .. ": " .. WG.Translate("interface", "select_type") .. "\n" ..
green .. WG.Translate("interface", "shift") .. "+" .. WG.Translate("interface", "rmb") .. ": " .. WG.Translate("interface", "deselect_type") .. "\n" ..
green .. WG.Translate("interface", "mmb") .. ": " .. WG.Translate("interface", "go_to")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local Chili
local screen0
local screenWidth, screenHeight = Spring.GetWindowGeometry()
local tooltipWindow
local selectionWindow
local ICON_SIZE = 20
local BAR_SIZE = 22
local BAR_FONT = 13
local BAR_SPACING = 24
local IMAGE_FONT = 10
local DESC_FONT = 10
local TOOLTIP_FONT = 12
local NAME_FONT = 14
local LEFT_SPACE = 24
local LEFT_LABEL_HEIGHT = 16
local SEL_BUTTON_SHORTENING = 2
local LEFT_WIDTH = 55
local PIC_HEIGHT = LEFT_WIDTH*4/5
local RIGHT_WIDTH = 235
local GROUP_STATS_WIDTH = 150
local IMAGE = {
HEALTH = 'LuaUI/images/commands/bold/health.png',
SHIELD = 'LuaUI/Images/commands/Bold/guard.png',
BUILD = 'LuaUI/Images/commands/Bold/buildsmall.png',
COST = 'LuaUI/images/costIcon.png',
TIME = 'LuaUI/images/clock.png',
METAL = 'LuaUI/images/metalplus.png',
ENERGY = 'LuaUI/images/energyplus.png',
METAL_RECLAIM = 'LuaUI/images/ibeamReclaim.png',
ENERGY_RECLAIM = 'LuaUI/images/energyReclaim.png',
}
local CURSOR_ERASE = 'eraser'
local CURSOR_POINT = 'flagtext'
local CURSOR_DRAW = 'pencil'
local CURSOR_ERASE_NAME = "map_erase"
local CURSOR_POINT_NAME = "map_point"
local CURSOR_DRAW_NAME = "map_draw"
local NO_TOOLTIP = "NONE"
local iconTypesPath = LUAUI_DIRNAME .. "Configs/icontypes.lua"
local icontypes = VFS.FileExists(iconTypesPath) and VFS.Include(iconTypesPath)
local _, iconFormat = VFS.Include(LUAUI_DIRNAME .. "Configs/chilitip_conf.lua" , nil, VFS.ZIP)
local UNIT_BURST_DAMAGES = VFS.Include(LUAUI_DIRNAME .. "Configs/burst_damages.lua" , nil, VFS.ZIP)
local terraformGeneralTip =
green.. 'Click&Drag'..white..': Free draw terraform. \n'..
green.. 'Alt+Click&Drag'..white..': Box terraform. \n'..
green.. 'Alt+Ctrl+Click&Drag'..white..': Hollow box terraform. \n'..
green.. 'Ctrl+Click on unit' ..white..': Terraform around unit. \n'..
'\n'
local terraCmdTip = {
[CMD_RAMP] =
yellow..'[Ramp between two points]\n'..
'1: ' .. green.. 'Click&Drag'..white..' from start to end. \n' ..
'2: ' .. green.. 'Click' ..white..' again to set width. \n'..
'\n'..
yellow..'[Ramp with raised end]\n'..
'1: ' .. green.. 'Click'..white..' at start. \n'..
'2: ' .. green.. 'Click&Drag'..white..' at end to set height. \n'..
'3: ' .. green.. 'Click' ..white..' again to set width. \n'..
'\n'..
yellow..'[Modifiers]\n'..
'- Hold '.. green..'Ctrl or Alt'..white..' and '.. green..'drag' ..white..' in Step 1 to set start height. \n'..
'- Hold '.. green..'Alt'..white..' to snap height or gradient. \n'..
'- Press '..green.. 'Space'..white..' to cycle raise/lower. \n'..
'\n'..
yellow..'[Wireframe indicator colors]\n'..
green.. 'Green'..white..': All units can traverse. \n'..
green.. 'Yellow'..white..': Vehicles cannot traverse. \n'..
green.. 'Red'..white..': Only all-terrain units can traverse.',
[CMD_LEVEL] = terraformGeneralTip ..
yellow..'[During Terraform Draw]\n'..
green.. 'Ctrl'..white..': Draw straight line segment. \n'..
'\n'..
yellow..'[After Terraform Draw]\n'..
green.. 'Alt'..white..': Snap to starting height / below water level (prevent ships) / below water level (prevent land units). \n'..
green.. 'Ctrl'..white..': Hold and point at terrain to level to height pointed at.\n'..
'\n'..
yellow..'[Any Time]\n'..
green.. 'Space'..white..': Cycle through only raise/lower',
[CMD_RAISE] = terraformGeneralTip ..
yellow..'[During Terraform Draw]\n'..
green.. 'Ctrl'..white..': Draw straight line segment. \n'..
'\n'..
yellow..'[After Terraform Draw]\n'..
green.. 'Alt'..white..': Snap to steps of 15 height. \n'..
green.. 'Ctrl'..white..': Snap to 0 height.',
[CMD_SMOOTH] = terraformGeneralTip ..
yellow..'[During Terraform Draw]\n'..
green.. 'Ctrl'..white..': Draw straight line segment.',
[CMD_RESTORE] = terraformGeneralTip ..
yellow..'[Any Time]\n'..
green.. 'Space'..white..': Limit to only raise/lower',
}
local DRAWING_TOOLTIP =
green.. 'Left click'..white..': Draw on map. \n' ..
green.. 'Right click'..white..': Erase. \n' ..
green.. 'Middle click'..white..': Place marker. \n' ..
green.. 'Double click'..white..': Place marker with label.'
local reloadBarColor = {013, 245, 243, 1}
local fullHealthBarColor = {0, 255, 0, 1}
-- TODO, autogenerate
local econStructureDefs = {
[UnitDefNames["staticmex"].id] = {cost = 75, mex = true},
[UnitDefNames["energywind"].id] = {cost = 35, income = 1.25, isWind = true},
[UnitDefNames["energysolar"].id] = {cost = 70, income = 2},
[UnitDefNames["energygeo"].id] = {cost = 500, income = 25},
[UnitDefNames["energyheavygeo"].id] = {cost = 1000, income = 75},
[UnitDefNames["energyfusion"].id] = {cost = 1000, income = 35},
[UnitDefNames["energysingu"].id] = {cost = 4000, income = 225},
}
local dynamicTooltipDefs = {
[UnitDefNames["terraunit"].id] = true,
[UnitDefNames["energypylon"].id] = true,
[UnitDefNames["zenith"].id] = true,
}
for unitDefID,_ in pairs(econStructureDefs) do
dynamicTooltipDefs[unitDefID] = true
end
local filterUnitDefIDs = {
[UnitDefNames["terraunit"].id] = true
}
local tidalHeight
local tidalStrength
local windMin
local windMax
local windGroundMin
local windGroundSlope
local windMinBound
local GAIA_TEAM = Spring.GetGaiaTeamID()
local UPDATE_FREQUENCY = 0.2
local isCommander = {}
for i = 1, #UnitDefs do
local ud = UnitDefs[i]
if ud.customParams.level or ud.customParams.dynamic_comm then
isCommander[i] = true
end
end
local manualFireTimeDefs = {}
for unitDefID = 1, #UnitDefs do
local ud = UnitDefs[unitDefID]
local unitWeapon = (ud and ud.weapons and ud.weapons[3])
--Note: weapon no.3 is by ZK convention is usually used for user controlled weapon
if (unitWeapon ~= nil) and WeaponDefs[unitWeapon.weaponDef].manualFire then
manualFireTimeDefs[unitDefID] = WeaponDefs[unitWeapon.weaponDef].reload
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Variables
local drawHotkeyBytes = {}
local drawHotkeyBytesCount = 0
local oldMouseX, oldMouseY = 0, 0
local stillCursorTime = 0
local global_totalBuildPower = 0
local sameObjectID
local sameObjectIDTime = 0
local selectedUnitsList = {}
local commanderManualFireReload = {}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Settings
options_path = 'Settings/HUD Panels/Tooltip'
local selPath = 'Settings/HUD Panels/Selected Units Panel'
options_order = {
--tooltip
'tooltip_delay', 'independant_world_tooltip_delay',
'show_for_units', 'show_for_wreckage', 'show_for_unreclaimable', 'showdrawtooltip','showterratooltip',
'showDrawTools', 'tooltip_opacity',
--selected units
'selection_opacity', 'allowclickthrough', 'groupbehaviour', 'showgroupinfo','uniticon_size', 'manualWeaponReloadBar',
'fancySkinning', 'leftPadding',
}
local showManualFire = true
options = {
tooltip_delay = {
name = 'Tooltip display delay (0 - 4s)',
desc = 'Determines how long you can leave the mouse idle until the tooltip is displayed.',
type = 'number',
min=0,max=4,step=0.05,
value = 0,
},
independant_world_tooltip_delay = { -- Done
name = 'Unit and Feature tooltip delay (0 - 4s)',
--desc = 'Determines how long you can leave the mouse over a unit or feature until the tooltip is displayed.',
type = 'number',
min=0,max=4,step=0.05,
value = 0.2,
},
show_for_units = {
name = "Show Tooltip for Units",
type = 'bool',
value = true,
noHotkey = true,
desc = 'Show the tooltip for units.',
},
show_for_wreckage = {
name = "Show Tooltip for Wreckage",
type = 'bool',
value = true,
noHotkey = true,
desc = 'Show the tooltip for wreckage and map features.',
},
show_for_unreclaimable = {
name = "Show Tooltip for Unreclaimables",
type = 'bool',
advanced = true,
value = false,
noHotkey = true,
desc = 'Show the tooltip for unreclaimable features.',
},
showdrawtooltip = {
name = "Show Map-drawing Tooltip",
type = 'bool',
value = true,
noHotkey = true,
desc = 'Show map-drawing tooltip when holding down the tilde (~).',
},
showterratooltip = {
name = "Show Terraform Tooltip",
type = 'bool',
value = true,
noHotkey = true,
desc = 'Show terraform tooltip when performing terraform commands.',
},
showDrawTools = {
name = "Show Drawing Tools When Drawing",
type = 'bool',
value = true,
noHotkey = true,
desc = 'Show pencil or eraser when drawing or erasing.'
},
tooltip_opacity = {
name = "Opacity",
type = "number",
value = 0.8, min = 0, max = 1, step = 0.01,
update_on_the_fly = true,
OnChange = function(self)
if not tooltipWindow then
return
end
tooltipWindow.SetOpacity(self.value)
end,
},
selection_opacity = {
name = "Opacity",
type = "number",
value = 0.8, min = 0, max = 1, step = 0.01,
update_on_the_fly = true,
OnChange = function(self)
if selectionWindow then
selectionWindow.SetOpacity(self.value)
end
end,
path = selPath,
},
allowclickthrough = {
name='Allow clicking through', type='bool', value=true,
path = selPath,
OnChange = function(self)
if selectionWindow then
selectionWindow.SetAllowClickThrough(self.value)
end
end,
},
groupbehaviour = {name='Unit Grouping Behaviour', type='radioButton',
value='overflow',
items = {
{key = 'overflow', name = 'On window overflow'},
{key = 'multitype', name = 'With multiple unit types'},
{key = 'always', name = 'Always'},
},
path = selPath,
},
showgroupinfo = {name='Show Group Info', type='bool', value=true,
path = selPath,
OnChange = function(self)
if selectionWindow then
selectionWindow.SetGroupInfoVisible(self.value)
end
end,
},
--unitCommand = {
-- name="Show Unit's Command",
-- type='bool',
-- value= false,
-- noHotkey = true,
-- desc = "Display current command on unit's icon (only for ungrouped unit selection)",
-- path = selPath,
--},
uniticon_size = {
name = 'Icon size on selection list',
--desc = 'Determines how small the icon in selection list need to be.',
type = 'number',
min=30,max=100,step=1,
value = 57,
path = selPath,
OnChange = function(self)
if selectionWindow then
selectionWindow.SetSelectionIconSize(self.value)
end
end,
},
manualWeaponReloadBar = {
name="Show Unit's Special Weapon Status",
type='bool',
value= true,
noHotkey = true,
desc = "Show reload progress for weapon that use manual trigger (only for ungrouped unit selection)",
path = selPath,
OnChange = function(self)
showManualFire = self.value
end,
},
fancySkinning = {
name = 'Fancy Skinning',
type = 'radioButton',
value = 'panel',
path = selPath,
items = {
{key = 'panel', name = 'None'},
{key = 'panel_1120', name = 'Bottom Left Flush',},
{key = 'panel_0120', name = 'Bot Mid Left Flush',},
{key = 'panel_2120', name = 'Bot Mid Both Flush',},
},
OnChange = function (self)
if selectionWindow then
selectionWindow.SetSkin(self.value)
end
end,
hidden = true,
noHotkey = true,
},
leftPadding = {
name = "Left Padding",
type = "number",
value = 0, min = 0, max = 500, step = 1,
OnChange = function(self)
if selectionWindow then
selectionWindow.SetLeftPadding(self.value)
end
end,
path = selPath,
},
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Utilities
function Round(num, idp)
if (not idp) then
return math.floor(num+.5)
else
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
end
local function Format(amount, displaySign)
local formatted
if type(amount) == "number" then
if (amount ==0) then formatted = "0" else
if (amount < 20 and (amount * 10)%10 ~=0) then
if displaySign then formatted = strFormat("%+.1f", amount)
else formatted = strFormat("%.1f", amount) end
else
if displaySign then
formatted = strFormat("%+d", amount)
else
formatted = strFormat("%d", amount)
end
end
end
else
formatted = amount .. ""
end
return formatted
end
local function FormatPlusMinus(num)
if num > 0.04 then
return green .. Format(num, true)
elseif num < -0.04 then
return red .. Format(num, true)
end
return Format(num)
end
local function SecondsToMinutesSeconds(seconds)
if seconds%60 < 10 then
return math.floor(seconds/60) ..":0" .. math.floor(seconds%60)
else
return math.floor(seconds/60) ..":" .. math.floor(seconds%60)
end
end
local function UnitDefTableSort(a,b)
return a and UnitDefs[a] and b and UnitDefs[b] and UnitDefs[a].name < UnitDefs[b].name
end
local function IsGroupingRequired(selectedUnits, selectionSortOrder, selectionSpace)
if options.groupbehaviour.value == 'overflow' then
return #selectedUnits > selectionSpace
elseif options.groupbehaviour.value == 'multitype' then
return not (#selectedUnits <= selectionSpace and #selectionSortOrder <= 1)
else
return true
end
end
local function GetHealthColor(fraction, returnString)
local midpt = (fraction > 0.5)
local r, g
if midpt then
r = (1 - fraction)*2
g = 1
else
r = 1
g = fraction*2
end
if returnString then
return string.char(255, math.floor(255*r), math.floor(255*g), 0)
end
return {r, g, 0, 1}
end
local function SetPanelSkin(targetPanel, className)
local currentSkin = Chili.theme.skin.general.skinName
local skin = Chili.SkinHandler.GetSkin(currentSkin)
local newClass = skin.panel
if skin[className] then
newClass = skin[className]
end
targetPanel.tiles = newClass.tiles
targetPanel.TileImageFG = newClass.TileImageFG
--targetPanel.backgroundColor = newClass.backgroundColor
targetPanel.TileImageBK = newClass.TileImageBK
if newClass.padding then
targetPanel.padding = newClass.padding
targetPanel:UpdateClientArea()
end
targetPanel:Invalidate()
end
local iconTypeCache = {}
local function GetUnitIcon(unitDefID)
if unitDefID and iconTypeCache[unitDefID] then
return iconTypeCache[unitDefID]
end
local ud = UnitDefs[unitDefID]
if not ud then
return
end
iconTypeCache[unitDefID] = icontypes[(ud and ud.iconType or "default")].bitmap or 'icons/' .. ud.iconType .. iconFormat
return iconTypeCache[unitDefID]
end
local function GetCurrentBuildSpeed(unitID, buildSpeed)
return (Spring.GetUnitCurrentBuildPower(unitID) or 0)*(spGetUnitRulesParam(unitID, "totalEconomyChange") or 1)*buildSpeed
end
local unitBorderCache = {}
local function GetUnitBorder(unitDefID)
if unitDefID and unitBorderCache[unitDefID] then
return unitBorderCache[unitDefID]
end
local ud = UnitDefs[unitDefID]
if not ud then
return
end
unitBorderCache[unitDefID] = WG.GetBuildIconFrame and WG.GetBuildIconFrame(ud)
return unitBorderCache[unitDefID]
end
local unitSelectionTooltipCache = {}
local function GetUnitSelectionTooltip(ud, unitDefID, unitID)
if ud.level then
return GetHumanName(ud, unitID) .. " - " .. GetDescription(ud, unitID) .. selectionTooltip
end
if not unitSelectionTooltipCache[unitDefID] then
unitSelectionTooltipCache[unitDefID] = GetHumanName(ud, unitID) .. " - " .. GetDescription(ud, unitID) .. selectionTooltip
end
return unitSelectionTooltipCache[unitDefID]
end
local function GetWeaponReloadStatus(unitID, weapNum, reloadTime)
local _, _, weaponReloadFrame, _, _ = spGetUnitWeaponState(unitID, weapNum) --select weapon no.X
if weaponReloadFrame then
local currentFrame, _ = Spring.GetGameFrame()
local remainingTime = (weaponReloadFrame - currentFrame)/30
local reloadFraction = 1 - remainingTime/reloadTime
return reloadFraction, remainingTime
end
return nil --Note: this mean unit doesn't have weapon number 'weapNum'
end
local function GetUnitResources(unitID)
local mm, mu, em, eu = Spring.GetUnitResources(unitID)
mm = (mm or 0) + (spGetUnitRulesParam(unitID, "current_metalIncome") or 0)
em = (em or 0) + (spGetUnitRulesParam(unitID, "current_energyIncome") or 0)
eu = (eu or 0) + (spGetUnitRulesParam(unitID, "overdrive_energyDrain") or 0)
if mm ~= 0 or mu ~= 0 or em ~= 0 or eu ~= 0 then
return mm, (mu or 0), em, eu
else
return
end
end
local function GetUnitRegenString(unitID, ud)
if unitID and (not select(3, spGetUnitIsStunned(unitID))) then
local regen_timer = spGetUnitRulesParam(unitID, "idleRegenTimer")
if regen_timer and ud then
if ((ud.idleTime <= 600) and (regen_timer > 0)) then
return " (" .. math.ceil(regen_timer / 30) .. "s)"
else
local regenMult = (1 - (spGetUnitRulesParam(unitID, "slowState") or 0)) * (1 - (spGetUnitRulesParam(unitID,"disarmed") or 0))
if regenMult == 0 then
return
end
local regen = 0
if (regen_timer <= 0) then
regen = regen + (spGetUnitRulesParam(unitID, "comm_autorepair_rate") or ud.customParams.idle_regen)
end
if ud.customParams.amph_regen then
local x,y,z = Spring.GetUnitPosition(unitID)
local h = Spring.GetGroundHeight(x,z) or y
if (h < 0) then
regen = regen + math.min(ud.customParams.amph_regen, ud.customParams.amph_regen*(-h / ud.customParams.amph_submerged_at))
end
end
if ud.customParams.armored_regen and Spring.GetUnitArmored(unitID) then
regen = regen + ud.customParams.armored_regen
end
if (regen > 0) then
return " (+" .. math.ceil(regenMult*regen) .. ")"
end
end
end
end
end
local function GetUnitShieldRegenString(unitID, ud)
if ud.customParams.shield_recharge_delay or true then
local shieldRegen = spGetUnitRulesParam(unitID, "shieldRegenTimer")
if shieldRegen and shieldRegen > 0 then
return " (" .. math.ceil(shieldRegen / 30) .. "s)"
end
end
local mult = spGetUnitRulesParam(unitID,"totalReloadSpeedChange") or 1 * (1 - (spGetUnitRulesParam(unitID, "shieldChargeDisabled") or 0))
if mult == 0 then
return ""
end
-- FIXME: take energy stall into account
local wd = WeaponDefs[ud.shieldWeaponDef]
return " (+" .. math.ceil(mult * (wd.customParams.shield_rate or wd.shieldPowerRegen)) .. ")"
end
local function IsUnitInLos(unitID)
local spectating, fullView = Spring.GetSpectatingState()
if fullView then
return true
end
if not unitID then
return false
end
local state = Spring.GetUnitLosState(unitID)
return state and state.los
end
local function GetManualFireReload(unitID, unitDefID)
if not (unitDefID and showManualFire) then
return false
end
if unitID and commanderManualFireReload[unitID] then
local reload = commanderManualFireReload[unitID]
if reload[1] == 0 then
return false
end
return reload[1], reload[2]
end
unitDefID = unitDefID or Spring.GetUnitDefID(unitID)
if not unitDefID then
return false
end
if manualFireTimeDefs[unitDefID] then
return manualFireTimeDefs[unitDefID], 3
end
if not (unitID and isCommander[unitDefID]) then
return false
end
local manualFire = spGetUnitRulesParam(unitID, "comm_weapon_manual_2")
if manualFire ~= 1 then
commanderManualFireReload[unitID] = {0}
return false
end
local weaponNum = spGetUnitRulesParam(unitID, "comm_weapon_num_2")
if not weaponNum then
commanderManualFireReload[unitID] = {0}
return false
end
local ud = UnitDefs[unitDefID]
local unitWeapon = ud and ud.weapons and ud.weapons[weaponNum]
if (unitWeapon ~= nil) and WeaponDefs[unitWeapon.weaponDef].manualFire then
local reload = WeaponDefs[unitWeapon.weaponDef].reload
commanderManualFireReload[unitID] = {reload, weaponNum}
return reload, weaponNum
end
commanderManualFireReload[unitID] = {0}
return false
end
local function GetExtraBuildTooltipAndHealthOverride(unitDefID, mousePlaceX, mousePlaceY)
local econDef = econStructureDefs[unitDefID]
if not econDef then
return
end
if econDef.mex then
if mousePlaceX and WG.mouseoverMexIncome then
local extraText = ", ".. WG.Translate("interface", "income") .. " +" .. string.format("%.2f", WG.mouseoverMexIncome)
if WG.mouseoverMexIncome > 0 then
return extraText .. "\n" .. WG.Translate("interface", "base_payback") .. ": " .. SecondsToMinutesSeconds(econDef.cost/WG.mouseoverMexIncome)
else
return extraText .. "\n" .. WG.Translate("interface", "base_payback") .. ": " .. WG.Translate("interface", "never")
end
end
return
end
local income = econDef.income
local cost = econDef.cost
local extraText = ""
local healthOverride = false
if econDef.isWind and mousePlaceX and mousePlaceY then
local _, pos = spTraceScreenRay(mousePlaceX, mousePlaceY, true)
if pos and pos[1] and pos[3] then
local x,z = math.floor(pos[1]/16)*16, math.floor(pos[3]/16)*16
local y = Spring.GetGroundHeight(x,z)
if y then
if y <= tidalHeight then
extraText = ", " .. WG.Translate("interface", "tidal_income") .. " +" .. string.format("%.1f", tidalStrength)
income = tidalStrength
healthOverride = 400
else
local minWindIncome = windMin + (windMax - windMin)*math.max(0, math.min(windMinBound, windGroundSlope*(y - windGroundMin)))
extraText = ", " .. WG.Translate("interface", "wind_range") .. " " .. string.format("%.1f", minWindIncome ) .. " - " .. string.format("%.1f", windMax)
income = (minWindIncome+windMax)/2
end
end
end
end
local teamID = Spring.GetLocalTeamID()
local metalOD = Spring.GetTeamRulesParam(teamID, "OD_team_metalOverdrive") or 0
local energyOD = Spring.GetTeamRulesParam(teamID, "OD_team_energyOverdrive") or 0
if metalOD and metalOD > 0 and energyOD and energyOD > 0 then
-- Best case payback assumes that extra energy will make
-- metal at the current energy:metal ratio. Note that if
-- grids are linked better then better payback may be
-- achieved.
--local bestCasePayback = cost/(income*metalOD/energyOD)
-- Uniform case payback assumes that all mexes are being
-- overdriven equally and figures out their multiplier
-- from the base mex income. It then figures out how many
-- mexes there are and adds a portion of the new enginer to
-- them.
--local totalMexIncome = WG.mexIncome
--if not totalMexIncome then
-- local singleMexMult = math.sqrt(energyOD)/4
-- totalMexIncome = metalOD/singleMexMult
--end
--local overdriveMult = metalOD/totalMexIncome
--local energyPerMex = 16*overdriveMult^2
--local mexCount = energyOD/energyPerMex
--local incomePerMex = income/mexCount
--local overdrivePerMex = metalOD/mexCount
--local extraMetalPerMex = totalMexIncome/mexCount*math.sqrt(energyPerMex+incomePerMex)/4 - overdrivePerMex
--local extraMetal = extraMetalPerMex*mexCount
--local unitformCasePayback = cost/extraMetal
-- Worst case payback assumes that all your OD metal is from
-- a single mex and you are going to link your new energy to it.
-- It seems to be equal to Uniform case payback and quite accurate.
local singleMexMult = math.sqrt(energyOD)/4
local mexIncome = metalOD/singleMexMult
local worstCasePayback = cost/(mexIncome*math.sqrt(energyOD+income)/4 - metalOD)
--extraText = extraText
--.. "\n overdriveMult: " .. overdriveMult
--.. "\n energyPerMex: " .. energyPerMex
--.. "\n mexCount: " .. mexCount
--.. "\n incomePerMex: " .. incomePerMex
--.. "\n overdrivePerMex: " .. overdrivePerMex
--.. "\n extraMetalPerMex: " .. extraMetalPerMex
--.. "\n extraMetal: " .. extraMetalza
--.. "\n unitformCasePayback: " .. unitformCasePayback
--.. "\n worstCasePayback: " .. worstCasePayback
return extraText .. "\n" .. WG.Translate("interface", "od_payback") .. ": " .. SecondsToMinutesSeconds(worstCasePayback), healthOverride
end
return extraText .. "\n" .. WG.Translate("interface", "od_payback") .. ": " .. WG.Translate("interface", "unknown"), healthOverride
end
local function GetPlayerCaption(teamID)
local _, player,_,isAI = Spring.GetTeamInfo(teamID, false)
local playerName
if isAI then
local _, aiName, _, shortName = Spring.GetAIInfo(teamID)
playerName = aiName -- .. ' (' .. shortName .. ')'
else
playerName = (player and Spring.GetPlayerInfo(player, false)) or (teamID ~= GAIA_TEAM and "noname")
if not playerName then
return false
end
end
local teamColor = Chili.color2incolor(Spring.GetTeamColor(teamID))
return WG.Translate("interface", "player") .. ': ' .. teamColor .. playerName
end
local function GetIsHoldingDrawKey()
if drawHotkeyBytesCount == 0 then
WG.drawtoolKeyPressed = false
return false
end
for i = 1, drawHotkeyBytesCount do
local key = drawHotkeyBytes[i]
if Spring.GetKeyState(key) then
WG.drawtoolKeyPressed = true
return true
end
end
WG.drawtoolKeyPressed = false
return false
end
local function UpdateMouseCursor(holdingDrawKey)
if not (holdingDrawKey and options.showDrawTools.value) then
return
end
local x, y, drawing, addingPoint, erasing = Spring.GetMouseState()
if addingPoint then
Spring.SetMouseCursor(CURSOR_POINT_NAME)
elseif erasing then
Spring.SetMouseCursor(CURSOR_ERASE_NAME)
else
Spring.SetMouseCursor(CURSOR_DRAW_NAME)
end
end
local function SelectionsIconClick(button, unitID, unitList, unitDefID)
unitID = unitID or (unitList and unitList[1])
if not unitID then
return
end
local alt, ctrl, meta, shift = spGetModKeyState()
-- selectedUnitsList is global and has the same ordering as unitList
local newSelectedUnits
if (button == 3) then
if shift then
--// deselect a whole unitdef block
newSelectedUnits = {}
local j = 1
for i = 1, #selectedUnitsList do
if unitList[j] and selectedUnitsList[i] == unitList[j] then
j = j + 1
else
newSelectedUnits[#newSelectedUnits + 1] = selectedUnitsList[i]
end
end
else
--// deselect a single unit
for i = 1, #selectedUnitsList do
if selectedUnitsList[i] == unitID then
selectedUnitsList[i] = selectedUnitsList[#selectedUnitsList]
selectedUnitsList[#selectedUnitsList] = nil
end
end
newSelectedUnits = selectedUnitsList
end
spSelectUnitArray(newSelectedUnits)
widget:SelectionChanged(newSelectedUnits)
elseif button == 1 then
if shift then
spSelectUnitArray(unitList) -- select all
else
spSelectUnitArray({unitID}) -- only 1
end
else --button2 (middle)
local x,y,z = Spring.GetUnitPosition(unitID)
SetCameraTarget(x, y, z, 1)
end
end
local cacheFeatureTooltip = {}
local cacheFeatureUnitDefID = {}
local function GetFeatureDisplayAttributes(featureDefID)
if cacheFeatureTooltip[featureDefID] or cacheFeatureUnitDefID[featureDefID] then
return cacheFeatureTooltip[featureDefID], cacheFeatureUnitDefID[featureDefID]
end
local fd = FeatureDefs[featureDefID]
local featureName = fd and fd.name
local unitName
if fd and fd.customParams and fd.customParams.unit then
unitName = fd.customParams.unit
else
unitName = featureName:gsub('(.*)_.*', '%1') --filter out _dead or _dead2 or _anything
end
local unitDefID
if unitName and UnitDefNames[unitName] then
unitDefID = UnitDefNames[unitName].id
end
if featureName:find("dead2") or featureName:find("heap") then
addedName = " (" .. WG.Translate("interface", "debris") .. ")"
elseif featureName:find("dead") then
addedName = " (" .. WG.Translate("interface", "wreckage") .. ")"
end
if unitDefID then
cacheFeatureUnitDefID[featureDefID] = unitDefID
return nil, cacheFeatureUnitDefID[featureDefID]
end
cacheFeatureTooltip[featureDefID] = fd.tooltip
return cacheFeatureTooltip[featureDefID]
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Unit tooltip window components
local function GetBarWithImage(parentControl, name, initY, imageFile, color, colorFunc)
local image = Chili.Image:New{
name = name .. "_image",
x = 0,
y = initY,
width = ICON_SIZE,
height = ICON_SIZE,
file = imageFile,
parent = parentControl,
}
local bar = Chili.Progressbar:New {
name = name .. "_bar",
x = ICON_SIZE + 1,
y = initY,
right = 0,
height = BAR_SIZE,
max = 1,
color = color,
itemMargin = {0,0,0,0},
itemPadding = {0,0,0,0},
padding = {0,0,0,0},
caption = '',
font = {size = BAR_FONT},
parent = parentControl
}
local function UpdateBar(visible, yPos, currentValue, maxValue, extraCaption, newCaption)
image:SetVisibility(visible)
bar:SetVisibility(visible)
if not visible then
return
end
if yPos then
image:SetPos(nil, yPos, nil, nil, nil, true)
bar:SetPos(nil, yPos, nil, nil, nil, true)
end
if not newCaption then
newCaption = Format(currentValue) .. ' / ' .. Format(maxValue)
if extraCaption then
newCaption = newCaption .. extraCaption
end
end
bar:SetCaption(newCaption)
if colorFunc then
color = colorFunc(currentValue/maxValue)
bar.color = color
end
bar:SetValue(currentValue/maxValue)
end
return UpdateBar
end
local function GetImageWithText(parentControl, name, initY, imageFile, caption, fontSize, iconSize, textOffset)
fontSize = fontSize or IMAGE_FONT
iconSize = iconSize or ICON_SIZE
local image = Chili.Image:New{
name = name .. "_image",
x = 0,
y = initY,
width = iconSize,
height = iconSize,
file = imageFile,
parent = parentControl,
}
local label = Chili.Label:New{
name = name .. "_label",
x = iconSize + 2,
y = initY + (textOffset or 0),
right = 0,
height = LEFT_LABEL_HEIGHT,
caption = IMAGE_FONT,
fontSize = fontSize,
parent = parentControl,
}
image:SetVisibility(false)
label:SetVisibility(false)
local function Update(visible, newCaption, newImage, yPos)
image:SetVisibility(visible)
label:SetVisibility(visible)
if not visible then
return
end
if yPos then
image:SetPos(nil, yPos, nil, nil, nil, true)
label:SetPos(nil, yPos + textOffset, nil, nil, nil, true)
end
label:SetCaption(newCaption)
if newImage ~= imageFile then
if imageFile == nil then
label:SetPos(iconSize + 2, nil, nil, nil, nil, true)
elseif newImage == nil then
label:SetPos(2, nil, nil, nil, nil, true)
end
imageFile = newImage
image.file = imageFile
image:Invalidate()
end
end
return Update
end
local function GetMorphInfo(parentControl, yPos)
local holder = Chili.Control:New{
x = 0,
y = yPos,
right = 0,
height = ICON_SIZE,
padding = {0,0,0,0},
parent = parentControl,
}
local morphLabel = Chili.Label:New{
x = 4,
y = 0,
height = ICON_SIZE,
width = 50,
valign = 'center',
caption = cyan .. 'Morph:',
fontSize = BAR_FONT,
parent = holder,
}
local timeImage = Chili.Image:New{
x = 54,
y = 0,
width = ICON_SIZE,
height = ICON_SIZE,
file = IMAGE.TIME,
parent = holder,
}
local timeLabel = Chili.Label:New{
x = 54 + ICON_SIZE + 4,
y = 4,
right = 0,
height = BAR_SIZE,
caption = BAR_FONT,
fontSize = fontSize,
parent = holder,
}
local costImage = Chili.Image:New{
x = 114,
y = 0,
width = ICON_SIZE,
height = ICON_SIZE,
file = IMAGE.COST,
parent = holder,
}
local costLabel = Chili.Label:New{
x = 113 + ICON_SIZE + 4,
y = 4,
right = 0,
height = BAR_SIZE,
caption = BAR_FONT,
fontSize = fontSize,
parent = holder,
}
local function Update(visible, newTime, newCost, yPos)
holder:SetVisibility(visible)
if not visible then
return
end
if yPos then
holder:SetPos(nil, yPos, nil, nil, nil, true)
end
timeLabel:SetCaption(cyan .. newTime)
costLabel:SetCaption(cyan .. newCost)
end
return Update
end
local function UpdateManualFireReload(reloadBar, parentImage, unitID, weaponNum, reloadTime)
if not reloadBar then
reloadBar = Chili.Progressbar:New {
x = "82%",
y = 5,
right = 5,
bottom = 5,
minWidth = 4,
max = 1,
caption = false,
noFont = true,
color = reloadBarColor,
skinName = 'default',
orientation = "vertical",
reverse = true,
parent = parentImage,
}
end
local reloadFraction, remainingTime = GetWeaponReloadStatus(unitID, weaponNum, reloadTime)
if reloadFraction and reloadFraction < 1 then
reloadBar:SetValue(reloadFraction)
reloadBar:SetVisibility(true)
else
reloadBar:SetVisibility(false)
end
return reloadBar
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Group buttons window
local function GetUnitGroupIconButton(parentControl)
local unitDefID
local unitID
local unitList
local unitCount
local size = options.uniticon_size.value
local holder = Chili.Control:New{
x = 0,
y = 0,
width = size,
height = size,
padding = {1,1,1,1},
parent = parentControl,
}
local reloadBar
local healthBar = Chili.Progressbar:New {
x = 0,
y = "80%",
right = 0,
height = 0,
max = 1,
caption = false,
noFont = true,
color = fullHealthBarColor,
parent = holder
}
local unitImage = Chili.Image:New{
keepAspect = false,
x = 0,
y = 0,
right = 0,
bottom = "20%",
padding = {0,0,0,0},
parent = holder,
OnClick = {
function(_,_,_,button)
SelectionsIconClick(button, unitID, unitList, unitDefID)
end
}
}
local groupLabel = Chili.Label:New{
x = 0,
right = 2,
bottom = 0,
height = 25,
align = "right",
valign = "top",
fontsize = 20,
fontshadow = true,
fontOutline = true,
parent = unitImage
}
local function UpdateUnitInfo()
if unitID then
local health, maxhealth = spGetUnitHealth(unitID)
if health then
healthBar.color = GetHealthColor(health/maxhealth)
healthBar:SetValue(health/maxhealth)
end
local reloadTime, weaponNum = GetManualFireReload(unitID, unitDefID)
if reloadTime then
reloadBar = UpdateManualFireReload(reloadBar, unitImage, unitID, weaponNum, reloadTime)
elseif reloadBar then
reloadBar:SetVisibility(false)
end
return
end
if reloadBar then
reloadBar:SetVisibility(false)
end
local totalHealth, totalMax = 0, 0
for i = 1, #unitList do
local health, maxhealth = spGetUnitHealth(unitList[i])
if health and maxhealth then
totalHealth = totalHealth + health
totalMax = totalMax + maxhealth
end
end
if totalMax > 0 then
healthBar.color = GetHealthColor(totalHealth/totalMax)
healthBar:SetValue(totalHealth/totalMax)
end
end
local function UpdateUnitDefID(newUnitDefID)
if newUnitDefID == unitDefID then
return
end
unitDefID = newUnitDefID
local ud = UnitDefs[unitDefID]
if not ud then
return
end
unitImage.tooltip = GetUnitSelectionTooltip(ud, unitDefID, unitID)
unitImage.file = "#" .. unitDefID
unitImage.file2 = GetUnitBorder(unitDefID)
unitImage:Invalidate()
end
local function UpdateUnits(newUnitID, newUnitList)
unitID = newUnitID
unitList = newUnitList
local newCount = (not unitID) and newUnitList and #newUnitList
if newCount and newCount < 2 then
newCount = false
end
if newCount == unitCount then
return
end
unitCount = newCount
groupLabel._relativeBounds.left = 0
groupLabel._relativeBounds.right = 2
groupLabel:SetCaption(unitCount or "")
end
local externalStuff = {
visible = true
}
function externalStuff.SetPosition(x,y,size)
holder:SetPos(x*size,y*size - SEL_BUTTON_SHORTENING*y,size,size)
end
function externalStuff.SetHidden()
holder:SetVisibility(false)
externalStuff.visible = false
end
function externalStuff.UpdateUnitButton()
UpdateUnitInfo()
end
function externalStuff.SetGroupIconUnits(newUnitID, newUnitList, newUnitDefID)
holder:SetVisibility(true)
externalStuff.visible = true
UpdateUnitDefID(newUnitDefID)
UpdateUnits(newUnitID, newUnitList)
UpdateUnitInfo()
end
return externalStuff
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Group info handler
local function GetSelectionStatsDisplay(parentControl)
local holder = Chili.Control:New{
name = "holder",
y = 0,
right = 0,
bottom = 0,
width = GROUP_STATS_WIDTH,
padding = {0,0,0,0},
parent = parentControl,
}
local selectedUnits
local selectedUnitDefID = {}
local visible = true
local statLabel = Chili.Label:New{
name = "statLabel",
x = 0,
y = 3,
right = 0,
valign = 'top',
fontSize = 12,
fontShadow = true,
parent = holder,
}
local total_count = 0
local total_finishedcost = 0
local total_totalbp = 0
local total_maxhp = 0
local total_totalburst = 0
local unreliableBurst = false
local burstClass = 0
local function UpdateDynamicGroupInfo()
local total_cost = 0
local total_hp = 0
local total_metalincome = 0
local total_metaldrain = 0
local total_energyincome = 0
local total_energydrain = 0
local total_usedbp = 0
local unitID, unitDefID, ud --micro optimization, avoiding repeated localization.
local name, hp, paradam, cap, build, mm, mu, em, eu
local stunned_or_inbuild
for i = 1, total_count do
unitID = selectedUnits[i]
unitDefID = selectedUnitDefID[i]
ud = unitDefID and UnitDefs[unitDefID]
if ud then
hp, _, paradam, cap, build = spGetUnitHealth(unitID)
mm, mu, em, eu = GetUnitResources(unitID)
if hp then
total_cost = total_cost + GetUnitCost(unitID, unitDefID)*build
total_hp = total_hp + hp
end
stunned_or_inbuild = spGetUnitIsStunned(unitID)
if not stunned_or_inbuild then
if mm then
total_metalincome = total_metalincome + mm
total_metaldrain = total_metaldrain + mu
total_energyincome = total_energyincome + em
total_energydrain = total_energydrain + eu
end
if ud.buildSpeed ~= 0 then
total_usedbp = total_usedbp + (GetCurrentBuildSpeed(unitID, GetUnitBuildSpeed(unitID, unitDefID)) or 0)
end
end
end
end
local unitInfoString = WG.Translate("interface", "selected_units") .. ": " .. Format(total_count) .. "\n" ..
WG.Translate("interface", "health") .. ": " .. Format(total_hp) .. " / " .. Format(total_maxhp) .. "\n" ..
WG.Translate("interface", "value") .. ": " .. Format(total_cost) .. " / " .. Format(total_finishedcost) .. "\n"
if total_metalincome ~= 0 or total_metaldrain ~= 0 or total_energyincome ~= 0 or total_energydrain ~= 0 then
unitInfoString = unitInfoString ..
WG.Translate("interface", "metal") .. ": " .. FormatPlusMinus(total_metalincome) .. white .. " / " .. FormatPlusMinus(-total_metaldrain) .. white .. "\n" ..
WG.Translate("interface", "energy") .. ": " .. FormatPlusMinus(total_energyincome) .. white .. " / " .. FormatPlusMinus(-total_energydrain) .. white .. "\n"
end
if total_totalbp ~= 0 then
unitInfoString = unitInfoString ..
WG.Translate("interface", "buildpower") .. ": " .. Format(total_usedbp) .. " / " .. Format(total_totalbp) .. "\n"
end
if burstClass and total_totalburst ~= 0 then
unitInfoString = unitInfoString ..
WG.Translate("interface", "burst_damage") .. ": " .. ((unreliableBurst and "~") or "") .. Format(total_totalburst) .. "\n"
end
statLabel:SetCaption(unitInfoString)
end
--updates values that don't change over time for group info
local function UpdateStaticGroupInfo()
total_count = #selectedUnits
total_finishedcost = 0
total_totalbp = 0
total_maxhp = 0
total_totalburst = 0
unreliableBurst = false
burstClass = 0
local unitID, unitDefID
for i = 1, total_count do
unitID = selectedUnits[i]
unitDefID = Spring.GetUnitDefID(unitID)
if unitDefID and not filterUnitDefIDs[unitDefID] then
selectedUnitDefID[i] = unitDefID
total_totalbp = total_totalbp + GetUnitBuildSpeed(unitID, unitDefID)
total_maxhp = total_maxhp + (select(2, Spring.GetUnitHealth(unitID)) or 0)
total_finishedcost = total_finishedcost + GetUnitCost(unitID, unitDefID)
local burstData = UNIT_BURST_DAMAGES[unitDefID]
if burstData and burstClass then
if burstClass == 0 then
burstClass = burstData.class
end
if burstClass == burstData.class then
total_totalburst = total_totalburst + burstData.damage
unreliableBurst = unreliableBurst or burstData.unreliable
else
burstClass = false
end
end
global_totalBuildPower = total_totalbp
end
end
total_totalburst = math.floor(total_totalburst / 10) * 10 -- round numbers are easier to parse and compare
UpdateDynamicGroupInfo()
end
local externalFunctions = {}
function externalFunctions.ChangeSelection(newSelection)
selectedUnits = newSelection
if visible and selectedUnits then
UpdateStaticGroupInfo()
end
end
function externalFunctions.UpdateStats()
if visible and selectedUnits then
UpdateDynamicGroupInfo()
end
end
function externalFunctions.SetVisibile(newVisible)
visible = newVisible
holder:SetVisibility(newVisible)
end
return externalFunctions
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Group window
local function GetMultiUnitInfoPanel(parentControl)
local holder = Chili.Control:New{
x = 0,
y = 0,
right = GROUP_STATS_WIDTH,
bottom = 0,
padding = {-1,1,0,0},
parent = parentControl,
}
local iconSize = options.uniticon_size.value
local displayColumns = 5
local displayRows = 3
local displayUnits
local displayButtons = {}
local function UpdateButtonPosition(index)
local col = (index - 1)%displayColumns
local row = (index - 1 - col)/displayColumns
displayButtons[index].SetPosition(col, row, iconSize)
end
local function GetButton(index)
if not displayButtons[index] then
displayButtons[index] = GetUnitGroupIconButton(holder)
UpdateButtonPosition(index)
end
return displayButtons[index]
end
local function HideButtonsFromIndex(index)
while displayButtons[index] and displayButtons[index].visible do
displayButtons[index].SetHidden()
index = index + 1
end
end
local function Resize(self)
local sizeX, sizeY = self.clientWidth, self.clientHeight
local newIconSize = options.uniticon_size.value
local newCols = math.floor(sizeX/iconSize)
local newRows = math.floor(sizeY/(iconSize - SEL_BUTTON_SHORTENING))
if newCols == displayColumns and newRows == displayRows and newIconSize == iconSize then
return
end
iconSize = newIconSize
displayColumns = newCols
displayRows = newRows
local displaySpace = displayRows*displayColumns
local index = 1
while displayButtons[index] and index <= displaySpace do
UpdateButtonPosition(index)
index = index + 1
end
HideButtonsFromIndex(displaySpace + 1)
end
holder.OnResize[#holder.OnResize + 1] = Resize
local function StaticButtonUpdate(selectionSortOrder, displayUnitsByDefID)
local displaySpace = displayRows*displayColumns
local groupRequired = IsGroupingRequired(displayUnits, selectionSortOrder, displaySpace)
local buttonIndex = 1
for i = 1, #selectionSortOrder do
if displaySpace < buttonIndex then
return false
end
local unitDefID = selectionSortOrder[i]
local unitList = displayUnitsByDefID[unitDefID]
if groupRequired then
local button = GetButton(buttonIndex)
button.SetGroupIconUnits(nil, unitList, unitDefID)
buttonIndex = buttonIndex + 1
else
for j = 1, #unitList do
if displaySpace < buttonIndex then
return false
end
local button = GetButton(buttonIndex)
button.SetGroupIconUnits(unitList[j], unitList, unitDefID)
buttonIndex = buttonIndex + 1
end
end
end
return buttonIndex
end
local function DynamicButtonUpdate()
for i = 1, #displayButtons do
local button = displayButtons[i]
if button.visible then
button.UpdateUnitButton()
end
end
end
local externalFunctions = {}
function externalFunctions.UpdateUnitDisplay()
if displayUnits then
DynamicButtonUpdate()
end
end
function externalFunctions.SetUnitDisplay(newDisplayUnits)
if not newDisplayUnits then
displayUnits = false
holder:SetVisibility(false)
return
end
holder:SetVisibility(true)
displayUnits = newDisplayUnits
local unitDefAdded = {}
local displayUnitsByDefID = {}
local selectionSortOrder = {}
for i = 1, #displayUnits do
local unitID = displayUnits[i]
local unitDefID = Spring.GetUnitDefID(unitID) or 0
local byDefID = displayUnitsByDefID[unitDefID] or {}
byDefID[#byDefID + 1] = unitID
displayUnitsByDefID[unitDefID] = byDefID
if not unitDefAdded[unitDefID] then
selectionSortOrder[#selectionSortOrder + 1] = unitDefID
unitDefAdded[unitDefID] = true
end
end
table.sort(selectionSortOrder, UnitDefTableSort)
local buttonIndex = StaticButtonUpdate(selectionSortOrder, displayUnitsByDefID)
if buttonIndex then
HideButtonsFromIndex(buttonIndex)
end
end
function externalFunctions.SetRightPadding(newRightPadding)
holder._relativeBounds.left = 0
holder._relativeBounds.right = newRightPadding
holder:UpdateClientArea()
end
function externalFunctions.SetIconSize(newIconSize)
iconSize = newIconSize
Resize(holder)
end
return externalFunctions
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Unit tooltip window
local function GetSingleUnitInfoPanel(parentControl, isTooltipVersion)
local selectedUnitID
local leftPanel = Chili.Control:New{
name = "leftPanel",
x = 0,
y = 0,
width = LEFT_WIDTH,
minWidth = LEFT_WIDTH,
autosize = true,
padding = {0,2,0,2},
parent = parentControl,
}
local rightPanel = Chili.Control:New{
name = "rightPanel",
x = LEFT_WIDTH,
y = 0,
width = RIGHT_WIDTH,
minWidth = RIGHT_WIDTH,
autosize = true,
padding = {2,2,0,2},
parent = parentControl,
}
local reloadBar
local unitImage = Chili.Image:New{
name = "unitImage",
x = 0,
y = 0,
right = 0,
height = PIC_HEIGHT,
keepAspect = false,
file = imageFile,
parent = leftPanel,
}
if not isTooltipVersion then
unitImage.OnClick[#unitImage.OnClick + 1] = function()
if selectedUnitID then
local x,y,z = Spring.GetUnitPosition(selectedUnitID)
SetCameraTarget(x, y, z, 1)
end
end
end
local unitNameUpdate = GetImageWithText(rightPanel, "unitNameUpdate", 1, nil, nil, NAME_FONT, nil, 3)
local unitDesc = Chili.TextBox:New{
name = "unitDesc",
x = 4,
y = 25,
right = 0,
height = BAR_SIZE,
fontSize = DESC_FONT,
parent = rightPanel,
}
local costInfoUpdate = GetImageWithText(leftPanel, "costInfoUpdate", PIC_HEIGHT + 4, IMAGE.COST, nil, nil, ICON_SIZE, 5)
local metalInfoUpdate = GetImageWithText(leftPanel, "metalInfoUpdate", PIC_HEIGHT + LEFT_SPACE + 4, IMAGE.METAL, nil, nil, ICON_SIZE, 5)
local energyInfoUpdate = GetImageWithText(leftPanel, "energyInfoUpdate", PIC_HEIGHT + 2*LEFT_SPACE + 4, IMAGE.ENERGY, nil, nil, ICON_SIZE, 5)
local maxHealthLabel = GetImageWithText(rightPanel, "maxHealthLabel", PIC_HEIGHT + 4, IMAGE.HEALTH, nil, NAME_FONT, ICON_SIZE, 3)
local healthBarUpdate = GetBarWithImage(rightPanel, "healthBarUpdate", PIC_HEIGHT + 4, IMAGE.HEALTH, {0, 1, 0, 1}, GetHealthColor)
local metalInfo
local energyInfo
local spaceClickLabel, shieldBarUpdate, buildBarUpdate, morphInfo, playerNameLabel, timeInfoUpdate
if isTooltipVersion then
playerNameLabel = Chili.Label:New{
name = "playerNameLabel",
x = 4,
y = PIC_HEIGHT + 31,
right = 0,
height = BAR_FONT,
fontSize = BAR_FONT,
parent = rightPanel,
}
spaceClickLabel = Chili.Label:New{
name = "spaceClickLabel",
x = 4,
y = PIC_HEIGHT + 55,
right = 0,
height = 18,
fontSize = DESC_FONT,
caption = green .. WG.Translate("interface", "space_click_show_stats"),
parent = rightPanel,
}
morphInfo = GetMorphInfo(rightPanel, PIC_HEIGHT + LEFT_SPACE + 3)
timeInfoUpdate = GetImageWithText(leftPanel, "timeInfoUpdate", PIC_HEIGHT + LEFT_SPACE + 4, IMAGE.TIME, nil, nil, ICON_SIZE, 5)
else
shieldBarUpdate = GetBarWithImage(rightPanel, "shieldBarUpdate", PIC_HEIGHT + 4, IMAGE.SHIELD, {0.3,0,0.9,1})
buildBarUpdate = GetBarWithImage(rightPanel, "buildBarUpdate", PIC_HEIGHT + 58, IMAGE.BUILD, {0.8,0.8,0.2,1})
end
local prevUnitID, prevUnitDefID, prevFeatureID, prevFeatureDefID, prevVisible, prevMorphTime, prevMorphCost, prevMousePlace
local externalFunctions = {}
local function UpdateReloadTime(unitID, unitDefID)
local reloadTime, weaponNum = GetManualFireReload(unitID, unitDefID)
if reloadTime then
reloadBar = UpdateManualFireReload(reloadBar, unitImage, unitID, weaponNum, reloadTime)
elseif reloadBar then
reloadBar:SetVisibility(false)
end
end
local function UpdateDynamicUnitAttributes(unitID, unitDefID, ud)
local mm, mu, em, eu = GetUnitResources(unitID)
local showMetalInfo = false
if mm then
metalInfoUpdate(true, FormatPlusMinus(mm - mu), IMAGE.METAL, PIC_HEIGHT + LEFT_SPACE + 4)
energyInfoUpdate(true, FormatPlusMinus(em - eu), IMAGE.ENERGY, PIC_HEIGHT + 2*LEFT_SPACE + 4)
showMetalInfo = true
else
metalInfoUpdate(false)
energyInfoUpdate(false)
end
local healthPos
if shieldBarUpdate then
if ud and (ud.shieldPower > 0 or ud.level) then
local shieldPower = spGetUnitRulesParam(unitID, "comm_shield_max") or ud.shieldPower
local _, shieldCurrentPower = Spring.GetUnitShieldState(unitID, -1)
if shieldCurrentPower and shieldPower then
shieldBarUpdate(true, nil, shieldCurrentPower, shieldPower, (shieldCurrentPower < shieldPower) and GetUnitShieldRegenString(unitID, ud))
end
healthPos = PIC_HEIGHT + 4 + BAR_SPACING
else
shieldBarUpdate(false)
healthPos = PIC_HEIGHT + 4
end
end
local health, maxHealth = spGetUnitHealth(unitID)
if health and maxHealth then
healthBarUpdate(true, healthPos, health, maxHealth, (health < maxHealth) and GetUnitRegenString(unitID, ud))
end
if buildBarUpdate then
if ud and ud.buildSpeed > 0 then
local metalMake, metalUse, energyMake,energyUse = Spring.GetUnitResources(unitID)
local buildSpeed = GetUnitBuildSpeed(unitID, unitDefID)
local currentBuild = GetCurrentBuildSpeed(unitID, buildSpeed)
buildBarUpdate(true, (healthPos or (PIC_HEIGHT + 4)) + BAR_SPACING, currentBuild or 0, buildSpeed)
else
buildBarUpdate(false)
end
end
if dynamicTooltipDefs[unitDefID] then
unitDesc:SetText(GetDescription(ud, unitID))
end
UpdateReloadTime(unitID, unitDefID)
return showMetalInfo
end
local function UpdateDynamicFeatureAttributes(featureID, unitDefID)
local metal, _, energy, _, _ = Spring.GetFeatureResources(featureID)
local leftOffset = 1
if unitDefID then
leftOffset = PIC_HEIGHT + LEFT_SPACE
end
metalInfoUpdate(true, Format(metal), IMAGE.METAL_RECLAIM, leftOffset + 4)
energyInfoUpdate(true, Format(energy), IMAGE.ENERGY_RECLAIM, leftOffset + LEFT_SPACE + 4)
end
local function UpdateDynamicEconInfo(unitDefID, mousePlaceX, mousePlaceY)
local ud = UnitDefs[unitDefID]
local extraTooltip, healthOverride
if not (unitID or featureID) then
extraTooltip, healthOverride = GetExtraBuildTooltipAndHealthOverride(unitDefID, mousePlaceX, mousePlaceY)
end
if extraTooltip then
unitDesc:SetText(GetDescription(ud, unitID) .. extraTooltip)
else
unitDesc:SetText(GetDescription(ud, unitID))
end
unitDesc:Invalidate()
if econStructureDefs[unitDefID].isWind then
maxHealthLabel(true, healthOverride or ud.health, IMAGE.HEALTH)
end
end
local function UpdateBuildTime(unitDefID)
if not timeInfoUpdate then
return
end
if (global_totalBuildPower or 0) < 1 then
timeInfoUpdate(true, cyan .. "??", IMAGE.TIME)
return
end
local buildCost = GetUnitCost(nil, unitDefID)
if not buildCost then
timeInfoUpdate(false)
return
end
timeInfoUpdate(true, cyan .. SecondsToMinutesSeconds(math.floor(buildCost/global_totalBuildPower)), IMAGE.TIME)
end
function externalFunctions.SetDisplay(unitID, unitDefID, featureID, featureDefID, blueprint, morphTime, morphCost, mousePlaceX, mousePlaceY, requiredOnly)
local teamID
local addedName
local ud
local metalInfoShown = false
local maxHealthShown = false
local morphShown = false
local visible = IsUnitInLos(unitID)
if prevUnitID == unitID and prevUnitDefID == unitDefID and prevFeatureID == featureID and prevFeatureDefID == featureDefID and
prevVisible == visible and prevMorphTime == morphTime and prevMorphCost == morphCost and prevMousePlace == ((mousePlaceX and true) or false) then
if not requiredOnly then
if unitID and unitDefID and visible then
UpdateDynamicUnitAttributes(unitID, unitDefID, UnitDefs[unitDefID])
end
if featureID then
UpdateDynamicFeatureAttributes(featureID, prevUnitDefID)
end
if unitDefID and not (unitID or featureID) then
if blueprint then
UpdateBuildTime(unitDefID)
end
if econStructureDefs[unitDefID] then
UpdateDynamicEconInfo(unitDefID, mousePlaceX, mousePlaceY)
end
end
end
return
end
if featureID then
teamID = Spring.GetFeatureTeam(featureID)
local featureTooltip, featureUnitDefID = GetFeatureDisplayAttributes(featureDefID)
healthBarUpdate(false)
if featureUnitDefID then
unitDefID = featureUnitDefID
if playerNameLabel then
playerNameLabel:SetPos(nil, PIC_HEIGHT + 10, nil, nil, nil, true)
spaceClickLabel:SetPos(nil, PIC_HEIGHT + 34, nil, nil, nil, true)
end
else
costInfoUpdate(false)
unitNameUpdate(true, featureTooltip, nil)
if playerNameLabel then
playerNameLabel:SetPos(nil, PIC_HEIGHT - 10, nil, nil, nil, true)
spaceClickLabel:SetPos(nil, PIC_HEIGHT + 14, nil, nil, nil, true)
end
end
UpdateDynamicFeatureAttributes(featureID, featureUnitDefID)
metalInfoShown = true
end
if unitDefID then
ud = UnitDefs[unitDefID]
unitImage.file = "#" .. unitDefID
unitImage.file2 = GetUnitBorder(unitDefID)
unitImage:Invalidate()
costInfoUpdate(true, cyan .. math.floor(GetUnitCost(unitID, unitDefID) or 0), IMAGE.COST, PIC_HEIGHT + 4)
local extraTooltip, healthOverride
if not (unitID or featureID) then
extraTooltip, healthOverride = GetExtraBuildTooltipAndHealthOverride(unitDefID, mousePlaceX, mousePlaceY)
end
if extraTooltip then
unitDesc:SetText(GetDescription(ud, unitID) .. extraTooltip)
else
unitDesc:SetText(GetDescription(ud, unitID))
end
unitDesc:Invalidate()
local unitName = GetHumanName(ud, unitID)
if addedName then
unitName = unitName .. addedName
end
unitNameUpdate(true, unitName, GetUnitIcon(unitDefID))
if unitID then
if playerNameLabel then
playerNameLabel:SetPos(nil, PIC_HEIGHT + 31, nil, nil, nil, true)
spaceClickLabel:SetPos(nil, PIC_HEIGHT + 55, nil, nil, nil, true)
end
end
if (not (unitID and visible)) and not featureDefID then
healthBarUpdate(false)
maxHealthLabel(true, healthOverride or ud.health, IMAGE.HEALTH)
maxHealthShown = true
if blueprint then
UpdateBuildTime(unitDefID)
end
if morphTime then
morphInfo(true, morphTime, morphCost)
morphShown = true
if spaceClickLabel then
spaceClickLabel:SetPos(nil, PIC_HEIGHT + LEFT_SPACE + 31, nil, nil, nil, true)
end
elseif spaceClickLabel and not unitID then
spaceClickLabel:SetPos(nil, PIC_HEIGHT + 30, nil, nil, nil, true)
end
end
end
if timeInfoUpdate and not blueprint then
timeInfoUpdate(false)
end
if unitID then
teamID = Spring.GetUnitTeam(unitID)
if UpdateDynamicUnitAttributes(unitID, unitDefID, ud) then
metalInfoShown = true
end
selectedUnitID = unitID
else
selectedUnitID = nil
if reloadBar then
reloadBar:SetVisibility(false)
end
end
if not metalInfoShown then
metalInfoUpdate(false)
energyInfoUpdate(false)
end
if playerNameLabel then
local playerName = teamID and GetPlayerCaption(teamID)
if playerName then
playerNameLabel:SetCaption(playerName)
end
playerNameLabel:SetVisibility((playerName and true) or false)
end
local visibleUnitDefID = (unitDefID and true) or false
unitImage:SetVisibility(visibleUnitDefID)
unitDesc:SetVisibility(visibleUnitDefID)
if spaceClickLabel then
spaceClickLabel:SetVisibility(visibleUnitDefID)
end
if maxHealthLabel and not maxHealthShown then
maxHealthLabel(false)
end
if morphInfo and not morphShown then
morphInfo(false)
end
prevUnitID, prevUnitDefID, prevFeatureID, prevFeatureDefID = unitID, unitDefID, featureID, featureDefID
prevVisible = visible
prevMorphTime, prevMorphCost, prevMousePlace = morphTime, morphCost, ((mousePlaceX and true) or false)
end
function externalFunctions.SetVisible(newVisible)
leftPanel:SetVisibility(newVisible)
rightPanel:SetVisibility(newVisible)
end
return externalFunctions
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Tooltip window handler
local function GetTooltipWindow()
local window = Chili.Window:New{
name = "tooltipWindow",
x = 300,
y = 250,
savespace = true,
resizable = false,
draggable = false,
autosize = true,
minWidth = RIGHT_WIDTH,
padding = {6,4,6,2},
color = {1, 1, 1, options.tooltip_opacity.value},
parent = screen0
}
window:Hide()
local textTooltip = Chili.TextBox:New{
name = "textTooltip",
x = 0,
y = 4,
width = RIGHT_WIDTH - 10,
height = 5,
valign = "ascender",
autoHeight = true,
font = {size = TOOLTIP_FONT},
parent = window,
}
textTooltip:SetVisibility(false)
local unitDisplay = GetSingleUnitInfoPanel(window, true)
local externalFunctions = {}
function externalFunctions.SetVisible(newVisible)
window:SetVisibility(newVisible)
end
function externalFunctions.SetOpacity(opacity)
window.color[4] = opacity
window:Invalidate()
end
function externalFunctions.SetPosition(x, y)
y = screenHeight - y
if x + window.width > screenWidth - 2 then
x = screenWidth - window.width - 2
end
if y + window.height > screenHeight - 2 then
y = screenHeight - window.height - 2
end
local map = WG.MinimapPosition
if map then
-- Only move tooltip up and/or left if it overlaps the minimap. This is because the
-- minimap does not have tooltips.
if x < map[1] + map[3] and y < map[2] + map[4] then
local inX = x + window.width - map[1] + 2
local inY = y + window.height - map[2] + 2
if inX > 0 and inY > 0 then
if inX > inY then
y = y - inY
else
x = x - inX
end
end
end
if x + window.width > screenWidth - 2 then
x = screenWidth - window.width - 2
end
if y + window.height > screenHeight - 2 then
y = screenHeight - window.height - 2
end
end
window:SetPos(x, y, nil, nil, nil, true)
window:BringToFront()
end
function externalFunctions.SetTextTooltip(text)
if text == "" then
return false
end
textTooltip:SetText(text)
textTooltip:Invalidate()
textTooltip:SetVisibility(true)
unitDisplay.SetVisible(false)
return true
end
function externalFunctions.SetUnitishTooltip(unitID, unitDefID, featureID, featureDefID, blueprint, morphTime, morphCost, mousePlaceX, mousePlaceY, requiredOnly)
if unitDefID or featureID or featureDefID then
unitDisplay.SetDisplay(unitID, unitDefID, featureID, featureDefID, blueprint, morphTime, morphCost, mousePlaceX, mousePlaceY, requiredOnly)
textTooltip:SetVisibility(false)
unitDisplay.SetVisible(true)
else
externalFunctions.SetTextTooltip("Enemy unit")
end
end
return externalFunctions
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Tooltip updates
local function ShowUnitCheck(holdingSpace)
if holdingSpace or options.show_for_units.value then
return true
end
end
local function ShowFeatureCheck(holdingSpace, featureDefID)
if holdingSpace then
return true
end
if options.show_for_wreckage.value then
if options.show_for_unreclaimable.value then
local fd = FeatureDefs[featureDefID]
if not (fd and fd.reclaimable) then
return false
end
end
return true
end
end
local function UpdateTooltipContent(mx, my, dt, requiredOnly)
local holdingDrawKey = GetIsHoldingDrawKey()
local holdingSpace = select(3, Spring.GetModKeyState()) and not Spring.IsUserWriting()
UpdateMouseCursor(holdingDrawKey)
if not (holdingSpace or (options.tooltip_delay.value == 0)) then
local mouseMoved = (mx ~= oldMouseX or my ~= oldMouseY)
if not mouseMoved then
stillCursorTime = stillCursorTime + dt
if stillCursorTime < options.tooltip_delay.value then
return false
end
else
stillCursorTime = 0
oldMouseX = mx
oldMouseY = my
return false
end
end
-- Mouseover build option tooltip (screen0.currentTooltip)
local chiliTooltip = screen0.currentTooltip
if chiliTooltip == NO_TOOLTIP then
return false
end
if chiliTooltip and string.find(chiliTooltip, "BuildUnit") then
local name = string.sub(chiliTooltip, 10)
local ud = name and UnitDefNames[name]
if ud then
tooltipWindow.SetUnitishTooltip(nil, ud.id, nil, nil, true)
return true
end
elseif chiliTooltip and string.find(chiliTooltip, "Build") then
local name = string.sub(chiliTooltip, 6)
local ud = name and UnitDefNames[name]
if ud then
tooltipWindow.SetUnitishTooltip(nil, ud.id, nil, nil, true)
return true
end
end
-- Mouseover morph tooltip (screen0.currentTooltip)
if chiliTooltip and string.find(chiliTooltip, "Morph") then
local unitDefID, morphTime, morphCost = chiliTooltip:match('(%d+) (%d+) (%d+)')
if unitDefID and morphTime and morphCost then
tooltipWindow.SetUnitishTooltip(nil, tonumber(unitDefID), nil, nil, false, tonumber(morphTime), tonumber(morphCost))
end
return true
end
-- Generic chili text tooltip
if chiliTooltip then
return tooltipWindow.SetTextTooltip(chiliTooltip)
end
-- Map drawing tooltip
if holdingDrawKey and (holdingSpace or options.showdrawtooltip.value) then
return tooltipWindow.SetTextTooltip(DRAWING_TOOLTIP)
end
-- Terraform tooltip (spring.GetActiveCommand)
local index, cmdID, cmdType, cmdName = Spring.GetActiveCommand()
if cmdID and terraCmdTip[cmdID] and (holdingSpace or options.showterratooltip.value) then
return tooltipWindow.SetTextTooltip(terraCmdTip[cmdID])
end
-- Placing structure tooltip (spring.GetActiveCommand)
if cmdID and cmdID < 0 then
tooltipWindow.SetUnitishTooltip(nil, -cmdID, nil, nil, true, nil, nil, mx, my, requiredOnly)
return true
end
-- Unit or feature tooltip
local thingType, thingID = spTraceScreenRay(mx,my)
local thingIsUnit = (thingType == "unit")
if thingIsUnit or (thingType == "feature") then
local ignoreDelay = holdingSpace or (options.independant_world_tooltip_delay.value == 0)
if ignoreDelay or (thingID == sameObjectID) then
if ignoreDelay or (sameObjectIDTime > options.independant_world_tooltip_delay.value) then
if thingIsUnit then
local thingDefID = Spring.GetUnitDefID(thingID)
if ShowUnitCheck(holdingSpace) then
tooltipWindow.SetUnitishTooltip(thingID, thingDefID, nil, nil, false, nil, nil, nil, nil, requiredOnly)
return true
end
else
local thingDefID = Spring.GetFeatureDefID(thingID)
if ShowFeatureCheck(holdingSpace, thingDefID) then
tooltipWindow.SetUnitishTooltip(nil, nil, thingID, thingDefID, false, nil, nil, nil, nil, requiredOnly)
return true
end
end
else
sameObjectIDTime = sameObjectIDTime + dt
end
else
sameObjectID = thingID
sameObjectIDTime = 0
end
end
-- Ground position tooltip (spGetCurrentTooltip())
if holdingSpace then
local springTooltip = Spring.GetCurrentTooltip()
if springTooltip and string.find(springTooltip, "Terrain type:") then
return tooltipWindow.SetTextTooltip(springTooltip)
end
end
-- Start position tooltip (really bad widget interface)
-- Don't want to implement this as is (pairs over positions registered in WG).
-- Geothermal tooltip (WG.mouseAboveGeo)
if WG.mouseAboveGeo then
return tooltipWindow.SetTextTooltip(WG.Translate("interface", "geospot"))
end
return false
end
local function UpdateTooltip(dt, requiredOnly)
local mx, my, _, _, _, outsideSpring = spScaledGetMouseState()
local worldMx, worldMy = spGetMouseState()
local visible = (not outsideSpring) and UpdateTooltipContent(worldMx, worldMy, dt, requiredOnly)
tooltipWindow.SetVisible(visible)
if visible then
tooltipWindow.SetPosition(mx + 20/(WG.uiScale or 1), my - 20/(WG.uiScale or 1))
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Selection window handler
local function GetSelectionWindow()
local integralWidth = math.max(350, math.min(450, screenWidth*screenHeight*0.0004))
local integralHeight = math.min(screenHeight/4.5, 200*integralWidth/450) + 8
local x = integralWidth
local visible = true
local height = integralHeight*0.84
local holderWindow = Chili.Window:New{
name = 'selections',
x = x,
bottom = 0,
width = 450,
height = height,
minWidth = 450,
minHeight = 120,
bringToFrontOnClick = false,
dockable = true,
draggable = false,
resizable = false,
tweakDraggable = true,
tweakResizable = true,
padding = {0, 0, 0, -1},
color = {0, 0, 0, 0},
parent = screen0,
}
holderWindow:SendToBack()
local mainPanel = Chili.Panel:New{
name = "mainPanel",
classname = options.fancySkinning.value,
x = 0,
y = 0,
right = 0,
bottom = 0,
padding = {8, 4, 4, 2},
backgroundColor = {1, 1, 1, options.selection_opacity.value},
OnMouseDown = {
function(self)
local _,_, meta,_ = spGetModKeyState()
if not meta then
return false
end
WG.crude.OpenPath('Settings/HUD Panels/Selected Units Window')
WG.crude.ShowMenu()
return true --skip button function, else clicking on build pic will also select the unit.
end
},
noClickThrough = false,
parent = holderWindow
}
mainPanel.padding[1] = mainPanel.padding[1] + options.leftPadding.value
mainPanel:Hide()
local singleUnitDisplay = GetSingleUnitInfoPanel(mainPanel, false)
local multiUnitDisplay = GetMultiUnitInfoPanel(mainPanel)
local selectionStatsDisplay = GetSelectionStatsDisplay(mainPanel)
local singleUnitID, singleUnitDefID
local externalFunctions = {}
function externalFunctions.ShowSingleUnit(unitID)
singleUnitID, singleUnitDefID = unitID, Spring.GetUnitDefID(unitID)
singleUnitDisplay.SetDisplay(unitID, Spring.GetUnitDefID(unitID))
singleUnitDisplay.SetVisible(true)
multiUnitDisplay.SetUnitDisplay()
selectionStatsDisplay.ChangeSelection({unitID})
end
function externalFunctions.ShowMultiUnit(newSelection)
singleUnitID = nil
multiUnitDisplay.SetUnitDisplay(newSelection)
singleUnitDisplay.SetVisible(false)
selectionStatsDisplay.ChangeSelection(newSelection)
end
function externalFunctions.UpdateSelectionWindow()
if not visible then
return
end
if singleUnitID then
singleUnitDisplay.SetDisplay(singleUnitID, singleUnitDefID)
else
multiUnitDisplay.UpdateUnitDisplay()
end
selectionStatsDisplay.UpdateStats()
end
function externalFunctions.SetVisible(newVisible)
if not newVisible then
singleUnitID = nil
end
visible = newVisible
mainPanel:SetVisibility(newVisible)
singleUnitDisplay.SetVisible(false)
multiUnitDisplay.SetUnitDisplay(false)
end
function externalFunctions.SetOpacity(opacity)
mainPanel.backgroundColor = {1,1,1,opacity}
mainPanel:Invalidate()
end
function externalFunctions.SetSkin(className)
SetPanelSkin(mainPanel, className)
end
function externalFunctions.SetLeftPadding(padding)
mainPanel.padding[1] = 8 + padding
mainPanel:UpdateClientArea()
end
function externalFunctions.SetAllowClickThrough(allowClickThrough)
mainPanel.noClickThrough = not allowClickThrough
end
function externalFunctions.SetGroupInfoVisible(newVisible)
local rightPadding = newVisible and GROUP_STATS_WIDTH or 0
multiUnitDisplay.SetRightPadding(rightPadding)
selectionStatsDisplay.SetVisibile(newVisible)
end
function externalFunctions.SetSelectionIconSize(iconSize)
multiUnitDisplay.SetIconSize(iconSize)
end
-- Initialization
externalFunctions.SetGroupInfoVisible(options.showgroupinfo.value)
return externalFunctions
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Selection update
local function UpdateSelection(newSelection)
-- Check if selection is 0, hide window. Return
-- Check if selection is 1, get unit tooltip
-- Check if selection is many, get unit list tooltip
-- Update group info.
selectedUnitsList = newSelection
if (not newSelection) or (#newSelection == 0) then
selectionWindow.SetVisible(false)
return
end
selectionWindow.SetVisible(true)
if #newSelection == 1 then
selectionWindow.ShowSingleUnit(newSelection[1])
else
selectionWindow.ShowMultiUnit(newSelection)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Widget Interface
local function InitializeWindParameters()
windMin = spGetGameRulesParam("WindMin")
windMax = spGetGameRulesParam("WindMax")
windGroundMin = spGetGameRulesParam("WindGroundMin")
windGroundSlope = spGetGameRulesParam("WindSlope")
windMinBound = spGetGameRulesParam("WindMinBound")
tidalStrength = Spring.GetGameRulesParam("tidalStrength")
tidalHeight = Spring.GetGameRulesParam("tidalHeight")
end
local updateTimer = 0
function widget:Update(dt)
updateTimer = updateTimer + dt
local slowUpdate = updateTimer > UPDATE_FREQUENCY
UpdateTooltip(dt, not slowUpdate)
if slowUpdate then
selectionWindow.UpdateSelectionWindow()
updateTimer = 0
end
end
function widget:SelectionChanged(newSelection)
UpdateSelection(newSelection)
end
function widget:ViewResize(vsx, vsy)
screenWidth = vsx/(WG.uiScale or 1)
screenHeight = vsy/(WG.uiScale or 1)
end
function widget:Initialize()
Chili = WG.Chili
screen0 = Chili.Screen0
Spring.AssignMouseCursor(CURSOR_ERASE_NAME, CURSOR_ERASE, true, false) -- Hotspot center.
Spring.AssignMouseCursor(CURSOR_POINT_NAME, CURSOR_POINT, true, true)
Spring.AssignMouseCursor(CURSOR_DRAW_NAME, CURSOR_DRAW, true, true)
Spring.SendCommands({"tooltip 0"})
Spring.SetDrawSelectionInfo(false)
local hotkeys = WG.crude.GetHotkeys("drawinmap")
for k,v in pairs(hotkeys) do
drawHotkeyBytesCount = drawHotkeyBytesCount + 1
drawHotkeyBytes[drawHotkeyBytesCount] = v:byte(-1)
end
selectionWindow = GetSelectionWindow()
tooltipWindow = GetTooltipWindow()
InitializeWindParameters()
end
function widget:UnitDestroyed(unitID)
if commanderManualFireReload[unitID] then
commanderManualFireReload[unitID] = nil
end
end
function widget:Shutdown()
Spring.SendCommands({"tooltip 1"})
Spring.SetDrawSelectionInfo(true)
Spring.SetDrawSelectionInfo(true)
end
| gpl-2.0 |
RyMarq/Zero-K | effects/gundam_greencannonimpact.lua | 25 | 7046 | -- greencannonimpact
-- yellowcannonimpact
return {
["greencannonimpact"] = {
groundflash = {
air = true,
alwaysvisible = true,
circlealpha = 1,
circlegrowth = 5.5,
flashalpha = 0.8,
flashsize = 120,
ground = true,
ttl = 10,
water = true,
color = {
[1] = 0,
[2] = 1,
[3] = 0,
},
},
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[1.0 1.0 1.0 0.04 0.5 0.9 0.2 0.01 0.1 0.8 0.1 0.01]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.05, 0]],
numparticles = 8,
particlelife = 5,
particlelifespread = 5,
particlesize = 15,
particlesizespread = 0,
particlespeed = 2,
particlespeedspread = 5,
pos = [[0, 2, 0]],
sizegrowth = 1,
sizemod = 1.0,
texture = [[flashside1]],
useairlos = false,
},
},
poof02 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[0.8 0.8 0.2 0.01 0.2 0.8 0.2 0.01 0.0 0.0 0.0 0.01]],
directional = false,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.005, 0]],
numparticles = 8,
particlelife = 5,
particlelifespread = 8,
particlesize = 10,
particlesizespread = 0,
particlespeed = 8,
particlespeedspread = 3,
pos = [[0, 2, 0]],
sizegrowth = 0.8,
sizemod = 1.0,
texture = [[randdots]],
useairlos = false,
},
},
pop1 = {
air = true,
class = [[heatcloud]],
count = 2,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 0.8,
maxheat = 10,
pos = [[0, 5, 0]],
size = 0.2,
sizegrowth = 7,
speed = [[0, 0, 0]],
texture = [[greennovaexplo]],
},
},
pop2 = {
air = true,
class = [[heatcloud]],
count = 2,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 2,
maxheat = 15,
pos = [[r-3 r3, 5, r-3 r3]],
size = 0.2,
sizegrowth = 3,
speed = [[0, 1, 0]],
texture = [[3explo]],
},
},
},
["yellowcannonimpact"] = {
groundflash = {
air = true,
alwaysvisible = true,
circlealpha = 1,
circlegrowth = 5.5,
flashalpha = 0.8,
flashsize = 120,
ground = true,
ttl = 10,
water = true,
color = {
[1] = 1,
[2] = 1,
[3] = 0,
},
},
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[1.0 1.0 1.0 0.04 0.9 0.9 0.2 0.01 0.8 0.8 0.1 0.01]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.05, 0]],
numparticles = 8,
particlelife = 5,
particlelifespread = 5,
particlesize = 15,
particlesizespread = 0,
particlespeed = 2,
particlespeedspread = 5,
pos = [[0, 2, 0]],
sizegrowth = 1,
sizemod = 1.0,
texture = [[flashside1]],
useairlos = false,
},
},
poof02 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[0.8 0.8 0.2 0.01 0.8 0.8 0.2 0.01 0.0 0.0 0.0 0.01]],
directional = false,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.005, 0]],
numparticles = 8,
particlelife = 5,
particlelifespread = 8,
particlesize = 10,
particlesizespread = 0,
particlespeed = 8,
particlespeedspread = 3,
pos = [[0, 2, 0]],
sizegrowth = 0.8,
sizemod = 1.0,
texture = [[randdots]],
useairlos = false,
},
},
pop1 = {
air = true,
class = [[heatcloud]],
count = 2,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 0.8,
maxheat = 10,
pos = [[0, 5, 0]],
size = 0.2,
sizegrowth = 7,
speed = [[0, 0, 0]],
texture = [[yellownovaexplo]],
},
},
pop2 = {
air = true,
class = [[heatcloud]],
count = 2,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 2,
maxheat = 15,
pos = [[r-3 r3, 5, r-3 r3]],
size = 0.2,
sizegrowth = 3,
speed = [[0, 1, 0]],
texture = [[3explo]],
},
},
},
}
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Selbina/npcs/Jimaida.lua | 1 | 1272 | -----------------------------------
-- Area: Selbina
-- NPC: Jimaida
-- Involved in Quests: Under the sea
-- @zone 248
-- @pos -15 -2 -16
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getVar("underTheSeaVar") == 2) then
player:startEvent(0x0021); -- During quest "Under the sea" - 2nd dialog
else
player:startEvent(0x0098); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0021) then
player:setVar("underTheSeaVar",3);
end
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Northern_San_dOria/npcs/Nouveil.lua | 1 | 2534 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Nouveil
-- Quest NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
-- "Waters of the Cheval" quest status var
waterOfTheCheval = player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(MagicmartFlyer,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
-- Waters of the Cheval, trade 10 gil for blessed waterskin
if (waterOfTheCheval == 1) then
gil = trade:getGil();
freeSlot = player:getFreeSlotsCount();
hasWaterskin = player:hasItem(602);
if (gil >= 10 and freeSlot >= 1 and hasWaterskin == false) then
player:tradeComplete();
player:delGil(10);
player:startEvent(0x023b);
else
player:messageSpecial(6564, 602); -- CANNOT_OBTAIN_ITEM, inv full or already has item
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- "Waters of the Cheval" quest status var
waterOfTheCheval = player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL);
-- Waters of the Cheval event selection
if (waterOfTheCheval == 1) then
player:startEvent(0x023f);
else
player:startEvent(0x023e);
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
-- Waters of the Cheval, recieve blessed waterskin
if (csid == 0x023b) then
player:addItem(602);
player:messageSpecial(6567, 602);
end;
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Windurst_Walls/npcs/Seven_of_Diamonds.lua | 1 | 1044 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Seven of Diamonds
-- Type: Standard NPC
-- @zone: 239
-- @pos: 6.612 -3.5 278.553
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0108);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
mojab/.files | .config/awesome/vicious/contrib/sensors.lua | 5 | 1740 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Greg D. <jabbas@jabbas.pl>
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local io = { popen = io.popen }
local setmetatable = setmetatable
local table = { insert = table.insert }
local string = {
gsub = string.gsub,
match = string.match
}
-- }}}
-- Sensors: provides access to lm_sensors data
module("vicious.contrib.sensors")
-- {{{ Split helper function
local function datasplit(str)
-- Splitting strings into associative array
-- with some magic to get the values right.
str = string.gsub(str, "\n", ":")
local tbl = {}
string.gsub(str, "([^:]*)", function (v)
if string.match(v, ".") then
table.insert(tbl, v)
end
end)
local assoc = {}
for c = 1, #tbl, 2 do
local k = string.gsub(tbl[c], ".*_", "")
local v = tonumber(string.match(tbl[c+1], "[%d]+"))
assoc[k] = v
end
return assoc
end
-- }}}
-- {{{ Sensors widget type
local function worker(format, warg)
-- Get data from all sensors
local f = io.popen("LANG=C sensors -uA")
local lm_sensors = f:read("*all")
f:close()
local sensor_data = string.gsub(
string.match(lm_sensors, warg..":\n(%s%s.-)\n[^ ]"), " ", "")
-- One of: crit, max
local divisor = "crit"
local s_data = datasplit(sensor_data)
if s_data[divisor] and s_data[divisor] > 0 then
s_data.percent = s_data.input / s_data[divisor] * 100
end
return {s_data.input, tonumber(s_data.percent)}
end
-- }}}
setmetatable(_M, { __call = function(_, ...) return worker(...) end })
| gpl-3.0 |
Grocel/wire-extras | lua/weapons/gmod_tool/stools/wire_painter.lua | 4 | 5737 | TOOL.Category = "Wire Extras/Visuals"
TOOL.Name = "Painter"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
if ( CLIENT ) then
language.Add( "Tool.wire_painter.name", "Painter Tool (Wire)" )
language.Add( "Tool.wire_painter.desc", "Spawns a decal painter for use with the wire system." )
language.Add( "Tool.wire_painter.0", "Primary: Create/Update Painter" )
language.Add( "WirePainterTool_painter", "Painter:" )
language.Add( "WirePainterTool_playsnd", "Play Sound:" )
language.Add( "WirePainterTool_paintrate", "Paint Rate:" )
language.Add( "WirePainterTool_decal", "Decal:" )
language.Add( "WirePainterTool_Range", "Max Range:" )
language.Add( "WirePainterTool_Model", "Choose a Model:")
language.Add( "sboxlimit_wire_painters", "You've hit painters limit!" )
language.Add( "undone_Wire Painter", "Undone Wire Painter" )
end
if (SERVER) then
CreateConVar('sbox_maxwire_painters', 20)
CreateConVar('sbox_wire_painters_maxlen', 30)
CreateConVar('sbox_wire_painters_allowtrgply',1)
end
TOOL.ClientConVar[ "playsnd" ] = "1"
TOOL.ClientConVar[ "paintrate" ] = "0"
TOOL.ClientConVar[ "decal" ] = "Blood"
TOOL.ClientConVar[ "Range" ] = 2048
TOOL.ClientConVar[ "Model" ] = "models/jaanus/wiretool/wiretool_siren.mdl"
local paintermodels = {
["models/jaanus/wiretool/wiretool_beamcaster.mdl"] = {},
["models/jaanus/wiretool/wiretool_siren.mdl"] = {}};
cleanup.Register( "wire_painters" )
function TOOL:LeftClick( trace )
if (!trace.HitPos) then return false end
if (trace.Entity:IsPlayer()) then return false end
if ( CLIENT ) then return true end
local ply = self:GetOwner()
local playsnd = (self:GetClientNumber( "playsnd" ) ~= 0)
local paintrate = self:GetClientNumber("paintrate")
local decal = self:GetClientInfo("decal")
local Range = self:GetClientNumber("Range")
local model = self:GetClientInfo("Model")
if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_painter" && trace.Entity:GetTable().pl == ply ) then
trace.Entity:Setup(Range, decal, playsnd, paintrate)
return true
end
if ( !self:GetSWEP():CheckLimit( "wire_painters" ) ) then return false end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local wire_painter = MakeWirePainter( ply, trace.HitPos, Range, decal, playsnd, paintrate, model, Ang )
local min = wire_painter:OBBMins()
wire_painter:SetPos( trace.HitPos - trace.HitNormal * min.z )
local const = WireLib.Weld(wire_painter, trace.Entity, trace.PhysicsBone, true)
undo.Create("Wire Painter")
undo.AddEntity( wire_painter )
undo.AddEntity( const )
undo.SetPlayer( ply )
undo.Finish()
ply:AddCleanup( "wire_painters", wire_painter )
return true
end
if (SERVER) then
function MakeWirePainter( pl, Pos, Range, decal, playsnd, paintrate, Model, Ang )
if ( !pl:CheckLimit( "wire_painters" ) ) then return false end
local wire_painter = ents.Create( "gmod_wire_painter" )
if (!wire_painter:IsValid()) then return false end
wire_painter:SetAngles( Ang )
wire_painter:SetPos( Pos )
wire_painter:SetModel( Model )
wire_painter:Spawn()
wire_painter:Setup(Range, decal, playsnd, paintrate)
wire_painter:SetPlayer( pl )
local ttable = {
Range = Range,
Decal = decal,
PlaySound = playsnd,
PaintRate = paintrate,
pl = pl
}
table.Merge(wire_painter:GetTable(), ttable )
pl:AddCount( "wire_painters", wire_painter )
return wire_painter
end
duplicator.RegisterEntityClass("gmod_wire_painter", MakeWirePainter, "Pos", "Range", "Decal", "PlaySound", "PaintRate", "Model", "Ang", "Vel", "aVel", "frozen")
end
function TOOL:UpdateGhostWirePainter( ent, player )
if ( !ent || !ent:IsValid() ) then return end
local tr = util.GetPlayerTrace( player, player:GetAimVector() )
local trace = util.TraceLine( tr )
if (!trace.Hit || trace.Entity:IsPlayer() || trace.Entity:GetClass() == "gmod_wire_painter" ) then
ent:SetNoDraw( true )
return
end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local min = ent:OBBMins()
ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
ent:SetAngles( Ang )
ent:SetNoDraw( false )
end
function TOOL:Think()
if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self:GetClientInfo("Model") ) then
self:MakeGhostEntity( self:GetClientInfo("Model"), Vector(0,0,0), Angle(0,0,0) )
end
self:UpdateGhostWirePainter( self.GhostEntity, self:GetOwner() )
end
function TOOL.BuildCPanel(panel)
panel:AddControl("Header", { Text = "#Tool.wire_painter.name", Description = "#Tool.wire_painter.desc" })
panel:AddControl( "PropSelect", { Label = "#WirePainterTool_Model",
ConVar = "wire_painter_Model",
Category = "Wire Painter",
Models = paintermodels } )
local Options = list.Get( "PaintMaterials" )
table.sort( Options )
local RealOptions = {}
for k, decal in pairs( Options ) do
RealOptions[ decal ] = { wire_painter_decal = decal }
end
panel:AddControl( "ListBox", {
Label = "#WirePainterTool_decal",
Height = "300",
Options = RealOptions
} )
panel:AddControl("CheckBox", {
Label = "#WirePainterTool_playsnd",
Command = "wire_painter_playsnd"
})
panel:AddControl("Slider", {
Label = "#WirePainterTool_paintrate",
Type = "Float",
Min = "0",
Max = "2",
Command = "wire_painter_paintrate"
})
panel:AddControl("Slider", {
Label = "#WirePainterTool_Range",
Type = "Float",
Min = "1",
Max = "10000",
Command = "wire_painter_Range"
})
end
| apache-2.0 |
RyMarq/Zero-K | LuaRules/Gadgets/unit_decloak_damaged.lua | 2 | 10726 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Decloak when damaged",
desc = "Decloaks units when they are damaged",
author = "Google Frog",
date = "Nov 25, 2009", -- Major rework 12 Feb 2014
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
include("LuaRules/Configs/customcmds.h.lua")
local CMD_CLOAK = CMD.CLOAK
local unitWantCloakCommandDesc = {
id = CMD_WANT_CLOAK,
type = CMDTYPE.ICON_MODE,
name = 'Cloak State',
action = 'wantcloak',
tooltip = 'Unit cloaking state',
params = {0, 'Decloaked', 'Cloaked'}
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (not gadgetHandler:IsSyncedCode()) then
return false -- silent removal
end
local alliedTrueTable = {allied = true}
local Spring = Spring
local spAreTeamsAllied = Spring.AreTeamsAllied
local spSetUnitCloak = Spring.SetUnitCloak
local spGetUnitIsCloaked = Spring.GetUnitIsCloaked
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spSetUnitRulesParam = Spring.SetUnitRulesParam
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitIsDead = Spring.GetUnitIsDead
local recloakUnit = {}
local recloakFrame = {}
local noFFWeaponDefs = {}
for i = 1, #WeaponDefs do
local wd = WeaponDefs[i]
if wd.customParams and wd.customParams.nofriendlyfire then
noFFWeaponDefs[i] = true
end
end
local DEFAULT_DECLOAK_TIME = 100
local UPDATE_FREQUENCY = 10
local CLOAK_MOVE_THRESHOLD = math.sqrt(0.2)
local currentFrame = 0
local cloakUnitDefID = {}
for i = 1, #UnitDefs do
local ud = UnitDefs[i]
if ud.canCloak and not ud.customParams.dynamic_comm then
cloakUnitDefID[i] = true
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Water handling
local waterUnitCount = 0
local waterUnitMap = {}
local waterUnits = {}
local waterUnitCloakBlocked = {}
local function AddWaterUnit(unitID)
if waterUnitMap[unitID] then
return
end
waterUnitCount = waterUnitCount + 1
waterUnitMap[unitID] = waterUnitCount
waterUnits[waterUnitCount] = unitID
end
local function RemoveWaterUnit(unitID)
if not waterUnitMap[unitID] then
return
end
waterUnits[waterUnitMap[unitID]] = waterUnits[waterUnitCount]
waterUnitMap[waterUnits[waterUnitCount]] = waterUnitMap[unitID]
waterUnits[waterUnitCount] = nil
waterUnitMap[unitID] = nil
waterUnitCount = waterUnitCount - 1
waterUnitCloakBlocked[unitID] = nil
end
function gadget:UnitEnteredWater(unitID)
AddWaterUnit(unitID)
end
function gadget:UnitLeftWater(unitID)
RemoveWaterUnit(unitID)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function PokeDecloakUnit(unitID, duration)
if recloakUnit[unitID] then
recloakUnit[unitID] = duration or DEFAULT_DECLOAK_TIME
else
spSetUnitRulesParam(unitID, "cannotcloak", 1, alliedTrueTable)
spSetUnitCloak(unitID, 0)
recloakUnit[unitID] = duration or DEFAULT_DECLOAK_TIME
end
end
GG.PokeDecloakUnit = PokeDecloakUnit
function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer,
weaponID, attackerID, attackerDefID, attackerTeam)
if damage > 0 and
not (attackerTeam and
weaponID and
noFFWeaponDefs[weaponID] and
attackerID ~= unitID and
spAreTeamsAllied(unitTeam, attackerTeam)) then
PokeDecloakUnit(unitID)
end
end
local function CheckWaterBlockCloak(unitID, pos)
local radius = Spring.GetUnitRadius(unitID)
if radius + pos < 0 then
if not waterUnitCloakBlocked[unitID] then
PokeDecloakUnit(unitID)
spSetUnitRulesParam(unitID, "cannotcloak", 1, alliedTrueTable)
waterUnitCloakBlocked[unitID] = true
end
return true
end
return false
end
function gadget:GameFrame(n)
currentFrame = n
if n%UPDATE_FREQUENCY == 2 then
for unitID, frames in pairs(recloakUnit) do
if frames <= UPDATE_FREQUENCY then
if not ((spGetUnitRulesParam(unitID,"on_fire") == 1) or (spGetUnitRulesParam(unitID,"disarmed") == 1) or waterUnitCloakBlocked[unitID]) then
local wantCloakState = spGetUnitRulesParam(unitID, "wantcloak")
local areaCloaked = spGetUnitRulesParam(unitID, "areacloaked")
spSetUnitRulesParam(unitID, "cannotcloak", 0, alliedTrueTable)
if wantCloakState == 1 or areaCloaked == 1 then
spSetUnitCloak(unitID, 1)
end
recloakUnit[unitID] = nil
end
else
recloakUnit[unitID] = frames - UPDATE_FREQUENCY
end
end
local i = 1
while i <= waterUnitCount do
local unitID = waterUnits[i]
if Spring.ValidUnitID(unitID) then
local pos = select(5, Spring.GetUnitPosition(unitID, true))
if pos < 0 then
if (not CheckWaterBlockCloak(unitID, pos)) and waterUnitCloakBlocked[unitID] then
spSetUnitRulesParam(unitID, "cannotcloak", 0, alliedTrueTable)
waterUnitCloakBlocked[unitID] = false
end
else
if waterUnitCloakBlocked[unitID] then
spSetUnitRulesParam(unitID, "cannotcloak", 0, alliedTrueTable)
waterUnitCloakBlocked[unitID] = false
end
end
i = i + 1
else
RemoveWaterUnit(unitID)
end
end
end
end
-- Only called with enemyID if an enemy is within decloak radius.
function gadget:AllowUnitCloak(unitID, enemyID)
if enemyID then
local transID = Spring.GetUnitTransporter(unitID)
if transID then
-- For some reason enemyID indicates that the unit is being transported.
return Spring.GetUnitIsCloaked(transID)
end
return false
end
if recloakFrame[unitID] then
if recloakFrame[unitID] > currentFrame then
return false
end
recloakFrame[unitID] = nil
end
local stunnedOrInbuild = Spring.GetUnitIsStunned(unitID)
if stunnedOrInbuild then
return false
end
local unitDefID = unitID and Spring.GetUnitDefID(unitID)
local ud = unitDefID and UnitDefs[unitDefID]
if not ud then
return false
end
local areaCloaked = (Spring.GetUnitRulesParam(unitID, "areacloaked") == 1) and ((Spring.GetUnitRulesParam(unitID, "cloak_shield") or 0) == 0)
if not areaCloaked then
local speed = select(4, Spring.GetUnitVelocity(unitID))
local moving = speed and speed > CLOAK_MOVE_THRESHOLD
local cost = moving and ud.cloakCostMoving or ud.cloakCost
if not Spring.UseUnitResource(unitID, "e", cost/2) then -- SlowUpdate happens twice a second.
return false
end
end
return true
end
function gadget:AllowUnitDecloak(unitID, objectID, weaponID)
recloakFrame[unitID] = currentFrame + DEFAULT_DECLOAK_TIME
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function SetWantedCloaked(unitID, state)
if (not unitID) or spGetUnitIsDead(unitID) then
return
end
local wantCloakState = spGetUnitRulesParam(unitID, "wantcloak")
local cmdDescID = Spring.FindUnitCmdDesc(unitID, CMD_WANT_CLOAK)
if (cmdDescID) then
Spring.EditUnitCmdDesc(unitID, cmdDescID, { params = {state, 'Decloaked', 'Cloaked'}})
end
if state == 1 and wantCloakState ~= 1 then
local cannotCloak = spGetUnitRulesParam(unitID, "cannotcloak")
local areaCloaked = spGetUnitRulesParam(unitID, "areacloaked")
if cannotCloak ~= 1 and areaCloaked ~= 1 then
spSetUnitCloak(unitID, 1)
end
spSetUnitRulesParam(unitID, "wantcloak", 1, alliedTrueTable)
elseif state == 0 and wantCloakState == 1 then
local areaCloaked = spGetUnitRulesParam(unitID, "areacloaked")
if areaCloaked ~= 1 then
spSetUnitCloak(unitID, 0)
end
spSetUnitRulesParam(unitID, "wantcloak", 0, alliedTrueTable)
end
end
GG.SetWantedCloaked = SetWantedCloaked
function gadget:AllowCommand_GetWantedCommand()
return {[CMD_CLOAK] = true, [CMD_WANT_CLOAK] = true}
end
function gadget:AllowCommand_GetWantedUnitDefID()
return true
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
if cmdID == CMD_WANT_CLOAK then
if cloakUnitDefID[unitDefID] or GG.Upgrades_UnitCanCloak(unitID) then
SetWantedCloaked(unitID,cmdParams[1])
end
return false
elseif cmdID == CMD_CLOAK then
return false
end
return true
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:UnitCreated(unitID, unitDefID)
local ud = UnitDefs[unitDefID]
if cloakUnitDefID[unitDefID] or GG.Upgrades_UnitCanCloak(unitID) then
local cloakDescID = Spring.FindUnitCmdDesc(unitID, CMD_CLOAK)
if cloakDescID then
Spring.InsertUnitCmdDesc(unitID, unitWantCloakCommandDesc)
Spring.RemoveUnitCmdDesc(unitID, cloakDescID)
spSetUnitRulesParam(unitID, "wantcloak", 0, alliedTrueTable)
if ud.customParams.initcloaked then
SetWantedCloaked(unitID, 1)
end
return
end
elseif ud.customParams.dynamic_comm then
local cloakDescID = Spring.FindUnitCmdDesc(unitID, CMD_CLOAK)
if cloakDescID then
Spring.RemoveUnitCmdDesc(unitID, cloakDescID)
end
end
end
function gadget:Initialize()
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = spGetUnitDefID(unitID)
gadget:UnitCreated(unitID, unitDefID)
local pos = select(2, Spring.GetUnitPosition(unitID))
if pos <= 0 then
gadget:UnitEnteredWater(unitID)
end
end
end
function gadget:Load(zip)
for _, unitID in ipairs(Spring.GetAllUnits()) do
-- restore cloak for dyncomms during a loaded savegame
-- the CMD_CLOAK cmd desc ID was already removed during the UnitCreated() call, so we can't use the detection method used there
-- instead we do this
if GG.Upgrades_UnitCanCloak(unitID) then
Spring.InsertUnitCmdDesc(unitID, unitWantCloakCommandDesc)
local wantedState = spGetUnitRulesParam(unitID, "wantcloak")
spSetUnitRulesParam(unitID, "wantcloak", 0, alliedTrueTable)
SetWantedCloaked(unitID, wantedState)
-- unit_commander_upgrade runs after us and decloaks us while setting our decloak radius,
-- so reset at earliest opportunity
if wantedState == 1 then
recloakUnit[unitID] = 0
end
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampParentsPageDetailConfig.lua | 1 | 5461 | --[[
Title: RedSummerCampParentsPageDetailConfig
Author(s): pbb
Date: 2021/7/9
Desc: the parent's detail page for red summer camp 2021
Use Lib:
-------------------------------------------------------
local RedSummerCampParentsPageDetailConfig = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampParentsPageDetailConfig.lua");
--]]
local RedSummerCampParentsPageDetailConfig = NPL.export();
RedSummerCampParentsPageDetailConfig.network ={
{
desc = [[——为孩子营造一个学习&展示人工智能的舞台<br/>
“游玩”、“学习”、“创造”构成了一个孩子日常的生活。<br/>
如果只有“游玩”,那是消极而没有意义的;<br/>
如果只有“学习”,那是枯燥而没有快乐的;<br/>
如果只有“创造”,那是漫无目的的。<br/><br/>
《帕拉卡》Paracraft正是这样一款将“游玩”、“学习”、“创造”整合于一体的寓教于乐学习工具。通过人工智能赋能,为中国青少年营造一个学习、展示人工智能的舞台。<br/>
21世纪将是人工智能的时代,大量传统的工作正在逐步被AI和计算机所取代。《帕拉卡》Paracraft基于全球领先的STEAM和PBL等自主教育理念,结合帕拉卡在软件编程方面十多年的丰富经验,研发出大量自主学习内容和网上课程。<br/>
]],
icons={"636 662 300 170","318 662 300 170","0 662 300 170"},
iconsdetail={"△各省教育局认可正规校本课软件","△从兴趣出发培养学生自主式学习","△PBL项目式小组化学习"}
},
{
desc = [[——告诉孩子,什么是人工智能<br/>
哈尔滨工业大学,参与新中国第一颗卫星研制工作的李铁才教授,基于人工智能研究领域中最重要的仿生学习,提出“相似性与相似性原理”(并出版相关著作),对人工智能做出了如下的定义:<br/>
思维和记忆构成了人类的智能;<br/>
编程和动画构成了计算的智能,即人工智能<br/>
《帕拉卡》是全球极少数真正从人工智能的本质去思考未来计算机教育的软件,《帕拉卡》软件的重点从来都不是单纯教授某一种编程语言,而是让孩子在使用编程去控制动画的过程中体会人工智能,培养对人工智能的兴趣,为成为新时代中国前沿人才播下种子。<br/>
]],
icons={"0 475 300 170","318 475 300 170","636 475 300 170"},
iconsdetail={"△三维电脑动画的学习","△使用程序控制动画","△模拟人脑结构学习人工智能编程"}
},
{
desc = [[——学以致用,伴随一生<br/>
由中国人完全自主研发的NPL(神经元并行)计算机语言以及ParaEngine三维图形引擎,构成了《帕拉卡》的大脑和心脏。《帕拉卡》正是使用NPL语言进行开发,同时孩子学习的也正是相同的计算机语言,《帕拉卡》足以成为陪伴孩子从计算机入门直至成长为计算机人才的全过程。<br/>
持续输出“作品”,是让人保持不断“学习”和“创造”的源动力。让每个学习了《帕拉卡》的孩子不仅都能收获自己的动画作品和编程作品,更重要的是通过用编程去控制动画,使之成为能够有简单交互的人工智能。而这种简单的交互,正是所有电子游戏最初始的形态。<br/>
]],
icons={"636 475 300 170","318 288 300 170","0 288 300 170"},
iconsdetail={"△创作高水准动画短片","△制作可以弹奏的钢琴","△创造人工智能虚拟校园"}
},
{
desc = [[——创造一个基于人工智能的未来虚拟校园<br/>
编程不应该是孤独的,人工智能更不应该是孤独的。当一个人工智能与另一个人工智能相遇的时候,或许“她们”将碰撞出奇妙的火花,这就是《帕拉卡》的人工智能虚拟校园计划。同学与同学的人工智能融合成一个虚拟的班级;班级与班级的人工智能融合成一个虚拟的校园。当我们徜徉在虚拟的校园中,被它的乐趣深深吸引的时候,我们应当感到兴奋和惊奇。因为眼前的所见,大多出自学生的作品。<br/>
]],
icons={"0 0 1016 268"},
}
}
RedSummerCampParentsPageDetailConfig.charge = {
{
desc = [[——成为《帕拉卡》会员畅享全部服务<br/>
成为《帕拉卡》会员后畅享全部在线课程及数款由帕拉卡教育联盟企业共同制作的精品软件以及在线一对一的软件技术解决服务。<br/>
每周《帕拉卡》都会有新课不断上线,只要在会员权益期限内,均可无限次享受新课程的学习体验。<br/>]],
icons={"1355 3 300 170","1035 3 300 170","1675 3 300 170"},
iconsdetail={"专项赛事赛点精讲课程","AI宏示教辅助教学功能","联盟企业特色精品课程"}
}
}
local RedSummerCampParentsPageDetailConfig = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampParentsPageDetailConfig.lua");
function RedSummerCampParentsPageDetailConfig.GetNetConfigDesc(index)
local desc = RedSummerCampParentsPageDetailConfig.network[index].desc
--print("desc=================",desc)
return desc
end
function RedSummerCampParentsPageDetailConfig.GetNetConfigImgDesc(index,idx)
local data = RedSummerCampParentsPageDetailConfig.network[index]
if data then
local str = data.iconsdetail[idx]
print("str================",str,index,idx)
--echo(data)
return str
end
end | gpl-2.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua | 50 | 6053 | --[[
Luci statistics - statistics controller module
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2012 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module("luci.controller.luci_statistics.luci_statistics", package.seeall)
function index()
require("nixio.fs")
require("luci.util")
require("luci.statistics.datatree")
-- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path
function _entry( path, ... )
local file = path[5] or path[4]
if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then
entry( path, ... )
end
end
local labels = {
s_output = _("Output plugins"),
s_system = _("System plugins"),
s_network = _("Network plugins"),
conntrack = _("Conntrack"),
cpu = _("Processor"),
csv = _("CSV Output"),
df = _("Disk Space Usage"),
disk = _("Disk Usage"),
dns = _("DNS"),
email = _("Email"),
exec = _("Exec"),
interface = _("Interfaces"),
iptables = _("Firewall"),
irq = _("Interrupts"),
iwinfo = _("Wireless"),
load = _("System Load"),
memory = _("Memory"),
netlink = _("Netlink"),
network = _("Network"),
nut = _("UPS"),
olsrd = _("OLSRd"),
ping = _("Ping"),
processes = _("Processes"),
rrdtool = _("RRDTool"),
tcpconns = _("TCP Connections"),
unixsock = _("UnixSock"),
uptime = _("Uptime")
}
-- our collectd menu
local collectd_menu = {
output = { "csv", "network", "rrdtool", "unixsock" },
system = { "cpu", "df", "disk", "email", "exec", "irq", "load", "memory", "nut", "processes", "uptime" },
network = { "conntrack", "dns", "interface", "iptables", "netlink", "olsrd", "ping", "tcpconns", "iwinfo" }
}
-- create toplevel menu nodes
local st = entry({"admin", "statistics"}, template("admin_statistics/index"), _("Statistics"), 80)
st.index = true
entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true
-- populate collectd plugin menu
local index = 1
for section, plugins in luci.util.kspairs( collectd_menu ) do
local e = entry(
{ "admin", "statistics", "collectd", section },
firstchild(), labels["s_"..section], index * 10
)
e.index = true
for j, plugin in luci.util.vspairs( plugins ) do
_entry(
{ "admin", "statistics", "collectd", section, plugin },
cbi("luci_statistics/" .. plugin ),
labels[plugin], j * 10
)
end
index = index + 1
end
-- output views
local page = entry( { "admin", "statistics", "graph" }, template("admin_statistics/index"), _("Graphs"), 80)
page.setuser = "nobody"
page.setgroup = "nogroup"
local vars = luci.http.formvalue(nil, true)
local span = vars.timespan or nil
local host = vars.host or nil
-- get rrd data tree
local tree = luci.statistics.datatree.Instance(host)
local _, plugin, idx
for _, plugin, idx in luci.util.vspairs( tree:plugins() ) do
-- get plugin instances
local instances = tree:plugin_instances( plugin )
-- plugin menu entry
entry(
{ "admin", "statistics", "graph", plugin },
call("statistics_render"), labels[plugin], idx
).query = { timespan = span , host = host }
-- if more then one instance is found then generate submenu
if #instances > 1 then
local _, inst, idx2
for _, inst, idx2 in luci.util.vspairs(instances) do
-- instance menu entry
entry(
{ "admin", "statistics", "graph", plugin, inst },
call("statistics_render"), inst, idx2
).query = { timespan = span , host = host }
end
end
end
end
function statistics_render()
require("luci.statistics.rrdtool")
require("luci.template")
require("luci.model.uci")
local vars = luci.http.formvalue()
local req = luci.dispatcher.context.request
local path = luci.dispatcher.context.path
local uci = luci.model.uci.cursor()
local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true )
local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1]
local host = vars.host or uci:get( "luci_statistics", "collectd", "Hostname" ) or luci.sys.hostname()
local opts = { host = vars.host }
local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ), opts )
local hosts = graph.tree:host_instances()
local is_index = false
local i, p, inst, idx
-- deliver image
if vars.img then
local l12 = require "luci.ltn12"
local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r")
if png then
luci.http.prepare_content("image/png")
l12.pump.all(l12.source.file(png), luci.http.write)
png:close()
end
return
end
local plugin, instances
local images = { }
-- find requested plugin and instance
for i, p in ipairs( luci.dispatcher.context.path ) do
if luci.dispatcher.context.path[i] == "graph" then
plugin = luci.dispatcher.context.path[i+1]
instances = { luci.dispatcher.context.path[i+2] }
end
end
-- no instance requested, find all instances
if #instances == 0 then
--instances = { graph.tree:plugin_instances( plugin )[1] }
instances = graph.tree:plugin_instances( plugin )
is_index = true
-- index instance requested
elseif instances[1] == "-" then
instances[1] = ""
is_index = true
end
-- render graphs
for i, inst in luci.util.vspairs( instances ) do
for i, img in luci.util.vspairs( graph:render( plugin, inst, is_index ) ) do
table.insert( images, graph:strippngpath( img ) )
images[images[#images]] = inst
end
end
luci.template.render( "public_statistics/graph", {
images = images,
plugin = plugin,
timespans = spans,
current_timespan = span,
hosts = hosts,
current_host = host,
is_index = is_index
} )
end
| gpl-2.0 |
flyzjhz/witi-openwrt | package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua | 50 | 6053 | --[[
Luci statistics - statistics controller module
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2012 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module("luci.controller.luci_statistics.luci_statistics", package.seeall)
function index()
require("nixio.fs")
require("luci.util")
require("luci.statistics.datatree")
-- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path
function _entry( path, ... )
local file = path[5] or path[4]
if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then
entry( path, ... )
end
end
local labels = {
s_output = _("Output plugins"),
s_system = _("System plugins"),
s_network = _("Network plugins"),
conntrack = _("Conntrack"),
cpu = _("Processor"),
csv = _("CSV Output"),
df = _("Disk Space Usage"),
disk = _("Disk Usage"),
dns = _("DNS"),
email = _("Email"),
exec = _("Exec"),
interface = _("Interfaces"),
iptables = _("Firewall"),
irq = _("Interrupts"),
iwinfo = _("Wireless"),
load = _("System Load"),
memory = _("Memory"),
netlink = _("Netlink"),
network = _("Network"),
nut = _("UPS"),
olsrd = _("OLSRd"),
ping = _("Ping"),
processes = _("Processes"),
rrdtool = _("RRDTool"),
tcpconns = _("TCP Connections"),
unixsock = _("UnixSock"),
uptime = _("Uptime")
}
-- our collectd menu
local collectd_menu = {
output = { "csv", "network", "rrdtool", "unixsock" },
system = { "cpu", "df", "disk", "email", "exec", "irq", "load", "memory", "nut", "processes", "uptime" },
network = { "conntrack", "dns", "interface", "iptables", "netlink", "olsrd", "ping", "tcpconns", "iwinfo" }
}
-- create toplevel menu nodes
local st = entry({"admin", "statistics"}, template("admin_statistics/index"), _("Statistics"), 80)
st.index = true
entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true
-- populate collectd plugin menu
local index = 1
for section, plugins in luci.util.kspairs( collectd_menu ) do
local e = entry(
{ "admin", "statistics", "collectd", section },
firstchild(), labels["s_"..section], index * 10
)
e.index = true
for j, plugin in luci.util.vspairs( plugins ) do
_entry(
{ "admin", "statistics", "collectd", section, plugin },
cbi("luci_statistics/" .. plugin ),
labels[plugin], j * 10
)
end
index = index + 1
end
-- output views
local page = entry( { "admin", "statistics", "graph" }, template("admin_statistics/index"), _("Graphs"), 80)
page.setuser = "nobody"
page.setgroup = "nogroup"
local vars = luci.http.formvalue(nil, true)
local span = vars.timespan or nil
local host = vars.host or nil
-- get rrd data tree
local tree = luci.statistics.datatree.Instance(host)
local _, plugin, idx
for _, plugin, idx in luci.util.vspairs( tree:plugins() ) do
-- get plugin instances
local instances = tree:plugin_instances( plugin )
-- plugin menu entry
entry(
{ "admin", "statistics", "graph", plugin },
call("statistics_render"), labels[plugin], idx
).query = { timespan = span , host = host }
-- if more then one instance is found then generate submenu
if #instances > 1 then
local _, inst, idx2
for _, inst, idx2 in luci.util.vspairs(instances) do
-- instance menu entry
entry(
{ "admin", "statistics", "graph", plugin, inst },
call("statistics_render"), inst, idx2
).query = { timespan = span , host = host }
end
end
end
end
function statistics_render()
require("luci.statistics.rrdtool")
require("luci.template")
require("luci.model.uci")
local vars = luci.http.formvalue()
local req = luci.dispatcher.context.request
local path = luci.dispatcher.context.path
local uci = luci.model.uci.cursor()
local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true )
local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1]
local host = vars.host or uci:get( "luci_statistics", "collectd", "Hostname" ) or luci.sys.hostname()
local opts = { host = vars.host }
local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ), opts )
local hosts = graph.tree:host_instances()
local is_index = false
local i, p, inst, idx
-- deliver image
if vars.img then
local l12 = require "luci.ltn12"
local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r")
if png then
luci.http.prepare_content("image/png")
l12.pump.all(l12.source.file(png), luci.http.write)
png:close()
end
return
end
local plugin, instances
local images = { }
-- find requested plugin and instance
for i, p in ipairs( luci.dispatcher.context.path ) do
if luci.dispatcher.context.path[i] == "graph" then
plugin = luci.dispatcher.context.path[i+1]
instances = { luci.dispatcher.context.path[i+2] }
end
end
-- no instance requested, find all instances
if #instances == 0 then
--instances = { graph.tree:plugin_instances( plugin )[1] }
instances = graph.tree:plugin_instances( plugin )
is_index = true
-- index instance requested
elseif instances[1] == "-" then
instances[1] = ""
is_index = true
end
-- render graphs
for i, inst in luci.util.vspairs( instances ) do
for i, img in luci.util.vspairs( graph:render( plugin, inst, is_index ) ) do
table.insert( images, graph:strippngpath( img ) )
images[images[#images]] = inst
end
end
luci.template.render( "public_statistics/graph", {
images = images,
plugin = plugin,
timespans = spans,
current_timespan = span,
hosts = hosts,
current_host = host,
is_index = is_index
} )
end
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Code/HaqiDef/HaqiDef_Arena.lua | 1 | 24399 | --[[
Title: Block Pen
Author(s): LiXizhi
Date: 2020/2/16
Desc:
use the lib:
-------------------------------------------------------
-------------------------------------------------------
]]
NPL.export({
-----------------------
{
type = "createArena",
message0 = "法阵 名字%1 位置%2",
arg0 = {
{
name = "name",
type = "input_value",
shadow = { type = "text", value = "Arena1",},
text = "Arena1",
},
{
name = "position",
type = "input_value",
shadow = { type = "text", value = "~ ~ ~",},
text = "~ ~ ~",
},
},
category = "arena",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'createArena(%s, %s)',
ToNPL = function(self)
return string.format('createArena("%s", "%s")\n', self:getFieldValue('name'), self:getFieldValue('position'));
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-----------------------
{
type = "addArenaMob",
message0 = "添加怪物 %1 名字:%2",
arg0 = {
{
name = "index",
type = "field_dropdown",
options = {
{ "1号位", "1" },
{ "2号位", "2" },
{ "3号位", "3" },
{ "4号位", "4" },
},
},
{
name = "name",
type = "input_value",
shadow = { type = "text", value = "Default",},
text = "Default",
},
},
category = "arena",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'addArenaMob(%s, %s)',
ToNPL = function(self)
return string.format('addArenaMob(%s, "%s")\n', self:getFieldValue('index'), self:getFieldValue('name'));
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-----------------------
{
type = "setMyCards",
message0 = "设置我的卡牌包 {%1%2%3}",
arg0 = {
{
name = "start_dummy",
type = "input_dummy",
},
{
name = "end_dummy",
type = "input_dummy",
},
{
name = "btn",
type = "field_button",
content = {
src = "png/plus-2x.png"
},
width = 16,
height = 16,
callback = "FIELD_BUTTON_CALLBACK_append_mcml_attr"
},
},
category = "Control",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description_lua_provider = [[
var attrs = Blockly.Extensions.readTextFromMcmlAttrs(block, "Lua", ",");
if (attrs) {
return "setMyCards({%s})\n".format(attrs);
}else{
return "setMyCards({})\n";
}
]],
ToNPL = function(self)
return string.format('setMyCards({})\n');
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-----------------------
{
type = "setUserValue",
message0 = "设置属性%1 %2",
arg0 = {
{
name = "name",
type = "field_dropdown",
options = {
{"血量增加绝对值", "addonlevel_hp_absolute"},
{"伤害增加绝对值", "addonlevel_damage_absolute"},
{"伤害增加百分之", "addonlevel_damage_percent"},
{"韧性增加百分之", "addonlevel_resilience_percent"},
{"暴击率增加百分之", "addonlevel_criticalstrike_percent"},
{"防御增加绝对值", "addonlevel_resist_absolute"},
{"战斗等级", "combatlel"},
},
},
{
name = "value",
type = "field_number",
text = "0",
},
},
category = "Control",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'setUserValue("%s", %s)',
ToNPL = function(self)
return string.format('setUserValue("%s", %s)\n', self:getFieldValue('name'), self:getFieldValue('value'));
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-----------------------
{
type = "getUserValue",
message0 = "获取属性 %1",
arg0 = {
{
name = "name",
type = "field_dropdown",
options = {
{"血量增加绝对值", "addonlevel_hp_absolute"},
{"伤害增加绝对值", "addonlevel_damage_absolute"},
{"伤害增加百分之", "addonlevel_damage_percent"},
{"韧性增加百分之", "addonlevel_resilience_percent"},
{"暴击率增加百分之", "addonlevel_criticalstrike_percent"},
{"防御增加绝对值", "addonlevel_resist_absolute"},
{"战斗等级", "combatlel"},
},
},
},
output = {type = "field_number",},
category = "Control",
helpUrl = "",
canRun = false,
func_description = 'getUserValue("%s")',
ToNPL = function(self)
return string.format('getUserValue("%s")', self:getFieldValue('name'));
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-----------------------------------
{
type = "setCurrentHP",
message0 = "设置当前血量 %1",
arg0 = {
{
name = "value",
type = "field_number",
text = "0",
},
},
category = "Control",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'setCurrentHP(%s)',
ToNPL = function(self)
return string.format('setCurrentHP(%s)\n', self:getFieldValue('value'));
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-----------------------
{
type = "getCurrentHP",
message0 = "获取当前血量",
arg0 = {
},
output = {type = "field_number",},
category = "Control",
helpUrl = "",
canRun = false,
func_description = 'getCurrentHP()',
ToNPL = function(self)
return string.format('getCurrentHP()');
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-----------------------
{
type = "removeAllArenas",
message0 = "刪除所有法阵",
arg0 = {
},
category = "Control",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'removeAllArenas()',
ToNPL = function(self)
return string.format('removeAllArenas()\n');
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-----------------------
{
type = "removeArena",
message0 = "删除法阵 %1",
arg0 = {
{
name = "name",
type = "input_value",
shadow = { type = "text", value = "Arena1",},
text = "Arena1",
},
},
category = "Control",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'removeArena(%s)',
ToNPL = function(self)
return string.format('removeArena("%s")\n', self:getFieldValue('name'));
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-----------------------
{
type = "restart",
message0 = "重启服务器",
arg0 = {
},
category = "Control",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'restart()',
ToNPL = function(self)
return string.format('restart()\n');
end,
examples = {{desc = "", canRun = false, code = [[
]]}},
},
-------------------------------
{
type = "cardIce",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{"冰霜破", "22139"},
{"陨落冰石", "22140"},
{"冰剑凛空", "22141"},
{"结界守护", "22142"},
{"破地冰钻", "22143"},
{"冰魄漫天", "22144"},
{"冰极对抗", "22145"},
{"海狮冰剑", "22146"},
{"寒冰眩晕", "22147"},
{"寒冰陷阱", "22148"},
{"寒冰棱镜", "22149"},
{"坚固壁垒", "22150"},
{"神偷之手", "22151"},
{"冰雹来袭", "22152"},
{"寒冰术", "22153"},
{"寒冰之敌", "22155"},
{"眩晕吸收", "22156"},
{"寒冰盾", "22157"},
{"寒冰陷阱(小)", "22458"},
{"坚冰形态", "22380"},
},
},
},
category = "Data",
output = {type = "field_number",},
helpUrl = "",
canRun = false,
func_description = '%s',
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
-------------------------------
{
type = "cardFire",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{"火焰爆", "22101"},
{"火神之怒", "22102"},
{"火凤焚天", "22103"},
{"烈火陷阱", "22104"},
{"星火袭空", "22105"},
{"火极对抗", "22106"},
{"火焰喷发", "22107"},
{"火魔掷石", "22108"},
{"烈火术", "22109"},
{"烈火棱镜", "22110"},
{"烈火链", "22111"},
{"偷天换日", "22112"},
{"火狼咆哮", "22113"},
{"灼伤之炎", "22114"},
{"烈火怒吼", "22115"},
{"烟雾", "22116"},
{"烈火眩晕", "22117"},
{"烈火之敌", "22119"},
{"烈火盾", "22120"},
{"火神之怒", "22250"},
{"星火袭空", "22252"},
{"烈火陷阱(小)", "22456"},
{"烈焰形态", "22448"},
},
},
},
category = "Data",
output = {type = "field_number",},
helpUrl = "",
canRun = false,
func_description = '%s',
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
-------------------------------
{
type = "cardLife",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{"生灵光弧", "22158"},
{"灵木刺阵", "22159"},
{"莽林狂舞", "22160"},
{"生生不息", "22161"},
{"吸收盾", "22162"},
{"噬草召唤", "22163"},
{"生机勃发", "22164"},
{"大地之怒", "22165"},
{"生命对抗", "22166"},
{"静水灵体", "22167"},
{"生命庇护", "22168"},
{"生命棱镜", "22169"},
{"生命术", "22170"},
{"生命之礼", "22171"},
{"治疗术", "22172"},
{"生命圣光", "22173"},
{"精灵之舞", "22174"},
{"重生", "22175"},
{"万象凝气", "22176"},
{"万象回春", "22177"},
{"生命陷阱", "22178"},
{"生命之敌", "22179"},
{"生命盾", "22180"},
{"生命陷阱(小)", "22459"},
},
},
},
category = "Data",
output = {type = "field_number",},
helpUrl = "",
canRun = false,
func_description = '%s',
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
-------------------------------
{
type = "cardDeath",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{"暗灵之咒", "22181"},
{"吸血幽灵", "22182"},
{"幽灵突袭", "22183"},
{"回光返照", "22184"},
{"墓地莽石", "22185"},
{"死亡绝", "22186"},
{"死亡对抗", "22187"},
{"蝠王吸魂", "22188"},
{"死亡陷阱", "22189"},
{"死亡术", "22190"},
{"死亡棱镜", "22191"},
{"祭献", "22192"},
{"黑暗诅咒", "22193"},
{"死亡毒", "22194"},
{"群之羁绊", "22195"},
{"死亡群攻", "22196"},
{"死亡巫术", "22197"},
{"死亡之敌", "22198"},
{"死亡盾", "22199"},
{"死亡陷阱(小)", "22460"},
{"魔刃形态", "22451"},
},
},
},
category = "Data",
output = {type = "field_number",},
helpUrl = "",
canRun = false,
func_description = '%s',
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
-------------------------------
{
type = "cardStorm",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{"疾电术", "22121"},
{"金灵遁空", "22122"},
{"暗夜雷动", "22123"},
{"风暴陷阱", "22124"},
{"雷神之剑", "22125"},
{"雷云风暴", "22126"},
{"风暴对抗", "22127"},
{"蛇女雷暴", "22128"},
{"风暴神箭", "22129"},
{"风暴术", "22130"},
{"厉风破运", "22131"},
{"和风逐暗", "22132"},
{"风鹰之眼", "22133"},
{"极限暴熊", "22134"},
{"旋风爆击", "22135"},
{"风暴之敌", "22137"},
{"风暴盾", "22138"},
{"暗夜雷动", "22251"},
{"风暴陷阱(小)", "22457"},
{"狂风形态", "22449"},
},
},
},
category = "Data",
output = {type = "null",},
helpUrl = "",
canRun = false,
func_description = '%s',
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
-------------------------------
{
type = "cardPet",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{"蛇女雷暴", "22255"},
{"强化治疗术", "22256"},
{"强化结界守护", "22257"},
{"咕噜大法", "22258"},
{"火兽袭击", "22259"},
{"土猿猛击", "22260"},
{"铁壳毒物", "22261"},
{"苍蝇穿刺", "22262"},
{"暴怒鬃王", "22263"},
{"连环闪电", "22264"},
{"死亡章鱼", "22265"},
{"凤凰涅磐", "22266"},
{"冰兽发威", "22297"},
{"超能神兔", "22298"},
{"圣灵复活", "22299"},
{"冰刺魂体", "22300"},
{"疾猫霹雳", "22301"},
{"强化风暴陷阱", "22302"},
{"强化烈火陷阱", "22303"},
{"强化死亡陷阱", "22304"},
{"强化生命陷阱", "22305"},
{"帽子戏法", "22306"},
{"强化烈火盾", "22307"},
{"冰魄神柱", "22308"},
{"强化寒冰陷阱", "22309"},
{"埃尔温生命术", "22310"},
{"恶狼袭击", "22311"},
{"亡灵大军", "22312"},
{"群之暗伤", "22313"},
{"烈火盾墙", "22314"},
{"寒冰盾墙", "22315"},
{"风暴盾墙", "22316"},
{"生命盾墙", "22317"},
{"死亡盾墙", "22318"},
{"火魔投石", "22329"},
{"雷神电轮", "22330"},
{"熔岩炸弹", "22331"},
{"冰霜魔镜", "22332"},
{"惊雷裂隙", "22333"},
{"天魔杀星", "22334"},
{"圣灵净化", "22335"},
{"急速点燃", "22336"},
{"冰封神符", "22337"},
{"怒风逆转", "22338"},
{"灵魂契约", "22339"},
{"希望之光", "22340"},
{"瘟神巫术", "22341"},
{"召唤•群之暗伤", "22342"},
{"超魔抑制", "22343"},
{"强化墓地莽石", "22344"},
{"强化烈火怒吼", "22345"},
{"火鬃王暴怒", "22346"},
{"强化海狮冰剑", "22347"},
{"强化厉风破运", "22348"},
{"强化雷神之剑", "22349"},
{"强化大地之怒", "22350"},
{"迅雷闪电", "22351"},
{"幽灵大军", "22352"},
{"暗黑力场", "22353"},
{"强化生命庇护", "22354"},
{"强化生命术", "22355"},
{"蛇后雷暴", "22356"},
{"强化风暴陷阱", "22357"},
{"强化熔岩炸弹", "22358"},
{"强化星火袭空", "22359"},
{"冰兽暴击", "22360"},
{"强化寒冰陷阱", "22361"},
{"烈火魔光", "22362"},
{"风暴魔光", "22363"},
{"寒冰魔光", "22364"},
{"生命魔光", "22365"},
{"死亡魔光", "22366"},
{"[炫彩]噬草召唤", "22367"},
{"[炫彩]灵木刺阵", "22368"},
{"[炫彩]火凤焚天", "22369"},
{"[炫彩]灼伤之炎", "22370"},
{"[炫彩]幽灵突袭", "22371"},
{"[炫彩]回光返照", "22372"},
{"[炫彩]暗夜雷动", "22373"},
{"[炫彩]雷神之剑", "22374"},
{"[炫彩]冰剑凛空", "22375"},
{"[炫彩]破地冰钻", "22376"},
{"超魔爆发", "22377"},
{"愈合", "22378"},
{"地狱爆炎", "22379"},
{"狂风形态", "22449"},
{"烈焰形态", "22448"},
{"光刃形态", "22450"},
{"魔刃形态", "22451"},
{"坚冰形态", "22380"},
{"风影斗篷", "22381"},
{"天使赐福", "22382"},
{"灵魂替身", "22383"},
{"烈阳闪耀", "22384"},
{"叹息冰墙", "22385"},
{"遗忘术", "22386"},
{"天使附灵", "22387"},
{"虚弱之云", "22388"},
{"旋风爆击", "22389"},
{"海狮冰剑", "22390"},
{"火魔掷石", "22391"},
{"天魔杀星", "22392"},
{"大地之怒", "22393"},
{"强化烈火术", "22394"},
{"强化寒冰术", "22395"},
{"强化风暴术", "22396"},
{"强化生命术", "22397"},
{"强化死亡术", "22398"},
{"[炫彩]莽林狂舞", "22399"},
{"群晕吸收", "22400"},
{"熔岩爆", "22401"},
{"冰霜裂", "22402"},
{"疾空破", "22403"},
{"生灵光刃", "22404"},
{"湮灭之咒", "22405"},
{"火神天罚", "22406"},
{"陨落冰山", "22407"},
{"雷鸣遁空", "22408"},
{"荆棘刺尖", "22409"},
{"吸星幽魂", "22410"},
{"强化生机勃发", "22411"},
{"火魔怒吼", "22434"},
{"海狮冰锥", "22435"},
{"狂风暴击", "22436"},
{"巨岩之怒", "22437"},
{"恶灵夺魂", "22438"},
{"烈火反转", "22461"},
{"风暴反转", "22462"},
{"寒冰反转", "22463"},
{"生命反转", "22464"},
{"死亡反转", "22465"},
{"超魔祝福", "22466"},
{"潘多拉盾墙守护", "22467"},
{"梦龙脉冲", "22468"},
{"梦龙之光", "22469"},
{"梦龙极光", "22470"},
},
},
},
category = "Data",
output = {type = "field_number",},
helpUrl = "",
canRun = false,
func_description = '%s',
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
-------------------------------
{
type = "cardEquipment",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{"能量脉冲", "22442"},
{"超能脉冲", "22443"},
{"脉冲奥义", "22444"},
{"潘多拉结界守护", "22445"},
{"潘多拉结界守护", "22446"},
{"潘多拉结界守护", "22447"},
},
},
},
category = "Data",
output = {type = "field_number",},
helpUrl = "",
canRun = false,
func_description = '%s',
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
-------------------------------
{
type = "cardBattleField",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{"愈合MAX", "22452"},
{"弑神脉冲", "22453"},
{"先发制人", "22454"},
{"狰狞", "22455"},
},
},
},
category = "Data",
output = {type = "field_number",},
helpUrl = "",
canRun = false,
func_description = '%s',
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
-------------------------------
{
type = "cardRune",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{"火焰爆", "23101"},
{"火神之怒", "23102"},
{"火凤焚天", "23103"},
{"烈火陷阱", "23104"},
{"星火袭空", "23105"},
{"火极对抗", "23106"},
{"火焰喷发", "23107"},
{"火魔掷石", "23108"},
{"烈火术", "23109"},
{"烈火棱镜", "23110"},
{"烈火链", "23111"},
{"偷天换日", "23112"},
{"火狼咆哮", "23113"},
{"灼伤之炎", "23114"},
{"烈火怒吼", "23115"},
{"烟雾", "23116"},
{"烈火眩晕", "23117"},
{"烈火之敌", "23119"},
{"烈火盾", "23120"},
{"疾电术", "23121"},
{"金灵遁空", "23122"},
{"暗夜雷动", "23123"},
{"风暴陷阱", "23124"},
{"雷神之剑", "23125"},
{"雷云风暴", "23126"},
{"风暴对抗", "23127"},
{"蛇女雷暴", "23128"},
{"风暴神箭", "23129"},
{"风暴术", "23130"},
{"厉风破运", "23131"},
{"和风逐暗", "23132"},
{"风鹰之眼", "23133"},
{"极限暴熊", "23134"},
{"旋风爆击", "23135"},
{"风暴攻7", "23136"},
{"风暴之敌", "23137"},
{"风暴盾", "23138"},
{"冰霜破", "23139"},
{"陨落冰石", "23140"},
{"冰剑凛空", "23141"},
{"结界守护", "23142"},
{"破地冰钻", "23143"},
{"冰魄漫天", "23144"},
{"冰极对抗", "23145"},
{"海狮冰剑", "23146"},
{"寒冰眩晕", "23147"},
{"寒冰陷阱", "23148"},
{"寒冰棱镜", "23149"},
{"坚固壁垒", "23150"},
{"神偷之手", "23151"},
{"冰雹来袭", "23152"},
{"寒冰术", "23153"},
{"寒冰之敌", "23155"},
{"眩晕吸收", "23156"},
{"寒冰盾", "23157"},
{"生灵光弧", "23158"},
{"灵木刺阵", "23159"},
{"莽林狂舞", "23160"},
{"生生不息", "23161"},
{"吸收盾", "23162"},
{"噬草召唤", "23163"},
{"生机勃发", "23164"},
{"大地之怒", "23165"},
{"生命对抗", "23166"},
{"静水灵体", "23167"},
{"生命庇护", "23168"},
{"生命棱镜", "23169"},
{"生命术", "23170"},
{"生命之礼", "23171"},
{"治疗术", "23172"},
{"生命圣光", "23173"},
{"精灵之舞", "23174"},
{"重生", "23175"},
{"万象凝气", "23176"},
{"万象回春", "23177"},
{"生命陷阱", "23178"},
{"生命之敌", "23179"},
{"生命盾", "23180"},
{"暗灵之咒", "23181"},
{"吸血幽灵", "23182"},
{"幽灵突袭", "23183"},
{"回光返照", "23184"},
{"墓地莽石", "23185"},
{"死亡绝", "23186"},
{"死亡对抗", "23187"},
{"蝠王吸魂", "23188"},
{"死亡陷阱", "23189"},
{"死亡术", "23190"},
{"死亡棱镜", "23191"},
{"祭献", "23192"},
{"黑暗诅咒", "23193"},
{"死亡毒", "23194"},
{"群之羁绊", "23195"},
{"死亡群攻", "23196"},
{"死亡巫术", "23197"},
{"死亡之敌", "23198"},
{"死亡盾", "23199"},
{"火神之怒", "23250"},
{"暗夜雷动", "23251"},
{"星火袭空", "23252"},
{"火攻5", "23253"},
{"风暴攻5", "23254"},
{"蛇女雷暴", "23255"},
{"强化治疗术", "23256"},
{"强化结界守护", "23257"},
{"咕噜大法", "23258"},
{"火兽袭击", "23259"},
{"土猿猛击", "23260"},
{"铁壳毒物", "23261"},
{"苍蝇穿刺", "23262"},
{"暴怒鬃王", "23263"},
{"连环闪电", "23264"},
{"死亡章鱼", "23265"},
{"凤凰涅磐", "23266"},
{"冰兽发威", "23297"},
{"超能神兔", "23298"},
{"圣灵复活", "23299"},
{"冰刺魂体", "23300"},
{"疾猫霹雳", "23301"},
{"强化风暴陷阱", "23302"},
{"强化烈火陷阱", "23303"},
{"强化死亡陷阱", "23304"},
{"强化生命陷阱", "23305"},
{"帽子戏法", "23306"},
{"强化烈火盾", "23307"},
{"冰魄神柱", "23308"},
{"强化寒冰陷阱", "23309"},
{"埃尔温生命术", "23310"},
{"恶狼袭击", "23311"},
{"亡灵大军", "23312"},
{"群之暗伤符文_屏蔽", "23313"},
{"烈火盾墙符文", "23314"},
{"寒冰盾墙符文", "23315"},
{"风暴盾墙符文", "23316"},
{"生命盾墙符文", "23317"},
{"死亡盾墙符文", "23318"},
{"烈火群击符文", "23319"},
{"寒冰群击符文", "23320"},
{"风暴群击符文", "23321"},
{"生命群击符文", "23322"},
{"死亡群击符文", "23323"},
{"烈火专注", "23324"},
{"寒冰专注", "23325"},
{"风暴专注", "23326"},
{"生命专注", "23327"},
{"死亡专注", "23328"},
{"急速点燃符文", "23336"},
{"冰封神符符文", "23337"},
{"怒风逆转符文", "23338"},
{"灵魂契约符文", "23339"},
{"希望之光符文", "23340"},
{"瘟神巫术符文", "23341"},
{"群之暗伤符文", "23342"},
{"超魔抑制符文", "23343"},
{"首领激怒符文卡", "23344"},
{"闪卡_噬草召唤符文", "23367"},
{"超魔爆发符文", "23377"},
{"愈合符文", "23378"},
{"地狱爆炎符文", "23379"},
{"坚冰形态符文", "23380"},
{"风影斗篷符文", "23381"},
{"天使赐福符文", "23382"},
{"灵魂替身符文", "23383"},
{"烈阳闪耀符文", "23384"},
{"叹息冰墙符文", "23385"},
{"遗忘术符文", "23386"},
{"天使附灵符文", "23387"},
{"虚弱之云符文", "23388"},
{"强化烈火术", "23394"},
{"强化寒冰术", "23395"},
{"强化风暴术", "23396"},
{"强化生命术", "23397"},
{"强化死亡术", "23398"},
{"[炫彩]莽林狂舞符文", "23399"},
{"群晕吸收符文", "23400"},
{"烈火群击符文(绑定)", "23411"},
{"寒冰群击符文(绑定)", "23412"},
{"风暴群击符文(绑定)", "23413"},
{"生命群击符文(绑定)", "23414"},
{"死亡群击符文(绑定)", "23415"},
{"烈火盾墙符文(绑定)", "23416"},
{"寒冰盾墙符文(绑定)", "23417"},
{"风暴盾墙符文(绑定)", "23418"},
{"生命盾墙符文(绑定)", "23419"},
{"死亡盾墙符文(绑定)", "23420"},
{"1级激怒符文卡", "23421"},
{"2级激怒符文卡", "23422"},
{"3级激怒符文卡", "23423"},
{"4级激怒符文卡", "23424"},
{"5级激怒符文卡", "23425"},
{"6级激怒符文卡", "23426"},
{"7级激怒符文卡", "23427"},
{"8级激怒符文卡", "23428"},
{"9级激怒符文卡", "23429"},
{"10级激怒符文卡", "23430"},
{"传说级激怒符文卡(1~3级)", "23431"},
{"传说级激怒符文卡(4~7级)", "23432"},
{"传说级激怒符文卡(8~10级)", "23433"},
{"火魔怒吼", "23434"},
{"海狮冰锥", "23435"},
{"狂风暴击", "23436"},
{"巨岩之怒", "23437"},
{"恶灵夺魂", "23438"},
{"普通抓宠符文", "23439"},
{"高级抓宠符文", "23440"},
{"顶级抓宠符文", "23441"},
{"能量脉冲符文", "23442"},
{"超能脉冲符文", "23443"},
{"脉冲奥义符文", "23444"},
{"潘多拉结界守护", "23445"},
{"潘多拉结界守护", "23446"},
{"潘多拉结界守护", "23447"},
{"烈焰形态符文", "23448"},
{"狂风形态符文", "23449"},
{"光刃形态符文", "23450"},
{"魔刃形态符文", "23451"},
{"愈合MAX符文", "23452"},
{"弑神脉冲符文", "23453"},
{"先发制人符文", "23454"},
{"狰狞符文", "23455"},
{"烈火陷阱(小)", "23456"},
{"风暴陷阱(小)", "23457"},
{"寒冰陷阱(小)", "23458"},
{"生命陷阱(小)", "23459"},
{"死亡陷阱(小)", "23460"},
{"烈火反转", "23461"},
{"风暴反转", "23462"},
{"寒冰反转", "23463"},
{"生命反转", "23464"},
{"死亡反转", "23465"},
{"超魔祝福符文", "23466"},
{"潘多拉盾墙守护符文", "23467"},
{"梦龙脉冲符文", "23468"},
{"梦龙之光符文", "23469"},
{"梦龙极光符文", "23470"},
},
},
},
category = "Data",
output = {type = "field_number",},
helpUrl = "",
canRun = false,
func_description = '%s',
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
});
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Movie/ActorBlock.lua | 1 | 5784 | --[[
Title: block actor
Author(s): LiXizhi
Date: 2014/4/17
Desc: for recording and playing back of block creation and deletion.
This is different from ActorBlocks, in that it will record one creation or deletion action per keyframe.
This class is thus used by ActorNPC for block creation and deletion playback.
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/ActorBlocks.lua");
local actor = commonlib.gettable("MyCompany.Aries.Game.Movie.ActorBlock");
-------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/Actor.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/SelectBlocksTask.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Common/TimeSeries.lua");
local TimeSeries = commonlib.gettable("MyCompany.Aries.Game.Common.TimeSeries");
local SelectBlocks = commonlib.gettable("MyCompany.Aries.Game.Tasks.SelectBlocks")
local SlashCommand = commonlib.gettable("MyCompany.Aries.SlashCommand.SlashCommand");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local Actor = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Movie.Actor"), commonlib.gettable("MyCompany.Aries.Game.Movie.ActorBlock"));
function Actor:ctor()
-- this is precalculated temporary data set.
self.TimeSeries_blocks = TimeSeries:new{name = "Actor",};
self.blocks = self.TimeSeries_blocks:CreateVariableIfNotExist("blocks", "Discrete");
end
function Actor:Init(itemStack, movieclipEntity, movieclip)
if(not Actor._super.Init(self, itemStack, movieclipEntity, movieclip)) then
return;
end
local timeseries = self.TimeSeries;
timeseries:CreateVariableIfNotExist("block", "Discrete");
self:InitializeTimeSeries();
return self;
end
-- remove all blocks
function Actor:OnRemove()
local blocks = self.blocks:getValue(1, 0);
if(blocks) then
for sparse_index, b in pairs(blocks) do
if(b[1]) then
BlockEngine:SetBlock(b[1], b[2], b[3], b[4], b[5]);
end
end
end
end
-- update block set in block time series variable as well as the given new_blocks
-- precalculate time series
function Actor:InitializeTimeSeries()
local v = self:GetVariable("block");
local block_set = {};
local block_set_time0 = {};
for i, blocks in ipairs(v.data) do
for sparse_index, b in pairs(blocks) do
if(not block_set[sparse_index]) then
block_set[sparse_index] = b;
local x,y,z = b[1], b[2], b[3];
block_set_time0[sparse_index] = {x,y,z, BlockEngine:GetBlockId(x,y,z), BlockEngine:GetBlockData(x,y,z)}
end
end
end
self.blocks:TrimEnd(0);
self.blocks:AutoAppendKey(0, block_set_time0, true);
local last_block_set = block_set_time0;
for i, blocks in ipairs(v.data) do
local cur_set = commonlib.copy(last_block_set);
for sparse_index, b in pairs(blocks) do
cur_set[sparse_index] = b;
end
local time = v.times[i];
self.blocks:AutoAppendKey(time, cur_set, true);
last_block_set = cur_set;
end
end
-- clear all record to a given time. if curTime is nil, it will use the current time.
function Actor:ClearRecordToTime(curTime)
Actor._super.ClearRecordToTime(self, curTime);
self.blocks:TrimEnd(curTime);
end
-- add movie blocks at the current time.
-- @param blocks: {{x,y,z,block_id, block_data, last_block_id = number, last_block_data = number, }, ...}
function Actor:AddKeyFrameOfBlocks(new_blocks)
if(new_blocks) then
local curTime = self:GetTime();
local last_blocks = self.blocks:getValue(1, curTime);
if(not last_blocks) then
last_blocks = {};
self.blocks:AutoAppendKey(0, last_blocks, true);
end
local blocks = {};
for _, b in ipairs(new_blocks) do
-- {x,y,z,block_id, block_data}
local x,y,z = b[1], b[2], b[3];
if(x and y and z) then
local sparse_index = BlockEngine:GetSparseIndex(x,y,z);
blocks[sparse_index] = {x,y,z, b[4], b[5]};
local last_block_id = b.last_block_id or BlockEngine:GetBlockId(x,y,z);
local last_block_data = b.last_block_data or BlockEngine:GetBlockData(x,y,z);
if(not last_blocks[sparse_index]) then
for i, blocks in ipairs(self.blocks.data) do
blocks[sparse_index] = {x,y,z, last_block_id, last_block_data};
end
end
end
end
if(next(blocks)) then
self:AddKeyFrameByName("block", curTime, blocks);
local cur_set = commonlib.copy(last_blocks);
for sparse_index, b in pairs(blocks) do
cur_set[sparse_index] = b;
end
self.blocks:AutoAppendKey(curTime, cur_set, true);
end
end
end
-- @param blocks: update blocks.
function Actor:UpdateBlocks(blocks, curTime)
if(blocks) then
local block_pieces_count = 0;
for sparse_index, b in pairs(blocks) do
local x,y,z = b[1], b[2], b[3];
local cur_block_id = BlockEngine:GetBlockId(x,y,z);
local new_block_id = b[4];
if( cur_block_id ~= new_block_id) then
if(new_block_id == 0) then
BlockEngine:SetBlockToAir(x,y,z);
block_pieces_count = block_pieces_count + 1;
if(block_pieces_count <= 27) then
-- create some block pieces
local block_template = block_types.get(cur_block_id);
if(block_template) then
block_template:CreateBlockPieces(x,y,z);
end
end
else
BlockEngine:SetBlock(x,y,z, new_block_id, b[5]);
end
end
end
end
end
function Actor:FrameMovePlaying(deltaTime)
local curTime = self:GetTime();
if(not curTime) then
return
end
local blocks = self.blocks:getValue2(1, curTime);
if(self.last_blocks ~= blocks) then
self.last_blocks = blocks;
self:UpdateBlocks(blocks);
end
end
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/RuAun_Gardens/Zone.lua | 1 | 1120 | -----------------------------------
--
-- Zone: RuAun_Gardens
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Port_Windurst/npcs/Three_of_Clubs.lua | 5 | 1038 | -----------------------------------
-- Area: Port Windurst
-- NPC: Three of Clubs
-- Type: Standard NPC
-- @zone: 240
-- @pos: -7.238 -5 106.982
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00de);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Areas/BuilderDock.lua | 1 | 5385 | --[[
Title: The dock page
Author(s): LiXizhi
Date: 2012/12/28
Desc:
There dock has 2 mode: one for editor and one for creator
Use Lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/BuilderDock.lua");
local BuilderDock = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.BuilderDock");
BuilderDock.ShowPage(true)
-------------------------------------------------------
]]
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic");
local Desktop = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop");
local BuilderDock = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.BuilderDock");
function BuilderDock.OnInit()
BuilderDock.RegisterCmds();
end
function BuilderDock.ShowPage(bShow)
if(not GameLogic.GameMode:CanShowDock()) then
return
end
if(bShow==false) then
BuilderDock.HideAllWindows()
end
System.App.Commands.Call("File.MCMLWindowFrame", {
url = "script/apps/Aries/Creator/Game/Areas/BuilderDock.html",
name = "BuilderDock.ShowPage",
isShowTitleBar = false,
DestroyOnClose = false,
style = CommonCtrl.WindowFrame.ContainerStyle,
app_key = Desktop.App.app_key,
--allowDrag = true,
bShow = bShow,
zorder = -5,
directPosition = true,
align = "_rb",
x = -260,
y = -66,
width = 240,
height = 60,
});
end
function BuilderDock.RegisterCmds()
if(not BuilderDock.cmds)then
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/NatureBuilder.lua");
local NatureBuilder = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.NatureBuilder");
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/StaticBlockBuilder.lua");
local StaticBlockBuilder = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.StaticBlockBuilder");
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/SpecialBlockBuilder.lua");
local SpecialBlockBuilder = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.SpecialBlockBuilder");
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/DecoBuilder.lua");
local DecoBuilder = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.DecoBuilder");
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/TaskBuilder.lua");
local TaskBuilder = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.TaskBuilder");
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/CreatorDesktop.lua");
local CreatorDesktop = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.CreatorDesktop");
BuilderDock.cmds = {
["nature"] = { wndName = "NatureBuilder.ShowPage", show_func = NatureBuilder.ShowPage, },
-- ["static_blocks"] = { wndName = "StaticBlockBuilder.ShowPage", show_func = StaticBlockBuilder.ShowPage, },
["creator_desktop"] = { wndName = "CreatorDesktop.ShowPage", show_func = function()
GameLogic.ToggleDesktop("builder");
end, },
["special_blocks"] = { wndName = "SpecialBlockBuilder.ShowPage", show_func = SpecialBlockBuilder.ShowPage, },
["deco"] = { wndName = "DecoBuilder.ShowPage", show_func = DecoBuilder.ShowPage, },
["task"] = { wndName = "TaskBuilder.ShowPage", show_func = TaskBuilder.ShowPage, },
["system"] = { wndName = "SystemMenuPage.ShowPage", show_func = function()
GameLogic.ToggleDesktop("esc");
end, },
}
end
end
function BuilderDock.FireCmd(cmd,...)
if(not cmd)then return end
if(BuilderDock.last_cmd and BuilderDock.last_cmd ~= cmd)then
local node = BuilderDock.cmds[BuilderDock.last_cmd];
local wndName = node.wndName or "";
Map3DSystem.App.Commands.Call("File.MCMLWindowFrame", {name = wndName, app_key=Desktop.App.app_key, bShow = false,}); -- bDestroy = true,
end
BuilderDock.__FireCmd(cmd,...);
BuilderDock.last_cmd = cmd;
end
function BuilderDock.__FireCmd(cmd,...)
if(not cmd)then return end
local node = BuilderDock.cmds[cmd];
local wndName = node.wndName or "";
local _wnd = BuilderDock.FindWindow(wndName);
if(_wnd)then
if(_wnd:IsVisible())then
Map3DSystem.App.Commands.Call("File.MCMLWindowFrame", {name = wndName, app_key=Desktop.App.app_key, bShow = false,}); -- bDestroy = true,
else
if(node and node.show_func)then
if(node.show_params) then
node.show_func(unpack(node.show_params));
else
node.show_func(...);
end
end
end
else
if(node and node.show_func)then
if(node.show_params) then
node.show_func(unpack(node.show_params));
else
node.show_func(...);
end
end
end
end
function BuilderDock.WindowIsShow()
if(BuilderDock.cmds)then
local k,v;
for k,v in pairs(BuilderDock.cmds) do
local wndName = v.wndName;
local _wnd = BuilderDock.FindWindow(wndName);
if(_wnd)then
if(_wnd:IsVisible())then
return true;
end
end
end
end
end
function BuilderDock.HideAllWindows()
if(BuilderDock.cmds)then
local k,v;
for k,v in pairs(BuilderDock.cmds) do
local wndName = v.wndName;
local _wnd = BuilderDock.FindWindow(wndName);
if(_wnd)then
if(_wnd:IsVisible())then
Map3DSystem.App.Commands.Call("File.MCMLWindowFrame", {name = wndName, app_key=Desktop.App.app_key, bShow = false,}); -- bDestroy = true,
end
end
end
end
end
function BuilderDock.FindWindow(wndName)
if(not wndName)then return end
if(Desktop.App) then
local _wnd = Desktop.App:FindWindow(wndName);
return _wnd;
end
end
function BuilderDock.OnToggleBuilder(name)
BuilderDock.FireCmd(name);
end
| gpl-2.0 |
Aminrezaa/megareborn | plugins/groupmanager.lua | 2 | 111852 | local function modadd(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
if not lang then
return '_#شما مدیر ربات نمیباشید!🍃_'
else
return '#شما مدیر ربات نمیباشید!🍃'
end
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not lang then
return '_#ربات بدون هیچ مشکلی فعال شد!🍃_'
else
return '#ربات در لیست مدیریتی موجود می باشد!🍃'
end
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
owners = {},
mods ={},
banned ={},
is_silent_users ={},
filterlist ={},
settings = {
set_name = msg.to.title,
lock_link = 'yes',
lock_tag = 'yes',
lock_spam = 'yes',
lock_webpage = 'no',
lock_markdown = 'no',
flood = 'yes',
lock_bots = 'yes',
lock_pin = 'no',
welcome = 'no',
},
mutes = {
mute_fwd = 'no',
mute_audio = 'no',
mute_video = 'no',
mute_contact = 'no',
mute_text = 'no',
mute_photos = 'no',
mute_gif = 'no',
mute_loc = 'no',
mute_doc = 'no',
mute_sticker = 'no',
mute_voice = 'no',
mute_all = 'no',
mute_keyboard = 'no'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
if not lang then
return '*#ربات بدون هیچ مشکلی فعال شد!🍃*'
else
return 'گروه با موفقیت به لیست گروه های مدیریتی ربات افزوده شد'
end
end
local function modrem(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
if not lang then
return '_#شما مدیر ربات reborn نمیباشید!🍃_'
else
return '#شما مدیر ربات reborn نمیباشید!🍃'
end
end
local data = load_data(_config.moderation.data)
local receiver = msg.to.id
if not data[tostring(msg.to.id)] then
if not lang then
return '_Group is not added_'
else
return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است'
end
end
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
if not lang then
return '*#گروه دیگر توسط reborn ساپورت نمیشود!🍃*'
else
return '#گروه دیگر توسط reborn ساپورت نمیشود!🍃'
end
end
local function filter_word(msg, word)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)]['filterlist'] then
data[tostring(msg.to.id)]['filterlist'] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(msg.to.id)]['filterlist'][(word)] then
if not lang then
return "_Word_ *"..word.."* _is already filtered_"
else
return "_کلمه_ *"..word.."* _از قبل فیلتر بود_"
end
end
data[tostring(msg.to.id)]['filterlist'][(word)] = true
save_data(_config.moderation.data, data)
if not lang then
return "_Word_ *"..word.."* _added to filtered words list_"
else
return "_کلمه_ *"..word.."* _به لیست کلمات فیلتر شده اضافه شد_"
end
end
local function unfilter_word(msg, word)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)]['filterlist'] then
data[tostring(msg.to.id)]['filterlist'] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(msg.to.id)]['filterlist'][word] then
data[tostring(msg.to.id)]['filterlist'][(word)] = nil
save_data(_config.moderation.data, data)
if not lang then
return "_Word_ *"..word.."* _removed from filtered words list_"
elseif lang then
return "_کلمه_ *"..word.."* _از لیست کلمات فیلتر شده حذف شد_"
end
else
if not lang then
return "_Word_ *"..word.."* _is not filtered_"
elseif lang then
return "_کلمه_ *"..word.."* _از قبل فیلتر نبود_"
end
end
end
local function modlist(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local i = 1
if not data[tostring(msg.chat_id_)] then
if not lang then
return "_Group is not added_"
else
return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است"
end
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['mods']) == nil then --fix way
if not lang then
return "_No_ *moderator* _in this group_"
else
return "در حال حاضر هیچ مدیری برای گروه انتخاب نشده است"
end
end
if not lang then
message = '*List of moderators :*\n'
else
message = '*لیست مدیران گروه :*\n'
end
for k,v in pairs(data[tostring(msg.to.id)]['mods'])
do
message = message ..i.. '- '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function ownerlist(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local i = 1
if not data[tostring(msg.to.id)] then
if not lang then
return "_Group is not added_"
else
return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است"
end
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['owners']) == nil then --fix way
if not lang then
return "_No_ *owner* _in this group_"
else
return "در حال حاضر هیچ مالکی برای گروه انتخاب نشده است"
end
end
if not lang then
message = '*List of moderators :*\n'
else
message = '*لیست مالکین گروه :*\n'
end
for k,v in pairs(data[tostring(msg.to.id)]['owners']) do
message = message ..i.. '- '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function action_by_reply(arg, data)
local hash = "gp_lang:"..data.chat_id_
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not tonumber(data.sender_user_id_) then return false end
if data.sender_user_id_ then
if not administration[tostring(data.chat_id_)] then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md")
end
end
if cmd == "setowner" then
local function owner_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "promote" then
local function promote_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, promote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "remowner" then
local function rem_owner_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, rem_owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "demote" then
local function demote_cb(arg, data)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, demote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "id" then
local function id_cb(arg, data)
return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md")
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, id_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
else
if lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_username(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not administration[tostring(arg.chat_id)] then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md")
end
end
if not arg.username then return false end
if data.id_ then
if data.type_.user_.username_ then
user_name = '@'..check_markdown(data.type_.user_.username_)
else
user_name = check_markdown(data.title_)
end
if cmd == "setowner" then
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md")
end
end
if cmd == "promote" then
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md")
end
end
if cmd == "remowner" then
if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md")
end
end
if cmd == "demote" then
if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md")
end
end
if cmd == "id" then
return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md")
end
if cmd == "res" then
if not lang then
text = "Result for [ "..check_markdown(data.type_.user_.username_).." ] :\n"
.. ""..check_markdown(data.title_).."\n"
.. " ["..data.id_.."]"
else
text = "اطلاعات برای [ "..check_markdown(data.type_.user_.username_).." ] :\n"
.. "".. check_markdown(data.title_) .."\n"
.. " [".. data.id_ .."]"
end
return tdcli.sendMessage(arg.chat_id, 0, 1, text, 1, 'md')
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_id(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not administration[tostring(arg.chat_id)] then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md")
end
end
if not tonumber(arg.user_id) then return false end
if data.id_ then
if data.first_name_ then
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if cmd == "setowner" then
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md")
end
end
if cmd == "promote" then
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md")
end
end
if cmd == "remowner" then
if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md")
end
end
if cmd == "demote" then
if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md")
end
end
if cmd == "whois" then
if data.username_ then
username = '@'..check_markdown(data.username_)
else
if not lang then
username = 'not found'
else
username = 'ندارد'
end
end
if not lang then
return tdcli.sendMessage(arg.chat_id, 0, 1, 'Info for [ '..data.id_..' ] :\nUserName : '..username..'\nName : '..data.first_name_, 1)
else
return tdcli.sendMessage(arg.chat_id, 0, 1, 'اطلاعات برای [ '..data.id_..' ] :\nیوزرنیم : '..username..'\nنام : '..data.first_name_, 1)
end
end
else
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User not founded_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
end
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
---------------Lock Link-------------------
local function lock_link(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_link = data[tostring(target)]["settings"]["lock_link"]
if lock_link == "yes" then
if not lang then
return "*Link* _Posting Is Already Locked_"
elseif lang then
return "ارسال لینک در گروه هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_link"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Link* _Posting Has Been Locked_"
else
return "ارسال لینک در گروه ممنوع شد"
end
end
end
local function unlock_link(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_link = data[tostring(target)]["settings"]["lock_link"]
if lock_link == "no" then
if not lang then
return "*Link* _Posting Is Not Locked_"
elseif lang then
return "ارسال لینک در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["lock_link"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "*Link* _Posting Has Been Unlocked_"
else
return "ارسال لینک در گروه آزاد شد"
end
end
end
---------------Lock Tag-------------------
local function lock_tag(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_tag = data[tostring(target)]["settings"]["lock_tag"]
if lock_tag == "yes" then
if not lang then
return "*Tag* _Posting Is Already Locked_"
elseif lang then
return "ارسال تگ در گروه هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_tag"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Tag* _Posting Has Been Locked_"
else
return "ارسال تگ در گروه ممنوع شد"
end
end
end
local function unlock_tag(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_tag = data[tostring(target)]["settings"]["lock_tag"]
if lock_tag == "no" then
if not lang then
return "*Tag* _Posting Is Not Locked_"
elseif lang then
return "ارسال تگ در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["lock_tag"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "*Tag* _Posting Has Been Unlocked_"
else
return "ارسال تگ در گروه آزاد شد"
end
end
end
---------------Lock Mention-------------------
local function lock_mention(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_mention = data[tostring(target)]["settings"]["lock_mention"]
if lock_mention == "yes" then
if not lang then
return "*Mention* _Posting Is Already Locked_"
elseif lang then
return "ارسال فراخوانی افراد هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_mention"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mention* _Posting Has Been Locked_"
else
return "ارسال فراخوانی افراد در گروه ممنوع شد"
end
end
end
local function unlock_mention(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_mention = data[tostring(target)]["settings"]["lock_mention"]
if lock_mention == "no" then
if not lang then
return "*Mention* _Posting Is Not Locked_"
elseif lang then
return "ارسال فراخوانی افراد در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["lock_mention"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "*Mention* _Posting Has Been Unlocked_"
else
return "ارسال فراخوانی افراد در گروه آزاد شد"
end
end
end
---------------Lock Arabic--------------
local function lock_arabic(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"]
if lock_arabic == "yes" then
if not lang then
return "*Arabic/Persian* _Posting Is Already Locked_"
elseif lang then
return "ارسال کلمات عربی/فارسی در گروه هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_arabic"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Arabic/Persian* _Posting Has Been Locked_"
else
return "ارسال کلمات عربی/فارسی در گروه ممنوع شد"
end
end
end
local function unlock_arabic(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"]
if lock_arabic == "no" then
if not lang then
return "*Arabic/Persian* _Posting Is Not Locked_"
elseif lang then
return "ارسال کلمات عربی/فارسی در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["lock_arabic"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "*Arabic/Persian* _Posting Has Been Unlocked_"
else
return "ارسال کلمات عربی/فارسی در گروه آزاد شد"
end
end
end
---------------Lock Edit-------------------
local function lock_edit(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_edit = data[tostring(target)]["settings"]["lock_edit"]
if lock_edit == "yes" then
if not lang then
return "*Editing* _Is Already Locked_"
elseif lang then
return "ویرایش پیام هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_edit"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Editing* _Has Been Locked_"
else
return "ویرایش پیام در گروه ممنوع شد"
end
end
end
local function unlock_edit(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_edit = data[tostring(target)]["settings"]["lock_edit"]
if lock_edit == "no" then
if not lang then
return "*Editing* _Is Not Locked_"
elseif lang then
return "ویرایش پیام در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["lock_edit"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "*Editing* _Has Been Unlocked_"
else
return "ویرایش پیام در گروه آزاد شد"
end
end
end
---------------Lock spam-------------------
local function lock_spam(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_spam = data[tostring(target)]["settings"]["lock_spam"]
if lock_spam == "yes" then
if not lang then
return "*Spam* _Is Already Locked_"
elseif lang then
return "ارسال هرزنامه در گروه هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_spam"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Spam* _Has Been Locked_"
else
return "ارسال هرزنامه در گروه ممنوع شد"
end
end
end
local function unlock_spam(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_spam = data[tostring(target)]["settings"]["lock_spam"]
if lock_spam == "no" then
if not lang then
return "*Spam* _Posting Is Not Locked_"
elseif lang then
return "ارسال هرزنامه در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["lock_spam"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Spam* _Posting Has Been Unlocked_"
else
return "ارسال هرزنامه در گروه آزاد شد"
end
end
end
---------------Lock Flood-------------------
local function lock_flood(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_flood = data[tostring(target)]["settings"]["flood"]
if lock_flood == "yes" then
if not lang then
return "*Flooding* _Is Already Locked_"
elseif lang then
return "ارسال پیام مکرر در گروه هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["flood"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Flooding* _Has Been Locked_"
else
return "ارسال پیام مکرر در گروه ممنوع شد"
end
end
end
local function unlock_flood(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_flood = data[tostring(target)]["settings"]["flood"]
if lock_flood == "no" then
if not lang then
return "*Flooding* _Is Not Locked_"
elseif lang then
return "ارسال پیام مکرر در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["flood"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "*Flooding* _Has Been Unlocked_"
else
return "ارسال پیام مکرر در گروه آزاد شد"
end
end
end
---------------Lock Bots-------------------
local function lock_bots(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_bots = data[tostring(target)]["settings"]["lock_bots"]
if lock_bots == "yes" then
if not lang then
return "*Bots* _Protection Is Already Enabled_"
elseif lang then
return "محافظت از گروه در برابر ربات ها هم اکنون فعال است"
end
else
data[tostring(target)]["settings"]["lock_bots"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Bots* _Protection Has Been Enabled_"
else
return "محافظت از گروه در برابر ربات ها فعال شد"
end
end
end
local function unlock_bots(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_bots = data[tostring(target)]["settings"]["lock_bots"]
if lock_bots == "no" then
if not lang then
return "*Bots* _Protection Is Not Enabled_"
elseif lang then
return "محافظت از گروه در برابر ربات ها غیر فعال است"
end
else
data[tostring(target)]["settings"]["lock_bots"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "*Bots* _Protection Has Been Disabled_"
else
return "محافظت از گروه در برابر ربات ها غیر فعال شد"
end
end
end
---------------Lock Markdown-------------------
local function lock_markdown(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"]
if lock_markdown == "yes" then
if not lang then
return "*Markdown* _Posting Is Already Locked_"
elseif lang then
return "ارسال پیام های دارای فونت در گروه هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_markdown"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Markdown* _Posting Has Been Locked_"
else
return "ارسال پیام های دارای فونت در گروه ممنوع شد"
end
end
end
local function unlock_markdown(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"]
if lock_markdown == "no" then
if not lang then
return "*Markdown* _Posting Is Not Locked_"
elseif lang then
return "ارسال پیام های دارای فونت در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["lock_markdown"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "*Markdown* _Posting Has Been Unlocked_"
else
return "ارسال پیام های دارای فونت در گروه آزاد شد"
end
end
end
---------------Lock Webpage-------------------
local function lock_webpage(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"]
if lock_webpage == "yes" then
if not lang then
return "*Webpage* _Is Already Locked_"
elseif lang then
return "ارسال صفحات وب در گروه هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_webpage"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Webpage* _Has Been Locked_"
else
return "ارسال صفحات وب در گروه ممنوع شد"
end
end
end
local function unlock_webpage(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"]
if lock_webpage == "no" then
if not lang then
return "*Webpage* _Is Not Locked_"
elseif lang then
return "ارسال صفحات وب در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["lock_webpage"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Webpage* _Has Been Unlocked_"
else
return "ارسال صفحات وب در گروه آزاد شد"
end
end
end
---------------Lock Pin-------------------
local function lock_pin(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_pin = data[tostring(target)]["settings"]["lock_pin"]
if lock_pin == "yes" then
if not lang then
return "*Pinned Message* _Is Already Locked_"
elseif lang then
return "سنجاق کردن پیام در گروه هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_pin"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Pinned Message* _Has Been Locked_"
else
return "سنجاق کردن پیام در گروه ممنوع شد"
end
end
end
local function unlock_pin(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_pin = data[tostring(target)]["settings"]["lock_pin"]
if lock_pin == "no" then
if not lang then
return "*Pinned Message* _Is Not Locked_"
elseif lang then
return "سنجاق کردن پیام در گروه ممنوع نمیباشد"
end
else
data[tostring(target)]["settings"]["lock_pin"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Pinned Message* _Has Been Unlocked_"
else
return "سنجاق کردن پیام در گروه آزاد شد"
end
end
end
function group_settings(msg, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local data = load_data(_config.moderation.data)
local target = msg.to.id
if data[tostring(target)] then
if data[tostring(target)]["settings"]["num_msg_max"] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['num_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_link"] then
data[tostring(target)]["settings"]["lock_link"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_tag"] then
data[tostring(target)]["settings"]["lock_tag"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_mention"] then
data[tostring(target)]["settings"]["lock_mention"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_arabic"] then
data[tostring(target)]["settings"]["lock_arabic"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_edit"] then
data[tostring(target)]["settings"]["lock_edit"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_spam"] then
data[tostring(target)]["settings"]["lock_spam"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_flood"] then
data[tostring(target)]["settings"]["lock_flood"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_bots"] then
data[tostring(target)]["settings"]["lock_bots"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_markdown"] then
data[tostring(target)]["settings"]["lock_markdown"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_webpage"] then
data[tostring(target)]["settings"]["lock_webpage"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["welcome"] then
data[tostring(target)]["settings"]["welcome"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_pin"] then
data[tostring(target)]["settings"]["lock_pin"] = "no"
end
end
local expire_date = ''
local expi = redis:ttl('ExpireDate:'..msg.to.id)
if expi == -1 then
if lang then
expire_date = 'نامحدود!'
else
expire_date = 'Unlimited!'
end
else
local day = math.floor(expi / 86400) + 1
if lang then
expire_date = day..' روز'
else
expire_date = day..' Days'
end
end
if not lang then
local settings = data[tostring(target)]["settings"]
text = "*Group Settings:*\n_Lock edit :_ *"..settings.lock_edit.."*\n_Lock links :_ *"..settings.lock_link.."*\n_Lock tags :_ *"..settings.lock_tag.."*\n_Lock flood :_ *"..settings.flood.."*\n_Lock spam :_ *"..settings.lock_spam.."*\n_Lock mention :_ *"..settings.lock_mention.."*\n_Lock arabic :_ *"..settings.lock_arabic.."*\n_Lock webpage :_ *"..settings.lock_webpage.."*\n_Lock markdown :_ *"..settings.lock_markdown.."*\n_Group welcome :_ *"..settings.welcome.."*\n_Lock pin message :_ *"..settings.lock_pin.."*\n_Bots protection :_ *"..settings.lock_bots.."*\n_Flood sensitivity :_ *"..NUM_MSG_MAX.."*\n*____________________*\n_Expire Date :_ *"..expire_date.."*\n*Bot channel*: @telereborn\n*Group Language* : *EN*"
else
local settings = data[tostring(target)]["settings"]
text = "*تنظیمات گروه:*\n_قفل ویرایش پیام :_ *"..settings.lock_edit.."*\n_قفل لینک :_ *"..settings.lock_link.."*\n_قفل تگ :_ *"..settings.lock_tag.."*\n_قفل پیام مکرر :_ *"..settings.flood.."*\n_قفل هرزنامه :_ *"..settings.lock_spam.."*\n_قفل فراخوانی :_ *"..settings.lock_mention.."*\n_قفل عربی :_ *"..settings.lock_arabic.."*\n_قفل صفحات وب :_ *"..settings.lock_webpage.."*\n_قفل فونت :_ *"..settings.lock_markdown.."*\n_پیام خوشآمد گویی :_ *"..settings.welcome.."*\n_قفل سنجاق کردن :_ *"..settings.lock_pin.."*\n_محافظت در برابر ربات ها :_ *"..settings.lock_bots.."*\n_حداکثر پیام مکرر :_ *"..NUM_MSG_MAX.."*\n*____________________*\n_تاریخ انقضا :_ *"..expire_date.."*\n*کانال ما*: @telereborn\n_زبان سوپرگروه_ : *FA*"
end
return text
end
--------Mutes---------
--------Mute all--------------------------
local function mute_all(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_all = data[tostring(target)]["mutes"]["mute_all"]
if mute_all == "yes" then
if not lang then
return "*Mute All* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن همه فعال است"
end
else
data[tostring(target)]["mutes"]["mute_all"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute All* _Has Been Enabled_"
else
return "بیصدا کردن همه فعال شد"
end
end
end
local function unmute_all(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_all = data[tostring(target)]["mutes"]["mute_all"]
if mute_all == "no" then
if not lang then
return "*Mute All* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن همه غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_all"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute All* _Has Been Disabled_"
else
return "بیصدا کردن همه غیر فعال شد"
end
end
end
---------------Mute Gif-------------------
local function mute_gif(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_gif = data[tostring(target)]["mutes"]["mute_gif"]
if mute_gif == "yes" then
if not lang then
return "*Mute Gif* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن تصاویر متحرک فعال است"
end
else
data[tostring(target)]["mutes"]["mute_gif"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Gif* _Has Been Enabled_"
else
return "بیصدا کردن تصاویر متحرک فعال شد"
end
end
end
local function unmute_gif(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_gif = data[tostring(target)]["mutes"]["mute_gif"]
if mute_gif == "no" then
if not lang then
return "*Mute Gif* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن تصاویر متحرک غیر فعال بود"
end
else
data[tostring(target)]["mutes"]["mute_gif"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Gif* _Has Been Disabled_"
else
return "بیصدا کردن تصاویر متحرک غیر فعال شد"
end
end
end
---------------Mute Game-------------------
local function mute_game(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_game = data[tostring(target)]["mutes"]["mute_game"]
if mute_game == "yes" then
if not lang then
return "*Mute Game* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن بازی های تحت وب فعال است"
end
else
data[tostring(target)]["mutes"]["mute_game"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Game* _Has Been Enabled_"
else
return "بیصدا کردن بازی های تحت وب فعال شد"
end
end
end
local function unmute_game(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_game = data[tostring(target)]["mutes"]["mute_game"]
if mute_game == "no" then
if not lang then
return "*Mute Game* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن بازی های تحت وب غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_game"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Game* _Has Been Disabled_"
else
return "بیصدا کردن بازی های تحت وب غیر فعال شد"
end
end
end
---------------Mute Inline-------------------
local function mute_inline(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_inline = data[tostring(target)]["mutes"]["mute_inline"]
if mute_inline == "yes" then
if not lang then
return "*Mute Inline* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن کیبورد شیشه ای فعال است"
end
else
data[tostring(target)]["mutes"]["mute_inline"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Inline* _Has Been Enabled_"
else
return "بیصدا کردن کیبورد شیشه ای فعال شد"
end
end
end
local function unmute_inline(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_inline = data[tostring(target)]["mutes"]["mute_inline"]
if mute_inline == "no" then
if not lang then
return "*Mute Inline* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن کیبورد شیشه ای غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_inline"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Inline* _Has Been Disabled_"
else
return "بیصدا کردن کیبورد شیشه ای غیر فعال شد"
end
end
end
---------------Mute Text-------------------
local function mute_text(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_text = data[tostring(target)]["mutes"]["mute_text"]
if mute_text == "yes" then
if not lang then
return "*Mute Text* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن متن فعال است"
end
else
data[tostring(target)]["mutes"]["mute_text"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Text* _Has Been Enabled_"
else
return "بیصدا کردن متن فعال شد"
end
end
end
local function unmute_text(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_text = data[tostring(target)]["mutes"]["mute_text"]
if mute_text == "no" then
if not lang then
return "*Mute Text* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن متن غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_text"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Text* _Has Been Disabled_"
else
return "بیصدا کردن متن غیر فعال شد"
end
end
end
---------------Mute photo-------------------
local function mute_photo(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_photo = data[tostring(target)]["mutes"]["mute_photo"]
if mute_photo == "yes" then
if not lang then
return "*Mute Photo* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن عکس فعال است"
end
else
data[tostring(target)]["mutes"]["mute_photo"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Photo* _Has Been Enabled_"
else
return "بیصدا کردن عکس فعال شد"
end
end
end
local function unmute_photo(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_photo = data[tostring(target)]["mutes"]["mute_photo"]
if mute_photo == "no" then
if not lang then
return "*Mute Photo* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن عکس غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_photo"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Photo* _Has Been Disabled_"
else
return "بیصدا کردن عکس غیر فعال شد"
end
end
end
---------------Mute Video-------------------
local function mute_video(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_video = data[tostring(target)]["mutes"]["mute_video"]
if mute_video == "yes" then
if not lang then
return "*Mute Video* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن فیلم فعال است"
end
else
data[tostring(target)]["mutes"]["mute_video"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Video* _Has Been Enabled_"
else
return "بیصدا کردن فیلم فعال شد"
end
end
end
local function unmute_video(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_video = data[tostring(target)]["mutes"]["mute_video"]
if mute_video == "no" then
if not lang then
return "*Mute Video* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن فیلم غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_video"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Video* _Has Been Disabled_"
else
return "بیصدا کردن فیلم غیر فعال شد"
end
end
end
---------------Mute Audio-------------------
local function mute_audio(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_audio = data[tostring(target)]["mutes"]["mute_audio"]
if mute_audio == "yes" then
if not lang then
return "*Mute Audio* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن آهنگ فعال است"
end
else
data[tostring(target)]["mutes"]["mute_audio"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Audio* _Has Been Enabled_"
else
return "بیصدا کردن آهنگ فعال شد"
end
end
end
local function unmute_audio(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_audio = data[tostring(target)]["mutes"]["mute_audio"]
if mute_audio == "no" then
if not lang then
return "*Mute Audio* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن آهنک غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_audio"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Audio* _Has Been Disabled_"
else
return "بیصدا کردن آهنگ غیر فعال شد"
end
end
end
---------------Mute Voice-------------------
local function mute_voice(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_voice = data[tostring(target)]["mutes"]["mute_voice"]
if mute_voice == "yes" then
if not lang then
return "*Mute Voice* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن صدا فعال است"
end
else
data[tostring(target)]["mutes"]["mute_voice"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Voice* _Has Been Enabled_"
else
return "بیصدا کردن صدا فعال شد"
end
end
end
local function unmute_voice(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_voice = data[tostring(target)]["mutes"]["mute_voice"]
if mute_voice == "no" then
if not lang then
return "*Mute Voice* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن صدا غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_voice"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Voice* _Has Been Disabled_"
else
return "بیصدا کردن صدا غیر فعال شد"
end
end
end
---------------Mute Sticker-------------------
local function mute_sticker(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_sticker = data[tostring(target)]["mutes"]["mute_sticker"]
if mute_sticker == "yes" then
if not lang then
return "*Mute Sticker* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن برچسب فعال است"
end
else
data[tostring(target)]["mutes"]["mute_sticker"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Sticker* _Has Been Enabled_"
else
return "بیصدا کردن برچسب فعال شد"
end
end
end
local function unmute_sticker(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_sticker = data[tostring(target)]["mutes"]["mute_sticker"]
if mute_sticker == "no" then
if not lang then
return "*Mute Sticker* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن برچسب غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_sticker"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Sticker* _Has Been Disabled_"
else
return "بیصدا کردن برچسب غیر فعال شد"
end
end
end
---------------Mute Contact-------------------
local function mute_contact(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_contact = data[tostring(target)]["mutes"]["mute_contact"]
if mute_contact == "yes" then
if not lang then
return "*Mute Contact* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن مخاطب فعال است"
end
else
data[tostring(target)]["mutes"]["mute_contact"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Contact* _Has Been Enabled_"
else
return "بیصدا کردن مخاطب فعال شد"
end
end
end
local function unmute_contact(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_contact = data[tostring(target)]["mutes"]["mute_contact"]
if mute_contact == "no" then
if not lang then
return "*Mute Contact* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن مخاطب غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_contact"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Contact* _Has Been Disabled_"
else
return "بیصدا کردن مخاطب غیر فعال شد"
end
end
end
---------------Mute Forward-------------------
local function mute_forward(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_forward = data[tostring(target)]["mutes"]["mute_forward"]
if mute_forward == "yes" then
if not lang then
return "*Mute Forward* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن نقل قول فعال است"
end
else
data[tostring(target)]["mutes"]["mute_forward"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Forward* _Has Been Enabled_"
else
return "بیصدا کردن نقل قول فعال شد"
end
end
end
local function unmute_forward(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_forward = data[tostring(target)]["mutes"]["mute_forward"]
if mute_forward == "no" then
if not lang then
return "*Mute Forward* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن نقل قول غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_forward"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Forward* _Has Been Disabled_"
else
return "بیصدا کردن نقل قول غیر فعال شد"
end
end
end
---------------Mute Location-------------------
local function mute_location(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_location = data[tostring(target)]["mutes"]["mute_location"]
if mute_location == "yes" then
if not lang then
return "*Mute Location* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن موقعیت فعال است"
end
else
data[tostring(target)]["mutes"]["mute_location"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Location* _Has Been Enabled_"
else
return "بیصدا کردن موقعیت فعال شد"
end
end
end
local function unmute_location(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_location = data[tostring(target)]["mutes"]["mute_location"]
if mute_location == "no" then
if not lang then
return "*Mute Location* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن موقعیت غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_location"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Location* _Has Been Disabled_"
else
return "بیصدا کردن موقعیت غیر فعال شد"
end
end
end
---------------Mute Document-------------------
local function mute_document(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_document = data[tostring(target)]["mutes"]["mute_document"]
if mute_document == "yes" then
if not lang then
return "*Mute Document* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن اسناد فعال لست"
end
else
data[tostring(target)]["mutes"]["mute_document"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Document* _Has Been Enabled_"
else
return "بیصدا کردن اسناد فعال شد"
end
end
end
local function unmute_document(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_document = data[tostring(target)]["mutes"]["mute_document"]
if mute_document == "no" then
if not lang then
return "*Mute Document* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن اسناد غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_document"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Document* _Has Been Disabled_"
else
return "بیصدا کردن اسناد غیر فعال شد"
end
end
end
---------------Mute TgService-------------------
local function mute_tgservice(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_tgservice = data[tostring(target)]["mutes"]["mute_tgservice"]
if mute_tgservice == "yes" then
if not lang then
return "*Mute TgService* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن خدمات تلگرام فعال است"
end
else
data[tostring(target)]["mutes"]["mute_tgservice"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute TgService* _Has Been Enabled_"
else
return "بیصدا کردن خدمات تلگرام فعال شد"
end
end
end
local function unmute_tgservice(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نیستید"
end
end
local mute_tgservice = data[tostring(target)]["mutes"]["mute_tgservice"]
if mute_tgservice == "no" then
if not lang then
return "*Mute TgService* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن خدمات تلگرام غیر فعال است"
end
else
data[tostring(target)]["mutes"]["mute_tgservice"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute TgService* _Has Been Disabled_"
else
return "بیصدا کردن خدمات تلگرام غیر فعال شد"
end
end
end
---------------Mute Keyboard-------------------
local function mute_keyboard(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_keyboard = data[tostring(target)]["mutes"]["mute_keyboard"]
if mute_keyboard == "yes" then
if not lang then
return "*Mute Keyboard* _Is Already Enabled_"
elseif lang then
return "بیصدا کردن صفحه کلید فعال است"
end
else
data[tostring(target)]["mutes"]["mute_keyboard"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute Keyboard* _Has Been Enabled_"
else
return "بیصدا کردن صفحه کلید فعال شد"
end
end
end
local function unmute_keyboard(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نیستید"
end
end
local mute_keyboard = data[tostring(target)]["mutes"]["mute_keyboard"]
if mute_keyboard == "no" then
if not lang then
return "*Mute Keyboard* _Is Already Disabled_"
elseif lang then
return "بیصدا کردن صفحه کلید غیرفعال است"
end
else
data[tostring(target)]["mutes"]["mute_keyboard"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "*Mute TgService* _Has Been Disabled_"
else
return "بیصدا کردن صفحه کلید غیرفعال شد"
end
end
end
----------MuteList---------
local function mutes(msg, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نیستید"
end
end
local data = load_data(_config.moderation.data)
local target = msg.to.id
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_all"] then
data[tostring(target)]["mutes"]["mute_all"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_gif"] then
data[tostring(target)]["mutes"]["mute_gif"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_text"] then
data[tostring(target)]["mutes"]["mute_text"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_photo"] then
data[tostring(target)]["mutes"]["mute_photo"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_video"] then
data[tostring(target)]["mutes"]["mute_video"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_audio"] then
data[tostring(target)]["mutes"]["mute_audio"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_voice"] then
data[tostring(target)]["mutes"]["mute_voice"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_sticker"] then
data[tostring(target)]["mutes"]["mute_sticker"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_contact"] then
data[tostring(target)]["mutes"]["mute_contact"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_forward"] then
data[tostring(target)]["mutes"]["mute_forward"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_location"] then
data[tostring(target)]["mutes"]["mute_location"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_document"] then
data[tostring(target)]["mutes"]["mute_document"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_tgservice"] then
data[tostring(target)]["mutes"]["mute_tgservice"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_inline"] then
data[tostring(target)]["mutes"]["mute_inline"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_game"] then
data[tostring(target)]["mutes"]["mute_game"] = "no"
end
end
if data[tostring(target)]["mutes"] then
if not data[tostring(target)]["mutes"]["mute_keyboard"] then
data[tostring(target)]["mutes"]["mute_keyboard"] = "no"
end
end
if not lang then
local mutes = data[tostring(target)]["mutes"]
text = " *Group Mute List* : \n_Mute all : _ *"..mutes.mute_all.."*\n_Mute gif :_ *"..mutes.mute_gif.."*\n_Mute text :_ *"..mutes.mute_text.."*\n_Mute inline :_ *"..mutes.mute_inline.."*\n_Mute game :_ *"..mutes.mute_game.."*\n_Mute photo :_ *"..mutes.mute_photo.."*\n_Mute video :_ *"..mutes.mute_video.."*\n_Mute audio :_ *"..mutes.mute_audio.."*\n_Mute voice :_ *"..mutes.mute_voice.."*\n_Mute sticker :_ *"..mutes.mute_sticker.."*\n_Mute contact :_ *"..mutes.mute_contact.."*\n_Mute forward :_ *"..mutes.mute_forward.."*\n_Mute location :_ *"..mutes.mute_location.."*\n_Mute document :_ *"..mutes.mute_document.."*\n_Mute TgService :_ *"..mutes.mute_tgservice.."*\n_Mute Keyboard :_ *"..mutes.mute_keyboard.."*\n*____________________*\n*Bot channel*: @BeyondTeam\n*Group Language* : *EN*"
else
local mutes = data[tostring(target)]["mutes"]
text = " *لیست بیصدا ها* : \n_بیصدا همه : _ *"..mutes.mute_all.."*\n_بیصدا تصاویر متحرک :_ *"..mutes.mute_gif.."*\n_بیصدا متن :_ *"..mutes.mute_text.."*\n_بیصدا کیبورد شیشه ای :_ *"..mutes.mute_inline.."*\n_بیصدا بازی های تحت وب :_ *"..mutes.mute_game.."*\n_بیصدا عکس :_ *"..mutes.mute_photo.."*\n_بیصدا فیلم :_ *"..mutes.mute_video.."*\n_بیصدا آهنگ :_ *"..mutes.mute_audio.."*\n_بیصدا صدا :_ *"..mutes.mute_voice.."*\n_بیصدا برچسب :_ *"..mutes.mute_sticker.."*\n_بیصدا مخاطب :_ *"..mutes.mute_contact.."*\n_بیصدا نقل قول :_ *"..mutes.mute_forward.."*\n_بیصدا موقعیت :_ *"..mutes.mute_location.."*\n_بیصدا اسناد :_ *"..mutes.mute_document.."*\n_بیصدا خدمات تلگرام :_ *"..mutes.mute_tgservice.."*\n_بیصدا صفحه کلید :_ *"..mutes.mute_keyboard.."*\n*____________________*\n*Bot channel*: @telereborn\n_زبان سوپرگروه_ : *FA*"
end
return text
end
local function run(msg, matches)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local chat = msg.to.id
local user = msg.from.id
if msg.to.type ~= 'pv' then
if matches[1] == "id" then
if not matches[2] and not msg.reply_id then
local function getpro(arg, data)
if data.photos_[0] then
if not lang then
tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,'Chat ID : '..msg.to.id..'\nUser ID : '..msg.from.id,dl_cb,nil)
elseif lang then
tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,'شناسه گروه : '..msg.to.id..'\nشناسه شما : '..msg.from.id,dl_cb,nil)
end
else
if not lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, "`You Have Not Profile Photo...!`\n\n> *Chat ID :* `"..msg.to.id.."`\n*User ID :* `"..msg.from.id.."`", 1, 'md')
elseif lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, "_شما هیچ عکسی ندارید...!_\n\n> _شناسه گروه :_ `"..msg.to.id.."`\n_شناسه شما :_ `"..msg.from.id.."`", 1, 'md')
end
end
end
tdcli_function ({
ID = "GetUserProfilePhotos",
user_id_ = msg.from.id,
offset_ = 0,
limit_ = 1
}, getpro, nil)
end
if msg.reply_id and not matches[2] then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="id"})
end
if matches[2] then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="id"})
end
end
if matches[1] == "pin" and is_mod(msg) and msg.reply_id then
local lock_pin = data[tostring(msg.to.id)]["settings"]["lock_pin"]
if lock_pin == 'yes' then
if is_owner(msg) then
data[tostring(chat)]['pin'] = msg.reply_id
save_data(_config.moderation.data, data)
tdcli.pinChannelMessage(msg.to.id, msg.reply_id, 1)
if not lang then
return "*Message Has Been Pinned*"
elseif lang then
return "پیام سجاق شد"
end
elseif not is_owner(msg) then
return
end
elseif lock_pin == 'no' then
data[tostring(chat)]['pin'] = msg.reply_id
save_data(_config.moderation.data, data)
tdcli.pinChannelMessage(msg.to.id, msg.reply_id, 1)
if not lang then
return "*Message Has Been Pinned*"
elseif lang then
return "پیام سجاق شد"
end
end
end
if matches[1] == 'unpin' and is_mod(msg) then
local lock_pin = data[tostring(msg.to.id)]["settings"]["lock_pin"]
if lock_pin == 'yes' then
if is_owner(msg) then
tdcli.unpinChannelMessage(msg.to.id)
if not lang then
return "*Pin message has been unpinned*"
elseif lang then
return "پیام سنجاق شده پاک شد"
end
elseif not is_owner(msg) then
return
end
elseif lock_pin == 'no' then
tdcli.unpinChannelMessage(msg.to.id)
if not lang then
return "*Pin message has been unpinned*"
elseif lang then
return "پیام سنجاق شده پاک شد"
end
end
end
if matches[1] == "add" then
return modadd(msg)
end
if matches[1] == "rem" then
return modrem(msg)
end
if matches[1] == "setowner" and is_admin(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="setowner"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="setowner"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="setowner"})
end
end
if matches[1] == "remowner" and is_admin(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="remowner"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="remowner"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="remowner"})
end
end
if matches[1] == "promote" and is_owner(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="promote"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="promote"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="promote"})
end
end
if matches[1] == "demote" and is_owner(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="demote"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="demote"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="demote"})
end
end
if matches[1] == "lock" and is_mod(msg) then
local target = msg.to.id
if matches[2] == "link" then
return lock_link(msg, data, target)
end
if matches[2] == "tag" then
return lock_tag(msg, data, target)
end
if matches[2] == "mention" then
return lock_mention(msg, data, target)
end
if matches[2] == "arabic" then
return lock_arabic(msg, data, target)
end
if matches[2] == "edit" then
return lock_edit(msg, data, target)
end
if matches[2] == "spam" then
return lock_spam(msg, data, target)
end
if matches[2] == "flood" then
return lock_flood(msg, data, target)
end
if matches[2] == "bots" then
return lock_bots(msg, data, target)
end
if matches[2] == "markdown" then
return lock_markdown(msg, data, target)
end
if matches[2] == "webpage" then
return lock_webpage(msg, data, target)
end
if matches[2] == "pin" and is_owner(msg) then
return lock_pin(msg, data, target)
end
end
if matches[1] == "unlock" and is_mod(msg) then
local target = msg.to.id
if matches[2] == "link" then
return unlock_link(msg, data, target)
end
if matches[2] == "tag" then
return unlock_tag(msg, data, target)
end
if matches[2] == "mention" then
return unlock_mention(msg, data, target)
end
if matches[2] == "arabic" then
return unlock_arabic(msg, data, target)
end
if matches[2] == "edit" then
return unlock_edit(msg, data, target)
end
if matches[2] == "spam" then
return unlock_spam(msg, data, target)
end
if matches[2] == "flood" then
return unlock_flood(msg, data, target)
end
if matches[2] == "bots" then
return unlock_bots(msg, data, target)
end
if matches[2] == "markdown" then
return unlock_markdown(msg, data, target)
end
if matches[2] == "webpage" then
return unlock_webpage(msg, data, target)
end
if matches[2] == "pin" and is_owner(msg) then
return unlock_pin(msg, data, target)
end
end
if matches[1] == "mute" and is_mod(msg) then
local target = msg.to.id
if matches[2] == "all" then
return mute_all(msg, data, target)
end
if matches[2] == "gif" then
return mute_gif(msg, data, target)
end
if matches[2] == "text" then
return mute_text(msg ,data, target)
end
if matches[2] == "photo" then
return mute_photo(msg ,data, target)
end
if matches[2] == "video" then
return mute_video(msg ,data, target)
end
if matches[2] == "audio" then
return mute_audio(msg ,data, target)
end
if matches[2] == "voice" then
return mute_voice(msg ,data, target)
end
if matches[2] == "sticker" then
return mute_sticker(msg ,data, target)
end
if matches[2] == "contact" then
return mute_contact(msg ,data, target)
end
if matches[2] == "forward" then
return mute_forward(msg ,data, target)
end
if matches[2] == "location" then
return mute_location(msg ,data, target)
end
if matches[2] == "document" then
return mute_document(msg ,data, target)
end
if matches[2] == "tgservice" then
return mute_tgservice(msg ,data, target)
end
if matches[2] == "inline" then
return mute_inline(msg ,data, target)
end
if matches[2] == "game" then
return mute_game(msg ,data, target)
end
if matches[2] == "keyboard" then
return mute_keyboard(msg ,data, target)
end
end
if matches[1] == "unmute" and is_mod(msg) then
local target = msg.to.id
if matches[2] == "all" then
return unmute_all(msg, data, target)
end
if matches[2] == "gif" then
return unmute_gif(msg, data, target)
end
if matches[2] == "text" then
return unmute_text(msg, data, target)
end
if matches[2] == "photo" then
return unmute_photo(msg ,data, target)
end
if matches[2] == "video" then
return unmute_video(msg ,data, target)
end
if matches[2] == "audio" then
return unmute_audio(msg ,data, target)
end
if matches[2] == "voice" then
return unmute_voice(msg ,data, target)
end
if matches[2] == "sticker" then
return unmute_sticker(msg ,data, target)
end
if matches[2] == "contact" then
return unmute_contact(msg ,data, target)
end
if matches[2] == "forward" then
return unmute_forward(msg ,data, target)
end
if matches[2] == "location" then
return unmute_location(msg ,data, target)
end
if matches[2] == "document" then
return unmute_document(msg ,data, target)
end
if matches[2] == "tgservice" then
return unmute_tgservice(msg ,data, target)
end
if matches[2] == "inline" then
return unmute_inline(msg ,data, target)
end
if matches[2] == "game" then
return unmute_game(msg ,data, target)
end
if matches[2] == "keyboard" then
return unmute_keyboard(msg ,data, target)
end
end
if matches[1] == "gpinfo" and is_mod(msg) and msg.to.type == "channel" then
local function group_info(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if not lang then
ginfo = "*Group Info :*\n_Admin Count :_ *"..data.administrator_count_.."*\n_Member Count :_ *"..data.member_count_.."*\n_Kicked Count :_ *"..data.kicked_count_.."*\n_Group ID :_ *"..data.channel_.id_.."*"
print(serpent.block(data))
elseif lang then
ginfo = "*اطلاعات گروه :*\n_تعداد مدیران :_ *"..data.administrator_count_.."*\n_تعداد اعضا :_ *"..data.member_count_.."*\n_تعداد اعضای حذف شده :_ *"..data.kicked_count_.."*\n_شناسه گروه :_ *"..data.channel_.id_.."*"
print(serpent.block(data))
end
tdcli.sendMessage(arg.chat_id, arg.msg_id, 1, ginfo, 1, 'md')
end
tdcli.getChannelFull(msg.to.id, group_info, {chat_id=msg.to.id,msg_id=msg.id})
end
if matches[1] == 'newlink' and is_mod(msg) then
local function callback_link (arg, data)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if not data.invite_link_ then
administration[tostring(msg.to.id)]['settings']['linkgp'] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "_Bot is not group creator_\n_set a link for group with using_ /setlink", 1, 'md')
elseif lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "_ربات سازنده گروه نیست_\n_با دستور_ setlink/ _لینک جدیدی برای گروه ثبت کنید_", 1, 'md')
end
else
administration[tostring(msg.to.id)]['settings']['linkgp'] = data.invite_link_
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "*Newlink Created*", 1, 'md')
elseif lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "_لینک جدید ساخته شد_", 1, 'md')
end
end
end
tdcli.exportChatInviteLink(msg.to.id, callback_link, nil)
end
if matches[1] == 'setlink' and is_owner(msg) then
data[tostring(chat)]['settings']['linkgp'] = 'waiting'
save_data(_config.moderation.data, data)
if not lang then
return '_Please send the new group_ *link* _now_'
else
return 'لطفا لینک گروه خود را ارسال کنید'
end
end
if msg.text then
local is_link = msg.text:match("^([https?://w]*.?telegram.me/joinchat/%S+)$") or msg.text:match("^([https?://w]*.?t.me/joinchat/%S+)$")
if is_link and data[tostring(chat)]['settings']['linkgp'] == 'waiting' and is_owner(msg) then
data[tostring(chat)]['settings']['linkgp'] = msg.text
save_data(_config.moderation.data, data)
if not lang then
return "*Newlink* _has been set_"
else
return "لینک جدید ذخیره شد"
end
end
end
if matches[1] == 'link' and is_mod(msg) then
local linkgp = data[tostring(chat)]['settings']['linkgp']
if not linkgp then
if not lang then
return "_First create a link for group with using_ /newlink\n_If bot not group creator set a link with using_ /setlink"
else
return "ابتدا با دستور newlink/ لینک جدیدی برای گروه بسازید\nو اگر ربات سازنده گروه نیس با دستور setlink/ لینک جدیدی برای گروه ثبت کنید"
end
end
if not lang then
text = "<b>Group Link :</b>\n"..linkgp
else
text = "<b>لینک گروه :</b>\n"..linkgp
end
return tdcli.sendMessage(chat, msg.id, 1, text, 1, 'html')
end
if matches[1] == 'linkpv' and is_mod(msg) then
local linkgp = data[tostring(chat)]['settings']['linkgp']
if not linkgp then
if not lang then
return "_First create a link for group with using_ /newlink\n_If bot not group creator set a link with using_ /setlink"
else
return "ابتدا با دستور newlink/ لینک جدیدی برای گروه بسازید\nو اگر ربات سازنده گروه نیس با دستور setlink/ لینک جدیدی برای گروه ثبت کنید"
end
end
if not lang then
tdcli.sendMessage(user, "", 1, "<b>Group Link "..msg.to.title.." :</b>\n"..linkgp, 1, 'html')
else
tdcli.sendMessage(user, "", 1, "<b>لینک گروه "..msg.to.title.." :</b>\n"..linkgp, 1, 'html')
end
if not lang then
return "*Group Link Was Send In Your Private Message*"
else
return "_لینک گروه به چت خصوصی شما ارسال شد_"
end
end
if matches[1] == "setrules" and matches[2] and is_mod(msg) then
data[tostring(chat)]['rules'] = matches[2]
save_data(_config.moderation.data, data)
if not lang then
return "*Group rules* _has been set_"
else
return "قوانین گروه ثبت شد"
end
end
if matches[1] == "rules" then
if not data[tostring(chat)]['rules'] then
if not lang then
rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban.\n@telereborn"
elseif lang then
rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام مکرر ممنوع.\n2⃣ اسپم ممنوع.\n3⃣ تبلیغ ممنوع.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی ممنوع .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود.\n@telereborn"
end
else
rules = "*Group Rules :*\n"..data[tostring(chat)]['rules']
end
return rules
end
if matches[1] == "res" and matches[2] and is_mod(msg) then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="res"})
end
if matches[1] == "whois" and matches[2] and is_mod(msg) then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="whois"})
end
if matches[1] == 'setflood' and is_mod(msg) then
if tonumber(matches[2]) < 1 or tonumber(matches[2]) > 50 then
return "_Wrong number, range is_ *[1-50]*"
end
local flood_max = matches[2]
data[tostring(chat)]['settings']['num_msg_max'] = flood_max
save_data(_config.moderation.data, data)
return "_Group_ *flood* _sensitivity has been set to :_ *[ "..matches[2].." ]*"
end
if matches[1]:lower() == 'clean' and is_owner(msg) then
if matches[2] == 'mods' then
if next(data[tostring(chat)]['mods']) == nil then
if not lang then
return "_No_ *moderators* _in this group_"
else
return "هیچ مدیری برای گروه انتخاب نشده است"
end
end
for k,v in pairs(data[tostring(chat)]['mods']) do
data[tostring(chat)]['mods'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "_All_ *moderators* _has been demoted_"
else
return "تمام مدیران گروه تنزیل مقام شدند"
end
end
if matches[2] == 'filterlist' then
if next(data[tostring(chat)]['filterlist']) == nil then
if not lang then
return "*Filtered words list* _is empty_"
else
return "_لیست کلمات فیلتر شده خالی است_"
end
end
for k,v in pairs(data[tostring(chat)]['filterlist']) do
data[tostring(chat)]['filterlist'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "*Filtered words list* _has been cleaned_"
else
return "_لیست کلمات فیلتر شده پاک شد_"
end
end
if matches[2] == 'rules' then
if not data[tostring(chat)]['rules'] then
if not lang then
return "_No_ *rules* _available_"
else
return "قوانین برای گروه ثبت نشده است"
end
end
data[tostring(chat)]['rules'] = nil
save_data(_config.moderation.data, data)
if not lang then
return "*Group rules* _has been cleaned_"
else
return "قوانین گروه پاک شد"
end
end
if matches[2] == 'welcome' then
if not data[tostring(chat)]['setwelcome'] then
if not lang then
return "*Welcome Message not set*"
else
return "پیام خوشآمد گویی ثبت نشده است"
end
end
data[tostring(chat)]['setwelcome'] = nil
save_data(_config.moderation.data, data)
if not lang then
return "*Welcome message* _has been cleaned_"
else
return "پیام خوشآمد گویی پاک شد"
end
end
if matches[2] == 'about' then
if msg.to.type == "chat" then
if not data[tostring(chat)]['about'] then
if not lang then
return "_No_ *description* _available_"
else
return "پیامی مبنی بر درباره گروه ثبت نشده است"
end
end
data[tostring(chat)]['about'] = nil
save_data(_config.moderation.data, data)
elseif msg.to.type == "channel" then
tdcli.changeChannelAbout(chat, "", dl_cb, nil)
end
if not lang then
return "*Group description* _has been cleaned_"
else
return "پیام مبنی بر درباره گروه پاک شد"
end
end
end
if matches[1]:lower() == 'clean' and is_admin(msg) then
if matches[2] == 'owners' then
if next(data[tostring(chat)]['owners']) == nil then
if not lang then
return "_No_ *owners* _in this group_"
else
return "مالکی برای گروه انتخاب نشده است"
end
end
for k,v in pairs(data[tostring(chat)]['owners']) do
data[tostring(chat)]['owners'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "_All_ *owners* _has been demoted_"
else
return "تمامی مالکان گروه تنزیل مقام شدند"
end
end
end
if matches[1] == "setname" and matches[2] and is_mod(msg) then
local gp_name = matches[2]
tdcli.changeChatTitle(chat, gp_name, dl_cb, nil)
end
if matches[1] == "setabout" and matches[2] and is_mod(msg) then
if msg.to.type == "channel" then
tdcli.changeChannelAbout(chat, matches[2], dl_cb, nil)
elseif msg.to.type == "chat" then
data[tostring(chat)]['about'] = matches[2]
save_data(_config.moderation.data, data)
end
if not lang then
return "*Group description* _has been set_"
else
return "پیام مبنی بر درباره گروه ثبت شد"
end
end
if matches[1] == "about" and msg.to.type == "chat" then
if not data[tostring(chat)]['about'] then
if not lang then
about = "_No_ *description* _available_"
elseif lang then
about = "پیامی مبنی بر درباره گروه ثبت نشده است"
end
else
about = "*Group Description :*\n"..data[tostring(chat)]['about']
end
return about
end
if matches[1] == 'filter' and is_mod(msg) then
return filter_word(msg, matches[2])
end
if matches[1] == 'unfilter' and is_mod(msg) then
return unfilter_word(msg, matches[2])
end
if matches[1] == 'filterlist' and is_mod(msg) then
return filter_list(msg)
end
if matches[1] == "settings" then
return group_settings(msg, target)
end
if matches[1] == "mutelist" then
return mutes(msg, target)
end
if matches[1] == "modlist" then
return modlist(msg)
end
if matches[1] == "ownerlist" and is_owner(msg) then
return ownerlist(msg)
end
if matches[1] == "setlang" and is_owner(msg) then
if matches[2] == "en" then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
redis:del(hash)
return "_Group Language Set To:_ EN"
elseif matches[2] == "fa" then
redis:set(hash, true)
return "*زبان گروه تنظیم شد به : فارسی*"
end
end
if matches[1] == "help" and is_mod(msg) then
if not lang then
text = [[
*Beyond Bot Commands:*
*!setowner* `[username|id|reply]`
_Set Group Owner(Multi Owner)_
*!remowner* `[username|id|reply]`
_Remove User From Owner List_
*!promote* `[username|id|reply]`
_Promote User To Group Admin_
*!demote* `[username|id|reply]`
_Demote User From Group Admins List_
*!setflood* `[1-50]`
_Set Flooding Number_
*!silent* `[username|id|reply]`
_Silent User From Group_
*!unsilent* `[username|id|reply]`
_Unsilent User From Group_
*!kick* `[username|id|reply]`
_Kick User From Group_
*!ban* `[username|id|reply]`
_Ban User From Group_
*!unban* `[username|id|reply]`
_UnBan User From Group_
*!res* `[username]`
_Show User ID_
*!id* `[reply]`
_Show User ID_
*!whois* `[id]`
_Show User's Username And Name_
*!lock* `[link | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | pin]`
_If This Actions Lock, Bot Check Actions And Delete Them_
*!unlock* `[link | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | pin]`
_If This Actions Unlock, Bot Not Delete Them_
*!mute* `[gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]`
_If This Actions Lock, Bot Check Actions And Delete Them_
*!unmute* `[gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]`
_If This Actions Unlock, Bot Not Delete Them_
*!set*`[rules | name | photo | link | about | welcome]`
_Bot Set Them_
*!clean* `[bans | mods | bots | rules | about | silentlist | filtelist | welcome]`
_Bot Clean Them_
*!filter* `[word]`
_Word filter_
*!unfilter* `[word]`
_Word unfilter_
*!pin* `[reply]`
_Pin Your Message_
*!unpin*
_Unpin Pinned Message_
*!welcome enable/disable*
_Enable Or Disable Group Welcome_
*!settings*
_Show Group Settings_
*!mutelist*
_Show Mutes List_
*!silentlist*
_Show Silented Users List_
*!filterlist*
_Show Filtered Words List_
*!banlist*
_Show Banned Users List_
*!ownerlist*
_Show Group Owners List_
*!modlist*
_Show Group Moderators List_
*!rules*
_Show Group Rules_
*!about*
_Show Group Description_
*!id*
_Show Your And Chat ID_
*!gpinfo*
_Show Group Information_
*!newlink*
_Create A New Link_
*!link*
_Show Group Link_
*!linkpv*
_Send Group Link In Your Private Message_
*!setwelcome [text]*
_set Welcome Message_
*!helptools*
_Show Tools Help_
*!helpfun*
_Show Fun Help_
_You Can Use_ *[!/#]* _To Run The Commands_
_This Help List Only For_ *Moderators/Owners!*
_Its Means, Only Group_ *Moderators/Owners* _Can Use It!_
*Good luck ;)*]]
elseif lang then
text = [[
لیست_دستورات_سوپرگروه
📌قفل کردن یکی از موارد زیر4
!mute [gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]
!lock [link | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | pin]
📌بازکردن قفل یکی موارد زیر
!unmute [gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]
—----------------
تنظیمات لیست موت
/mutelist
—----------------
دستورات ربات ریبورن :
!setowner [username|id|reply]
انتخاب مالک گروه(قابل انتخاب چند مالک)
!remowner [username|id|reply]
حذف کردن فرد از فهرست مالکان گروه
!promote [username|id|reply]
ارتقا مقام کاربر به مدیر گروه
!demote [username|id|reply]
تنزیل مقام مدیر به کاربر
!setflood [1-50]
تنظیم حداکثر تعداد پیام مکرر
!silent [username|id|reply]
بیصدا کردن کاربر در گروه
!unsilent [username|id|reply]
در آوردن کاربر از حالت بیصدا در گروه
!kick [username|id|reply]
حذف کاربر از گروه
!ban [username|id|reply]
مسدود کردن کاربر از گروه
!unban [username|id|reply]
در آوردن از حالت مسدودیت کاربر از گروه
!res [username]
نمایش شناسه کاربر
!id [reply]
نمایش شناسه کاربر
!whois [id]
نمایش نام کاربر, نام کاربری و اطلاعات حساب
!lock [link | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | | fosh |pin]
در صورت قفل بودن فعالیت ها, ربات آنهارا حذف خواهد کرد
!unlock [link | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | fosh | mention |pin]
—------------------
برای پین کردن متنی در گروه شما میتوانید پیام مورد نظر را ریپلای کرده و
/pin
برای غیر فعال کردن پیام
/unpin
—------------------
را ارسال کنید همچنین برای تنظیم خوشآمدگویی بصورت دلخواه به صورت زیر عمل کنید:
/setwelcome متن مورد نظر
برای نشان دادن ایدی و اسم فرد وارد شونده میتوانید از
یوزرنیم = {username}
نام = {name}
نام خانوادگی = {lastname}
استفاده کنید
مثال:
/setweclome سلام {name} خوش اومدی
—------------------
/setflood
تنظیم تعداد پیام مکرر مجاز
مثال:
برای مثال اگر تعداد پیام های مکرر مجاز را برای عدد 4 قرار بدهید
/setflood 4
—------------------
برای ممنوع کردن کلمه ای خاص در گروه میتوانید ازدستور زیر استفاده کنید
/filter کلمه مورد نظر
استفاده میکنید, برای مشاهده لیست کلمات ممنوع شده نیز کافیست
/filterlist
را ارسال کنید
—------------------
برای قفل کردن گروه برای زمان مشخص به شکل زیر عمل کنید
/muteall
مثال:
با دستور زیر گروه برای 1 ساعت و 20 دقیقه و 4 ثانیه قفل میشود
/muteall 1
—------------------
تعیین وضعیت خروج داوطلبانه
/stats kickme [active/off]
—------------------
/ban [ریپلی و آیدی]
مسدود کردن کاربر
/unban [ریپلی و آیدی]
حذف کاربر از لیست افراد مسدود شده
/banlist
لیست افراد مسدود شده
/silent [ریپلی و آیدی]
اضافه کردن کاربر به لیست افراد سکوت شده
/unsilent [ریپلی و آیدی]
حذف کردن کاربر به لیست افراد سکوت شده
/silentlist
لیست افراد سکوت شده
/promote [ریپلی و آیدی]
ارتقا دادن کاربر
/demote [ریپلی و آیدی]
برکنار کردن کاربر از مدیریت ربات
/modlist
لیست ادمین های ربات در گروه
/getpro [1-10]
دریافت عکس پروفایل شما
عکس دوم پروفایل شما را نمایش میدهد
/setlink
تنظیم لینک برای گروه
/setrules قوانین
تنظیم متن قوانین گروه
/setmester[آیدی عددی]
تنظیم دریافت کننده گزارشات
/report [ریپلی]
گزارش فرد خاطی به کاربر تنظیم شد گروه
/link
دریافت لینک گروه
/rules
دریافت قوانین
/myid
دریافت اطلاعات خود در ربات
/id
دریافت شناسه عددی گروه و کاربر
!whois [آیدی عددی]
دریافت اطلاعت فرد مورد نظر
/settings
دریافت تنظیمات گروه
/linkpv
دریافت لینک گروه در پ ویتان!
/kickme
خارج شدن از گروه بصورت داوطلبانه
!clean [bans | mods | bots | rules | about | silentlist | filterlist | welcome]
پاکسازی لیست افراد مسدود/سکوت/مدیر/مالک شده
—----------------
🔊دستورات فان و تولز!🍃
!helpfun
------------
!helptools
—----------------
⚠️شما میتوانید از ! و # و / در اول دستور ها استفاده کنید
⚠️هرگونه سوال و انتقاد یا پیشنهادخود را میتوانید در گروه پشتیبانی مطرح کنید
@telereborn]]
end
return text
end
--------------------- Welcome -----------------------
if matches[1] == "welcome" and is_mod(msg) then
if matches[2] == "enable" then
welcome = data[tostring(chat)]['settings']['welcome']
if welcome == "yes" then
if not lang then
return "_Group_ *welcome* _is already enabled_"
elseif lang then
return "_خوشآمد گویی از قبل فعال بود_"
end
else
data[tostring(chat)]['settings']['welcome'] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "_Group_ *welcome* _has been enabled_"
elseif lang then
return "_خوشآمد گویی فعال شد_"
end
end
end
if matches[2] == "disable" then
welcome = data[tostring(chat)]['settings']['welcome']
if welcome == "no" then
if not lang then
return "_Group_ *Welcome* _is already disabled_"
elseif lang then
return "_خوشآمد گویی از قبل فعال نبود_"
end
else
data[tostring(chat)]['settings']['welcome'] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "_Group_ *welcome* _has been disabled_"
elseif lang then
return "_خوشآمد گویی غیرفعال شد_"
end
end
end
end
if matches[1] == "setwelcome" and matches[2] and is_mod(msg) then
data[tostring(chat)]['setwelcome'] = matches[2]
save_data(_config.moderation.data, data)
if not lang then
return "_Welcome Message Has Been Set To :_\n*"..matches[2].."*\n\n*You can use :*\n_{gpname} Group Name_\n_{rules} ➣ Show Group Rules_\n_{name} ➣ New Member First Name_\n_{username} ➣ New Member Username_"
else
return "_پیام خوشآمد گویی تنظیم شد به :_\n*"..matches[2].."*\n\n*شما میتوانید از*\n_{gpname} نام گروه_\n_{rules} ➣ نمایش قوانین گروه_\n_{name} ➣ نام کاربر جدید_\n_{username} ➣ نام کاربری کاربر جدید_\n_استفاده کنید_"
end
end
end
end
-----------------------------------------
local function pre_process(msg)
local chat = msg.to.id
local user = msg.from.id
local data = load_data(_config.moderation.data)
local function welcome_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
administration = load_data(_config.moderation.data)
if administration[arg.chat_id]['setwelcome'] then
welcome = administration[arg.chat_id]['setwelcome']
else
if not lang then
welcome = "*Welcome Dude*"
elseif lang then
welcome = "_خوش آمدید_"
end
end
if administration[tostring(arg.chat_id)]['rules'] then
rules = administration[arg.chat_id]['rules']
else
if not lang then
rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban.\n@telereborn"
elseif lang then
rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام مکرر ممنوع.\n2⃣ اسپم ممنوع.\n3⃣ تبلیغ ممنوع.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی ممنوع .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود.\n@telereborn"
end
end
if data.username_ then
user_name = "@"..check_markdown(data.username_)
else
user_name = ""
end
local welcome = welcome:gsub("{rules}", rules)
local welcome = welcome:gsub("{name}", check_markdown(data.first_name_))
local welcome = welcome:gsub("{username}", user_name)
local welcome = welcome:gsub("{gpname}", arg.gp_name)
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, welcome, 0, "md")
end
if data[tostring(chat)] and data[tostring(chat)]['settings'] then
if msg.adduser then
welcome = data[tostring(msg.to.id)]['settings']['welcome']
if welcome == "yes" then
tdcli_function ({
ID = "GetUser",
user_id_ = msg.adduser
}, welcome_cb, {chat_id=chat,msg_id=msg.id,gp_name=msg.to.title})
else
return false
end
end
if msg.joinuser then
welcome = data[tostring(msg.to.id)]['settings']['welcome']
if welcome == "yes" then
tdcli_function ({
ID = "GetUser",
user_id_ = msg.joinuser
}, welcome_cb, {chat_id=chat,msg_id=msg.id,gp_name=msg.to.title})
else
return false
end
end
end
-- return msg
end
return {
patterns ={
"^[!/#](id)$",
"^[!/#](id) (.*)$",
"^[!/#](pin)$",
"^[!/#](unpin)$",
"^[!/#](gpinfo)$",
"^[!/#](test)$",
"^[!/#](add)$",
"^[!/#](rem)$",
"^[!/#](setowner)$",
"^[!/#](setowner) (.*)$",
"^[!/#](remowner)$",
"^[!/#](remowner) (.*)$",
"^[!/#](promote)$",
"^[!/#](promote) (.*)$",
"^[!/#](demote)$",
"^[!/#](demote) (.*)$",
"^[!/#](modlist)$",
"^[!/#](ownerlist)$",
"^[!/#](lock) (.*)$",
"^[!/#](unlock) (.*)$",
"^[!/#](settings)$",
"^[!/#](mutelist)$",
"^[!/#](mute) (.*)$",
"^[!/#](unmute) (.*)$",
"^[!/#](link)$",
"^[!/#](linkpv)$",
"^[!/#](setlink)$",
"^[!/#](newlink)$",
"^[!/#](rules)$",
"^[!/#](setrules) (.*)$",
"^[!/#](about)$",
"^[!/#](setabout) (.*)$",
"^[!/#](setname) (.*)$",
"^[!/#](clean) (.*)$",
"^[!/#](setflood) (%d+)$",
"^[!/#](res) (.*)$",
"^[!/#](whois) (%d+)$",
"^[!/#](help)$",
"^[!/#](setlang) (.*)$",
"^[#!/](filter) (.*)$",
"^[#!/](unfilter) (.*)$",
"^[#!/](filterlist)$",
"^([https?://w]*.?t.me/joinchat/%S+)$",
"^([https?://w]*.?telegram.me/joinchat/%S+)$",
"^[!/#](setwelcome) (.*)",
"^[!/#](welcome) (.*)$"
},
run=run,
pre_process = pre_process
}
--end groupmanager.lua #beyond team#
| gpl-3.0 |
hfjgjfg/eli25 | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
rigeirani/sss | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
lyzardiar/seal2d | libs/lua-socket/gem/test.lua | 37 | 1081 | function readfile(n)
local f = io.open(n, "rb")
local s = f:read("*a")
f:close()
return s
end
lf = readfile("t1lf.txt")
os.remove("t1crlf.txt")
os.execute("lua t1.lua < t1lf.txt > t1crlf.txt")
crlf = readfile("t1crlf.txt")
assert(crlf == string.gsub(lf, "\010", "\013\010"), "broken")
gt = readfile("t2gt.qp")
os.remove("t2.qp")
os.execute("lua t2.lua < t2.txt > t2.qp")
t2 = readfile("t2.qp")
assert(gt == t2, "broken")
os.remove("t1crlf.txt")
os.execute("lua t3.lua < t1lf.txt > t1crlf.txt")
crlf = readfile("t1crlf.txt")
assert(crlf == string.gsub(lf, "\010", "\013\010"), "broken")
t = readfile("test.lua")
os.execute("lua t4.lua < test.lua > t")
t2 = readfile("t")
assert(t == t2, "broken")
os.remove("output.b64")
gt = readfile("gt.b64")
os.execute("lua t5.lua")
t5 = readfile("output.b64")
assert(gt == t5, "failed")
print("1 2 5 6 10 passed")
print("2 3 4 5 6 10 passed")
print("2 5 6 7 8 10 passed")
print("5 9 passed")
print("5 6 10 11 passed")
os.remove("t")
os.remove("t2.qp")
os.remove("t1crlf.txt")
os.remove("t11.b64")
os.remove("output.b64")
| mit |
Laterus/Darkstar-Linux-Fork | scripts/zones/Tahrongi_Canyon/npcs/Pucotte.lua | 1 | 1224 | -----------------------------------
-- Area: Tahrongi Canyon
-- NPC: Pucotte
-- Chocobo Vendor
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
price = 100;
gil = player:getGil();
hasLicense = player:hasKeyItem(CHOCOBO_LICENSE);
level = player:getMainLvl();
if (hasLicense and level >= 15) then
player:startEvent(0x038e,price,gil);
else
player:startEvent(0x038f,price,gil);
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID:",csid);
--print("OPTION:",option);
price = 100;
level = player:getMainLvl();
if (csid == 0x038e and option == 0) then
if (level >= 20) then
player:addStatusEffect(EFFECT_CHOCOBO,1,0,1800);
else
player:addStatusEffect(EFFECT_CHOCOBO,1,0,900);
end
player:delGil(price);
end
end; | gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/mcml/pe_mc_mcml.lua | 1 | 3564 | --[[
Title: MC Main Login Procedure
Author(s): LiXizhi
Company: ParaEnging
Date: 2013.10.14
Desc:
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/pe_mc_mcml.lua");
MyCompany.Aries.Game.mcml_controls.register_all();
------------------------------------------------------------
]]
local mcml_controls = commonlib.gettable("MyCompany.Aries.Game.mcml_controls");
local is_init = false;
-- all this function to register all mcml tag
function mcml_controls.register_all()
if(is_init) then
return;
end
is_init = true;
LOG.std("", "system", "mcml", "register mc related mcml tags");
NPL.load("(gl)script/kids/3DMapSystemApp/mcml/mcml_controls.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/pe_mc_player.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/pe_mc_block.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/pe_mc_slot.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/pe_mc_entity_canvas.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/pe_checkbox_button.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/NplBrowser/pe_nplbrowser.lua");
NPL.load("(gl)script/apps/Aries/mcml/pe_aries_textsprite.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/kp_item.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/kp_slot.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/kp_redtip.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/kp_usertag.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/kp_window.lua");
-- lessons ppt
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/lessons_ppt/step.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/lessons_ppt/action.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/lessons_ppt/notes.lua");
-- mc tags
Map3DSystem.mcml_controls.RegisterUserControl("pe:mc_player", MyCompany.Aries.Game.mcml.pe_mc_player);
Map3DSystem.mcml_controls.RegisterUserControl("pe:mc_block", MyCompany.Aries.Game.mcml.pe_mc_block);
Map3DSystem.mcml_controls.RegisterUserControl("pe:mc_slot", MyCompany.Aries.Game.mcml.pe_mc_slot);
Map3DSystem.mcml_controls.RegisterUserControl("pe:mc_entity_canvas", MyCompany.Aries.Game.mcml.pe_mc_entity_canvas);
Map3DSystem.mcml_controls.RegisterUserControl("pe:checkbox_button", MyCompany.Aries.Game.mcml.pe_checkbox_button);
Map3DSystem.mcml_controls.RegisterUserControl("aries:textsprite", MyCompany.Aries.mcml_controls and MyCompany.Aries.mcml_controls.aries_textsprite);
Map3DSystem.mcml_controls.RegisterUserControl("kp:item", MyCompany.Aries.Game.mcml.kp_item);
Map3DSystem.mcml_controls.RegisterUserControl("kp:slot", MyCompany.Aries.Game.mcml.kp_slot);
Map3DSystem.mcml_controls.RegisterUserControl("kp:redtip", MyCompany.Aries.Game.mcml.kp_redtip);
Map3DSystem.mcml_controls.RegisterUserControl("kp:usertag", MyCompany.Aries.Game.mcml.kp_usertag);
Map3DSystem.mcml_controls.RegisterUserControl("kp:window", MyCompany.Aries.Game.mcml.kp_window);
local pe_nplbrowser = commonlib.gettable("NplBrowser.pe_nplbrowser");
Map3DSystem.mcml_controls.RegisterUserControl("pe:nplbrowser", pe_nplbrowser);
Map3DSystem.mcml_controls.RegisterUserControl("step", MyCompany.Aries.Game.mcml.lessons_ppt.step);
Map3DSystem.mcml_controls.RegisterUserControl("action", MyCompany.Aries.Game.mcml.lessons_ppt.action);
Map3DSystem.mcml_controls.RegisterUserControl("notes", MyCompany.Aries.Game.mcml.lessons_ppt.notes);
end | gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/Dock/DockTipPage.lua | 1 | 9801 | --[[
Title: DockTipPage
Author(s): leio
Date: 2020/8/17
Desc:
Use Lib:
-------------------------------------------------------
local DockTipPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/Dock/DockTipPage.lua");
DockTipPage.GetInstance():PushGsid(888);
DockTipPage.GetInstance():PushGsid(998,100);
DockTipPage.GetInstance():PushGsid(888,10);
--]]
local KeepWorkItemManager = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/KeepWorkItemManager.lua");
local DockPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/Dock/DockPage.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/game_logic.lua");
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local DockTipPage = NPL.export();
DockTipPage.timer = nil;
DockTipPage.node_list = {};
DockTipPage.page_name = "DockTipPage.ShowPage";
DockTipPage.page_ctrl = nil;
DockTipPage.page_file = "script/apps/Aries/Creator/Game/Tasks/Dock/DockTipPage.html";
DockTipPage.cur_interval = 0;
DockTipPage.interval = 100;
DockTipPage.duration = 5000;
DockTipPage.timer_enabled = false;
DockTipPage.instance_map = {};
function DockTipPage.GetInstance(name)
name = name or "docktippage_instance";
if(not DockTipPage.instance_map[name])then
DockTipPage.instance_map[name] = DockTipPage:new()
end
return DockTipPage.instance_map[name];
end
function DockTipPage:new (o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
o:OnInit();
return o
end
function DockTipPage:GetParams(name)
if(not name)then return end
local k,v;
for k,v in ipairs(self.pos_list) do
if(v.name == name)then
return v;
end
end
end
function DockTipPage:OnInit_GetPageCtrl()
self.page = document:GetPageCtrl();
end
function DockTipPage:ChangeWorld()
if(self.timer)then
self.timer:Change(0, self.interval);
end
self.is_showing_node = false;
end
function DockTipPage:GetNodeList()
return self.node_list;
end
function DockTipPage:GetUserName()
local User = commonlib.gettable("System.User")
return User.username or "";
end
function DockTipPage:OnInit()
self:ChangeWorld();
if(self.is_init)then
return
end
self.is_init = true;
self.timer = commonlib.Timer:new();
self.timer.callbackFunc = DockTipPage.TimerCallBack;
self.node_list = {};
self.pending_gsid_list = {};
self.pos_list = {
{name = "bag", label = "背包", x = -130, y = -5, title="你获得了新物品!", },
}
local key = string.format("DockTipPage:SetActiveTimer_%s",DockTipPage:GetUserName());
self.timer_enabled = GameLogic.GetPlayerController():LoadLocalData(key, false);
self.timer:Change(0, self.interval);
end
function DockTipPage:IsVisible()
if(self.page)then
return self.page:IsVisible();
end
end
function DockTipPage:RemoveTopNode()
local len = #self.node_list;
local node = self.node_list[1];
if(node)then
table.remove(self.node_list,1);
end
self:HideTip();
return node;
end
function DockTipPage:ShowTopNode()
self:HideTip();
self:BubbleTip();
end
function DockTipPage:HideTip()
if(self.page)then
self.page:CloseWindow();
self.page = nil;
end
end
function DockTipPage:BubbleTip()
local node = self:GetFirstNode();
if(not node or not node.name)then return end
local name = node.name;
local params = self:GetParams(name);
if(params)then
local obj = DockPage.FindUIControl(name);
local x = 0;
local y = 0;
if(obj and obj:IsValid())then
local obj_x, obj_y, screen_width, screen_height = obj:GetAbsPosition();
x = obj_x + params.x;
y = obj_y + params.y;
end
self:CreatePage(x,y,name);
end
end
function DockTipPage:DoAction(node)
if(node) then
local onclick_func = node.onclick;
local gsid = node.gsid;
if(onclick_func and DockTipPage[onclick_func])then
DockTipPage[onclick_func](gsid, node);
end
end
end
-- called periodically
function DockTipPage.TimerCallBack(timer)
if(DockTipPage.instance_map)then
local k,dock_tip;
for k,dock_tip in pairs(DockTipPage.instance_map) do
local max_duration = 3000;
local pending_time = dock_tip.pending_time or 0
pending_time = pending_time + dock_tip.interval;
if(pending_time >= max_duration)then
dock_tip:CheckAllPendingGsids();
dock_tip.pending_time = 0
else
dock_tip.pending_time = pending_time;
end
if(not dock_tip:HasChildren())then
return
end
local can_show = dock_tip:CheckCanShow();
if(can_show)then
if(not dock_tip.is_showing_node)then
dock_tip.cur_interval = 0;
dock_tip:ShowTopNode();
dock_tip.is_showing_node = true;
else
dock_tip.cur_interval = dock_tip.cur_interval + dock_tip.interval;
if(dock_tip.cur_interval >= dock_tip.duration)then
if(dock_tip.timer_enabled)then
dock_tip.is_showing_node = false;
local node = dock_tip:RemoveTopNode();
dock_tip:DoAction(node);
end
end
end
--逻辑显示 但是窗口没有显示
if(dock_tip.is_showing_node and not dock_tip:IsVisible())then
dock_tip:ShowTopNode();
end
else
dock_tip:HideTip();
end
end
end
end
function DockTipPage:SetActiveTimer()
if(self.timer_enabled)then
self.timer_enabled = false;
else
self.timer_enabled = true
if(self.is_showing_node)then
self.cur_interval = 0;
end
end
local key = string.format("DockTipPage:SetActiveTimer_%s",DockTipPage:GetUserName());
GameLogic.GetPlayerController():SaveLocalData(key, self.timer_enabled);
end
function DockTipPage:TimerIsEnabled()
return self.timer_enabled;
end
--检查窗口是否在显示,如果显示,隐藏DockTipPage
function DockTipPage:CheckCanShow()
return DockPage.IsShow();
end
function DockTipPage:GetTipCount()
return #self.node_list;
end
function DockTipPage:__PushNode(node)
if(not node or node.animation_only)then return end
local gsid = node.gsid;
table.insert(self.node_list,node);
end
function DockTipPage:PushNode(node)
if(not node)then return end
if(not self.is_init)then
return
end
self:__PushNode(node);
end
function DockTipPage:Manual_RemoveFirstNode()
self.is_showing_node = false;
self:RemoveTopNode();
end
function DockTipPage:GetFirstNode()
return self.node_list[1];
end
function DockTipPage:HasChildren()
local len = #self.node_list;
if(len > 0)then
return true;
end
end
function DockTipPage:DeleteNodeByName(name)
if(not name)then return end
local node = self:GetFirstNode();
if(node and node.name and node.name == name)then
table.remove(self.node_list,1);
end
end
function DockTipPage:ShowPage()
end
function DockTipPage:CreatePage(x,y,name)
local url = string.format("%s?name=%s",self.page_file,name or "");
local params = {
url = url,
name = self.page_name,
app_key=MyCompany.Aries.app.app_key,
isShowTitleBar = false,
DestroyOnClose = true, -- prevent many ViewProfile pages staying in memory
style = CommonCtrl.WindowFrame.ContainerStyle,
zorder = 1,
enable_esc_key = false,
isTopLevel = false,
allowDrag = false,
click_through = true, -- allow clicking through
directPosition = true,
align = "_lt",
x = x ,
y = y - 100,
width = 200,
height = 100,
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
end
function DockTipPage:BuildTag(gsid,tag)
if(not gsid)then
return
end
if(tag)then
return tag;
end
end
function DockTipPage:RemovePendingGsid(gsid)
if(not gsid)then
return
end
local k,v;
for k,v in ipairs(self.pending_gsid_list) do
if(v.gsid == gsid)then
table.remove(self.pending_gsid_list,k);
end
end
end
function DockTipPage:CheckAllPendingGsids()
local len = #self.pending_gsid_list;
if(len > 0)then
LOG.std("", "info","before DockTipPage:CheckAllPendingGsids one time");
end
while(len > 0)do
local node = self.pending_gsid_list[len];
if(node)then
local check_times = node.check_times or 0;
local gsid = node.gsid;
local count = node.count;
local tag = node.tag;
--尝试3次
if(check_times < 3)then
LOG.std("", "info","DockTipPage:CheckAllPendingGsids",node);
local bHas = KeepWorkItemManager.HasGSItem(gsid);
LOG.std("", "info","bHas",bHas);
self:PushGsid(gsid, count, tag);
check_times = check_times + 1;
node.check_times = check_times;
else
LOG.std("", "info","DockTipPage:CheckAllPendingGsids delete node",node);
table.remove(self.pending_gsid_list,len);
end
end
len = len - 1;
end
if(len > 0)then
LOG.std("", "info","after DockTipPage:CheckAllPendingGsids one time");
end
end
function DockTipPage:GetPendingNode(gsid)
if(not gsid)then
return
end
local k,v;
for k,v in ipairs(self.pending_gsid_list) do
if(v.gsid == gsid)then
return v;
end
end
end
function DockTipPage:PushToPendingList(gsid,tag)
if(not gsid)then
return
end
local node = self:GetPendingNode(gsid);
if(node)then
return
else
table.insert(self.pending_gsid_list,{
gsid = gsid,
tag = tag,
check_times = 0,
});
end
end
function DockTipPage:PushGsid(gsid, count, tag)
if(not self.is_init)then
return
end
if(not DockTipPage.CanPush(gsid))then
return
end
count = count or 1;
LOG.std("", "info","DockTipPage:PushGsid",{gsid = gsid, count = count, });
local node = { name = "bag", gsid = gsid, count = count, title = L"你获得了新物品!", animation_only = false};
self:PushNode(node);
end
function DockTipPage.CanPush(gsid)
if(not gsid)then
return
end
local UserBagPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/User/UserBagPage.lua");
local itemTemplate = KeepWorkItemManager.GetItemTemplate(gsid);
if(not itemTemplate)then
return
end
for k,bagId in ipairs(UserBagPage.accepted_bags) do
if(itemTemplate.bagId == bagId)then
return true;
end
end
end
| gpl-2.0 |
tempbottle/openlua | src/prototype.lua | 2 | 11570 | require("common.lua")
require("list.lua")
require("set.lua")
--[[---------------------------------------------------
Rightside prototype inherits List
--]]---------------------------------------------------
Rightside = List{}
Rightside.__concat = List.__concat
Rightside.__unm = List.__unm
Rightside.__le = List.__le
Rightside.__lt = List.__lt
Rightside.__eq = List.__eq
Rightside.__index = Rightside
Rightside.__call = List.__call
function Rightside.New(t)
local o = List.New(t)
setmetatable(o,Rightside)
return o
end
function Rightside:Serialize(outfile,sep)
outfile:write("Rightside")
self:WriteContent(outfile,sep)
end
--[[---------------------------------------------------
Rightside prototype definition end
--]]---------------------------------------------------
--[[---------------------------------------------------
Production prototype definition
prototype Production
{
string [_ls] --²úÉúʽ×ó²¿
Rightside [_rs] --²úÉúʽÓÒ²¿
}
--]]---------------------------------------------------
local _ls = {}
local _rs = {}
Production = {}
Production.__index = Production
function Production.New(t)
local prod = { [_ls] = t[1],[_rs] = t[2] }
setmetatable(prod,Production)
return prod
end
function Production.__call(t,...)
return t.New(arg[1])
end
function Production:GetLeftside()
return self[_ls]
end
function Production:GetRightside()
return self[_rs]
end
function Production.__eq(this,other)
if rawequal(this,other) then
return true
end
return this[_ls] == other[_ls]
and this[_rs] == other[_rs]
end
function Production:WriteContent(outfile,sep)
outfile:write("{")
local sep = sep or ", "
outfile:write('"',self[_ls],'"',sep)
self[_rs]:Serialize(outfile)
outfile:write("}")
end
function Production:Serialize(outfile,sep)
outfile:write("Production")
self:WriteContent(outfile,sep)
end
function Production:Print(sep)
self:Serialize(io.output(),sep)
io.output():write("\n")
end
setmetatable(Production,primogenitor_mt)
--[[---------------------------------------------------
Production prototype definition end
--]]---------------------------------------------------
--[[----------------------------------------------
prototype Item
{
private:
Production [_prod] --²úÉúʽ
number [_dotpos] --·Ö¸ôµãµÄλÖÃ
}
--]]----------------------------------------------
local _prod = {}
Item = {}
Item.__index = Item
local _dotpos = {}
function Item.New(ls,rs)
local item = { [_prod] = Production{ls,rs}, [_dotpos] = 1 }
setmetatable(item,Item)
return item
end
function Item:DotPos()
return self[_dotpos]
end
function Item:GetLeftside()
return self[_prod]:GetLeftside()
end
function Item:GetRightside()
return self[_prod]:GetRightside()
end
function Item:GetProduction()
return self[_prod]
end
function Item:NextSymbol()
local ns = self:GetRightside():Get(self:DotPos())
if "empty" == ns then
--self:Print()
return
else
return ns
end
end
function Item:Goto(symbol)
assert(symbol)
assert("empty" ~= symbol)
if self:NextSymbol() ~= symbol then
return nil
end
local newitem = self.New(self:GetLeftside(),self:GetRightside())
newitem[_dotpos] = self:DotPos() + 1
return newitem
end
function Item.__eq(this,other)
if rawequal(this,other) then
return true
end
return this[_prod] == other[_prod]
and this[_dotpos] == other[_dotpos]
end
function Item:WriteContent(outfile,sep)
outfile:write("{")
local sep = sep or ", "
self[_prod]:Serialize(outfile)
outfile:write(sep)
outfile:write(self:DotPos())
outfile:write("}")
end
function Item:Serialize(outfile,sep)
outfile:write("Item")
self:WriteContent(outfile,sep)
end
function Item:Print(sep)
self:Serialize(io.output(),sep)
io.output():write("\n")
end
--clear the keys of private data
local _dotpos = nil
--[[----------------------------------------------
prototype Item end
--]]----------------------------------------------
--[[-------------------------------------------
prototype ParseTable definition
--]]-------------------------------------------
ParseTable = {}
ParseTable.__index = ParseTable
local _data = {}
function ParseTable.New()
local res = { [_data] = {} }
setmetatable(res,ParseTable)
return res
end
function ParseTable:Get(i1,i2)
if self[_data][i1] then
return self[_data][i1][i2]
end
return nil
end
function ParseTable:Add(i1,i2,value)
if self[_data][i1] then
if self[_data][i1][i2] then
self[_data][i1][i2]:Add(value)
else
self[_data][i1][i2] = Set{value}
end
else
self[_data][i1] = { [i2] = Set{value} }
end
end
function ParseTable:TraverseRows()
return pairs(self[_data])
end
--clear the keys of private data
local _data = nil
--[[---------------------------------------------------
prototype ParseTable end
--]]---------------------------------------------------
--[[---------------------------------------------------
prototype Symbol definition
prototype Symbol
{
public:
number open_line -- symbol¿ªÊ¼µÄÐÐÊý
number close_line -- symbol½áÊøµÄÐÐÊý
List children -- Èç¹ûsymbolÊÇ·ÇÖÕ½á·û£¬¸Ã×ֶα£´æµÄÊÇ×é³ÉËüµÄ×Ósymbols
private:
string type -- symbolµÄÀàÐÍ£¬¶ÔÓÚ·ÇÖÕ½á·ûÀ´Ëµ£¬¾ÍÊÇËüÃǵÄÃû×Ö£¬
-- ¶ÔÓÚÖÕ½á·ûÀ´Ëµ£¬·Ökeymark(°üÀ¨¹Ø¼ü×Ö¡¢²Ù×÷·û¡¢±êµã·ûºÅºÍempty)¡¢
-- Name¡¢Number¡¢Literal
void value -- ¸ù¾ÝsymbolµÄÀàÐÍ´æ´¢µÄsymbolÖµ
}
--]]---------------------------------------------------
Symbol = {}
Symbol.__index = Symbol
local _type = {}
local _value = {}
function Symbol.New(t)
local symbol = {
[_type] = t[1],
[_value] = t[2],
open_line = t[3] or 0,
close_line = t[4] or 0 }
setmetatable(symbol,Symbol)
return symbol
end
function Symbol:type()
return self[_type]
end
function Symbol:name()
local t = self[_type]
if "keymark" == t then
return self[_value]
else
return t
end
end
function Symbol:value()
return self[_value]
end
function Symbol:empty()
return "keymark" == self[_type] and "empty" == self[_value]
or "keymark" == self:get_child(1):type() and "empty" == self:get_child(1):value()
end
function Symbol:has_children()
return nil ~= self.children
end
function Symbol:get_child(childNo)
if self.children then
return self.children:Get(childNo)
end
return nil
end
function Symbol:children_count()
if self.children then
return self.children:Count()
end
return 0
end
function Symbol:last_order_foreach(predict, operation)
local children = self.children
if nil ~= children then
for _,node in children:Traverse() do
node:last_order_foreach(predict,operation)
end
end
if predict(self) then
operation(self)
end
end
function Symbol:first_order_foreach(predict, operation)
if predict(self) then
operation(self)
end
local children = self.children
if nil ~= children then
for _,node in children:Traverse() do
node:first_order_foreach(predict,operation)
end
end
end
function Symbol:foreach(op_before_subtree, op_after_subtree)
if op_before_subtree then
op_before_subtree(self)
end
local children = self.children
if nil ~= children then
for _,node in children:Traverse() do
node:foreach(op_before_subtree,op_after_subtree)
end
end
if op_after_subtree then
op_after_subtree(self)
end
end
function Symbol:emit()
local str = ""
local children = self.children
if nil ~= children then
local nodestr
for _,node in children:Traverse() do
nodestr = node:emit()
if "" ~= nodestr and "" ~= str then
str = str.." "..nodestr
else
str = str..nodestr
end
end
if "stat" == self:type()
or "metastat" == self:type()
or "field" == self:type() then
str = str.."\n"
end
return str
elseif "Literal" == self:type() then
return string.format("%q",self:value())
elseif "keymark" == self:type()
and "empty" == self:value() then
--do nothing
return ""
else
return self:value()
end
end
local newlineKeymarks = Set{"end","else","elseif", "until", "}" }
local indent_spaces = 4
function Symbol:format(indent)
local str = ""
indent = indent or 0
local indentStr = string.rep(" ",indent)
if "keymark" == self:type() then
local code = ""
if "empty" == self:value() then
code = ""
else
if newlineKeymarks:Contains(self:value()) then
code = indentStr..self:value()
else
code = self:value()
end
if "{" == self:value() then
code = "{\n"
elseif "}" == self:value() then
code = "\n"..code
end
end
return code
end
if "stat" == self:type()
or "field" == self:type() then
str = indentStr
end
local children = self.children
if nil ~= children then
local nodestr
for _,node in children:Traverse() do
if "block" == node:type() then
nodestr = node:format(indent + indent_spaces)
if "" ~= nodestr then
nodestr = "\n"..nodestr
end
elseif "optional_fieldlist" == node:type() then
nodestr = node:format(indent + indent_spaces)
-- if "" ~= nodestr then
-- nodestr = nodestr
-- end
else
nodestr = node:format(indent)
end
if "" ~= nodestr and not IsSpaceStr(str)
and "\n" ~= string.sub(str,-1) then
str = str.." "..nodestr
else
str = str..nodestr
end
end
if "stat_sep" == self:type()
or "fieldsep" == self:type() then
str = str.."\n"
end
return str
elseif "Literal" == self:type() then
return str..string.format("%q",self:value())
else
return self:value()
end
end
function Symbol.__call(t,...)
return t.New(arg[1])
end
function Symbol.__eq(this,other)
if rawequal(this,other) then
return true
end
return this[_type] == other[_type]
and this[_value] == other[_value]
end
function Symbol:WriteContent(outfile,sep)
outfile:write("{")
local sep = sep or ", "
outfile:write('"',self[_type],'"')
if nil == self[_value] then
--
outfile:write(', nil')
elseif "string" == type(self[_value]) then
outfile:write(', ','"',self[_value],'"')
else
outfile:write(', ',self[_value])
end
outfile:write(', ',self.open_line,', ',self.close_line)
outfile:write("}")
end
function Symbol:Serialize(outfile,sep)
outfile:write("Symbol")
self:WriteContent(outfile,sep)
end
function Symbol:Print(sep)
self:Serialize(io.output(),sep)
io.output():write("\n")
end
setmetatable(Symbol,primogenitor_mt)
-- clear
local _type = nil
local _value = nil
--[[---------------------------------------------------
Symbol prototype definition end
--]]---------------------------------------------------
--[[---------------------------------------------------
IStream prototype definition
ÓÉ×Ö·û´®¹¹³ÉµÄÊäÈëÁ÷ÀàÐÍ
--]]---------------------------------------------------
IStream = {}
IStream.__index = IStream
function IStream.New(data)
local stream = {data = data[1],pos = 1}
if "string" ~= type(data[1]) then
-- should never be here
assert(false)
end
setmetatable(stream,IStream)
return stream
end
function IStream:lines()
local function iter()
local line,endpos
_,endpos,line = string.find(self.data,"([^\n]*)\n",self.pos)
if nil ~= endpos then
self.pos = endpos + 1
else
_,_,line = string.find(self.data,"(.+)",self.pos)
self.pos = string.len(self.data) + 1
end
return line
end
return iter
end
function IStream:read()
local line,endpos
_,endpos,line = string.find(self.data,"([^\n]*)\n",self.pos)
if nil ~= endpos then
self.pos = endpos + 1
else
_,_,line = string.find(self.data,"(.+)",self.pos)
self.pos = string.len(self.data) + 1
end
return line
end
setmetatable(IStream,primogenitor_mt)
--[[---------------------------------------------------
IStream prototype definition end
--]]--------------------------------------------------- | mit |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Code/HaqiDef/Haqi.lua | 1 | 3359 | --[[
Title: Haqi
Author(s): LiXizhi
Date: 2020/4/7
Desc: Haqi Code block
use the lib:
-------------------------------------------------------
local Haqi = NPL.load("(gl)script/apps/Aries/Creator/Game/Code/HaqiDef/Haqi.lua");
-------------------------------------------------------
]]
local CodeBlockWindow = commonlib.gettable("MyCompany.Aries.Game.Code.CodeBlockWindow");
local Files = commonlib.gettable("MyCompany.Aries.Game.Common.Files");
local CodeCompiler = commonlib.gettable("MyCompany.Aries.Game.Code.CodeCompiler");
local Haqi = NPL.export();
commonlib.setfield("MyCompany.Aries.Game.Code.Haqi.Haqi", Haqi);
local is_installed = false;
local all_cmds = {};
local all_cmds_map = {};
Haqi.categories = {
{name = "arena", text = "法阵", colour = "#0078d7", },
{name = "Control", text = L"控制", colour="#d83b01", },
{name = "Data", text = L"数据", colour="#459197", },
};
function Haqi.GetCategoryButtons()
return Haqi.categories;
end
function Haqi.AppendAll()
if(is_installed)then
return
end
is_installed = true;
local all_source_cmds = {
NPL.load("./HaqiDef_Arena.lua"),
}
for k,v in ipairs(all_source_cmds) do
Haqi.AppendDefinitions(v);
end
end
function Haqi.AppendDefinitions(source)
if(source)then
for k,v in ipairs(source) do
table.insert(all_cmds,v);
all_cmds_map[v.type] = v;
end
end
end
function Haqi.GetAllCmds()
Haqi.AppendAll();
return all_cmds;
end
-- custom compiler here:
-- @param codeblock: code block object here
function Haqi.CompileCode(code, filename, codeblock)
code = Haqi.GetCode(code);
local compiler = CodeCompiler:new():SetFilename(filename)
if(codeblock and codeblock:GetEntity() and codeblock:GetEntity():IsAllowFastMode()) then
compiler:SetAllowFastMode(true);
end
return compiler:Compile(code);
end
-- @param relativePath: can be nil, in which case filepath will be used.
function Haqi.GetCode(code)
if(not Haqi.templateCode) then
Haqi.templateCode = [[
local Haqi = NPL.load("(gl)script/apps/Aries/Creator/Game/Code/HaqiDef/Haqi.lua")
local HaqiAPI = NPL.load("(gl)script/apps/Aries/Creator/Game/Code/HaqiDef/HaqiAPI.lua")
local api = HaqiAPI:new():Init(codeblock:GetCodeEnv())
hide()
<code>
if(isArenaModified()) then
wait(1)
restart()
api:addIncludeFiles();
end
]]
Haqi.templateCode = Haqi.templateCode:gsub("(\r?\n)", ""):gsub("<code>", "%%s")
end
local s = string.format(Haqi.templateCode, code or "");
return s
end
function Haqi.OnClickLearn()
-- ParaGlobal.ShellExecute("open", L"https://keepwork.com/pbl/project/852/", "", "", 1);
end
function Haqi.OnClickRestartServer()
local HaqiAPI = NPL.load("(gl)script/apps/Aries/Creator/Game/Code/HaqiDef/HaqiAPI.lua");
HaqiAPI.restart();
end
-- custom toolbar UI's mcml on top of the code block window. return nil for default UI.
-- return nil or a mcml string.
function Haqi.GetCustomToolbarMCML()
Haqi.toolBarMcmlText = Haqi.toolBarMcmlText or string.format([[
<div style="float:left;margin-left:5px;margin-top:7px;">
<input type="button" value='%s' tooltip='%s' name='restart' onclick="MyCompany.Aries.Game.Code.CodeBlockWindow.OnChangeModel" style="margin-top:0px;background:url(Texture/whitedot.png);background-color:#808080;color:#ffffff;height:25px;min-width:20px;" />
</div>
]], L"角色模型", L"也可以通过电影方块编辑");
return Haqi.toolBarMcmlText;
end | gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/Quest/QuestSpecialCourse.lua | 1 | 15067 | --[[
Title: QuestSpecialCourse
Author(s): yangguiyi
Date: 2021/01/28
Desc:
Use Lib:
-------------------------------------------------------
local QuestSpecialCourse = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/Quest/QuestSpecialCourse.lua");
QuestSpecialCourse.Show();
--]]
local QuestSpecialCourse = NPL.export();
local HttpWrapper = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/HttpWrapper.lua");
-- local QuestProvider = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/Quest/QuestProvider.lua");
local QuestProvider = commonlib.gettable("MyCompany.Aries.Game.Tasks.Quest.QuestProvider");
local KeepWorkItemManager = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/KeepWorkItemManager.lua");
local pe_gridview = commonlib.gettable("Map3DSystem.mcml_controls.pe_gridview");
local ParacraftLearningRoomDailyPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/ParacraftLearningRoom/ParacraftLearningRoomDailyPage.lua");
local DailyTaskManager = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/DailyTask/DailyTaskManager.lua");
local TaskIdList = DailyTaskManager.GetTaskIdList()
local QuestAction = commonlib.gettable("MyCompany.Aries.Game.Tasks.Quest.QuestAction");
local QuestRewardPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/Quest/QuestRewardPage.lua");
local VipToolNew = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/VipToolTip/VipToolNew.lua")
local page;
QuestSpecialCourse.isOpen = false
QuestSpecialCourse.TaskData = {}
QuestSpecialCourse.is_add_event = false
QuestSpecialCourse.begain_time_t = {year=2021, month=1, day=28, hour=0, min=0, sec=0}
QuestSpecialCourse.begain_exid = 40028
QuestSpecialCourse.end_exid = 40030
QuestSpecialCourse.GiftState = {
can_not_get = 0, --未能领取
can_get = 1, --可领取
has_get = 2, --已领取
}
QuestSpecialCourse.TaskState = {
can_go = 0,
has_go = 1,
can_not_go = 2,
}
QuestSpecialCourse.CourseData = {}
QuestSpecialCourse.CourseTimeLimit = {
{begain_time = {hour=10,min=30}, end_time = {hour=10,min=45}},
{begain_time = {hour=13,min=30}, end_time = {hour=13,min=45}},
{begain_time = {hour=16,min=0}, end_time = {hour=16,min=15}},
{begain_time = {hour=18,min=0}, end_time = {hour=18,min=15}},
{begain_time = {hour=19,min=0}, end_time = {hour=19,min=15}},
}
QuestSpecialCourse.ToCourseState = {
before = 0, -- 提前
in_time = 1, -- 课程时间内
late = 2, -- 迟到
finish = 3, -- 今日课程结束
}
local VersionToKey = {
ONLINE = 1,
RELEASE = 2,
LOCAL = 3,
}
local ProInitData = {}
local TargetProgerssValue = 60
local MaxProgressValue = 100
local RewardNums = 5
local modele_bag_id = 0
local server_time = 0
local today_weehours = 0
function QuestSpecialCourse.OnInit()
page = document:GetPageCtrl();
page.OnClose = QuestSpecialCourse.CloseView
page.OnCreate = QuestSpecialCourse.OnCreate()
end
function QuestSpecialCourse.OnCreate()
end
-- is_make_up 是否补课面板
function QuestSpecialCourse.Show(is_make_up)
QuestSpecialCourse.is_make_up = is_make_up
if(not GameLogic.GetFilters():apply_filters('is_signed_in'))then
return
end
QuestSpecialCourse.ShowView()
end
function QuestSpecialCourse.RefreshData()
if not QuestSpecialCourse.IsVisible() then
return
end
QuestSpecialCourse.HandleTaskData()
QuestSpecialCourse.HandleCourseData()
QuestSpecialCourse.OnRefreshGridView()
end
function QuestSpecialCourse.ShowView()
if page and page:IsVisible() then
page:CloseWindow()
-- QuestSpecialCourse.CloseView()
end
QuestSpecialCourse.HandleTaskData()
QuestSpecialCourse.HandleCourseData()
if not QuestSpecialCourse.is_add_event then
QuestProvider:GetInstance():AddEventListener(QuestProvider.Events.OnRefresh,function()
if not page or not page:IsVisible() then
return
end
QuestSpecialCourse.RefreshData()
end, nil, "QuestSpecialCourse_Event_Init")
QuestProvider:GetInstance():AddEventListener(QuestProvider.Events.OnFinished,function(__, event)
if not page or not page:IsVisible() then
return
end
end, nil, "QuestSpecialCourse_OnFinished")
QuestSpecialCourse.is_add_event = true
end
local bagNo = 1007;
for _, bag in ipairs(KeepWorkItemManager.bags) do
if (bagNo == bag.bagNo) then
modele_bag_id = bag.id;
break;
end
end
QuestSpecialCourse.isOpen = true
local view_width = 960
local view_height = 480
local params = {
url = "script/apps/Aries/Creator/Game/Tasks/Quest/QuestSpecialCourse.html",
name = "QuestSpecialCourse.Show",
isShowTitleBar = false,
DestroyOnClose = true,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = true,
enable_esc_key = true,
zorder = 0,
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
directPosition = true,
align = "_ct",
x = -view_width/2,
y = -view_height/2,
width = view_width,
height = view_height,
isTopLevel = true
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
end
function QuestSpecialCourse.IsVisible()
if page == nil then
return false
end
return page:IsVisible()
end
function QuestSpecialCourse.OnRefreshGridView()
-- if(page)then
-- page:Refresh(0);
-- end
local gvw_name = "item_gridview";
local node = page:GetNode(gvw_name);
pe_gridview.DataBind(node, gvw_name, false);
end
function QuestSpecialCourse.CloseView()
QuestSpecialCourse.isOpen = false
local file_fold_name = "Texture/Aries/Creator/keepwork/Quest/"
local Files = commonlib.gettable("MyCompany.Aries.Game.Common.Files");
Files:UnloadFoldAssets(file_fold_name);
end
function QuestSpecialCourse.EnterWorld(world_id)
page:CloseWindow()
QuestSpecialCourse.CloseView()
local CommandManager = commonlib.gettable("MyCompany.Aries.Game.CommandManager")
CommandManager:RunCommand(string.format('/loadworld -force -s %s', world_id))
-- QuestSpecialCourse.RefreshData()
end
function QuestSpecialCourse.WeekWork()
local TeachingQuestLinkPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/User/TeachingQuestLinkPage.lua");
TeachingQuestLinkPage.ShowPage();
end
function QuestSpecialCourse.GetCompletePro(data)
local task_id = data.task_id or "0"
local task_data = DailyTaskManager.GetTaskData(task_id)
local complete_times = task_data.complete_times or 0
return complete_times .. "/" .. task_data.max_times
end
function QuestSpecialCourse.HandleTaskData(data)
QuestSpecialCourse.TaskData = {}
if QuestSpecialCourse.TaskAllData == nil then
local quest_datas = QuestProvider:GetInstance().templates_map
local exid_list = {}
QuestSpecialCourse.TaskAllData = {}
for i, v in pairs(quest_datas) do
-- 获取兑换规则
if exid_list[v.exid] == nil and v.exid >= QuestSpecialCourse.begain_exid and v.exid <= QuestSpecialCourse.end_exid then
exid_list[v.exid] = 1
local index = #QuestSpecialCourse.TaskAllData + 1
QuestSpecialCourse.TaskAllData[index] = v
end
end
table.sort(QuestSpecialCourse.TaskAllData,function(a,b)
return a.gsid < b.gsid
end)
end
local quest_datas = QuestProvider:GetInstance().templates_map
for i, v in pairs(QuestSpecialCourse.TaskAllData) do
-- 获取兑换规则
if QuestSpecialCourse.GetTaskVisible(v) then
local index = #QuestSpecialCourse.TaskData + 1
local task_data = {}
local exchange_data = KeepWorkItemManager.GetExtendedCostTemplate(v.exid)
local name = exchange_data.name
local desc = exchange_data.desc
task_data.name = name
task_data.task_id = v.exid
task_data.task_desc = desc
task_data.id = v.id
task_data.gsid = v.gsid
task_data.is_finish = QuestAction.IsFinish(v.gsid)
task_data.task_type = QuestSpecialCourse.GetTaskType(v)
task_data.is_main_task = task_data.task_type == "main"
task_data.goto_world = v.goto_world
task_data.click = v.click
task_data.task_pro_desc = QuestSpecialCourse.GetTaskProDescByQuest(v)
task_data.task_state = QuestSpecialCourse.GetTaskStateByQuest(task_data)
task_data.order = QuestSpecialCourse.GetTaskOrder(v)
task_data.bg_img = QuestSpecialCourse.GetBgImg(task_data)
task_data.goods_data = {}
QuestSpecialCourse.TaskData[index] = task_data
end
end
-- 主线任务在前
table.sort(QuestSpecialCourse.TaskData, function(a, b)
local value_a = 10000
local value_b = 10000
if a.is_main_task then
value_a = value_a + 10000
end
if b.is_main_task then
value_b = value_b + 10000
end
if a.task_type == "branch" then
value_a = value_a + 1000
end
if b.task_type == "branch" then
value_b = value_b + 1000
end
if a.task_type == "loop" then
value_a = value_a + 100
end
if b.task_type == "loop" then
value_b = value_b + 100
end
if a.order < b.order then
value_a = value_a + 10
end
if b.order < a.order then
value_b = value_b + 10
end
if a.task_id < b.task_id then
value_a = value_a + 1
end
if b.task_id < a.task_id then
value_b = value_b + 1
end
return value_a > value_b
end)
end
function QuestSpecialCourse.GetTaskProDescByQuest(data)
local value = QuestAction.GetValue(data.id) or 0
local finish_value = data.finished_value
local desc = string.format("进度:%s/%s", value, finish_value)
return desc
end
function QuestSpecialCourse.GetTaskOrder(data)
if data and data.order then
return tonumber(data.order)
end
return 0
end
function QuestSpecialCourse.GetTaskVisible(data)
local exid = data.exid
if exid < QuestSpecialCourse.begain_exid or exid > QuestSpecialCourse.end_exid then
return false
end
return true
end
function QuestSpecialCourse.GetTaskStateByQuest(data)
if data.task_id == QuestAction.is_always_exist_exid then
if not QuestSpecialCourse.IsGraduateTime(server_time) then
return QuestSpecialCourse.TaskState.can_not_go
end
return QuestSpecialCourse.TaskState.can_go
end
if data.is_finish then
return QuestSpecialCourse.TaskState.has_go
end
return QuestSpecialCourse.TaskState.can_go
end
function QuestSpecialCourse.GetBgImg(task_data)
local img = "Texture/Aries/Creator/keepwork/Quest/bjtiao2_226X90_32bits.png#0 0 226 90:195 20 16 20"
if QuestSpecialCourse.CheckIsMissClass(task_data) then
img = "Texture/Aries/Creator/keepwork/Quest/bjtiao_226X90_32bits.png#0 0 226 90:195 20 16 20"
end
return img
end
function QuestSpecialCourse.HandleCourseData()
local gift_state_list = QuestAction.GetGiftStateList()
QuestSpecialCourse.CourseData = {}
for i, v in ipairs(QuestSpecialCourse.TaskAllData) do
local data = {}
data.is_finish = QuestAction.IsFinish(v.gsid)
data.img = QuestSpecialCourse.GetIconImg(i, v)
-- data.number_img = QuestSpecialCourse.GetNumImg(v)
data.desc = string.format("第%s课", i)
if i == #QuestSpecialCourse.TaskAllData then
data.desc = "GOAL"
end
QuestSpecialCourse.CourseData[#QuestSpecialCourse.CourseData + 1] = data
end
end
function QuestSpecialCourse.GetIconImg(index, item)
-- 最后一个礼拜要做不同显示
if index == #QuestSpecialCourse.TaskAllData then
return "Texture/Aries/Creator/keepwork/Quest/boshimao_81X60_32bits.png#0 0 81 60"
end
return ""
end
function QuestSpecialCourse.GetNumImg(item)
local num = item.catch_value
return string.format("Texture/Aries/Creator/keepwork/Quest/zi_%s_23X12_32bits.png#0 0 23 12", num)
end
-- 这里的task_id 其实就是exid
function QuestSpecialCourse.GetReward(task_id)
local task_data = nil
for key, v in pairs(QuestSpecialCourse.TaskData) do
if v.task_id == task_id then
task_data = v
break
end
end
if nil == task_data then
return
end
-- local quest_data = QuestSpecialCourse.GetQuestData(task_data.task_id)
-- if quest_data == nil then
-- return
-- end
-- if task_data.task_type == "loop" then
-- local childrens = quest_data.questItemContainer.children or {}
-- for i, v in ipairs(childrens) do
-- QuestAction.FinishDailyTask(v.template.id)
-- end
-- QuestSpecialCourse.RefreshData()
-- else
-- if quest_data.questItemContainer then
-- quest_data.questItemContainer:DoFinish()
-- end
-- end
end
function QuestSpecialCourse.Goto(task_id)
local task_data = QuestSpecialCourse.GetQuestData(task_id)
if task_data == nil then
return
end
local httpwrapper_version = HttpWrapper.GetDevVersion() or "ONLINE"
local target_index = VersionToKey[httpwrapper_version]
if task_data.goto_world and #task_data.goto_world > 0 then
local world_id = task_data.goto_world[target_index]
if world_id then
QuestSpecialCourse.EnterWorld(world_id)
end
elseif task_data.click and task_data.click ~= "" then
if string.find(task_data.click, "loadworld ") then
page:CloseWindow()
QuestSpecialCourse.CloseView()
end
NPL.DoString(task_data.click)
end
GameLogic.GetFilters():apply_filters('user_behavior', 1, 'click.quest_action.click_go_button')
end
function QuestSpecialCourse.GetQuestData(task_id)
for i, v in ipairs(QuestSpecialCourse.TaskData) do
if v.task_id == task_id then
return v
end
end
end
function QuestSpecialCourse.GetTaskType(data)
return data.type
end
function QuestSpecialCourse.IsOpen()
if nil == page then
return false
end
return page:IsVisible()
end
function QuestSpecialCourse.IsRoleModel(item_data)
if item_data and item_data.bagId == modele_bag_id then
return true
end
return false
end
function QuestSpecialCourse.OnClikcGift(gift_data)
end
-- 获取今天是第几天
function QuestSpecialCourse.GetSecondDay(exid)
if exid == nil then
return 0
end
return exid - QuestSpecialCourse.begain_exid + 1
end
function QuestSpecialCourse.Close()
if nil == page then
return
end
page:CloseWindow()
QuestSpecialCourse.CloseView()
end
function QuestSpecialCourse.CheckCourseTimeState(cur_time_stamp)
local day_weehours = commonlib.timehelp.GetWeeHoursTimeStamp(cur_time_stamp)
for i, v in ipairs(QuestSpecialCourse.CourseTimeLimit) do
local begain_time_stamp = day_weehours + v.begain_time.min * 60 + v.begain_time.hour * 3600
local end_time_stamp = day_weehours + v.end_time.min * 60 + v.end_time.hour * 3600
if cur_time_stamp >= begain_time_stamp and cur_time_stamp <= end_time_stamp then
return QuestSpecialCourse.ToCourseState.in_time
end
if i == 1 and cur_time_stamp < begain_time_stamp then
return QuestSpecialCourse.ToCourseState.before
end
-- print("saaaaaaaaaaaaaa", i, #QuestSpecialCourse.CourseTimeLimit, cur_time_stamp, begain_time_stamp, cur_time_stamp > begain_time_stamp)
if i == #QuestSpecialCourse.CourseTimeLimit and cur_time_stamp > begain_time_stamp then
return QuestSpecialCourse.ToCourseState.finish
end
end
for i, v in ipairs(QuestSpecialCourse.CourseTimeLimit) do
local begain_time_stamp = day_weehours + v.begain_time.min * 60 + v.begain_time.hour * 3600
local end_time_stamp = day_weehours + v.end_time.min * 60 + v.end_time.hour * 3600
if cur_time_stamp < begain_time_stamp then
return QuestSpecialCourse.ToCourseState.late, v
end
end
return QuestSpecialCourse.ToCourseState.late
end
function QuestSpecialCourse.CheckIsMissClass(data)
return QuestSpecialCourse.is_make_up and not data.is_finish
end | gpl-2.0 |
RyMarq/Zero-K | LuaRules/Configs/StartBoxes/Altored_Arctic.lua | 8 | 18453 | return {
[0] = {
boxes = {
{
{1340, 3389},
{1335, 3399},
{1336, 3410},
{1342, 3420},
{1353, 3425},
{1363, 3428},
{1374, 3429},
{1385, 3431},
{1395, 3433},
{1407, 3434},
{1417, 3437},
{1456, 3449},
{1510, 3472},
{1540, 3487},
{1576, 3503},
{1601, 3512},
{1611, 3513},
{1622, 3516},
{1634, 3517},
{1645, 3518},
{1655, 3519},
{1666, 3521},
{1676, 3522},
{1687, 3522},
{1697, 3522},
{1796, 3521},
{1877, 3521},
{1924, 3518},
{1998, 3513},
{2073, 3505},
{2116, 3497},
{2158, 3493},
{2206, 3485},
{2244, 3478},
{2271, 3474},
{2282, 3473},
{2294, 3473},
{2323, 3471},
{2347, 3466},
{2392, 3447},
{2444, 3415},
{2457, 3401},
{2475, 3373},
{2490, 3344},
{2498, 3334},
{2507, 3323},
{2515, 3313},
{2526, 3303},
{2536, 3296},
{2546, 3292},
{2603, 3263},
{2645, 3242},
{2660, 3228},
{2663, 3218},
{2663, 3208},
{2660, 3185},
{2647, 3141},
{2642, 3130},
{2639, 3119},
{2623, 3060},
{2623, 3049},
{2622, 3038},
{2621, 3026},
{2623, 2982},
{2626, 2971},
{2630, 2960},
{2633, 2948},
{2637, 2936},
{2642, 2925},
{2645, 2914},
{2656, 2878},
{2658, 2867},
{2653, 2857},
{2643, 2841},
{2633, 2831},
{2623, 2822},
{2600, 2806},
{2590, 2802},
{2579, 2795},
{2568, 2790},
{2558, 2787},
{2547, 2782},
{2536, 2777},
{2526, 2771},
{2477, 2732},
{2455, 2704},
{2443, 2669},
{2446, 2623},
{2465, 2568},
{2485, 2534},
{2507, 2510},
{2537, 2493},
{2569, 2485},
{2596, 2485},
{2634, 2491},
{2669, 2498},
{2684, 2503},
{2758, 2545},
{2770, 2555},
{2788, 2581},
{2804, 2603},
{2819, 2617},
{2842, 2629},
{2884, 2641},
{2900, 2642},
{2927, 2634},
{2977, 2610},
{3022, 2596},
{3049, 2591},
{3070, 2592},
{3103, 2600},
{3125, 2610},
{3156, 2617},
{3191, 2621},
{3226, 2619},
{3247, 2615},
{3259, 2606},
{3272, 2589},
{3299, 2539},
{3312, 2522},
{3349, 2479},
{3355, 2461},
{3363, 2366},
{3376, 2289},
{3389, 2234},
{3397, 2194},
{3397, 2161},
{3395, 2129},
{3383, 2070},
{3348, 2006},
{3297, 1928},
{3271, 1887},
{3243, 1826},
{3212, 1771},
{3181, 1736},
{3147, 1702},
{3128, 1660},
{3110, 1615},
{3100, 1606},
{3089, 1604},
{3079, 1607},
{3069, 1609},
{3050, 1613},
{3029, 1615},
{2996, 1616},
{2986, 1615},
{2972, 1611},
{2955, 1602},
{2940, 1591},
{2920, 1570},
{2910, 1555},
{2888, 1513},
{2877, 1500},
{2853, 1496},
{2808, 1504},
{2732, 1525},
{2711, 1529},
{2653, 1532},
{2568, 1533},
{2538, 1523},
{2491, 1496},
{2449, 1487},
{2369, 1488},
{2336, 1485},
{2301, 1477},
{2269, 1462},
{2238, 1435},
{2221, 1405},
{2210, 1361},
{2208, 1338},
{2214, 1314},
{2219, 1267},
{2230, 1229},
{2234, 1200},
{2232, 1176},
{2222, 1145},
{2214, 1125},
{2203, 1078},
{2195, 1033},
{2194, 991},
{2197, 963},
{2224, 888},
{2237, 850},
{2238, 833},
{2225, 786},
{2215, 743},
{2202, 717},
{2183, 696},
{2164, 686},
{2148, 686},
{2069, 686},
{2023, 680},
{1993, 679},
{1963, 680},
{1927, 687},
{1874, 690},
{1795, 701},
{1740, 708},
{1678, 709},
{1631, 700},
{1549, 706},
{1453, 720},
{1397, 731},
{1329, 731},
{1294, 725},
{1242, 702},
{1191, 684},
{1181, 683},
{1170, 685},
{1160, 691},
{1157, 701},
{1162, 711},
{1187, 744},
{1206, 775},
{1221, 797},
{1240, 834},
{1249, 866},
{1259, 891},
{1262, 915},
{1256, 954},
{1247, 980},
{1208, 1031},
{1178, 1067},
{1140, 1100},
{1086, 1134},
{1050, 1159},
{1024, 1169},
{1000, 1173},
{951, 1171},
{913, 1169},
{879, 1174},
{840, 1182},
{821, 1183},
{792, 1177},
{750, 1177},
{709, 1173},
{695, 1175},
{678, 1185},
{665, 1199},
{657, 1215},
{658, 1230},
{671, 1252},
{699, 1293},
{726, 1343},
{755, 1429},
{759, 1469},
{744, 1569},
{706, 1653},
{701, 1666},
{701, 1682},
{703, 1709},
{701, 1749},
{702, 1779},
{689, 1931},
{682, 1955},
{662, 2007},
{657, 2035},
{663, 2074},
{678, 2115},
{694, 2141},
{732, 2165},
{755, 2176},
{771, 2174},
{813, 2140},
{849, 2100},
{912, 2049},
{948, 2037},
{984, 2035},
{1012, 2042},
{1028, 2051},
{1044, 2066},
{1053, 2086},
{1076, 2151},
{1085, 2170},
{1096, 2179},
{1153, 2202},
{1183, 2207},
{1226, 2218},
{1289, 2251},
{1349, 2303},
{1378, 2352},
{1409, 2437},
{1448, 2476},
{1469, 2501},
{1481, 2531},
{1485, 2590},
{1481, 2620},
{1476, 2643},
{1481, 2668},
{1475, 2722},
{1439, 2806},
{1434, 2833},
{1440, 2855},
{1552, 3035},
{1574, 3083},
{1580, 3119},
{1576, 3169},
{1550, 3216},
{1509, 3250},
{1459, 3274},
{1433, 3285},
{1414, 3301},
{1389, 3339},
{1359, 3368},
},
},
startpoints = {
{1647, 1802},
},
nameLong = "North-West",
nameShort = "NW",
},
[1] = {
boxes = {
{
{4818, 6471},
{4821, 6445},
{4816, 6390},
{4803, 6318},
{4803, 6294},
{4803, 6270},
{4796, 6236},
{4764, 6137},
{4747, 6048},
{4736, 6007},
{4701, 5943},
{4673, 5915},
{4641, 5862},
{4627, 5833},
{4630, 5800},
{4656, 5735},
{4689, 5689},
{4763, 5625},
{4829, 5558},
{4866, 5535},
{4899, 5530},
{4952, 5538},
{4995, 5547},
{5106, 5547},
{5145, 5540},
{5194, 5535},
{5236, 5531},
{5269, 5535},
{5296, 5545},
{5329, 5578},
{5380, 5628},
{5411, 5651},
{5441, 5663},
{5471, 5669},
{5548, 5665},
{5576, 5658},
{5649, 5628},
{5681, 5600},
{5710, 5561},
{5727, 5493},
{5726, 5458},
{5711, 5410},
{5683, 5367},
{5654, 5340},
{5616, 5322},
{5567, 5315},
{5533, 5305},
{5523, 5294},
{5522, 5284},
{5524, 5274},
{5525, 5258},
{5555, 5167},
{5557, 5143},
{5558, 5078},
{5561, 5038},
{5564, 5003},
{5561, 4973},
{5547, 4940},
{5532, 4901},
{5532, 4890},
{5544, 4875},
{5572, 4853},
{5594, 4839},
{5610, 4834},
{5670, 4825},
{5730, 4822},
{5759, 4821},
{5806, 4823},
{5844, 4816},
{5889, 4816},
{5991, 4799},
{6100, 4785},
{6172, 4770},
{6220, 4770},
{6286, 4775},
{6369, 4785},
{6431, 4786},
{6525, 4784},
{6574, 4795},
{6624, 4819},
{6711, 4874},
{6723, 4888},
{6723, 4911},
{6723, 4936},
{6727, 4973},
{6732, 4994},
{6745, 5015},
{6748, 5028},
{6741, 5039},
{6714, 5057},
{6688, 5081},
{6674, 5100},
{6671, 5138},
{6678, 5168},
{6699, 5198},
{6743, 5236},
{6760, 5261},
{6765, 5278},
{6762, 5298},
{6747, 5325},
{6735, 5353},
{6721, 5409},
{6714, 5453},
{6720, 5493},
{6722, 5531},
{6735, 5587},
{6750, 5636},
{6751, 5673},
{6745, 5747},
{6741, 5794},
{6748, 5831},
{6772, 5878},
{6804, 5910},
{6842, 5929},
{6919, 5934},
{6958, 5937},
{6971, 5945},
{6979, 5963},
{6986, 6005},
{6998, 6031},
{7026, 6050},
{7092, 6073},
{7128, 6076},
{7156, 6069},
{7194, 6039},
{7221, 6012},
{7252, 5966},
{7274, 5947},
{7294, 5940},
{7331, 5938},
{7365, 5932},
{7395, 5930},
{7432, 5929},
{7452, 5923},
{7466, 5922},
{7476, 5931},
{7500, 5999},
{7516, 6048},
{7527, 6074},
{7531, 6105},
{7523, 6142},
{7511, 6189},
{7504, 6222},
{7507, 6294},
{7514, 6361},
{7525, 6394},
{7539, 6425},
{7545, 6450},
{7544, 6466},
{7523, 6500},
{7510, 6533},
{7511, 6580},
{7519, 6626},
{7516, 6644},
{7480, 6686},
{7464, 6725},
{7467, 6791},
{7482, 6837},
{7496, 6855},
{7500, 6865},
{7493, 6876},
{7446, 6898},
{7410, 6933},
{7372, 6996},
{7358, 7040},
{7344, 7056},
{7258, 7092},
{7188, 7122},
{7139, 7156},
{7057, 7239},
{6955, 7348},
{6931, 7360},
{6909, 7352},
{6859, 7324},
{6806, 7306},
{6740, 7298},
{6696, 7304},
{6633, 7334},
{6588, 7359},
{6536, 7397},
{6517, 7415},
{6496, 7426},
{6477, 7419},
{6444, 7400},
{6363, 7387},
{6269, 7389},
{6191, 7392},
{6159, 7399},
{6134, 7397},
{6085, 7406},
{6050, 7419},
{6017, 7419},
{5996, 7406},
{5966, 7367},
{5956, 7336},
{5963, 7319},
{6030, 7267},
{6051, 7239},
{6067, 7191},
{6066, 7134},
{6050, 7083},
{6016, 7018},
{5960, 6943},
{5896, 6841},
{5862, 6780},
{5813, 6722},
{5748, 6694},
{5704, 6676},
{5656, 6670},
{5612, 6660},
{5535, 6631},
{5492, 6623},
{5456, 6635},
{5401, 6656},
{5367, 6671},
{5349, 6669},
{5326, 6651},
{5314, 6632},
{5299, 6589},
{5279, 6556},
{5252, 6529},
{5221, 6513},
{5139, 6492},
{5095, 6492},
{5053, 6499},
{5013, 6512},
{4966, 6544},
{4936, 6577},
{4906, 6632},
{4890, 6661},
{4853, 6688},
{4827, 6706},
{4797, 6712},
{4771, 6704},
{4761, 6685},
{4760, 6646},
{4786, 6577},
{4804, 6515},
},
},
startpoints = {
{6478, 6540},
},
nameLong = "South-East",
nameShort = "SE",
},
[2] = {
boxes = {
{
{1052, 7141},
{1003, 7085},
{981, 7051},
{910, 6999},
{864, 6975},
{845, 6953},
{820, 6920},
{787, 6876},
{778, 6840},
{792, 6794},
{818, 6732},
{818, 6685},
{795, 6635},
{751, 6604},
{727, 6585},
{694, 6519},
{701, 6486},
{724, 6450},
{755, 6411},
{767, 6355},
{786, 6302},
{814, 6261},
{825, 6207},
{815, 6108},
{817, 6059},
{824, 6015},
{836, 6009},
{863, 6011},
{896, 6015},
{945, 6004},
{1043, 5991},
{1094, 5987},
{1141, 5975},
{1190, 5948},
{1229, 5936},
{1253, 5938},
{1323, 5947},
{1377, 5944},
{1409, 5931},
{1445, 5889},
{1472, 5842},
{1476, 5791},
{1462, 5705},
{1468, 5687},
{1505, 5627},
{1524, 5595},
{1529, 5567},
{1530, 5514},
{1512, 5440},
{1495, 5369},
{1461, 5309},
{1440, 5273},
{1440, 5245},
{1460, 5192},
{1505, 5118},
{1540, 5040},
{1579, 4976},
{1605, 4932},
{1659, 4885},
{1695, 4868},
{1738, 4861},
{1778, 4865},
{1870, 4866},
{1962, 4874},
{2085, 4868},
{2143, 4857},
{2250, 4810},
{2331, 4776},
{2419, 4768},
{2469, 4760},
{2496, 4766},
{2533, 4789},
{2580, 4821},
{2600, 4838},
{2610, 4851},
{2611, 4861},
{2597, 4876},
{2557, 4906},
{2515, 4947},
{2489, 4988},
{2470, 5031},
{2461, 5106},
{2462, 5141},
{2474, 5175},
{2509, 5218},
{2548, 5237},
{2627, 5253},
{2651, 5263},
{2659, 5273},
{2659, 5284},
{2652, 5294},
{2642, 5303},
{2622, 5317},
{2594, 5326},
{2542, 5327},
{2509, 5333},
{2473, 5355},
{2457, 5373},
{2439, 5404},
{2425, 5460},
{2427, 5498},
{2450, 5557},
{2482, 5606},
{2526, 5636},
{2563, 5650},
{2632, 5657},
{2691, 5656},
{2753, 5631},
{2805, 5583},
{2847, 5539},
{2863, 5532},
{2881, 5533},
{2917, 5550},
{2954, 5574},
{2990, 5586},
{3054, 5595},
{3110, 5595},
{3153, 5585},
{3209, 5569},
{3267, 5549},
{3302, 5544},
{3332, 5544},
{3364, 5539},
{3409, 5529},
{3464, 5527},
{3498, 5529},
{3531, 5527},
{3541, 5530},
{3551, 5538},
{3551, 5548},
{3549, 5559},
{3548, 5570},
{3534, 5629},
{3521, 5661},
{3508, 5709},
{3503, 5740},
{3432, 5914},
{3408, 5948},
{3374, 6013},
{3335, 6085},
{3313, 6130},
{3301, 6177},
{3296, 6205},
{3304, 6259},
{3315, 6311},
{3315, 6358},
{3307, 6417},
{3305, 6440},
{3312, 6470},
{3326, 6509},
{3322, 6538},
{3305, 6583},
{3261, 6634},
{3236, 6651},
{3206, 6650},
{3162, 6631},
{3144, 6612},
{3138, 6583},
{3124, 6545},
{3101, 6519},
{3067, 6498},
{3034, 6492},
{2987, 6490},
{2951, 6494},
{2908, 6530},
{2884, 6573},
{2863, 6618},
{2847, 6671},
{2819, 6689},
{2769, 6690},
{2718, 6684},
{2655, 6662},
{2619, 6656},
{2573, 6665},
{2511, 6694},
{2430, 6715},
{2387, 6735},
{2332, 6783},
{2291, 6845},
{2278, 6888},
{2273, 6909},
{2251, 6941},
{2231, 6984},
{2223, 7025},
{2224, 7081},
{2237, 7205},
{2253, 7267},
{2254, 7292},
{2237, 7324},
{2189, 7386},
{2154, 7411},
{2120, 7448},
{2077, 7457},
{2025, 7466},
{2002, 7468},
{1934, 7465},
{1898, 7448},
{1882, 7414},
{1873, 7373},
{1847, 7339},
{1814, 7314},
{1775, 7306},
{1744, 7305},
{1719, 7318},
{1698, 7344},
{1653, 7399},
{1634, 7412},
{1623, 7412},
{1613, 7406},
{1603, 7395},
{1596, 7384},
{1564, 7349},
{1553, 7339},
{1541, 7336},
{1482, 7322},
{1431, 7324},
{1389, 7335},
{1324, 7346},
{1291, 7365},
{1248, 7400},
{1230, 7438},
{1213, 7458},
{1190, 7465},
{1168, 7458},
{1164, 7445},
{1173, 7379},
{1181, 7349},
{1180, 7313},
{1173, 7274},
{1160, 7248},
{1127, 7205},
{1077, 7167},
},
},
startpoints = {
{1790, 6466},
},
nameLong = "South-West",
nameShort = "SW",
},
[3] = {
boxes = {
{
{5474, 2461},
{5443, 2463},
{5409, 2481},
{5361, 2520},
{5327, 2563},
{5301, 2596},
{5282, 2608},
{5257, 2610},
{5224, 2602},
{5197, 2588},
{5184, 2572},
{5179, 2529},
{5177, 2499},
{5183, 2455},
{5187, 2357},
{5186, 2321},
{5180, 2277},
{5162, 2207},
{5146, 2166},
{5122, 2121},
{5098, 2079},
{5059, 2013},
{5039, 1979},
{5030, 1950},
{5019, 1923},
{5019, 1889},
{5027, 1836},
{5043, 1779},
{5072, 1702},
{5115, 1616},
{5144, 1543},
{5164, 1526},
{5207, 1500},
{5245, 1490},
{5280, 1492},
{5360, 1517},
{5398, 1531},
{5430, 1536},
{5479, 1527},
{5552, 1501},
{5616, 1492},
{5694, 1464},
{5739, 1452},
{5775, 1453},
{5803, 1458},
{5860, 1459},
{5904, 1447},
{5936, 1409},
{5950, 1372},
{5945, 1334},
{5930, 1303},
{5914, 1258},
{5906, 1223},
{5914, 1184},
{5939, 1113},
{5945, 1071},
{5945, 1029},
{5948, 999},
{5960, 926},
{5957, 901},
{5941, 873},
{5923, 846},
{5921, 827},
{5928, 804},
{5953, 758},
{5977, 685},
{5987, 669},
{6002, 653},
{6023, 648},
{6064, 650},
{6132, 659},
{6158, 669},
{6168, 684},
{6181, 716},
{6211, 758},
{6234, 774},
{6269, 781},
{6307, 778},
{6386, 747},
{6429, 702},
{6453, 684},
{6484, 678},
{6528, 686},
{6585, 711},
{6634, 733},
{6706, 735},
{6787, 713},
{6924, 687},
{6976, 689},
{7043, 701},
{7054, 710},
{7058, 731},
{7053, 774},
{7060, 811},
{7098, 903},
{7123, 935},
{7205, 992},
{7271, 1052},
{7330, 1116},
{7389, 1169},
{7410, 1188},
{7415, 1208},
{7411, 1230},
{7374, 1293},
{7362, 1324},
{7353, 1384},
{7352, 1437},
{7364, 1506},
{7387, 1540},
{7423, 1574},
{7475, 1597},
{7513, 1604},
{7540, 1614},
{7553, 1626},
{7555, 1639},
{7540, 1670},
{7535, 1693},
{7534, 1742},
{7541, 1767},
{7552, 1790},
{7548, 1802},
{7512, 1829},
{7498, 1852},
{7493, 1879},
{7496, 1914},
{7508, 1949},
{7537, 1994},
{7556, 2022},
{7559, 2036},
{7551, 2064},
{7521, 2140},
{7494, 2189},
{7477, 2208},
{7447, 2230},
{7416, 2236},
{7369, 2234},
{7341, 2232},
{7309, 2236},
{7290, 2232},
{7252, 2218},
{7227, 2206},
{7201, 2185},
{7192, 2158},
{7183, 2105},
{7171, 2079},
{7148, 2060},
{7107, 2048},
{7076, 2046},
{7059, 2048},
{7026, 2060},
{6996, 2079},
{6966, 2111},
{6950, 2143},
{6928, 2204},
{6915, 2232},
{6887, 2259},
{6853, 2284},
{6815, 2331},
{6786, 2385},
{6772, 2408},
{6755, 2421},
{6734, 2426},
{6692, 2437},
{6653, 2455},
{6625, 2477},
{6590, 2515},
{6565, 2562},
{6550, 2623},
{6551, 2680},
{6563, 2726},
{6585, 2764},
{6617, 2793},
{6650, 2808},
{6690, 2814},
{6723, 2824},
{6744, 2840},
{6750, 2854},
{6746, 2872},
{6712, 2923},
{6698, 2954},
{6691, 2995},
{6690, 3070},
{6698, 3112},
{6709, 3144},
{6741, 3197},
{6759, 3241},
{6771, 3282},
{6769, 3300},
{6759, 3317},
{6734, 3342},
{6670, 3376},
{6607, 3391},
{6550, 3398},
{6520, 3407},
{6455, 3410},
{6425, 3410},
{6355, 3423},
{6303, 3421},
{6210, 3411},
{6128, 3390},
{6039, 3384},
{5926, 3379},
{5818, 3370},
{5717, 3363},
{5617, 3364},
{5593, 3360},
{5576, 3347},
{5529, 3281},
{5514, 3242},
{5520, 3212},
{5553, 3151},
{5563, 3118},
{5560, 2951},
{5548, 2904},
{5535, 2875},
{5540, 2852},
{5558, 2833},
{5600, 2821},
{5647, 2814},
{5690, 2797},
{5731, 2763},
{5755, 2720},
{5761, 2678},
{5747, 2603},
{5721, 2548},
{5692, 2518},
{5645, 2505},
{5585, 2485},
{5531, 2463},
{5500, 2459},
},
},
startpoints = {
{6450, 1739},
},
nameLong = "North-East",
nameShort = "NE",
},
},
{2, 4}
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Network/TunnelService/LobbyRoomInfo.lua | 1 | 2425 | --[[
Title: LobbyRoomInfo
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Network/TunnelService/LobbyRoomInfo.lua");
local LobbyRoomInfo = commonlib.gettable("MyCompany.Aries.Game.Network.LobbyRoomInfo");
local room_info = LobbyRoomInfo:new():init(room_key)
-------------------------------------------------------
]]
local LobbyRoomInfo = commonlib.inherit(commonlib.gettable("System.Core.ToolBase"), commonlib.gettable("MyCompany.Aries.Game.Network.LobbyRoomInfo"));
LobbyRoomInfo:Property({"MaxClients", 8, "GetMaxClients", "SetMaxClients", auto=true});
function LobbyRoomInfo:ctor()
self._room_key = nil;
self._password = nil;
self._clients_count = 0;
self._users = {};
self._projectId = nil;
self._room_group = nil;
end
local next_room_key = 0;
-- static function
function LobbyRoomInfo:GenerateRoomKey()
next_room_key = next_room_key + 1;
return "room_" .. self._projectId .. "_" .. next_room_key;
end
-- @param room_key: if nil, we will dynamically generate a room key
function LobbyRoomInfo:Init(projectId, room_group, room_key, password)
self._projectId = projectId;
self._room_group = room_group;
self._room_key = room_key or self:GenerateRoomKey();
self._password = password;
return self;
end
function LobbyRoomInfo:UpdateState()
self:getRoomGroup():SetRoomFull(self:GetRoomKey(), self:isFull());
end
function LobbyRoomInfo:getRoomGroup()
return self._room_group;
end
function LobbyRoomInfo:getProjectId()
return self._projectId;
end
function LobbyRoomInfo:isFull()
return self._clients_count >= self:GetMaxClients();
end
function LobbyRoomInfo:GetClientCount()
return self._clients_count;
end
function LobbyRoomInfo:hasPassword()
return self._password ~= nil;
end
function LobbyRoomInfo:canJoin(password)
if self._password then
return password == self._password;
else
return true;
end
end
function LobbyRoomInfo:AddClient(keepworkUsername, client)
self._users[keepworkUsername] = client;
self._clients_count = self._clients_count + 1;
end
function LobbyRoomInfo:GetClient(keepworkUsername)
return self._users[keepworkUsername];
end
function LobbyRoomInfo:GetClients()
return self._users;
end
function LobbyRoomInfo:RemoveClient(keepworkUsername)
self._users[keepworkUsername] = nil;
self._clients_count = self._clients_count - 1;
end
function LobbyRoomInfo:GetRoomKey()
return self._room_key;
end
| gpl-2.0 |
RyMarq/Zero-K | LuaUI/Widgets/cmd_select_load.lua | 2 | 6023 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Transport Load Double Tap",
desc = "Matches selected tranaports and units when load is double pressed.",
author = "GoogleFrog",
date = "8 May 2015",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
VFS.Include("LuaRules/Configs/customcmds.h.lua")
local CMD_MOVE = CMD.MOVE
local CMD_SET_WANTED_MAX_SPEED = CMD.SET_WANTED_MAX_SPEED
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- From transport AI
local EMPTY_TABLE = {}
local MAX_UNITS = Game.maxUnits
local areaTarget -- used to match area command targets
local goodCommand = {
[CMD.MOVE] = true,
[CMD_RAW_MOVE] = true,
[CMD_RAW_BUILD] = true,
[CMD.SET_WANTED_MAX_SPEED or 70] = true,
[CMD.GUARD] = true,
[CMD.RECLAIM] = true,
[CMD.REPAIR] = true,
[CMD.RESURRECT] = true,
[CMD_JUMP] = true,
}
local function ProcessCommand(unitID, cmdID, params)
if not (goodCommand[cmdID] or cmdID < 0) then
return false
end
local halting = not (cmdID == CMD.MOVE or cmdID == CMD_RAW_MOVE or cmdID == CMD.SET_WANTED_MAX_SPEED)
if cmdID == CMD.SET_WANTED_MAX_SPEED then
return true, halting
end
local targetOverride
if #params == 5 and (cmdID == CMD.RESURRECT or cmdID == CMD.RECLAIM or cmdID == CMD.REPAIR) then
areaTarget = {
x = params[2],
z = params[4],
objectID = params[1]
}
elseif areaTarget and #params == 4 then
if params[1] == areaTarget.x and params[3] == areaTarget.z then
targetOverride = areaTarget.objectID
end
areaTarget = nil
elseif areaTarget then
areaTarget = nil
end
if not targetOverride then
if #params == 3 or #params == 4 then
return true, halting, params
elseif not params[1] then
return true, halting
end
end
local moveParams = {1, 2, 3}
if cmdID == CMD.RESURRECT or cmdID == CMD.RECLAIM then
moveParams[1], moveParams[2], moveParams[3] = Spring.GetFeaturePosition((targetOverride or params[1] or 0) - MAX_UNITS)
else
moveParams[1], moveParams[2], moveParams[3] = Spring.GetUnitPosition(targetOverride or params[1])
end
return true, halting, moveParams
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function CopyMoveThenUnload(transportID, unitID)
local cmdQueue = Spring.GetCommandQueue(unitID, -1)
if not cmdQueue then
return
end
local commandLocations = {}
local queueToRemove = {}
areaTarget = nil
for i = 1, #cmdQueue do
local cmd = cmdQueue[i]
local keepGoing, haltAtCommand, moveParams = ProcessCommand(unitID, cmd.id, cmd.params)
if not keepGoing then
break
end
if moveParams then
commandLocations[#commandLocations + 1] = moveParams
end
if haltAtCommand then
break
else
queueToRemove[#queueToRemove + 1] = cmd.tag
end
end
if #commandLocations == 0 then
return
end
local commands = {}
for i = 1, #commandLocations - 1 do
commands[i] = {CMD_RAW_MOVE, commandLocations[i], CMD.OPT_SHIFT}
end
commandLocations[#commandLocations][4] = 100
commands[#commandLocations] = {CMD.UNLOAD_UNITS, commandLocations[#commandLocations], CMD.OPT_SHIFT}
Spring.GiveOrderArrayToUnitArray({transportID}, commands)
Spring.GiveOrderToUnit(unitID, CMD.REMOVE, queueToRemove, 0)
end
local function DoSelectionLoad()
-- Find the units which can transport and the units which are transports
local selectedUnits = Spring.GetSelectedUnits()
local lightTrans = {}
local heavyTrans = {}
local light = {}
local heavy = {}
for i = 1, #selectedUnits do
local unitID = selectedUnits[i]
local unitDefID = Spring.GetUnitDefID(unitID)
local ud = unitDefID and UnitDefs[unitDefID]
if ud then
if (ud.canFly or ud.cantBeTransported) then
if ud.isTransport then
local transportUnits = Spring.GetUnitIsTransporting(unitID)
if transportUnits and #transportUnits == 0 then
if ud.customParams.islighttransport then
lightTrans[#lightTrans + 1] = unitID
else
heavyTrans[#heavyTrans + 1] = unitID
end
end
end
elseif ud.customParams.requireheavytrans then
heavy[#heavy + 1] = unitID
else
light[#light + 1] = unitID
end
end
end
-- Assign transports to units
local lightEnd = math.min(#light, #lightTrans)
for i = 1, lightEnd do
Spring.GiveOrderToUnit(lightTrans[i], CMD.LOAD_UNITS, {light[i]}, CMD.OPT_RIGHT)
Spring.GiveOrderToUnit(light[i], CMD.WAIT, EMPTY_TABLE, CMD.OPT_RIGHT)
CopyMoveThenUnload(lightTrans[i], light[i])
end
local heavyEnd = math.min(#heavy, #heavyTrans)
for i = 1, heavyEnd do
Spring.GiveOrderToUnit(heavyTrans[i], CMD.LOAD_UNITS, {heavy[i]}, CMD.OPT_RIGHT)
Spring.GiveOrderToUnit(heavy[i], CMD.WAIT, EMPTY_TABLE, CMD.OPT_RIGHT)
CopyMoveThenUnload(heavyTrans[i], heavy[i])
end
--Spring.Echo("light", #light)
--Spring.Echo("heavy", #heavy)
--Spring.Echo("lightTrans", #lightTrans)
--Spring.Echo("heavyTrans", #heavyTrans)
if #light > #lightTrans then
local offset = #heavy - #lightTrans
heavyEnd = math.min(#light, #heavyTrans + #lightTrans - #heavy)
--Spring.Echo("offset", offset)
for i = #lightTrans + 1, heavyEnd do
Spring.GiveOrderToUnit(heavyTrans[offset + i], CMD.LOAD_UNITS, {light[i]}, CMD.OPT_RIGHT)
Spring.GiveOrderToUnit(light[i], CMD.WAIT, EMPTY_TABLE, CMD.OPT_RIGHT)
CopyMoveThenUnload(heavyTrans[offset + i], light[i])
end
end
Spring.SetActiveCommand(-1)
end
function widget:CommandNotify(cmdId)
if cmdId == CMD_LOADUNITS_SELECTED then
DoSelectionLoad()
return true
end
end
| gpl-2.0 |
westredev/PTD | server/CTeam.lua | 1 | 1870 | class 'CTeam'
function CTeam:__init(teamName)
self.teamName = teamName
self.members = {}
self.spawnPoint = nil
end
function CTeam:SetName(name)
self.teamName = name
end
function CTeam:GetName()
return self.teamName
end
function CTeam:GetMembers()
return self.members
end
function CTeam:GetMemberCount()
local count = 0
for key, value in pairs(self.members) do
count = count + 1
end
return count
end
function CTeam:SetMembers(memberTable)
self.members = memberTable
end
function CTeam:AddMember(cPlayer)
table.insert(self.members, cPlayer)
print(cPlayer:GetPlayer():GetName() .. " has been added to team " .. self.teamName .. " team count: " .. self:GetMemberCount())
Chat:Broadcast(cPlayer:GetPlayer():GetName() .. " has been added to team " .. self.teamName .. " team count: " .. self:GetMemberCount(), Color(255, 255, 255))
end
function CTeam:ClearMembers()
for key, value in pairs(self.members) do
table.remove(self.members, key)
end
end
function CTeam:DelMember(cPlayer)
-- self.members[cPlayer] = nil doesnt work?
-- ofcourse not, we use table.insert, the key is an int, not a CPlayer objecT!!
for key, value in pairs(self.members) do
if(value == cPlayer) then
print("ref found!")
cPlayer:SetTeam(nil)
table.remove(self.members, key)
end
end
print(cPlayer:GetPlayer():GetName() .. " has been removed from team " .. self.teamName .. " team count: " .. self:GetMemberCount())
Chat:Broadcast(cPlayer:GetPlayer():GetName() .. " has been removed from team " .. self.teamName .. " team count: " .. self:GetMemberCount(), Color(255, 255, 255))
end
function CTeam:SetSpawnPoint(vaTable)
self.spawnPoint = vaTable
end
function CTeam:GetSpawnPoint()
return self.spawnPoint
end
function CTeam:print()
print("Team Name: " .. self:GetName())
end | mit |
gleachkr/luakit | lib/adblock_chrome.lua | 3 | 9101 | --- Simple URI-based content filter - chrome page.
--
-- This module allows you to configure the `adblock` module with a simple
-- graphical webpage at <luakit://adblock/>. You can
-- currently:
--
-- - enable/disable the adblocker globally, and
-- - enable/disable individual filter lists.
--
-- The adblocker page also shows some statistics about the number of adblock
-- rules in effect.
--
-- @module adblock_chrome
-- @author Henning Hasemann
-- @author Mason Larobina
-- @author Plaque FCC
-- @copyright 2010 Henning Hasemann
-- @copyright 2010 Mason Larobina <mason.larobina@gmail.com>
-- @copyright 2010 Plaque FCC <Reslayer@ya.ru>
local adblock = require("adblock")
local lousy = require("lousy")
local chrome = require("chrome")
local window = require("window")
local webview = require("webview")
local error_page = require("error_page")
local modes = require("modes")
local add_binds, add_cmds = modes.add_binds, modes.add_cmds
local _M = {}
--- HTML template for enabled adblock list.
-- @type string
-- @readwrite
_M.list_template_enabled = [==[
<tr>
<td>{title}</td>
<td>B: {black}</td><td>W: {white}</td><td>I: {ignored}</td>
<td><a href="{uri}">{name}</a></td>
<td class="state_{state}">{state}</td>
<td><a class=disable href=# onclick="adblock_list_toggle({id}, false)">Disable</a></td>
</tr>
]==]
--- HTML template for disabled adblock list.
-- @type string
-- @readwrite
_M.list_template_disabled = [==[
<tr>
<td>{title}</td>
<td></td><td></td><td></td>
<td><a href="{uri}">{name}</a></td>
<td class="state_{state}">{state}</td>
<td><a class=enable href=# onclick="adblock_list_toggle({id}, true)">Enable</a></td>
</tr>
]==]
--- HTML template for adblock state toggle button.
-- @type string
-- @readwrite
_M.toggle_button_template = [==[
<input type="button" class="button" onclick="adblock_toggle({state})" value="{label}" />
]==]
--- HTML template for adblock chrome page content.
-- @type string
-- @readwrite
_M.html_template = [==[
<html>
<head>
<title>{title}</title>
<style type="text/css">
{style}
</style>
</head>
<body>
<header id="page-header">
<h1>AdBlock</h1>
<span class=state_{state}>{state}</span>
<span>B: {black} / W: {white} / I: {ignored}</span>
<div class="rhs">{toggle}</div>
</header>
<div class="content-margin">
<table>
<thead>
<th>File</th>
<th colspan=3>Rules in use</th>
<th>Update URL</th>
<th>State</th>
<th>Actions</th>
</thead>
<tbody>
{links}
</tbody>
</table>
</div>
</body>
</html>
]==]
--- Title for the adblock chrome page.
-- @type string
-- @readwrite
_M.html_page_title = "AdBlock filters"
--- CSS applied to the adblock chrome page.
-- @type string
-- @readwrite
_M.html_style = [===[
table {
width: 100%;
margin: 1em 0;
}
th {
text-align: left;
font-size: 1.3em;
font-weight: 100;
margin: 1em 0 0.5em 0.5em;
-webkit-user-select: none;
cursor: default;
}
td {
}
th, td {
white-space: nowrap;
}
th:not(:nth-last-child(3)),
td:not(:nth-last-child(3)) {
width: 1px;
}
th:nth-last-child(3),
td:nth-last-child(3) {
overflow: hidden;
text-overflow: ellipsis;
max-width: 100px;
width: 100%;
}
td + td, th + th {
padding-left: 1rem;
}
header > span {
padding: 1em;
}
.state_Enabled {
color: #799D6A;
font-weight: bold;
}
.state_Disabled {
color: #CF6A4C;
font-weight: bold;
}
]===]
-- Functions
-- Refresh open filters views (if any)
local function refresh_views()
for _, w in pairs(window.bywidget) do
for _, v in ipairs(w.tabs.children) do
if string.match(v.uri or "", "^luakit://adblock/?") then
v:reload()
end
end
end
end
adblock.refresh_views = refresh_views
--- URI of the adblock chrome page.
-- @type string
-- @readwrite
_M.chrome_page = "luakit://adblock/"
-- Shows the chrome page in the given view.
chrome.add("adblock", function ()
local id = 0
local lists = {}
for _, list in pairs(adblock.subscriptions) do
id = id + 1
list['id'] = id
lists[list.title] = list
end
local links = {}
for _, list in pairs(lists) do
local link_subs = {
uri = list.uri,
id = list.id,
name = lousy.util.escape(list.uri),
title = list.title,
white = list.white,
black = list.black,
ignored = list.ignored,
state = lousy.util.table.hasitem(list.opts, "Enabled") and "Enabled" or "Disabled"
}
local list_template = _M.list_template_disabled
-- Show rules count only when enabled this list and have read its rules
if lousy.util.table.hasitem(list.opts, "Enabled") and list.white and list.black and list.ignored then
-- For totals count items only once (protection from multi-tagging by several opts confusion)
list_template = _M.list_template_enabled
end
local link = string.gsub(list_template, "{(%w+)}", link_subs)
table.insert(links, link)
end
local rulescount = { black = 0, white = 0, ignored = 0 }
for _, list in pairs(adblock.rules) do
if list.black and list.white and list.ignored then
rulescount.black, rulescount.white = rulescount.black + list.black, rulescount.white + list.white
rulescount.ignored = rulescount.ignored + list.ignored
end
end
local toggle_button_subs = {
state = tostring(not adblock.enabled),
label = (not adblock.enabled) and "Enable" or "Disable",
}
local html_subs = {
links = table.concat(links, "\n\n"),
title = _M.html_page_title,
style = chrome.stylesheet .. _M.html_style,
state = adblock.enabled and "Enabled" or "Disabled",
white = rulescount.white,
black = rulescount.black,
ignored = rulescount.ignored,
toggle = string.gsub(_M.toggle_button_template, "{(%w+)}", toggle_button_subs),
}
local html = string.gsub(_M.html_template, "{(%w+)}", html_subs)
return html
end,
nil,
{
adblock_toggle = function (_, enable)
adblock.enabled = enable
end,
adblock_list_toggle = function (_, id, enable)
adblock.list_set_enabled(id, enable)
end,
})
--- CSS for error page shown when page navigation is blocked.
-- @type string
-- @readwrite
_M.navigation_blocked_css_tmpl = [===[
body {
background-color: #ddd;
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
}
#errorContainer {
background: #fff;
min-width: 35em;
max-width: 35em;
padding: 2.5em;
border: 2px solid #aaa;
-webkit-border-radius: 5px;
}
#errorTitleText {
font-size: 120%;
font-weight: bold;
margin-bottom: 1em;
}
.errorMessage {
font-size: 90%;
}
p {
margin: 0;
}
]===]
luakit.register_scheme("adblock-blocked")
webview.add_signal("init", function (view)
view:add_signal("scheme-request::adblock-blocked", function (v, uri, request)
uri = uri:gsub("^adblock%-blocked:", "")
error_page.show_error_page(v, {
style = _M.navigation_blocked_css_tmpl,
heading = "Page blocked",
content = [==[
<div class="errorMessage">
<p>AdBlock has prevented the page at {uri} from loading</p>
</div>
]==],
buttons = {{
label = "Continue anyway",
callback = function(vv)
webview.modify_load_block(v, "adblock", true)
webview.set_location(vv, uri)
adblock.whitelist_domain_access(lousy.uri.parse(uri).host)
end
}},
uri = uri,
request = request,
})
return
end)
end)
-- Add chrome binds.
add_binds("normal", {
{ "ga", "Open <luakit://adblock/> in the current tab.",
function (w) w:navigate(_M.chrome_page) end },
{ "gA", "Open <luakit://adblock/> in a new tab.",
function (w, m)
for _=1, m.count do
w:new_tab(_M.chrome_page)
end
end, {count=1} },
})
-- Add chrome commands.
add_cmds({
{ ":adblock", "Open <luakit://adblock/> in a new tab.",
function (w) w:new_tab(_M.chrome_page) end },
})
return _M
-- vim: et:sw=4:ts=8:sts=4:tw=80
| gpl-3.0 |
RyMarq/Zero-K | LuaUI/Widgets/unit_transport_ai.lua | 1 | 32877 | -- $Id: unit_transport_ai.lua 4460 2009-04-20 20:36:16Z licho $
include("keysym.lua")
function widget:GetInfo()
return {
name = "Transport AI",
desc = "Automatically transports units going to factory waypoint.\n" ..
"Adds embark=call for transport and disembark=unload from transport command",
author = "Licho, xponen, GoogleFrog",
date = "1.11.2007, 9.7.2014",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true,
handler = true
}
end
local floatDefs = VFS.Include("LuaRules/Configs/float_defs.lua") --list of unit able to float for pickup at sea
VFS.Include("LuaRules/Configs/customcmds.h.lua")
local CONST_HEIGHT_MULTIPLIER = 3 -- how many times to multiply height difference when evaluating distance
local CONST_TRANSPORT_PICKUPTIME = 9 -- how long (in seconds) does transport land and takeoff with unit
local CONST_PRIORITY_BENEFIT = 10000 -- how much more important are priority transfers
local CONST_TRANSPORT_STOPDISTANCE = 350 -- how close by has transport be to stop the unit
local CONST_UNLOAD_RADIUS = 100 -- how big is the radious for unload command for factory transports
local idleTransports = {} -- list of idle transports key = id, value = {defid}
local activeTransports = {} -- list of transports with AI enabled
local allMyTransports = {} -- list of all transports key = id, value = {defid}
local waitingUnits = {} -- list of units waiting for traqnsport - key = unitID, {unit state, unitDef, factory}
local priorityUnits = {} -- lists of priority units waiting for key= unitId, value = state
local autoCallTransportUnits = {} -- map of units that want to be automatically transported
local toGuard = {} -- list of transports which need to guard something at the end of their queue. key = id, value = guardieeID
local toPick = {} -- list of units waiting to be picked - key = transportID, value = {id, stoppedState}
local toPickRev = {} -- list of units waiting to be picked - key = unitID, value=transportID
local storedQueue = {} -- unit keyed stored queues
local hackIdle ={} -- temp field to overcome unitIdle problem
local areaTarget = {} -- indexed by ID, used to match area command targets
local ST_ROUTE = 1 -- unit is enroute from factory
local ST_PRIORITY = 2 -- unit is in need of priority transport
local ST_STOPPED = 3 -- unit is enroute from factory but stopped
local MAX_UNITS = Game.maxUnits
local timer = 0
local myTeamID
local spGetUnitPosition = Spring.GetUnitPosition
local spGetUnitDefID = Spring.GetUnitDefID
local spEcho = Spring.Echo
local spGetPlayerInfo = Spring.GetPlayerInfo
local spGetCommandQueue = Spring.GetCommandQueue
local spGetUnitSeparation = Spring.GetUnitSeparation
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spGetUnitDefDimensions = Spring.GetUnitDefDimensions
local spGetTeamUnits = Spring.GetTeamUnits
local spGetSelectedUnits = Spring.GetSelectedUnits
local spGetUnitIsTransporting = Spring.GetUnitIsTransporting
local spGetGroundHeight = Spring.GetGroundHeight
local spSetActiveCommand = Spring.SetActiveCommand
local EMPTY_TABLE = {}
local autoCallTransportCmdDesc = {
id = CMD_AUTO_CALL_TRANSPORT,
type = CMDTYPE.ICON_MODE,
tooltip = 'Allows the unit to automatically call for transportation',
name = 'Auto Call Transport',
cursor = 'Repair',
action = 'autocalltransport',
params = {0, 'off', 'on'},
pos = {CMD.ONOFF, CMD.REPEAT, CMD.MOVE_STATE, CMD.FIRE_STATE, CMD_RETREAT},
}
local unitAICmdDesc = {
id = CMD_UNIT_AI,
type = CMDTYPE.ICON_MODE,
name = 'Unit AI',
action = 'unitai',
tooltip = 'Toggles smart unit AI for the unit',
params = {0, 'AI Off','AI On'}
}
options_path = 'Settings/Unit Behaviour/Transport AI'
options = {
transportFromFactory = {
name = "Transport From Factory",
type = "bool",
value = false,
desc = "When enabled newly completed units will be transported to the waypoint of their parent factory.",
noHotkey = true,
},
lingerOnConstructorTransport = {
name = "Linger on Constructor Transport",
type = "bool",
value = true,
desc = "Enable to make transports sit next to constructors after transporting them.",
noHotkey = true,
},
ignoreBuilders = {
name = "Ignore Constructors From Factory",
type = "bool",
value = false,
desc = "Enable to not transport newly completed constructors.",
noHotkey = true,
},
minimumTransportBenefit = {
name = 'Factory transport benefit threshold (s)',
type = 'number',
value = 2,
min = -10, max = 10, step = 0.1,
noHotkey = true,
},
}
-- Keep synced with unit_transport_ai_auto_call
local autoCallTransportDef = {}
local transportDef = {}
for i = 1, #UnitDefs do
local ud = UnitDefs[i]
if (Spring.Utilities.getMovetype(ud) == 2 and ud.isBuilder and not ud.cantBeTransported) or (ud.isFactory and not ud.customParams.nongroundfac) then
autoCallTransportDef[i] = true
end
if (ud.transportCapacity >= 1) and ud.canFly then
transportDef[i] = true
end
end
local function TableInsert(tab, toInsert)
tab[#tab+1] = toInsert
end
local function ExtractModifiedOptions(options) --FIXME: pls check again if I'm really needed. This is a respond to https://code.google.com/p/zero-k/issues/detail?id=1824 (options in online game coded different than in local game)
local alt,ctrl,shift,internal,right
for i,value in pairs(options) do
if value == "alt" then
alt = true
elseif value== "ctrl" then
ctrl = true
elseif value == "shift" then
shift =true
elseif value == "internal" then
internal = true
elseif value == "right" then
right = true
end
end
return alt,ctrl,shift,internal,right
end
local goodCommand = {
[CMD.MOVE] = true,
[CMD_RAW_MOVE] = true,
[CMD_RAW_BUILD] = true,
[CMD.WAIT] = true,
[CMD.SET_WANTED_MAX_SPEED or 70] = true,
[CMD.GUARD] = true,
[CMD.RECLAIM] = true,
[CMD.REPAIR] = true,
[CMD.RESURRECT] = true,
[CMD_JUMP] = true,
}
local ignoredCommand = {
[CMD.ONOFF] = true,
[CMD.FIRE_STATE] = true,
[CMD.MOVE_STATE] = true,
[CMD.REPEAT] = true,
[CMD.CLOAK] = true,
[CMD.STOCKPILE] = true,
[CMD.TRAJECTORY] = true,
[CMD.IDLEMODE] = true,
[CMD_GLOBAL_BUILD] = true,
[CMD_STEALTH] = true,
[CMD_CLOAK_SHIELD] = true,
[CMD_UNIT_FLOAT_STATE] = true,
[CMD_PRIORITY] = true,
[CMD_MISC_PRIORITY] = true,
[CMD_RETREAT] = true,
[CMD_UNIT_BOMBER_DIVE_STATE] = true,
[CMD_AP_FLY_STATE] = true,
[CMD_AP_AUTOREPAIRLEVEL] = true,
[CMD_UNIT_SET_TARGET] = true,
[CMD_UNIT_CANCEL_TARGET] = true,
[CMD_UNIT_SET_TARGET_CIRCLE] = true,
[CMD_ABANDON_PW] = true,
[CMD_RECALL_DRONES] = true,
[CMD_UNIT_KILL_SUBORDINATES] = true,
[CMD_GOO_GATHER] = true,
[CMD_DISABLE_ATTACK] = true,
[CMD_PUSH_PULL] = true,
[CMD_UNIT_AI] = true,
[CMD_WANT_CLOAK] = true,
[CMD_DONT_FIRE_AT_RADAR] = true,
[CMD_AIR_STRAFE] = true,
[CMD_PREVENT_OVERKILL] = true,
[CMD_SELECTION_RANK] = true,
}
local function ProcessCommand(unitID, cmdID, params, noUsefuless, noPosition)
if noUsefuless then
return false
end
if not (goodCommand[cmdID] or cmdID < 0) then
return false
end
local halting = not (cmdID == CMD.MOVE or cmdID == CMD_RAW_MOVE or cmdID == CMD_RAW_BUILD or cmdID == CMD.WAIT or cmdID == CMD.SET_WANTED_MAX_SPEED)
if noPosition or cmdID == CMD.WAIT or cmdID == CMD.SET_WANTED_MAX_SPEED then
return true, halting
end
local targetOverride
if #params == 5 and (cmdID == CMD.RESURRECT or cmdID == CMD.RECLAIM or cmdID == CMD.REPAIR) then
areaTarget[unitID] = {
x = params[2],
z = params[4],
objectID = params[1]
}
elseif areaTarget[unitID] and #params == 4 then
if params[1] == areaTarget[unitID].x and params[3] == areaTarget[unitID].z then
targetOverride = areaTarget[unitID].objectID
end
areaTarget[unitID] = nil
elseif areaTarget[unitID] then
areaTarget[unitID] = nil
end
if not targetOverride then
if #params == 3 or #params == 4 then
return true, halting, params[1], params[2], params[3]
elseif not params[1] then
return true, halting
end
end
if cmdID == CMD.RESURRECT or cmdID == CMD.RECLAIM then
local x, y, z = Spring.GetFeaturePosition((targetOverride or params[1] or 0) - MAX_UNITS)
return true, halting, x, y, z
else
local x, y, z = Spring.GetUnitPosition(targetOverride or params[1])
return true, halting, x, y, z
end
end
function IsTransportable(unitDefID, unitID)
ud = UnitDefs[unitDefID]
if (ud == nil) then
return false
end
udc = ud.springCategories
local _,_,_,_,y = spGetUnitPosition(unitID,true)
y = y + Spring.GetUnitRadius(unitID)
return (udc~= nil and ud.isGroundUnit and (y>-20 or floatDefs[unitDefID]))
end
function IsDisembark(cmd)
local alt,ctrl = ExtractModifiedOptions(cmd.options)
if (cmd.id == CMD.WAIT and (cmd.options.alt or alt) and (cmd.options.ctrl or ctrl)) then
return true
end
return false
end
local CMD_OPT_ALT = CMD.OPT_ALT
function IsWaitCommand(unitID)
local cmdID, cmdOpts = Spring.GetUnitCurrentCommand(unitID)
return cmdID == CMD.WAIT and (cmdOpts % (2*CMD_OPT_ALT) < CMD_OPT_ALT)
end
function IsIdle(unitID)
return spGetCommandQueue(unitID, 0) == 0
end
function GetToPickTransport(unitID)
local x = toPickRev[unitID]
if x~= nil then
return x
else
return 0
end
end
function GetToPickUnit(transportID)
local x = toPick[transportID]
if (x~=nil) then
if x[1] ~= nil then
return x[1]
else
return 0
end
end
return 0
end
function DeleteToPickTran(transportID)
local tr = toPick[transportID]
if (tr ~= nil) then
local uid = tr[1]
if (uid ~= nil) then
toPickRev[uid]=nil
end
end
toPick[transportID] = nil
end
function DeleteToPickUnit(unitID)
local tr = toPickRev[unitID]
if (tr~=nil) then
toPick[tr] = nil
end
toPickRev[unitID] = nil
end
function AddToPick(transportID, unitID, stopped, fact)
toPick[transportID] = {unitID, stopped, fact}
toPickRev[unitID] = transportID
end
local function GetAutoCallTransportState(unitID)
return autoCallTransportUnits[unitID]
end
local function SetAutoCallTransportState(unitID, unitDefID, newState)
if autoCallTransportDef[unitDefID] then
autoCallTransportUnits[unitID] = newState
end
end
function widget:UnitCreated(unitID, unitDefID, teamID)
if teamID == myTeamID and transportDef[unitDefID] then
allMyTransports[unitID] = unitDefID
end
end
function widget:Shutdown()
WG.GetAutoCallTransportState = nil
widgetHandler:DeregisterGlobal(widget, 'taiEmbark')
end
function widget:UnitTaken(unitID, unitDefID, oldTeamID, teamID)
widget:UnitCreated(unitID, unitDefID, teamID)
end
function RemoveUnit(unitID, unitDefID)
--spEcho("unit destroyed " ..unitID)
idleTransports[unitID] = nil
priorityUnits[unitID] = nil
waitingUnits[unitID] = nil
local tuid = GetToPickUnit(unitID)
if (tuid ~= 0) then -- transport which was about to pick something was destroyed
local state = toPick[unitID][2]
local fact = toPick[unitID][3]
if (state == ST_PRIORITY) then
waitingUnits[tuid] = {ST_PRIORITY, spGetUnitDefID(tuid)}
else
waitingUnits[tuid] = {ST_ROUTE, spGetUnitDefID(tuid), fact}
if (state == ST_STOPPED) then
spGiveOrderToUnit(tuid, CMD.WAIT, EMPTY_TABLE, 0)
end
end
DeleteToPickTran(unitID)
AssignTransports(0, tuid)
else -- unit which was about to be picked was destroyed
local pom = GetToPickTransport(unitID)
if (pom~=0) then
DeleteToPickUnit(unitID)
spGiveOrderToUnit(pom, CMD.STOP, EMPTY_TABLE, 0)
if toGuard[pom] then
spGiveOrderToUnit(pom, CMD.GUARD, {toGuard[pom]}, 0)
end
end -- delete form toPick list
end
end
function AddTransportToIdle(unitID, unitDefID)
if activeTransports[unitID] then
idleTransports[unitID] = unitDefID
--spEcho ("transport added " .. unitID)
return true
end
return false
end
local function RemoveTransport(unitID, unitDefID)
activeTransports[unitID] = nil
toGuard[unitID] = nil
autoCallTransportUnits[unitID] = false
RemoveUnit(unitID, unitDefID)
end
local function AddTransport(unitID, unitDefID)
if transportDef[unitDefID] then
activeTransports[unitID] = unitDefID
local queueCount = Spring.GetCommandQueue(unitID, 0)
if queueCount == 0 then
AddTransportToIdle(unitID, unitDefID)
end
end
end
local function PossiblyTransferAutoCallThroughMorph(unitID)
if not autoCallTransportUnits[unitID] then
return
end
local morphedTo = Spring.GetUnitRulesParam(unitID, "wasMorphedTo")
if not morphedTo then
return
end
local morphedToDefID = Spring.GetUnitDefID(morphedTo)
if morphedToDefID then
SetAutoCallTransportState(morphedTo, morphedToDefID, autoCallTransportUnits[unitID])
end
end
local function GiveUnloadOrder(transportID, x, y, z)
spGiveOrderToUnit(transportID, CMD.UNLOAD_UNIT, {x - 2, y, z - 2}, CMD.OPT_SHIFT)
spGiveOrderToUnit(transportID, CMD.UNLOAD_UNIT, {x + 2, y, z + 2, CONST_UNLOAD_RADIUS}, CMD.OPT_SHIFT)
spGiveOrderToUnit(transportID, CMD.UNLOAD_UNIT, {x - 2, y, z + 2, CONST_UNLOAD_RADIUS*2}, CMD.OPT_SHIFT)
spGiveOrderToUnit(transportID, CMD.UNLOAD_UNIT, {x + 2, y, z - 2, CONST_UNLOAD_RADIUS*4}, CMD.OPT_SHIFT)
end
function widget:UnitDestroyed(unitID, unitDefID, teamID)
if teamID == myTeamID then
PossiblyTransferAutoCallThroughMorph(unitID)
RemoveTransport(unitID, unitDefID)
end
if allMyTransports[unitID] then
allMyTransports[unitID] = nil
end
end
function widget:UnitGiven(unitID, unitDefID, newTeamID, teamID)
widget:UnitDestroyed(unitID, unitDefID, teamID)
end
function widget:UnitIdle(unitID, unitDefID, teamID)
if (teamID ~= myTeamID) or (WG.FerryUnits and WG.FerryUnits[unitID]) then
return
end
if (hackIdle[unitID] ~= nil) then
hackIdle[unitID] = nil
return
end
if (AddTransportToIdle(unitID, unitDefID)) then
AssignTransports(unitID, 0)
else
if (IsTransportable(unitDefID, unitID)) then
priorityUnits[unitID] = nil
local marked = GetToPickTransport(unitID)
if (waitingUnits[unitID] ~= nil) then -- unit was waiting for transport and now its suddenly idle (stopped) - delete it
-- spEcho("waiting unit idle "..unitID)
waitingUnits[unitID] = nil
end
if (marked ~= 0) then
-- spEcho("to pick unit idle "..unitID)
DeleteToPickTran(marked)
spGiveOrderToUnit(marked, CMD.STOP, EMPTY_TABLE, 0) -- and stop it (when it becomes idle it will be assigned)
end
end
end
end
function widget:UnitFromFactory(unitID, unitDefID, unitTeam, factID, factDefID, userOrders)
if unitTeam == myTeamID then
local ud = UnitDefs[unitDefID]
if (options.ignoreBuilders.value and ud.isBuilder and ud.canAssist) then
return
end
if (IsTransportable(unitDefID, unitID) and not userOrders) then
--spEcho ("new unit from factory "..unitID)
waitingUnits[unitID] = {ST_ROUTE, unitDefID, factID}
local foundTransport = AssignTransports(0, unitID, factID, not options.transportFromFactory.value)
-- Transport was not found so remove the unit. Factory guard transport only works
-- on units newly exiting the factory (too chaotic otherwise).
if (not options.transportFromFactory.value) and (not foundTransport) then
waitingUnits[unitID] = nil
end
end
end
end
function widget:CommandNotify(id, params, options)
if id == CMD_AUTO_CALL_TRANSPORT then
local selectedUnits = Spring.GetSelectedUnits()
local newState = (params[1] == 1)
for i = 1, #selectedUnits do
local unitID = selectedUnits[i]
local unitDefID = Spring.GetUnitDefID(unitID)
SetAutoCallTransportState(unitID, unitDefID, newState)
end
return true
end
if id == CMD_UNIT_AI then
local selectedUnits = Spring.GetSelectedUnits()
local newState = (params[1] == 1)
for i = 1, #selectedUnits do
local unitID = selectedUnits[i]
local unitDefID = Spring.GetUnitDefID(unitID)
if transportDef[unitDefID] then
if newState then
AddTransport(unitID, unitDefID)
else
RemoveTransport(unitID, unitDefID)
end
end
end
return false
end
if ignoredCommand[id] then
return false
end
local sel = nil
local alt,ctrl,shift = ExtractModifiedOptions(options)
if not (options.shift or shift) then
sel = spGetSelectedUnits()
for i = 1, #sel do
local uid = sel[i]
RemoveUnit(uid, spGetUnitDefID(uid))
end
end
if (id == CMD.WAIT and (options.alt or alt)) then
if (sel == nil) then sel = spGetSelectedUnits() end
for i=1,#sel do
local uid = sel[i]
priorityUnits[uid] = spGetUnitDefID(uid)
end
end
return false
end
function widget:UnitCmdDone(unitID, unitDefID, unitTeam, cmdID, cmdTag)
if autoCallTransportUnits[unitID] then
local useful, halting = ProcessCommand(unitID, cmdID, params, false, true)
local queue = Spring.GetCommandQueue(unitID, 0)
if useful and halting and queue >= 1 then
spGiveOrderToUnit(unitID, CMD_EMBARK, EMPTY_TABLE, CMD.OPT_ALT)
else
RemoveUnit(unitDefID, spGetUnitDefID(unitDefID))
end
end
end
function widget:CommandsChanged()
local selectedSorted = Spring.GetSelectedUnitsSorted()
local searchCall, searchTransport = true, true
for unitDefID, units in pairs(selectedSorted) do
if searchCall and autoCallTransportDef[unitDefID] then
local customCommands = widgetHandler.customCommands
local order = 0
if autoCallTransportUnits[units[1]] then
order = 1
end
autoCallTransportCmdDesc.params[1] = order
table.insert(customCommands, autoCallTransportCmdDesc)
searchCall = false
end
if searchTransport and transportDef[unitDefID] then
local customCommands = widgetHandler.customCommands
local order = 0
if activeTransports[units[1]] then
order = 1
end
unitAICmdDesc.params[1] = order
table.insert(customCommands, unitAICmdDesc)
searchTransport = false
end
end
end
function widget:Update(deltaTime)
timer = timer + deltaTime
if (timer < 1) then
return
end
StopCloseUnits()
local todel = {}
for unitID, unitDefID in pairs(priorityUnits) do
waitingUnits[unitID] = {ST_PRIORITY, unitDefID}
AssignTransports(0, unitID)
TableInsert(todel, unitID)
end
for i = 1, #todel do
priorityUnits[todel[i]] = nil
end
timer = 0
end
function StopCloseUnits() -- stops dune units which are close to transport
for transportID, val in pairs(toPick) do
local unitID = val[1]
local state = val[2]
if (state == ST_ROUTE or state == ST_PRIORITY) then
local dist = spGetUnitSeparation(transportID, unitID, true)
if (dist ~= nil and dist < CONST_TRANSPORT_STOPDISTANCE) then
local canStop = true
if (val[3] ~= nil) then
local fd = spGetUnitDefID(val[3])
local ud = spGetUnitDefID(unitID)
if (fd ~= nil and ud ~= nil) then
local fd = spGetUnitDefDimensions(fd)
local ud = spGetUnitDefDimensions(ud)
if (fd ~= nil and ud ~= nil) then
if (spGetUnitSeparation(unitID, val[3], true) < fd.radius + ud.radius) then
-- spEcho ("Cant stop - too close to factory")
canStop = false
end
end
end
end
if canStop then
if not IsWaitCommand(unitID) then
spGiveOrderToUnit(unitID, CMD.WAIT, EMPTY_TABLE, 0)
end
toPick[transportID][2] = ST_STOPPED
end
end
end
end
end
function widget:Initialize()
local _, _, spec, teamID = spGetPlayerInfo(Spring.GetMyPlayerID(), false)
if spec then
widgetHandler:RemoveWidget(widget)
return false
end
WG.GetAutoCallTransportState = GetAutoCallTransportState
WG.SetAutoCallTransportState = SetAutoCallTransportState
WG.AddTransport = AddTransport
myTeamID = teamID
widgetHandler:RegisterGlobal(widget, 'taiEmbark', taiEmbark)
local units = spGetTeamUnits(teamID)
for i = 1, #units do -- init existing transports
local unitID = units[i]
widget:UnitCreated(unitID, spGetUnitDefID(unitID), Spring.GetUnitTeam(unitID))
if AddTransportToIdle(unitID, spGetUnitDefID(unitID)) then
AssignTransports(unitID, 0)
end
end
end
local function ReturnToPickupLocation(unitDefID)
if not options.lingerOnConstructorTransport.value then
return false
end
local ud = unitDefID and UnitDefs[unitDefID]
return not (ud and ud.isBuilder)
end
function widget:UnitLoaded(unitID, unitDefID, teamID, transportID)
if (teamID ~= myTeamID or toPick[transportID]==nil) then
return
end
local queue = spGetCommandQueue(unitID, -1);
if (queue == nil) then
return
end
--spEcho("unit loaded " .. transportID .. " " ..unitID)
local torev = {}
local lastX, lastY, lastZ
local ender = false
storedQueue[unitID] = {}
DeleteToPickTran(transportID)
hackIdle[transportID] = true
local cnt = 0
for k = 1, #queue do
local v = queue[k]
local alt,ctrl,shift,internal,right = ExtractModifiedOptions(v.options)
if not (v.options.internal or internal) then --not other widget's command
local usefulCommand, haltingCommand, cx, cy, cz = ProcessCommand(unitID, v.id, v.params, ender)
if usefulCommand then
cnt = cnt +1
if cx then
if queue[k + 1] then
-- Do not give move order to the last waypoint.
spGiveOrderToUnit(transportID, CMD_RAW_MOVE, {cx, cy, cz}, CMD.OPT_SHIFT)
TableInsert(torev, {cx, cy, cz + 20})
end
lastX, lastY, lastZ = cx, cy, cz
end
if haltingCommand or (IsDisembark(v)) then
ender = true
if haltingCommand then
local opts = CMD.OPT_SHIFT
if (v.options.alt or alt) then opts = opts + CMD.OPT_ALT end
if (v.options.ctrl or ctrl) then opts = opts + CMD.OPT_CTRL end
if (v.options.right or right) then opts = opts + CMD.OPT_RIGHT end
TableInsert(storedQueue[unitID], {v.id, v.params, opts})
end
end
else
if (not ender) then
ender = true
end
if (v.ID ~= CMD.WAIT) then
local opts = CMD.OPT_SHIFT
if (v.options.alt or alt) then opts = opts + CMD.OPT_ALT end
if (v.options.ctrl or ctrl) then opts = opts + CMD.OPT_CTRL end
if (v.options.right or right) then opts = opts + CMD.OPT_RIGHT end
TableInsert(storedQueue[unitID], {v.id, v.params, opts})
end
end
end
end
spGiveOrderToUnit(unitID, CMD.STOP, EMPTY_TABLE, 0)
if lastX then
GiveUnloadOrder(transportID, lastX, lastY, lastZ)
if toGuard[transportID] or ReturnToPickupLocation(unitDefID) then
local i = #torev
while (i > 0) do
spGiveOrderToUnit(transportID, CMD_RAW_MOVE, torev[i], CMD.OPT_SHIFT) -- move in zig zaq (if queued)
i = i -1
end
local x,y,z = spGetUnitPosition(transportID)
spGiveOrderToUnit(transportID, CMD_RAW_MOVE, {x,y,z}, CMD.OPT_SHIFT)
--unload 2nd time at loading point incase transport refuse to drop unit at the intended destination (ie: in water)
GiveUnloadOrder(transportID, x, y, z)
if toGuard[transportID] then
spGiveOrderToUnit(transportID, CMD.GUARD, {toGuard[transportID]}, CMD.OPT_SHIFT)
end
end
else
local x,y,z = Spring.GetUnitPosition(transportID)
GiveUnloadOrder(transportID, x, y, z)
end
end
function widget:UnitUnloaded(unitID, unitDefID, teamID, transportID)
if (teamID ~= myTeamID or storedQueue[unitID] == nil) then
return
end
spGiveOrderToUnit(unitID, CMD.STOP, EMPTY_TABLE, 0)
for i=1, #storedQueue[unitID] do
local x = storedQueue[unitID][i]
spGiveOrderToUnit(unitID, x[1], x[2], x[3])
end
storedQueue[unitID] = nil
local cmdID = Spring.GetUnitCurrentCommand(unitID)
if cmdID == CMD.WAIT then
-- workaround: clears wait order if STOP fails to do so
spGiveOrderToUnit(unitID, CMD.WAIT, EMPTY_TABLE, 0)
end
end
function CanTransport(transportID, unitID)
local udef = spGetUnitDefID(unitID)
local tdef = spGetUnitDefID(transportID)
if (not udef or not tdef) then
return false
end
if (UnitDefs[udef].xsize > UnitDefs[tdef].transportSize * 2) then -- unit size check
-- spEcho ("size failed")
return false
end
local trans = spGetUnitIsTransporting(transportID) -- capacity check
if (UnitDefs[tdef].transportCapacity <= #trans) then
-- spEcho ("count failed")
return false
end
local mass = UnitDefs[udef].mass -- mass check
for i=1, #trans do
mass = mass + UnitDefs[spGetUnitDefID(trans[i])].mass
end
if (mass > UnitDefs[tdef].transportMass) then
-- spEcho ("mass failed")
return false
end
return true
end
local function GetTransportBenefit(unitID, pathLength, transporter, transDef, unitspeed, unitmass, priorityState)
local transpeed = UnitDefs[transDef].speed
local transMass = UnitDefs[transDef].mass
local speedMod = math.min(1, 3 * unitmass/(transMass +unitmass )) --see unit_transport_speed.lua gadget
local transportDist = spGetUnitSeparation(unitID, transporter, true)
local ttime = (transportDist + pathLength) / (transpeed*speedMod) + CONST_TRANSPORT_PICKUPTIME
local utime = pathLength / unitspeed
local benefit = utime - ttime
--spEcho (" "..transporter.. " " .. unitID .. " " .. benefit)
if (benefit > options.minimumTransportBenefit.value) then
if priorityState then
benefit = benefit + CONST_PRIORITY_BENEFIT
end
return {benefit, transporter, unitID}
end
end
function AssignTransports(transportID, unitID, guardID, guardOnly)
local best = {}
--spEcho ("assigning " .. transportID .. " " ..unitID)
if (transportID~=0) then
local unitDefID = spGetUnitDefID(transportID)
local transpeed = UnitDefs[unitDefID].speed
local transMass = UnitDefs[unitDefID].mass
local speedMod = 1
for id, val in pairs(waitingUnits) do
local waitDefID = val[2]
if CanTransport(transportID, id) and IsTransportable(waitDefID, id) then
local unitspeed = UnitDefs[waitDefID].speed
local unitmass = UnitDefs[waitDefID].mass
speedMod = math.min(1, 3 * unitmass/(transMass +unitmass )) --see unit_transport_speed.lua gadget
local pathLength = GetPathLength(id)
local transportDist = spGetUnitSeparation(id, transportID, true)
local ttime = (transportDist + pathLength) / (transpeed*speedMod) + CONST_TRANSPORT_PICKUPTIME
local utime = pathLength / unitspeed
local benefit = utime-ttime
--spEcho (" "..transportID .. " " .. id .. " " .. benefit)
if (benefit > options.minimumTransportBenefit.value) then
if (val[1]==ST_PRIORITY) then
benefit = benefit + CONST_PRIORITY_BENEFIT
end
TableInsert(best, {benefit, transportID, id})
end
end
end
elseif (unitID ~=0) then
local unitDefID = spGetUnitDefID(unitID)
local unitspeed = UnitDefs[unitDefID].speed
local unitmass = UnitDefs[unitDefID].mass
local priorityState = (waitingUnits[unitID][1] == ST_PRIORITY)
local pathLength = GetPathLength(unitID)
if not guardOnly then
for id, def in pairs(idleTransports) do
if CanTransport(id, unitID) and IsTransportable(unitDefID, unitID) then
local benefit = GetTransportBenefit(unitID, pathLength, id, def, unitspeed, unitmass, priorityState)
if benefit then
toGuard[id] = nil
TableInsert(best, benefit)
end
end
end
end
if guardID then
for id, def in pairs(allMyTransports) do
if CanTransport(id, unitID) and IsTransportable(unitDefID, unitID) then
local cmdID, _, _, cmdParam = Spring.GetUnitCurrentCommand(id)
if cmdID == CMD.GUARD and cmdParam == guardID then
local benefit = GetTransportBenefit(unitID, pathLength, id, def, unitspeed, unitmass, priorityState)
if benefit then
toGuard[id] = guardID
TableInsert(best, benefit)
end
end
end
end
end
end
table.sort(best, function(a,b) return a[1]>b[1] end)
local i = 1
local it = #best
local used = {}
while i <= it do
local tid = best[i][2]
local uid = best[i][3]
i = i +1
if (used[tid]==nil and used[uid]==nil) then --check if already given transport order in same loop
used[tid] = 1
used[uid] = 1
--spEcho ("ordering " .. tid .. " " .. uid )
if (waitingUnits[uid][1] == ST_PRIORITY) then
AddToPick(tid, uid, ST_PRIORITY)
else
AddToPick(tid, uid, ST_ROUTE, waitingUnits[uid][3])
end
waitingUnits[uid] = nil
idleTransports[tid] = nil
spGiveOrderToUnit(tid, CMD.LOAD_UNITS, {uid}, 0)
return true -- Transport was matched with the unit
end
end
return false -- Unit/Transport is still idle
end
function Dist(x,y,z, x2, y2, z2)
local xd = x2-x
local yd = y2-y
local zd = z2-z
return math.sqrt(xd*xd + yd*yd + zd*zd)
end
function GetPathLength(unitID)
local mini = math.huge
local maxi = -math.huge
local px,py,pz= spGetUnitPosition(unitID)
local h = spGetGroundHeight(px,pz)
if (h < mini) then mini = h end
if (h > maxi) then maxi = h end
local d = 0
local queue = spGetCommandQueue(unitID, -1);
local udid = spGetUnitDefID(unitID)
local moveID = UnitDefs[udid].moveDef.id
if (queue == nil) then return 0 end
for k = 1, #queue do
local v = queue[k]
local usefulCommand, haltingCommand, cx, cy, cz = ProcessCommand(unitID, v.id, v.params)
if usefulCommand then
if cx then
local reachable = true --always assume target reachable
local waypoints
if moveID then --unit has compatible moveID?
local result, lastwaypoint
result, lastwaypoint, waypoints = IsTargetReachable(moveID, px, py, pz, cx, cy, cz, 128)
if result == "outofreach" then --abit out of reach?
reachable=false --target is unreachable!
end
end
if reachable then
if waypoints then --we have waypoint to destination?
local way1,way2,way3 = px,py,pz
for i=1, #waypoints do --sum all distance in waypoints
d = d + Dist(way1,way2,way3, waypoints[i][1],waypoints[i][2],waypoints[i][3])
way1,way2,way3 = waypoints[i][1],waypoints[i][2],waypoints[i][3]
end
else --so we don't have waypoint?
d = d + Dist(px,py, pz, cx, cy, cz) --we don't have waypoint then measure straight line
end
else --pathing says target unreachable?!
d = d + Dist(px,py, pz, cx, cy, cz) + 9999 --target unreachable!
end
px, py, pz = cx, cy, cz
local h = spGetGroundHeight(px,pz)
if (h < mini) then mini = h end
if (h > maxi) then maxi = h end
if haltingCommand then
break
end
end
else
break
end
end
d = d + (maxi - mini) * CONST_HEIGHT_MULTIPLIER
return d
end
--This function process result of Spring.PathRequest() to say whether target is reachable or not
function IsTargetReachable (moveID, ox,oy,oz,tx,ty,tz,radius)
local result,lastcoordinate, waypoints
local path = Spring.RequestPath( moveID,ox,oy,oz,tx,ty,tz, radius)
if path then
local waypoint = path:GetPathWayPoints() --get crude waypoint (low chance to hit a 10x10 box). NOTE; if waypoint don't hit the 'dot' is make reachable build queue look like really far away to the GetWorkFor() function.
local finalCoord = waypoint[#waypoint]
if finalCoord then --unknown why sometimes NIL
local dx, dz = finalCoord[1]-tx, finalCoord[3]-tz
local dist = math.sqrt(dx*dx + dz*dz)
if dist <= radius+20 then --is within radius?
result = "reach"
lastcoordinate = finalCoord
waypoints = waypoint
else
result = "outofreach"
lastcoordinate = finalCoord
waypoints = waypoint
end
end
else
result = "noreturn"
lastcoordinate = nil
waypoints = nil
end
return result, lastcoordinate, waypoints
end
--[[
function widget:KeyPress(key, modifier, isRepeat)
if (key == KEYSYMS.Q and not modifier.ctrl) then
if (not modifier.alt) then
local opts = CMD.OPT_ALT
if (modifier.shift) then opts = opts + CMD.OPT_SHIFT end
for _, id in ipairs(spGetSelectedUnits()) do -- embark
local def = spGetUnitDefID(id)
if (IsTransportable(def) or UnitDefs[def].isFactory) then
spGiveOrderToUnit(id, CMD.WAIT, EMPTY_TABLE, opts)
if (not UnitDefs[def].isFactory) then priorityUnits[id] = def end
end
end
else
local opts = CMD.OPT_ALT + CMD.OPT_CTRL
if (modifier.shift) then opts = opts + CMD.OPT_SHIFT end
for _, id in ipairs(spGetSelectedUnits()) do --disembark
local def = spGetUnitDefID(id)
if (IsTransportable(def) or UnitDefs[def].isFactory) then spGiveOrderToUnit(id, CMD.WAIT, EMPTY_TABLE, opts) end
end
end
end
end ]]--
function taiEmbark(unitID, teamID, embark, shift, internal) -- called by gadget
if (teamID ~= myTeamID) then
return
end
if (not shift) then
RemoveUnit(unitID, spGetUnitDefID(unitID)) --remove existing command ASAP
end
if not internal then
local queue = spGetCommandQueue(unitID, -1)
if (not queue or #queue == 0) and (not shift) then --unit has no command at all and not queueing embark/disembark command
return false
else
local hasMoveCommand
for k = 1, #queue do
local v = queue[k]
local usefulCommand, haltingCommand, cx, cy, cz = ProcessCommand(unitID, v.id, v.params, false, true)
if usefulCommand then
hasMoveCommand = true
break
end
end
if (not hasMoveCommand) and (not shift) then --unit has no move command and not queueing embark/disembark command
return false
end
end
end
if (embark) then
local def = spGetUnitDefID(unitID)
local ud = UnitDefs[def]
if (ud ~= nil and not ud.isFactory) and not waitingUnits[unitID] then
priorityUnits[unitID] = def --add to priority list (will be read in Widget:Update())
end
end
end
| gpl-2.0 |
ghostry/openwrt-gmod | luci/luci-app-v2ray/luasrc/model/cbi/v2ray/outbound-list.lua | 1 | 1277 | -- Copyright 2019-2020 Xingwang Liao <kuoruan@gmail.com>
-- Licensed to the public under the MIT License.
local dsp = require "luci.dispatcher"
local m, s, o
m = Map("v2ray", "%s - %s" % { translate("V2Ray"), translate("Outbound") })
m:append(Template("v2ray/import_outbound"))
s = m:section(TypedSection, "outbound")
s.anonymous = true
s.addremove = true
s.sortable = true
s.template = "cbi/tblsection"
s.extedit = dsp.build_url("admin/services/v2ray/outbounds/%s")
s.create = function (...)
local sid = TypedSection.create(...)
if sid then
m.uci:save("v2ray")
luci.http.redirect(s.extedit % sid)
return
end
end
o = s:option(DummyValue, "alias", translate("Alias"))
o.cfgvalue = function (...)
return Value.cfgvalue(...) or "?"
end
o = s:option(DummyValue, "send_through", translate("Send Through"))
o.cfgvalue = function (...)
return Value.cfgvalue(...) or "-"
end
o = s:option(DummyValue, "protocol", translate("Protocol"))
o.cfgvalue = function (...)
return Value.cfgvalue(...) or "?"
end
o = s:option(DummyValue, "ss_network", translate("Stream Network"))
o.cfgvalue = function (...)
return Value.cfgvalue(...) or "?"
end
o = s:option(DummyValue, "tag", translate("Tag"))
o.cfgvalue = function (...)
return Value.cfgvalue(...) or "?"
end
return m
| apache-2.0 |
vince06fr/prosody-modules | mod_privacy_lists/mod_privacy_lists.lua | 32 | 15782 | -- Prosody IM
-- Copyright (C) 2009-2014 Matthew Wild
-- Copyright (C) 2009-2014 Waqas Hussain
-- Copyright (C) 2009 Thilo Cestonaro
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
module:add_feature("jabber:iq:privacy");
local st = require "util.stanza";
local bare_sessions, full_sessions = prosody.bare_sessions, prosody.full_sessions;
local util_Jid = require "util.jid";
local jid_bare = util_Jid.bare;
local jid_split, jid_join = util_Jid.split, util_Jid.join;
local load_roster = require "core.rostermanager".load_roster;
local to_number = tonumber;
local privacy_storage = module:open_store("privacy");
local user_sessions = hosts[module.host].sessions;
local function get_lists(username)
return user_sessions[username].privacy_lists;
end
local function save_lists(username)
local privacy_lists = user_sessions[username].privacy_lists;
if privacy_lists.default == nil and next(privacy_lists.lists) == nil then
privacy_lists = nil;
end
return privacy_storage:set(username, privacy_lists);
end
module:hook("resource-bind", function (event)
local username = event.session.username;
user_sessions[username].privacy_lists = privacy_storage:get(username) or { lists = {} };
end);
function isListUsed(origin, name, privacy_lists)
local user = bare_sessions[origin.username.."@"..origin.host];
if user then
for resource, session in pairs(user.sessions) do
if resource ~= origin.resource then
if session.activePrivacyList == name then
return true;
elseif session.activePrivacyList == nil and privacy_lists.default == name then
return true;
end
end
end
end
end
function isAnotherSessionUsingDefaultList(origin)
local user = bare_sessions[origin.username.."@"..origin.host];
if user then
for resource, session in pairs(user.sessions) do
if resource ~= origin.resource and session.activePrivacyList == nil then
return true;
end
end
end
end
function declineList(privacy_lists, origin, stanza, which)
if which == "default" then
if isAnotherSessionUsingDefaultList(origin) then
return { "cancel", "conflict", "Another session is online and using the default list."};
end
privacy_lists.default = nil;
origin.send(st.reply(stanza));
elseif which == "active" then
origin.activePrivacyList = nil;
origin.send(st.reply(stanza));
else
return {"modify", "bad-request", "Neither default nor active list specifed to decline."};
end
return true;
end
function activateList(privacy_lists, origin, stanza, which, name)
local list = privacy_lists.lists[name];
if which == "default" and list then
if isAnotherSessionUsingDefaultList(origin) then
return {"cancel", "conflict", "Another session is online and using the default list."};
end
privacy_lists.default = name;
origin.send(st.reply(stanza));
elseif which == "active" and list then
origin.activePrivacyList = name;
origin.send(st.reply(stanza));
elseif not list then
return {"cancel", "item-not-found", "No such list: "..name};
else
return {"modify", "bad-request", "No list chosen to be active or default."};
end
return true;
end
function deleteList(privacy_lists, origin, stanza, name)
local list = privacy_lists.lists[name];
if list then
if isListUsed(origin, name, privacy_lists) then
return {"cancel", "conflict", "Another session is online and using the list which should be deleted."};
end
if privacy_lists.default == name then
privacy_lists.default = nil;
end
if origin.activePrivacyList == name then
origin.activePrivacyList = nil;
end
privacy_lists.lists[name] = nil;
origin.send(st.reply(stanza));
return true;
end
return {"modify", "bad-request", "Not existing list specifed to be deleted."};
end
function createOrReplaceList (privacy_lists, origin, stanza, name, entries)
local bare_jid = origin.username.."@"..origin.host;
if privacy_lists.lists == nil then
privacy_lists.lists = {};
end
local list = {};
privacy_lists.lists[name] = list;
local orderCheck = {};
list.name = name;
list.items = {};
for _,item in ipairs(entries) do
if to_number(item.attr.order) == nil or to_number(item.attr.order) < 0 or orderCheck[item.attr.order] ~= nil then
return {"modify", "bad-request", "Order attribute not valid."};
end
if item.attr.type ~= nil and item.attr.type ~= "jid" and item.attr.type ~= "subscription" and item.attr.type ~= "group" then
return {"modify", "bad-request", "Type attribute not valid."};
end
local tmp = {};
orderCheck[item.attr.order] = true;
tmp["type"] = item.attr.type;
tmp["value"] = item.attr.value;
tmp["action"] = item.attr.action;
tmp["order"] = to_number(item.attr.order);
tmp["presence-in"] = false;
tmp["presence-out"] = false;
tmp["message"] = false;
tmp["iq"] = false;
if #item.tags > 0 then
for _,tag in ipairs(item.tags) do
tmp[tag.name] = true;
end
end
if tmp.type == "subscription" then
if tmp.value ~= "both" and
tmp.value ~= "to" and
tmp.value ~= "from" and
tmp.value ~= "none" then
return {"cancel", "bad-request", "Subscription value must be both, to, from or none."};
end
end
if tmp.action ~= "deny" and tmp.action ~= "allow" then
return {"cancel", "bad-request", "Action must be either deny or allow."};
end
list.items[#list.items + 1] = tmp;
end
table.sort(list.items, function(a, b) return a.order < b.order; end);
origin.send(st.reply(stanza));
if bare_sessions[bare_jid] ~= nil then
local iq = st.iq ( { type = "set", id="push1" } );
iq:tag ("query", { xmlns = "jabber:iq:privacy" } );
iq:tag ("list", { name = list.name } ):up();
iq:up();
for resource, session in pairs(bare_sessions[bare_jid].sessions) do
iq.attr.to = bare_jid.."/"..resource
session.send(iq);
end
else
return {"cancel", "bad-request", "internal error."};
end
return true;
end
function getList(privacy_lists, origin, stanza, name)
local reply = st.reply(stanza);
reply:tag("query", {xmlns="jabber:iq:privacy"});
if name == nil then
if privacy_lists.lists then
if origin.activePrivacyList then
reply:tag("active", {name=origin.activePrivacyList}):up();
end
if privacy_lists.default then
reply:tag("default", {name=privacy_lists.default}):up();
end
for name,list in pairs(privacy_lists.lists) do
reply:tag("list", {name=name}):up();
end
end
else
local list = privacy_lists.lists[name];
if list then
reply = reply:tag("list", {name=list.name});
for _,item in ipairs(list.items) do
reply:tag("item", {type=item.type, value=item.value, action=item.action, order=item.order});
if item["message"] then reply:tag("message"):up(); end
if item["iq"] then reply:tag("iq"):up(); end
if item["presence-in"] then reply:tag("presence-in"):up(); end
if item["presence-out"] then reply:tag("presence-out"):up(); end
reply:up();
end
else
return {"cancel", "item-not-found", "Unknown list specified."};
end
end
origin.send(reply);
return true;
end
module:hook("iq/bare/jabber:iq:privacy:query", function(data)
local origin, stanza = data.origin, data.stanza;
if stanza.attr.to == nil then -- only service requests to own bare JID
local query = stanza.tags[1]; -- the query element
local valid = false;
local privacy_lists = get_lists(origin.username);
if privacy_lists.lists[1] then -- Code to migrate from old privacy lists format, remove in 0.8
module:log("info", "Upgrading format of stored privacy lists for %s@%s", origin.username, origin.host);
local lists = privacy_lists.lists;
for idx, list in ipairs(lists) do
lists[list.name] = list;
lists[idx] = nil;
end
end
if stanza.attr.type == "set" then
if #query.tags == 1 then -- the <query/> element MUST NOT include more than one child element
for _,tag in ipairs(query.tags) do
if tag.name == "active" or tag.name == "default" then
if tag.attr.name == nil then -- Client declines the use of active / default list
valid = declineList(privacy_lists, origin, stanza, tag.name);
else -- Client requests change of active / default list
valid = activateList(privacy_lists, origin, stanza, tag.name, tag.attr.name);
end
elseif tag.name == "list" and tag.attr.name then -- Client adds / edits a privacy list
if #tag.tags == 0 then -- Client removes a privacy list
valid = deleteList(privacy_lists, origin, stanza, tag.attr.name);
else -- Client edits a privacy list
valid = createOrReplaceList(privacy_lists, origin, stanza, tag.attr.name, tag.tags);
end
end
end
end
elseif stanza.attr.type == "get" then
local name = nil;
local listsToRetrieve = 0;
if #query.tags >= 1 then
for _,tag in ipairs(query.tags) do
if tag.name == "list" then -- Client requests a privacy list from server
name = tag.attr.name;
listsToRetrieve = listsToRetrieve + 1;
end
end
end
if listsToRetrieve == 0 or listsToRetrieve == 1 then
valid = getList(privacy_lists, origin, stanza, name);
end
end
if valid ~= true then
valid = valid or { "cancel", "bad-request", "Couldn't understand request" };
if valid[1] == nil then
valid[1] = "cancel";
end
if valid[2] == nil then
valid[2] = "bad-request";
end
origin.send(st.error_reply(stanza, valid[1], valid[2], valid[3]));
else
save_lists(origin.username);
end
return true;
end
end);
function checkIfNeedToBeBlocked(e, session)
local origin, stanza = e.origin, e.stanza;
local user = user_sessions[session.username];
local privacy_lists = user and user.privacy_lists;
local bare_jid = session.username.."@"..session.host;
local to = stanza.attr.to or bare_jid;
local from = stanza.attr.from;
local is_to_user = bare_jid == jid_bare(to);
local is_from_user = bare_jid == jid_bare(from);
--module:log("debug", "stanza: %s, to: %s, from: %s", tostring(stanza.name), tostring(to), tostring(from));
if not privacy_lists or privacy_lists.lists == nil or
not (session.activePrivacyList or privacy_lists.default)
then
return; -- Nothing to block, default is Allow all
end
if is_from_user and is_to_user then
--module:log("debug", "Not blocking communications between user's resources");
return; -- from one of a user's resource to another => HANDS OFF!
end
local listname = session.activePrivacyList;
if listname == nil then
listname = privacy_lists.default; -- no active list selected, use default list
end
local list = privacy_lists.lists[listname];
if not list then -- should never happen
module:log("warn", "given privacy list not found. name: %s for user %s", listname, bare_jid);
return;
end
for _,item in ipairs(list.items) do
local apply = false;
local block = false;
if (
(stanza.name == "message" and item.message) or
(stanza.name == "iq" and item.iq) or
(stanza.name == "presence" and is_to_user and item["presence-in"]) or
(stanza.name == "presence" and is_from_user and item["presence-out"]) or
(item.message == false and item.iq == false and item["presence-in"] == false and item["presence-out"] == false)
) then
apply = true;
end
if apply then
local evilJid = {};
apply = false;
if is_to_user then
--module:log("debug", "evil jid is (from): %s", from);
evilJid.node, evilJid.host, evilJid.resource = jid_split(from);
else
--module:log("debug", "evil jid is (to): %s", to);
evilJid.node, evilJid.host, evilJid.resource = jid_split(to);
end
if item.type == "jid" and
(evilJid.node and evilJid.host and evilJid.resource and item.value == evilJid.node.."@"..evilJid.host.."/"..evilJid.resource) or
(evilJid.node and evilJid.host and item.value == evilJid.node.."@"..evilJid.host) or
(evilJid.host and evilJid.resource and item.value == evilJid.host.."/"..evilJid.resource) or
(evilJid.host and item.value == evilJid.host) then
apply = true;
block = (item.action == "deny");
elseif item.type == "group" then
local roster = load_roster(session.username, session.host);
local roster_entry = roster[jid_join(evilJid.node, evilJid.host)];
if roster_entry then
local groups = roster_entry.groups;
for group in pairs(groups) do
if group == item.value then
apply = true;
block = (item.action == "deny");
break;
end
end
end
elseif item.type == "subscription" then -- we need a valid bare evil jid
local roster = load_roster(session.username, session.host);
local roster_entry = roster[jid_join(evilJid.node, evilJid.host)];
if (not(roster_entry) and item.value == "none")
or (roster_entry and roster_entry.subscription == item.value) then
apply = true;
block = (item.action == "deny");
end
elseif item.type == nil then
apply = true;
block = (item.action == "deny");
end
end
if apply then
if block then
-- drop and not bounce groupchat messages, otherwise users will get kicked
if stanza.attr.type == "groupchat" then
return true;
end
module:log("debug", "stanza blocked: %s, to: %s, from: %s", tostring(stanza.name), tostring(to), tostring(from));
if stanza.name == "message" then
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
elseif stanza.name == "iq" and (stanza.attr.type == "get" or stanza.attr.type == "set") then
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
end
return true; -- stanza blocked !
else
--module:log("debug", "stanza explicitly allowed!")
return;
end
end
end
end
function preCheckIncoming(e)
local session;
if e.stanza.attr.to ~= nil then
local node, host, resource = jid_split(e.stanza.attr.to);
if node == nil or host == nil then
return;
end
if resource == nil then
local prio = 0;
if bare_sessions[node.."@"..host] ~= nil then
for resource, session_ in pairs(bare_sessions[node.."@"..host].sessions) do
if session_.priority ~= nil and session_.priority > prio then
session = session_;
prio = session_.priority;
end
end
end
else
session = full_sessions[node.."@"..host.."/"..resource];
end
if session ~= nil then
return checkIfNeedToBeBlocked(e, session);
else
--module:log("debug", "preCheckIncoming: Couldn't get session for jid: %s@%s/%s", tostring(node), tostring(host), tostring(resource));
end
end
end
function preCheckOutgoing(e)
local session = e.origin;
if e.stanza.attr.from == nil then
e.stanza.attr.from = session.username .. "@" .. session.host;
if session.resource ~= nil then
e.stanza.attr.from = e.stanza.attr.from .. "/" .. session.resource;
end
end
if session.username then -- FIXME do properly
return checkIfNeedToBeBlocked(e, session);
end
end
module:hook("pre-message/full", preCheckOutgoing, 500);
module:hook("pre-message/bare", preCheckOutgoing, 500);
module:hook("pre-message/host", preCheckOutgoing, 500);
module:hook("pre-iq/full", preCheckOutgoing, 500);
module:hook("pre-iq/bare", preCheckOutgoing, 500);
module:hook("pre-iq/host", preCheckOutgoing, 500);
module:hook("pre-presence/full", preCheckOutgoing, 500);
module:hook("pre-presence/bare", preCheckOutgoing, 500);
module:hook("pre-presence/host", preCheckOutgoing, 500);
module:hook("message/full", preCheckIncoming, 500);
module:hook("message/bare", preCheckIncoming, 500);
module:hook("message/host", preCheckIncoming, 500);
module:hook("iq/full", preCheckIncoming, 500);
module:hook("iq/bare", preCheckIncoming, 500);
module:hook("iq/host", preCheckIncoming, 500);
module:hook("presence/full", preCheckIncoming, 500);
module:hook("presence/bare", preCheckIncoming, 500);
module:hook("presence/host", preCheckIncoming, 500);
| mit |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/bretzel.lua | 1 | 1237 | -----------------------------------------
-- ID: 4391
-- Item: Bretzel
-- Food Effect: 3Min, All Races
-----------------------------------------
-- Magic % 8
-- Magic Cap 55
-- Vitality 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,180,0,4391);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 8);
target:addMod(MOD_FOOD_MP_CAP, 55);
target:addMod(MOD_VIT, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 8);
target:delMod(MOD_FOOD_MP_CAP, 55);
target:delMod(MOD_VIT, 2);
end;
| gpl-3.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/water_surface_20.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/water_surface_5.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/water_surface_18.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
madpilot78/ntopng | scripts/lua/rest/v2/get/all/alert/ts.lua | 2 | 1609 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path
local alert_utils = require "alert_utils"
local alert_consts = require "alert_consts"
local alert_entities = require "alert_entities"
local rest_utils = require("rest_utils")
local all_alert_store = require "all_alert_store".new()
local alert_severities = require "alert_severities"
local auth = require "auth"
--
-- Read alerts count by time
-- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1"}' http://localhost:3000/lua/rest/v2/get/host/alert/ts.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local ifid = _GET["ifid"]
if not auth.has_capability(auth.capabilities.alerts) then
rest_utils.answer(rest_utils.consts.err.not_granted)
return
end
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
interface.select(ifid)
local res = {
series = {},
colors = {}
}
local count_data = all_alert_store:count_by_severity_and_time(true)
for _, severity in pairsByField(alert_severities, "severity_id", rev) do
if(count_data[severity.severity_id] ~= nil) then
res.series[#res.series + 1] = {
name = i18n(severity.i18n_title),
data = count_data[severity.severity_id],
}
res.colors[#res.colors + 1] = severity.color
end
end
rest_utils.answer(rc, res)
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.