content
stringlengths 5
1.05M
|
|---|
local _M = {}
function _M.debug_log(msg)
ngx.log(ngx.DEBUG, msg);
end
function _M.warn_log(msg)
ngx.log(ngx.WARN, msg);
end
function _M.error_log(msg)
ngx.log(ngx.ERR, msg);
end
function _M.load_module_if_exists(module_name)
local status, res = pcall(require, module_name)
if status then
return true, res
-- Here we match any character because if a module has a dash '-' in its name, we would need to escape it.
elseif type(res) == "string" and string_find(res, "module '"..module_name.."' not found", nil, true) then
return false
else
error(res)
end
end
function _M.get_ip()
local myIP = ngx.req.get_headers()["X-Real-IP"]
if myIP == nil then
myIP = ngx.req.get_headers()["x_forwarded_for"]
end
if myIP == nil then
myIP = ngx.var.remote_addr
end
return myIP;
end
--判断table是否为空
function _M.isTableEmpty(t)
return t == nil or next(t) == nil
end
--两个table合并
function _M.union(table1,table2)
for k, v in pairs(table2) do
table1[k] = v
end
return table1
end
return _M
|
-- this is a comment
(( )){} -- grouping stuff
*+-/=<> <= == -- operators
"ivan"
[[
ivan\nvasil
]]
23.5
11.6
ivan = "ivan"
break
goto
until
-- a = {1, 2, 3}
-- print(string)
print("ivan\arakitic")
--[[
ivan
]]
|
local module = {
authenticationRequired = true;
};
function module.run(authentication)
local endpoint = "https://friends.roblox.com/v1/user/friend-requests/decline-all";
local response,body = api.request("POST",endpoint,{{"Content-Length",0}},{},authentication,true,true);
if(response.code == 200) then
return true,response;
else
logger:log(1,"Something went wrong.");
return false,response;
end
end
return module;
|
local SoftMin, parent = torch.class('nn.SoftMin', 'nn.Module')
function SoftMin:updateOutput(input)
self.mininput = self.mininput or input.new()
self.mininput:resizeAs(input):copy(input):mul(-1)
return input.nn.SoftMax_updateOutput(self, self.mininput)
end
function SoftMin:updateGradInput(input, gradOutput)
self.mininput = self.mininput or input.new()
self.mininput:resizeAs(input):copy(input):mul(-1)
self.gradInput = input.nn.SoftMax_updateGradInput(self, self.mininput, gradOutput)
self.gradInput:mul(-1)
return self.gradInput
end
|
--[[
© 2020 TERRANOVA do not share, re-distribute or modify
without permission of its author.
--]]
ITEM.name = "NOGO Vodka";
ITEM.model = "models/mark2580/gtav/barstuff/Vodka_Bottle.mdl";
ITEM.width = 1;
ITEM.height = 2;
ITEM.description = "Maybe the universe is trying to tell me something.";
ITEM.permit = "consumables";
ITEM.price = 20;
ITEM.capacity = 750
ITEM.restoreStamina = 22;
ITEM.category = "Alcohol"
ITEM.flag = "R"
ITEM.dropSound = {
"terranova/ui/movingalcohol1.wav",
"terranova/ui/movingalcohol2.wav",
"terranova/ui/movingalcohol3.wav",
}
|
RegisterCommand('coords', function(source, args, rawCommand)
local ped = PlayerPedId()
local coords = GetEntityCoords(PlayerPedId())
SendNUIMessage({
coords = ""..coords.x..","..coords.y..","..coords.z..", HEADING: "..GetEntityHeading(ped)..""
})
end)
|
--[[
Topology stored as set of faces. Each face is list of n vertex indices
corresponding to one oriented, n-sided face. Vertices listed clockwise as seen from outside.
this.faces = [ [vidx1, vidx2, vidx3] ]
--]]
local Polyhedron = require(game:GetService("ReplicatedStorage"):WaitForChild("polyhedron"))
function icosahedron()
local faces = {
{1, 2, 3}, {1, 3, 4}, {1, 4, 5}, {1, 5, 6},
{1, 6, 2}, {2, 6, 8}, {2, 8, 7}, {2, 7, 3},
{3, 7, 9}, {3, 9, 4}, {4, 9, 10}, {4, 10, 5},
{5, 10, 11}, {5, 11, 6}, {6, 11, 8}, {7, 8, 12},
{7, 12, 9}, {8, 11, 12}, {9, 12, 10}, {10, 12, 11},
}
local vertices = {
Vector3.new(0,0,1.176), Vector3.new(1.051,0,0.526),
Vector3.new(0.324,1.0,0.525), Vector3.new(-0.851,0.618,0.526),
Vector3.new(-0.851,-0.618,0.526), Vector3.new(0.325,-1.0,0.526),
Vector3.new(0.851,0.618,-0.526), Vector3.new(0.851,-0.618,-0.526),
Vector3.new(-0.325,1.0,-0.526), Vector3.new(-1.051,0,-0.526),
Vector3.new(-0.325,-1.0,-0.526), Vector3.new(0,0,-1.176),
}
local name = "I"
local poly = Polyhedron.new(faces, vertices, name)
poly:Scale(1.075269) -- make all vertices approx 1 unit away from center so scaling in the future is predictable
return poly
end
return icosahedron
|
DEFINE_BASECLASS( "player_default" )
local PLAYER = {}
--
-- See gamemodes/base/player_class/player_default.lua for all overridable variables
--
PLAYER.DisplayName = "Spectator"
PLAYER.SetObserverMode = 6
PLAYER.CanUseFlashlight = false
PLAYER.AvoidPlayers = false
PLAYER.lastTaunt = 0.0
function PLAYER:Spawn()
self.Player:Spectate( OBS_MODE_ROAMING )
end
function PLAYER:Loadout()
self.Player:RemoveAllAmmo()
end
player_manager.RegisterClass( "player_spectator", PLAYER, "player_default" )
|
return {
author = {
name = 'Mermaid Heavy Industries',
link = 'https://mermaid.industries'
}
}
|
pg = pg or {}
pg.enemy_data_statistics_153 = {
[10104024] = {
cannon = 200,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
rarity = 3,
air = 0,
torpedo = 0,
dodge = 11,
durability_growth = 340000,
antiaircraft = 180,
luck = 30,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 3,
hit = 25,
antisub_growth = 0,
air_growth = 4000,
battle_unit_type = 80,
base = 251,
durability = 18600,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 20,
armor = 0,
id = 10104024,
antiaircraft_growth = 4400,
antisub = 0,
equipment_list = {
564321,
564322,
564323,
564324,
564325
}
},
[10104101] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 0,
durability_growth = 6800,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
speed = 30,
star = 1,
hit = 8,
antisub_growth = 0,
air_growth = 0,
hit_growth = 120,
base = 90,
durability = 850,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
antiaircraft_growth = 0,
luck = 0,
battle_unit_type = 20,
id = 10104101,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
}
},
[10104102] = {
cannon = 0,
battle_unit_type = 35,
rarity = 1,
speed_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
luck = 0,
dodge = 0,
wave_fx = "danchuanlanghuaxiao2",
cannon_growth = 0,
speed = 15,
reload_growth = 0,
dodge_growth = 0,
id = 10104102,
star = 1,
hit = 8,
antisub_growth = 0,
air_growth = 0,
reload = 150,
base = 70,
durability = 320,
armor_growth = 0,
torpedo_growth = 864,
luck_growth = 0,
hit_growth = 120,
armor = 0,
torpedo = 70,
durability_growth = 2550,
antisub = 0,
antiaircraft = 0,
antiaircraft_growth = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
564101
}
},
[10104103] = {
cannon = 100,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 80000,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 180,
durability_growth = 2550,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 1200,
star = 1,
hit = 81,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 15,
base = 80,
durability = 90,
armor_growth = 0,
torpedo_growth = 900,
luck_growth = 0,
speed = 30,
luck = 0,
id = 10104103,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
564102
}
},
[10104510] = {
cannon = 360,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 70049,
air = 280,
rarity = 5,
dodge = 18,
torpedo = 0,
durability_growth = 0,
antiaircraft = 540,
reload_growth = 0,
dodge_growth = 256,
hit_growth = 210,
star = 5,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 95,
base = 252,
durability = 88000,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 18,
luck = 60,
id = 10104510,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
564521,
564522,
564523,
564524,
564525
}
},
[10104520] = {
cannon = 350,
antiaircraft_growth = 0,
rarity = 6,
speed_growth = 0,
pilot_ai_template_id = 70053,
air = 0,
luck = 60,
dodge = 14,
id = 10104520,
cannon_growth = 0,
speed = 16,
reload_growth = 0,
dodge_growth = 192,
reload = 150,
star = 6,
hit = 30,
antisub_growth = 0,
air_growth = 0,
torpedo = 220,
base = 233,
durability = 90000,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
battle_unit_type = 95,
armor = 0,
durability_growth = 0,
antiaircraft = 620,
antisub = 0,
hit_growth = 210,
cld_box = {
5.5,
7.5,
8
},
bound_bone = {
cannon = {
{
1.28,
1.19,
0
}
},
vicegun = {
{
1.28,
1.19,
0
}
},
torpedo = {
{
0.29,
0.09,
0
}
},
antiaircraft = {
{
1.28,
1.19,
0
}
}
},
smoke = {
{
70,
{
{
"smoke",
{
-0.74,
0.86,
-0.18
}
}
}
},
{
40,
{
{
"smoke",
{
0.03,
2.66,
-1.22
}
}
}
}
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
564511,
564513,
564514,
564517,
564518,
564519
}
},
[10104530] = {
cannon = 350,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 70050,
air = 0,
rarity = 5,
dodge = 16,
torpedo = 200,
durability_growth = 0,
antiaircraft = 520,
reload_growth = 0,
dodge_growth = 228,
hit_growth = 210,
star = 5,
hit = 35,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 0,
base = 261,
durability = 97000,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 18,
luck = 60,
id = 10104530,
armor = 0,
antisub = 0,
equipment_list = {
564531,
564532,
564533,
564535,
564536,
564537
},
buff_list = {
{
ID = 50500,
LV = 4
}
}
},
[10105001] = {
cannon = 8,
prefab = "srDD2",
reload = 150,
cannon_growth = 560,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 36,
durability_growth = 16500,
antiaircraft = 80,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
hit_growth = 144,
base = 123,
durability = 750,
armor_growth = 0,
torpedo_growth = 3250,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 25,
antisub = 0,
id = 10105001,
antiaircraft_growth = 1000,
equipment_list = {
100219,
535001,
313091
}
},
[10105002] = {
cannon = 16,
prefab = "srCL2",
reload = 150,
cannon_growth = 880,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 28,
durability_growth = 26000,
antiaircraft = 240,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
hit_growth = 144,
base = 124,
durability = 1050,
armor_growth = 0,
torpedo_growth = 2250,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 30,
antisub = 0,
id = 10105002,
antiaircraft_growth = 2250,
equipment_list = {
561024,
100349
}
},
[10105003] = {
cannon = 21,
prefab = "srCA2",
reload = 150,
cannon_growth = 1800,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 18,
durability_growth = 46000,
antiaircraft = 180,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
hit_growth = 144,
base = 125,
durability = 2000,
armor_growth = 0,
torpedo_growth = 1250,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 35,
antisub = 0,
id = 10105003,
antiaircraft_growth = 1400,
equipment_list = {
100206,
100519,
535002
}
},
[10105004] = {
cannon = 47,
prefab = "srBB2",
reload = 150,
cannon_growth = 2200,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 0,
durability_growth = 88000,
antiaircraft = 140,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
hit_growth = 144,
base = 126,
durability = 6200,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 60,
antisub = 0,
id = 10105004,
antiaircraft_growth = 1400,
equipment_list = {
531033,
531034,
531035
}
},
[10105005] = {
cannon = 0,
prefab = "srCV2",
reload = 150,
cannon_growth = 0,
speed_growth = 0,
air = 60,
rarity = 2,
dodge = 0,
torpedo = 0,
durability_growth = 82000,
antiaircraft = 260,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 2000,
hit_growth = 144,
base = 127,
durability = 5500,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 65,
antisub = 0,
id = 10105005,
antiaircraft_growth = 1800,
bound_bone = {
cannon = {
{
1.8,
1.14,
0
}
},
torpedo = {
{
1.07,
0.24,
0
}
},
antiaircraft = {
{
1.8,
1.14,
0
}
},
plane = {
{
1.8,
1.14,
0
}
}
},
equipment_list = {
565001,
565002,
565003,
565004
}
},
[10105006] = {
cannon = 75,
reload = 150,
speed_growth = 0,
cannon_growth = 900,
rarity = 5,
air = 0,
torpedo = 160,
dodge = 14,
durability_growth = 48500,
antiaircraft = 120,
luck = 40,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 5,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 248,
durability = 13600,
armor_growth = 0,
torpedo_growth = 6000,
luck_growth = 0,
speed = 20,
armor = 0,
id = 10105006,
antiaircraft_growth = 2500,
antisub = 0,
equipment_list = {
565301,
565302,
565303,
565304,
565305,
565306
}
},
[10105007] = {
cannon = 115,
reload = 150,
speed_growth = 0,
cannon_growth = 1400,
rarity = 5,
air = 0,
torpedo = 100,
dodge = 14,
durability_growth = 65000,
antiaircraft = 280,
luck = 40,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 5,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 65,
base = 249,
durability = 16400,
armor_growth = 0,
torpedo_growth = 4500,
luck_growth = 0,
speed = 20,
armor = 0,
id = 10105007,
antiaircraft_growth = 3800,
antisub = 0,
equipment_list = {
565311,
565312,
565313,
565314,
565315,
565316
}
},
[10105008] = {
cannon = 175,
reload = 150,
speed_growth = 0,
cannon_growth = 2000,
rarity = 5,
air = 0,
torpedo = 60,
dodge = 14,
durability_growth = 84000,
antiaircraft = 220,
luck = 40,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 5,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 70,
base = 250,
durability = 22200,
armor_growth = 0,
torpedo_growth = 2400,
luck_growth = 0,
speed = 20,
armor = 0,
id = 10105008,
antiaircraft_growth = 2800,
antisub = 0,
equipment_list = {
565321,
565322,
565323,
565324,
565325,
565326,
565327
}
},
[10105009] = {
cannon = 200,
reload = 150,
speed_growth = 0,
cannon_growth = 2000,
rarity = 5,
air = 0,
torpedo = 0,
dodge = 14,
durability_growth = 132000,
antiaircraft = 180,
luck = 40,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 5,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 75,
base = 252,
durability = 28200,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 20,
armor = 0,
id = 10105009,
antiaircraft_growth = 3400,
antisub = 0,
equipment_list = {
565331,
565332,
565333,
565334,
565335
}
}
}
return
|
-----------------------------------------------------
local FLASHTIMER = 2; --time in seconds, for the grenade to transition from full white to clear
local EFFECT_DELAY = 10; --time, in seconds when the effects still are going on, even when the whiteness of the flash is gone (set to -1 for no effects at all =]).
local Endflash, Endflash2;
function ENT:Initialize()
local Pos = self:GetPos()
timer.Simple(2, function()
local dynamicflash = DynamicLight( self:EntIndex() )
if ( dynamicflash ) then
dynamicflash.Pos = Pos
dynamicflash.r = 255
dynamicflash.g = 255
dynamicflash.b = 255
dynamicflash.Brightness = 5
dynamicflash.Size = 1000
dynamicflash.Decay = 1000
dynamicflash.DieTime = CurTime() + 0.5
end
end)
end
function ENT:Think()
end
function ENT:Draw()
self.Entity:DrawModel()
end
function ENT:IsTranslucent()
return true
end
function FlashEffect() if LocalPlayer():GetNetworkedFloat("FLASHED_END") > CurTime() then
local pl = LocalPlayer();
local FlashedEnd = pl:GetNetworkedFloat("FLASHED_END")
local FlashedStart = pl:GetNetworkedFloat("FLASHED_START")
local Alpha
if(FlashedEnd - CurTime() > FLASHTIMER) then
Alpha = 150;
else
local FlashAlpha = 1 - (CurTime() - (FlashedEnd - FLASHTIMER)) / (FlashedEnd - (FlashedEnd - FLASHTIMER));
Alpha = FlashAlpha * 150;
end
surface.SetDrawColor(255, 255, 255, math.Round(Alpha))
surface.DrawRect(0, 0, surface.ScreenWidth(), surface.ScreenHeight())
end
end
hook.Add("HUDPaint", "FlashEffect", FlashEffect);
local function StunEffect()
local pl = LocalPlayer();
local FlashedEnd = pl:GetNetworkedFloat("FLASHED_END")
local FlashedStart = pl:GetNetworkedFloat("FLASHED_START")
if (FlashedEnd > CurTime() and FlashedEnd - EFFECT_DELAY - CurTime() <= FLASHTIMER) then
local FlashAlpha = 1 - (CurTime() - (FlashedEnd - FLASHTIMER)) / (FLASHTIMER);
DrawMotionBlur( 0, FlashAlpha / ((FLASHTIMER + EFFECT_DELAY) / (FLASHTIMER * 4)), 0);
elseif (FlashedEnd > CurTime()) then
DrawMotionBlur( 0, 0.01, 0);
else
DrawMotionBlur( 0, 0, 0);
end
end
hook.Add( "RenderScreenspaceEffects", "StunEffect", StunEffect )
|
local APIData = require(script.APIData)
local APIInterface = require(script.APIInterface)
---
local APIUtils = {}
APIUtils.createAPIData = APIData.new
APIUtils.createAPIInterface = APIInterface.new
return APIUtils
|
data:extend(
{
{
type = "item",
name = "cursix-scrambled-eggs-equipment",
icon = "__cursix-tech__/graphics/icons/cursix-scrambled-eggs-equipment.png",
icon_size = 32,
placed_as_equipment_result = "cursix-scrambled-eggs-equipment",
flags = {},
subgroup = "equipment",
order = "a[energy-source]-b[sonic-scrambled-eggs]",
stack_size = 500,
default_request_amount = 10
},
{
type = "item",
name = "cursix-akane-eggs-equipment",
icon = "__cursix-tech__/graphics/icons/cursix-akane-eggs-equipment.png",
icon_size = 32,
placed_as_equipment_result = "cursix-akane-eggs-equipment",
flags = {},
subgroup = "equipment",
order = "a[energy-source]-c[akane-eggs]",
stack_size = 500,
default_request_amount = 10
},
{
type = "item",
name = "cursix-barrier-jacket-equipment",
icon = "__cursix-tech__/graphics/icons/cursix-barrier-jacket-equipment.png",
icon_size = 32,
placed_as_equipment_result = "cursix-barrier-jacket-equipment",
flags = {},
subgroup = "equipment",
order = "b[shield]-a[barrier-jacket]",
stack_size = 500,
default_request_amount = 10
},
{
type = "item",
name = "cursix-barrier-jacket-mk2-equipment",
icon = "__cursix-tech__/graphics/icons/cursix-barrier-jacket-mk2-equipment.png",
icon_size = 32,
placed_as_equipment_result = "cursix-barrier-jacket-mk2-equipment",
flags = {},
subgroup = "equipment",
order = "b[shield]-b[barrier-jacket-mk2]",
stack_size = 500,
default_request_amount = 10
},
{
type = "item",
name = "cursix-energy-storage-crystal-equipment",
icon = "__cursix-tech__/graphics/icons/cursix-energy-storage-crystal-equipment.png",
icon_size = 32,
placed_as_equipment_result = "cursix-energy-storage-crystal-equipment",
flags = {},
subgroup = "equipment",
order = "c[battery]-b[cursix-energy-storage-crystal-equipment]",
stack_size = 500,
default_request_amount = 10
},
{
type = "item",
name = "cursix-speed-shoes-equipment",
icon = "__cursix-tech__/graphics/icons/cursix-speed-shoes-equipment.png",
icon_size = 32,
placed_as_equipment_result = "cursix-speed-shoes-equipment",
flags = {},
subgroup = "equipment",
order = "e[exoskeleton]-a[cursix-speed-shoes-equipment]",
stack_size = 500,
default_request_ammount = 10
},
{
type = "item",
name = "cursix-axel-shooter-equipment",
icon = "__cursix-tech__/graphics/icons/cursix-axel-shooter-equipment.png",
icon_size = 64,
placed_as_equipment_result = "cursix-axel-shooter-equipment",
flags = {},
subgroup = "equipment",
order = "b[active-defense]-a[cursix-axel-shooter-equipment]",
stack_size = 500,
default_request_amount = 10
},
{
type = "item",
name = "cursix-moogle-roboport-equipment",
icon = "__cursix-tech__/graphics/icons/cursix-moogle-roboport-equipment.png",
icon_size = 64,
placed_as_equipment_result = "cursix-moogle-roboport-equipment",
flags = {},
subgroup = "equipment",
order = "e[robotics]-c[cursix-moogle-roboport-equipment]",
stack_size = 500,
default_request_amount = 20
}
}
)
|
--[[
Casual Mission script - Version: 1.02 - 2/2/2020 by Theodossis Papadopoulos
-- Requires MIST
-- Points only work with my other script: PointSystem ELSE use variables: extraBluePoints, extraRedPoints
]]
-- -----------------------------------CODE DO NOT TOUCH-----------------------------------
local TARGETS_FOR_BLUE = {}
local TARGETS_FOR_RED = {}
-- -----------------------------------CONFIGURATION---------------------------------------
TARGETS_FOR_BLUE[1] = {
Targets = {"BT_1A", "BT_1B"},
DisplayName = "mobiles/sat",
Briefing = "Just destroy them",
Points = 2
}
TARGETS_FOR_BLUE[2] = {
Targets = {"BT_2"},
DisplayName = "something 2",
Briefing = "some briefing",
Points = 2
}
TARGETS_FOR_BLUE[3] = {
Targets = {"BT_3"},
DisplayName = "something 3",
Briefing = "some briefing",
Points = 2
}
TARGETS_FOR_RED[1] = {
Targets = {"RT_1", "RT_2"},
DisplayName = "something",
Briefing = "Just destroy them",
Points = 2
}
-- -----------------------------------CODE DO NOT TOUCH-----------------------------------
local function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
local function contains(tab, val)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
local function groupIsDead(inGroupName)
local groupHealth = 0
local groupDead = false
for index, unitData in pairs(Group.getByName(inGroupName):getUnits()) do
groupHealth = groupHealth + unitData:getLife()
end
if groupHealth < 1 then
groupDead = true
end
return groupDead
end
local function tableConcat(t1, t2)
for i=1, #t2 do
t1[#t1+1] = t2[i]
end
return t1
end
local function showTargets(gpid)
local earlyBreak = false
local blueUnits = mist.utils.deepCopy(coalition.getPlayers(coalition.side.BLUE))
local redUnits = mist.utils.deepCopy(coalition.getPlayers(coalition.side.RED))
local allUnits = tableConcat(blueUnits, redUnits)
for j=1, tablelength(allUnits) do
local us = allUnits[j]
if us:getGroup():getID() == gpid then -- Found him/them for two seat
earlyBreak = true
local finalMsg = nil
if us:getCoalition() == coalition.side.BLUE then
finalMsg = "Target report:"
for i=1, tablelength(TARGETS_FOR_BLUE) do
if tablelength(TARGETS_FOR_BLUE[i].Progression) ~= tablelength(TARGETS_FOR_BLUE[i].Targets) then -- Check if it is already done
finalMsg = finalMsg .. "\n#" .. i .. ": " .. TARGETS_FOR_BLUE[i].Briefing
end
end
elseif us:getCoalition() == coalition.side.RED then
finalMsg = "Target report:"
for i=1, tablelength(TARGETS_FOR_RED) do
if tablelength(TARGETS_FOR_RED[i].Progression) ~= tablelength(TARGETS_FOR_RED[i].Targets) then -- Check if it is already done
finalMsg = finalMsg .. "\n#" .. i .. ": " .. TARGETS_FOR_RED[i].Briefing
end
end
end
trigger.action.outTextForGroup(gpid, finalMsg, 45)
end
if earlyBreak == true then
break
end
end
end
local EV_MANAGER = {}
function EV_MANAGER:onEvent(event)
if event.id == world.event.S_EVENT_BIRTH then
if event.initiator:getCategory() == Object.Category.UNIT then
if event.initiator:getGroup():getCategory() == Group.Category.AIRPLANE or event.initiator:getGroup():getCategory() == Group.Category.HELICOPTER then
local gpid = event.initiator:getGroup():getID()
missionCommands.removeItemForGroup(event.initiator:getGroup():getID(), {[1] = "Show targets"})
missionCommands.addCommandForGroup(gpid, "Show targets", nil, showTargets, gpid)
end
end
elseif event.id == world.event.S_EVENT_DEAD then
-- FOR BLUE TEAM
local un = event.initiator
if un:getCategory() == Object.Category.UNIT or un:getCategory() == Object.Category.STATIC then
if un:getCoalition() == coalition.side.RED then -- Red target destroyed
local earlyBreak = false
for i=1, tablelength(TARGETS_FOR_BLUE) do
if tablelength(TARGETS_FOR_BLUE[i].Progression) ~= tablelength(TARGETS_FOR_BLUE[i].Targets) then -- Check if it is already done
if un:getCategory() == Object.Category.UNIT then
if groupIsDead(un:getGroup():getName()) then
if contains(TARGETS_FOR_BLUE[i].Targets, un:getGroup():getName()) then
TARGETS_FOR_BLUE[i].Progression[tablelength(TARGETS_FOR_BLUE[i].Progression) + 1] = un:getGroup():getName()
earlyBreak = true
end
end
elseif un:getCategory() == Object.Category.STATIC then
if contains(TARGETS_FOR_BLUE[i].Targets, un:getName()) then
TARGETS_FOR_BLUE[i].Progression[tablelength(TARGETS_FOR_BLUE[i].Progression) + 1] = un:getName()
earlyBreak = true
end
end
if tablelength(TARGETS_FOR_BLUE[i].Progression) == tablelength(TARGETS_FOR_BLUE[i].Targets) then -- TARGET DESTRUCTION COMPLETED
trigger.action.outTextForCoalition(coalition.side.BLUE, "We have successfully destroyed RED's team " .. TARGETS_FOR_BLUE[i].DisplayName, 20)
trigger.action.outTextForCoalition(coalition.side.RED, "Our " .. TARGETS_FOR_BLUE[i].DisplayName .. " have just been destroyed by BLUE team", 20)
if extraBluePoints ~= nil then
extraBluePoints = extraBluePoints + TARGETS_FOR_BLUE[i].Points
end
end
if earlyBreak == true then
break
end
end
end
end
-- FOR RED TEAM
if un:getCoalition() == coalition.side.BLUE then -- Blue target destroyed
local earlyBreak = false
for i=1, tablelength(TARGETS_FOR_RED) do
if tablelength(TARGETS_FOR_RED[i].Progression) ~= tablelength(TARGETS_FOR_RED[i].Targets) then -- Check if it is already done
if un:getCategory() == Object.Category.UNIT then
if groupIsDead(un:getGroup():getName()) then
if contains(TARGETS_FOR_RED[i].Targets, un:getGroup():getName()) then
TARGETS_FOR_RED[i].Progression[tablelength(TARGETS_FOR_RED[i].Progression) + 1] = un:getGroup():getName()
earlyBreak = true
end
end
elseif un:getCategory() == Object.Category.STATIC then
if contains(TARGETS_FOR_RED[i].Targets, un:getName()) then
TARGETS_FOR_RED[i].Progression[tablelength(TARGETS_FOR_RED[i].Progression) + 1] = un:getName()
earlyBreak = true
end
end
if tablelength(TARGETS_FOR_RED[i].Progression) == tablelength(TARGETS_FOR_RED[i].Targets) then -- TARGET DESTRUCTION COMPLETED
trigger.action.outTextForCoalition(coalition.side.RED, "We have successfully destroyed BLUE's team " .. TARGETS_FOR_RED[i].DisplayName , 20)
trigger.action.outTextForCoalition(coalition.side.BLUE, "Our " .. TARGETS_FOR_RED[i].DisplayName .. " have just been destroyed by RED team", 20)
if extraRedPoints ~= nil then
extraRedPoints = extraRedPoints + TARGETS_FOR_RED[i].Points
end
end
if earlyBreak == true then
break
end
end
end
end
end
end
end
world.addEventHandler(EV_MANAGER)
-- Setup progression
for i=1, tablelength(TARGETS_FOR_BLUE) do
TARGETS_FOR_BLUE[i].Progression = {}
end
for i=1, tablelength(TARGETS_FOR_RED) do
TARGETS_FOR_RED[i].Progression = {}
end
|
Citizen.CreateThread(function()
local uptimeMinute, uptimeHour, uptime = 0, 0, ''
while true do
Citizen.Wait(1000 * 60) -- every minute
uptimeMinute = uptimeMinute + 1
if uptimeMinute == 60 then
uptimeMinute = 0
uptimeHour = uptimeHour + 1
end
uptime = string.format("%02dh %02dm", uptimeHour, uptimeMinute)
SetConvarServerInfo('Uptime', uptime)
TriggerClientEvent('uptime:tick', -1, uptime)
TriggerEvent('uptime:tick', uptime)
end
end)
|
if vim.fn.executable'neuron' == 0 then
error("Unable to find neuron executable on the path. Install it.")
end
local neuron_builtin = require'telescope._extensions.neuron_builtin'
return require'telescope'.register_extension{
exports = {
list = neuron_builtin.list,
backlinks = neuron_builtin.backlinks
},
}
|
Runes = Runes or class({})
function Runes:Init()
--Debug.EnableDebugging()
--DebugPrint('Init runes module')
if self.initialized then
print("Runes were already initialized and there was an attempt to initialize it again -> preventing")
return nil
end
-- Check every 0.5 second if there is a rune spawned before the first duel, if yes remove it
Timers:CreateTimer(function()
if HudTimer and HudTimer:GetGameTime() then
if HudTimer:GetGameTime() < -1 then
Runes:RemoveAllRunes()
return 0.5
end
else
return 0.5
end
end)
-- Configuring rune spawn time would be easy if RuneSpawn filter actually worked, just return false in filter if the time isn't right
--FilterManager:AddFilter(FilterManager.RuneSpawn, self, Dynamic_Wrap(Runes, "RunesSpawnFilter"))
-- dota_item_rune entities are some special entities, they are not items or npcs !!!
-- GetName() works on rune entities but returns nothing, thanks Valve
-- with GetModelName() you can find out what rune it is (model names can be found in assets browser)
-- GetOrigin() and SetOrigin() work on rune entities, at least something
-- Spawning rune entity with SpawnEntityFromTableSynchronous("dota_item_rune", { model = "", origin =}) works partially only for double damage
-- Nobody knows what parameters should be used in the table for SpawnEntityFromTableSynchronous
self.initialized = true
end
function Runes:RemoveAllRunes()
local all_runes = Entities:FindAllByClassname("dota_item_rune")
for _,rune in pairs(all_runes) do
if rune and not rune:IsNull() then
UTIL_Remove(rune)
end
end
end
|
#!/usr/bin/env lua
local sig = require 'signal'
local irc = require 'irc'
irc.DEBUG = true
local nick = "luabot"
local channel = "#doytest"
local network = "irc.freenode.org"
local envs = {}
local function create_env()
return {
_VERSION = _VERSION,
assert = assert,
collectgarbage = collectgarbage,
error = error,
getfenv = getfenv,
getmetatable = getmetatable,
ipairs = ipairs,
loadstring = loadstring,
next = next,
pairs = pairs,
pcall = pcall,
rawequal = rawequal,
rawget = rawget,
rawset = rawset,
select = select,
setfenv = setfenv,
setmetatable = setmetatable,
tonumber = tonumber,
tostring = tostring,
type = type,
unpack = unpack,
xpcall = xpcall,
coroutine = coroutine,
math = math,
string = string,
table = table,
}
end
local commands = {
eval = function(target, from, code)
code = code:gsub("^=", "return ")
local fn, err = loadstring(code)
if not fn then
irc.say(target, from .. ": Error loading code: " .. code .. err:match(".*(:.-)$"))
return
else
setfenv(fn, envs[from])
sig.signal("ALRM", error)
sig.alarm(5)
local result = {pcall(fn)}
sig.alarm(0)
sig.signal("ALRM", "default")
local success = table.remove(result, 1)
if not success then
local err = result[1]:match(".*: (.-)$")
if err == "ALRM" then err = "timed out" end
irc.say(target, from .. ": Error running code: " .. code ..
": " .. err)
else
if result[1] == nil then
irc.say(target, from .. ": nil")
else
for i, v in ipairs(result) do result[i] = tostring(v) end
irc.say(target, from .. ": " .. table.concat(result, ", "))
end
end
end
end,
clear = function(target, from)
irc.say(target, from .. ": Clearing your environment")
envs[from] = create_env()
end,
help = function(target, from, arg)
if arg == "" or not arg then
irc.say(target, from .. ": Commands: !clear, !eval, !help")
elseif arg == "eval" then
irc.say(target, from .. ": Evaluates a Lua statement in your own persistent environment")
elseif arg == "clear" then
irc.say(target, from .. ": Clears your personal environment")
end
end
}
irc.register_callback("connect", function()
irc.join(channel)
end)
irc.register_callback("channel_msg", function(channel, from, message)
message = message:gsub("^" .. nick .. "[:,>] ", "!eval ")
local is_cmd, cmd, arg = message:match("^(!)([%w_]+) ?(.-)$")
if is_cmd and commands[cmd] then
envs[from] = envs[from] or create_env()
commands[cmd](channel.name, from, arg)
end
end)
irc.register_callback("private_msg", function(from, message)
message = message:gsub("^" .. nick .. "[:,>] ", "!eval ")
local is_cmd, cmd, arg = message:match("^(!)([%w_]+) ?(.-)$")
envs[from] = envs[from] or create_env()
if is_cmd and commands[cmd] then
commands[cmd](from, from, arg)
else
commands["eval"](from, from, message)
end
end)
irc.register_callback("nick_change", function(from, old_nick)
if envs[old_nick] and not envs[from] then
envs[from] = envs[old_nick]
envs[old_nick] = nil
end
end)
irc.connect{network = network, nick = nick}
|
require('boolexpr.src.boolexpr')
Listener = setmetatable({}, {})
do
local listener = getmetatable(Listener)
listener.__index = listener
local data_table = {}
local recur_table = {}
function listener.create()
local self = setmetatable(BoolExpr.Any(), listener)
self.index_table = {}
return self
end
function listener.new() return listener.create() end
function listener:__gc()
self:clear()
self.index_table = nil
end
local evaluate = BoolExpr.evaluate
function listener:register(handler, data, max_recursion_depth)
max_recursion_depth = (max_recursion_depth and max_recursion_depth > 0) and
max_recursion_depth or 1
local index_t = self.index_table[handler] or {}
self.index_table[handler] = index_t
local handler_closure = function (func, reverse, ...)
local result
local recur_count = recur_table[func] + 1
recur_table[func] = recur_count
if recur_count <= max_recursion_depth then
result = evaluate(handler, reverse, ..., data_table[func])
self.EXCEPTION_MSG = (self.EXCEPTION_MSG or '') .. (type(handler) == 'table' and handler.EXCEPTION_MSG or '')
else
result = true
self.EXCEPTION_MSG = (self.EXCEPTION_MSG or '') .. "[Recursion Error] Recursion Level: " .. tostring(recur_count) .. '\n'
end
recur_table[func] = recur_count - 1
return result
end
self[#self + 1] = handler_closure
index_t[#index_t + 1] = #self
data_table[handler_closure] = data
recur_table[handler_closure] = 0
end
local min = math.min
function listener:deregister(handler, deregister_all)
local index_t = self.index_table[handler]
if deregister_all then
local index = index_t and index_t[1]
if index then
local n = #self
local i = 1
data_table[self[index]] = nil
index_t[i] = nil
for j = index, n do
if j + i == index_t[i + 1] then
i = i + 1
data_table[self[index_t[i]]] = nil
index_t[i] = nil
end
self[j] = self[j + i]
end
end
else
local index = index_t and index_t[#index_t]
index_t[#index_t] = nil
if index then
data_table[self[index]] = nil
for i = index, #self do
self[i] = self[i + 1]
end
end
end
end
listener.unregister = listener.deregister
function listener:clear()
for i = 2, #self do
data_table[self[i]] = nil
self[i] = nil
end
self.index_table = {}
end
function listener:__call(reverse, ...) return evaluate(self, reverse, ...) end
listener.execute = listener.__call
end
|
local sin, floor
do
local _obj_0 = math
sin, floor = _obj_0.sin, _obj_0.floor
end
local death = { }
death.textTop = "YOU"
death.textBottom = "\nDIED"
death.height = 32
death.y = death.height
local move
move = function()
return flux.to(death, 0.48, {
y = death.height + 16
}):ease("cubicin"):oncomplete(function()
return flux.to(death, 0.48, {
y = death.height
}):ease("cubicout"):oncomplete(move)
end)
end
move()
local textCentered
textCentered = function(s, font, y)
local x = gameWidth / 2 - font:getWidth(s) / 2
love.graphics.setFont(font)
return love.graphics.print(s, x, y)
end
local text
text = function(s, font, y)
love.graphics.setFont(font)
return love.graphics.print(s, 0, y)
end
death.update = function(self, dt)
return flux.update(dt)
end
death.draw = function(self)
push:start()
textCentered(self.textTop, fontFantasy, floor(self.y))
textCentered(self.textBottom, fontFantasy, floor(self.y))
textCentered("YOUR DEPTH BEFORE DYING WAS " .. tostring(depth), fontRetro, screenHeight - 64)
textCentered("PRESS ANY KEY TO CONTINUE", fontRetro, screenHeight - 48)
return push:finish()
end
death.keypressed = function(self, key)
if key == "f" then
return push:switchFullscreen(windowedWidth, windowedHeight)
else
return manager:enter(states.title, false)
end
end
return death
|
-- ======= Copyright (c) 2003-2011, Unknown Worlds Entertainment, Inc. All rights reserved. =======
--
-- lua\ShieldpackMarine.lua
--
-- Created by: Andreas Urwalek (a_urwa@sbox.tugraz.at
--
-- Thanks to twiliteblue for initial input.
--
-- ========= For more information, visit us at http://www.unknownworlds.com =====================
Script.Load("lua/Marine.lua")
Script.Load("lua/Shieldpack.lua")
class 'ShieldpackMarine' (Marine)
PrecacheAsset("cinematics/vfx_materials/nanoshield.surface_shader")
PrecacheAsset("cinematics/vfx_materials/nanoshield_view.surface_shader")
PrecacheAsset("cinematics/vfx_materials/nanoshield_exoview.surface_shader")
local kNanoShieldStartSound = PrecacheAsset("sound/NS2.fev/marine/commander/nano_shield_3D")
local kNanoLoopSound = PrecacheAsset("sound/NS2.fev/marine/commander/nano_loop")
local kNanoDamageSound = PrecacheAsset("sound/NS2.fev/marine/commander/nano_damage")
local kNanoshieldMaterial = PrecacheAsset("cinematics/vfx_materials/nanoshield.material")
local kNanoshieldExoViewMaterial = PrecacheAsset("cinematics/vfx_materials/nanoshield_exoview.material")
local kNanoshieldViewMaterial = PrecacheAsset("cinematics/vfx_materials/nanoshield_view.material")
ShieldpackMarine.kMapName = "shieldpackmarine"
ShieldpackMarine.kModelName = PrecacheAsset("models/marine/male/male.model")
ShieldpackMarine.kShieldpackPickupSound = PrecacheAsset("sound/NS2.fev/marine/common/pickup_jetpack")
ShieldpackMarine.kShieldpackNode = "ShieldPack"
kShieldCapacity = 100
kShieldCapacityUpgrade = 100
kShieldPackDamageReduction = 0 --0 = 100%
kShieldRecharge = 10
kShieldRechargeUpgrade = 10
kCombatDuration = 5
kCombatDurationUpgrade = 2.5
if Server then
Script.Load("lua/ShieldpackMarine_Server.lua")
end
local networkVars =
{
shieldCharge = "float (0 to 300 by 1)",
shieldMaxCapacity = "float (0 to 300 by 1)",
isShieldEmpty = "boolean",
lastHitTime = "time"
}
function ShieldpackMarine:OnCreate()
Marine.OnCreate(self)
self.shieldCharge = self:GetShieldCapacity()
self.shieldMaxCapacity = self:GetShieldCapacity()
self.isShieldEmpty = false
self.lastTimeHit = 0
self.isInCombat = false
end
local function InitEquipment(self)
assert(Server)
if Server then
assert(self.shieldLoopSound == nil)
self.shieldLoopSound = Server.CreateEntity(SoundEffect.kMapName)
self.shieldLoopSound:SetAsset(kNanoLoopSound)
self.shieldLoopSound:SetParent(self)
self.shieldLoopSound:Start()
StartSoundEffectOnEntity(kNanoShieldStartSound, self)
end
end
function ShieldpackMarine:OnInitialized()
Marine.OnInitialized(self)
if Server then
InitEquipment(self)
end
end
function ShieldpackMarine:OnDestroy()
Marine.OnDestroy(self)
if self.shieldDisplayUI then
Client.DestroyGUIView(self.shieldDisplayUI)
self.shieldDisplayUI = nil
end
self.equipmentId = Entity.invalidId
end
function ShieldpackMarine:GetHasEquipment()
return true
end
function ShieldpackMarine:GetHasCapacityUpgrade()
if GetHasTech(self, kTechId.ShieldCapacityTech, true) then
return kShieldCapacityUpgrade
else
return 0
end
end
function ShieldpackMarine:GetHasRechargeUpgrade()
if GetHasTech(self, kTechId.ShieldRechargeTech, true) then
return kShieldRechargeUpgrade
else
return 0
end
end
function ShieldpackMarine:GetHasCombatDurationUpgrade()
if GetHasTech(self, kTechId.ShieldRechargeTech, true) then
return kCombatDurationUpgrade
else
return 0
end
end
function ShieldpackMarine:GetShieldCapacity()
self.shieldMaxCapacity = kShieldCapacity + self:GetHasCapacityUpgrade()
return self.shieldMaxCapacity
end
function ShieldpackMarine:GetShieldRecharge()
return kShieldRecharge + self:GetHasRechargeUpgrade()
end
function ShieldpackMarine:GetCombatDuration()
return kCombatDuration - self:GetHasCombatDurationUpgrade()
end
function ShieldpackMarine:GetShieldpack()
if Server then
-- There is a case where this function is called after the ShieldpackMarine has been
-- destroyed but we don't have reproduction steps.
if not self:GetIsDestroyed() and self.equipmentId == Entity.invalidId then
InitEquipment(self)
end
-- Help us track down this problem.
if self:GetIsDestroyed() then
DebugPrint("Warning - ShieldpackMarine:GetShieldpack() was called after the ShieldpackMarine was destroyed")
DebugPrint(Script.CallStack())
end
end
return Shared.GetEntity(self.equipmentId)
end
function ShieldpackMarine:OnEntityChange(oldId, newId)
if oldId == self.equipmentId and newId then
self.equipmentId = newId
end
end
function ShieldpackMarine:GetWeaponName()
local currentWeapon = self:GetActiveWeaponName()
if currentWeapon then
return string.lower(currentWeapon)
else
return nil
end
end
function ShieldpackMarine:UpdateShieldCharge(damageTable)
if self.shieldCharge == 0 then
self.isShieldEmpty = true
--Print("Empty %s", self.isShieldEmpty)
else
self.isShieldEmpty = false
--Print("Empty %s", self.isShieldEmpty)
end
if not self.isShieldEmpty then
self.shieldCharge = Clamp(self.shieldCharge - damageTable.damage, 0, self:GetShieldCapacity())
self.lastHitTime = Shared.GetTime()
--
end
end
function ShieldpackMarine:ModifyDamageTaken(damageTable, attacker, doer, damageType, hitPoint)
self:UpdateShieldCharge(damageTable)
if not self.isShieldEmpty then
damageTable.damage = damageTable.damage * kShieldPackDamageReduction
StartSoundEffectAtOrigin(kNanoDamageSound, self:GetOrigin())
end
end
function ShieldpackMarine:OnUpdatePlayer(deltaTime)
if self.shieldCharge < self:GetShieldCapacity() and not (Shared.GetTime() < self.lastHitTime + self:GetCombatDuration()) then
self.shieldCharge = Clamp(self.shieldCharge + self:GetShieldRecharge() * deltaTime, 0, self:GetShieldCapacity())
end
end
local function UpdateClientNanoShieldEffects(self)
assert(Client)
if not self.isShieldEmpty and self:GetIsAlive() then
self:_CreateEffect()
else
self:_RemoveEffect()
end
end
function ShieldpackMarine:OnUpdateRender()
if Client and not Shared.GetIsRunningPrediction() then
UpdateClientNanoShieldEffects(self)
end
local parent = self:GetParent()
if parent and parent:GetIsLocalPlayer() then
local shieldDisplayUI = self.shieldDisplayUI
if not shieldDisplayUI then
shieldDisplayUI:Load("lua/GUIShieldpackFuel.lua")
self.shieldDisplayUI = shieldDisplayUI
end
end
end
function ShieldpackMarine:GetShieldCharge()
return self.shieldCharge
end
if Client then
-- Adds the material effect to the entity and all child entities (hat have a Model mixin)
local function AddEffect(entity, material, viewMaterial, entities)
local numChildren = entity:GetNumChildren()
if HasMixin(entity, "Model") then
local model = entity._renderModel
if model ~= nil then
if model:GetZone() == RenderScene.Zone_ViewModel then
model:AddMaterial(viewMaterial)
else
model:AddMaterial(material)
end
table.insert(entities, entity:GetId())
end
end
for i = 1, entity:GetNumChildren() do
local child = entity:GetChildAtIndex(i - 1)
AddEffect(child, material, viewMaterial, entities)
end
end
local function RemoveEffect(entities, material, viewMaterial)
for i =1, #entities do
local entity = Shared.GetEntity( entities[i] )
if entity ~= nil and HasMixin(entity, "Model") then
local model = entity._renderModel
if model ~= nil then
if model:GetZone() == RenderScene.Zone_ViewModel then
model:RemoveMaterial(viewMaterial)
else
model:RemoveMaterial(material)
end
end
end
end
end
function NanoShieldMixin:_CreateEffect()
if not self.nanoShieldMaterial then
local material = Client.CreateRenderMaterial()
material:SetMaterial(kNanoshieldMaterial)
local viewMaterial = Client.CreateRenderMaterial()
viewMaterial:SetMaterial(kNanoshieldViewMaterial)
self.nanoShieldEntities = {}
self.nanoShieldMaterial = material
self.nanoShieldViewMaterial = viewMaterial
AddEffect(self, material, viewMaterial, self.nanoShieldEntities)
end
end
function NanoShieldMixin:_RemoveEffect()
if self.nanoShieldMaterial then
RemoveEffect(self.nanoShieldEntities, self.nanoShieldMaterial, self.nanoShieldViewMaterial)
Client.DestroyRenderMaterial(self.nanoShieldMaterial)
Client.DestroyRenderMaterial(self.nanoShieldViewMaterial)
self.nanoShieldMaterial = nil
self.nanoShieldViewMaterial = nil
self.nanoShieldEntities = nil
end
end
end
Shared.LinkClassToMap("ShieldpackMarine", ShieldpackMarine.kMapName, networkVars, true)
|
wait(1)
script.Parent:Destroy()
|
------------------------------------------------------------------------------
--
-- This file is part of the Corona game engine.
-- For overview and more information on licensing please refer to README.md
-- Home page: https://github.com/coronalabs/corona
-- Contact: support@coronalabs.com
--
------------------------------------------------------------------------------
local json = require('json')
local lfs = require('lfs')
-- defines modifyPlist()
local CoronaPListSupport = require("CoronaPListSupport")
local captureCommandOutput = CoronaPListSupport.captureCommandOutput
-- get the numeric value of the "debugBuildProcess" preference or 0 if it's not set (note due to a Lua bug
-- the value is actually the exit code multiplied by 256)
local debugBuildProcess = os.execute("exit $(defaults read com.coronalabs.Corona_Simulator debugBuildProcess 2>/dev/null || echo 0)") / 256
-- Read a value from the user's preferences
local function getPreference( prefName )
return captureCommandOutput("defaults read com.coronalabs.Corona_Simulator "..tostring(prefName))
end
-- Double quote a string escaping backslashes and any double quotes
local function quoteString( str )
str = str:gsub('\\', '\\\\')
str = str:gsub('"', '\\"')
return "\"" .. str .. "\""
end
local function makepath( inPath, ... )
local path = inPath or ""
for p=1, select('#', ...) do
local arg = select(p, ...)
path = path .. "/"
path = path .. arg
end
path = path:gsub('/+', '/')
return path
end
local function setStatus( msg )
print( "Building: " .. msg )
end
--------------------------------------------------------------------------------
-- isAlpha
--
-- val = ASCII character
--
-- Returns true if alpha character, otherwise false
--------------------------------------------------------------------------------
local function isAlpha( val )
if val >= "A" and val <= "Z" then
return true
end
if val >= "a" and val <= "z" then
return true
end
return false -- not Alpha
end
--------------------------------------------------------------------------------
-- isNumber
--
-- val = ASCII character
--
-- Returns true if number, otherwise false
--------------------------------------------------------------------------------
local function isNumber( val )
if val >= "0" and val <= "9" then
return true
end
return false -- not number
end
--------------------------------------------------------------------------------
-- isNumber
--
-- val = ASCII character
-- allowDots = true if dots are allowed
--
-- Returns true if number, otherwise false
--------------------------------------------------------------------------------
local function isDotDash( val, allowDots )
local char2 = "-" -- default is to not test for dot
if allowDots then
char2 = "." -- test for dot
end
if val == "-" or val == char2 then
return true
end
return false -- not dot or dash
end
--------------------------------------------------------------------------------
-- sanitize Bundle ID String
--
-- bundleStr = Bundle string
-- allowDots = true to allow dots in name, otherwise dots converted to dash
--
-- Returns validated Bundle ID string
--
-- This code is used to convert non-alphanumeric (except dash and maybe dot)
-- into dashes for a valid bundle ID.
-- "com.example.Tom's App_Name" returns as "com.example.Tom-s-App-Name"
-- Refer RFC1034 for string specification which is needed to match Xcode (and Apple)
--------------------------------------------------------------------------------
local function sanitizeBundleString( bundleStr, allowDots )
local newBundleStr = "" -- new string
local val
for i = 1, string.len( bundleStr ) do
val = string.sub( bundleStr, i, i )
if isAlpha( val ) then
newBundleStr = newBundleStr .. val
elseif isNumber( val ) then
newBundleStr = newBundleStr .. val
elseif isDotDash( val, allowDots ) then
newBundleStr = newBundleStr .. val
else
newBundleStr = newBundleStr .. "-"
end
end -- do
return newBundleStr
end
--------------------------------------------------------------------------------
local function getCopyResourcesScript( src, dst, options )
-- Generate a script to copy the project's assets to the built app
-- rsync is used to speed up building apps with very large numbers of assets
--
-- rsync flags:
-- --delete-excluded also delete excluded files from dest dirs
-- --exclude=PATTERN exclude files matching PATTERN
-- --delete delete extraneous files from dest dirs
-- --force force deletion of dirs even if not empty
-- --prune-empty-dirs prune empty directory chains from file-list
-- --human-readable output numbers in a human-readable format
-- --itemize-changes output a change-summary for all updates
-- --recursive recurse into directories
-- --links copy symlinks as symlinks
-- --copy-unsafe-links copy external symlinked files to destination
-- --hard-links preserve hard links
-- --times preserve times
-- --perms preserve permissions (needed by next option)
-- --chmod specify base level permissions (prevents us generating bad apps)
--
local script = [==[
# rsync goes haywire if either the source or destination are empty
if [ -z "$SRC_DIR" -o -z "$DST_DIR" ]
then
echo "OSXPackageApp: invalid SRC_DIR or DST_DIR for rsync"
exit 1
fi
rsync -rv --times --delete-excluded {{EXCLUDED_FILES}} --exclude="**/*.lua" --exclude="build.settings" --exclude="**/.*" --delete --prune-empty-dirs --links --copy-unsafe-links --hard-links --perms --chmod="Da+rx,Fa+r" --human-readable --itemize-changes "$SRC_DIR/" "$DST_DIR"
]==]
local excludedFilesSh = ""
if options and options.settings then
-- Generate shell code from the excludeFiles entry in build.settings
if options.settings.excludeFiles then
-- we have actual files to exclude
print("Excluding specified files from build: ")
for platform,excludes in pairs(options.settings.excludeFiles) do
if platform == "all" or platform == "osx" or platform == "macos" then
for index,pattern in ipairs(excludes) do
print(" excluding: "..pattern)
pattern = pattern:gsub("'", "'\\''") -- quote single quotes
excludedFilesSh = excludedFilesSh .. " --exclude='" .. pattern .."'"
end
end
end
end
end
local args = "SRC_DIR="..src.."\nDST_DIR="..dst.."/Contents/Resources/Corona\n"
-- Replace the placeholders in the script with the generated code (or an empty string if there was none)
script = args .. script:gsub("{{EXCLUDED_FILES}}", excludedFilesSh)
if debugBuildProcess > 0 then
print("script: ".. script)
end
return script
end
--------------------------------------------------------------------------------
local function getCodesignScript( entitlements, path, appIdentity, codesign )
local quotedpath = quoteString( path )
-- Remove any extended macOS attributes from files in the bundle because
-- codesign doesn't like them
local removeXattrs = "/usr/bin/xattr -cr "..quoteString(path) .." && "
local entitlementsParam = ""
if entitlements ~= nil and entitlements ~= "" then
entitlementsParam = " --entitlements ".. entitlements .." "
end
local verboseParam = ""
if debugBuildProcess and debugBuildProcess ~= 0 then
verboseParam = "-".. string.rep("v", debugBuildProcess) .." "
end
local cmd = removeXattrs .. codesign.." --options runtime --deep -f -s "..quoteString(appIdentity).." "..entitlementsParam..verboseParam..quotedpath
return cmd
end
local function getProductBuildScript( path, installerIdentity, productbuild )
local infoPlist = makepath(path, "Contents/Info.plist")
local packagePath = path:gsub('.app$', '') .. ".pkg"
-- productbuild --component "$APP" /Applications --sign "3rd Party Mac Developer Installer: Corona Labs Inc" --product "$APP/Contents/Info.plist" "$APP_BASENAME".pkg
local cmd = productbuild.." --component ".. quoteString(path) .." /Applications --sign "..quoteString(installerIdentity).." --product "..quoteString(infoPlist) .." "..quoteString(packagePath)
return cmd
end
local function getProductValidateScript( path, itunesConnectUsername, itunesConnectPassword, applicationLoader )
local packagePath = path:gsub('.app$', '') .. ".pkg"
-- Apple tells us to use this buried utility to automate Application Loader tasks in
-- https://itunesconnect.apple.com/docs/UsingApplicationLoader.pdf
local altool = makepath(applicationLoader, "Contents/Frameworks/ITunesSoftwareService.framework/Support/altool")
-- If the "cmd" generated below fails because it's the wrong path that's very hard to detect amongst all the XML parsing so we do it here
if lfs.attributes( altool ) == nil then
print("ERROR: cannot find 'altool' utility in "..altool)
return "echo Failed to find build utilities in expected places (cannot find 'altool' utility in '"..altool.."')"
end
-- Removing the "!DOCTYPE" line from the XML stops xpath trying to access the DTD
-- The xpath command parses the XML output looking for an error message
-- The final sed command adds a newline to the last line of output which xpath omits
local cmd = quoteString(altool) .. " --validate-app -f ".. quoteString(packagePath) .." -u '".. itunesConnectUsername .."' -p '".. itunesConnectPassword .."' --output-format xml | grep -v '^<!DOCTYPE' | /usr/bin/xpath '/plist/dict/key[.=\"product-errors\"]/following-sibling::*[1]//key[.=\"message\"]/following-sibling::*[1]/node()' 2>/dev/null | sed -ne 'p'"
return cmd
end
local function getProductUploadScript( path, itunesConnectUsername, itunesConnectPassword, applicationLoader )
local packagePath = path:gsub('.app$', '') .. ".pkg"
-- Apple tells us to use this buried utility to automate Application Loader tasks in
-- https://itunesconnect.apple.com/docs/UsingApplicationLoader.pdf
local altool = makepath(applicationLoader, "Contents/Frameworks/ITunesSoftwareService.framework/Support/altool")
-- Removing the "!DOCTYPE" line from the XML stops xpath trying to access the DTD
-- The xpath command parses the XML output looking for an error message
-- The final sed command adds a newline to the last line of output which xpath omits
local cmd = quoteString(altool) .. " --upload-app -f ".. quoteString(packagePath) .." -u '".. itunesConnectUsername .."' -p '".. itunesConnectPassword .."' --output-format xml | grep -v '^<!DOCTYPE' | /usr/bin/xpath '/plist/dict/key[.=\"product-errors\"]/following-sibling::*[1]//key[.=\"message\"]/following-sibling::*[1]/node()' 2>/dev/null | sed -ne 'p'"
return cmd
end
local function getCreateDMGScript( path )
local dmgPath = path:gsub('(.*)%.%w+$', '%1') .. ".dmg"
local dmgName = path:gsub('.*/(.+)', '%1'):gsub('%.app$', '')
local verboseParam = ""
if debugBuildProcess and debugBuildProcess ~= 0 then
verboseParam = "-verbose"
end
local cmd = "/usr/bin/hdiutil create -srcfolder '"..path.."' -volname '"..dmgName.."' -fs HFS+ -format UDZO -imagekey zlib-level=9 '"..dmgPath.."'"
return cmd
end
local function getShowFileInFinderScript( path )
local cmd = [[osascript -e 'set thePath to "__PATH__"
tell application "Finder"
reveal POSIX file thePath as text
activate
end tell']]
cmd = cmd:gsub("__PATH__", path)
return cmd
end
--------------------------------------------------------------------------------
function runScript( script, debugLevel )
local debugLevel = debugLevel or 0
local errMsg = nil
if debugBuildProcess and debugBuildProcess > debugLevel then
print("Running: ".. tostring(script))
end
-- Run the command capturing any output
local tmpFile = os.tmpname()
local exitCode = os.execute( '( ' .. script .. ' ) 2>' .. tmpFile )
if exitCode ~= 0 then
print("ERROR: build command failed: ".. script)
-- divide exitcode by 256 to work around Lua bug
print("ERROR: with exit code ".. (exitCode / 256) .." and output: ")
errMsg = captureCommandOutput( "/bin/cat " .. tmpFile )
print( errMsg )
end
os.remove( tmpFile )
return exitCode, errMsg
end
--------------------------------------------------------------------------------
local templateXcent = [[
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
{{CUSTOM_ENTITLEMENTS}}
</dict>
</plist>
]]
local function generateOSXEntitlements(filename, settings, provisionFile)
local outFile = io.open( filename, "wb" )
if outFile == nil then
return "failed to open xcent file for writing: "..tostring(filename)
end
local data = templateXcent
local entitlementsStr = ""
local generatedEntitlements, includeProvisioning = CoronaPListSupport.generateEntitlements(settings, 'osx', provisionFile)
data, numMatches = string.gsub( data, "{{CUSTOM_ENTITLEMENTS}}", generatedEntitlements )
assert( numMatches == 1 )
outFile:write(data)
outFile:close()
if debugBuildProcess and debugBuildProcess ~= 0 then
print( "Created entitlements file: " .. filename );
runScript("/bin/cat "..filename)
end
return "", includeProvisioning
end
--
-- generateFiles
--
-- Create the Info.plist file
--
-- returns an error message or nil on success
--
local function generateFiles( options )
local result = nil
result = CoronaPListSupport.modifyPlist( options )
if result then
return result
end
return result
end
-- helper function to figure out if building for App Store distribution
-- returns true or false
local function isBuildForAppStoreDistribution( options )
if not options.signingIdentity then
return false
end
-- FIXME: Should handle App Store vs. Ad-hoc
local retval = string.match( options.signingIdentityName, "3rd Party Mac Developer" ) or string.match( options.signingIdentityName, "Apple Distribution" )
if retval then
return true
else
return false
end
end
--
-- packageApp
--
-- Copy the assets from the project directory to the app bundle
--
-- returns an error message or nil on success
--
local function packageApp( options )
local baseName = options.dstFile;
-- Introducing an unquoted string because we should be quoting as the final set after appending strings, not before.
-- See casenum: 1008
local appBundleFileUnquoted = options.dstDir .. "/" .. baseName .. ".app"
-- Quoting should happen around the final string, otherwise you get quotes in multiple places which might not be what you expect.
local appBundleFile = quoteString( appBundleFileUnquoted )
local binDir = options.binDir
setStatus("Copying changed app resources")
local result, errMsg = runScript( getCopyResourcesScript( quoteString( options.srcAssets ), appBundleFile, options ), 2 )
if result ~= 0 then
return "ERROR: copying resources failed: "..tostring(errMsg)
end
runScript( "/bin/chmod 755 " .. appBundleFile )
return nil
end
--------------------------------------------------------------------------------
local function getNames( name, result )
local err
result.bundledisplayname = name
result.bundlename = name
result.bundleexecutable = name
result.dstFile = name
return err
end
-- determines appid and bundleid from provision file
-- if wildcard is present, then requires bundlename to be supplied as input
local function getIDs( mobileProvision, result )
local err
if debugBuildProcess and debugBuildProcess ~= 0 then
print("getIDs: mobileProvision '"..tostring(mobileProvision).."'")
end
if not mobileProvision then
result.mobileProvision = nil
result.appid = sanitizeBundleString( result.bundlename, false )
result.bundleid = result.appid -- string.match( result.appid, "[^%.]+%.(.*)" )
result.pushEnvironment = nil
return nil
end
result.mobileProvision = mobileProvision
-- Extract app id from provision file
local data = nil
local inFile, errorMsg = io.open( mobileProvision, "rb" )
if inFile then
data = inFile:read( "*all" )
inFile:close()
else
return "Error: Cannot open '"..mobileProvision.."' for reading ("..tostring(errorMsg)..")"
end
if not data or string.len(data) == 0 then
return "Error: '"..mobileProvision.."' is not a valid provision file"
end
local patternPrefix =
"<key>com.apple.application%-identifier</key>%s*<string>([%w%.%-]*)"
local patternWithWildcard = patternPrefix .. "%.%*</string>"
local patternWithoutWildcard = patternPrefix .. "</string>"
local appid = string.match( data, patternWithWildcard )
local usesWildcard = true
if ( not appid ) then
usesWildcard = false
appid = string.match( data, patternWithoutWildcard )
end
if ( not appid ) then
local pattern = patternPrefix .. "</string>"
local appid= string.match( data, pattern )
if ( not appid ) then
--assert( appid )
err = "Error: Could not obtain application identifier from '"..mobileProvision.."'"
end
end
if ( appid ) then
local value = appid
assert( result )
-- only append if wildcard was used
if usesWildcard then
-- Convert the bundlename into alphanumeric and dash characters only
value = value .. "." .. sanitizeBundleString( result.bundlename, false )
end
result.appid = value
result.bundleid = string.match( value, "[^%.]+%.(.*)" )
end
-- Determine push notification aps-environment (default to nil)
local pattern =
"<key>aps%-environment</key>%s*<string>([%w]*)</string>"
local pushEnvironment = string.match( data, pattern )
result.pushEnvironment = pushEnvironment
return err
end
local function fileExists( filename )
local f = io.open( filename, "r" )
if ( f ) then
io.close( f )
end
return ( nil ~= f )
end
function getBundleId( mobileProvision, bundledisplayname )
local options = {}
local err = getNames( bundledisplayname, options )
if debugBuildProcess and debugBuildProcess ~= 0 then
print("getBundleId: bundledisplayname '"..tostring(bundledisplayname).."'; options: "..json.prettify(options))
end
if ( not err ) then
err = getIDs( mobileProvision, options )
if ( not err ) then
return options.bundleid
end
end
return nil
end
-- Corona table extension that we want to use here
table.indexOf = function( t, object )
local result
if "table" == type( t ) then
for i=1,#t do
if object == t[i] then
result = i
break
end
end
end
return result
end
function signAllPlugins(pluginsDir, signingIdentity, codesign)
local entitlements = ""
if lfs.attributes( pluginsDir ) == nil then
return "" -- no plugins dir
end
for file in lfs.dir(pluginsDir) do
-- Only sign files in the Plugins directory (directories will contain assets that don't need to be signed)
local pluginFile = makepath(pluginsDir, file)
if lfs.attributes( pluginFile ).mode ~= "directory" then
local result, errMsg = runScript( getCodesignScript( entitlements, pluginFile, signingIdentity, codesign ) )
if result ~= 0 then
errMsg = "ERROR: plugin code signing for '"..pluginFile.."' failed: "..tostring(errMsg)
return errMsg
end
end
end
return ""
end
--
-- OSXPostPackage
--
-- Process the app bundle return by the build server (including code signing, Info.plist processing, etc)
--
-- returns an error message or nil on success
--
function OSXPostPackage( params )
local srcAssets = params.srcAssets
local compiledLuaArchive = params.compiledLuaArchive
local tmpDir = params.tmpDir
local dstDir = params.dstDir
local bundledisplayname = params.bundledisplayname
local bundleversion = params.bundleversion
local provisionFile = params.provisionFile
local signingIdentity = params.signingIdentity
local targetDevice = params.targetDevice
local targetPlatform = params.targetPlatform
local verbose = ( debugBuildProcess and debugBuildProcess > 1 )
local osPlatform = params.osPlatform
local sdkRoot = params.xcodetoolhelper.sdkRoot
local err = nil
setStatus("Building for macOS")
-- init options
local options = {
dstDir=dstDir,
srcAssets=srcAssets,
compiledLuaArchive=compiledLuaArchive,
bundleversion=bundleversion,
signingIdentity=signingIdentity,
tmpDir=tmpDir,
sdkRoot=sdkRoot,
targetDevice=targetDevice,
targetPlatform=targetPlatform,
verbose=verbose,
osPlatform=osPlatform,
sdkType=params.sdkType,
sdkRoot=sdkRoot,
osxAppTemplate=params.osxAppTemplate,
tmpPluginsDir=params.tmpPluginsDir,
corona_build_id=params.corona_build_id,
xcodetoolhelper = params.xcodetoolhelper,
}
local customSettingsFile = srcAssets .. "/build.settings"
if ( fileExists( customSettingsFile ) ) then
local customSettings, msg = loadfile( customSettingsFile )
if ( customSettings ) then
local status, msg = pcall( customSettings )
if status then
print( "Using additional build settings from: " .. customSettingsFile )
-- forwards compatibility
if settings.macos ~= nil then
if settings.osx ~= nil then
print( "WARNING: settings.macos overrides settings.osx in "..customSettingsFile )
end
settings.osx = settings.macos
end
options.settings = settings
else
err = "Warning: Error found in build.settings file:\n\t".. msg
print(err)
end
else
err = "Warning: Could not load build.settings file:\n\t".. msg
print(err)
end
end
if ( not err ) then
local err = getNames( bundledisplayname, options )
if ( not err ) then
-- Special case for no provision profile (e.g. Xcode simulator)
if not provisionFile then
options.bundleid = "com.example." .. sanitizeBundleString(bundledisplayname)
else
err = getIDs( provisionFile, options )
end
end
end
if ( not err ) then
-- Make sure the build directory exists
runScript( "/bin/mkdir -p "..quoteString( dstDir ) )
local appBundleFileUnquoted = options.dstDir .. "/" .. options.dstFile .. ".app"
appBundleFileUnquoted = appBundleFileUnquoted:gsub('//', '/')
options.appBundleFile = quoteString( appBundleFileUnquoted )
-- If the output bundle directory exists but is not writeable, error
-- (a common cause of this is testing a .pkg install which will replace the original app
-- with an installed copy owned by root)
if lfs.attributes( appBundleFileUnquoted ) ~= nil and not lfs.touch( appBundleFileUnquoted ) then
return "ERROR: app bundle '".. appBundleFileUnquoted .."' is not writeable (you may need to remove it before building)"
end
-- If an iOS app with the same name as this macOS app exists in the build directory, tell
-- the user and refuse to overwrite it (this also works around an apparent bug in macOS which
-- causes a macOS app that replaces an iOS app to not be runnable)
if lfs.attributes( appBundleFileUnquoted.."/"..options.dstFile ) ~= nil then
return "ERROR: an iOS application with the same name exists in the output folder and will not be overwritten"
end
setStatus("Unpacking template")
-- extract template into dstDir
local result, errMsg = runScript( "/usr/bin/ditto -x -k "..quoteString( options.osxAppTemplate ).." "..options.appBundleFile )
runScript("find " .. options.appBundleFile .. " -name _CodeSignature -exec rm -vr {} +")
if result ~= 0 then
return "ERROR: unzipping template failed: "..tostring(errMsg)
end
-- cleanup signature from the template
runScript( "cd ".. options.appBundleFile .. " ; /usr/bin/codesign --remove-signature --deep . " )
-- If "bundleResourcesDirectory" is set, copy the contents of that directory to the
-- application's Resource directory
if options and options.settings and options.settings.osx and options.settings.osx.bundleResourcesDirectory then
local customBundleResources = makepath(srcAssets, options.settings.osx.bundleResourcesDirectory)
if ( fileExists( customBundleResources ) ) then
local resourceDir = makepath(options.appBundleFile, "/Contents/Resources/")
setStatus("Copying 'bundleResourcesDirectory' resources")
runScript("/bin/cp -av "..quoteString(customBundleResources).."/ "..resourceDir)
else
print("WARNING: 'bundleResourcesDirectory' does not exist: "..customBundleResources)
end
end
-- rename the internal binary
runScript( "/bin/mv -v "..options.appBundleFile.."/Contents/MacOS/CoronaShell "..options.appBundleFile.."/Contents/MacOS/"..quoteString(options.dstFile) )
runScript( "/bin/mkdir -p "..options.appBundleFile.."/Contents/Resources/Corona/" )
-- We get the signingIdentity as a cert fingerprint but we also need the plaintext name
if options.signingIdentity then
options.signingIdentityName = captureCommandOutput("security find-identity -p codesigning -v | grep '".. options.signingIdentity .."' | sed -e 's/.*\\(\".*\"\\).*/\\1/'")
if not options.signingIdentityName or options.signingIdentityName == "" then
print("WARNING: identity '"..options.signingIdentity.."' does not appear to be valid for codesigning. You should open Keychain Access and verify that your signing identities are valid")
else
print("Code signing identity: ".. options.signingIdentityName .." (".. options.signingIdentity ..")")
end
end
if options and debugBuildProcess and debugBuildProcess ~= 0 then
print("====================================")
print("OSXPostPackage: options: "..json.prettify(options))
print("====================================")
end
-- finalize package
setStatus("Creating Info.plist")
result = generateFiles( options )
if result then
return result
end
setStatus("Copying application assets")
result = packageApp( options )
if result then
return result
end
-- If we have a plugins dir ...
if lfs.attributes( options.tmpPluginsDir ) ~= nil then
setStatus("Processing plugins")
local appPluginsDirUnquoted = makepath(appBundleFileUnquoted, "Contents/Plugins")
local appPluginsDir = quoteString(appPluginsDirUnquoted)
-- Remove Lua files from tmpPluginsDir
runScript( "/usr/bin/find "..quoteString(options.tmpPluginsDir).." \\( -name '*.lua' -o -name '*.lu' \\) -delete" )
-- Make sure the plugins directory exists
runScript( "/bin/mkdir -p "..appPluginsDir )
-- Copy all files from tmpPluginsDir to the app's Plugins directory (that way we get Lua plugin assets)
runScript( 'cp -Rv ' .. quoteString(options.tmpPluginsDir) .."/* ".. appPluginsDir )
-- Prune all empty directories
runScript( 'find ' .. appPluginsDir .. ' -type d -empty -delete' )
-- sign all the plugins
if options.signingIdentity then
local result = signAllPlugins(appPluginsDirUnquoted, options.signingIdentity, options.xcodetoolhelper.codesign)
if result ~= "" then
return tostring(result)
end
end
end
-- Copy the resource.car to the app's Corona resource directory
runScript( "/bin/cp -v "..quoteString(options.compiledLuaArchive).." "..options.appBundleFile.."/Contents/Resources/Corona/resource.car" )
-- If we have a macOS icon with a new or old name ...
local iconPath = makepath(options.srcAssets, "Icon-macos.icns")
if lfs.attributes( iconPath ) == nil then
iconPath = makepath(options.srcAssets, "Icon-osx.icns")
end
if lfs.attributes( iconPath ) ~= nil then
-- Copy the macOS (if any) to the app's resource directory
-- calling it Icon-osx.icns for backwards compatibility
runScript( "/bin/cp -v "..quoteString(iconPath).." "..options.appBundleFile.."/Contents/Resources/Icon-osx.icns" )
else
print("WARNING: no Icon-macos.icns / Icon-osx.icns file found, using default icon")
end
setStatus("Cleaning up")
-- Mark app as updated
runScript( "/usr/bin/touch "..options.appBundleFile )
-- bundle is now ready to be signed
if options.signingIdentity then
local entitlements_filename = os.tmpname() .. "_entitlements.xcent"
local entitlements = entitlements_filename
local result, includeProvisioning = generateOSXEntitlements( entitlements_filename, settings, provisionFile )
if result ~= "" then
entitlements = ""
end
-- Copy provisioning profile if we need it
if includeProvisioning then
runScript( "/bin/cp " .. quoteString(provisionFile) .. " " .. quoteString(makepath(appBundleFileUnquoted, "Contents/embedded.provisionprofile")) )
end
setStatus("Signing application with "..tostring(options.signingIdentityName))
local result, errMsg = runScript( getCodesignScript( entitlements, appBundleFileUnquoted, options.signingIdentity, options.xcodetoolhelper.codesign ) )
runScript( "/bin/rm -f " .. entitlements_filename )
if result ~= 0 then
errMsg = "ERROR: code signing failed: "..tostring(errMsg)
runScript( "/bin/ls -Rl '"..appBundleFileUnquoted.."'")
return errMsg
end
end
-- Sometimes macOS gets confused about whether the apps we build are opennable, this
-- tells macOS to flush its cache of such things
runScript( "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -u "..options.appBundleFile)
end
return err
end
--
-- OSXPackageForAppStore
--
-- Create an App Store package and optionally send it to iTunes Connect
--
-- returns an error message or nil on success
--
function OSXPackageForAppStore( params )
local srcAssets = params.srcAssets
local appSigningIdentity = params.appSigningIdentity
local installerSigningIdentity = params.installerSigningIdentity
local dstDir = params.dstDir
local dstFile = params.bundledisplayname
local sendToAppStore = params.sendToAppStore
local osxAppEntitlementsFile = params.osxAppEntitlements
local itunesConnectUsername = params.itc1
local itunesConnectPassword = params.itc2
local sdkRoot = params.xcodetoolhelper.sdkRoot
local codesign = params.xcodetoolhelper.codesign
local applicationLoader = params.xcodetoolhelper.applicationLoader
local productbuild = params.xcodetoolhelper.productbuild
local err = nil
local appSigningIdentityName
local installerSigningIdentityName
local provisionFile = params.provisionFile
print("Using Xcode utilities from "..sdkRoot)
local customSettingsFile = srcAssets .. "/build.settings"
if ( fileExists( customSettingsFile ) ) then
local customSettings, msg = loadfile( customSettingsFile )
if ( customSettings ) then
-- this creates a global called "settings"
local status, msg = pcall( customSettings )
if status then
print( "Using additional build settings from: " .. customSettingsFile )
else
err = "Warning: Error found in build.settings file:\n\t".. msg
print(err)
end
-- forwards compatibility
if settings.macos ~= nil then
if settings.osx ~= nil then
print( "WARNING: settings.macos overrides settings.osx in "..customSettingsFile )
end
settings.osx = settings.macos
end
else
err = "Warning: Could not load build.settings file:\n\t".. msg
print(err)
end
end
local appBundleFile = makepath(dstDir, dstFile) .. ".app"
if not appSigningIdentity or not installerSigningIdentity then
return "ERROR: building an App Store package requires valid app and installer signing identities (if you've made changes to these recently you may need to restart the Corona Simulator to pick them up)"
end
-- We get the {app|installer}SigningIdentity as a cert fingerprint but we also need the plaintext name
if appSigningIdentity then
appSigningIdentityName = captureCommandOutput("security find-identity -p codesigning -v | grep '".. appSigningIdentity .."' | sed -e 's/.*\\(\".*\"\\).*/\\1/'")
if not appSigningIdentityName or appSigningIdentityName == "" then
print("WARNING: application identity '"..appSigningIdentity.."' does not appear to be valid for codesigning. You should open Keychain Access and verify that your signing identities are valid")
else
print("Application signing identity: ".. appSigningIdentityName .." (".. appSigningIdentity ..")")
end
end
if installerSigningIdentity then
installerSigningIdentityName = captureCommandOutput("security find-identity -p basic -v | grep '".. installerSigningIdentity .."' | sed -e 's/.*\\(\".*\"\\).*/\\1/'")
if not installerSigningIdentityName or installerSigningIdentityName == "" then
print("WARNING: installer identity '"..installerSigningIdentity.."' does not appear to be valid for codesigning. You should open Keychain Access and verify that your signing identities are valid")
else
print("Installer signing identity: ".. installerSigningIdentityName .." (".. installerSigningIdentity ..")")
end
end
--
-- Sign application with production identity
--
local entitlements_filename = os.tmpname() .. "_entitlements.xcent"
local result, includeProvisioning = generateOSXEntitlements( entitlements_filename, settings, provisionFile )
if result ~= "" then
return "ERROR: generating entitlements file failed: "..tostring(result)
end
-- Copy provisioning profile if we need it
if includeProvisioning then
runScript( "/bin/cp " .. quoteString(provisionFile) .. " " .. quoteString(makepath(appBundleFile, "Contents/embedded.provisionprofile")) )
end
-- sign all the plugins
local appPluginsDirUnquoted = makepath(appBundleFile, "Contents/Plugins")
local result = signAllPlugins(appPluginsDirUnquoted, appSigningIdentity, codesign)
if result ~= "" then
return tostring(result)
end
setStatus("Signing application with "..tostring(appSigningIdentityName))
local result, errMsg = runScript( getCodesignScript( entitlements_filename, appBundleFile, appSigningIdentity, codesign ) )
runScript( "/bin/rm -f " .. entitlements_filename )
if result ~= 0 then
errMsg = "ERROR: code signing failed: "..tostring(errMsg)
runScript( "/bin/ls -Rl '"..appBundleFile.."'")
return errMsg
end
--
-- Create package
--
setStatus("Packaging application with "..tostring(appSigningIdentityName))
local productFile = appBundleFile:gsub('.app$', '') .. ".pkg"
local result, errMsg = runScript( getProductBuildScript( appBundleFile, installerSigningIdentity, productbuild ) )
if result ~= 0 then
errMsg = "ERROR: creating installation package failed: "..tostring(errMsg)
return errMsg
end
if itunesConnectUsername and itunesConnectUsername ~= "" then
--
-- Validate package with iTunes Connect
--
setStatus("Validating application package with iTunes Connect")
local result = captureCommandOutput( getProductValidateScript( appBundleFile, itunesConnectUsername, itunesConnectPassword, applicationLoader ), 2 )
if result ~= "" then
if result:match('Unable to validate archive') then
-- Validation requires an internet connection but the error message is somewhat inscrutable
result = result .. "\n\n(make sure you are connected to the internet)"
end
errMsg = "ERROR: validation failed: "..tostring(result)
return errMsg
end
end
if sendToAppStore then
--
-- Upload package to iTunes Connect
--
setStatus("Uploading application package to iTunes Connect")
local result = captureCommandOutput( getProductUploadScript( appBundleFile, itunesConnectUsername, itunesConnectPassword, applicationLoader ), 2 )
if result ~= "" then
errMsg = "ERROR: upload failed: "..tostring(result)
return errMsg
end
else
-- Not sending to App Store so just show what we built in the Finder
runScript( getShowFileInFinderScript( productFile ) )
end
return nil
end
--
-- OSXPackageForSelfDistribution
--
-- Sign app for self distribution and optionally create an installer and DMG
--
-- returns an error message or nil on success
--
function OSXPackageForSelfDistribution( params )
local appBundle = params.appBundle
local appSigningIdentity = params.appSigningIdentity
local installerSigningIdentity = params.installerSigningIdentity
local tmpDir = params.tmpDir
local dstDir = params.dstDir
local dstFile = params.bundledisplayname
local createInstaller = params.createInstaller
local createDMG = params.createDMG
local sdkRoot = params.xcodetoolhelper.sdkRoot
local codesign = params.xcodetoolhelper.codesign
local err = nil
local appBundleFile = makepath(dstDir, dstFile) .. ".app"
local productFile = appBundleFile
local appSigningIdentityName = ""
-- We get the appSigningIdentity as a cert fingerprint but we also need the plaintext name (unless it's "None")
if appSigningIdentity and appSigningIdentity ~= "None" then
appSigningIdentityName = captureCommandOutput("security find-identity -p codesigning -v | grep '".. appSigningIdentity .."' | sed -e 's/.*\\(\".*\"\\).*/\\1/'")
if not appSigningIdentityName or appSigningIdentityName == "" then
print("WARNING: application identity '"..appSigningIdentity.."' does not appear to be valid for codesigning. You should open Keychain Access and verify that your signing identities are valid")
else
print("Application signing identity: ".. appSigningIdentityName .." (".. appSigningIdentity ..")")
end
--
-- Sign application with production identity
--
-- sign all the plugins
local appPluginsDirUnquoted = makepath(appBundleFile, "Contents/Plugins")
local result = signAllPlugins(appPluginsDirUnquoted, appSigningIdentity, codesign)
if result ~= "" then
return tostring(result)
end
local entitlements = "" -- quoteString( osxAppEntitlementsFile )
setStatus("Signing application with "..tostring(appSigningIdentityName))
local result, errMsg = runScript( getCodesignScript( entitlements, appBundleFile, appSigningIdentity, codesign ) )
if result ~= 0 then
errMsg = "ERROR: code signing failed: "..tostring(errMsg)
runScript( "/bin/ls -Rl '"..appBundleFile.."'") -- to aid debugging
return errMsg
end
end
if createDMG then
--
-- Create DMG
--
setStatus("Creating DMG for application")
productFile = appBundleFile:gsub('.app$', '.dmg')
if lfs.attributes( productFile ) ~= nil then
-- Remove existing DMG file as hdiutil wont overwrite it
local result, errMsg = os.remove(productFile)
if not result then
errMsg = "ERROR: removing old DMG failed: "..tostring(errMsg)
return errMsg
end
end
local result, errMsg = runScript( getCreateDMGScript( appBundleFile ) )
if result ~= 0 then
errMsg = "ERROR: creating DMG failed: "..tostring(errMsg)
return errMsg
end
end
-- Show what we built in the Finder
runScript( getShowFileInFinderScript( productFile ) )
return nil
end
|
-- Premier écran, pas grand chose à voir ici :D
Start = class.set(Start)
function Start:init()
self.delay = 60*2
end
function Start:load()
self.delay = 60*2 -- en steps
end
function Start:update()
if self.delay == 0 then
game.state = MAIN_MENU_LOAD
else
self.delay = self.delay - 1
end
--fx.Update()
end
function Start:draw()
-- fx.Draw()
love.graphics.setColor(1, 0, 0, 1)
love.graphics.setFont(font96)
love.graphics.printf("MISSILES", 0, config.gameHeight/2-90, config.gameWidth,"center", 0, 1, 1)
love.graphics.printf("ENCOUNTERS", 0, config.gameHeight/2, config.gameWidth,"center", 0, 1, 1)
love.graphics.setFont(font32)
love.graphics.setColor(0.4, 1, 0.4, 1)
love.graphics.printf("Version "..GAME_VERSION, 0, config.gameHeight/2+100, config.gameWidth,"center", 0, 1, 1)
end
return class.new(Start)
|
data:extend(
{
{
type = "recipe",
name = "long-handed-inserter",
enabled = false,
ingredients =
{
{"iron-gear-wheel", 1},
{"iron-plate", 1},
{"inserter", 1}
},
result = "long-handed-inserter"
},
{
type = "recipe",
name = "fast-inserter",
enabled = false,
ingredients =
{
{"electronic-circuit", 2},
{"iron-plate", 2},
{"inserter", 1}
},
result = "fast-inserter"
},
{
type = "recipe",
name = "filter-inserter",
enabled = false,
ingredients =
{
{"fast-inserter", 1},
{"electronic-circuit", 4}
},
result = "filter-inserter"
},
{
type = "recipe",
name = "stack-inserter",
enabled = false,
ingredients =
{
{"iron-gear-wheel", 15},
{"electronic-circuit", 15},
{"advanced-circuit", 1},
{"fast-inserter", 1}
},
result = "stack-inserter"
},
{
type = "recipe",
name = "stack-filter-inserter",
enabled = false,
ingredients =
{
{"stack-inserter", 1},
{"electronic-circuit", 5}
},
result = "stack-filter-inserter"
}
}
)
|
--
-- main.lua
-- AdColony Sample App
--
-- Copyright (c) 2016 Corona Labs Inc. All rights reserved.
--
local adcolony = require("plugin.adcolony")
local widget = require("widget")
local json = require("json")
--------------------------------------------------------------------------
-- set up UI
--------------------------------------------------------------------------
local interstitialButton
local rewardedButton
display.setStatusBar( display.HiddenStatusBar )
display.setDefault("background", 1)
local adcolonyLogo = display.newImage("logo-adcolony-600x.png")
adcolonyLogo.anchorY = 0
adcolonyLogo.x, adcolonyLogo.y = display.contentCenterX, 0
adcolonyLogo:scale(0.3, 0.3)
local subTitle = display.newText {
text = "plugin for Corona SDK",
x = display.contentCenterX,
y = 50,
font = display.systemFont,
fontSize = 14
}
subTitle:setFillColor(0.3)
local eventDataTextBox = native.newTextBox( display.contentCenterX, display.contentHeight - 100, 310, 200)
eventDataTextBox.placeholder = "Event data will appear here"
processEventTable = function(event)
local logString = json.prettify(event):gsub("\\","")
logString = "\nPHASE: "..event.phase.." - - - - - - - - - - - -\n" .. logString
print(logString)
eventDataTextBox.text = logString .. eventDataTextBox.text
end
--------------------------------------------------------------------------
-- plugin implementation
--------------------------------------------------------------------------
local appId = "n/a"
local adZones = {}
local platformName = system.getInfo("platformName")
if platformName == "Android" then
if system.getInfo("targetAppStore") == "amazon" then
appId = "app022c863a0bd044b580"
adZones = {interstitial="vzd3edac151669436fb0", rewardedVideo="vz026b1d196f6c4e9898"}
else -- Google Play
appId = "app93d88471b8064af082"
adZones = {interstitial="vzd0d91d3fe357403b97", rewardedVideo="vz7d8e59fc7c074471b0"}
end
elseif platformName == "iPhone OS" then
appId = "app4a776411414e465d87"
adZones = {interstitial="vz287414efb3f04229ac", rewardedVideo="vz59e1fa6deb5b486db4"}
else
print "Unsupported platform"
end
print("App ID: "..appId)
print("Ad zones: "..json.prettify(adZones))
local adcolonyListener = function(event)
processEventTable(event)
local data = (event.data ~= nil) and json.decode(event.data) or {}
if event.phase == "init" then
if (adcolony.isLoaded("interstitial")) then
interstitialButton:setLabel("Show interstitial")
end
if (adcolony.isLoaded("rewardedVideo")) then
rewardedButton:setLabel("Show rewarded video")
end
elseif event.phase == "loaded" then
if data.zoneName == "interstitial" then
interstitialButton:setLabel("Show interstitial video")
elseif data.zoneName == "rewardedVideo" then
rewardedButton:setLabel("Show rewarded video")
end
elseif event.phase == "failed" then
if data.zoneName == "interstitial" then
interstitialButton:setLabel("Load interstitial video")
elseif data.zoneName == "rewardedVideo" then
rewardedButton:setLabel("Load rewarded video")
end
end
end
adcolony.init(adcolonyListener, {
appId = appId,
adZones = adZones,
adOrientation = "landscape",
debugLogging = true,
hasUserConsent = true
})
interstitialButton = widget.newButton {
label = "Load interstitial...",
width = 300,
onRelease = function(event)
if adcolony.isLoaded("interstitial") then
interstitialButton:setLabel("Load interstitial video...")
adcolony.show("interstitial")
else
interstitialButton:setLabel("Loading interstitial video...")
adcolony.load("interstitial")
end
end
}
interstitialButton.x, interstitialButton.y = display.contentCenterX, 100
rewardedButton = widget.newButton {
label = "Load rewarded video...",
width = 300,
onRelease = function(event)
if adcolony.isLoaded("rewardedVideo") then
rewardedButton:setLabel("Load rewarded video...")
adcolony.show("rewardedVideo")
else
rewardedButton:setLabel("Loading rewarded video...")
adcolony.load("rewardedVideo", { postPopup=true })
end
end
}
rewardedButton.x, rewardedButton.y = display.contentCenterX, 150
|
-- Provides a toggleable systray widget.
-- Code is based on this old wiki entry:
-- http://web.archive.org/web/20160316064839/http://awesome.naquadah.org/wiki/Systray_Hide/Show
local awful = require("awful")
local wibox = require("wibox")
local M = {}
local function creator(reverse)
local tray = wibox.widget.systray(reverse)
return {
visible = true,
stupid_bug = drawin({}),
systray = tray,
widget = wibox.container.constraint(tray, "min"),
toggle = M.toggle
}
end
function M.toggle(reg, visible)
if visible == reg.visible then
return
end
reg.visible = not reg.visible
if reg.visible then
reg.widget:set_strategy("min")
reg.widget:set_widget(reg.systray)
else
awesome.systray(reg.stupid_bug, 0, 0, 10, true, "#000000") -- black magic
reg.widget:set_strategy("exact")
reg.widget:set_widget(nil)
end
end
return setmetatable(M, { __call = function(_, ...) return creator(...) end })
|
--- Like a rotated camera, except we end up pushing back to a default rotation.
-- This same behavior is seen in Roblox vehicle seats
-- @classmod PushCamera
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local CameraState = require("CameraState")
local getRotationInXZPlane = require("getRotationInXZPlane")
local Math = require("Math")
local SummedCamera = require("SummedCamera")
local PushCamera = {}
PushCamera.ClassName = "PushCamera"
-- Max/Min aim up and down
PushCamera._maxY = math.rad(80)
PushCamera._minY = math.rad(-80)
PushCamera._angleXZ0 = 0 -- Initial
PushCamera._angleY = 0
PushCamera.FadeBackTime = 0.5
PushCamera.DefaultAngleXZ0 = 0
PushCamera._lastUpdateTime = -1
PushCamera.PushBackAfter = 0.5
function PushCamera.new()
local self = setmetatable({}, PushCamera)
return self
end
function PushCamera:__add(other)
return SummedCamera.new(self, other)
end
---
-- @param xzrotVector Vector2, the delta rotation to apply
function PushCamera:RotateXY(xzrotVector)
self.AngleX = self.AngleX + xzrotVector.x
self.AngleY = self.AngleY + xzrotVector.y
end
function PushCamera:StopRotateBack()
self.CFrame = self.CFrame
end
--- Resets to default position automatically
function PushCamera:Reset()
self.LastUpdateTime = 0
end
function PushCamera:__newindex(index, value)
if index == "CFrame" then
local xzrot = getRotationInXZPlane(value)
self.AngleXZ = math.atan2(xzrot.lookVector.x, xzrot.lookVector.z) + math.pi
local yrot = xzrot:toObjectSpace(value).lookVector.y
self.AngleY = math.asin(yrot)
elseif index == "DefaultCFrame" then
local xzrot = getRotationInXZPlane(value)
self.DefaultAngleXZ0 = math.atan2(xzrot.lookVector.x, xzrot.lookVector.z) + math.pi
local yrot = xzrot:toObjectSpace(value).lookVector.y
self.AngleY = math.asin(yrot)
elseif index == "AngleY" then
self._angleY = math.clamp(value, self.MinY, self.MaxY)
elseif index == "AngleX" or index == "AngleXZ" then
self.LastUpdateTime = tick()
self._angleXZ0 = value
elseif index == "MaxY" then
assert(value > self.MinY, "MaxY must be greater than MinY")
self._maxY = value
self.AngleY = self.AngleY -- Reclamp value
elseif index == "MinY" then
assert(value < self.MinY, "MinY must be less than MeeeaxY")
self._maxY = value
self.AngleY = self.AngleY -- Reclamp value
elseif index == "LastUpdateTime" then
self._lastUpdateTime = value
elseif PushCamera[index] ~= nil then
rawset(self, index, value)
else
error(index .. " is not a valid member or PushCamera")
end
end
function PushCamera:__index(index)
if index == "State" or index == "CameraState" or index == "Camera" then
local State = CameraState.new()
State.CFrame = self.CFrame
return State
elseif index == "LastUpdateTime" then
return self._lastUpdateTime
elseif index == "LookVector" then
return self.Rotation.lookVector
elseif index == "CFrame" then
return CFrame.Angles(0, self.AngleXZ, 0) * CFrame.Angles(self.AngleY, 0, 0)
elseif index == "AngleY" then
return self._angleY
elseif index == "PushBackDelta" then
return tick() - self.LastUpdateTime - self.PushBackAfter
elseif index == "PercentFaded" then
-- How far in we are to the animation. Starts at 0 upon update and goes slowly to 1.
return math.clamp(self.PushBackDelta / self.FadeBackTime, 0, 1)
elseif index == "PercentFadedCurved" then
-- A curved value of PercentFaded
return self.PercentFaded ^ 2
elseif index == "AngleX" or index == "AngleXZ" then
return Math.lerp(self._angleXZ0, self.DefaultAngleXZ0, self.PercentFadedCurved)
elseif index == "MaxY" then
return self._maxY
elseif index == "MinY" then
return self._minY
else
return PushCamera[index]
end
end
return PushCamera
|
local HardTanh = torch.class('nn.HardTanh', 'nn.Module')
function HardTanh:updateOutput(input)
return input.nn.HardTanh_updateOutput(self, input)
end
function HardTanh:updateGradInput(input, gradOutput)
return input.nn.HardTanh_updateGradInput(self, input, gradOutput)
end
|
return {'exil','existentialisme','existentialist','existentialistisch','existentie','existentieel','existentiefilosofie','existeren','exit','exitgesprek','exitinterview','exitpoll','exitstrategie','existentiefilosoof','existeer','existeerde','existeerden','existeert','existentialistische','existentiele','existentialisten','existenties','existerende','exitgesprekken','exitinterviews','exitpolls','existentiefilosofen'}
|
--Very small extension to structuredmission.
function mission.Log(_MethodName, _Msg, _OverrideDebug)
local _TempDebug = mission._Debug
if _OverrideDebug then mission._Debug = _OverrideDebug end
if mission._Debug and mission._Debug == 1 then
local _Name = mission._Name or mission.title or "Mission"
print("[" .. _Name .. "] - [" .. _MethodName .. "] - " .. _Msg)
end
if _OverrideDebug then mission._Debug = _TempDebug end
end
|
function onSay(cid, words, param)
local param = param.explode(param, ',')
if param then
if isPlayer(getCreatureByName(param[1])) == TRUE then
doPlayerSendTextMessage(getCreatureByName(param[1]), 22, "Você acabou de receber um item do Senhor!")
doPlayerAddItem(getCreatureByName(param[1]), param[2], param[3])
end
else
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Command param required.")
end
return TRUE
end
|
--[[
TheNexusAvenger
Runs callbacks when the aspect ratio of a GUI
requires switching for portrait and landscape.
--]]
local ReplicatedStorageProject = require(game:GetService("ReplicatedStorage"):WaitForChild("Project"):WaitForChild("ReplicatedStorage"))
local NexusObject = ReplicatedStorageProject:GetResource("ExternalUtil.NexusInstance.NexusObject")
local AspectRatioSwitcher = NexusObject:Extend()
AspectRatioSwitcher:SetClassName("AspectRatioSwitcher")
--[[
Creates an aspect ratio swticher.
--]]
function AspectRatioSwitcher:__new(Frame,MinimumAspectRatioForLandscape,SwitchToLandscapeCallback,SwitchToPortraitCallback)
self:InitializeSuper()
--Store the state.
self.CurrentState = "Unitialized"
self.Frame = Frame
self.MinimumAspectRatioForLandscape = MinimumAspectRatioForLandscape
self.SwitchCallbacks = {
Landscape = SwitchToLandscapeCallback,
Portrait = SwitchToPortraitCallback,
}
--Create the changed size event.
Frame:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
self:UpdateState()
end)
self:UpdateState()
end
--[[
Updates the state.
--]]
function AspectRatioSwitcher:UpdateState()
--Determine the new state.
local AspectRatio = self.Frame.AbsoluteSize.X/self.Frame.AbsoluteSize.Y
local NewState = (AspectRatio > self.MinimumAspectRatioForLandscape and "Landscape" or "Portrait")
--Call the callback if the state changed.
if NewState ~= self.CurrentState then
self.CurrentState = NewState
self.SwitchCallbacks[NewState]()
end
end
return AspectRatioSwitcher
|
local PistolShotGUIImp
local PistolShotGUIImpag
function CreatePistolGUI()
local PistolShotGUI = CreateFrame("Frame", "PistolShotGUI", UIParent, BackdropTemplateMixin and "BackdropTemplate")
PistolShotGUI:SetWidth(420)
PistolShotGUI:SetHeight(420)
PistolShotGUI:SetPoint("CENTER", UIParent)
PistolShotGUIImp = PistolShotGUI:CreateTexture("impGraphic")
PistolShotGUIImp:SetTexture("Interface\\AddOns\\RogueBox\\Guns.tga")
PistolShotGUIImp:SetWidth(420)
PistolShotGUIImp:SetHeight(420)
PistolShotGUIImp:SetPoint("CENTER", 0, 0)
PistolShotGUIImp:Hide()
PistolShotGUIImpag = PistolShotGUIImp:CreateAnimationGroup("PistolShotGUIImpag")
local PistolShotGUIImpanimation = PistolShotGUIImpag:CreateAnimation("Scale", "PistolShotGUIImpanimation")
PistolShotGUIImpanimation:SetScale(1.2, 1.2)
PistolShotGUIImpanimation:SetDuration(4)
PistolShotGUIImpanimation:SetSmoothing("IN_OUT")
PistolShotGUIImpanimation:SetEndDelay(26)
end
function HasShot()
--PistolShotGUIImp:Show()
--PistolShotGUIImpag:Play()
end
function EndShot()
PistolShotGUIImp:Hide()
PistolShotGUIImpag:Stop()
end
|
local combinations
local function generate_combinations(a, n, offset)
if n > (#a - offset) then
return
end
if n == 0 then
coroutine.yield({})
return
end
for v in combinations(a, n - 1, offset + 1) do
table.insert(v, 1, a[1 + offset])
coroutine.yield(v)
end
for v in combinations(a, n, offset + 1) do
coroutine.yield(v)
end
end
function combinations(a, n, offset)
return coroutine.wrap(function() generate_combinations(a, n, offset or 0) end)
end
local function generate_permutations(a, n)
if n == 0 then
coroutine.yield(a)
else
for i = 1, n do
a[n], a[i] = a[i], a[n]
generate_permutations(a, n - 1)
a[n], a[i] = a[i], a[n]
end
end
end
local function permutations(a)
return coroutine.wrap(function () generate_permutations(a, #a) end)
end
local function unique_letters(s)
local letter_set = {}
s:gsub('%a', function(l)
letter_set[l] = true
end)
local letters = {}
for l in pairs(letter_set) do
table.insert(letters, l)
end
return letters
end
local function populate_letter_map(letter_map, letters, values)
for i = 1, #letters do
letter_map[letters[i]] = values[i]
end
end
local function evaluates_true(solution)
return load('return ' .. solution)()
end
local function has_no_leading_zeros(solution)
return not (solution:find('^0%d+') or solution:find('%D0%d+'))
end
local function solve(puzzle)
local letters = unique_letters(puzzle)
local letter_map = {}
for c in combinations({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, #letters) do
for p in permutations(c) do
populate_letter_map(letter_map, letters, p)
local solution = puzzle:gsub('%a', letter_map)
if evaluates_true(solution) and has_no_leading_zeros(solution) then
return letter_map
end
end
end
end
return {
solve = solve
}
|
-- {{{ Required deps
local awesome, tag = awesome, screen
local awful = require("awful")
-- }}}
-- {
-- workspace {
-- screen {
-- tag1, tag2, ...
-- }
-- }
-- }
local workspaces = {
workspaces = {},
current_workspace = 1
}
local workspace_tags = {}
function workspaces.next_workspace()
-- Compute the new workspace number
if workspaces.current_workspace == #workspaces.workspaces then
workspaces.switchWorkspace(1)
else
workspaces.switchWorkspace(workspaces.current_workspace + 1)
end
end
function workspaces.previous_workspace()
if workspaces.current_workspace == 1 then
workspaces.switchWorkspace(#workspaces.workspaces)
else
workspaces.switchWorkspace(workspaces.current_workspace - 1)
end
end
function workspaces.switchWorkspace(newWorkspace)
-- Make sure that we have a spot in the workspace_tags
if workspace_tags[workspaces.current_workspace] == nil then
workspace_tags[workspaces.current_workspace] = {}
end
for s in screen do
-- Current implem is a bit shitty : the address of the screen could change
local screenId = s
workspace_tags[workspaces.current_workspace][screenId] = {
workspaces = {},
selection = {}
}
-- Make sure that we have all the tags of each screen in the current workspace saved
-- and desactivate all of them
for k,v in pairs(s.tags) do
workspace_tags[workspaces.current_workspace][screenId]["workspaces"][v.name] = v
workspace_tags[workspaces.current_workspace][screenId]["selection"][v.name] = v.selected
v.activated = false
end
-- Either we already have an entry for this screen in the workspace tags
-- in that case, we restore it
-- else, we create a new one
if workspace_tags[newWorkspace] == nil or workspace_tags[newWorkspace][screenId] == nil then
-- Create something new
awful.tag(workspaces.all_tags[workspaces.workspaces[newWorkspace]], s, awful.layout.layouts)
else
-- Restore
for k,v in pairs(workspace_tags[newWorkspace][screenId]["workspaces"]) do
v.activated = true
v.selected = workspace_tags[newWorkspace][screenId]["selection"][v.name]
end
end
end
workspaces.current_workspace = newWorkspace
end
return workspaces
|
--[[----------------------------------------------------------------------------
Application Name:
CalibratedBlobDiameters
Summary:
Measuring coin diameters on calibrated and corrected image
Description:
Calibrating a camera using one shot of a checkerboard calibration target.
Correcting the image by rectification with alignment of camera and world coordinates.
Finding coins and measuring their diameters in the rectified image.
How to Run:
Starting this sample is possible either by running the app (F5) or
debugging (F7+F10). Setting breakpoint on the first row inside the 'main'
function allows debugging step-by-step after 'Engine.OnStarted' event.
Results can be seen in the image viewer on the DevicePage.
To run this sample a device with SICK Algorithm API is necessary.
For example InspectorP or SIM4000 with latest firmware. Alternatively the
Emulator on AppStudio 2.3 or higher can be used. The images can be seen in the
image viewer on the DevicePage.
More Information:
Tutorial "Algorithms - Calibration2D".
------------------------------------------------------------------------------]]
--Start of Global Scope---------------------------------------------------------
-- Delay in ms between visualization steps for demonstration purpose
local DELAY = 1000
-- The diameter of a 10 cent Euro coin is 19.75 mm (source: Wikipedia)
local COIN_DIAMETER = 19.75 -- in mm
local DIAMETER_TOLERANCE = 1 -- in mm
-- Creating viewer
local viewer = View.create()
-- Shape decorations for pass/fail
local passDecoration = View.PixelRegionDecoration.create()
passDecoration:setColor(0, 255, 0, 100) -- Transparent green
local failDecoration = View.PixelRegionDecoration.create()
failDecoration:setColor(255, 0, 0, 100) -- Transparent red
--End of Global Scope-----------------------------------------------------------
--Start of Function and Event Scope---------------------------------------------
--@calibrate(checkerBoard:Image):Image
local function calibrate(checkerBoard)
-- Specify the size of a square in the world (for example 166 mm / 11 squares)
local squareSize = 166.0 / 11 -- mm
-- Perform a one-shot calibration
local cameraModel, error = Image.Calibration.Pose.estimateOneShot(checkerBoard, {squareSize}, 'COORDINATE_CODE')
print('Camera calibrated with average error: ' .. (math.floor(error * 10)) / 10 .. ' px')
-- Correct the image of the calibration target as a test, using "align" mode
local correction = Image.Calibration.Correction.create()
local cxy = squareSize * 6 -- Select center point for aligned image in both x and y
local sxy = squareSize * 13 -- Select the size of the alignment region in both x and y
local worldRectangle = Shape.createRectangle(Point.create(cxy, cxy), sxy, sxy)
correction:setAlignMode(cameraModel, worldRectangle)
local correctedImage = correction:apply(checkerBoard)
viewer:clear()
viewer:addImage(correctedImage)
viewer:present()
Script.sleep(DELAY) -- For demonstration purpose only
return correction
end
--@measure(liveImage:Image,correction:Image.Calibration.Correction)
local function measure(liveImage, correction)
-- Rectify the image
local correctedImage = correction:apply(liveImage)
viewer:clear()
viewer:addImage(correctedImage)
viewer:present()
Script.sleep(DELAY) -- For demonstration purpose only
-- Find the coins
local darkRegions =
correctedImage:threshold(1, 125):dilate(5):erode(5):fillHoles()
local blobs = darkRegions:findConnected(1000)
local coinFilter = Image.PixelRegion.Filter.create()
coinFilter:setRange('COMPACTNESS', 0.7, 1.0)
coinFilter:sortBy('AREA')
local coins = coinFilter:apply(blobs, correctedImage)
-- Measure the coin sizes
for c = 1, #coins do
local area = coins[c]:getArea(correctedImage)
local center = coins[c]:getCenterOfGravity(correctedImage)
local r = math.sqrt(area / math.pi)
local d = 2 * r
-- Visualize pass/fail
if math.abs(d - COIN_DIAMETER) <= DIAMETER_TOLERANCE then
viewer:addPixelRegion(coins[c], passDecoration)
else
viewer:addPixelRegion(coins[c], failDecoration)
end
-- Add text with the measured size
local text = View.TextDecoration.create()
text:setPosition(center:getX() + r, center:getY() - r)
text:setSize(8) -- Text size in mm
viewer:addText(string.format('d = %.1f', d), text) -- Print result with one decimal
print('Diameter coin ' .. c .. ': ' .. string.format('d = %.2f', d))
end
viewer:present()
print('App finished.')
end
local function main()
-- Calibrate
local checkerBoard = Image.load('resources/pose.bmp')
viewer:clear()
viewer:addImage(checkerBoard)
viewer:present()
Script.sleep(DELAY) -- For demonstration purpose only
local correction = calibrate(checkerBoard)
-- Calibrated measurement in simulated "live image"
local liveImage = Image.load('resources/coins.bmp')
viewer:clear()
viewer:addImage(liveImage)
viewer:present()
Script.sleep(DELAY) -- For demonstration purpose only
measure(liveImage, correction)
end
--The following registration is part of the global scope which runs once after startup
--Registration of the 'main' function to the 'Engine.OnStarted' event
Script.register('Engine.OnStarted', main)
--End of Function and Event Scope--------------------------------------------------
|
local formatter = require('formatter.format')
local logging = require('yode-nvim.logging')
local storeBundle = require('yode-nvim.redux.index')
local seditors = storeBundle.seditors
local changeSyncing = require('yode-nvim.changeSyncing')
local M = {}
local formatBuffer = function(bufId, shouldWrite, callback)
local currentLines = vim.api.nvim_buf_get_lines(bufId, 0, -1, true)
return formatter.format('', '', 1, #currentLines, shouldWrite, callback)
end
M.formatWrite = function()
local log = logging.create('formatWrite')
local bufId = vim.fn.bufnr('%')
local sed = seditors.selectors.getSeditorById(bufId)
if sed then
log.debug(
string.format(
'formatting file buffer %d of seditor %d',
sed.fileBufferId,
sed.seditorBufferId
)
)
local cleanup = function()
-- NOTICE: this is needed to schedule the subscription behind all other
-- scheduled text changig actions in `changeSyncing.lua`. Without it
-- you get a 'onSeditorBufferLines' call of the `sed.seditorBufferId` buffer for the
-- changes of the formatter. This is the case, because you subscribe to
-- the seditor again, before the changes to the file buffer get
-- applied.
vim.schedule(function()
log.debug('subscribe to seditor (current) buffer again', vim.fn.bufnr('%'))
changeSyncing.subscribeToBuffer()
end)
end
vim.api.nvim_buf_call(sed.fileBufferId, function()
log.debug('subscribe to file buffer to sync changes', sed.fileBufferId)
changeSyncing.subscribeToBuffer()
formatBuffer(sed.fileBufferId, true, function(err, msg)
if err then
log.error('formatting error:', err, bufId)
cleanup()
return
end
if msg == formatter.statusCodes.BUFFER_CHANGED then
log.info('formatting aborted, because buffer changed!', bufId)
else
log.debug('formatting succeeded with msg:', msg, bufId)
log.info('succeeded')
end
-- TODO `update` call in formatter.nvim doesn't write the file, nor
-- `write`. Also calling `update` here instead of `write` doesn't
-- write the file. Only `write` here seems to work, but why?
vim.cmd('write')
cleanup()
end)
end)
else
log.debug('normal buffer')
-- NOTICE using callback here also, to have the right point in time to
-- call `write`, which doesn't work always.
formatBuffer(bufId, true, function(err, msg)
if err then
log.error('formatting error:', err, bufId)
return
end
if msg == formatter.statusCodes.BUFFER_CHANGED then
log.info('formatting aborted, because buffer changed!', bufId)
else
log.debug('formatting succeeded with msg:', msg, bufId)
log.info('succeeded')
end
-- TODO same problem as above
vim.cmd('write')
end)
end
end
return M
|
local Broadcast = require("core.Broadcast")
return {
listeners = {
playerEnter = function(state)
return function(self, player)
Broadcast.sayAt(player)
Broadcast.sayAt(player,
"<cyan>Hint: You can pick up items from the room listed in '<white>look' with '<white>get' followed by a reasonable keyword for the item e.g., '<white>get cheese' Some items, like the chest, may contain items; you can check by looking at the item.",
80);
end
end,
},
}
|
--[[
Licensed under GNU General Public License v2
* (c) 2014, projektile
* (c) 2013, Luke Bonham
* (c) 2010-2012, Peter Hofmann
--]]
local tag = require("awful.tag")
local beautiful = require("beautiful")
local math = { ceil = math.ceil,
floor = math.floor,
max = math.max }
local tonumber = tonumber
local termfair = { name = "termfair" }
function termfair.arrange(p)
-- Layout with fixed number of vertical columns (read from nmaster).
-- New windows align from left to right. When a row is full, a now
-- one above it is created. Like this:
-- (1) (2) (3)
-- +---+---+---+ +---+---+---+ +---+---+---+
-- | | | | | | | | | | | |
-- | 1 | | | -> | 2 | 1 | | -> | 3 | 2 | 1 | ->
-- | | | | | | | | | | | |
-- +---+---+---+ +---+---+---+ +---+---+---+
-- (4) (5) (6)
-- +---+---+---+ +---+---+---+ +---+---+---+
-- | 4 | | | | 5 | 4 | | | 6 | 5 | 4 |
-- +---+---+---+ -> +---+---+---+ -> +---+---+---+
-- | 3 | 2 | 1 | | 3 | 2 | 1 | | 3 | 2 | 1 |
-- +---+---+---+ +---+---+---+ +---+---+---+
-- A useless gap (like the dwm patch) can be defined with
-- beautiful.useless_gap_width.
local useless_gap = tonumber(beautiful.useless_gap_width) or 0
if useless_gap < 0 then useless_gap = 0 end
-- A global border can be defined with
-- beautiful.global_border_width
local global_border = tonumber(beautiful.global_border_width) or 0
if global_border < 0 then global_border = 0 end
-- Themes border width requires an offset
local bw = tonumber(beautiful.border_width) or 0
-- Screen.
local wa = p.workarea
local cls = p.clients
-- Borders are factored in.
wa.height = wa.height - ((global_border * 2) + (bw * 2))
wa.width = wa.width - ((global_border * 2) + (bw * 2))
-- How many vertical columns?
local t = tag.selected(p.screen)
local num_x = termfair.nmaster or tag.getnmaster(t)
-- Do at least "desired_y" rows.
local desired_y = termfair.ncol or tag.getncol(t)
if #cls > 0
then
local num_y = math.max(math.ceil(#cls / num_x), desired_y)
local cur_num_x = num_x
local at_x = 0
local at_y = 0
local remaining_clients = #cls
local width = math.floor(wa.width / num_x)
local height = math.floor(wa.height / num_y)
-- We start the first row. Left-align by limiting the number of
-- available slots.
if remaining_clients < num_x
then
cur_num_x = remaining_clients
end
-- Iterate in reversed order.
for i = #cls,1,-1
do
-- Get x and y position.
local c = cls[i]
local this_x = cur_num_x - at_x - 1
local this_y = num_y - at_y - 1
-- Calc geometry.
local g = {}
if this_x == (num_x - 1)
then
g.width = wa.width - (num_x - 1) * width - useless_gap
else
g.width = width - useless_gap
end
if this_y == (num_y - 1)
then
g.height = wa.height - (num_y - 1) * height - useless_gap
else
g.height = height - useless_gap
end
g.x = wa.x + this_x * width + global_border
g.y = wa.y + this_y * height + global_border
if useless_gap > 0
then
-- All clients tile evenly.
g.x = g.x + (useless_gap / 2)
g.y = g.y + (useless_gap / 2)
end
c:geometry(g)
remaining_clients = remaining_clients - 1
-- Next grid position.
at_x = at_x + 1
if at_x == num_x
then
-- Row full, create a new one above it.
at_x = 0
at_y = at_y + 1
-- We start a new row. Left-align.
if remaining_clients < num_x
then
cur_num_x = remaining_clients
end
end
end
end
end
return termfair
|
------------------------------- Sourcing ---------------------------------------
-- This file executes all the plugins. This file itself will be executed from
-- the init.lua file. This file serves as the entrypoint to the plugins folder
-- under lua (/lua/plugins/). Executing plugins will execute this file which
-- in turn execute the specific plugin mentioned.
--
-- NOTE: names must begin with plugins followed by the name of the folder the
-- plugin is placed in.
vim.cmd('source ' .. vim.fn.stdpath('config') .. '/lua/configs/gruvbox.vim')
vim.cmd('source ' .. vim.fn.stdpath('config') .. '/lua/configs/undotree.vim')
require "configs.lspinstall"
require "configs.nvimtree"
require "configs.telescope"
require "configs.treesitter"
require "configs.completion"
require "configs.diffview"
require "configs.icons"
require "configs.statusline"
require "configs.whichkey"
require "configs.dashboard"
require "configs.autopairs"
require "configs.colorizer"
require "configs.lsptrouble"
require "configs.zenmode"
require "configs.dim"
require "configs.git"
require "configs.gitsigns"
require "configs.indentmarkers"
|
Global( "PlayerDistance", {} )
function PlayerDistance:Init(anID)
self.playerID = anID
self.unitParams = {}
self.distance = 0
self.lastDistance = -1
self.lastAngle = -1
self.SKIP_UPDATES_CNT = 5
self.skipCnt = 0
self.base = copyTable(PlayerBase)
self.base:Init()
self.eventFunc = self:GetEventFunc()
self:RegisterEvent(anID)
end
function PlayerDistance:SubscribeTargetGui(aLitener)
end
function PlayerDistance:UnsubscribeTargetGui()
end
function PlayerDistance:SubscribeRaidGui(aLitener)
self.lastDistance = -1
self.lastAngle = -1
self.skipCnt = 0
self.base:SubscribeRaidGui(self.playerID, aLitener, self.eventFunc)
self:UpdateValueIfNeeded()
end
function PlayerDistance:UnsubscribeRaidGui()
local info = { }
info.needShow = false
info.visibleChanged = true
local res = self.base.guiRaidListener and self.base.guiRaidListener.listenerDistance(info, self.base.guiRaidListener)
self.base:UnsubscribeRaidGui()
end
function PlayerDistance:TryDestroy()
if self.base:CanDestroy() then
self:UnRegisterEvent()
return true
end
return false
end
function PlayerDistance:UpdateValueIfNeeded()
if self.skipCnt == 0 then
self.skipCnt = self.SKIP_UPDATES_CNT
else
self.skipCnt = self.skipCnt - 1
return
end
self.distance = getDistanceToTarget( self.playerID )
local angle = 0
local profile = GetCurrentProfile()
if self.distance ~= nil and profile.raidFormSettings.showArrowButton then
angle = getAngleToTarget(self.playerID)
end
if self.distance ~= self.lastDistance or angle ~= self.lastAngle then
local info = { }
info.dist = self.distance
info.angle = angle
info.needShow = self.distance ~= nil
info.visibleChanged = self.distance ~= self.lastDistance
self.lastDistance = info.dist
self.lastAngle = info.angle
local res = self.base.guiRaidListener and self.base.guiRaidListener.listenerDistance(info, self.base.guiRaidListener)
end
end
function PlayerDistance:GetEventFunc()
return function(aParams)
end
end
function PlayerDistance:RegisterEvent(anID)
end
function PlayerDistance:UnRegisterEvent()
end
|
-- gruvbox
-- Retro groove color scheme for Vim
-- https://github.com/morhetz/gruvbox
--
vim.cmd [[
augroup gruvbox-overrides
autocmd!
" HTML
autocmd ColorScheme gruvbox highlight htmlArg cterm=italic gui=italic ctermfg=214 guifg=#fabd2f
" Css
autocmd ColorScheme gruvbox highlight cssBorderProp cterm=none gui=none ctermfg=208 guifg=#fe8019
"JavaScript
autocmd ColorScheme gruvbox highlight jsFunction cterm=italic gui=italic ctermfg=108 guifg=#8ec07c
" JSON
autocmd ColorScheme gruvbox highlight jsonKeyword cterm=italic gui=italic ctermfg=142 guifg=#b8bb26
" JSX
autocmd ColorScheme gruvbox highlight xmlAttrib cterm=italic gui=italic ctermfg=214 guifg=#fabd2f
autocmd ColorScheme gruvbox highlight jsxTagName cterm=none gui=none ctermfg=109 guifg=#83a598
" Ruby
autocmd ColorScheme gruvbox highlight rubyDefine cterm=italic gui=italic ctermfg=108 guifg=#8ec07c
autocmd ColorScheme gruvbox highlight rubyDefine cterm=italic gui=italic ctermfg=108 guifg=#8ec07c
autocmd ColorScheme gruvbox highlight rubyKeyword cterm=italic gui=italic ctermfg=167 guifg=#fb4934
autocmd ColorScheme gruvbox highlight rubyPseudoVariable cterm=italic gui=italic ctermfg=175 guifg=#d3869b
autocmd ColorScheme gruvbox highlight rubyTestAction ctermfg=229 guifg=#fbf1c7
autocmd ColorScheme gruvbox highlight rubyAssertion ctermfg=229 guifg=#fbf1c7
autocmd ColorScheme gruvbox highlight rubyResponse ctermfg=229 guifg=#fbf1c7
" TypeScript
autocmd ColorScheme gruvbox highlight typescriptStorageClass cterm=italic gui=italic ctermfg=208 guifg=#fe8019
autocmd ColorScheme gruvbox highlight typescriptStatement cterm=italic gui=italic ctermfg=167 guifg=#fb4934
autocmd ColorScheme gruvbox highlight typescriptReserved cterm=italic gui=italic ctermfg=108 guifg=#8ec07c
autocmd ColorScheme gruvbox highlight typescriptLabel cterm=italic gui=italic ctermfg=108 guifg=#8ec07c
autocmd ColorScheme gruvbox highlight typescriptType cterm=italic gui=italic ctermfg=214 guifg=#fabd2f
autocmd ColorScheme gruvbox highlight jsxAttrib cterm=italic gui=italic ctermfg=214 guifg=#fabd2f
" Global
autocmd ColorScheme gruvbox highlight Conditional cterm=italic gui=italic ctermfg=167 guifg=#fb4934
autocmd ColorScheme gruvbox highlight StorageClass cterm=italic gui=italic ctermfg=208 guifg=#fe8019
autocmd ColorScheme gruvbox highlight Include cterm=italic gui=italic ctermfg=108 guifg=#8ec07c
autocmd ColorScheme gruvbox highlight Identifier cterm=italic gui=italic ctermfg=109 guifg=#83a598
autocmd ColorScheme gruvbox highlight Statement cterm=italic gui=italic ctermfg=167 guifg=#fb4934
autocmd ColorScheme gruvbox highlight PreProc cterm=italic gui=italic ctermfg=108 guifg=#8ec07c
augroup END
]]
vim.g.gruvbox_contrast_dark = 'hard' -- Set contrast level
vim.g.gruvbox_bold = 1 -- Enable bold
vim.g.gruvbox_undercurl = 1 -- Enable squigglies
vim.g.gruvbox_italic = 1 -- Enable italics
-- os.setenv("BAT_THEME", "gruvbox-dark")
-- vim.cmd [[
-- colorscheme gruvbox
-- ]]
|
-- Define sets and vars used by this job file.
function init_gear_sets()
gear.melee = {}
gear.melee.feet = { name="Argosy Sollerets +1", augments={'HP+65','"Dbl.Atk."+3','"Store TP"+5',}}
gear.acc = {}
gear.acc.head = { name="Valorous Mask", augments={'Accuracy+25 Attack+25','STR+10','Accuracy+15','Attack+6',}}
gear.wsdmg = {}
gear.wsdmg.head = { name="Valorous Mask", augments={'Weapon skill damage +4%','STR+4','Accuracy+12','Attack+15',}}
gear.wsdmg.feet = { name="Argosy Sollerets +1", augments={'STR+12','DEX+12','Attack+20',}}
--------------------------------------
-- Precast sets
--------------------------------------
sets.precast.JA['Killer Instinct'] = {head="Ankusa Helm +1"}
sets.precast.JA['Feral Howl'] = {body="Ankusa Jackcoat +1"}
sets.precast.JA['Call Beast'] = {hands="Ankusa Gloves +1"}
sets.precast.JA['Familiar'] = {legs="Ankusa Trousers +1"}
sets.precast.JA['Tame'] = {head="Totemic Helm +1",ear1="Tamer's Earring",legs="Stout Kecks"}
sets.precast.JA['Spur'] = {feet="Ferine Ocreae +2"}
sets.precast.JA['Reward'] = {ammo=RewardFood,
head="Stout Bonnet",neck="Aife's Medal",ear1="Lifestorm Earring",ear2="Neptune's Pearl",
body="Totemic Jackcoat +1",hands="Totemic Gloves +1",ring1="Aquasoul Ring",ring2="Aquasoul Ring",
back="Pastoralist's Mantle",waist="Crudelis Belt",legs="Ankusa Trousers +1",feet="Ankusa Gaiters +1"}
sets.precast.JA['Charm'] = {ammo="Tsar's Egg",
head="Totemic Helm +1",neck="Ferine Necklace",ear1="Enchanter's Earring",ear2="Reverie Earring +1",
body="Ankusa Jackcoat +1",hands="Ankusa Gloves +1",ring1="Dawnsoul Ring",ring2="Dawnsoul Ring",
back="Aisance Mantle +1",waist="Aristo Belt",legs="Ankusa Trousers +1",feet="Ankusa Gaiters +1"}
-- CURING WALTZ
sets.precast.Waltz = {ammo="Tsar's Egg",
head="Totemic Helm +1",neck="Ferine Necklace",ear1="Enchanter's Earring",ear2="Reverie Earring +1",
body="Gorney Haubert +1",hands="Totemic Gloves +1",ring1="Valseur's Ring",ring2="Asklepian Ring",
back="Aisance Mantle +1",waist="Aristo Belt",legs="Osmium Cuisses",feet="Scamp's Sollerets"}
-- HEALING WALTZ
sets.precast.Waltz['Healing Waltz'] = {}
-- STEPS
sets.precast.Step = {ammo="Jukukik Feather",
head="Yaoyotl Helm",neck="Ziel Charm",ear1="Choreia Earring",ear2="Heartseeker Earring",
body="Mikinaak Breastplate",hands="Buremte Gloves",ring1="Mars's Ring",ring2="Oneiros Annulet",
back="Letalis Mantle",waist="Hurch'lan Sash",legs="Skadi's Chausses +1",feet="Gorney Sollerets +1"}
-- VIOLENT FLOURISH
sets.precast.Flourish1 = {}
sets.precast.Flourish1['Violent Flourish'] = {body="Ankusa Jackcoat +1",legs="Iuitl Tights +1",feet="Iuitl Gaiters +1"}
sets.precast.FC = {ammo="Impatiens",neck="Baetyl Pendant",ring1="Prolix Ring"}
sets.precast.FC.Utsusemi = set_combine(sets.precast.FC, {neck="Magoraga Beads"})
-- WEAPONSKILLS
-- Default weaponskill set.
sets.precast.WS = {
head="Nyame Helm",neck="Fotia Gorget",ear1="Moonshade Earring",ear2="Sherida Earring",
body="Valorous Mail",hands="Nyame Gauntlets",ring1="Gere Ring",ring2="Regal Ring",
back="Artio's Mantle",waist="Fotia Belt",legs="Nyame Flanchard",feet="Nyame Sollerets"}
sets.precast.WS.WSAcc = sets.precast.WS
-- Specific weaponskill sets.
sets.precast.WS['Primal Rend'] = {ammo="Erlene's Notebook",
head="Jumalik Helm",neck="Baetyl Pendant",ear1="Crematio Earring",ear2="Friomisi Earring",
body="Valorous Mail",hands="Valorous Mitts",ring1="Shiva Ring +1",ring2="Acumen Ring",
back="Toro Cape",waist="Orpheus's Sash",legs="Augury Cuisses +1",feet="Valorous Greaves"}
sets.precast.WS['Cloudsplitter'] = set_combine(sets.precast.WS['Primal Rend'])
--------------------------------------
-- Midcast sets
--------------------------------------
sets.midcast.FastRecast = {ammo="Demonry Core",
head="Iuitl Headgear +1",neck="Baetyl Pendant",
body="Totemic Jackcoat +1",hands="Iuitl Wristbands +1",ring1="Prolix Ring",ring2="Dark Ring",
back="Mollusca Mantle",waist="Hurch'lan Sash",legs="Iuitl Tights +1",feet="Iuitl Gaiters +1"}
sets.midcast.Utsusemi = sets.midcast.FastRecast
-- PET SIC & READY MOVES
sets.midcast.Pet.WS = {ammo="Demonry Core",
head="Totemic Helm +1",neck="Ferine Necklace",ear1="Domesticator's Earring",ear2="Sabong Earring",
body="Mirke Wardecors",hands="Ferine Manoplas +2",ring1="Angel's Ring",ring2="Angel's Ring",
back="Ferine Mantle",waist="Hurch'lan Sash",legs="Desultor Tassets",feet="Totemic Gaiters +1"}
sets.midcast.Pet.WS.Unleash = set_combine(sets.midcast.Pet.WS, {hands="Scorpion Mittens"})
sets.midcast.Pet.Neutral = {legs="Desultor Tassets"}
sets.midcast.Pet.Favorable = {head="Ferine Cabasset +2",legs="Desultor Tassets"}
--------------------------------------
-- Idle/resting/defense/etc sets
--------------------------------------
-- RESTING
sets.resting = {ammo="Demonry Core",
head="Twilight Helm",neck="Wiglen Gorget",ear1="Domesticator's Earring",ear2="Sabong Earring",
body="Twilight Mail",hands="Totemic Gloves +1",ring1="Paguroidea Ring",ring2="Sheltered Ring",
back="Pastoralist's Mantle",waist="Muscle Belt +1",legs="Ferine Quijotes +2",feet="Skadi's Jambeaux +1"}
-- IDLE SETS
sets.idle = {ammo="Demonry Core",
head="Twilight Helm",neck="Wiglen Gorget",ear1="Domesticator's Earring",ear2="Sabong Earring",
body="Twilight Mail",hands="Totemic Gloves +1",ring1="Paguroidea Ring",ring2="Sheltered Ring",
back="Pastoralist's Mantle",waist="Muscle Belt +1",legs="Malignance Tights",feet="Skadi's Jambeaux +1"}
sets.idle.Refresh = {head="Wivre Hairpin",body="Twilight Mail",hands="Ogier's Gauntlets",legs="Ogier's Breeches"}
sets.idle.Reraise = set_combine(sets.idle, {head="Twilight Helm",body="Twilight Mail"})
sets.idle.Pet = sets.idle
sets.idle.Pet.Engaged = {ammo="Demonry Core",
head="Anwig Salade",neck="Ferine Necklace",ear1="Domesticator's Earring",ear2="Sabong Earring",
body="Ankusa Jackcoat +1",hands="Totemic Gloves +1",ring1="Angel's Ring",ring2="Angel's Ring",
back="Ferine Mantle",waist="Hurch'lan Sash",legs="Ankusa Trousers +1",feet="Armada Sollerets"}
-- DEFENSE SETS
sets.defense.PDT = {ammo="Jukukik Feather",
head="Malignance Chapeau",neck="Loricate Torque +1",
body="Malignance Tabard",ring1="Patricius Ring",ring2="Defending Ring",
back="Moonlight Cape",waist="Flume Belt +1",legs="Malignance Tights",feet="Malignance Boots"}
sets.defense.Hybrid = set_combine(sets.defense.PDT, {ring1="Purity Ring"})
sets.defense.Killer = set_combine(sets.defense.Hybrid, {body="Ferine Gausape +2"})
sets.defense.MDT = set_combine(sets.defense.PDT, {ammo="Sihirik",
head="Ogier's Helm",ear1="Flashward Earring",ear2="Spellbreaker Earring",
body="Nocturnus Mail",ring1="Shadow Ring",
back="Engulfer Cape",waist="Nierenschutz"})
sets.Kiting = {ammo="Demonry Core",
head="Iuitl Headgear +1",neck="Twilight Torque",
body="Mekira Meikogai",hands="Iuitl Wristbands +1",ring1="Dark Ring",ring2="Defending Ring",
back="Repulse Mantle",waist="Hurch'lan Sash",legs="Iuitl Tights +1",feet="Skadi's Jambeaux +1"}
--------------------------------------
-- Engaged sets
--------------------------------------
sets.engaged = {ammo="Aurgelmir Orb",
head="Blistering Sallet +1",neck="Anu Torque",ear1="Suppanomimi",ear2="Sherida Earring",
body="Tali'ah Manteel +2",hands="Emi. Gauntlets +1",ring1="Gere Ring",ring2="Epona's Ring",
back="Artio's Mantle",waist="Sweordfaetels",legs="Meg. Chausses +2",feet="Nyame Sollerets"}
sets.engaged.Acc = {ammo="Jukukik Feather",
head="Yaoyotl Helm",neck="Ziel Charm",ear1="Heartseeker Earring",ear2="Dudgeon Earring",
body="Mes'yohi Haubergeon",hands="Buremte Gloves",ring1="Mars's Ring",ring2="Oneiros Annulet",
back="Letalis Mantle",waist="Hurch'lan Sash",legs="Malignance Tights",feet="Whirlpool Greaves"}
sets.engaged.Killer = set_combine(sets.engaged, {body="Ferine Gausape +2",waist="Cetl Belt"})
sets.engaged.Killer.Acc = set_combine(sets.engaged.Acc, {body="Ferine Gausape +2",waist="Cetl Belt"})
-- EXAMPLE SETS WITH PET MODES
--[[
sets.engaged.PetStance = {}
sets.engaged.PetStance.Acc = {}
sets.engaged.PetTank = {}
sets.engaged.PetTank.Acc = {}
sets.engaged.PetStance.Killer = {}
sets.engaged.PetStance.Killer.Acc = {}
sets.engaged.PetTank.Killer = {}
sets.engaged.PetTank.Killer.Acc = {}
]]
-- MORE EXAMPLE SETS WITH EXPANDED COMBAT FORMS
--[[
sets.engaged.DW.PetStance = {}
sets.engaged.DW.PetStance.Acc = {}
sets.engaged.DW.PetTank = {}
sets.engaged.DW.PetTank.Acc = {}
sets.engaged.KillerDW.PetStance = {}
sets.engaged.KillerDW.PetStance.Acc = {}
sets.engaged.KillerDW.PetTank= {}
sets.engaged.KillerDW.PetTank.Acc = {}
]]
--------------------------------------
-- Custom buff sets
--------------------------------------
sets.buff['Killer Instinct'] = {body="Ferine Gausape +2"}
end
|
data:extend({
{
type = "sound",
name = "ion-cannon-ready-CommandAndConquer",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/CommandAndConquer/IonCannonReady.ogg",
volume = 0.75
},
},
},
{
type = "sound",
name = "ion-cannon-charging-CommandAndConquer",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/CommandAndConquer/IonCannonCharging.ogg",
volume = 0.75
},
},
},
{
type = "sound",
name = "select-target-CommandAndConquer",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/CommandAndConquer/SelectTarget.ogg",
volume = 0.75
},
},
},
{
type = "sound",
name = "unable-to-comply-CommandAndConquer",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/CommandAndConquer/UnableToComply.ogg",
volume = 0.75
},
},
},
})
data:extend({
{
type = "sound",
name = "ion-cannon-ready-TiberianSunCABAL",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/TiberianSunCABAL/IonCannonReady.ogg",
volume = 0.75
},
},
},
{
type = "sound",
name = "ion-cannon-charging-TiberianSunCABAL",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/TiberianSunCABAL/IonCannonCharging.ogg",
volume = 0.75
},
},
},
{
type = "sound",
name = "select-target-TiberianSunCABAL",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/TiberianSunCABAL/SelectTarget.ogg",
volume = 0.75
},
},
},
{
type = "sound",
name = "unable-to-comply-TiberianSunCABAL",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/TiberianSunCABAL/UnableToComply.ogg",
volume = 0.75
},
},
},
})
data:extend({
{
type = "sound",
name = "ion-cannon-ready-TiberianSunEVA",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/TiberianSunEVA/IonCannonReady.ogg",
volume = 0.75
},
},
},
{
type = "sound",
name = "ion-cannon-charging-TiberianSunEVA",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/TiberianSunEVA/IonCannonCharging.ogg",
volume = 0.75
},
},
},
{
type = "sound",
name = "select-target-TiberianSunEVA",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/TiberianSunEVA/SelectTarget.ogg",
volume = 0.75
},
},
},
{
type = "sound",
name = "unable-to-comply-TiberianSunEVA",
variations =
{
{
filename = "__Orbital Ion Cannon__/sound/TiberianSunEVA/UnableToComply.ogg",
volume = 0.75
},
},
},
})
|
local kong = kong
local HeaderRouter = {
-- plugin should be executed after authentication and transformation
-- phase, but before logging
PRIORITY = 600,
VERSION = "0.1",
}
local function match_rule(rule)
for header_name,header_value in pairs(rule.condition) do
local request_header_value = kong.request.get_header(header_name)
-- all headers must be matched
if request_header_value ~= header_value then
return
end
end
return true
end
local function find_corresponding_upstream(rules)
for i,rule in ipairs(rules) do
local rule_upstream = rule["upstream_name"]
if match_rule(rule) then
return rule_upstream
end
end
end
function HeaderRouter:access(plugin_conf)
local rules = plugin_conf.rules
local alternate_upstream = find_corresponding_upstream(rules)
if alternate_upstream then
-- sets alternate upstream if a rule is matched
local ok, err = kong.service.set_upstream(alternate_upstream)
if not ok then
kong.log.err(err)
return
end
end
end
return HeaderRouter
|
object_mobile_dressed_bh_male_human_02 = object_mobile_shared_dressed_bh_male_human_02:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_bh_male_human_02, "object/mobile/dressed_bh_male_human_02.iff")
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
--
--[[ SkillsAdvisor Singleton ]]--
--
local SkillsAdvisor_Manager = ZO_CallbackObject:Subclass()
function SkillsAdvisor_Manager:New(...)
ZO_SKILLS_ADVISOR_SINGLETON = ZO_CallbackObject.New(self)
ZO_SKILLS_ADVISOR_SINGLETON:Initialize(...) -- ZO_CallbackObject does not have an initialize function
return ZO_SKILLS_ADVISOR_SINGLETON
end
function SkillsAdvisor_Manager:Initialize()
self.skillBuilds = {}
self.availableAbilityList = {}
self.purchasedAbilityList = {}
self.numSkillBuildIndicies = 0
self.numAvailableSkillBuilds = 0
self.advancedSkillBuildData =
{
name = GetString(SI_SKILLS_ADVISOR_ADVANCED_PLAYER_NAME),
description = GetString(SI_SKILLS_ADVISOR_ADVANCED_PLAYER_DESCRIPTION),
isTank = false,
isHealer = false,
isDPS = false,
skillAbilities = {},
}
local function UpdateSkillBuildData()
self:UpdateSkillBuildData()
end
local function RefreshVisibleAbilityLists()
local BROADCAST = true
self:RefreshVisibleAbilityLists(BROADCAST)
end
SKILLS_DATA_MANAGER:RegisterCallback("FullSystemUpdated", UpdateSkillBuildData)
SKILLS_DATA_MANAGER:RegisterCallback("SkillLineRankUpdated", RefreshVisibleAbilityLists)
SKILL_POINT_ALLOCATION_MANAGER:RegisterCallback("OnSkillsCleared", RefreshVisibleAbilityLists)
SKILL_POINT_ALLOCATION_MANAGER:RegisterCallback("PurchasedChanged", RefreshVisibleAbilityLists)
SKILL_POINT_ALLOCATION_MANAGER:RegisterCallback("SkillProgressionKeyChanged", RefreshVisibleAbilityLists)
SKILLS_AND_ACTION_BAR_MANAGER:RegisterCallback("SkillPointAllocationModeChanged", RefreshVisibleAbilityLists)
SKILLS_AND_ACTION_BAR_MANAGER:RegisterCallback("RespecStateReset", RefreshVisibleAbilityLists)
EVENT_MANAGER:RegisterForEvent("SkillsAdvisor_Manager", EVENT_SKILL_BUILD_SELECTION_UPDATED, function(eventId, ...) self:OnBuildSelectionUpdated(...) end)
--TODO: Support def changes
self:UpdateSkillBuildData()
end
function SkillsAdvisor_Manager:UpdateSkillBuildData()
if not SKILLS_DATA_MANAGER:IsDataReady() then
--If we don't have skills data, the rest of this is pretty useless, so wait until the data becomes ready
return
end
self.numAvailableSkillBuilds = GetNumAvailableSkillBuilds()
self.isAdvancedMode = IsSkillBuildAdvancedMode()
local selectedSkillBuildId = GetSkillBuildId()
if self.isAdvancedMode or selectedSkillBuildId <= 0 then
selectedSkillBuildId = nil
end
self.selectedSkillBuildId = selectedSkillBuildId
self.selectedSkillBuildIndex = nil
for skillBuildIndex = 1, self.numAvailableSkillBuilds do
local skillBuildId = GetAvailableSkillBuildIdByIndex(skillBuildIndex)
local oldSkillBuild = self.skillBuilds[skillBuildIndex]
-- Builds don't change, so we only need to load when IDs are different
if oldSkillBuild == nil or oldSkillBuild.id ~= skillBuildId then
local name, description, isTank, isHealer, isDPS = GetSkillBuildInfo(skillBuildId)
self.skillBuilds[skillBuildIndex] =
{
id = skillBuildId,
index = skillBuildIndex,
name = zo_strformat(SI_SKILLS_ADVISOR_SKILL_BUILD_NAME, name),
description = zo_strformat(SI_SKILLS_ADVISOR_SKILL_BUILD_DESCRIPTION, description),
isTank = isTank,
isHealer = isHealer,
isDPS = isDPS,
skillAbilities = {},
}
end
if skillBuildId == selectedSkillBuildId then
self.selectedSkillBuildIndex = skillBuildIndex
end
end
self.numSkillBuildIndicies = self.numAvailableSkillBuilds + 1
self.skillBuilds[self.numSkillBuildIndicies] = self.advancedSkillBuildData
self.advancedSkillBuildData.index = self.numSkillBuildIndicies
-- Remove remaining stale entries, if any
for i = self.numSkillBuildIndicies + 1, #self.skillBuilds do
self.skillBuilds[i] = nil
end
-- Only get SkillBuild Data for currently selected SkillBuild
if self.selectedSkillBuildIndex ~= nil then
local skillAbilities = self.skillBuilds[self.selectedSkillBuildIndex].skillAbilities
ZO_ClearNumericallyIndexedTable(skillAbilities)
for skillBuildAbilityIndex = 1, GetNumSkillBuildAbilities(selectedSkillBuildId) do
local skillProgressionData = self:GetSkillProgressionData(selectedSkillBuildId, skillBuildAbilityIndex)
if skillProgressionData then
table.insert(skillAbilities, skillProgressionData)
end
end
end
local DONT_BROADCAST = false
self:RefreshVisibleAbilityLists(DONT_BROADCAST)
self:FireCallbacks("OnSkillsAdvisorDataUpdated")
end
function SkillsAdvisor_Manager:GetSkillProgressionData(skillBuildId, skillBuildAbilityIndex)
local skillType, skillLineIndex, skillIndex, _, skillBuildMorphChoice, skillBuildRank = GetSkillBuildEntryInfo(skillBuildId, skillBuildAbilityIndex)
local skillData = SKILLS_DATA_MANAGER:GetSkillDataByIndices(skillType, skillLineIndex, skillIndex)
if not skillData then
-- ESO-566272 / ESO-581396: We added logging but it didn't really help us narrow down why this can happen.
-- Best guess is a timing issue between getting the skills info and the actual C++ progression data populated.
-- Removed the logging that was here because it was flooding our reports for no real benefit.
-- TODO: A refactor to separate progression from static data would probably solve this, but that's not going to be something we'll do anytime soon
return nil
end
local skillProgressionData = skillData:IsPassive() and skillData:GetRankData(skillBuildRank) or skillData:GetMorphData(skillBuildMorphChoice)
return skillProgressionData
end
do
local ADVANCED_MODE_SELECTED = true
local SKILL_BUILD_SELECTED = false
function SkillsAdvisor_Manager:OnSkillBuildSelected(skillBuildIndex)
if skillBuildIndex == self.numSkillBuildIndicies then
SelectSkillBuild(0, ADVANCED_MODE_SELECTED)
else
SelectSkillBuild(self.skillBuilds[skillBuildIndex].id, SKILL_BUILD_SELECTED)
end
end
end
function SkillsAdvisor_Manager:OnRequestSelectSkillLine()
self:FireCallbacks("OnRequestSelectSkillLine")
end
function SkillsAdvisor_Manager:OnBuildSelectionUpdated()
self:UpdateSkillBuildData()
self:FireCallbacks("OnSelectedSkillBuildUpdated")
end
function SkillsAdvisor_Manager:IsAdvancedModeSelected()
return self.isAdvancedMode
end
function SkillsAdvisor_Manager:GetNumSkillBuildOptions()
return self.numSkillBuildIndicies
end
function SkillsAdvisor_Manager:GetAvailableSkillBuildByIndex(index)
return self.skillBuilds[index]
end
function SkillsAdvisor_Manager:GetAvailableSkillBuildById(skillBuildId, getAdvancedIfNoId)
if skillBuildId or getAdvancedIfNoId then
for _, data in ipairs(self.skillBuilds) do
if data.id == skillBuildId then
return data
end
end
end
return nil
end
function SkillsAdvisor_Manager:GetSelectedSkillBuildId()
return self.selectedSkillBuildId
end
function SkillsAdvisor_Manager:GetSelectedSkillBuildIndex()
local selectedSkillBuild = self:GetAvailableSkillBuildById(self.selectedSkillBuildId, self:IsAdvancedModeSelected())
if selectedSkillBuild then
return selectedSkillBuild.index
else
return nil
end
end
function SkillsAdvisor_Manager:GetSkillBuildRoleLinesById(skillBuildId)
local skillBuild = self:GetAvailableSkillBuildById(skillBuildId)
local results = {}
if skillBuild then
local selectedRoles = {}
if skillBuild.isDPS then
table.insert(selectedRoles, LFG_ROLE_DPS)
end
if skillBuild.isHealer then
table.insert(selectedRoles, LFG_ROLE_HEAL)
end
if skillBuild.isTank then
table.insert(selectedRoles, LFG_ROLE_TANK)
end
if #selectedRoles == 1 then
local text = zo_strformat(SI_TOOLTIP_ITEM_ROLE, GetString("SI_LFGROLE", selectedRoles[1]), zo_iconFormat(GetRoleIcon(selectedRoles[1]), "100%", "100%"))
table.insert(results, zo_strformat(SI_TOOLTIP_ITEM_ROLE_FORMAT, text))
elseif #selectedRoles > 1 then
table.insert(results, GetString(SI_TOOLTIP_ITEM_ROLES_FORMAT))
for i, role in ipairs(selectedRoles) do
local text = zo_strformat(SI_TOOLTIP_ITEM_ROLE, GetString("SI_LFGROLE", role), zo_iconFormat(GetRoleIcon(role), "100%", "100%"))
table.insert(results, text)
end
end
end
return results
end
function SkillsAdvisor_Manager:GetAvailableAbilityList()
return self.availableAbilityList
end
function SkillsAdvisor_Manager:GetPurchasedAbilityList()
return self.purchasedAbilityList
end
function SkillsAdvisor_Manager:RefreshVisibleAbilityLists(broadcast)
ZO_ClearNumericallyIndexedTable(self.availableAbilityList)
ZO_ClearNumericallyIndexedTable(self.purchasedAbilityList)
if self.selectedSkillBuildId ~= nil then
local skillBuild = self:GetAvailableSkillBuildById(self.selectedSkillBuildId)
if skillBuild ~= nil then
local suggestionLimit = GetSkillsAdvisorSuggestionLimit()
local firstLockedAbilityAtLimit
for _, skillProgressionData in ipairs(skillBuild.skillAbilities) do
local skillData = skillProgressionData:GetSkillData()
local skillPointAllocator = skillData:GetPointAllocator()
local isUnlocked = skillProgressionData:IsUnlocked()
if skillPointAllocator:IsPurchased() then
if skillData:IsPassive() then
local entryRank = skillProgressionData:GetRank()
local allocatedRank = skillPointAllocator:GetRank()
if allocatedRank >= entryRank then
table.insert(self.purchasedAbilityList, skillProgressionData)
elseif allocatedRank + 1 == entryRank then
-- This data is the next rank to purchased
if #self.availableAbilityList < suggestionLimit then
if #self.availableAbilityList < suggestionLimit - 1 or isUnlocked then
table.insert(self.availableAbilityList, skillProgressionData)
elseif firstLockedAbilityAtLimit == nil then
firstLockedAbilityAtLimit = skillProgressionData
end
end
end
else
local entryMorphSlot = skillProgressionData:GetMorphSlot()
local allocatedMorphSlot = skillPointAllocator:GetMorphSlot()
if skillProgressionData:IsBase() or entryMorphSlot == allocatedMorphSlot then
table.insert(self.purchasedAbilityList, skillProgressionData)
elseif #self.availableAbilityList < suggestionLimit then
if allocatedMorphSlot == MORPH_SLOT_BASE then
-- If we're currently at base, any advised morph is acceptable to display
if #self.availableAbilityList < suggestionLimit - 1 or isUnlocked then
table.insert(self.availableAbilityList, skillProgressionData)
elseif firstLockedAbilityAtLimit == nil then
firstLockedAbilityAtLimit = skillProgressionData
end
else
-- If we've already morphed, only continue to show this morph as advised if the other morph is NOT advised
local siblingMorphData = skillProgressionData:GetSiblingMorphData()
if not siblingMorphData:IsAdvised() then
if #self.availableAbilityList < suggestionLimit - 1 or isUnlocked then
table.insert(self.availableAbilityList, skillProgressionData)
elseif firstLockedAbilityAtLimit == nil then
firstLockedAbilityAtLimit = skillProgressionData
end
end
end
end
end
elseif #self.availableAbilityList < suggestionLimit then
if #self.availableAbilityList < suggestionLimit - 1 or isUnlocked then
if skillData:IsPassive() then
if skillProgressionData:GetRank() == 1 then
table.insert(self.availableAbilityList, skillProgressionData)
end
else
if skillProgressionData:IsBase() then
table.insert(self.availableAbilityList, skillProgressionData)
end
end
elseif firstLockedAbilityAtLimit == nil then
firstLockedAbilityAtLimit = skillProgressionData
end
end
end
if #self.availableAbilityList <= suggestionLimit - 1 and firstLockedAbilityAtLimit then
table.insert(self.availableAbilityList, firstLockedAbilityAtLimit)
end
end
end
if broadcast then
self:FireCallbacks("RefreshVisibleAbilityLists")
end
end
function SkillsAdvisor_Manager:IsSkillDataInSelectedBuild(skillData)
local skillType, skillLineIndex, skillIndex = skillData:GetIndices()
local skillProgressionData
if skillData:IsPassive() then
skillProgressionData = skillData:GetRankData(1)
else
skillProgressionData = skillData:GetMorphData(MORPH_SLOT_BASE)
end
return self:IsSkillProgressionDataInSelectedBuild(skillProgressionData)
end
function SkillsAdvisor_Manager:IsSkillProgressionDataInSelectedBuild(skillProgressionData)
if self.selectedSkillBuildIndex ~= nil then
local skillAbilities = self.skillBuilds[self.selectedSkillBuildIndex].skillAbilities
for _, skillBuildProgressionData in ipairs(skillAbilities) do
if skillBuildProgressionData == skillProgressionData then
return true
end
end
end
return false
end
function SkillsAdvisor_Manager:GetValidatedRankIndex(rankIndex)
if not rankIndex or rankIndex == 0 then
return 1
else
return rankIndex
end
end
function SkillsAdvisor_Manager:SetupKeyboardSkillBuildTooltip(data)
if data then
local buildTypeTable = ZO_SKILLS_ADVISOR_SINGLETON:GetSkillBuildRoleLinesById(data.id)
GameTooltip:AddLine(data.name, "ZoFontHeader", ZO_SELECTED_TEXT:UnpackRGBA())
ZO_Tooltip_AddDivider(GameTooltip)
for i, type in ipairs(buildTypeTable) do
GameTooltip:AddLine(type, "", ZO_SELECTED_TEXT:UnpackRGBA())
end
GameTooltip:AddLine(data.description, "", ZO_NORMAL_TEXT:UnpackRGBA())
if GetDefaultSkillBuildId() == data.id then
GameTooltip:AddLine(GetString(SI_SKILLS_ADVISOR_SKILL_BUILD_NEW_PLAYER), "", ZO_SUCCEEDED_TEXT:UnpackRGBA())
end
end
end
SkillsAdvisor_Manager:New()
|
-----------------------------------
-- Ability: Innin
-- Reduces enmity and impairs evasion. Grants a bonus to accuracy, critical hit rate, and ninjutsu damage when striking target from behind.
-- Obtained: Ninja Level 40
-- Recast Time: 3:00
-- Duration: 5:00
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
-----------------------------------
function onAbilityCheck(player, target, ability)
return 0, 0
end
function onUseAbility(player, target, ability)
target:delStatusEffect(tpz.effect.INNIN)
target:delStatusEffect(tpz.effect.YONIN)
target:addStatusEffect(tpz.effect.INNIN, 30, 15, 300, 0, 20)
end
|
-- The bio reactor was copied from the Bio Industries mod, who copied it from the Tree Mod
data:extend({
{
type = "item",
name = "biotech-biosolarpanel",
icon = "__BioTech__/graphics/icons/panel-1.png",
flags = {"goes-to-quickbar"},
subgroup = "biotech-equipment",
order = "c[solar]",
place_result = "biotech-biosolarpanel",
stack_size = 64
},
{
type = "item",
name = "biotech-biosolarpanel-2",
icon = "__BioTech__/graphics/icons/panel-2.png",
flags = {"goes-to-quickbar"},
subgroup = "biotech-equipment",
order = "c[solar]",
place_result = "biotech-biosolarpanel-2",
stack_size = 64
},
{
type = "item",
name = "biotech-biosolarpanel-3",
icon = "__BioTech__/graphics/icons/panel-3.png",
flags = {"goes-to-quickbar"},
subgroup = "biotech-equipment",
order = "c[solar]",
place_result = "biotech-biosolarpanel-3",
stack_size = 64
},
{
type = "fluid",
name = "biotech-sugar-solution",
default_temperature = 25,
max_temperature = 95,
heat_capacity = "1KJ",
fuel_value = "6MJ",
base_color = {r=0.8, g=1.0, b=1.0},
flow_color = {r=1.00, g=1.0, b=1.0},
icon = "__BioTech__/graphics/icons/liquid-sugar-solution.png",
subgroup = "biotech-products",
order = "a[fluid]",
pressure_to_speed_ratio = 0.4,
flow_to_energy_ratio = 0.59,
},
{
type = "item",
name = "biotech-biosolarpanel-pole",
icon = "__BioTech__/graphics/icons/big-wooden-pole.png",
flags = {"goes-to-quickbar", "hidden"},
subgroup = "biotech-equipment",
place_result = "biotech-biosolarpanel-pole",
stack_size = 50
},
{
type = "item",
name = "biotech-biosolarpanel-solarpanel",
icon = "__base__/graphics/icons/solar-panel.png",
flags = {"goes-to-quickbar", "hidden"},
subgroup = "biotech-equipment",
place_result = "biotech-biosolarpanel-solarpanel",
stack_size = 50
},
})
|
local cjson = require "cjson"
require "init.lua_func_ex"
local _M = {}
_M._VERSION = '0.01'
local mt = { __index = _M }
function _M.new()
return setmetatable({}, mt)
end
--[[
-- 获取http get/post 请求参数
--]]
function _M.getArgs()
-- local request_method = ngx.var.request_method
local getArgs = {}
local postArgs = {}
-- if "GET" == request_method then
getArgs = ngx.req.get_uri_args()
-- 参数获取
-- elseif "POST" == request_method then
ngx.req.read_body()
local postTempArgs = ngx.req.get_post_args()
if postTempArgs then
for k, v in pairs(postTempArgs) do
postArgs[k] = v
end
end
-- end
if not getArgs then
getArgs = {}
end
table.merge(getArgs,postArgs)
return getArgs
end
--[[
专门取URI地址内的参数
--]]
function _M.getUriArgs()
local args = nil
args = ngx.req.get_uri_args()
return args
end
local function explode ( _str,seperator )
local pos, arr = 0, {}
for st, sp in function() return string.find( _str, seperator, pos, true ) end do
table.insert( arr, string.sub( _str, pos, st-1 ) )
pos = sp + 1
end
table.insert( arr, string.sub( _str, pos ) )
return arr
end
local args = {}
local file_args = {}
local is_have_file_param = false
--[[
当body有文件时使用获取参数接口
--]]
function _M.init_form_args()
local receive_headers = ngx.req.get_headers()
local request_method = ngx.var.request_method
if "GET" == request_method then
args = ngx.req.get_uri_args()
elseif "POST" == request_method then
ngx.req.read_body()
if string.sub(receive_headers["content-type"],1,20) == "multipart/form-data;" then--判断是否是multipart/form-data类型的表单
is_have_file_param = true
content_type = receive_headers["content-type"]
body_data = ngx.req.get_body_data()--body_data可是符合http协议的请求体,不是普通的字符串
--请求体的size大于nginx配置里的client_body_buffer_size,则会导致请求体被缓冲到磁盘临时文件里,client_body_buffer_size默认是8k或者16k
if not body_data then
local datafile = ngx.req.get_body_file()
if not datafile then
error_code = 1
error_msg = "no request body found"
else
local fh, err = io.open(datafile, "r")
if not fh then
error_code = 2
error_msg = "failed to open " .. tostring(datafile) .. "for reading: " .. tostring(err)
else
fh:seek("set")
body_data = fh:read("*a")
fh:close()
if body_data == "" then
error_code = 3
error_msg = "request body is empty"
end
end
end
end
local new_body_data = {}
--确保取到请求体的数据
if not error_code then
local boundary = "--" .. string.sub(receive_headers["content-type"],31)
local body_data_table = explode(tostring(body_data),boundary)
local first_string = table.remove(body_data_table,1)
local last_string = table.remove(body_data_table)
for i,v in ipairs(body_data_table) do
local start_pos,end_pos,capture,capture2 = string.find(v,'Content%-Disposition: form%-data; name="(.+)"; filename="(.*)"')
if not start_pos then--普通参数
local t = explode(v,"\r\n\r\n")
local temp_param_name = string.sub(t[1],41,-2)
local temp_param_value = string.sub(t[2],1,-3)
args[temp_param_name] = temp_param_value
else--文件类型的参数,capture是参数名称,capture2是文件名
file_args[capture] = capture2
table.insert(new_body_data,v)
end
end
table.insert(new_body_data,1,first_string)
table.insert(new_body_data,last_string)
--去掉app_key,app_secret等几个参数,把业务级别的参数传给内部的API
body_data = table.concat(new_body_data,boundary)--body_data可是符合http协议的请求体,不是普通的字符串
end
else
args = ngx.req.get_post_args()
end
end
end
return _M
|
local validWeaponIDs = {
1, 2, 3, 4, 5, 6, 7, 8, 9,
22, 23, 24,
25, 26, 27,
28, 29, 32,
30, 31,
33, 34,
35, 36, 37, 38,
16, 17, 18, 39,
41, 42, 43,
10, 11, 12, 14, 15,
44, 45, 46
}
function getValidWeaponIDs()
return table.copy(validWeaponIDs)
end
function isValidWeaponID(id)
if not scheck("n") then return false end
return table.index(validWeaponIDs, id) and true or false
end
function getWeaponIDFromPartialName(partialName)
if not scheck("s") then return false end
local id = getWeaponIDFromName(partialName)
if id then return id end
partialName = utf8.lower(partialName)
for i, id in ipairs(validWeaponIDs) do
if utf8.find(utf8.lower(getWeaponNameFromID(id)), partialName, 1, true) then return id end
end
return nil
end
|
local RPTAGS = RPTAGS;
RPTAGS.queue:WaitUntil("after UTILS_LOCALE",
function(self, event, ...)
local locUtils = RPTAGS.utils.locale;
local loc = locUtils.loc;
local function getTagDescription(tag)
return loc("TAG_" .. tag .. "_DESC");
end;
local function chooseDescInstead(tag)
local hash =
{ ["rp:npc"] = true,
["rp:ooc"] = true,
["rp:ic"] = true,
};
return tag:match("icon")
or tag:match("color")
or tag:match("^rp:%a$")
or hash[tag]
or not tag:match("rp:")
end;
local function getTagLabel(tag)
if chooseDescInstead(tag)
then return getTagDescription(tag)
else return loc("TAG_" .. tag .. "_LABEL")
end;
end;
local function getTagLabelColon()
if chooseDescInstead(tag)
then return ""
else return loc("TAG_" .. tag .. "_LABEL") .. ": "
end;
end;
locUtils.tagLabel = getTagLabel;
locUtils.tagDesc = getTagDescription;
locUtils.tagLabelColon = getTagLabelColon;
end);
RPTAGS.queue:WaitUntil("UTILS_TAGS",
function(self, event, ...)
-- RPQ ------------------------------------------------------------------------------------------------------------------------
local split = RPTAGS.utils.text.split;
local sizeTrim = RPTAGS.utils.text.sizeTrim;
local Config = RPTAGS.utils.config;
local function addAllTags()
local source = RPTAGS.CONST.TAG_DATA;
-- As per Data\tags.lua, the source consists of a list of tag groups
for _, group in ipairs(source)
do RPTAGS.utils.tags.addTagGroup(group)
end;
end;
local function addTagGroup(groupData)
-- each tag group has this structure:
-- { key = "KEY", -- not localized
-- title = "Human readable title (localized)",
-- help = "Help for the group (localized)",
-- tags = { tag, tag, tag, tag }
-- external = false, -- boolean for whether the tag is one of ours; for the editor
-- }
for _, tag in ipairs(groupData.tags)
do RPTAGS.utils.tags.addTag(tag, groupData)
end;
end;
local function addTag(tag, group)
-- Each tag has this structure:
-- { name = "rp:tag", -- not localized
-- alias = { alias, alias, alias },
-- desc = "Human readable description (localized)",
-- method = function(u) return "Tag Value" end, -- the method for getting the tag
-- size = false, -- boolean for whether or not the tag can take sizes
-- label = "Human readable label (localized), -- nil if the tag has no labels
-- external = false, -- same as group.external
-- events = "EXTRA_EVENTS",
-- },
--
-- We need to send the data to registerTag, which expects the following:
--
-- registerTag("rp:tag", method, "EXTRA_EVENTS");
-- ^name ^method ^events
RPTAGS.cache.help = RPTAGS.cache.help or {};
RPTAGS.cache.help.tagIndex = RPTAGS.cache.help.tagIndex or {};
local registerTag = RPTAGS.utils.tags.registerTag;
local registerTagAndSizeVariants = RPTAGS.utils.tags.sizeVariants;
local registerColorTag = RPTAGS.utils.tags.colorTag;
local registerLabel = RPTAGS.utils.tags.registerLabel;
if tag.external or group.external
then -- if it's an external source then skip
elseif tag.title
then -- it's just a header for the documentation
else -- first we make the core tag
local tagMethod, tagNames, prefix, suffix = tag.method, { tag.name }, "", "";
if RPTAGS.CONST.UNSUP[tag.name]
then tagMethod = RPTAGS.utils.text[RPTAGS.CONST.UNSUP[tag.name]];
end;
if tag.alias
then for _, aka in ipairs(tag.alias) do table.insert(tagNames, aka) end;
end;
-- time to build our tags!
for _, tname in ipairs(tagNames)
do if tag.size -- do we have size variants?
then registerTagAndSizeVariants(tname, tagMethod, tag.extraEvents);
elseif tag.color
then registerColorTag( tname, tagMethod, tag.extraEvents);
else registerTag( tname, tagMethod, tag.extraEvents);
end;
if tag.label
then RPTAGS.utils.tags.registerLabel(tname, tagMethod, tag.extraEvents, tag.label);
end;
RPTAGS.cache.help.tagIndex[tag.name] = "opt://help/tags/" .. group.key;
end;
end;
return tag, group; -- pass these values through in case a module needs it
-- and that tag is done!
end;
local function registerTagLabel(tagName, tagMethod, tagExtraEvents, label)
local split = RPTAGS.utils.text.split;
local lab = split(label, "|");
local prefix, suffix = lab[1] or "", lab[2] or "";
RPTAGS.utils.tags.registerTag(
tagName .. "-label",
function(...)
local result = tagMethod( ... );
if result and result ~= ""
then return prefix .. ": " .. result .. suffix;
else return result
end;
end,
tagExtraEvents
);
end;
-- this will be extended by UF-specific functions
local function registerTag( ... ) return ... end;
local function refreshFrame( ... ) return ... end;
local function refreshAll( ... ) return ... end;
local function registerTagSizeVariants( ... ) return ... end;
local function registerColorTag( ... ) return ... end;
local function evalTagString(tagstr, unit, realUnit, use_oUF) -- adapted from oUF/elements/tags.lua
if not tagstr then return "" end;
local oUF = use_oUF or RPTAGS.oUF;
local methods = oUF.Tags.Methods;
local TAG_PATTERN = '%[..-%]+'
local funcResults = {};
local function getBracketData(tag) -- full tag syntax: '[prefix$>tag-name<$suffix(a,r,g,s)]'
local suffixEnd = (tag:match('()%(') or -1) - 1
local prefixEnd, prefixOffset = tag:match('()%$>'), 1
if not prefixEnd
then prefixEnd = 1
else prefixEnd = prefixEnd - 1
prefixOffset = 3
end;
local suffixStart, suffixOffset = tag:match('%<$()', prefixEnd), 1
if not suffixStart
then suffixStart = suffixEnd + 1
else suffixOffset = 3
end;
return
tag:sub(prefixEnd + prefixOffset, suffixStart - suffixOffset),
prefixEnd,
suffixStart,
suffixEnd,
tag:match('%((.-)%)')
end
local func;
local format, numTags = tagstr:gsub('%%', '%%%%'):gsub(TAG_PATTERN, '%%s')
local args = {}
for bracket in tagstr:gmatch(TAG_PATTERN)
do local tagFunc;
local tagName, prefixEnd, suffixStart, suffixEnd, customArgs = getBracketData(bracket)
local tag = methods[tagName]
if tag
then if prefixEnd ~= 1 and suffixStart - suffixEnd ~= 1
then local prefix = bracket:sub(2, prefixEnd)
local suffix = bracket:sub(suffixStart, suffixEnd)
tagFunc =
function(unit, realUnit)
local str
if customArgs
then str = tag(unit, realUnit, strsplit(',', customArgs))
else str = tag(unit, realUnit)
end
if str and str ~= '' then return prefix .. str .. suffix end
end
elseif prefixEnd ~= 1
then local prefix = bracket:sub(2, prefixEnd)
tagFunc =
function(unit, realUnit)
local str
if customArgs
then str = tag(unit, realUnit, strsplit(',', customArgs))
else str = tag(unit, realUnit)
end
if str and str ~= '' then return prefix .. str end
end
elseif suffixStart - suffixEnd ~= 1
then local suffix = bracket:sub(suffixStart, -2)
tagFunc =
function(unit, realUnit)
local str
if customArgs
then str = tag(unit, realUnit, strsplit(',', customArgs))
else str = tag(unit, realUnit)
end
if str and str ~= '' then return str .. suffix end
end
else tagFunc =
function(unit, realUnit)
local str
if customArgs
then str = tag(unit, realUnit, strsplit(',', customArgs))
else str = tag(unit, realUnit)
end
if str and str ~= '' then return str end
end
end -- if (lotsa stuff)
end -- if tag
if tagFunc
then table.insert(args, tagFunc)
else table.insert(args, function() return "[" .. tagName .. "]" end);
end
end -- for
for i, f in next, args do funcResults[i] = f(unit, realUnit or unit) or '' end
return string.format(format, unpack(funcResults));
end; -- function evalTagString
local function evalTagStringAsPlayer(tagStr, use_oUF)
return evalTagString(tagStr, "player", "player", use_oUF);
end;
local function tagExists(tag, oUF)
oUF = oUF or RPTAGS.oUF;
return tag and oUF.Tags.Methods[tag] and true or false;
end;
RPTAGS.utils.tags = RPTAGS.utils.tags or {};
RPTAGS.utils.tags.exists = tagExists;
RPTAGS.utils.tags.eval = evalTagString;
RPTAGS.utils.tags.evalPlayer = evalTagStringAsPlayer;
RPTAGS.utils.tags.registerTag = registerTag;
RPTAGS.utils.tags.sizeVariants = registerTagSizeVariants;
RPTAGS.utils.tags.colorTag = registerColorTag;
RPTAGS.utils.tags.registerLabel = registerTagLabel;
RPTAGS.utils.tags.addTag = addTag;
RPTAGS.utils.tags.addTagGroup = addTagGroup;
RPTAGS.utils.tags.addAllTags = addAllTags;
-- RPQ -----------------------------------------------------------------------------------------------------------------------
end);
|
return require('lib.oop.generated.button')
|
include ( "panel/animation.lua" )
include ( "panel/dragdrop.lua" )
include ( "panel/selections.lua" )
include ( "panel/scriptedpanels.lua" )
local meta = FindMetaTable( "Panel" )
AccessorFunc( meta, "m_strCookieName", "CookieName" )
meta.SetFGColorEx = meta.SetFGColor
meta.SetBGColorEx = meta.SetBGColor
--[[---------------------------------------------------------
Name: SetFGColor
Desc: Override to make it possible to pass Color's
-----------------------------------------------------------]]
function meta:SetFGColor( r, g, b, a )
if ( istable( r ) ) then
return self:SetFGColorEx( r.r, r.g, r.b, r.a )
end
return self:SetFGColorEx( r, g, b, a )
end
--[[---------------------------------------------------------
Name: SetBGColor
Desc: Override to make it possible to pass Color's
-----------------------------------------------------------]]
function meta:SetBGColor( r, g, b, a )
if ( istable( r ) ) then
return self:SetBGColorEx( r.r, r.g, r.b, r.a )
end
return self:SetBGColorEx( r, g, b, a )
end
--[[---------------------------------------------------------
Name: SetHeight
-----------------------------------------------------------]]
function meta:SetHeight( h )
self:SetSize( self:GetWide(), h )
end
meta.SetTall = meta.SetHeight
--[[---------------------------------------------------------
Name: SetHeight
-----------------------------------------------------------]]
function meta:SetWidth( w )
self:SetSize( w, self:GetTall() )
end
meta.SetWide = meta.SetWidth
--[[---------------------------------------------------------
Name: StretchToParent (borders)
-----------------------------------------------------------]]
function meta:StretchToParent( l, u, r, d )
local w, h = self:GetParent():GetSize()
if ( l != nil ) then
self.x = l
end
if ( u != nil ) then
self.y = u
end
if ( r != nil ) then
self:SetWide( w - self.x - r )
end
if ( d != nil ) then
self:SetTall( h - self.y - d )
end
--self:SetPos( l, u )
--self:SetSize( w - (r + l), h - (d + u) )
end
--[[---------------------------------------------------------
Name: CopyHeight
-----------------------------------------------------------]]
function meta:CopyHeight( pnl )
self:SetTall( pnl:GetTall() )
end
--[[---------------------------------------------------------
Name: CopyWidth
-----------------------------------------------------------]]
function meta:CopyWidth( pnl )
self:SetWide( pnl:GetWide() )
end
--[[---------------------------------------------------------
Name: CopyPos
-----------------------------------------------------------]]
function meta:CopyPos( pnl )
self:SetPos( pnl:GetPos() )
end
--[[---------------------------------------------------------
Name: Align with the edge of the parent
-----------------------------------------------------------]]
function meta:AlignBottom( m ) m = m or 0; self:SetPos( self.x, self:GetParent():GetTall() - self:GetTall() - m ) end
function meta:AlignRight( m ) m = m or 0; self:SetPos( self:GetParent():GetWide() - self:GetWide() - m, self.y ) end
function meta:AlignTop( m ) m = m or 0; self:SetPos( self.x, m ) end
function meta:AlignLeft( m ) m = m or 0; self:SetPos( m, self.y ) end
--[[---------------------------------------------------------
Name: Move relative to another panel
-----------------------------------------------------------]]
function meta:MoveAbove( pnl, m ) m = m or 0; self:SetPos( self.x, pnl.y - self:GetTall() - m ) end
function meta:MoveBelow( pnl, m ) m = m or 0; self:SetPos( self.x, pnl.y + pnl:GetTall() + m ) end
function meta:MoveRightOf( pnl, m ) m = m or 0; self:SetPos( pnl.x + pnl:GetWide() + m, self.y ) end
function meta:MoveLeftOf( pnl, m ) m = m or 0; self:SetPos( pnl.x - self:GetWide() - m, self.y ) end
--[[---------------------------------------------------------
Name: StretchRightTo
-----------------------------------------------------------]]
function meta:StretchRightTo( pnl, m ) m = m or 0; self:SetWide( pnl.x - self.x - m ) end
function meta:StretchBottomTo( pnl, m ) m = m or 0; self:SetTall( pnl.y - self.y - m ) end
--[[---------------------------------------------------------
Name: CenterVertical
-----------------------------------------------------------]]
function meta:CenterVertical( fraction )
fraction = fraction or 0.5
self:SetPos( self.x, self:GetParent():GetTall() * fraction - self:GetTall() * 0.5 )
end
--[[---------------------------------------------------------
Name: CenterHorizontal
-----------------------------------------------------------]]
function meta:CenterHorizontal( fraction )
fraction = fraction or 0.5
self:SetPos( self:GetParent():GetWide() * fraction - self:GetWide() * 0.5, self.y )
end
--[[---------------------------------------------------------
Name: CenterHorizontal
-----------------------------------------------------------]]
function meta:Center()
self:CenterVertical()
self:CenterHorizontal()
end
--[[---------------------------------------------------------
Name: CopyBounds
-----------------------------------------------------------]]
function meta:CopyBounds( pnl )
local x, y, w, h = pnl:GetBounds()
self:SetPos( x, y )
self:SetSize( w, h )
end
--[[---------------------------------------------------------
Name: GetCookieNumber
-----------------------------------------------------------]]
function meta:SetCookieName( cookiename )
self.m_strCookieName = cookiename
-- If we have a loadcookies function, call it.
if ( self.LoadCookies ) then
self:LoadCookies()
self:InvalidateLayout()
end
end
--[[---------------------------------------------------------
Name: GetCookieNumber
-----------------------------------------------------------]]
function meta:GetCookieNumber( cookiename, default )
local name = self:GetCookieName()
if ( !name ) then return default end
return cookie.GetNumber( name.."."..cookiename, default )
end
--[[---------------------------------------------------------
Name: GetCookie
-----------------------------------------------------------]]
function meta:GetCookie( cookiename, default )
local name = self:GetCookieName()
if ( !name ) then return default end
return cookie.GetString( name.."."..cookiename, default )
end
--[[---------------------------------------------------------
Name: SetCookie
-----------------------------------------------------------]]
function meta:SetCookie( cookiename, value )
local name = self:GetCookieName()
if ( !name ) then return end
return cookie.Set( name.."."..cookiename, value )
end
--[[---------------------------------------------------------
Name: InvalidateParent
-----------------------------------------------------------]]
function meta:InvalidateParent( layoutnow )
local parent = self:GetParent()
if ( !parent ) then return end
if ( self.LayingOutParent ) then return end
self.LayingOutParent = true
parent:InvalidateLayout( layoutnow )
self.LayingOutParent = false
end
--[[---------------------------------------------------------
Name: PositionLabel
-----------------------------------------------------------]]
function meta:PositionLabel( LabelWidth, X, Y, Lbl, Control )
Lbl:SetWide( LabelWidth )
Lbl:SetPos( X, Y )
Control.y = Y
Control:MoveRightOf( Lbl, 0 )
return Y + math.max( Lbl:GetTall(), Control:GetTall() )
end
--[[---------------------------------------------------------
Name: SetTooltip
-----------------------------------------------------------]]
function meta:SetTooltip( tooltip )
self.strTooltipText = tooltip
end
meta.SetToolTip = meta.SetTooltip
--[[---------------------------------------------------------
Name: SetTooltipPanel
-----------------------------------------------------------]]
function meta:SetTooltipPanel( panel )
self.pnlTooltipPanel = panel
end
meta.SetToolTipPanel = meta.SetTooltipPanel
--[[---------------------------------------------------------
Name: SizeToContentsY (Only works on Labels)
-----------------------------------------------------------]]
function meta:SizeToContentsY( addval )
local w, h = self:GetContentSize()
if (!w || !h ) then return end
addval = addval or 0
self:SetTall( h )
end
--[[---------------------------------------------------------
Name: SizeToContentsX (Only works on Labels)
-----------------------------------------------------------]]
function meta:SizeToContentsX( addval )
local w, h = self:GetContentSize()
if (!w || !h) then return end
addval = addval or 0
self:SetWide( w + addval )
end
--[[---------------------------------------------------------
Name: SetSkin
-----------------------------------------------------------]]
function meta:SetSkin( strSkin )
if ( self.m_ForceSkinName == strSkin ) then return end
self.m_ForceSkinName = strSkin
self.m_iSkinIndex = nil
derma.RefreshSkins()
end
--[[---------------------------------------------------------
Name: GetSkin
-----------------------------------------------------------]]
function meta:GetSkin()
local skin = nil
if ( derma.SkinChangeIndex() == self.m_iSkinIndex ) then
skin = self.m_Skin
if ( skin ) then return skin end
end
-- We have a default skin
if ( !skin && self.m_ForceSkinName ) then
skin = derma.GetNamedSkin( self.m_ForceSkinName )
end
-- No skin, inherit from parent
local parent = self:GetParent()
if ( !skin && IsValid( parent ) ) then
skin = parent:GetSkin()
end
-- Parent had no skin, use default
if ( !skin) then
skin = derma.GetDefaultSkin()
end
-- Save skin details on us so we don't have to keep looking up
self.m_Skin = skin
self.m_iSkinIndex = derma.SkinChangeIndex()
self:InvalidateLayout( false )
return skin
end
--[[---------------------------------------------------------
Name: ToggleVisible
-----------------------------------------------------------]]
function meta:ToggleVisible()
self:SetVisible( !self:IsVisible() )
end
function meta:Distance( pnl )
if ( !IsValid( pnl ) ) then return 0 end
return self:DistanceFrom( pnl.x + pnl:GetWide() * 0.5, pnl.y + pnl:GetTall() * 0.5 )
end
function meta:DistanceFrom( x, y )
local x = self.x + self:GetWide() * 0.5 - x;
local y = self.y + self:GetTall() * 0.5 - y;
return math.sqrt( x * x + y *y )
end
--[[---------------------------------------------------------
Name: Retusn the child position on this panel. Even if its parented to children of children.
-----------------------------------------------------------]]
function meta:GetChildPosition( pnl )
local x = 0;
local y = 0;
while ( IsValid( pnl ) && pnl != self ) do
x = x + pnl.x
y = y + pnl.y
pnl = pnl:GetParent();
end
return x, y;
end
--[[---------------------------------------------------------
Name: Returns true if the panel is valid. This does not
check the type. If the passed object is anything other
than a panel or nil, this will error. (speed)
-----------------------------------------------------------]]
function ValidPanel( pnl )
if (!pnl) then return false end
return pnl:IsValid()
end
function meta:InvalidateChildren( bRecurse )
local children = self:GetChildren()
for k, v in pairs( children ) do
if ( bRecurse ) then
v:InvalidateChildren( true )
else
v:InvalidateChildren( false )
end
end
self:InvalidateLayout( true )
end
function meta:IsOurChild( pPanel )
if ( pPanel == self ) then return true end
local children = self:GetChildren()
for k, v in pairs( children ) do
if ( v:IsOurChild( pPanel ) ) then return true end
end
return false
end
function meta:CopyBase( pnl )
self:CopyBounds( pnl )
self:Dock( pnl:GetDock() )
// TODO. More.
end
function meta:Add( pnl )
if ( isstring( pnl ) ) then
local pnl = vgui.Create( pnl, self )
return pnl
end
if ( istable( pnl ) ) then
local pnl = vgui.CreateFromTable( pnl, self )
return pnl
end
pnl:SetParent( self )
return pnl
end
function meta:GetClosestChild( x, y )
local distance = 9999
local closest = nil
local children = self:GetChildren()
for k, v in pairs( children ) do
local dist = v:DistanceFrom( x, y )
if ( dist < distance ) then
distance = dist;
closest = v
end
end
return closest, distance
end
function meta:LocalCursorPos()
return self:ScreenToLocal( gui.MouseX(), gui.MouseY() )
end
function meta:MoveToAfter( pnl )
local children = self:GetParent():GetChildren()
-- remove us from the table
table.RemoveByValue( children, self )
-- find the key, where we want to be
local key = table.KeyFromValue( children, pnl )
if ( key ) then
-- insert us where we wanna be
table.insert( children, key+1, self )
else
return false;
end
for k, v in pairs( children ) do
v:SetZPos( k )
end
end
function meta:MoveToBefore( pnl )
local children = self:GetParent():GetChildren()
-- remove us from the table
table.RemoveByValue( children, self )
-- find the key, where we want to be
local key = table.KeyFromValue( children, pnl )
if ( key ) then
-- insert us where we wanna be
table.insert( children, key, self )
else
return false
end
for k, v in pairs( children ) do
v:SetZPos( k )
end
end
function meta:Clear()
for k, panel in pairs( self:GetChildren() ) do
panel:Remove()
end
end
function meta:IsHovered()
return vgui.GetHoveredPanel() == self
end
function meta:Show()
self:SetVisible( true )
end
function meta:Hide()
self:SetVisible( false )
end
function meta:IsChildHovered( iDepth )
local Hovered = vgui.GetHoveredPanel()
if ( !IsValid( Hovered ) ) then return false end
for i=1, iDepth do
Hovered = Hovered:GetParent()
if ( !IsValid( Hovered ) ) then return false end
if ( Hovered == self ) then return true end
end
return false
end
|
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
Clockwork was created by Conna Wiles (also known as kurozael.)
http://cloudsixteen.com/license/clockwork.html
--]]
DEFINE_BASECLASS("base_gmodentity");
ENT.Type = "anim";
ENT.Author = "kurozael";
ENT.PrintName = "Cash";
ENT.Spawnable = false;
ENT.AdminSpawnable = false;
ENT.UsableInVehicle = true;
-- Called when the data tables are setup.
function ENT:SetupDataTables()
self:DTVar("Int", 0, "Amount");
end;
|
--[[
The user registry is simply an association of a user to their command environment.
when a user first appears, they can be registered to have their environment created.
note that for players, this doesn't happen immediately but either on login,
or first use after gaining the correct privileges to use the /lua command.
see commands.lua and login.lua for details.
]]
local registry = {}
local util = {}
local execenv = dofile(_modpath.."execenv.lua")
local wp = minetest.get_worldpath()
--[[
gets an exec environment associated with an opaque ID object.
this could be e.g. a player ref or some some other identifier used to link players.
the implementation object (see user_ref.lua for a description)
allows the env to send textual data.
]]
-- if no env exists for that ID, call the factory to construct the user ref for it
-- (see user_ref.lua), then construct a new environment using that.
local msg_factory_fail = "user_registry get(): ID didn't exist and unable to construct new environment"
local get = function(id, factory)
assert(id ~= nil, "insanity condition: user_registry get() ID is nil!")
local reg = registry[id]
if not reg then
local impl = factory and factory(id) or nil
if not impl then error(msg_factory_fail) end
reg = execenv.new(impl, wp)
registry[id] = reg
end
return reg
end
util.get = get
local remove = function(id, expected)
if not registry[id] and expected then
local desc = tostring(id)
minetest.log("warning", "duplicate player env removal: " .. desc)
end
registry[id] = nil
end
util.remove = remove
return registry, util
|
local class = require('class')
local UIWidget = class:extend()
function UIWidget:init(x, y, w, h)
self.parent = nil
self.children = {}
self.x = x
self.y = y
self.w = w
self.h = h
self.focus = nil
self.transform = nil
self.background = nil
self._mouseactive = nil
if parent ~= nil then
parent:add(self)
end
end
function UIWidget:_reflow()
if self.parent == nil then return end
local didrew = false
if self.parent.w ~= nil and self.parent.w >= 0 then
didrew = true
if self.w == nil then self.w = self.parent.w - self.x
elseif self.w < 0 then self.w = self.parent.w + self.w - self.x
else didrew = false
end
end
local didreh = false
if self.parent.h ~= nil and self.parent.h >= 0 then
didreh = true
if self.h == nil then self.h = self.parent.h - self.y
elseif self.h < 0 then self.h = self.parent.h + self.h - self.y
else didreh = false
end
end
if didrew or didreh then
for i, child in ipairs(self.children) do
child:_reflow()
end
end
end
function UIWidget:add(child)
child.parent = self
child:_reflow()
table.insert(self.children, child)
return child
end
function UIWidget:do_update(dt)
self:update(dt)
for i, child in ipairs(self.children) do
child:do_update(dt)
end
end
function UIWidget:do_draw()
love.graphics.push('all')
if self.transform ~= nil then
love.graphics.applyTransform(self.transform)
else
love.graphics.translate(self.x, self.y)
end
self:draw()
for i, child in ipairs(self.children) do
child:do_draw()
end
love.graphics.pop()
end
function UIWidget:update(dt) end
function UIWidget:draw()
if self.background == nil then return end
if type(self.background.typeOf) == 'function' then
if self.background:typeOf('Texture') then
local bw, bh = self.background:getPixelDimensions()
local sx = 1
local sy = 1
local bx = 0
local by = 0
if self.w < bw then sx = self.w / bw
else bx = (self.w / 2) - (bw / 2)
end
if self.h < bh then sy = self.h / bh
else by = (self.h / 2) - (bh / 2)
end
love.graphics.draw(self.background, bx, by, 0, sx, sy)
elseif self.background:typeOf('Drawable') then
love.graphics.draw(self.background)
end
elseif type(self.background) == 'table' then
love.graphics.setColor(self.background)
love.graphics.rectangle('fill', 0, 0, self.w, self.h)
end
end
local function revpairs(t)
return function (s, var)
var = var - 1
if var == 0 then return nil end
return var, s[var]
end, t, #t + 1
end
function UIWidget:findchild(x, y, deep)
for i, child in revpairs(self.children) do
local rx = x - child.x
local ry = y - child.y
if rx >= 0 and rx < child.w and ry >= 0 and ry < child.h then
if deep then
return child:findchild(rx, ry)
else
return child, rx, ry
end
end
end
return self, x, y
end
function UIWidget:mousepressed(x, y, button, istouch, presses)
if self._mouseactive then return false end
self._mouseactive = button
local child, rx, ry = self:findchild(x, y)
self.focus = child
if child == self then
return false
else
return child:mousepressed(rx, ry, button, istouch, presses)
end
end
function UIWidget:mousereleased(x, y, button, istouch, presses)
if button ~= self._mouseactive then return false end
local child = self.focus
self.focus = nil
self._mouseactive = nil
if child == self then
return false
else
local rx = x - child.x
local ry = y - child.y
return child:mousereleased(rx, ry, button, istouch, presses)
end
end
function UIWidget:mousemoved(x, y, dx, dy, istouch)
local child = self.focus
if child == nil then
child = self:findchild(x, y)
end
if child == self then
return false
else
local rx = x - child.x
local ry = y - child.y
return child:mousemoved(rx, ry, dx, dy, istouch)
end
end
function UIWidget:wheelmoved(x, y, atx, aty)
local child = self.focus
if child == nil then
child, atx, aty = self:findchild(atx, aty)
end
if child == self then
return false
else
return child:wheelmoved(x, y, atx, aty)
end
end
return UIWidget
|
slot0 = class("WorldMediaCollectionSubLayer", import("view.base.BaseSubView"))
slot0.Ctor = function (slot0, slot1, ...)
slot0.super.Ctor(slot0, ...)
slot0.viewParent = slot1
slot0.buffer = setmetatable({}, {
__index = function (slot0, slot1)
return function (slot0, ...)
slot0:ActionInvoke(slot0.ActionInvoke, ...)
end
end,
__newindex = function ()
errorMsg("Cant write Data in ActionInvoke buffer")
end
})
end
slot0.SetActive = function (slot0, slot1)
if slot1 then
slot0:Show()
else
slot0:Hide()
end
end
slot0.OnDestroy = function (slot0)
if slot0.loader then
slot0.loader:Clear()
slot0.loader = nil
end
end
return slot0
|
BaseNpc_PersistDialogState(this, "{{Tale_ChildNode_Unused_Function}}")
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
self:SetModel("models/weapons/molotov3rd_zm.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:GetPhysicsObject():Wake()
self:SetAngles(Angle(math.random(0, 360), math.random(0, 360), math.random(0, 360)))
local fireTrail = ents.Create("env_fire_trail")
fireTrail:SetPos(self:GetPos())
fireTrail:SetParent(self)
fireTrail:Spawn()
fireTrail:Activate()
end
function ENT:PhysicsCollide(data, physObject)
if self.bRemove then return end
local contents = util.PointContents(self:GetPos())
if bit.band(contents, MASK_WATER) ~= 0 then
self.bRemove = true
return
end
local dmginfo = DamageInfo()
dmginfo:SetAttacker(self.Owner)
dmginfo:SetInflictor(self)
dmginfo:SetDamage(40)
dmginfo:SetDamagePosition(self:GetPos())
dmginfo:SetDamageType(DMG_BURN)
util.BlastDamageInfo(dmginfo, self:GetPos(), 128)
local effectdata = EffectData()
effectdata:SetOrigin(self:GetPos())
util.Effect("HelicopterMegaBomb", effectdata)
self:EmitSound("Grenade_Molotov.Detonate")
self:EmitSound("Grenade_Molotov.Detonate2")
self.bRemove = true
end
function ENT:Think()
if self.bRemove then
self:Remove()
end
end
function ENT:OnRemove()
local owner = self:GetOwner()
for _, v in pairs(ents.FindInSphere(self:GetPos(), 128)) do
if v:IsNPC() then
v:Ignite(100)
elseif v == owner then
v:Ignite(3)
end
end
for i = 1, 10 do
local fire = ents.Create("env_fire")
fire:SetPos(self:GetPos() +Vector(math.random(-80, 80), math.random(-80, 80), 0))
fire:SetKeyValue("health", 25)
fire:SetKeyValue("firesize", "60")
fire:SetKeyValue("fireattack", "2")
fire:SetKeyValue("damagescale", "4.0")
fire:SetKeyValue("StartDisabled", "0")
fire:SetKeyValue("firetype", "0" )
fire:SetKeyValue("spawnflags", "132")
fire:Spawn()
fire:Fire("StartFire", "", 0)
fire:SetOwner(owner)
if owner:IsPlayer() then
fire.OwnerTeam = owner:Team()
else
fire.OwnerTeam = TEAM_SURVIVOR
end
end
for i=1, 8 do
local sparks = ents.Create( "env_spark" )
sparks:SetPos( self:GetPos() + Vector( math.random( -40, 40 ), math.random( -40, 40 ), math.random( -40, 40 ) ) )
sparks:SetKeyValue( "MaxDelay", "0" )
sparks:SetKeyValue( "Magnitude", "2" )
sparks:SetKeyValue( "TrailLength", "3" )
sparks:SetKeyValue( "spawnflags", "0" )
sparks:Spawn()
sparks:Fire( "SparkOnce", "", 0 )
end
end
|
local func = require 'ldk.func'
describe("#func", function()
describe("compose", function()
it("should return the proper result", function()
local function f(x) return x + 1 end
local function g(x) return x * 10 end
local fg = func.compose(f, g)
assert.equal(11, fg(1))
assert.equal(101, fg(10))
end)
it("should handle function returning multiple values", function()
local function f(x, y) return x + y end
local function g(x) return x * 10, x end
local fg = func.compose(f, g)
assert.equal(11, fg(1))
end)
end)
describe("partial", function()
it("should return the proper result", function()
local f = function(x, y) return x + y end
local f1 = func.partial(1, f)
assert.equal(2, f1(1))
assert.equals(10, f1(9))
end)
end)
describe("curry", function()
it("should return the proper result", function()
local f = function(x, y) return x + y end
local curried = func.curry(f)
assert.equal(2, curried(1)(1))
assert.equals(10, curried(9)(1))
end)
end)
local function test_memoize(n, memoize, f, ...)
for _ = 1, n do
local call_count = 0
local mf = memoize(function(...)
call_count = call_count + 1
return f(...)
end)
assert.equal(0, call_count)
local fa, fb = f(...)
local mfa, mfb = mf(...)
assert.equal(fa, mfa)
assert.equal(fb, mfb)
assert.equal(1, call_count)
mf(...)
assert.equal(1, call_count)
end
end
describe("memoize0", function()
it("should cache the function result", function()
test_memoize(5, func.memoize0, function()
return true
end)
test_memoize(5, func.memoize0, function()
return true, 'true'
end)
test_memoize(5, func.memoize0, function()
return nil, true
end)
end)
end)
describe("memoize1", function()
it("should cache the function execution", function()
test_memoize(5, func.memoize1, function(x)
return x == nil
end)
test_memoize(5, func.memoize1, function(x)
return x
end, 1)
test_memoize(5, func.memoize1, function(x)
return x, x + 1
end, 1)
test_memoize(5, func.memoize1, function(x)
return nil, x * x
end, 1)
end)
end)
describe("memoize2", function()
it("should cache the function execution", function()
test_memoize(5, func.memoize2, function(x1, x2)
return x1 == nil and x2 == nil
end)
test_memoize(5, func.memoize2, function(x1, x2)
return x1 + x2
end, 7, 13)
test_memoize(5, func.memoize2, function(x1, x2)
return x1, x2
end, 7, 15)
test_memoize(5, func.memoize2, function(x1, x2)
return nil, x1 * x2
end, 7, 13)
end)
end)
describe("memoize3", function()
it("should cache the function execution", function()
test_memoize(5, func.memoize3, function(x1, x2, x3)
return x1 == nil and x2 == nil and x3 == nil
end)
test_memoize(5, func.memoize3, function(x1, x2, x3)
return x1 + x2, x3
end, 17, 13, 29)
test_memoize(5, func.memoize3, function(x1, x2, x3)
return x1, x2 + x3
end, 7, 15, 29)
test_memoize(5, func.memoize3, function(x1, x2, x3)
return nil, x1 * x2 * x3
end, 7, 17, 31)
end)
end)
describe("memoize4", function()
it("should cache the function execution", function()
test_memoize(5, func.memoize4, function(x1, x2, x3, x4)
return x1 == nil and x2 == nil and x3 == nil and x4 == nil
end)
test_memoize(5, func.memoize4, function(x1, x2, x3, x4)
return x1 + x2, x3 + x4
end, 17, 13, 29, 37)
test_memoize(5, func.memoize4, function(x1, x2, x3, x4)
return x1, x2 + x3 + x4
end, 7, 15, 29, 31)
test_memoize(5, func.memoize4, function(x1, x2, x3, x4)
return nil, x1 * x2 * x3 / x4
end, 7, 17, 31, 29)
end)
end)
describe("always", function()
it("should always return the same value", function()
local one = func.always(1)
assert.equal(1, one())
assert.equal(1, one())
end)
end)
describe("identity", function()
it("should return the input value", function()
for i = 1, 100 do
assert.equal(i, func.identity(i))
end
end)
end)
describe("lambda", function()
it("should compile a string into a simple function", function()
local one, err = func.lambda('() => 1')
assert.is_nil(err)
assert.equal(1, one())
end)
it("should compile a string into a simple function", function()
local sum2, err = func.lambda('(x,y) => x + y')
assert.is_nil(err)
assert.equal(1, sum2(1, 0))
assert.equal(5, sum2(2, 3))
end)
it("should compile a string into a simple function", function()
local pack = func.lambda('(x,y) => {y,x}')
assert.same({0, 1}, pack(1, 0))
assert.same({3, 2}, pack(2, 3))
end)
end)
end)
|
local draw_nearby_boxes = require("__subterra__.scripts.events.ui.draw_nearby_boxes")
local get_adjacent_surfaces = require("__subterra__.scripts.events.player.get_adjacent_surfaces")
local get_all_subterra_surfaces = require("__subterra__.scripts.events.player.get_all_subterra_surfaces")
local get_player_level = require("__subterra__.scripts.events.player.get_player_level")
local duration = ((subterra and subterra.config and subterra.config.BOX_DURATION) or 60) + 1
local draw_radius = (subterra and subterra.config and subterra.config.HUD_DRAW_RADIUS) or 20
local power_radius = math.floor(draw_radius / 2)
-- helper callback functions
local above_callback = function(surface)
return get_adjacent_surfaces (surface, 1)
end
local below_callback = function(surface)
return get_adjacent_surfaces (surface, -1)
end
local get_all_but = function (current_surface)
-- debug("current: " .. current_surface.name)
local surfaces = {}
local all_surfaces = get_all_subterra_surfaces()
for i = 1, #all_surfaces do
local surface_tuple = all_surfaces[i]
-- debug(surface_tuple[1].name)
if surface_tuple[1] ~= current_surface then
table.insert(surfaces, surface_tuple)
end
end
return surfaces
end
-- callbacks based on entity name
local check_entities = {}
check_entities["subterra-telepad-up"] = above_callback
check_entities["subterra-telepad-down"] = below_callback
check_entities["subterra-power-up"] = get_all_but
check_entities["subterra-power-column"] = get_all_but
-- TODO: change when belt-elevators become dynamicly generated
check_entities["subterra-transport-belt-up"] = above_callback
check_entities["subterra-fast-transport-belt-up"] = above_callback
check_entities["subterra-express-transport-belt-up"] = above_callback
check_entities["subterra-transport-belt-down"] = below_callback
check_entities["subterra-fast-transport-belt-down"] = below_callback
check_entities["subterra-express-transport-belt-down"] = below_callback
--============================================================================--
-- on_player_cursor_stack_changed(event)
--
-- Called when a player changes their cursor stack or when changing surfaces
--
-- param event (table): { player_index }
--
-- remarks: This sets the proxy's draw_surfaces and current_level properties
-- which are used to draw the "HUD" that aids entity placement.
--============================================================================--
local on_player_cursor_stack_changed = function(event)
debug("on_player_cursor_stack_changed")
local player_proxies = global.player_proxies
local p_index = event.player_index
local proxy = player_proxies[p_index]
if not proxy then
return
end
local player = proxy.player
local cursor_stack = player.cursor_stack
local old_surface = proxy.draw_surface
local draw_surfaces
local player_surface
if cursor_stack and cursor_stack.valid_for_read then
local tech = player.force.technologies["subterra-mapping"]
if tech.level > 1 then
local name = cursor_stack.name
debug("name: " .. name)
local callback = check_entities[name]
if callback then
player_surface = player.surface
draw_surfaces = callback(player_surface)
end
end
end
proxy.draw_surfaces = draw_surfaces
proxy.current_level = (draw_surfaces and get_player_level(proxy)) or nil
local drawing_players = global.drawing_players
local count = # drawing_players
local current_index
if count > 0 then
for i = 1, count do
if drawing_players[i] == proxy then
current_index = i
break
end
end
end
if draw_surfaces and # draw_surfaces > 0 then
if not current_index then
table.insert(drawing_players, proxy)
end
else
if current_index then
table.remove(drawing_players, current_index)
end
end
-- if new_surface and (old_surface ~= new_surface) then
-- local remaining_ticks = event.tick % duration
-- if remaining_ticks > 0 then
-- draw_nearby_boxes(player, player_surface, new_surface, draw_radius, remaining_ticks)
-- end
-- end
end
return on_player_cursor_stack_changed
|
--[[
Copyright 2021 边蓬(bianpeng001@163.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local GameObject = UnityEngine.GameObject
local TrailRenderer = UnityEngine.TrailRenderer
local Input = UnityEngine.Input
local Time = UnityEngine.Time
local Example02 = bLua.Example02
local LuaBehaviour = require("Core/LuaBehaviour")
local Math = require("Core/Math")
local Vector3 = Math.Vector3
local ACT_MOVE <const> = 1
local ACT_SHOOT <const> = 2
local _G <const> = -9.8
local module = LuaBehaviour.CreateModule()
local _example02 = nil
local _deltaTime = 0
local _unitsMgr
local _bulletsMgr
local _pidSeed = 1000
local Player = {}
Player.__index = Player
function Player.New()
_pidSeed = _pidSeed + 1
local obj =
{
pid = _pidSeed,
position = { 0, 0, 0, },
hp = 100,
speed = 1.5,
action = 0,
gameObject = nil,
shoot_cd = 0,
bullet_count = 3,
}
setmetatable(obj, Player)
return obj
end
function Player:SetPosition(pos)
self.position[1] = pos[1]
self.position[2] = pos[2]
self.position[3] = pos[3]
if self.transform then
self.transform.localPosition = pos
end
end
function Player:Action()
if self.action == ACT_MOVE then
if self.time < 1 then
self.time = self.time + _deltaTime * self.timeRactor
local pos = Vector3.Add(self.startPosition, Vector3.Scale(self.deltaPosition, self.time))
self:SetPosition(pos)
else
self.action = ACT_SHOOT
end
elseif self.action == ACT_SHOOT then
self.shoot_cd = self.shoot_cd - _deltaTime
if self.shoot_cd < 0 then
self.shoot_cd = 0.5
self.bullet_count = self.bullet_count - 1
if self.bullet_count < 0 then
self.hp = -1
end
local bullet = _bulletsMgr:NewBullet()
local p = Vector3.Add(self.position, { 0, 1, 0 })
local delta = Vector3.Sub({ 0, 2, 0 }, p)
Vector3.Set(bullet.startPosition, p[1], p[2], p[3])
bullet.transform.localPosition = p
delta[2] = delta[2] - 0.5 * _G
Vector3.Set(bullet.v0, delta[1], delta[2], delta[3])
end
end
end
local UnitsMgr = {}
UnitsMgr.__index = UnitsMgr
function UnitsMgr.New()
local obj = {
units = {},
deads = {},
}
setmetatable(obj, UnitsMgr)
return obj
end
function UnitsMgr:Add(p)
self.units[p.pid] = p
end
function UnitsMgr:Remove(p)
self.units[p.pid] = nil
end
local BulletsMgr = {}
BulletsMgr.__index = BulletsMgr
function BulletsMgr.New()
local obj = {
freeList = {},
flyList = {},
fly2List = {},
template = nil,
}
setmetatable(obj, BulletsMgr)
return obj
end
function BulletsMgr:NewBullet()
local obj
local n = #self.freeList
if n > 0 then
obj = self.freeList[n]
self.freeList[n] = nil
obj.time = 0
else
obj =
{
startPosition = { 0, 0, 0, },
v0 = { 0, 0, 0, },
time = 0,
timeScale = 1.0,
gameObject = self.template:Clone(),
}
obj.transform = obj.gameObject.transform
obj.transform.parent = nil
obj.transform.localPosition = Vector3.zero
obj.trailRenderer = cast2type(
obj.gameObject:GetComponent2(typeof(TrailRenderer)),
TrailRenderer)
end
obj.gameObject:SetActive(true)
table.insert(self.flyList, obj)
return obj
end
function BulletsMgr:OnUpdate()
local flyList = self.flyList
self.flyList = self.fly2List
self.fly2List = flyList
for i = 1, #flyList do
local obj = flyList[i]
flyList[i] = nil
obj.time = obj.time + _deltaTime * obj.timeScale
if obj.time < 1 then
local pos = Vector3.Add(obj.startPosition, Vector3.Mul(obj.v0, obj.time))
pos[2] = pos[2] + 0.5 * _G * obj.time * obj.time
obj.transform.localPosition = pos
table.insert(self.flyList, obj)
else
obj.trailRenderer:Clear()
obj.gameObject:SetActive(false)
table.insert(self.freeList, obj)
end
end
end
_unitsMgr = UnitsMgr.New()
_bulletsMgr = BulletsMgr.New()
function module.Awake()
print('gameObject:', module.gameObject)
print('name:', module.name)
print(module.luaBehaviour, getmetatable(module.luaBehaviour).class)
_example02 = cast2type(module.luaBehaviour, Example02)
print('Awake', Time.time, Time.deltaTime)
module.unitPrefab = { GameObject.Find("Res/Unit01") }
_bulletsMgr.template = GameObject.Find("Res/Bullet01")
end
local function CreatePlayer()
local pos = _example02:GetFloorPoint()
local obj = module.unitPrefab[1]:Clone()
obj.name = 'Player01'
local tr = obj.transform
tr.parent = nil
print('CreatePlayer', obj, tr)
local p = Player.New()
p.gameObject = obj
p.transform = tr
_unitsMgr:Add(p)
p:SetPosition(pos)
p.action = ACT_MOVE
p.time = 0
p.startPosition = Vector3.Clone(pos)
p.deltaPosition = Example02.GetDeltaPosition(pos, Vector3.zero, 3.0)
p.timeRactor = 1/ 3.0
p.gameObject:LookAt(Vector3.zero)
end
local _tickTime = 0
local function OnTick()
_tickTime = _tickTime + Time.deltaTime
if _tickTime < 0.2 then
return
end
_tickTime = 0
end
local function OnUpdate()
_bulletsMgr:OnUpdate()
local n = 0
local deads = _unitsMgr.deads
for pid, v in pairs(_unitsMgr.units) do
if v.hp < 0 then
n = n + 1
deads[n] = pid
else
v:Action()
end
end
if n > 0 then
for i = 1, n do
local pid = deads[i]
local unit = _unitsMgr.units[pid]
if unit.gameObject then
GameObject.Destroy2(unit.gameObject)
unit.gameObject = nil
end
_unitsMgr.units[pid] = nil
deads[i] = nil
end
end
end
function module.Update()
if Input.GetMouseButtonUp(0) then
local pos = Input.mousePosition
print('ButtonUp, go =', module.gameObject, ', pos =', table.unpack(pos))
CreatePlayer()
end
_deltaTime = Time.deltaTime
OnTick()
OnUpdate()
end
return module
|
local class = require 'middleclass'
local lume = require 'lume'
-- ホワイトリスト
local Whitelist = class 'Whitelist'
-- 初期化
function Whitelist:initialize(t)
self.list = t or {}
end
-- オーバーライド:比較
function Whitelist:__eq(other)
local equal = true
if #self.list ~= #other.list then
equal = false
else
for i, value in ipairs(self.list) do
if value ~= other.list[i] then
equal = false
break
end
end
end
return equal
end
-- オーバーライド:呼び出し
function Whitelist:__call(...)
return self:allow(...)
end
-- チェック
function Whitelist:allow(v)
return #self.list == 0 or not not lume.find(self.list, v)
end
return Whitelist
|
if opt.begin_epoch == 1 then
if opt.model == 'c3d' then
dofile('models/c3d.lua')
elseif opt.model == 'resnet' then
dofile('models/resnet.lua')
end
model = create_model()
if not opt.no_cuda then
model = model:cuda()
cudnn.convert(model, cudnn)
end
else
local model_file_path = paths.concat(
opt.result_path, 'model_' .. (opt.begin_epoch - 1) .. '.t7')
assert(paths.filep(model_file_path),
'pretrained model at epoch ' .. (opt.begin_epoch - 1) .. ' does not exist')
print('pretrained model at epoch ' .. (opt.begin_epoch - 1) .. ' is loaded')
model = torch.load(model_file_path)
if not opt.no_cuda then
model = utils.make_data_parallel(model, opt.gpu_id, opt.n_gpus)
end
end
print(model)
criterion = nn.ClassNLLCriterion()
if not opt.no_cuda then
criterion = criterion:cuda()
end
|
map = class("map")
local buttonImage = love.graphics.newImage("assets/gfx/images/button.png")
function map:initialize()
self.tileset = tileset:new("blocks.png")
self.canvas = love.graphics.newCanvas(405, 720)
self.rects = {}
self.turrets = {}
self.doors = {}
self.button = {
x = 10,
y = 10,
width = 15,
height = 15,
type = "button"
}
collisionWorld:add(self.button, self.button.x, self.button.y, self.button.width, self.button.height)
self.number = 0
self:changeMap(1)
end
function map:update(dt)
for i,v in pairs(self.turrets) do
v:update(dt)
end
for i,v in pairs(self.doors) do
v:update(dt)
end
updateBullets(dt)
end
function map:draw()
love.graphics.setColor(1, 1, 1)
love.graphics.draw(self.canvas)
love.graphics.draw(buttonImage, self.button.x, self.button.y)
drawBullets()
for i,v in pairs(self.turrets) do
v:draw()
end
for i,v in pairs(self.doors) do
v:draw()
end
end
function map:changeMap(num)
for i,v in pairs(self.rects) do
collisionWorld:remove(v)
end
for i,v in pairs(self.doors) do
if v.isInWorld then
collisionWorld:remove(v)
end
end
local data = require("assets/maps/map"..tostring(num))
local layers = data.layers
local tileLayer = layers[1]
self.tileset = tileset:new("blocks.png")
self.canvas = love.graphics.newCanvas(405, 720)
self.rects = {}
self.turrets = {}
self.doors = {}
love.graphics.setColor(1, 1, 1)
love.graphics.setCanvas(self.canvas)
for y = 1, tileLayer.height do
for x=1, tileLayer.width do
local index = tileLayer.data[(y-1)*tileLayer.width+x]
love.graphics.draw(self.tileset.set, self.tileset.quads[index], (x-1)*15, (y-1)*15)
end
end
game:fontSize(12)
if num == 1 then
love.graphics.print("Jump on the button!", 230, 430)
elseif num == 2 then
game:fontSize(15)
love.graphics.print("Don't hit the gray ceiling!", game.width / 2 - game.font:getWidth("Don't hit the gray ceiling!") / 2, 250)
elseif num == 4 then
love.graphics.print("You can wall jump!", 25, 450)
elseif num == 10 then
love.graphics.print("Watch out!", 16, 350)
elseif num == 16 then
love.graphics.print("Timing is key!", 198, 575)
elseif num == 25 then
game:fontSize(20)
love.graphics.print("You Win!", findMiddle("You Win!"), 140)
love.graphics.print("Thanks for playing!", findMiddle("Thanks for playing!"), 170)
end
love.graphics.setCanvas()
local collisionLayer = layers[2]
for i,v in pairs(collisionLayer.objects) do
local rect = {x = v.x, y = v.y, width = v.width, height = v.height}
collisionWorld:add(rect, rect.x, rect.y, rect.width, rect.height)
table.insert(self.rects, rect)
end
self.button.x = layers[3].objects[1].x
self.button.y = layers[3].objects[1].y - 15
collisionWorld:update(self.button, self.button.x, self.button.y)
if layers[4] then --If map has turrets
local turretLayer = layers[4]
for i,v in pairs(turretLayer.objects) do
table.insert(self.turrets, turret:new(v.x, v.y))
end
end
if layers[5] then -- If map has doors
local doorLayer = layers[5]
for i,v in pairs(doorLayer.objects) do
table.insert(self.doors, door:new(v.x, v.y))
end
end
self.number = self.number + 1
end
|
local torch = require "torch"
local nn = require "nn"
local lua_util = require "lua_util"
local ucl = require "ucl"
local rescore_utility = require "rspamadm/rescore_utility"
local function make_dataset_from_logs(logs, all_symbols)
-- Returns a list of {input, output} for torch SGD train
local dataset = {}
for _, log in pairs(logs) do
local input = torch.Tensor(#all_symbols)
local output = torch.Tensor(1)
log = lua_util.rspamd_str_split(log, " ")
if log[1] == "SPAM" then
output[1] = 1
else
output[1] = 0
end
local symbols_set = {}
for i=4,#log do
symbols_set[log[i]] = true
end
for index, symbol in pairs(all_symbols) do
if symbols_set[symbol] then
input[index] = 1
else
input[index] = 0
end
end
dataset[#dataset + 1] = {input, output}
end
function dataset:size()
return #dataset
end
return dataset
end
local function init_weights(all_symbols, original_symbol_scores)
local weights = torch.Tensor(#all_symbols)
local mean = 0
for i, symbol in pairs(all_symbols) do
local score = original_symbol_scores[symbol]
if not score then score = 0 end
weights[i] = score
mean = mean + score
end
return weights
end
local function shuffle(logs)
local size = #logs
for i = size, 1, -1 do
local rand = math.random(size)
logs[i], logs[rand] = logs[rand], logs[i]
end
end
local function split_logs(logs, split_percent)
if not split_percent then
split_percent = 60
end
local split_index = math.floor(#logs * split_percent / 100)
local test_logs = {}
local train_logs = {}
for i=1,split_index do
train_logs[#train_logs + 1] = logs[i]
end
for i=split_index + 1, #logs do
test_logs[#test_logs + 1] = logs[i]
end
return train_logs, test_logs
end
local function stitch_new_scores(all_symbols, new_scores)
local new_symbol_scores = {}
for idx, symbol in pairs(all_symbols) do
new_symbol_scores[symbol] = new_scores[idx]
end
return new_symbol_scores
end
local function update_logs(logs, symbol_scores)
for i, log in ipairs(logs) do
log = lua_util.rspamd_str_split(log, " ")
local score = 0
for j=4,#log do
log[j] = log[j]:gsub("%s+", "")
score = score + (symbol_scores[log[j ]] or 0)
end
log[2] = rescore_utility.round(score, 2)
logs[i] = table.concat(log, " ")
end
return logs
end
local function write_scores(new_symbol_scores, file_path)
local file = assert(io.open(file_path, "w"))
local new_scores_ucl = ucl.to_format(new_symbol_scores, "ucl")
file:write(new_scores_ucl)
file:close()
end
local function print_score_diff(new_symbol_scores, original_symbol_scores)
print(string.format("%-35s %-10s %-10s", "SYMBOL", "OLD_SCORE", "NEW_SCORE"))
for symbol, new_score in pairs(new_symbol_scores) do
print(string.format("%-35s %-10s %-10s",
symbol,
original_symbol_scores[symbol] or 0,
rescore_utility.round(new_score, 2)))
end
print "\nClass changes \n"
for symbol, new_score in pairs(new_symbol_scores) do
if original_symbol_scores[symbol] ~= nil then
if (original_symbol_scores[symbol] > 0 and new_score < 0) or
(original_symbol_scores[symbol] < 0 and new_score > 0) then
print(string.format("%-35s %-10s %-10s",
symbol,
original_symbol_scores[symbol] or 0,
rescore_utility.round(new_score, 2)))
end
end
end
end
local function calculate_fscore_from_weights(logs, all_symbols, weights, bias, threshold)
local new_symbol_scores = weights:clone()
new_symbol_scores = stitch_new_scores(all_symbols, new_symbol_scores)
logs = update_logs(logs, new_symbol_scores)
local file_stats, _ = rescore_utility.generate_statistics_from_logs(logs, threshold)
return file_stats.fscore
end
local function print_stats(logs, threshold)
local file_stats, _ = rescore_utility.generate_statistics_from_logs(logs, threshold)
local file_stat_format = [[
F-score: %.2f
False positive rate: %.2f %%
False negative rate: %.2f %%
Overall accuracy: %.2f %%
]]
io.write("\nStatistics at threshold: " .. threshold .. "\n")
io.write(string.format(file_stat_format,
file_stats.fscore,
file_stats.false_positive_rate,
file_stats.false_negative_rate,
file_stats.overall_accuracy))
end
return function (_, res)
local logs = rescore_utility.get_all_logs(res["logdir"])
local all_symbols = rescore_utility.get_all_symbols(logs)
local original_symbol_scores = rescore_utility.get_all_symbol_scores(res["timeout"])
shuffle(logs)
local train_logs, validation_logs = split_logs(logs, 70)
local cv_logs, test_logs = split_logs(validation_logs, 50)
local dataset = make_dataset_from_logs(train_logs, all_symbols)
local learning_rates = {0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2.5, 5, 7.5, 10}
local penalty_weights = {0, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 3, 5, 10, 15, 20, 25, 50, 75, 100}
-- Start of perceptron training
local input_size = #all_symbols
local linear_module = nn.Linear(input_size, 1)
local perceptron = nn.Sequential()
perceptron:add(linear_module)
local activation = nn.Sigmoid()
perceptron:add(activation)
local criterion = nn.MSECriterion()
criterion.sizeAverage = false
local best_fscore = -math.huge
local best_weights = linear_module.weight[1]:clone()
local trainer = nn.StochasticGradient(perceptron, criterion)
trainer.maxIteration = res["iters"]
trainer.verbose = false
trainer.hookIteration = function(self, iteration, error)
if iteration == trainer.maxIteration then
local fscore = calculate_fscore_from_weights(cv_logs,
all_symbols,
linear_module.weight[1],
linear_module.bias[1],
res["threshold"])
print("Cross-validation fscore: " .. fscore)
if best_fscore < fscore then
best_fscore = fscore
best_weights = linear_module.weight[1]:clone()
end
end
end
for _, learning_rate in pairs(learning_rates) do
for _, weight in pairs(penalty_weights) do
trainer.weightDecay = weight
print("Learning with learning_rate: " .. learning_rate
.. " | l2_weight: " .. weight)
linear_module.weight[1] = init_weights(all_symbols, original_symbol_scores)
trainer.learningRate = learning_rate
trainer:train(dataset)
print()
end
end
-- End perceptron training
local new_symbol_scores = best_weights
new_symbol_scores = stitch_new_scores(all_symbols, new_symbol_scores)
if res["output"] then
write_scores(new_symbol_scores, res["output"])
end
if res["diff"] then
print_score_diff(new_symbol_scores, original_symbol_scores)
end
-- Pre-rescore test stats
print("\n\nPre-rescore test stats\n")
test_logs = update_logs(test_logs, original_symbol_scores)
print_stats(test_logs, res['threshold'])
-- Post-rescore test stats
test_logs = update_logs(test_logs, new_symbol_scores)
print("\n\nPost-rescore test stats\n")
print_stats(test_logs, res['threshold'])
end
|
object_static_item_lair_fake_cave_small = object_static_item_shared_lair_fake_cave_small:new {
}
ObjectTemplates:addTemplate(object_static_item_lair_fake_cave_small, "object/static/item/lair_fake_cave_small.iff")
|
vim.keymap.set("n", "[file]f", [[<Cmd>tab drop ~/workspace/todo/todo.tsv<CR>]], { buffer = true })
|
object_mobile_shocktrooper_blue = object_mobile_shared_shocktrooper_blue:new {
}
ObjectTemplates:addTemplate(object_mobile_shocktrooper_blue, "object/mobile/shocktrooper_blue.iff")
|
local skynet = require "skynet"
local sc = require "skynet.socketchannel"
local socket = require "skynet.socket"
local cluster = require "skynet.cluster.core"
local ignoreret = skynet.ignoreret
local clusterd, gate, fd = ...
clusterd = tonumber(clusterd)
gate = tonumber(gate)
fd = tonumber(fd)
local large_request = {}
local inquery_name = {}
local register_name_mt = { __index =
function(self, name)
local waitco = inquery_name[name]
if waitco then
local co=coroutine.running()
table.insert(waitco, co)
skynet.wait(co)
return rawget(self, name)
else
waitco = {}
inquery_name[name] = waitco
local addr = skynet.call(clusterd, "lua", "queryname", name:sub(2)) -- name must be '@xxxx'
if addr then
self[name] = addr
end
inquery_name[name] = nil
for _, co in ipairs(waitco) do
skynet.wakeup(co)
end
return addr
end
end
}
local function new_register_name()
return setmetatable({}, register_name_mt)
end
local register_name = new_register_name()
local tracetag
local function dispatch_request(_,_,addr, session, msg, sz, padding, is_push)
ignoreret() -- session is fd, don't call skynet.ret
if session == nil then
-- trace
tracetag = addr
return
end
if padding then
local req = large_request[session] or { addr = addr , is_push = is_push, tracetag = tracetag }
tracetag = nil
large_request[session] = req
cluster.append(req, msg, sz)
return
else
local req = large_request[session]
if req then
tracetag = req.tracetag
large_request[session] = nil
cluster.append(req, msg, sz)
msg,sz = cluster.concat(req)
addr = req.addr
is_push = req.is_push
end
if not msg then
tracetag = nil
local response = cluster.packresponse(session, false, "Invalid large req")
socket.write(fd, response)
return
end
end
local ok, response
if addr == 0 then
local name = skynet.unpack(msg, sz)
skynet.trash(msg, sz)
local addr = register_name["@" .. name]
if addr then
ok = true
msg = skynet.packstring(addr)
else
ok = false
msg = "name not found"
end
sz = nil
else
if cluster.isname(addr) then
addr = register_name[addr]
end
if addr then
if is_push then
skynet.rawsend(addr, "lua", msg, sz)
return -- no response
else
if tracetag then
ok , msg, sz = pcall(skynet.tracecall, tracetag, addr, "lua", msg, sz)
tracetag = nil
else
ok , msg, sz = pcall(skynet.rawcall, addr, "lua", msg, sz)
end
end
else
ok = false
msg = "Invalid name"
end
end
if ok then
response = cluster.packresponse(session, true, msg, sz)
if type(response) == "table" then
for _, v in ipairs(response) do
socket.lwrite(fd, v)
end
else
socket.write(fd, response)
end
else
response = cluster.packresponse(session, false, msg)
socket.write(fd, response)
end
end
skynet.start(function()
skynet.register_protocol {
name = "client",
id = skynet.PTYPE_CLIENT,
unpack = cluster.unpackrequest,
dispatch = dispatch_request,
}
-- fd can write, but don't read fd, the data package will forward from gate though client protocol.
skynet.call(gate, "lua", "forward", fd)
skynet.dispatch("lua", function(_,source, cmd, ...)
if cmd == "exit" then
socket.close(fd)
skynet.exit()
elseif cmd == "namechange" then
register_name = new_register_name()
else
skynet.error(string.format("Invalid command %s from %s", cmd, skynet.address(source)))
end
end)
end)
|
require 'tables'
require 'sets'
file = require 'files'
config = require 'config'
require 'strings'
res = require 'resources'
require 'actions'
require 'pack'
bit = require 'bit'
require 'generic_helpers'
require 'parse_action_packet'
require 'statics'
_addon.version = '3.29'
_addon.name = 'BattleMod'
_addon.author = 'Byrth, maintainer: SnickySnacks'
_addon.commands = {'bm','battlemod'}
windower.register_event('load',function()
if debugging then windower.debug('load') end
options_load()
end)
windower.register_event('login',function (name)
if debugging then windower.debug('login') end
windower.send_command('@wait 10;lua i battlemod options_load;')
end)
windower.register_event('addon command', function(command, ...)
if debugging then windower.debug('addon command') end
local args = {...}
command = command and command:lower()
if command then
if command:lower() == 'commamode' then
commamode = not commamode
windower.add_to_chat(121,'Battlemod: Comma Mode flipped! - '..tostring(commamode))
elseif command:lower() == 'oxford' then
oxford = not oxford
windower.add_to_chat(121,'Battlemod: Oxford Mode flipped! - '..tostring(oxford))
elseif command:lower() == 'targetnumber' then
targetnumber = not targetnumber
windower.add_to_chat(121,'Battlemod: Target Number flipped! - '..tostring(targetnumber))
elseif command:lower() == 'condensetargetname' then
condensetargetname = not condensetargetname
windower.add_to_chat(121,'Battlemod: Target Name Condensation flipped! - '..tostring(condensetargetname))
elseif command:lower() == 'swingnumber' then
swingnumber = not swingnumber
windower.add_to_chat(121,'Battlemod: Round Number flipped! - '..tostring(swingnumber))
elseif command:lower() == 'sumdamage' then
sumdamage = not sumdamage
windower.add_to_chat(121,'Battlemod: Sum Damage flipped! - '..tostring(sumdamage))
elseif command:lower() == 'condensecrits' then
condensecrits = not condensecrits
windower.add_to_chat(121,'Battlemod: Condense Crits flipped! - '..tostring(condensecrits))
elseif command:lower() == 'cancelmulti' then
cancelmulti = not cancelmulti
windower.add_to_chat(121,'Battlemod: Multi-canceling flipped! - '..tostring(cancelmulti))
elseif command:lower() == 'reload' then
current_job = 'NONE'
options_load()
elseif command:lower() == 'unload' then
windower.send_command('@lua u battlemod')
elseif command:lower() == 'simplify' then
simplify = not simplify
windower.add_to_chat(121,'Battlemod: Text simplification flipped! - '..tostring(simplify))
elseif command:lower() == 'condensedamage' then
condensedamage = not condensedamage
windower.add_to_chat(121,'Battlemod: Condensed Damage text flipped! - '..tostring(condensedamage))
elseif command:lower() == 'condensetargets' then
condensetargets = not condensetargets
windower.add_to_chat(121,'Battlemod: Condensed Targets flipped! - '..tostring(condensetargets))
elseif command:lower() == 'showownernames' then
showownernames = not showownernames
windower.add_to_chat(121,'Battlemod: Show pet owner names flipped! - '..tostring(showownernames))
elseif command:lower() == 'crafting' then
crafting = not crafting
windower.add_to_chat(121,'Battlemod: Display crafting results flipped! - '..tostring(crafting))
elseif command:lower() == 'colortest' then
local counter = 0
local line = ''
for n = 1, 262 do
if not color_redundant:contains(n) and not black_colors:contains(n) then
if n <= 255 then
loc_col = string.char(0x1F, n)
else
loc_col = string.char(0x1E, n - 254)
end
line = line..loc_col..string.format('%03d ', n)
counter = counter + 1
end
if counter == 16 or n == 262 then
windower.add_to_chat(6, line)
counter = 0
line = ''
end
end
windower.add_to_chat(122,'Colors Tested!')
elseif command:lower() == 'help' then
print(' ::: '.._addon.name..' ('.._addon.version..') :::')
print('Toggles: (* subtoggles)')
print(' 1. simplify - Condenses battle text using custom messages ('..tostring(simplify)..')')
print(' 2. condensetargets - Collapse similar messages with multiple targets ('..tostring(condensetargets)..')')
print(' * targetnumber - Toggle target number display ('..tostring(targetnumber)..')')
print(' * condensetargetname - Toggle target name condensation ('..tostring(condensetargetname)..')')
print(' * oxford - Toggle use of oxford comma ('..tostring(oxford)..')')
print(' * commamode - Toggle comma-only mode ('..tostring(commamode)..')')
print(' 3. condensedamage - Condenses damage messages within attack rounds ('..tostring(condensedamage)..')')
print(' * swingnumber - Show # of attack rounds ('..tostring(swingnumber)..')')
print(' * sumdamage - Sums condensed damage if true, comma-separated if false ('..tostring(sumdamage)..')')
print(' * condensecrits - Condenses critical hits and normal hits together ('..tostring(condensecrits)..')')
print(' 4. cancelmulti - Cancels multiple consecutive identical lines ('..tostring(cancelmulti)..')')
print(' 5. showonernames - Shows the name of the owner on pet messages ('..tostring(showownernames)..')')
print(' 6. crafting - Enables early display of crafting results ('..tostring(crafting)..')')
print('Utilities: 1. colortest - Shows the 509 possible colors for use with the settings file')
print(' 2. reload - Reloads settings file')
print(' 3. unload - Unloads Battlemod')
end
end
end)
windower.register_event('incoming text',function (original, modified, color, color_m, blocked)
if debugging then windower.debug('incoming text') end
local redcol = color%256
if redcol == 121 and cancelmulti then
a,z = string.find(original,'Equipment changed')
if a and not block_equip then
windower.send_command('@wait 1;lua i battlemod flip_block_equip')
block_equip = true
elseif a and block_equip then
modified = true
end
elseif redcol == 123 and cancelmulti then
a,z = string.find(original,'You were unable to change your equipped items')
b,z = string.find(original,'You cannot use that command while viewing the chat log')
c,z = string.find(original,'You must close the currently open window to use that command')
if (a or b or c) and not block_cannot then
windower.send_command('@wait 1;lua i battlemod flip_block_cannot')
block_cannot = true
elseif (a or b or c) and block_cannot then
modified = true
end
end
if block_modes:contains(color) then
local endline = string.char(0x7F, 0x31)
local item = string.char(0x1E)
if not bm_message(original) then
if original:endswith(endline) then --allow add_to_chat messages with the modes we blocking
blocked = true
return blocked
end
elseif original:endswith(endline) and string.find(original, item) then --block items action messages
blocked = true
return blocked
end
end
return modified,color
end)
function bm_message(original)
local check = string.char(0x1E)
local check2 = string.char(0x1F)
if string.find(original, check) or string.find(original, check2) then
return true
end
end
function flip_block_equip()
block_equip = not block_equip
end
function flip_block_cannot()
block_cannot = not block_cannot
end
function options_load()
if windower.ffxi.get_player() then
Self = windower.ffxi.get_player()
end
if not windower.dir_exists(windower.addon_path..'data\\') then
windower.create_dir(windower.addon_path..'data\\')
end
if not windower.dir_exists(windower.addon_path..'data\\filters\\') then
windower.create_dir(windower.addon_path..'data\\filters\\')
end
local settingsFile = file.new('data\\settings.xml',true)
local filterFile=file.new('data\\filters\\filters.xml',true)
local colorsFile=file.new('data\\colors.xml',true)
if not file.exists('data\\settings.xml') then
settingsFile:write(default_settings)
print('Default settings xml file created')
end
local settingtab = config.load('data\\settings.xml',default_settings_table)
config.save(settingtab)
for i,v in pairs(settingtab) do
_G[i] = v
end
if not file.exists('data\\filters\\filters.xml') then
filterFile:write(default_filters)
print('Default filters xml file created')
end
local tempplayer = windower.ffxi.get_player()
if tempplayer then
if tempplayer.main_job ~= 'NONE' then
filterload(tempplayer.main_job)
elseif windower.ffxi.get_mob_by_id(tempplayer.id)['race'] == 0 then
filterload('MON')
else
filterload('DEFAULT')
end
else
filterload('DEFAULT')
end
if not file.exists('data\\colors.xml') then
colorsFile:write(default_colors)
print('Default colors xml file created')
end
local colortab = config.load('data\\colors.xml',default_color_table)
config.save(colortab)
for i,v in pairs(colortab) do
color_arr[i] = colconv(v,i)
end
end
function filterload(job)
if current_job == job then return end
if file.exists('data\\filters\\filters-'..job..'.xml') then
default_filt = false
filter = config.load('data\\filters\\filters-'..job..'.xml',default_filter_table,false)
config.save(filter)
windower.add_to_chat(4,'Loaded '..job..' Battlemod filters')
elseif not default_filt then
default_filt = true
filter = config.load('data\\filters\\filters.xml',default_filter_table,false)
config.save(filter)
windower.add_to_chat(4,'Loaded default Battlemod filters')
end
current_job = job
end
ActionPacket.open_listener(parse_action_packet)
windower.register_event('incoming chunk',function (id,original,modified,is_injected,is_blocked)
if debugging then windower.debug('incoming chunk '..id) end
------- ACTION MESSAGE -------
if id == 0x29 then
local am = {}
am.actor_id = original:unpack("I",0x05)
am.target_id = original:unpack("I",0x09)
am.param_1 = original:unpack("I",0x0D)
am.param_2 = original:unpack("H",0x11)%2^9 -- First 7 bits
am.param_3 = math.floor(original:unpack("I",0x11)/2^5) -- Rest
am.actor_index = original:unpack("H",0x15)
am.target_index = original:unpack("H",0x17)
am.message_id = original:unpack("H",0x19)%2^15 -- Cut off the most significant bit
local actor = player_info(am.actor_id)
local target = player_info(am.target_id)
-- Filter these messages
if not check_filter(actor,target,0,am.message_id) then return true end
if not actor or not target then -- If the actor or target table is nil, ignore the packet
elseif am.message_id == 800 then -- Spirit bond message
local status = color_it(res.buffs[am.param_1][language],color_arr.statuscol)
local targ = color_it(target.name or '',color_arr[target.owner or target.type])
local number = am.param_2
local color = color_filt(res.action_messages[am.message_id].color, am.target_id==Self.id)
if simplify then
local msg = line_noactor
:gsub('${abil}',status or '')
:gsub('${target}',targ)
:gsub('${numb}',number or '')
windower.add_to_chat(color, msg)
else
local msg = res.action_messages[am.message_id][language]
:gsub('${status}',status or '')
:gsub('${target}',targ)
:gsub('${number}',number or '')
windower.add_to_chat(color, msg)
end
elseif am.message_id == 206 and condensetargets then -- Wears off messages
-- Condenses across multiple packets
local status
if enfeebling:contains(am.param_1) and res.buffs[param_1] then
status = color_it(res.buffs[param_1][language],color_arr.enfeebcol)
elseif color_arr.statuscol == rcol then
status = color_it(res.buffs[am.param_1][language],string.char(0x1F,191))
else
status = color_it(res.buffs[am.param_1][language],color_arr.statuscol)
end
if not multi_actor[status] then multi_actor[status] = player_info(am.actor_id) end
if not multi_msg[status] then multi_msg[status] = am.message_id end
if not multi_targs[status] and not stat_ignore:contains(am.param_1) then
multi_targs[status] = {}
multi_targs[status][1] = target
windower.send_command('@wait 0.5;lua i battlemod multi_packet '..status)
elseif not (stat_ignore:contains(am.param_1)) then
multi_targs[status][#multi_targs[status]+1] = target
else
-- This handles the stat_ignore values, which are things like Utsusemi,
-- Sneak, Invis, etc. that you don't want to see on a delay
multi_targs[status] = {}
multi_targs[status][1] = target
windower.send_command('@lua i battlemod multi_packet '..status)
end
am.message_id = false
elseif passed_messages:contains(am.message_id) then
local item,status,spell,skill,number,number2
local fields = fieldsearch(res.action_messages[am.message_id][language])
if fields.status then
if log_form_debuffs:contains(am.param_1) then
status = res.buffs[am.param_1].english_log
else
status = nf(res.buffs[am.param_1],language)
end
if enfeebling:contains(am.param_1) then
status = color_it(status,color_arr.enfeebcol)
else
status = color_it(status,color_arr.statuscol)
end
end
if fields.spell then
if not res.spells[am.param_1] then
return false
end
spell = nf(res.spells[am.param_1],language)
end
if fields.item then
if not res.items[am.param_1] then
return false
end
item = nf(res.items[am.param_1],'english_log')
end
if fields.number then
number = am.param_1
end
if fields.number2 then
number2 = am.param_2
end
if fields.skill and res.skills[am.param_1] then
skill = res.skills[am.param_1][language]:lower()
end
if am.message_id > 169 and am.message_id <179 then
if am.param_1 > 2147483647 then
skill = 'to be level -1 ('..ratings_arr[am.param_2-63]..')'
else
skill = 'to be level '..am.param_1..' ('..ratings_arr[am.param_2-63]..')'
end
end
local outstr = (res.action_messages[am.message_id][language]
:gsub('$\123actor\125',color_it((actor.name or '') .. (actor.owner_name or ""),color_arr[actor.owner or actor.type]))
:gsub('$\123status\125',status or '')
:gsub('$\123item\125',color_it(item or '',color_arr.itemcol))
:gsub('$\123target\125',color_it(target.name or '',color_arr[target.owner or target.type]))
:gsub('$\123spell\125',color_it(spell or '',color_arr.spellcol))
:gsub('$\123skill\125',color_it(skill or '',color_arr.abilcol))
:gsub('$\123number\125',number or '')
:gsub('$\123number2\125',number2 or '')
:gsub('$\123skill\125',skill or '')
:gsub('$\123lb\125','\7'))
windower.add_to_chat(res.action_messages[am.message_id]['color'],outstr)
am.message_id = false
elseif debugging and res.action_messages[am.message_id] then
-- 38 is the Skill Up message, which (interestingly) uses all the number params.
-- 202 is the Time Remaining message, which (interestingly) uses all the number params.
print('debug_EAM#'..am.message_id..': '..res.action_messages[am.message_id][language]..' '..am.param_1..' '..am.param_2..' '..am.param_3)
elseif debugging then
print('debug_EAM#'..am.message_id..': '..'Unknown'..' '..am.param_1..' '..am.param_2..' '..am.param_3)
end
if not am.message_id then
return true
end
------------ SYNTHESIS ANIMATION --------------
elseif id == 0x030 and crafting then
if windower.ffxi.get_player().id == original:unpack("I",5) or windower.ffxi.get_mob_by_target('t') and windower.ffxi.get_mob_by_target('t').id == original:unpack("I",5) then
local crafter_name = (windower.ffxi.get_player().id == original:unpack("I",5) and windower.ffxi.get_player().name) or windower.ffxi.get_mob_by_target('t').name
local result = original:byte(13)
if result == 0 then
windower.add_to_chat(8,' ------------- NQ Synthesis ('..crafter_name..') -------------')
elseif result == 1 then
windower.add_to_chat(8,' ---------------- Break ('..crafter_name..') -----------------')
elseif result == 2 then
windower.add_to_chat(8,' ------------- HQ Synthesis ('..crafter_name..') -------------')
else
windower.add_to_chat(8,'Craftmod: Unhandled result '..tostring(result))
end
end
elseif id == 0x06F and crafting then
if original:byte(5) == 0 or original:byte(5) == 12 then
local result = original:byte(6)
if result == 1 then
windower.add_to_chat(8,' -------------- HQ Tier 1! --------------')
elseif result == 2 then
windower.add_to_chat(8,' -------------- HQ Tier 2! --------------')
elseif result == 3 then
windower.add_to_chat(8,' -------------- HQ Tier 3! --------------')
end
end
------------- JOB INFO ----------------
elseif id == 0x01B then
filterload(res.jobs[original:byte(9)][language..'_short'])
end
end)
function multi_packet(...)
local ind = table.concat({...},' ')
local targets = assemble_targets(multi_actor[ind],multi_targs[ind],0,multi_msg[ind])
local outstr = res.action_messages[multi_msg[ind]][language]
:gsub('$\123target\125',targets)
:gsub('$\123status\125',ind)
windower.add_to_chat(res.action_messages[multi_msg[ind]].color,outstr)
multi_targs[ind] = nil
multi_msg[ind] = nil
multi_actor[ind] = nil
end
|
-- =============================================================
-- Copyright Roaming Gamer, LLC. 2008-2016 (All Rights Reserved)
-- =============================================================
-- RG Files Module Library - Loader and Initializer
-- =============================================================
-- Last Updated: 15 DEC 2016
-- Last Validated:
-- =============================================================
local lfs = require "lfs"
local json = require "json"
local strGSub = string.gsub
local strSub = string.sub
local strFormat = string.format
local strFind = string.find
local pathSep = ( ssk.system.onWin ) and "\\" or "/"
local RGFiles = {}
-- =====================================================
-- Utility methods
-- =====================================================
require("ssk2.files.RGFiles_util").attach( RGFiles )
-- OSX Discovery Utility
local function getUserName()
-- 1. Try the $USER variable
local user = os.getenv("USER")
if( user ) then
print("Found $USER == " .. tostring( user ) )
return user
end
-- 2. Try extracting it from the $HOME path
local user = os.getenv("HOME")
if( user ) then
print("Found $HOME == ", user )
user = string.split(user, "/")
user = user[#user]
if( user ) then
print("Got USER from $HOME == " .. tostring( user ) )
return user
end
end
-- 3. Try the $LOGNAME variable
local user = os.getenv("LOGNAME")
if( user ) then
print("Got USER from $LOGNAME == " .. tostring( user ) )
return user
end
return nil
end
-- =====================================================
-- Discover full root paths to:
-- =====================================================
--
-- system.DocumentsDirectory
--
RGFiles.documentsRoot = system.pathForFile('', system.DocumentsDirectory) .. pathSep
--
-- system.ResourceDirectory
--
do
local tmp = system.pathForFile('main.lua', system.ResourceDirectory)
RGFiles.resourceRoot = (tmp) and tmp:sub(1, -9) or ""
end
--
-- system.TemporaryDirectory
--
RGFiles.temporaryRoot = system.pathForFile('', system.TemporaryDirectory) .. pathSep
--
-- OS My Documents Folder
--
RGFiles.myDocumentsRoot = ""
if( ssk.system.onWin ) then
RGFiles.myDocumentsRoot = os.getenv("appdata")
local appDataStart = string.find( RGFiles.myDocumentsRoot, "AppData" )
if( appDataStart ) then
RGFiles.myDocumentsRoot = string.sub( RGFiles.myDocumentsRoot, 1, appDataStart-1 )
if( RGFiles.util.isFolder(RGFiles.myDocumentsRoot .. "Documents") ) then
RGFiles.myDocumentsRoot = RGFiles.myDocumentsRoot .. "Documents"
else
RGFiles.myDocumentsRoot = RGFiles.myDocumentsRoot .. "My Documents" -- QUESTION: Is this right for Win 7 and before?
end
end
elseif( ssk.system.onOSX ) then
RGFiles.myDocumentsRoot = getUserName()
if( not RGFiles.myDocumentsRoot ) then
RGFiles.myDocumentsRoot = "TBD"
else
RGFiles.myDocumentsRoot = "/Users/" .. RGFiles.myDocumentsRoot .. "/" .. "Documents"
end
end
RGFiles.myDocumentsRoot = RGFiles.myDocumentsRoot .. pathSep
--
-- OS Desktop
--
RGFiles.desktopRoot = ""
if( ssk.system.onWin ) then
RGFiles.desktopRoot = os.getenv("appdata")
local appDataStart = string.find( RGFiles.desktopRoot, "AppData" )
if( appDataStart ) then
RGFiles.desktopRoot = string.sub( RGFiles.desktopRoot, 1, appDataStart-1 )
RGFiles.desktopRoot = RGFiles.desktopRoot .. "Desktop"
end
elseif( ssk.system.onOSX ) then
RGFiles.desktopRoot = getUserName()
if( not RGFiles.desktopRoot ) then
RGFiles.desktopRoot = "TBD"
else
RGFiles.desktopRoot = "/Users/" .. RGFiles.desktopRoot .. "/" .. "Desktop"
end
end
RGFiles.desktopRoot = RGFiles.desktopRoot .. pathSep
-- =====================================================
-- Attach OS Dependent features
-- =====================================================
require("ssk2.files.RGFiles_systemDocuments").attach( RGFiles )
require("ssk2.files.RGFiles_systemResource").attach( RGFiles )
require("ssk2.files.RGFiles_systemTemporary").attach( RGFiles )
require("ssk2.files.RGFiles_desktop").attach( RGFiles )
require("ssk2.files.RGFiles_tests").attach( RGFiles )
--table.dump( RGFiles.desktop )
----------------------------------------------------------------------
-- Attach To SSK and return
----------------------------------------------------------------------
if( _G.ssk ) then
ssk.files = RGFiles
else
_G.ssk = { RGFiles = RGFiles }
end
return RGFiles
|
ENT.Type = "anim"
ENT.Base = "base_gmodentity"
ENT.PrintName = "Painting"
ENT.Author = "Pilot2"
ENT.Category = "Museum robbery"
ENT.Spawnable = true
ENT.AdminOnly = true
ENT.RenderGroup = RENDERGROUP_BOTH
function ENT:SetupDataTables()
self:NetworkVar( "String", 0, "imgururl" )
self:NetworkVar( "String", 1, "ImgurID" )
self:NetworkVar( "String", 2, "imgurcrc" )
self:NetworkVar( "Bool", 0, "stolen" )
self:NetworkVar( "Bool", 1, "offered" )
if SERVER then
self:Setimgururl("")
self:SetImgurID("")
self:Setimgurcrc("")
self:Setstolen(false)
self:Setoffered(false)
end
end
|
string.startswith = function (s, p)
return string.sub(s, 1, string.len(p)) == p
end
string.endswith = function (s, p)
return string.sub(s, string.len(s) - string.len(p) + 1) == p
end
string.split = function (str, delimiter)
if str == nil or str == '' or delimiter == nil then
return nil
end
local result = {}
for match in (str .. delimiter):gmatch("(.-)" .. delimiter) do
table.insert(result, match)
end
return result
end
|
OpenNefia.Prototypes.Elona.FieldType.Elona =
{
Plains = {
Name = "平地",
},
Grassland = {
Name = "草原",
},
Desert = {
Name = "草原",
},
Sea = {
Name = "水上",
},
Forest = {
Name = "森",
},
SnowField = {
Name = "雪原"
}
}
|
local ENT = {}
ENT.Type = "anim"
ENT.Base = "base_entity"
-- Also allow spawnmenu spawning
ENT.Category = "nZombies Unlimited"
ENT.PrintName = "Invisible Wall"
ENT.Author = "Zet0r"
ENT.Spawnable = true
local defaultmodel = "models/hunter/plates/plate5x5.mdl"
local col = Color(255,150,0,100)
local mat = "models/wireframe"
-- TODO: Ray traces are taken care of, but find a way to make Hull traces ignore the entity unless PLAYERCLIP mask? :(
function ENT:Initialize()
if SERVER then
self:SetNoDraw(NZU_NZOMBIES)
self:UpdateModel(self:GetModel() ~= "models/error.mdl" and self:GetModel() or defaultmodel)
end
if NZU_NZOMBIES then
self:SetSolidFlags(FSOLID_CUSTOMRAYTEST) -- Runs TestCollision but ONLY for ray traces! (i.e. bullets and view traces)
end
self:DrawShadow(false)
self:SetColor(col)
self:SetMaterial(mat)
end
function ENT:UpdateModel(mdl)
self:SetModel(mdl)
self:PhysicsInit(SOLID_VPHYSICS)
--self:SetSolid(SOLID_CUSTOM)
--self:SetCollisionBounds(Vector(0,0,0), Vector(0,0,0))
--self:SetPos(Vector(0,0,0))
--local a,b = self:GetModelBounds()
--[[local a,b = Vector(-20,-20,-20), Vector(20,20,200)
self:PhysicsInitConvex({
a,
Vector(a.x,a.y,b.z),
Vector(a.x,b.y,a.z),
Vector(b.x,a.y,a.z),
Vector(a.x,b.y,b.z),
Vector(b.x,a.y,b.z),
Vector(b.x,b.y,a.z),
b
})
print(a,b)
self:EnableCustomCollisions(true)]]
local phys = self:GetPhysicsObject()
if IsValid(phys) then
phys:SetContents(CONTENTS_PLAYERCLIP) -- This only allows props to pass through, it does nothing for traces D:
phys:SetMaterial("default_silent")
phys:EnableMotion(false)
phys:Sleep()
end
end
function ENT:TestCollision(start, delta, box, extents, mask)
-- Nothing! This runs when the entity is shot through - we return nothing to let the trace pass right through!
end
if CLIENT then function ENT:Draw() self:DrawModel() end end
-- Support Door Tool, but have our own door handling logic
ENT.nzu_CanDoor = true -- This entity can be given a Door Lock
ENT.nzu_DoorHooked = true -- When given a door lock, this is instead a non-networked Group hook
-- nzu_DoorHooked means this can be given door data, but it won't get a DoorData function - it'll just get hooked into that group and OpenDoor'd when that is opened
if SERVER then
function ENT:OpenDoor()
self:Remove() -- No fancy effects, just remove
end
end
scripted_ents.Register(ENT, "nzu_prop_playerclip")
if not NZU_SANDBOX then return end
--[[-------------------------------------------------------------------------
Tool for spawning wall buys, browses weapon classes through filters
---------------------------------------------------------------------------]]
local TOOL = {}
TOOL.Category = "Mapping"
TOOL.Name = "#tool.nzu_tool_invisibleprop.name"
TOOL.ClientConVar = {
["model"] = defaultmodel,
}
function TOOL:LeftClick(trace)
if SERVER then
local ply = self:GetOwner()
local e = ents.Create("nzu_prop_playerclip")
e:SetPos(trace.HitPos)
e:SetAngles(trace.HitNormal:Angle() + Angle(90,0,0))
e:Spawn()
e:UpdateModel(self:GetClientInfo("model"))
if IsValid(ply) then
undo.Create("Invisible Prop")
undo.SetPlayer(ply)
undo.AddEntity(e)
undo.Finish()
end
end
return true
end
function TOOL:RightClick(trace)
if self:GetStage() == 0 then
local trace = trace
if not IsValid(trace.Entity) or trace.Entity:GetClass() ~= "nzu_prop_playerclip" then
trace = util.TraceLine({
start = trace.HitPos,
endpos = trace.HitPos - trace.Normal * 1,
ignoreworld = true,
filter = trace.Entity,
})
end
if IsValid(trace.Entity) and trace.Entity:GetClass() == "nzu_prop_playerclip" then
if SERVER then
self.TargetedEntity = trace.Entity
self.LocalAng = trace.HitNormal:Angle()
self.LocalPos = trace.Entity:WorldToLocal(trace.HitPos)
self:SetStage(1)
end
return true
end
else
if SERVER then
if IsValid(self.TargetedEntity) then
local trace = trace
if trace.Entity == self.TargetedEntity then
trace = util.TraceLine({
start = trace.HitPos,
endpos = trace.HitPos + trace.Normal * 4096 * 8,
filter = self.TargetedEntity
})
end
if trace.Hit then
self.TargetedEntity:SetAngles(trace.HitNormal:Angle() - self.LocalAng + self.TargetedEntity:GetAngles())
self.TargetedEntity:SetPos(self.TargetedEntity:LocalToWorld(self.TargetedEntity:WorldToLocal(trace.HitPos) - self.LocalPos))
--self:GetOwner():SetPos(self.TargetedEntity:GetPos())
end
end
self:SetStage(0)
self.TargetedEntity = nil
self.LocalPos = nil
self.LocalAng = nil
end
return true
end
end
function TOOL:Reload(trace)
if self:GetStage() ~= 0 then self:SetStage(0) return true end
if IsValid(trace.Entity) and trace.Entity:GetClass() == "nzu_prop_playerclip" then
if SERVER then trace.Entity:SetMaterial(trace.Entity:GetMaterial() == "" and mat or "") end
return true
end
end
if CLIENT then
TOOL.Information = {
{name = "left", stage = 0},
{name = "right", stage = 0},
{name = "reload", stage = 0},
{name = "right_finish", stage = 1},
{name = "reload_cancel", stage = 1}
}
language.Add("tool.nzu_tool_invisibleprop.name", "Invisible Wall")
language.Add("tool.nzu_tool_invisibleprop.desc", "Creates a prop that will be invisible in-game and only collide with Players and Zombies.")
language.Add("tool.nzu_tool_invisibleprop.left", "Create Invisible Plate")
language.Add("tool.nzu_tool_invisibleprop.right", "Target Plate to Align to Wall")
language.Add("tool.nzu_tool_invisibleprop.reload", "Toggle Wireframe Material")
language.Add("tool.nzu_tool_invisibleprop.right_finish", "Align targeted Plate to Surface")
language.Add("tool.nzu_tool_invisibleprop.reload_cancel", "Cancel Align")
function TOOL.BuildCPanel(panel)
panel:Help("Spawn a prop that collides only with players and NPCs, which cannot be seen in nZombies Unlimited.")
panel:TextEntry("Model", "nzu_tool_invisibleprop_model")
panel:Help("Tip: You can right-click any model in the Spawn Menu and 'Copy to clipboard', then paste in the text box above for that model.")
local f = file.Read("settings/spawnlist_default/008-plastic.txt", "GAME")
if f then
local tbl = util.KeyValuesToTable(f)
if tbl then
local scroll = vgui.Create("DScrollPanel", panel)
local p = vgui.Create("DIconLayout", scroll)
p:Dock(FILL)
--p:SetSpaceX(5)
--p:SetSpaceY(5)
for k,v in pairs(tbl.contents) do
if v.type == "model" and string.find(v.model, "plate") then
local icon = p:Add("SpawnIcon")
icon:SetModel(v.model)
icon.DoClick = function()
RunConsoleCommand("nzu_tool_invisibleprop_model", v.model)
end
end
end
scroll:SetTall(600)
panel:AddItem(scroll)
end
end
end
end
nzu.RegisterTool("invisibleprop", TOOL)
|
--
-- playercollider.lua
-- Inherits from the Collider class
-- Provides many player variables and functions
-- Mostly pertains to movement
--
local Class = require ("src.class")
local Collider = require ("src.logic.physics.collider")
local PlayerCollider = Class.new (Collider)
-- MODULES --
local Constants = require ("src.logic.general")
local PlayerLimits = require ("src.logic.physics.playerlimits")
local Input = require ("src.boundary.input")
local Rectangle = require ("src.logic.rectangle")
local General = require ("src.logic.general")
-- END --
PlayerCollider.STATES = {STANDING = 1, FALLING = 2, JUMPING = 3, EDGE = 4}
function PlayerCollider:_init (x, y)
Collider._init (self, x, y, 1, 1)
self.limits = PlayerLimits.new ()
self.state = PlayerCollider.STATES.FALLING
self.direction = false
self.grounded = false
self.leftWall = false
self.rightWall = false
self.grip = false
self.roof = false
self.currentFloor = nil
self.movementMultiplier = 1
self.playerDir = Constants.Directions.RIGHT
end
function PlayerCollider:facingRight ()
return not self.direction
end
-- Performs all movements for frame
-- Calls subroutines
function PlayerCollider:act ()
self:setLastPosition ()
self:horizontalMovement ()
self:verticalMovement ()
self:friction ()
Collider.limits (self)
-- TODO TODO TODO TODO
-- movement multiplier --
self.vSpeed = self.vSpeed * self.movementMultiplier
self.hSpeed = self.hSpeed * self.movementMultiplier
self:movePosition ()
self:setState ()
self.grounded = false
self.roof = false
self.leftWall = false
self.rightWall = false
self.grip = false
self.movementMultiplier = 1
end
-- Sets the floor to the arg
function PlayerCollider:setFloor (newFloor)
self.currentFloor = newFloor or nil
end
-- Vert. movement (including input polling)
function PlayerCollider:verticalMovement ()
if (self.grounded or self.roof or self.vSpeed < 0 and (not Input.keyDown (Input.KEYS.JUMP))) then
self.vSpeed = 0
end
if (self.vSpeed >= 0 and ((self.leftWall and Input.keyDown (Input.KEYS.LEFT)) or (self.rightWall and Input.keyDown (Input.KEYS.RIGHT)))) then
self.vSpeed = self.limits.GRIPFALL
else
self.vSpeed = self.vSpeed - Constants.GRAVITY
end
if Input.keyPressed (Input.KEYS.JUMP) then
if self.grounded then
self.vSpeed = self.limits.JUMP
else
if (self.leftWall and Input.keyDown (Input.KEYS.LEFT) and self.grip) then
self.vSpeed = self.limits.WALLJUMPVERT
self.hSpeed = self.limits.WALLJUMPHORI
elseif (self.rightWall and Input.keyDown (Input.KEYS.RIGHT) and self.grip) then
self.vSpeed = self.limits.WALLJUMPVERT
self.hSpeed = self.limits.WALLJUMPHORI * -1
end
end
end
end
-- Hori. movement (including input polling)
function PlayerCollider:horizontalMovement ()
if ((self.hSpeed > 0 and self.rightWall) or (self.hSpeed < 0 and self.leftWall)) then
self.hSpeed = 0
end
if Input.keyDown (Input.KEYS.LEFT) then
if self.grounded then
if Input.keyDown (Input.KEYS.SPRINT) then
self.hSpeed = self.hSpeed - (1.2 * General.dt)
if self.hSpeed < (self.limits.SPRINTCAP * -1) then
self.hSpeed = self.limits.SPRINTCAP * -1
end
else
self.hSpeed = self.hSpeed - (0.9 * General.dt)
if self.hSpeed < (self.limits.RUNCAP * -1) then
self.hSpeed = self.limits.RUNCAP * -1
end
end
else
self.hSpeed = self.hSpeed - (0.36 * General.dt)
end
end
if Input.keyDown (Input.KEYS.RIGHT) then
if self.grounded then
if Input.keyDown (Input.KEYS.SPRINT) then
self.hSpeed = self.hSpeed + (1.2 * General.dt)
if self.hSpeed > (self.limits.SPRINTCAP) then
self.hSpeed = self.limits.SPRINTCAP
end
else
self.hSpeed = self.hSpeed + (0.9 * General.dt)
if self.hSpeed > (self.limits.RUNCAP) then
self.hSpeed = self.limits.RUNCAP
end
end
else
self.hSpeed = self.hSpeed + (0.36 * General.dt)
end
end
end
-- Slows player down if grounded
function PlayerCollider:friction ()
if self.currentFloor then
if self.currentFloor.friction then
self.frictionValue = self.currentFloor.friction
end
else
self.frictionValue = Constants.DEFAULTFRICTION
end
if self.grounded then
if self.hSpeed > self.frictionValue then
self.hSpeed = self.hSpeed - self.frictionValue
elseif self.hSpeed > 0 then
self.hSpeed = 0
end
if self.hSpeed < (self.frictionValue * -1) then
self.hSpeed = self.hSpeed + self.frictionValue
elseif self.hSpeed < 0 then
self.hSpeed = 0
end
end
end
-- Sets the player state
-- Helps with animation
function PlayerCollider:setState ()
if self.grounded then
self.state = PlayerCollider.STATES.STANDING
else
if self.leftWall or self.rightWall then
self.state = PlayerCollider.STATES.EDGE
else
if self.vSpeed < 0 then
self.state = PlayerCollider.STATES.JUMPING
else
self.state = PlayerCollider.STATES.FALLING
end
end
end
if self.leftWall or self.rightWall then
if self.leftWall then
self.direction = false
if Input.keyDown (Input.KEYS.UP) then
self.playerDir = Constants.Directions.UPRIGHT
elseif Input.keyDown (Input.KEYS.DOWN) then
self.playerDir = Constants.Directions.DOWNRIGHT
else
self.playerDir = Constants.Directions.RIGHT
end
else
self.direction = true
if Input.keyDown (Input.KEYS.UP) then
self.playerDir = Constants.Directions.UPLEFT
elseif Input.keyDown (Input.KEYS.DOWN) then
self.playerDir = Constants.Directions.DOWNLEFT
else
self.playerDir = Constants.Directions.LEFT
end
end
else
if self.hSpeed > 0 then
self.direction = false
if Input.keyDown (Input.KEYS.UP) then
--if playerDir != UPRIGHT, woggle position
self.playerDir = Constants.Directions.UPRIGHT
elseif Input.keyDown (Input.KEYS.DOWN) then
self.playerDir = Constants.Directions.DOWNRIGHT
else
self.playerDir = Constants.Directions.RIGHT
end
elseif self.hSpeed < 0 then
self.direction = true
if Input.keyDown (Input.KEYS.UP) then
--if playerDir != UPLEFT, woggle position
self.playerDir = Constants.Directions.UPLEFT
elseif Input.keyDown (Input.KEYS.DOWN) then
self.playerDir = Constants.Directions.DOWNLEFT
else
self.playerDir = Constants.Directions.LEFT
end
end
end
end
-- Render function for debug
function PlayerCollider:render ()
love.graphics.setColor (0, 255, 255)
love.graphics.rectangle ("fill", self.x, self.y, self.width, self.height)
end
function PlayerCollider:getFloorDamage ()
return (self.grounded and self.currentFloor and self.currentFloor.damageOverTime)
end
return PlayerCollider
|
data:extend(
{
{
type = "string-setting",
name = "tlbe-save-folder",
setting_type = "runtime-per-user",
default_value = "timelapse",
order = "3"
},
{
type = "bool-setting",
name = "tlbe-sequential-names",
setting_type = "runtime-per-user",
default_value = true,
order = "6"
}
}
)
|
function onUpdate()
getPropertyFromClass('flixel.input', 'FlxKey') --Basically lets the script figure out what button you are pressing.
if keyJustPressed('up') then --self explanatory
triggerEvent('Play Animation', 'hey', 'BF')
--characterPlayAnim('boyfriend', 'hey', true); --This one works as well but whenever I pressed space it would cancel the animation midway sometimes.
--boyfriend.specialAnim = true;
--boyfriend.heyTimer = time;
end
end
|
return {
clock = 1,
date = 3,
difftime = 1,
execute = 3,
exit = 1,
getenv = 1,
remove = 1,
rename = 1,
setlocale = 1,
time = 1,
tmpname = 1,
}
|
package("rsync")
set_kind("binary")
set_homepage("https://rsync.samba.org/")
set_description("rsync is an open source utility that provides fast incremental file transfer.")
set_license("GPL-3.0")
add_urls("https://download.samba.org/pub/rsync/src/rsync-$(version).tar.gz")
add_versions("3.2.3", "becc3c504ceea499f4167a260040ccf4d9f2ef9499ad5683c179a697146ce50e")
add_deps("openssl", "xxhash", "lz4", "acl", "zstd", {host = true})
on_install("linux", function (package)
local cxflags = {}
local ldflags = {}
for _, dep in ipairs(package:orderdeps()) do
local fetchinfo = dep:fetch()
if fetchinfo then
for _, includedir in ipairs(fetchinfo.includedirs or fetchinfo.sysincludedirs) do
table.insert(cxflags, "-I" .. includedir)
end
for _, linkdir in ipairs(fetchinfo.linkdirs) do
table.insert(ldflags, "-L" .. linkdir)
end
for _, link in ipairs(fetchinfo.links) do
table.insert(ldflags, "-l" .. link)
end
end
end
import("package.tools.autoconf").install(package, configs, {cxflags = cxflags, ldflags = ldflags})
end)
on_test(function (package)
os.vrun("rsync --version")
end)
|
_C = {
pures = set.new(),
dets = {},
}
local types = {
void=true,
int=true,
u32=true, s32=true,
u16=true, s16=true,
u8=true, s8=true,
}
function _C.isNumeric (tp)
return tp~='void' and (not _C.deref(tp))
end
function _C.deref (tp)
return string.match(tp, '(.-)%*$')
end
function _C.ext (tp)
return (not _C.deref(tp)) and (not types[tp])
end
function _C.contains (tp1, tp2)
local _tp1, _tp2 = _C.deref(tp1), _C.deref(tp2)
if tp1 == tp2 then
return true
elseif _C.isNumeric(tp1) and _C.isNumeric(tp2) then
return true
elseif _C.ext(tp1) or _C.ext(tp2) then
return true
elseif _tp1 and _tp2 then
return tp1=='void*' or tp2=='void*'
end
return false
end
function _C.max (tp1, tp2)
if _C.contains(tp1, tp2) then
return tp1
elseif _C.contains(tp2, tp1) then
return tp2
else
return nil
end
end
F = {
Dcl_pure = function (me)
local cid = unpack(me)
_C.pures[cid[1]] = true
end,
Dcl_det = function (me)
for i=1, #me do
local id1 = me[i][1]
local t1 = _C.dets[id1] or {}
_C.dets[id1] = t1
for j=i+1, #me do
local id2 = me[j][1]
local t2 = _C.dets[id2] or {}
_C.dets[id2] = t2
t1[id2] = true
t2[id1] = true
end
end
end,
}
_VISIT(F)
|
-- another small bug (in 5.2.1)
f = load(string.dump(function () return 1 end), nil, "b", {})
assert(type(f) == "function" and f() == 1)
|
slot0 = class("WorldTrigger", import("...BaseEntity"))
slot0.Fields = {
config = "table",
progress = "number",
id = "number",
maxProgress = "number",
desc = "string"
}
slot0.Setup = function (slot0, slot1)
slot0.id = slot1
end
slot0.GetProgress = function (slot0)
return slot0.progress
end
slot0.GetMaxProgress = function (slot0)
return slot0.maxProgress
end
slot0.GetDesc = function (slot0)
return string.format("%s(%s/%s)", slot0.desc, slot0.progress, slot0.maxProgress)
end
slot0.IsAchieved = function (slot0)
return slot0:GetMaxProgress() <= slot0:GetProgress()
end
return slot0
|
include("shared.lua")
local mat = CreateMaterial("UnlitGeneric", "GMODScreenspace", { })
function ENT:Draw()
if not self.Rt then
self.Rt = GetRenderTarget("ControllerDrr" .. self:EntIndex(), 1024, 1024, false)
end
self:DrawModel()
cam.Start3D2D(self:LocalToWorld(Vector(-14.7, -14.4, 1.5)), self:LocalToWorldAngles(Angle(0, 90, 0)), 0.03)
local w, h = 520, 345
draw.RoundedBox(0, 0, 0, w, h, Color(0, 0, 0))
local drone = self:GetNWEntity("DronesRewriteDrone")
if drone:IsValid() then
if not DRONES_REWRITE.ClientCVars.NoScreen:GetBool() then
mat:SetTexture("$basetexture", self.Rt)
surface.SetMaterial(mat)
surface.DrawTexturedRect(0, 0, w, h)
end
draw.SimpleText("DRONE: " .. drone:GetUnit(), "DronesRewrite_font3", 8, 8, Color(255, 255, 255, 200))
draw.SimpleText("HEALTH: " .. drone:GetHealth(), "DronesRewrite_font3", 8, 30, Color(255, 255, 255, 200))
draw.SimpleText("MAX DISTANCE: " .. self:GetNWInt("Distance"), "DronesRewrite_font3", 8, 52, Color(255, 255, 255, 200))
else
surface.SetMaterial(Material("stuff/console/broken4"))
surface.SetDrawColor(Color(255, 255, 255, 50))
surface.DrawTexturedRect(0, 0, w, h)
draw.SimpleText("NO SIGNAL", "DronesRewrite_font1", w / 2, h / 2 - 16, Color(255, 255, 255, 50), TEXT_ALIGN_CENTER)
end
cam.End3D2D()
if not DRONES_REWRITE.ClientCVars.NoGlows:GetBool() then
local dlight = DynamicLight(self:EntIndex())
if dlight then
dlight.pos = self:LocalToWorld(Vector(-7, -7, 3))
dlight.r = 255
dlight.g = 255
dlight.b = 255
dlight.brightness = 1
dlight.Decay = 1000
dlight.Size = 36
dlight.DieTime = CurTime() + 0.1
end
end
end
function ENT:OpenMenu()
local win = DRONES_REWRITE.CreateWindow(265, 110)
local del = true
local text = vgui.Create("DTextEntry", win)
text:SetSize(245, 25)
text:SetPos(10, 30)
text.OnTextChanged = function()
net.Start("dronesrewrite_controllerlookup")
net.WriteEntity(self)
net.WriteString(text:GetValue())
net.SendToServer()
end
text.OnLoseFocus = function() text:RequestFocus() end
text:RequestFocus()
local btn = DRONES_REWRITE.CreateButton("Enter a valid drone id", 10, 70, 245, 30, win, function()
net.Start("dronesrewrite_controldr")
net.WriteEntity(self)
net.SendToServer()
win:Close()
end)
text.OnEnter = btn.DoClick
btn.Think = function(btn)
local text = self:GetNWEntity("DronesRewriteDrone"):IsValid() and "Control " .. self:GetNWEntity("DronesRewriteDrone"):GetUnit() or "Enter a valid drone id"
if text != btn:GetText() then btn:SetText(text) end
end
end
|
local _, Addon = ...
local Colors = Addon.Colors
local DB = Addon.DB
local DCL = Addon.Libs.DCL
local E = Addon.Events
local EventManager = Addon.EventManager
local L = Addon.Libs.L
local ListMixins = Addon.ListMixins
local Lists = Addon.Lists
local Utils = Addon.Utils
local UI = Addon.UI
local GROUP_KEYS = {
inclusions = "exclusions",
exclusions = "inclusions",
}
local LIST_KEYS = { "global", "profile" }
-- ============================================================================
-- Events
-- ============================================================================
EventManager:Once(E.DatabaseReady, function()
for list in Lists.globalLists() do
-- Set sv reference.
list._sv = list.getSvar()
-- Queue items to add directly from sv.
for k in pairs(list._sv) do list.toAdd[k] = true end
end
end)
EventManager:On(E.ProfileChanged, function()
for list in Lists.profileLists() do
-- Update sv reference
list._sv = list.getSvar()
-- Clear items
for k in pairs(list.items) do list.items[k] = nil end
-- Queue items to add directly from sv
for k in pairs(list._sv) do list.toAdd[k] = true end
end
end)
-- ============================================================================
-- Local Functions
-- ============================================================================
local function getLocales(groupKey, listKey)
local suffix = DCL:ColorString(
(listKey == "global" and L.GLOBAL_TEXT or L.PROFILE_TEXT),
"FFFFFF"
)
local locale = ("%s (%s)"):format(
(
groupKey == "inclusions" and
L.OPTION_GROUP_INCLUSIONS or
L.OPTION_GROUP_EXCLUSIONS
),
suffix
)
local shortLocale = ("%s (%s)"):format(
(
groupKey == "inclusions" and
L.INCLUSIONS_TEXT or
L.EXCLUSIONS_TEXT
),
suffix
)
return locale, shortLocale
end
--[[
Populates the group with required generic values and returns it.
@param {table} group = {
locale = string,
itemCanBeAdded = function(self, item) -> bool,
inclusions = {
uiGroup = table,
global = {
helpText = string,
getSvar = function() -> table
},
profile = {
helpText = string,
getSvar = function() -> table
},
},
exclusions = {
uiGroup = table,
global = {
helpText = string,
getSvar = function() -> table
},
profile = {
helpText = string,
getSvar = function() -> table
},
}
}
--]]
local function create(group)
group.inclusions.color = Colors.Red
group.exclusions.color = Colors.Green
for groupKey, siblingKey in pairs(GROUP_KEYS) do
for _, listKey in pairs(LIST_KEYS) do
local color = group[groupKey].color
local list = group[groupKey][listKey]
-- Add fields.
list.color = color
list.sibling = group[siblingKey][listKey]
list.toAdd = {}
list.items = {}
local locale, shortLocale = getLocales(groupKey, listKey)
list.locale = DCL:ColorString(locale:format(group.locale), color)
list.localeShort = DCL:ColorString(shortLocale, color)
-- Add mixins.
for k, v in pairs(ListMixins) do list[k] = v end
list.ItemCanBeAdded = group.itemCanBeAdded
end
end
return group
end
-- ============================================================================
-- Sell
-- ============================================================================
Lists.sell = create({
locale = L.SELL_TEXT,
itemCanBeAdded = function(self, item)
if not Utils:ItemCanBeSold(item) then
return false, L.ITEM_CANNOT_BE_SOLD:format(item.ItemLink)
end
return true
end,
inclusions = {
uiGroup = UI.Groups.SellInclusions,
global = {
helpText = L.SELL_INCLUSIONS_GLOBAL_HELP_TEXT,
getSvar = function() return DB.Global.sell.inclusions end
},
profile = {
helpText = L.SELL_INCLUSIONS_HELP_TEXT,
getSvar = function() return DB.Profile.sell.inclusions end
},
},
exclusions = {
uiGroup = UI.Groups.SellExclusions,
global = {
helpText = L.SELL_EXCLUSIONS_GLOBAL_HELP_TEXT,
getSvar = function() return DB.Global.sell.exclusions end
},
profile = {
helpText = L.SELL_EXCLUSIONS_HELP_TEXT,
getSvar = function() return DB.Profile.sell.exclusions end
},
}
})
-- ============================================================================
-- Destroy
-- ============================================================================
Lists.destroy = create({
locale = L.DESTROY_TEXT,
itemCanBeAdded = function(self, item)
if not Utils:ItemCanBeDestroyed(item) then
return false, L.ITEM_CANNOT_BE_DESTROYED:format(item.ItemLink)
end
return true
end,
inclusions = {
uiGroup = UI.Groups.DestroyInclusions,
global = {
helpText = L.DESTROY_INCLUSIONS_GLOBAL_HELP_TEXT,
getSvar = function() return DB.Global.destroy.inclusions end
},
profile = {
helpText = L.DESTROY_INCLUSIONS_HELP_TEXT,
getSvar = function() return DB.Profile.destroy.inclusions end
},
},
exclusions = {
uiGroup = UI.Groups.DestroyExclusions,
global = {
helpText = L.DESTROY_EXCLUSIONS_GLOBAL_HELP_TEXT,
getSvar = function() return DB.Global.destroy.exclusions end
},
profile = {
helpText = L.DESTROY_EXCLUSIONS_HELP_TEXT,
getSvar = function() return DB.Profile.destroy.exclusions end
},
}
})
-- ============================================================================
-- Iterators
-- ============================================================================
local _listGroups = {}
local _globalLists = {}
local _profileLists = {}
local _allLists = {}
-- Populate tables.
for _, group in pairs(Lists) do
for groupKey in pairs(GROUP_KEYS) do
local listGroup = group[groupKey]
_listGroups[listGroup] = true
_globalLists[listGroup.global] = true
_profileLists[listGroup.profile] = true
for _, listKey in pairs(LIST_KEYS) do
_allLists[listGroup[listKey]] = true
end
end
end
-- Set key consts.
Lists.GROUP_KEYS = GROUP_KEYS
Lists.LIST_KEYS = LIST_KEYS
--[[ Usage:
for listGroup in Lists.listGroups() do
-- ...
end
]]
function Lists.listGroups()
return next, _listGroups
end
--[[ Usage:
for list in Lists.globalLists() do
-- ...
end
--]]
function Lists.globalLists()
return next, _globalLists
end
--[[ Usage:
for list in Lists.profileLists() do
-- ...
end
--]]
function Lists.profileLists()
return next, _profileLists
end
--[[ Usage:
for list in Lists.allLists() do
-- ...
end
]]
function Lists.allLists()
return next, _allLists
end
|
--------------------------------------------------------------------------------
-- Handler.......... : onWalk
-- Author........... :
-- Description...... :
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function JPSpriteData.onWalk ( )
--------------------------------------------------------------------------------
this.bWalking ( true )
local hSprite = this.getSprite ( )
local bFlipX = this.nDirection ( ) < 0
JPSprite.setComponentAnimation ( hSprite, "walk", true, bFlipX, nil, true )
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
|
PROJECT_NAME = path.getname(os.getcwd())
if not minko.platform.supports { "windows32", "windows64", "linux32", "linux64", "osx64" } then
return
end
minko.project.application("minko-example-" .. PROJECT_NAME)
removeplatforms { "android", "ios", "html5" }
files { "src/**.cpp", "src/**.hpp", "asset/**" }
includedirs { "src" }
-- plugins
minko.plugin.enable("png")
minko.plugin.enable("jpeg")
minko.plugin.enable("sdl")
minko.plugin.enable("leap")
minko.plugin.enable("serializer")
|
--[=[
Update on heartbeat, must GC this camera state, unlike others. This
allows for camera effects to run on heartbeat and cache information once instead
of potentially going deeep into a tree and getting invoked multiple times
@class HeartbeatCamera
]=]
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local Janitor = require(ReplicatedStorage.Knit.Util.Janitor)
local SummedCamera = require(script.Parent.SummedCamera)
local HeartbeatCamera = {}
HeartbeatCamera.ClassName = "HeartbeatCamera"
HeartbeatCamera.ProfileName = "HeartbeatCamera"
function HeartbeatCamera.new(camera)
local self = setmetatable({}, HeartbeatCamera)
self._camera = camera or error("No camera")
self._janitor = Janitor.new()
self._currentStateCache = self._camera.CameraState or error("Camera state returned null")
self._janitor:Add(RunService.Heartbeat:Connect(function()
debug.profilebegin(self.ProfileName)
self._currentStateCache = self._camera.CameraState or error("Camera state returned null")
debug.profileend()
end), "Disconnect")
return self
end
function HeartbeatCamera:__add(other)
return SummedCamera.new(self, other)
end
function HeartbeatCamera:ForceUpdateCache()
self._currentStateCache = self._camera.CameraState
end
--[=[
The current state.
@readonly
@prop CameraState CameraState
@within DefaultCamera
]=]
function HeartbeatCamera:__index(index)
if index == "CameraState" then
return self._currentStateCache
else
return HeartbeatCamera[index]
end
end
function HeartbeatCamera:Destroy()
self._janitor:Destroy()
end
function HeartbeatCamera:__tostring()
return "HeartbeatCamera"
end
table.freeze(HeartbeatCamera)
return HeartbeatCamera
|
-- main.lua
FCLoadScript( "globals" )
FCLoadScript( "Languages/en" )
-- Language word tables
locale = FCDevice.GetString("locale")
FCLog( "Found locale " .. locale )
FCLoadScriptOptional( "Languages/" .. locale )
FCLoadScript( "frontendphase" )
FCLoadScript( "gamephase" )
screenWidth = FCDevice.GetInteger( kFCDeviceDisplayLogicalXRes )
screenHeight = FCDevice.GetInteger( kFCDeviceDisplayLogicalYRes )
FCLoadScript( "layout_global" )
if ( screenWidth == 768 ) and ( screenHeight == 1024 ) then
FCLog("Loading iPad layout")
FCLoadScript( "layout_ipad" )
else
FCLog("Loading iPhone layout")
FCLoadScript( "layout_iphone" ) -- defaults to iPhone
end
------------------------------------------------------------------------------------------
function PlayFailSFX()
FCAudio.SourcePlay( failSource )
end
function PlayWinSFX()
FCAudio.SourcePlay( winSource )
end
function PlayClickSFX()
FCAudio.SourcePlay( clickSource )
end
function PlayYaySFX()
FCAudio.SourcePlay( yaySource )
end
local function InitialiseAudio()
tone1 = FCAudio.CreateBuffer("Assets/Audio/1")
tone2 = FCAudio.CreateBuffer("Assets/Audio/2")
tone3 = FCAudio.CreateBuffer("Assets/Audio/3")
tone4 = FCAudio.CreateBuffer("Assets/Audio/4")
tone5 = FCAudio.CreateBuffer("Assets/Audio/5")
tone6 = FCAudio.CreateBuffer("Assets/Audio/6")
failBuffer = FCAudio.CreateBuffer("Assets/Audio/fail")
winBuffer = FCAudio.CreateBuffer("Assets/Audio/win")
clickBuffer = FCAudio.CreateBuffer("Assets/Audio/click")
yayBuffer = FCAudio.CreateBuffer("Assets/Audio/yay")
source1 = FCAudio.PrepareSourceWithBuffer( tone1, true )
source2 = FCAudio.PrepareSourceWithBuffer( tone2, true )
source3 = FCAudio.PrepareSourceWithBuffer( tone3, true )
source4 = FCAudio.PrepareSourceWithBuffer( tone4, true )
source5 = FCAudio.PrepareSourceWithBuffer( tone5, true )
source6 = FCAudio.PrepareSourceWithBuffer( tone6, true )
failSource = FCAudio.PrepareSourceWithBuffer( failBuffer, true )
winSource = FCAudio.PrepareSourceWithBuffer( winBuffer, true )
clickSource = FCAudio.PrepareSourceWithBuffer( clickBuffer, true )
yaySource = FCAudio.PrepareSourceWithBuffer( yayBuffer, true )
FCAudio.SourceLooping( source1, true )
FCAudio.SourceLooping( source2, true )
FCAudio.SourceLooping( source3, true )
FCAudio.SourceLooping( source4, true )
FCAudio.SourceLooping( source5, true )
FCAudio.SourceLooping( source6, true )
FCAudio.SourceSetVolume( source1, 0 )
FCAudio.SourcePlay( source1 )
FCAudio.SourceSetVolume( source2, 0 )
FCAudio.SourcePlay( source2 )
FCAudio.SourceSetVolume( source3, 0 )
FCAudio.SourcePlay( source3 )
FCAudio.SourceSetVolume( source4, 0 )
FCAudio.SourcePlay( source4 )
FCAudio.SourceSetVolume( source5, 0 )
FCAudio.SourcePlay( source5 )
FCAudio.SourceSetVolume( source6, 0 )
FCAudio.SourcePlay( source6 )
end
local function ShutdownAudio()
FCAudio.DeleteBuffer( tone1 )
FCAudio.DeleteBuffer( tone2 )
FCAudio.DeleteBuffer( tone3 )
FCAudio.DeleteBuffer( tone4 )
FCAudio.DeleteBuffer( tone5 )
FCAudio.DeleteBuffer( tone6 )
FCAudio.SourceStop( source1 )
FCAudio.SourceStop( source2 )
FCAudio.SourceStop( source3 )
FCAudio.SourceStop( source4 )
FCAudio.SourceStop( source5 )
FCAudio.SourceStop( source6 )
end
local function RandomBackgroundImage()
--backgroundView:SetStringProperty( "backgroundImage", "Assets/Images/Background" .. randomGenerator:Get() % 7 .. ".png" )
backgroundView:SetStringProperty( "backgroundImage", "Assets/Images/Background1.png" )
end
------------------------------------------------------------------------------------------
local function CreateViews()
backgroundView = FCView:New( "backgroundView", "BackgroundView" )
RandomBackgroundImage()
backgroundView:SetFrame( {0,0,1,1} )
titleLabel = FCView:New("titleLabel", "LabelView")
classicButton = FCView:New("classicButton", "MainButtonView")
sixButton = FCView:New( "sixButton", "MainButtonView" )
shuffleButton = FCView:New( "shuffleButton", "MainButtonView" )
multiButton = FCView:New( "multiButton", "MainButtonView" )
madnessButton = FCView:New( "madnessButton", "MainButtonView" )
quitButton = FCView:New( "quitButton", "ButtonView" )
quitButton:SetBackgroundColor( kRedColor )
scoreLabel = FCView:New("scoreLabel", "ScoreView")
scoreLabel:SetStringProperty( "backgroundImage", "Assets/Images/ScoreBackground.png")
redPlayButton = FCView:New("redPlayButton", "PlayView")
redPlayButton:SetIntegerProperty( "color", kRedPlayButton )
redPlayButton:SetStringProperty( "imageFilename", "Assets/Images/QuadRed.png" )
redPlayButton:SetStringProperty( "imagePressedFilename", "Assets/Images/QuadRedPressed.png" )
redPlayButton:SetAlpha( 1.0 )
greenPlayButton = FCView:New( "greenPlayButton", "PlayView" )
greenPlayButton:SetIntegerProperty( "color", kGreenPlayButton )
greenPlayButton:SetStringProperty( "imageFilename", "Assets/Images/QuadGreen.png" )
greenPlayButton:SetStringProperty( "imagePressedFilename", "Assets/Images/QuadGreenPressed.png" )
greenPlayButton:SetAlpha( 1.0 )
yellowPlayButton = FCView:New( "yellowPlayButton", "PlayView" )
yellowPlayButton:SetIntegerProperty( "color", kYellowPlayButton )
yellowPlayButton:SetStringProperty( "imageFilename", "Assets/Images/QuadYellow.png" )
yellowPlayButton:SetStringProperty( "imagePressedFilename", "Assets/Images/QuadYellowPressed.png" )
yellowPlayButton:SetAlpha( 1.0 )
bluePlayButton = FCView:New( "bluePlayButton", "PlayView" )
bluePlayButton:SetIntegerProperty( "color", kBluePlayButton )
bluePlayButton:SetStringProperty( "imageFilename", "Assets/Images/QuadBlue.png" )
bluePlayButton:SetStringProperty( "imagePressedFilename", "Assets/Images/QuadBluePressed.png" )
bluePlayButton:SetAlpha( 1.0 )
magentaPlayButton = FCView:New( "magentaPlayButton", "PlayView" )
magentaPlayButton:SetIntegerProperty( "color", kMagentaPlayButton )
magentaPlayButton:SetStringProperty( "imageFilename", "Assets/Images/QuadMagenta.png" )
magentaPlayButton:SetStringProperty( "imagePressedFilename", "Assets/Images/QuadMagentaPressed.png" )
magentaPlayButton:SetAlpha( 1.0 )
cyanPlayButton = FCView:New( "cyanPlayButton", "PlayView" )
cyanPlayButton:SetIntegerProperty( "color", kCyanPlayButton )
cyanPlayButton:SetStringProperty( "imageFilename", "Assets/Images/QuadCyan.png" )
cyanPlayButton:SetStringProperty( "imagePressedFilename", "Assets/Images/QuadCyanPressed.png" )
cyanPlayButton:SetAlpha( 1.0 )
backButton = FCView:New( "backButton", "ButtonView" )
backButton:SetAlpha( 1.0 )
retryButton = FCView:New( "retryButton", "ButtonView" )
retryButton:SetAlpha( 1.0 )
tweetButton = FCView:New( "tweetButton", "ButtonView" )
tweetButton:SetAlpha( 1.0 )
gameCenterButton = FCView:New( "gameCenterButton", "ButtonView" )
gameCenterButton:SetAlpha( 1.0 )
highScoreLabel = FCView:New( "highScoreLabel", "LabelView" )
highScoreLabel:SetText( kText_HighScore )
clockView = FCView:New( "clockView", "ClockView" )
clockView:SetStringProperty( "backgroundImage", "Assets/Images/ClockRim.png" )
end
local function DestroyViews()
titleLabel:Destroy( )
classicButton:Destroy( )
sixButton:Destroy( )
shuffleButton:Destroy( )
multiButton:Destroy( )
madnessButtonDestroy( )
quitButton:Destroy( )
scoreLabel:Destroy( )
redPlayButton:Destroy( )
greenPlayButton:Destroy( )
yellowPlayButton:Destroy( )
bluePlayButton:Destroy( )
magentaPlayButton:Destroy( )
cyanPlayButton:Destroy( )
backButton:Destroy( )
retryButton:Destroy( )
tweetButton:DestroyView( )
clockView:Destroy( )
end
------------------------------------------------------------------------------------------
function FCApp.ColdBoot()
FCApp.ShowStatusBar( false )
FCStats.Inc( "numBoots" )
FCPersistentData.Save()
math.randomseed( os.time() )
FCViewManager.SetScreenAspectRatio( 7, 10 ) -- portrait, mid way between iPad and iPhone
randomGenerator = FCRandom.New()
end
function FCApp.WarmBoot()
GameAppDelegate.ShowAdBanner()
FCPhaseManager.AddPhaseToQueue("FrontEnd") -- kick off game
-- High scores
FCPersistentData.Load()
if FCPersistentData.GetNumber( kGameHighScoreClassic ) == nil then
FCPersistentData.SetNumber( kGameHighScoreClassic, 0 )
end
if FCPersistentData.GetNumber( kGameHighScoreSix ) == nil then
FCPersistentData.SetNumber( kGameHighScoreSix, 0 )
end
if FCPersistentData.GetNumber( kGameHighScoreShuffle ) == nil then
FCPersistentData.SetNumber( kGameHighScoreShuffle, 0 )
end
if FCPersistentData.GetNumber( kGameHighScoreMulti ) == nil then
FCPersistentData.SetNumber( kGameHighScoreMulti, 0 )
end
if FCPersistentData.GetNumber( kGameHighScoreMadness ) == nil then
FCPersistentData.SetNumber( kGameHighScoreMadness, 0 )
end
FCPersistentData.Save()
FCPersistentData.Print()
FCApp.SetBackgroundColor( kBlackColor )
CreateViews()
InitialiseAudio()
FCNewThread( BackgroundFXThread )
end
function BackgroundFXThread()
end
function FCApp.WillResignActive()
end
function FCApp.DidBecomeActive()
if backgroundView then
RandomBackgroundImage()
end
end
function FCApp.DidEnterBackground()
end
function FCApp.WillEnterForeground()
end
function FCApp.WillTerminate()
ShutdownAudio()
DestroyViews()
end
function FCApp.SupportsPortrait()
return true;
end
function FCApp.SupportsLandscape()
return false;
end
|
local test = {}
local json = require('arken.json')
local Class = require('arken.oop.Class')
local Adapter = require('arken.ActiveRecord.SqliteAdapter')
local SqliteTypes = Class.new("SqliteTypes", "ActiveRecord")
SqliteTypes.tableName = 'sqlit_adapter_types'
test.beforeAll = function()
ActiveRecord.reset()
ActiveRecord.config = "config/active_record_sqlite.json"
local sql = [[
CREATE TABLE IF NOT EXISTS sqlit_adapter_types (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(250), observation TEXT,
created_at timestamp, updated_at timestamp, total REAL, cancel TINYINT,
cancel_default_true TINYINT default 1, cancel_default_false TINYINT default 0, birthday date,
date_meeting datetime, last_access timestamp, last_hour time, sub_total double, frete float,
observation_with_default TEXT default 'hello !!!', total_with_default REAL DEFAULT 135.35,
timestamp_with_default timestamp default '2015-03-11 13:35:10',
datetime_with_default datetime default '2016-05-29 14:50:30',
date_with_default date default '2015-03-15', time_with_default time default '14:50:30'
)]]
SqliteTypes.adapter():execute(sql)
end
test.before = function()
ActiveRecord.begin()
end
test.after = function()
ActiveRecord.rollback()
end
test.afterAll = function()
ActiveRecord.config = nil
end
test.should_return_table = function()
local columns = SqliteTypes.columns()
assert(type(columns) == 'table')
end
test.should_return_type = function()
local columns = SqliteTypes.columns()
assert(columns.id.format == 'number', columns.id.format)
assert(columns.name.format == 'string', columns.name.format)
assert(columns.total.format == 'number', columns.total.format)
assert(columns.observation.format == 'string', columns.observation.format)
assert(columns.created_at.format == 'timestamp', columns.created_at.format)
assert(columns.cancel.format == 'boolean', columns.cancel.format)
assert(columns.birthday.format == 'date', columns.birthday.format)
assert(columns.date_meeting.format == 'datetime', columns.date_meeting.format)
assert(columns.last_access.format == 'timestamp', columns.last_access.format)
assert(columns.sub_total.format == 'number', columns.sub_total.format)
assert(columns.frete.format == 'number', columns.frete.format)
end
test.should_return_not_null = function()
local columns = SqliteTypes.columns()
assert(columns.id.format == 'number', json.encode(columns.id))
assert(columns.id.notNull == true, json.encode(columns.id))
end
test.should_error_if_format_not_exists = function()
local adapter = Adapter.new()
local status, message = pcall(Adapter.parserFormat, adapter, 'unknow_type')
assert( status == false )
assert( message:contains('format_type: unknow_type not resolved') == true, message )
end
test.should_default_boolean_true = function()
local columns = SqliteTypes.columns()
assert(columns.cancel_default_true.format == 'boolean', columns.cancel_default_true.format)
assert(columns.cancel_default_true.default == true, tostring(columns.cancel_default_true.default))
end
test.should_default_boolean_false = function()
local columns = SqliteTypes.columns()
assert(columns.cancel_default_false.format == 'boolean', columns.cancel_default_false.format)
assert(columns.cancel_default_false.default == false, tostring(columns.cancel_default_false.default))
end
test.should_text_with_default = function()
local columns = SqliteTypes.columns()
assert(columns.observation_with_default.format == 'string', columns.observation_with_default.format)
assert(columns.observation_with_default.default == "hello !!!", tostring(columns.observation_with_default.default))
end
test.should_save_text_with_default = function()
local value = SqliteTypes.new{ name = 'John' }
value:save()
assert( value.observation_with_default == 'hello !!!' )
end
test.should_number_with_default = function()
local columns = SqliteTypes.columns()
assert(columns.total_with_default.format == 'number', columns.total_with_default.format)
assert(columns.total_with_default.default == 135.35, tostring(columns.total_with_default.default))
end
test.should_timestamp_with_default = function()
local columns = SqliteTypes.columns()
assert(columns.timestamp_with_default.format == 'timestamp', columns.timestamp_with_default.format)
assert(columns.timestamp_with_default.default == '2015-03-11 13:35:10', tostring(columns.timestamp_with_default.default))
end
test.should_datetime_with_default = function()
local columns = SqliteTypes.columns()
assert(columns.datetime_with_default.format == 'datetime', columns.datetime_with_default.format)
assert(columns.datetime_with_default.default == '2016-05-29 14:50:30', tostring(columns.datetime_with_default.default))
end
test.should_date_with_default = function()
local columns = SqliteTypes.columns()
assert(columns.date_with_default.format == 'date', columns.date_with_default.format)
assert(columns.date_with_default.default == '2015-03-15', tostring(columns.date_with_default.default))
end
test.should_datetime_with_default = function()
local columns = SqliteTypes.columns()
assert(columns.time_with_default.format == 'time', columns.time_with_default.format)
assert(columns.time_with_default.default == '14:50:30', tostring(columns.time_with_default.default))
end
test.should_return_primary_key_flag = function()
local columns = SqliteTypes.columns()
assert(columns.id.primaryKey == true, 'primary key not found')
assert(columns.name.primaryKey == false, 'name is not primary key')
end
return test
|
#!/usr/bin/env lua
-- MoonVulkan example: Custom allocator.
glfw = require("moonglfw")
vk = require("moonvulkan")
-- 1) Import the allocator module, and get the light userdata
allocator = require("allocator")
allocatorLUD = allocator.get()
allocator.trace(true)
if not glfw.vulkan_supported() then
error("MoonGLFW was not compiled with Vulkan support")
end
extension_names = glfw.get_required_instance_extensions()
-- 2) Pass the allocator to the instance creating function:
instance = vk.create_instance({ enabled_extension_names = extension_names }, allocatorLUD)
glfw.window_hint('client api', 'no api')
window = glfw.create_window(640, 480, "My first GLFW/Vulkan window")
-- 3) Pass the allocator to the surface creating function (MoonGLFW):
surfaceRAW = glfw.create_window_surface(window, instance:raw(), allocatorLUD)
-- 4) We need to pass it also to created_surface(), so that MoonVulkan
-- will use it instead of NULL when destroying the surface.
surface = vk.created_surface(instance, surfaceRAW, allocatorLUD)
--[[ Event loop:
while not glfw.window_should_close(window) do
glfw.poll_events()
end
--]]
|
-- This is the editbox module from Chatter by Antiarc
if not Prat.BN_CHAT then return end -- Requires 3.3.5
Prat:AddModuleToLoad(function()
local PRAT_MODULE = Prat:RequestModuleName("Editbox")
if PRAT_MODULE == nil then
return
end
local mod = Prat:NewModule(PRAT_MODULE, "AceHook-3.0")
local PL = mod.PL
--[===[@debug@
PL:AddLocale(PRAT_MODULE, "enUS", {
["Editbox"] = true,
["Editbox options."] = true,
["Top"] = true,
["Bottom"] = true,
["Free-floating"] = true,
["Free-floating, Locked"] = true,
["Background texture"] = true,
["Border texture"] = true,
["Background color"] = true,
["Border color"] = true,
["Background Inset"] = true,
["Tile Size"] = true,
["Edge Size"] = true,
["Attach to..."] = true,
["Attach edit box to..."] = true,
["Color border by channel"] = true,
["Sets the frame's border color to the color of your currently active channel"] = true,
["Use Alt key for cursor movement"] = true,
["Requires the Alt key to be held down to move the cursor in chat"] = true,
["Font"] = true,
currently_broken_alt_behavior = "Arrow key behaviour broken in current WoW client,\n\nUse ALT-UP and ALT-DOWN instead of just UP DOWN to access history",
["Select the font to use for the edit box"] = true,
})
--@end-debug@]===]
-- These Localizations are auto-generated. To help with localization
-- please go to http://www.wowace.com/projects/prat-3-0/localization/
--@non-debug@
do
local L
L=
{
["Editbox"] = {
["Attach edit box to..."] = true,
["Attach to..."] = true,
["Background color"] = true,
["Background Inset"] = true,
["Background texture"] = true,
["Border color"] = true,
["Border texture"] = true,
["Bottom"] = true,
["Color border by channel"] = true,
["currently_broken_alt_behavior"] = [=[Arrow key behaviour broken in current WoW client,
Use ALT-UP and ALT-DOWN instead of just UP DOWN to access history]=],
["Edge Size"] = true,
["Editbox"] = true,
["Editbox options."] = true,
["Font"] = true,
["Free-floating"] = true,
["Free-floating, Locked"] = true,
["Requires the Alt key to be held down to move the cursor in chat"] = true,
["Select the font to use for the edit box"] = true,
["Sets the frame's border color to the color of your currently active channel"] = true,
["Tile Size"] = true,
["Top"] = true,
["Use Alt key for cursor movement"] = true,
}
}
PL:AddLocale(PRAT_MODULE, "enUS",L)
L=
{
["Editbox"] = {
["Attach edit box to..."] = "Définit la position de la boîte d'édition.",
["Attach to..."] = "Position",
["Background color"] = "Couleur du fond",
["Background Inset"] = "Marge du fond",
["Background texture"] = "Texture du fond",
["Border color"] = "Couleur de la bordure",
["Border texture"] = "Texture de la bordure",
["Bottom"] = "Bas",
["Color border by channel"] = "Colorier avec le canal",
--[[Translation missing --]]
--[[ ["currently_broken_alt_behavior"] = "",--]]
["Edge Size"] = "Taille de la bordure",
["Editbox"] = "Boite d'édition",
["Editbox options."] = "Options de la boite d'édition.",
["Font"] = "Police d'écriture",
["Free-floating"] = "Flottante",
["Free-floating, Locked"] = "Flottante, verrouillée",
["Requires the Alt key to be held down to move the cursor in chat"] = "Requiert de maintenir la touche Alt enfoncée pour déplacer le curseur lorsque vous écrivez un message.",
["Select the font to use for the edit box"] = "Définit la police du texte dans la boîte d'édition.",
["Sets the frame's border color to the color of your currently active channel"] = "Définit la couleur de la bordure avec la couleur du canal actif.",
["Tile Size"] = "Taille du fond",
["Top"] = "Haut",
["Use Alt key for cursor movement"] = "Curseur avec Alt",
}
}
PL:AddLocale(PRAT_MODULE, "frFR",L)
L=
{
["Editbox"] = {
["Attach edit box to..."] = "Befestige Eingabefeld an ...",
["Attach to..."] = "Befestige an ...",
["Background color"] = "Hintergrundfarbe",
["Background Inset"] = "Hintergrundbild",
["Background texture"] = "Hintergrundtextur",
["Border color"] = "Randfarbe",
["Border texture"] = "Randtextur",
["Bottom"] = "Unten",
["Color border by channel"] = "Rand einfärben nach Kanal",
["currently_broken_alt_behavior"] = [=[Das Verhalten der Pfeiltasten im Chat ist im aktuellen WoW-Client defekt,
verwende stattdessen Alt+Hoch und Alt+Runter, um durch den Chatverlauf zu scrollen.]=],
["Edge Size"] = "Kantengröße",
["Editbox"] = "Eingabefeld",
["Editbox options."] = "Optionen für das Eingabefeld.",
["Font"] = "Schriftart",
["Free-floating"] = "Freischwebend",
["Free-floating, Locked"] = "Freischwebend, fixiert",
["Requires the Alt key to be held down to move the cursor in chat"] = "Das Drücken der Alt-Taste wird benötigt, um den Cursor (Zeiger) im Chat zu bewegen.",
["Select the font to use for the edit box"] = "Schriftart auswählen, die im Eingabefeld verwendet wird.",
["Sets the frame's border color to the color of your currently active channel"] = "Wendet die Randfarbe des Rahmens auf die Farbe deines gegenwärtig aktiven Kanals an.",
["Tile Size"] = "Kachelgröße",
["Top"] = "Oben",
["Use Alt key for cursor movement"] = "Benutze Alt-Taste für Cursor-Bewegung",
}
}
PL:AddLocale(PRAT_MODULE, "deDE",L)
L=
{
["Editbox"] = {
["Attach edit box to..."] = "입력창 붙이기...",
["Attach to..."] = "붙이기...",
["Background color"] = "배경 색상",
["Background Inset"] = "배경 삽입",
["Background texture"] = "배경 무늬",
["Border color"] = "테두리 색상",
["Border texture"] = "테두리 무늬",
["Bottom"] = "아래",
["Color border by channel"] = "채널에 의한 테두리 색상",
["currently_broken_alt_behavior"] = [=[화살표 키 동작은 현재 WoW 클라이언트에서 작동하지 않습니다.
기록 접근에 위쪽 아래쪽 키 대신 ALT-위와 ALT-아래 키를 사용하세요]=],
["Edge Size"] = "모서리 크기",
["Editbox"] = "대화 입력창",
["Editbox options."] = "대화 입력창을 설정합니다.",
["Font"] = "글꼴",
["Free-floating"] = "자유로운 이동",
["Free-floating, Locked"] = "자유로운 이동, 잠금",
["Requires the Alt key to be held down to move the cursor in chat"] = "대화 입력창 커서 이동에 Alt 키를 사용합니다",
["Select the font to use for the edit box"] = "대화 입력창에 사용할 글꼴 선택",
["Sets the frame's border color to the color of your currently active channel"] = "대화 입력창 테두리 색상을 현재 채널 색상으로 설정",
["Tile Size"] = "타일 크기",
["Top"] = "위",
["Use Alt key for cursor movement"] = "커서 이동에 Alt 키 사용",
}
}
PL:AddLocale(PRAT_MODULE, "koKR",L)
L=
{
["Editbox"] = {
--[[Translation missing --]]
--[[ ["Attach edit box to..."] = "",--]]
--[[Translation missing --]]
--[[ ["Attach to..."] = "",--]]
--[[Translation missing --]]
--[[ ["Background color"] = "",--]]
--[[Translation missing --]]
--[[ ["Background Inset"] = "",--]]
--[[Translation missing --]]
--[[ ["Background texture"] = "",--]]
--[[Translation missing --]]
--[[ ["Border color"] = "",--]]
--[[Translation missing --]]
--[[ ["Border texture"] = "",--]]
--[[Translation missing --]]
--[[ ["Bottom"] = "",--]]
--[[Translation missing --]]
--[[ ["Color border by channel"] = "",--]]
--[[Translation missing --]]
--[[ ["currently_broken_alt_behavior"] = "",--]]
--[[Translation missing --]]
--[[ ["Edge Size"] = "",--]]
--[[Translation missing --]]
--[[ ["Editbox"] = "",--]]
--[[Translation missing --]]
--[[ ["Editbox options."] = "",--]]
--[[Translation missing --]]
--[[ ["Font"] = "",--]]
--[[Translation missing --]]
--[[ ["Free-floating"] = "",--]]
--[[Translation missing --]]
--[[ ["Free-floating, Locked"] = "",--]]
--[[Translation missing --]]
--[[ ["Requires the Alt key to be held down to move the cursor in chat"] = "",--]]
--[[Translation missing --]]
--[[ ["Select the font to use for the edit box"] = "",--]]
--[[Translation missing --]]
--[[ ["Sets the frame's border color to the color of your currently active channel"] = "",--]]
--[[Translation missing --]]
--[[ ["Tile Size"] = "",--]]
--[[Translation missing --]]
--[[ ["Top"] = "",--]]
--[[Translation missing --]]
--[[ ["Use Alt key for cursor movement"] = "",--]]
}
}
PL:AddLocale(PRAT_MODULE, "esMX",L)
L=
{
["Editbox"] = {
["Attach edit box to..."] = "Закрепить поле ввода...",
["Attach to..."] = "Закрепить...",
["Background color"] = "Цвет фона",
["Background Inset"] = "Фоновая врезка",
["Background texture"] = "Текстура фона",
["Border color"] = "Цвет границ",
["Border texture"] = "Текстура границы",
["Bottom"] = "Внизу",
["Color border by channel"] = "Окраска границы по цвету канала",
["currently_broken_alt_behavior"] = [=[Поведение стрелок сломано в текущей версии WoW
Используйте ALT-СтрелкаВверх и ALT-СтрелкаВниз вместо просто стрелок вверх и вниз чтобы открыть историю]=],
["Edge Size"] = "Размер контура",
["Editbox"] = "Поле ввода",
["Editbox options."] = "Настройки поля ввода.",
["Font"] = "Шрифт",
["Free-floating"] = "Свободно",
["Free-floating, Locked"] = "Свободно, заблокировано",
["Requires the Alt key to be held down to move the cursor in chat"] = "Для перемещения курсора в чате требуется нажатая клавиша Alt",
["Select the font to use for the edit box"] = "Выбор шрифта для области редактирования",
["Sets the frame's border color to the color of your currently active channel"] = "Установить окраску границы в цвет вашего активного канала",
["Tile Size"] = "Размер мозаики",
["Top"] = "Вверху",
["Use Alt key for cursor movement"] = "Исп. кливишу Alt для перемещения курсора",
}
}
PL:AddLocale(PRAT_MODULE, "ruRU",L)
L=
{
["Editbox"] = {
["Attach edit box to..."] = "把输入框附加到……",
["Attach to..."] = "附加到……",
["Background color"] = "背景颜色",
["Background Inset"] = "背景嵌入",
["Background texture"] = "背景纹理",
["Border color"] = "边框颜色",
["Border texture"] = "边框纹理",
["Bottom"] = "底部",
["Color border by channel"] = "频道颜色边框",
["currently_broken_alt_behavior"] = [=[在现在WoW客户端里,方向键的行为已损坏,
使用Alt+上和Alt+下来替代上下键浏览历史]=],
["Edge Size"] = "边缘尺寸",
["Editbox"] = "输入框",
["Editbox options."] = "输入框选项",
["Font"] = "字体",
["Free-floating"] = "自由浮动",
["Free-floating, Locked"] = "自由浮动,锁定",
["Requires the Alt key to be held down to move the cursor in chat"] = "需要在聊天中按住Alt键移动光标",
["Select the font to use for the edit box"] = "选择输入框的字体",
["Sets the frame's border color to the color of your currently active channel"] = "设置边框颜色到你当前激活的频道颜色",
["Tile Size"] = "平铺尺寸",
["Top"] = "顶部",
["Use Alt key for cursor movement"] = "使用Alt键令光标移动",
}
}
PL:AddLocale(PRAT_MODULE, "zhCN",L)
L=
{
["Editbox"] = {
["Attach edit box to..."] = "Anclar la caja de edición a...",
["Attach to..."] = "Anclar a...",
["Background color"] = "Color de fondo",
--[[Translation missing --]]
--[[ ["Background Inset"] = "",--]]
["Background texture"] = "Textura de fondo",
["Border color"] = "Color del borde",
["Border texture"] = "Textura del borde",
["Bottom"] = "Abajo",
["Color border by channel"] = "Color del borde por canal",
--[[Translation missing --]]
--[[ ["currently_broken_alt_behavior"] = "",--]]
["Edge Size"] = "Tamaño del borde",
["Editbox"] = "Caja de edición",
["Editbox options."] = "Opciones de la caja de edición.",
["Font"] = "Fuente",
["Free-floating"] = "Flotar-libre",
["Free-floating, Locked"] = "Flotar-libre, Bloqueado",
["Requires the Alt key to be held down to move the cursor in chat"] = "Requiere la tecla Alt presionada para mover el cursor en el chat",
["Select the font to use for the edit box"] = "Seleccione la fuente a usar para la caja de edición",
["Sets the frame's border color to the color of your currently active channel"] = "Establece el color del borde del marco con el color de su canal actualmente activo",
["Tile Size"] = "Tamaño de mosaico",
["Top"] = "Arriba",
["Use Alt key for cursor movement"] = "Usar la tecla Alt para el desplazamiento del cursor",
}
}
PL:AddLocale(PRAT_MODULE, "esES",L)
L=
{
["Editbox"] = {
["Attach edit box to..."] = "附上編輯框...",
["Attach to..."] = "附上...",
["Background color"] = "背景色彩",
["Background Inset"] = "背景插入",
["Background texture"] = "背景材質",
["Border color"] = "邊緣色彩",
["Border texture"] = "邊緣材質",
["Bottom"] = "底部",
["Color border by channel"] = "顏色邊框由道頻",
--[[Translation missing --]]
--[[ ["currently_broken_alt_behavior"] = "",--]]
["Edge Size"] = "邊框尺寸",
["Editbox"] = "輸入框",
["Editbox options."] = "輸入框選單",
["Font"] = "字型",
["Free-floating"] = "自由浮動",
["Free-floating, Locked"] = "自由浮動, 已鎖定",
--[[Translation missing --]]
--[[ ["Requires the Alt key to be held down to move the cursor in chat"] = "",--]]
["Select the font to use for the edit box"] = "選擇字型使用編輯框",
--[[Translation missing --]]
--[[ ["Sets the frame's border color to the color of your currently active channel"] = "",--]]
["Tile Size"] = "並排尺寸",
["Top"] = "頂部",
["Use Alt key for cursor movement"] = "使用 Alt 鍵游標移動",
}
}
PL:AddLocale(PRAT_MODULE, "zhTW",L)
end
--@end-non-debug@
local mustUseAlt = select(4, _G.GetBuildInfo()) >= 50400
local Media = Prat.Media
local backgrounds, borders, fonts = {}, {}, {}
local CreateFrame = _G.CreateFrame
local max = _G.max
local pairs = _G.pairs
local select = _G.select
local VALID_ATTACH_POINTS = {
TOP = PL["Top"],
BOTTOM = PL["Bottom"],
FREE = PL["Free-floating"],
LOCK = PL["Free-floating, Locked"]
}
local function updateEditBox(method, ...)
for i = 1, NUM_CHAT_WINDOWS do
local f = _G["ChatFrame" .. i .. "EditBox"]
f[method](f, ...)
end
end
Prat:SetModuleOptions(mod, {
name = PL["Editbox"],
desc = PL["Editbox options."],
type = "group",
args = {
background = {
type = "select",
name = PL["Background texture"],
desc = PL["Background texture"],
values = backgrounds,
get = function() return mod.db.profile.background end,
set = function(info, v)
mod.db.profile.background = v
mod:SetBackdrop()
end
},
border = {
type = "select",
name = PL["Border texture"],
desc = PL["Border texture"],
values = borders,
get = function() return mod.db.profile.border end,
set = function(info, v)
mod.db.profile.border = v
mod:SetBackdrop()
end
},
backgroundColor = {
type = "color",
name = PL["Background color"],
desc = PL["Background color"],
hasAlpha = true,
get = function()
local c = mod.db.profile.backgroundColor
return c.r, c.g, c.b, c.a
end,
set = function(info, r, g, b, a)
local c = mod.db.profile.backgroundColor
c.r, c.g, c.b, c.a = r, g, b, a
mod:SetBackdrop()
end
},
borderColor = {
type = "color",
name = PL["Border color"],
desc = PL["Border color"],
hasAlpha = true,
get = function()
local c = mod.db.profile.borderColor
return c.r, c.g, c.b, c.a
end,
set = function(info, r, g, b, a)
local c = mod.db.profile.borderColor
c.r, c.g, c.b, c.a = r, g, b, a
mod:SetBackdrop()
end
},
inset = {
type = "range",
name = PL["Background Inset"],
desc = PL["Background Inset"],
min = 1,
max = 64,
step = 1,
bigStep = 1,
get = function() return mod.db.profile.inset end,
set = function(info, v)
mod.db.profile.inset = v
mod:SetBackdrop()
end
},
tileSize = {
type = "range",
name = PL["Tile Size"],
desc = PL["Tile Size"],
min = 1,
max = 64,
step = 1,
bigStep = 1,
get = function() return mod.db.profile.tileSize end,
set = function(info, v)
mod.db.profile.tileSize = v
mod:SetBackdrop()
end
},
edgeSize = {
type = "range",
name = PL["Edge Size"],
desc = PL["Edge Size"],
min = 1,
max = 64,
step = 1,
bigStep = 1,
get = function() return mod.db.profile.edgeSize end,
set = function(info, v)
mod.db.profile.edgeSize = v
mod:SetBackdrop()
end
},
attach = {
type = "select",
name = PL["Attach to..."],
desc = PL["Attach edit box to..."],
get = function() return mod.db.profile.attach end,
values = VALID_ATTACH_POINTS,
set = function(info, v)
mod.db.profile.attach = v
mod:SetAttach()
end
},
colorByChannel = {
type = "toggle",
name = PL["Color border by channel"],
desc = PL["Sets the frame's border color to the color of your currently active channel"],
get = function()
return mod.db.profile.colorByChannel
end,
set = function(info, v)
mod.db.profile.colorByChannel = v
if v then
mod:RawHook("ChatEdit_UpdateHeader", "SetBorderByChannel", true)
else
if mod:IsHooked("ChatEdit_UpdateHeader") then
mod:Unhook("ChatEdit_UpdateHeader")
local c = mod.db.profile.borderColor
for _, frame in ipairs(mod.frames) do
frame:SetBackdropBorderColor(c.r, c.g, c.b, c.a)
end
end
end
end
},
useAltKey = {
type = "toggle",
name = PL["Use Alt key for cursor movement"],
desc = PL["Requires the Alt key to be held down to move the cursor in chat"],
get = function()
return mod.db.profile.useAltKey
end,
set = function(info, v)
mod.db.profile.useAltKey = v
updateEditBox("SetAltArrowKeyMode", v)
end,
},
font = {
type = "select",
name = PL["Font"],
desc = PL["Select the font to use for the edit box"],
values = fonts,
get = function() return mod.db.profile.font end,
set = function(i, v)
mod.db.profile.font = v
for i = 1, NUM_CHAT_WINDOWS do
local ff = _G["ChatFrame" .. i .. "EditBox"]
local _, s, m = ff:GetFont()
ff:SetFont(Media:Fetch("font", v), s, m)
end
end
},
info = {
name = PL.currently_broken_alt_behavior;
type = "description",
hidden = not mustUseAlt;
order = 1000;
},
},
})
Prat:SetModuleDefaults(mod.name, {
profile = {
on = true,
background = "Blizzard Tooltip",
border = "Blizzard Tooltip",
backgroundColor = { r = 0, g = 0, b = 0, a = 1 },
borderColor = { r = 1, g = 1, b = 1, a = 1 },
inset = 3,
edgeSize = 12,
tileSize = 16,
height = 22,
attach = "BOTTOM",
colorByChannel = true,
useAltKey = false,
font = (function()
for i = 1, NUM_CHAT_WINDOWS do
local ff = _G["ChatFrame" .. i .. "EditBox"]
local f = ff:GetFont()
for k, v in pairs(Media:HashTable("font")) do
if v == f then return k end
end
end
end)()
}
})
function mod:LibSharedMedia_Registered()
for k, v in pairs(Media:List("background")) do
backgrounds[v] = v
end
for k, v in pairs(Media:List("border")) do
borders[v] = v
end
for k, v in pairs(Media:List("font")) do
fonts[v] = v
end
end
Prat:SetModuleInit(mod,
function(self)
Media.RegisterCallback(mod, "LibSharedMedia_Registered")
self.frames = {}
self:LibSharedMedia_Registered()
for i = 1, NUM_CHAT_WINDOWS do
local parent = _G["ChatFrame" .. i .. "EditBox"]
local frame = CreateFrame("Frame", nil, parent)
frame:SetFrameStrata("DIALOG")
frame:SetFrameLevel(parent:GetFrameLevel() - 1)
frame:SetAllPoints(parent)
frame:Hide()
parent.lDrag = CreateFrame("Frame", nil, parent)
parent.lDrag:SetWidth(15)
parent.lDrag:SetPoint("TOPLEFT", parent, "TOPLEFT")
parent.lDrag:SetPoint("BOTTOMLEFT", parent, "BOTTOMLEFT")
parent.rDrag = CreateFrame("Frame", nil, parent)
parent.rDrag:SetWidth(15)
parent.rDrag:SetPoint("TOPRIGHT", parent, "TOPRIGHT")
parent.rDrag:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT")
parent.lDrag.left = true
parent.frame = frame
tinsert(self.frames, frame)
end
end)
local function OnArrowPressed(self, key)
if #self.history_lines == 0 then
return
end
if key == "DOWN" then
self.history_index = self.history_index - 1
if self.history_index < 1 then
self.history_index = #self.history_lines
end
elseif key == "UP" then
self.history_index = self.history_index + 1
if self.history_index > #self.history_lines then
self.history_index = 1
end
else
return -- We don't want to interfere with LEFT/RIGHT because the tab-complete stuff might use it; we're already killing the other two.
end
self:SetText(self.history_lines[self.history_index])
end
local function enableArrowKeys(e)
e.history_lines = e.history_lines or {}
e.history_index = e.history_index or 0
e:HookScript("OnArrowPressed", OnArrowPressed)
end
function mod:Prat_FramesUpdated(info, name, chatFrame, ...)
local i = chatFrame:GetID()
local f = _G["ChatFrame" .. i .. "EditBox"]
_G["ChatFrame" .. i .. "EditBoxLeft"]:Hide()
_G["ChatFrame" .. i .. "EditBoxRight"]:Hide()
_G["ChatFrame" .. i .. "EditBoxMid"]:Hide()
_G["ChatFrame" .. i .. "EditBoxFocusLeft"]:SetTexture(nil)
_G["ChatFrame" .. i .. "EditBoxFocusRight"]:SetTexture(nil)
_G["ChatFrame" .. i .. "EditBoxFocusMid"]:SetTexture(nil)
f:Hide()
self.frames[i] = f
self.frames[i]:Show()
local font, s, m = f:GetFont()
f:SetFont(Media:Fetch("font", self.db.profile.font), s, m)
local header = _G[f:GetName() .. "Header"]
local font, s, m = header:GetFont()
header:SetFont(Media:Fetch("font", self.db.profile.font), s, m)
f:SetAltArrowKeyMode(mod.db.profile.useAltKey and 1 or nil)
if (not mod.db.profile.useAltKey) then
enableArrowKeys(f)
end
self:SetBackdrop()
self:UpdateHeight()
end
function mod:OnModuleEnable()
self:LibSharedMedia_Registered()
for i = 1, NUM_CHAT_WINDOWS do
local f = _G["ChatFrame" .. i .. "EditBox"]
_G["ChatFrame" .. i .. "EditBoxLeft"]:Hide()
_G["ChatFrame" .. i .. "EditBoxRight"]:Hide()
_G["ChatFrame" .. i .. "EditBoxMid"]:Hide()
_G["ChatFrame" .. i .. "EditBoxFocusLeft"]:SetTexture(nil)
_G["ChatFrame" .. i .. "EditBoxFocusRight"]:SetTexture(nil)
_G["ChatFrame" .. i .. "EditBoxFocusMid"]:SetTexture(nil)
f:Hide()
-- Prevent an error in FloatingChatFrame FCF_FadeOutChatFrame() (blizz bug)
f:SetAlpha(f:GetAlpha() or 0)
self.frames[i]:Show()
local font, s, m = f:GetFont()
f:SetFont(Media:Fetch("font", self.db.profile.font), s, m)
local header = _G[f:GetName() .. "Header"]
local font, s, m = header:GetFont()
header:SetFont(Media:Fetch("font", self.db.profile.font), s, m)
f:SetAltArrowKeyMode(mod.db.profile.useAltKey and 1 or nil)
if (not mod.db.profile.useAltKey) then
enableArrowKeys(f)
end
end
self:SetBackdrop()
self:SetAttach(nil, self.db.profile.editX, self.db.profile.editY, self.db.profile.editW)
self:SecureHook("ChatEdit_DeactivateChat")
self:SecureHook("ChatEdit_SetLastActiveWindow")
self:SetBackdrop()
self:UpdateHeight()
if self.db.profile.colorByChannel then
self:RawHook("ChatEdit_UpdateHeader", "SetBorderByChannel", true)
end
self:SecureHook("FCF_Tab_OnClick")
Prat.RegisterChatEvent(self, Prat.Events.FRAMES_UPDATED)
end
function mod:FCF_Tab_OnClick(frame, button)
if self.db.profile.attach == "TOP" and GetCVar("chatStyle") ~= "classic" then
local chatFrame = _G["ChatFrame" .. frame:GetID()];
ChatEdit_DeactivateChat(chatFrame.editBox)
end
end
function mod:OnModuleDisable()
for i = 1, NUM_CHAT_WINDOWS do
local f = _G["ChatFrame" .. i .. "EditBox"]
_G["ChatFrame" .. i .. "EditBoxLeft"]:Show()
_G["ChatFrame" .. i .. "EditBoxRight"]:Show()
_G["ChatFrame" .. i .. "EditBoxMid"]:Show()
f:SetAltArrowKeyMode(true)
f:EnableMouse(true)
f.frame:Hide()
self:SetAttach("BOTTOM")
end
end
function mod:GetDescription()
return PL["Editbox options."]
end
-- changed the Hide to SetAlpha(0), the new ChatSystem OnHide handlers go though some looping
-- when in IM style and Classic style, cause heavy delays on the chat edit box.
function mod:ChatEdit_SetLastActiveWindow(frame)
if frame:IsShown() then
frame:SetAlpha(0)
else
frame:SetAlpha(1)
end
frame:EnableMouse(true)
end
function mod:ChatEdit_DeactivateChat(frame)
if frame:IsShown() then
frame:SetAlpha(0)
frame:EnableMouse(false)
end
end
function mod:SetBackdrop()
for _, frame in ipairs(self.frames) do
frame:SetBackdrop({
bgFile = Media:Fetch("background", self.db.profile.background),
edgeFile = Media:Fetch("border", self.db.profile.border),
tile = true,
tileSize = self.db.profile.tileSize,
edgeSize = self.db.profile.edgeSize,
insets = { left = self.db.profile.inset, right = self.db.profile.inset, top = self.db.profile.inset,
bottom = self.db.profile.inset }
})
local c = self.db.profile.backgroundColor
frame:SetBackdropColor(c.r, c.g, c.b, c.a)
local c = self.db.profile.borderColor
frame:SetBackdropBorderColor(c.r, c.g, c.b, c.a)
end
end
function mod:SetBorderByChannel(...)
self.hooks.ChatEdit_UpdateHeader(...)
for index, frame in ipairs(self.frames) do
local f = _G["ChatFrame" .. index .. "EditBox"]
local attr = f:GetAttribute("chatType")
if attr == "CHANNEL" then
local chan = f:GetAttribute("channelTarget")
if chan == 0 then
local c = self.db.profile.borderColor
frame:SetBackdropBorderColor(c.r, c.g, c.b, c.a)
elseif chan then
local r, g, b = GetMessageTypeColor("CHANNEL" .. chan)
frame:SetBackdropBorderColor(r, g, b, 1)
end
else
local r, g, b = GetMessageTypeColor(attr)
frame:SetBackdropBorderColor(r, g, b, 1)
end
end
end
do
local function startMoving(self)
self:StartMoving()
end
local function stopMoving(self)
self:StopMovingOrSizing()
mod.db.profile.editX = self:GetLeft()
mod.db.profile.editY = self:GetTop()
mod.db.profile.editW = self:GetRight() - self:GetLeft()
end
local cfHeight
local function constrainHeight(self)
self:GetParent():SetHeight(cfHeight)
end
local function startDragging(self)
cfHeight = self:GetParent():GetHeight()
self:GetParent():StartSizing(not self.left and "TOPRIGHT" or "TOPLEFT")
self:SetScript("OnUpdate", constrainHeight)
end
local function stopDragging(self)
local parent = self:GetParent()
parent:StopMovingOrSizing()
self:SetScript("OnUpdate", nil)
mod.db.profile.editX = parent:GetLeft()
mod.db.profile.editY = parent:GetTop()
mod.db.profile.editW = parent:GetWidth()
end
function mod:SetAttach(val, x, y, w)
for i = 1, NUM_CHAT_WINDOWS do
local frame = _G["ChatFrame" .. i .. "EditBox"]
local val = val or self.db.profile.attach
if not x and val == "FREE" then
if self.db.profile.editX and self.db.profile.editY then
x, y, w = self.db.profile.editX, self.db.profile.editY, self.db.profile.editW
else
x, y, w = frame:GetLeft(), frame:GetTop(), max(frame:GetWidth(), (frame:GetRight() or 0) - (frame:GetLeft() or 0))
end
end
if not w or w < 10 then w = 100 end
frame:ClearAllPoints()
if val ~= "FREE" then
frame:SetMovable(false)
frame.lDrag:EnableMouse(false)
frame.rDrag:EnableMouse(false)
frame:SetScript("OnMouseDown", nil)
frame:SetScript("OnMouseUp", nil)
frame.lDrag:EnableMouse(false)
frame.rDrag:EnableMouse(false)
frame.lDrag:SetScript("OnMouseDown", nil)
frame.rDrag:SetScript("OnMouseDown", nil)
frame.lDrag:SetScript("OnMouseUp", nil)
frame.rDrag:SetScript("OnMouseUp", nil)
end
if val == "TOP" then
frame:SetPoint("BOTTOMLEFT", frame.chatFrame, "TOPLEFT", 0, 3)
frame:SetPoint("BOTTOMRIGHT", frame.chatFrame, "TOPRIGHT", 0, 3)
elseif val == "BOTTOM" then
frame:SetPoint("TOPLEFT", frame.chatFrame, "BOTTOMLEFT", 0, -8)
frame:SetPoint("TOPRIGHT", frame.chatFrame, "BOTTOMRIGHT", 0, -8)
elseif val == "FREE" then
frame:EnableMouse(true)
frame:SetMovable(true)
frame:SetResizable(true)
frame:SetScript("OnMouseDown", startMoving)
frame:SetScript("OnMouseUp", stopMoving)
frame:SetWidth(w)
frame:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", x, y)
frame:SetMinResize(40, 1)
frame.lDrag:EnableMouse(true)
frame.rDrag:EnableMouse(true)
frame.lDrag:SetScript("OnMouseDown", startDragging)
frame.rDrag:SetScript("OnMouseDown", startDragging)
frame.lDrag:SetScript("OnMouseUp", stopDragging)
frame.rDrag:SetScript("OnMouseUp", stopDragging)
elseif val == "LOCK" then
frame:SetWidth(self.db.profile.editW or w)
frame:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", self.db.profile.editX or x, self.db.profile.editY or y)
end
end
end
end
function mod:UpdateHeight()
for i, frame in ipairs(self.frames) do
local ff = _G["ChatFrame" .. i .. "EditBox"]
ff:SetHeight(mod.db.profile.height)
end
end
return
end) -- Prat:AddModuleToLoad
|
--[[
Code originally referenced from AyrA.
Modified greatly and improved a lot by Vas.
If you use this, please make sure to mention us somewhere like in your readme.
]]--
-- User Settings
local BASE_KIT = settings.global["basic-kit-base"].value
local EQUIPME = settings.global["basic-kit-equipment"].value
local POWER_KIT = settings.global["basic-kit-power"].value
local MORE_SUBS = settings.global["basic-kit-moresubs"].value
local ADD_EASY = settings.global["basic-kit-easy"].value
local ADD_MODULES = settings.global["basic-kit-module"].value
local ADD_ROBOTS = settings.global["basic-kit-robot"].value
local ADD_ROCHEST = settings.global["basic-kit-robotchests"].value
local ADD_CAR = settings.global["basic-kit-car"].value
local PERFECTIONIST = settings.global["basic-kit-perfectionist"].value
local MODU_ROBO = settings.global["basic-kit-modularrobots"].value
local START_EQUIP = settings.global["basic-kit-start-string"].value
local START_TECH = settings.global["basic-kit-start-research-string"].value
local DISASABLE_EQUIP = settings.global["basic-kit-disable-equipment-string"].value
local DISABLE_TECH = settings.global["basic-kit-disable-research-string"].value
--Start the kit table.
local kit = {
{ name = "iron-plate", count = 4}
}
-- Add stuff to inventory depending on the settings
-- Lets create a splitter function so we can split our additional strings properly.
local function split(inputstr, sep)
if sep == nil then sep = "%s" end
t={} i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end return t
end
--[[Choose Mining Equipment]]--
if BASE_KIT == "Base" then
table.insert(kit,{name="burner-mining-drill",count=1})
table.insert(kit,{name="stone-furnace",count=1})
elseif BASE_KIT == "Electric" then
table.insert(kit,{name="electric-mining-drill",count=1})
table.insert(kit,{name="medium-electric-pole",count=1})
table.insert(kit,{name="stone-furnace",count=1})
elseif BASE_KIT == "Easy Electric" then
table.insert(kit,{name="electric-mining-drill",count=2})
table.insert(kit,{name="medium-electric-pole",count=5})
table.insert(kit,{name="stone-furnace",count=3})
elseif BASE_KIT == "Mega Electric" then
table.insert(kit,{name="electric-mining-drill",count=4})
table.insert(kit,{name="medium-electric-pole",count=20})
table.insert(kit,{name="stone-furnace",count=6})
elseif BASE_KIT == "Epic Electric" then
table.insert(kit,{name="electric-mining-drill",count=8})
table.insert(kit,{name="electric-furnace",count=10})
if MORE_SUBS then
table.insert(kit,{name="substation",count=16})
else
table.insert(kit,{name="substation",count=4})
end
end
--[[Choose your combat starting gear]]--
if EQUIPME == "Civilian" then
table.insert(kit,{name="pistol",count=1})
table.insert(kit,{name="firearm-magazine",count=10})
elseif EQUIPME == "Soldier" then
table.insert(kit,{name="submachine-gun",count=1})
table.insert(kit,{name="shotgun",count=1})
table.insert(kit,{name="piercing-rounds-magazine",count=20})
table.insert(kit,{name="piercing-shotgun-shell",count=20})
elseif EQUIPME == "Rambo" then
table.insert(kit,{name="submachine-gun",count=1})
table.insert(kit,{name="flamethrower",count=1})
table.insert(kit,{name="combat-shotgun",count=1})
table.insert(kit,{name="uranium-rounds-magazine",count=100})
table.insert(kit,{name="flamethrower-ammo",count=50})
table.insert(kit,{name="piercing-shotgun-shell",count=50})
end
--[[Steam or Solar start]]--
if POWER_KIT == "Steam" then
table.insert(kit,{name="offshore-pump",count=1})
table.insert(kit,{name="boiler",count=1})
table.insert(kit,{name="pipe",count=10})
table.insert(kit,{name="steam-engine",count=1})
elseif POWER_KIT == "Solar" then
table.insert(kit,{name="solar-panel",count=6})
table.insert(kit,{name="accumulator",count=3})
if MORE_SUBS then
table.insert(kit,{name="substation",count=8})
else
table.insert(kit,{name="substation",count=2})
end
elseif POWER_KIT == "Super Solar" then
table.insert(kit,{name="solar-panel",count=12})
table.insert(kit,{name="accumulator",count=6})
if MORE_SUBS then
table.insert(kit,{name="substation",count=16})
else
table.insert(kit,{name="substation",count=4})
end
elseif POWER_KIT == "Insane Solar" then
table.insert(kit,{name="solar-panel",count=24})
table.insert(kit,{name="accumulator",count=12})
if MORE_SUBS then
table.insert(kit,{name="substation",count=32})
else
table.insert(kit,{name="substation",count=8})
end
end
--[[Easier Start]]--
if ADD_EASY == "Resources" then
table.insert(kit,{name="iron-plate",count=46})
table.insert(kit,{name="copper-plate",count=50})
elseif ADD_EASY == "Power Armor" then
table.insert(kit,{name="modular-armor",count=1})
table.insert(kit,{name="energy-shield-equipment",count=1})
table.insert(kit,{name="night-vision-equipment",count=1})
table.insert(kit,{name="battery-equipment",count=1})
table.insert(kit,{name="solar-panel-equipment",count=7})
table.insert(kit,{name="exoskeleton-equipment",count=1})
elseif ADD_EASY == "Research Equipment" then
if game.active_mods["timed_technology"] then
table.insert(kit,{name="lab",count=1})
else
table.insert(kit,{name="lab",count=1})
table.insert(kit,{name="automation-science-pack",count=50}) --science-pack-1
table.insert(kit,{name="logistic-science-pack",count=50}) --science-pack-2
table.insert(kit,{name="chemical-science-pack",count=50}) --science-pack-3
end
elseif ADD_EASY == "Power Armor & Resources" then
table.insert(kit,{name="iron-plate",count=46})
table.insert(kit,{name="copper-plate",count=50})
table.insert(kit,{name="modular-armor",count=1})
table.insert(kit,{name="energy-shield-equipment",count=1})
table.insert(kit,{name="night-vision-equipment",count=1})
table.insert(kit,{name="battery-equipment",count=1})
table.insert(kit,{name="solar-panel-equipment",count=7})
table.insert(kit,{name="exoskeleton-equipment",count=1})
elseif ADD_EASY == "All" then
table.insert(kit,{name="iron-plate",count=46})
table.insert(kit,{name="copper-plate",count=50})
table.insert(kit,{name="modular-armor",count=1})
table.insert(kit,{name="energy-shield-equipment",count=1})
table.insert(kit,{name="night-vision-equipment",count=1})
table.insert(kit,{name="battery-equipment",count=1})
table.insert(kit,{name="solar-panel-equipment",count=7})
table.insert(kit,{name="exoskeleton-equipment",count=1})
table.insert(kit,{name="lab",count=1})
table.insert(kit,{name="automation-science-pack",count=50}) --science-pack-1
table.insert(kit,{name="logistic-science-pack",count=50}) --science-pack-2
table.insert(kit,{name="chemical-science-pack",count=50}) --science-pack-3
end
--[[Modules]]--
if ADD_MODULES == "Speed" then
table.insert(kit,{name="speed-module-3",count=4})
elseif ADD_MODULES == "Productivity" then
table.insert(kit,{name="productivity-module-3",count=4})
elseif ADD_MODULES == "Energy Efficiency" then
table.insert(kit,{name="effectivity-module-3",count=4})
elseif ADD_MODULES == "All" then
table.insert(kit,{name="speed-module-3",count=4})
table.insert(kit,{name="productivity-module-3",count=4})
table.insert(kit,{name="effectivity-module-3",count=4})
elseif ADD_MODULES == "4x All" then
table.insert(kit,{name="speed-module-3",count=16})
table.insert(kit,{name="productivity-module-3",count=16})
table.insert(kit,{name="effectivity-module-3",count=16})
end
--[[Start with bots]]--
if ADD_ROBOTS == "Basic" then
if MODU_ROBO then --[[settings.global["bobmods-logistics-disableroboports"].value == true OR game.active_mods["boblogistics"]]--
table.insert(kit,{name="bob-robochest",count=1})
table.insert(kit,{name="bob-robo-charge-port",count=1})
table.insert(kit,{name="bob-logistic-zone-interface",count=1})
table.insert(kit,{name="bob-logistic-zone-expander",count=1})
else
table.insert(kit,{name="roboport",count=1})
end
table.insert(kit,{name="logistic-robot",count=10})
table.insert(kit,{name="construction-robot",count=2})
if ADD_ROCHEST then
table.insert(kit,{name="logistic-chest-passive-provider",count=3})
table.insert(kit,{name="logistic-chest-storage",count=1})
table.insert(kit,{name="logistic-chest-requester",count=3})
end
elseif ADD_ROBOTS == "Lots" then
if MODU_ROBO then
table.insert(kit,{name="bob-robochest",count=1})
table.insert(kit,{name="bob-robo-charge-port",count=2})
table.insert(kit,{name="bob-logistic-zone-interface",count=1})
table.insert(kit,{name="bob-logistic-zone-expander-2",count=1})
else
table.insert(kit,{name="roboport",count=1})
end
table.insert(kit,{name="logistic-robot",count=25})
table.insert(kit,{name="construction-robot",count=5})
if ADD_ROCHEST then
table.insert(kit,{name="logistic-chest-passive-provider",count=6})
table.insert(kit,{name="logistic-chest-storage",count=3})
table.insert(kit,{name="logistic-chest-requester",count=6})
end
elseif ADD_ROBOTS == "Too Many" then
if MODU_ROBO then
table.insert(kit,{name="bob-robochest",count=1})
table.insert(kit,{name="bob-robo-charge-port",count=3})
table.insert(kit,{name="bob-logistic-zone-interface",count=1})
table.insert(kit,{name="bob-logistic-zone-expander-3",count=2})
else
table.insert(kit,{name="roboport",count=2})
end
table.insert(kit,{name="logistic-robot",count=50})
table.insert(kit,{name="construction-robot",count=10})
if ADD_ROCHEST then
table.insert(kit,{name="logistic-chest-passive-provider",count=10})
table.insert(kit,{name="logistic-chest-storage",count=5})
table.insert(kit,{name="logistic-chest-requester",count=10})
end
elseif ADD_ROBOTS == "Too Many ++" then
if MODU_ROBO then
table.insert(kit,{name="bob-robochest",count=2})
table.insert(kit,{name="bob-robo-charge-port",count=4})
table.insert(kit,{name="bob-robo-charge-port-large",count=1})
table.insert(kit,{name="bob-logistic-zone-interface",count=1})
table.insert(kit,{name="bob-logistic-zone-expander-4",count=2})
else
table.insert(kit,{name="roboport",count=4})
end
table.insert(kit,{name="logistic-robot",count=100})
table.insert(kit,{name="construction-robot",count=20})
if ADD_ROCHEST then
table.insert(kit,{name="logistic-chest-passive-provider",count=15})
table.insert(kit,{name="logistic-chest-storage",count=10})
table.insert(kit,{name="logistic-chest-requester",count=15})
table.insert(kit,{name="logistic-chest-active-provider",count=5})
table.insert(kit,{name="logistic-chest-buffer",count=5})
end
end
--[[Add a car]]--
if ADD_CAR == "Car" then
table.insert(kit,{name="car",count=1})
table.insert(kit,{name="solid-fuel",count=5})
elseif ADD_CAR == "Tank" then
table.insert(kit,{name="tank",count=1})
table.insert(kit,{name="solid-fuel",count=5})
elseif ADD_CAR == "Train" then
table.insert(kit,{name="locomotive",count=1})
table.insert(kit,{name="cargo-wagon",count=2})
table.insert(kit,{name="fluid-wagon",count=1})
table.insert(kit,{name="solid-fuel",count=50})
table.insert(kit,{name="rail",count=300})
table.insert(kit,{name="train-stop",count=2})
table.insert(kit,{name="rail-signal",count=20})
table.insert(kit,{name="rail-chain-signal",count=20})
end
if PERFECTIONIST > 0 then
table.insert(kit,{name="landfill",count=PERFECTIONIST})
end
-- MODS
--if settings.startup["start-with-vehicle-miner"].value == true then
-- table.insert(kit,{name="vehicle-miner",count=1})
--end
--
--if settings.startup["start-with-unit-remote-control"].value == true then
-- table.insert(kit,{name="unit-remote-control",count=1})
--end
-- Now lets get the player that just joined, and clear all of his inventory to replace with ours.
script.on_event(defines.events.on_player_created,function(param)
local p=game.players[param.player_index]
if START_EQUIP ~= "" then
local items = split(START_EQUIP,",")
for no, item_str in pairs(items) do
local info = split(item_str,":")
if game.item_prototypes[info[1]] then
table.insert(kit, {name=info[1],count=tonumber(info[2])})
end
end
end
--[[if START_TECH == "everything" then
--p.force.research_all_technologies()
elseif ~= "" then
local techs = split(START_TECH,",")
for no, tech_str in pairs(techs) do
--p.force.technology[techs].enabled=true
end
end]]--
-- Here we run a check to clear all sections of his inventory.
for i,v in pairs(defines.inventory) do
pcall(function()
p.get_inventory(v).clear()
end)
end
-- Now we will add all the items from our mod settings choices.
for i,v in pairs(kit) do
p.insert(v)
end
end)
|
local ThreatLib = LibStub and LibStub("ThreatClassic-1.0", true)
if not ThreatLib then return end
if select(2, _G.UnitClass("player")) ~= "MAGE" then return end
local _G = _G
local select = _G.select
local max = _G.max
local GetTalentInfo = _G.GetTalentInfo
local Mage = ThreatLib:GetOrCreateModule("Player")
local SCHOOL_MASK_FIRE = _G.SCHOOL_MASK_FIRE or 0x04;
local SCHOOL_MASK_FROST = _G.SCHOOL_MASK_FROST or 0x10;
local SCHOOL_MASK_ARCANE = _G.SCHOOL_MASK_ARCANE or 0x40;
local NWBonusIDs = {
-- Scorch
2948, 8444, 8445, 8446, 10205, 10206, 10207,
-- Fireball
133, 143, 145, 3140, 8400, 8401, 8402, 10148, 10149, 10150, 10151, 25306,
-- Frostbolt
116, 205, 837, 7322, 8406, 8407, 8408, 10179, 10180, 10181, 25304,
}
local NWBonus20IDs = {
-- Arcane Missiles
5143, 5144, 5145, 8416, 8417, 10211, 10212, 25345,
}
function Mage:ClassInit()
-- School names come through in english thanks to Parser-3.0
self.schoolThreatMods[SCHOOL_MASK_FIRE] = function(self, amt) return amt * self.fireThreatMod * self:ItemSetMods() end
self.schoolThreatMods[SCHOOL_MASK_FROST] = function(self, amt) return amt * self.frostThreatMod * self:ItemSetMods() end
self.schoolThreatMods[SCHOOL_MASK_ARCANE] = function(self, amt) return amt * self.arcaneThreatMod * self:ItemSetMods() end
for i = 1, #NWBonusIDs do
self.AbilityHandlers[NWBonusIDs[i]] = self.NWBonus100
end
for i = 1, #NWBonus20IDs do
self.AbilityHandlers[NWBonus20IDs[i]] = self.NWBonus20
end
NWBonusIDs, NWBonus20IDs = nil, nil
-- I tested Counterspell with a level 32 mage. I would like mages of other levels
-- to test its threat value as well.
-- Counterspell
self.CastLandedHandlers[2139] = function(self, spellID, target) self:AddTargetThreat(target, 300 * self:threatMods()) end
-- Remove Lesser Curse
self.CastHandlers[475] = function(self, spellID, target) self:AddThreat(14 * self:threatMods()) end
self.itemSets = {
["Arcanist"] = {16795, 16796, 16797, 16800, 16802, 16799, 16798, 16801},
["Netherwind"] = {16914, 16915, 16917, 16912, 16818, 16918, 16916, 16913}
}
end
function Mage:ClassEnable()
self.passiveThreatModifiers = 1
end
function Mage:ScanTalents()
if ThreatLib.Classic then
self.arcaneThreatMod = 1 - 0.2 * select(5, GetTalentInfo(1, 1))
self.frostThreatMod = 1 - 0.1 * select(5, GetTalentInfo(3, 12))
self.fireThreatMod = 1 - 0.15 * select(5, GetTalentInfo(2, 9))
else
self.arcaneThreatMod = 1 -- for when testing in retail
self.frostThreatMod = 1 -- for when testing in retail
self.fireThreatMod = 1 -- for when testing in retail
end
end
function Mage:ItemSetMods()
local mod = 1
if self:getWornSetPieces("Arcanist") >= 8 then
mod = mod * 0.85
end
return mod
end
function Mage:NWBonus100(amt)
if self:getWornSetPieces("Netherwind") >= 3 then
amt = max(0, amt - 100)
end
return amt
end
function Mage:NWBonus20(amt)
if self:getWornSetPieces("Netherwind") >= 3 then
amt = max(0, amt - 20)
end
return amt
end
|
--************************
--name : ttid_001.lua
--ver : 0.1
--author : Ferron
--date : 2004/09/21
--lang : en
--desc : General Faction Information
--npc : Hacknet Broadcast Daemon v0.1.1
--************************
--changelog:
--2004/09/21(0.1): built from snows template
--************************
-- faction information
DBNAME="TangentTechnologies Broadcasting Daemon v0.0.1"
FACNAME="TangentTechnologies"
FACSLOGAN="In guns we trust"
FACGENERAL="General Faction Information\n Tangent develops weapons, basic technologies for weapon systems and other (mainly military) high-tech equipment."
FACHQ="Faction Headquarter\n Located in ViaRosso 2"
FACPERS="Key Personalities\n Hester Gabun, founder and former manager of Biotech Industries, founded Tangent in the year 2658 as an arms development department of Biotech. It was founded mainly to improve the poor financial situation of the parent company. \n Robert Jordan (92 years old, manager of Biotech Industries from 2691 to 2748 and still owner of the whole enterprise) is an old-line business man who enjoys watching his sons, Seymour and Damion compete each other as division managers since the splitting of the company in 2746. \n Manager: Damion Jordan, 30 years old and ambitious, suffers a little from absent-mindedness which is rumored to have been caused by the excessive use of badly prepared illegal substances in his youth. He does however have a feeling for business and this is why he leads by a hair's breadth in the competition with his brother. \n SysAdmin Chester Cohor, who is also known and respected as 'Rubik' in the virtual world, is 18 years old and a total computer addict."
FACHISTORY="Faction History\n In 2658 Hester Gabun, one of the managers and founders of Biotech Industries, founded a special department named Tangent.\n Tangent's purpose was the development of highly effective new weapon systems. Due to the tense political situation in 2722, Tangent Technologies produced more weapons than ever. In 2746 Tangent Technologies branched off from Biotech Industries and became an independent company. Damion Jordan was appointed manager. Two years later, Robert Jordan presented the key to the headquarters of Tangent Technologies Incorporated to his son Damion and retired to enjoy his old age. \n In his will he stipulated that whichever of his two sons (Seymour and Damion) could show higher sales for his enterprise (Biotech Industries and Tangent Technologies), would inherit both companies. Since then, Damion and Seymour have been engaged in a vehement struggle. The companies' balance sheets are almost equal, but Damion is slightly in the lead. In 2750 Tangent Technologies suffers severely from researchers and technicians opting out and leaving the company to join the idealistic Fallen Angels. This in turn does not really improve Damion's attitude towards the scientists. "
FACRUMORS="Faction Rumors\n Not all of the weapons in Neocron are manufactured by Tangent. This, of course, is a situation with which Tangent is less than pleased. Tactics employed by Tangent to correct this are rumored to include contracted strikes by the CityMercs on these competing manufacturers and distributors. \n A less believable rumor suggests that Tangent also uses the Black Dragon Clan for more shady dealings. The connection is expanded by a rumored drug problem plagueing Tangent CEO, Damion Jordan. It is unclear how an addict could run a major corporation as well as Damion does, but the rumor suggests that the Black Dragon Clan has been quietly supplying Damion for most of his adult life. \n It may also be worth noting that information has surfaced regarding the 'in development' load out for the CityAdmin CopBots. The numbers associated with the new load out are a tenfold increase in CopBot speed and a hundredfold increase in their lethality. Hackers have noted an increase in Tangent's network security, suspecting that this implies that Tangent's network was recently compromised. For this reason, the CopBot information is being taken very seriously. Chester Cohor, Tangent's SysAdmin, has stated that the increased security is simply 'routine upgrading'."
FACREL="Faction Relations\n Tangent has taken over a cooperation agreement with NEXT Systems Inc. from former BioTech Industries. Together they develop combat mechs, tanks and other mobile arms systems. A similar contract with Diamond Real Estate in the fields of security systems and building security has only shortly been established. The CityMercs often carry out protection, guard, and also sabotage jobs for Tangent and belong to Tangent's best customers. As Tangent is one of the largest arms suppliers for the STORM- and CopBot squads, relations between the company and the administrative institutions of the city are naturally very good. \n Damion's arch enemy is his own brother Seymour, manager of Biotech Industries. Over the years, a deep hatred has evolved out of an old family dispute and the fierce rivalry with his brother. Damion accuses the Fallen Angels of malevolently harming his business, not least by luring his most talented researchers away. Although direct contact between Tangent and the Anarchy Breed is seldom, Damion is the main weapons supplier of the Breed's enemies. As Damion's profits considerably depend on the stability of the present order, he has no sympathy for the Twilight Guardian rebels."
-- main dialog
function DIALOG()
NODE(0)
SAY("Broadcast system establishing link ...... Link established ...... System ready:"..DBNAME)
ANSWER(" - Continue",10)
ANSWER(" - Abort",25)
NODE(10)
SAY("Information categories")
ANSWER(" - General Faction Information",15)
ANSWER(" - Faction Headquarter",16)
ANSWER(" - Key Personalities",17)
ANSWER(" - Faction History",18)
ANSWER(" - Faction Rumors",19)
ANSWER(" - Faction Relations",20)
ANSWER(" - Abort",25)
NODE(15)
SAY(""..FACGENERAL)
ANSWER("Back",10)
NODE(16)
SAY(""..FACHQ)
ANSWER("Back",10)
NODE(17)
SAY(""..FACPERS)
ANSWER("Back",10)
NODE(18)
SAY(""..FACHISTORY)
ANSWER("Back",10)
NODE(19)
SAY(""..FACPERS)
ANSWER("Back",10)
NODE(20)
SAY(""..FACRUMORS)
ANSWER("Back",10)
NODE(25)
SAY("Closing Link ...... Disconnecting ......"..FACNAME.." - "..FACSLOGAN)
ANSWER(" - Disconnect",26)
ANSWER(" - Cancel",0)
NODE(26)
SAY("Disconnecting")
ENDDIALOG()
end
|
xivopeners_pld = {}
xivopeners_pld.debug = false
xivopeners_pld.supportedLevel = 80
xivopeners_pld.openerAbilities = {
ShieldLob = ActionList:Get(1, 24),
FastBlade = ActionList:Get(1, 9),
RiotBlade = ActionList:Get(1, 15),
GoringBlade = ActionList:Get(1, 3538),
RoyalAuthority = ActionList:Get(1, 3539),
CircleofScorn = ActionList:Get(1, 23),
Intervene = ActionList:Get(1, 16461),
Atonement = ActionList:Get(1, 16460),
SpiritsWithin = ActionList:Get(1, 29),
Requiescat = ActionList:Get(1, 7383),
HolySpirit = ActionList:Get(1, 7384),
Confiteor = ActionList:Get(1, 16459),
FightorFlight = ActionList:Get(1, 20),
-- Potion =
}
xivopeners_pld.openerInfo = {
listOpeners = {"Recommended", "Compatibility"},
currentOpenerIndex = 1,
}
xivopeners_pld.openers = {
recommended = {
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.FastBlade,
xivopeners_pld.openerAbilities.FightorFlight,
xivopeners_pld.openerAbilities.RiotBlade,
xivopeners_pld.openerAbilities.GoringBlade,
xivopeners_pld.openerAbilities.FastBlade,
xivopeners_pld.openerAbilities.RiotBlade,
-- xivopeners_pld.openerAbilities.Potion,
xivopeners_pld.openerAbilities.RoyalAuthority,
xivopeners_pld.openerAbilities.CircleofScorn,
xivopeners_pld.openerAbilities.Intervene,
xivopeners_pld.openerAbilities.Atonement,
xivopeners_pld.openerAbilities.SpiritsWithin,
xivopeners_pld.openerAbilities.Intervene,
xivopeners_pld.openerAbilities.Atonement,
xivopeners_pld.openerAbilities.Atonement,
xivopeners_pld.openerAbilities.FastBlade,
xivopeners_pld.openerAbilities.RiotBlade,
xivopeners_pld.openerAbilities.GoringBlade,
xivopeners_pld.openerAbilities.Requiescat,
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.CircleofScorn,
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.Confiteor,
xivopeners_pld.openerAbilities.FastBlade,
xivopeners_pld.openerAbilities.RiotBlade,
xivopeners_pld.openerAbilities.SpiritsWithin,
xivopeners_pld.openerAbilities.GoringBlade
},
compatibility = {
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.FastBlade,
xivopeners_pld.openerAbilities.FightorFlight,
xivopeners_pld.openerAbilities.RiotBlade,
xivopeners_pld.openerAbilities.GoringBlade,
xivopeners_pld.openerAbilities.FastBlade,
xivopeners_pld.openerAbilities.RiotBlade,
-- xivopeners_pld.openerAbilities.Potion,
xivopeners_pld.openerAbilities.RoyalAuthority,
xivopeners_pld.openerAbilities.CircleofScorn,
xivopeners_pld.openerAbilities.Intervene,
xivopeners_pld.openerAbilities.Atonement,
xivopeners_pld.openerAbilities.SpiritsWithin,
xivopeners_pld.openerAbilities.Intervene,
xivopeners_pld.openerAbilities.Atonement,
xivopeners_pld.openerAbilities.Atonement,
xivopeners_pld.openerAbilities.FastBlade,
xivopeners_pld.openerAbilities.RiotBlade,
xivopeners_pld.openerAbilities.GoringBlade,
xivopeners_pld.openerAbilities.Requiescat,
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.CircleofScorn,
xivopeners_pld.openerAbilities.HolySpirit,
xivopeners_pld.openerAbilities.Confiteor,
xivopeners_pld.openerAbilities.FastBlade,
xivopeners_pld.openerAbilities.RiotBlade,
xivopeners_pld.openerAbilities.SpiritsWithin,
xivopeners_pld.openerAbilities.GoringBlade
},
}
xivopeners_pld.abilityQueue = {}
xivopeners_pld.lastCastFromQueue = nil -- might need this for some more complex openers with conditions
xivopeners_pld.openerStarted = false
xivopeners_pld.lastcastid = 0
xivopeners_pld.lastcastid2 = 0
function xivopeners_pld.getOpener()
if (xivopeners_pld.openerInfo.currentOpenerIndex == 1) then
return xivopeners_pld.openers.recommended
else
return xivopeners_pld.openers.compatibility
end
end
function xivopeners_pld.checkOpenerIds()
for key, action in pairs(xivopeners_pld.getOpener()) do
if (action == nil) then
xivopeners.log("WARNING: Action at index " .. tostring(key) .. " was nil! The id is likely incorrect.")
end
end
end
function xivopeners_pld.openerAvailable()
-- check cooldowns
for _, action in pairs(xivopeners_pld.getOpener()) do
if (action.cd >= 1.5) then return false end
end
return true
end
function xivopeners_pld.queueOpener()
-- the only time this gets called is when the main script is toggled, so we can do more than just queue the opener
-- empty queue first
xivopeners_pld.abilityQueue = {}
for _, action in pairs(xivopeners_pld.getOpener()) do
xivopeners_pld.enqueue(action)
end
-- xivopeners.log("queue:")
-- for _, v in pairs(xivopeners_pld.abilityQueue) do
-- xivopeners.log(v.name)
-- end
xivopeners_pld.lastCastFromQueue = nil
xivopeners_pld.openerStarted = false
end
function xivopeners_pld.updateLastCast()
-- xivopeners.log(tostring(xivopeners_pld.lastcastid) .. ", " .. tostring(xivopeners_pld.lastcastid2) .. ", " .. tostring(Player.castinginfo.lastcastid))
if (xivopeners_pld.lastcastid == -1) then
-- compare the real castid and see if it changed, if it did, update from -1
if (xivopeners_pld.lastcastid2 ~= Player.castinginfo.castingid and Player.castinginfo.castingid ~= xivopeners_pld.openerAbilities.PitchPerfect.id) then
xivopeners.log("cast changed")
xivopeners_pld.lastcastid = Player.castinginfo.castingid
xivopeners_pld.lastcastid2 = Player.castinginfo.castingid
end
elseif (xivopeners_pld.lastcastid ~= Player.castinginfo.castingid) then
xivopeners_pld.lastcastid = Player.castinginfo.castingid
xivopeners_pld.lastcastid2 = Player.castinginfo.castingid
end
end
function xivopeners_pld.drawCall(event, tickcount)
if (xivopeners_pld.debug) then
GUI:Text("lastcastid")
GUI:NextColumn()
GUI:InputText("##xivopeners_pld_lastcastid_display", tostring(xivopeners_pld.lastcastid))
GUI:NextColumn()
GUI:Text("lastcastid2")
GUI:NextColumn()
GUI:InputText("##xivopeners_pld_lastcastid2_display", tostring(xivopeners_pld.lastcastid2))
GUI:NextColumn()
GUI:Text("lastcastid_o")
GUI:NextColumn()
GUI:InputText("##xivopeners_pld_lastcastid_original_display", tostring(Player.castinginfo.lastcastid))
GUI:NextColumn()
GUI:Text("castingid")
GUI:NextColumn()
GUI:InputText("##xivopeners_pld_castingid", tostring(Player.castinginfo.castingid))
if (xivopeners_pld.abilityQueue[1]) then
GUI:NextColumn()
GUI:Text("queue[1]")
GUI:NextColumn()
GUI:InputText("##xivopeners_pld_queue[1]", xivopeners_pld.abilityQueue[1].name)
end
if (xivopeners_pld.lastCastFromQueue) then
GUI:NextColumn()
GUI:Text("lastCastFromQueue")
GUI:NextColumn()
GUI:InputText("##xivopeners_pld_lastcastfromqueue", xivopeners_pld.lastCastFromQueue.name)
end
end
end
function xivopeners_pld.main(event, tickcount)
if (Player.level >= xivopeners_pld.supportedLevel) then
local target = Player:GetTarget()
if (not target) then return end
if (not xivopeners_pld.openerAvailable() and not xivopeners_pld.openerStarted) then return end -- don't start opener if it's not available, if it's already started then yolo
if (xivopeners_pld.openerStarted and next(xivopeners_pld.abilityQueue) == nil) then
-- opener is finished, pass control to ACR
xivopeners.log("Finished openers, handing control to ACR")
xivopeners_pld.openerStarted = false
if (xivopeners.running) then xivopeners.ToggleRun() end
if (not FFXIV_Common_BotRunning) then
ml_global_information.ToggleRun()
end
return
end
if (ActionList:IsCasting()) then return end
xivopeners_pld.updateLastCast()
if (not xivopeners_pld.openerStarted) then
-- technically, even if you use an ability from prepull, it should still work, since the next time this loop runs it'll jump to the elseif
xivopeners.log("Starting opener")
xivopeners_pld.openerStarted = true
xivopeners_pld.useNextAction(target)
elseif (xivopeners_pld.lastCastFromQueue and xivopeners_pld.lastcastid == xivopeners_pld.lastCastFromQueue.id) then
xivopeners_pld.lastcastid = -1
if (xivopeners_pld.lastCastFromQueue ~= xivopeners_pld.openerAbilities.PitchPerfect) then
xivopeners_pld.dequeue()
end
xivopeners_pld.useNextAction(target)
else
xivopeners_pld.useNextAction(target)
end
end
end
function xivopeners_pld.enqueueNext(action)
table.insert(xivopeners_pld.abilityQueue, 1, action)
end
function xivopeners_pld.enqueue(action)
-- implementation of the queue can be changed later
table.insert(xivopeners_pld.abilityQueue, action)
end
function xivopeners_pld.dequeue()
xivopeners.log("Dequeing " .. xivopeners_pld.abilityQueue[1].name)
table.remove(xivopeners_pld.abilityQueue, 1)
end
function xivopeners_pld.useNextAction(target)
-- do the actual opener
-- the current implementation uses a queue system
if (target and target.attackable and xivopeners_pld.abilityQueue[1]) then
-- idk how to make it not spam console
if (xivopeners_pld.abilityQueue[1] == xivopeners_pld.openerAbilities.RagingStrikes and HasBuff(Player.id, xivopeners_pld.openerAbilities.RagingStrikesBuffID)) then
xivopeners.log("Player already used raging strikes prepull, continue with opener")
-- xivopeners_pld.lastCastFromQueue = xivopeners_pld.openerAbilities.RagingStrikes
xivopeners_pld.dequeue()
return
end
if (Player.gauge[2] >= 3 and xivopeners_pld.abilityQueue[1] ~= xivopeners_pld.openerAbilities.PitchPerfect) then
-- don't want to dequeue here
xivopeners.log("Using PP3 proc")
xivopeners_pld.openerAbilities.PitchPerfect:Cast(target.id)
-- xivopeners_pld.lastCastFromQueue = xivopeners_pld.openerAbilities.PitchPerfect
return
end
if (xivopeners_pld.abilityQueue[1] == xivopeners_pld.openerAbilities.BurstShot and HasBuff(Player.id, xivopeners_pld.openerAbilities.StraightShotReadyBuffID)) then
xivopeners.log("Using RA proc during BurstShot window")
xivopeners_pld.openerAbilities.RefulgentArrow:Cast(target.id)
xivopeners_pld.lastCastFromQueue = xivopeners_pld.openerAbilities.RefulgentArrow
return
end
-- xivopeners.log("Casting " .. xivopeners_pld.abilityQueue[1].name)
xivopeners_pld.abilityQueue[1]:Cast(target.id)
-- if (Player.castinginfo.castingid == xivopeners_pld.abilityQueue[1].id) then
xivopeners_pld.lastCastFromQueue = xivopeners_pld.abilityQueue[1]
-- end
end
end
|
local Luna = assert(foundation.com.Luna)
local case = Luna:new("yatm_oku.OKU.Memory")
local m = assert(yatm_oku.OKU.Memory)
case:describe("adjust_and_check_bounds", function (t2)
t2:test("will correctly adjust the given index to match internal", function (t3)
local mem = m:new(256) -- really small memory for testing
local i, o
-- byte
i, o = mem:adjust_and_check_bounds(0, 1)
t3:assert_eq(i, 0)
t3:assert_eq(o, 0)
i, o = mem:adjust_and_check_bounds(1, 1)
t3:assert_eq(i, 0)
t3:assert_eq(o, 1)
i, o = mem:adjust_and_check_bounds(2, 1)
t3:assert_eq(i, 0)
t3:assert_eq(o, 2)
i, o = mem:adjust_and_check_bounds(3, 1)
t3:assert_eq(i, 0)
t3:assert_eq(o, 3)
i, o = mem:adjust_and_check_bounds(4, 1)
t3:assert_eq(i, 1)
t3:assert_eq(o, 0)
i, o = mem:adjust_and_check_bounds(255, 1)
t3:assert_eq(i, 63)
t3:assert_eq(o, 3)
-- short / 2 bytes
i, o = mem:adjust_and_check_bounds(0, 2)
t3:assert_eq(i, 0)
t3:assert_eq(o, 0)
i, o = mem:adjust_and_check_bounds(1, 2)
t3:assert_eq(i, 0)
t3:assert_eq(o, 1)
i, o = mem:adjust_and_check_bounds(2, 2)
t3:assert_eq(i, 1)
t3:assert_eq(o, 0)
-- int / 4 bytes
i, o = mem:adjust_and_check_bounds(0, 4)
t3:assert_eq(i, 0)
t3:assert_eq(o, 0)
i, o = mem:adjust_and_check_bounds(1, 4)
t3:assert_eq(i, 1)
t3:assert_eq(o, 0)
i, o = mem:adjust_and_check_bounds(2, 4)
t3:assert_eq(i, 2)
t3:assert_eq(o, 0)
end)
end)
case:describe("i8", function (t2)
t2:test("can address bytes at location", function (t3)
local mem = m:new(256) -- really small memory for testing
t3:assert_eq(mem:i8(0), 0)
mem:w_i8(0, 32)
t3:assert_eq(mem:i8(0), 32)
t3:assert_eq(mem:i8(1), 0)
mem:w_i8(1, 87)
t3:assert_eq(mem:i8(0), 32)
t3:assert_eq(mem:i8(1), 87)
t3:assert_eq(mem:i8(7), 0)
mem:w_i8(7, 120)
t3:assert_eq(mem:i8(0), 32)
t3:assert_eq(mem:i8(1), 87)
t3:assert_eq(mem:i8(7), 120)
mem:w_i8(255, 16)
t3:assert_eq(mem:i8(255), 16)
end)
end)
case:describe("bytes", function (t2)
t2:test("can retrieve a list of bytes", function (t3)
local mem = m:new(256)
mem:w_i8b(0, 'H')
mem:w_i8b(1, 'E')
mem:w_i8b(2, 'L')
mem:w_i8b(3, 'L')
mem:w_i8b(4, 'O')
local result = mem:bytes(0, 5)
t3:assert_table_eq(result, {72, 69, 76, 76, 79})
end)
end)
case:execute()
case:display_stats()
case:maybe_error()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.