content
stringlengths 5
1.05M
|
|---|
local EventManager = require "utils.EventManager"
local activityid = 0
local function Setactivityid(id)
activityid = id
end
local function Getactivityid()
return activityid
end
local NextMonstergid = 0
local function SetNextMonstergid(gid)
NextMonstergid = gid
end
local function GetNextMonstergid()
return NextMonstergid
end
local Combat_results_gid = nil
local function GetCombat_results_query()
return Combat_results_gid
end
local function Combat_results_query(gid,reset)--战斗胜利后单独查询
if gid or reset then
Combat_results_gid = gid
elseif Combat_results_gid then
utils.NetworkService.Send(16066,{nil,{Combat_results_gid}})--查询个人战斗
local teamInfo = module.TeamModule.GetTeamInfo();
if teamInfo.group ~= 0 then
utils.NetworkService.Send(16068,{nil,teamInfo.id,{Combat_results_gid}})--查询团队战斗
end
Combat_results_gid = nil
end
end
EventManager.getInstance():addListener("server_notify_16048", function(event, cmd, data)
-- ERROR_LOG("server_notify_16048",sprinttb(data))
Combat_results_gid = data[1]
end)
---------------------------队伍墓园进度------------------------------------------
local function Query_Team_Record(gid,fights)
local teamInfo = module.TeamModule.GetTeamInfo();
if teamInfo and teamInfo.group ~= 0 then
if fights then
utils.NetworkService.Send(16068,{nil,teamInfo.id,fights})--查询团队战斗
else
local list1 = {}
local list2 = {}
local CemeteryConf = require "config.cemeteryConfig"
local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
local _count = 0
for k,v in pairs(CemeteryConf.GetCemetery(gid) or {})do
for k1,v1 in pairs(SmallTeamDungeonConf.GetTeam_pve_fight(v.gid_id).idx) do
for i = 1,#v1 do
if _count > 50 then
table.insert(list2, v1[i].gid)
else
table.insert(list1, v1[i].gid)
_count = _count + 1
end
end
end
end
if #list2 > 0 then
utils.NetworkService.Send(16068,{nil, teamInfo.id, list2})
end
utils.NetworkService.Send(16068,{nil, teamInfo.id, list1})--查询团队战斗
end
end
end
local TEAM_PveStateUid = {}
local function GetTEAM_PveStateUid(gid)
if gid then
return TEAM_PveStateUid[gid]
end
return TEAM_PveStateUid
end
local TEAMRecord = {}
local function GetTEAMRecord(gid)
if gid then
return TEAMRecord[gid]
end
return TEAMRecord
end
local function RestTEAMRecord()
TEAMRecord = {}
Query_Team_Record(1)
Query_Team_Record(2)
end
local function SetTEAMRecord(data)
for i = 1,#data do
--if data[i][2] > 0 then
TEAMRecord[data[i][1]] = data[i][2]
--end
end
end
local function Query_Team_Fight_Win_Count(data)
local TeamModule = require "module.TeamModule"
local teamInfo = TeamModule.GetTeamInfo();
if teamInfo.group == 0 then
return
end
local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
local PveState = 0
for k,v in pairs(SmallTeamDungeonConf.GetTeam_pve_fight(activityid).idx) do
for i = 1,#v do
if TEAMRecord[v[i].gid] > 0 then
if PveState < SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid).sequence then
PveState = SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid).sequence
end
end
end
end
local Team_battle_conf = SmallTeamDungeonConf.GetTeam_battle_conf(activityid)
local _Type = Team_battle_conf.difficult
local cemeteryConf = require "config.cemeteryConfig"
--ERROR_LOG(activityid..">"..PveState)
local teamDescribeConf = cemeteryConf.GetteamDescribeConf(activityid)[PveState+1]
local test_info = {
type = (_Type == 1 and 4 or 5),
up_tittle2 = 2002,
number = 0,
desc = teamDescribeConf.des1,--"墓园队伍进度 "..(PveState+1).." 阶段",
name = teamDescribeConf.des,
desc2 = teamDescribeConf.des2,
cfg = {name = teamDescribeConf.des,desc = teamDescribeConf.des1},
is_show_on_task = 0,
icon = teamDescribeConf.icon,
reward = nil,
status = 0,
battleGid = Team_battle_conf.gid_id, --副本id
find_npc = teamDescribeConf.find_npc,
pos = {Team_battle_conf.enter_x,Team_battle_conf.enter_y,Team_battle_conf.enter_z},
Accomplish = (cemeteryConf.GetteamDescribeConf(activityid)[PveState+2] == nil and true or false),
script = "guide/10004.lua",
uuid = TEAM_PveStateUid[activityid] and TEAM_PveStateUid[activityid] or nil,
mapId = teamDescribeConf.mapid
}
local uid = module.QuestModule.RegisterQuest(test_info)
local teamInfo = module.TeamModule.GetTeamInfo();
if teamInfo.group == 0 or module.playerModule.Get().id == teamInfo.leader.pid then
module.QuestModule.SetOldUuid(uid)
end
--ERROR_LOG("uid->"..uid)
TEAM_PveStateUid[activityid] = uid
end
local function ContinuePve()
local cemeteryConf = require "config.cemeteryConfig"
local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
local Team_battle_conf = SmallTeamDungeonConf.GetTeam_battle_conf(activityid)
local PveState = 0
for k,v in pairs(SmallTeamDungeonConf.GetTeam_pve_fight(activityid).idx) do
for i = 1,#v do
if TEAMRecord[v[i].gid] > 0 then
if PveState < SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid).sequence then
PveState = SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid).sequence
end
end
end
end
local teamDescribeConf = cemeteryConf.GetteamDescribeConf(activityid)[PveState+1]
local quest = {
script = "guide/10004.lua",
find_npc = teamDescribeConf.find_npc,
pos = {Team_battle_conf.enter_x,Team_battle_conf.enter_y,Team_battle_conf.enter_z},
Accomplish = (cemeteryConf.GetteamDescribeConf(activityid)[PveState+2] == nil and true or false),
}
module.QuestModule.callQuestScript(quest, "Guide")
end
local Monsterg_state = {}
local function SetMonsterg_state(list)
Monsterg_state = list
end
local function GetMonsterg_state(id)
return Monsterg_state[id]
end
local function LoadMap_Accomplish()--加载地图检测是否有副本任务可以完成(删除)
for k,v in pairs(TEAM_PveStateUid) do
local quest = module.QuestModule.Get(v)
if quest and quest.Accomplish then
module.CemeteryModule.RestCemetery(function ()
module.QuestModule.Cancel(v)
module.QuestModule.SetOldUuid(nil)
end,k)
end
end
end
---------------------重置副本---------------------------------------------
local RestCemeterySn = {}
local function RestCemetery(fun,id)
local _activityid = nil
if id then
_activityid = id
else
_activityid = activityid
end
local TeamModule = require "module.TeamModule"
local teamInfo = TeamModule.GetTeamInfo();
if teamInfo.id <= 0 then
return
end
local fights = {}
local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
if SmallTeamDungeonConf.GetTeam_pve_fight(_activityid) then
for k,v in pairs(SmallTeamDungeonConf.GetTeam_pve_fight(_activityid).idx) do
for i = 1,#v do
fights[#fights+1] = v[i].gid
end
end
--local sn = utils.NetworkService.Send(16084,{nil,teamInfo.id,fights})--重置副本进度
local sn = utils.NetworkService.Send(16084,{nil,teamInfo.id,_activityid})--重置副本进度
RestCemeterySn[sn] = {fun = fun ,fights = fights,activityid = _activityid}
end
end
EventManager.getInstance():addListener("server_respond_16085", function(event, cmd, data)
--ERROR_LOG("重置副本16085->",sprinttb(data))
local sn = data[1]
local err = data[2]
if err == 0 then
showDlgError(nil,"重置副本成功")
if RestCemeterySn[sn] then
module.TeamModule.SetTeamPveTime(RestCemeterySn[sn].activityid,0,0)--重置副本,直接重置当前副本时间
RestCemeterySn[sn].fun()--删除任务
local fights = RestCemeterySn[sn].fights
if fights then
for i = 1,#fights do
TEAMRecord[fights[i]] = 0--重置当前团本
end
end
RestCemeterySn[sn] = nil
end
else
showDlgError(nil,"重置副本失败")
end
end)
-------------------------个人墓园进度---------------------------------------------
local function Query_Player_Record(gid)
local CemeteryConf = require "config.cemeteryConfig"
local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
local fights = {}
for k,v in pairs(CemeteryConf.GetCemetery(gid) or {})do
if SmallTeamDungeonConf.GetTeam_pve_fight(v.gid_id) then
for k1,v1 in pairs(SmallTeamDungeonConf.GetTeam_pve_fight(v.gid_id).idx) do
for i = 1,#v1 do
fights[#fights+1] = v1[i].gid
end
end
else
ERROR_LOG("config_team_battle_config的gid_id《"..v.gid_id.."》在config_team_pve_fight_config中gid_id不存在")
end
end
utils.NetworkService.Send(16066,{nil,fights})--查询个人副本战斗胜利次数
Query_Team_Record(gid,fights)
end
local PlayerRecord = {}
local function GetPlayerRecord(gid)
return PlayerRecord[gid]
end
local function SetPlayerRecord(data)
for i = 1,#data do
--if data[i][2] > 0 then
PlayerRecord[data[i][1]] = data[i][2]
--end
end
end
local function Query_Player_Fight_Win_Count(activityid)
local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
local PveState = 0
for k,v in pairs(SmallTeamDungeonConf.GetTeam_pve_fight(activityid).idx) do
for i = 1,#v do
if PlayerRecord[v[i].gid] > 0 then
if PveState < SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid).sequence then
PveState = SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid).sequence
end
end
end
end
return PveState
end
-----------------个人进度用来显示活动数据---------------------------
local TeamPveFightList = {}
local TeamPveFightData = {}
local function SetTeamPveFight(gid,idx,count,data)
if not TeamPveFightData[ gid ] then
TeamPveFightData[ gid ] = {}
end
local playerdata = data
local schedule = {count = 0,Max = count,list = {},gid = gid, idx = idx}
local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
-- ERROR_LOG(sprinttb(playerdata))
for i = 1,#playerdata do
if playerdata[i][2] and playerdata[i][2] > 0 then
--if schedule[ SmallTeamDungeonConf.GetTeam_pve_fight_gid(playerdata[i][1]).sequence ] then
schedule.list[ SmallTeamDungeonConf.GetTeam_pve_fight_gid(playerdata[i][1]).sequence ] = true
--end
elseif not schedule.list[ SmallTeamDungeonConf.GetTeam_pve_fight_gid(playerdata[i][1]).sequence ] then
schedule.list[ SmallTeamDungeonConf.GetTeam_pve_fight_gid(playerdata[i][1]).sequence ] = false
end
end
for i = 1, #schedule.list do
if schedule.list[i] then
schedule.count = schedule.count + 1
end
end
--ERROR_LOG(">"..sprinttb(schedule))
TeamPveFightData[ gid ][ idx ] = schedule
local listData = nil
for i = 1,#TeamPveFightData[ gid ] do
if i == 1 then
listData = TeamPveFightData[ gid ][i]--默认先存进去第一个进度的数据
else
if TeamPveFightData[ gid ][i].count > listData.count then--进度比对,拿最大进度的存TeamPveFightList
listData = TeamPveFightData[ gid ][i]
end
end
end
--ERROR_LOG(sprinttb(listData))
TeamPveFightList[listData.gid] = listData
end
local function GetTeamPveFight(gid)
local idx = 0
local CemeteryConf = require "config.cemeteryConfig"
for k,v in pairs(CemeteryConf.GetCemetery(gid))do
--self.CemeteryArr[#self.CemeteryArr+1] = v
local fights = {}
local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
local count = 0
for k1,v1 in pairs(SmallTeamDungeonConf.GetTeam_pve_fight(v.gid_id).idx) do
for i = 1,#v1 do
fights[#fights+1] = {v1[i].gid,PlayerRecord[v1[i].gid]}
end
count = count + 1
end
idx = idx + 1
SetTeamPveFight(gid,idx,count,fights)
end
end
local function GetTeamPveFightList(gid)
GetTeamPveFight(gid)
--ERROR_LOG(sprinttb(TeamPveFightList[gid]))
return TeamPveFightList[gid]
end
-----------------------------------------------------------------------------
local function GetTeam_stage(gid_id)
if gid_id == nil then
gid_id = activityid
end
local PveState = 0
local max = 0
local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf"
for k,v in pairs(SmallTeamDungeonConf.GetTeam_pve_fight(gid_id).idx) do
for i = 1,#v do
if GetTEAMRecord(v[i].gid) and GetTEAMRecord(v[i].gid) > 0 then
if PveState < SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid).sequence then
PveState = SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid).sequence
end
end
end
max = max + 1
end
return PveState,max
end
local function Query_Pve_Schedule(activity_id)
local CemeteryConf = require "config.cemeteryConfig"
local ItemModule = require "module.ItemModule"
local data = CemeteryConf.Getteam_battle_activity(activity_id,1)
if data then
return ItemModule.GetItemCount(data.rewrad_count_one),ItemModule.GetItemCount(data.rewrad_count_ten)
end
end
return{
Setactivityid = Setactivityid,
Getactivityid = Getactivityid,
SetNextMonstergid = SetNextMonstergid,
GetNextMonstergid = GetNextMonstergid,
GetPlayerRecord = GetPlayerRecord,
Query_Player_Fight_Win_Count = Query_Player_Fight_Win_Count,
Query_Team_Fight_Win_Count = Query_Team_Fight_Win_Count,
GetTEAM_PveStateUid = GetTEAM_PveStateUid,
GetTEAMRecord = GetTEAMRecord,
RestCemetery = RestCemetery,
GetTeamPveFight = GetTeamPveFight,
SetTeamPveFight = SetTeamPveFight,
GetTeamPveFightList = GetTeamPveFightList,
SetPlayerRecord = SetPlayerRecord,
SetTEAMRecord = SetTEAMRecord,
GetMonsterg_state = GetMonsterg_state,
SetMonsterg_state = SetMonsterg_state,
Combat_results_query = Combat_results_query,
Query_Team_Record = Query_Team_Record,
Query_Player_Record = Query_Player_Record,
RestTEAMRecord = RestTEAMRecord,
GetCombat_results_query = GetCombat_results_query,
GetTeam_stage = GetTeam_stage,
LoadMap_Accomplish = LoadMap_Accomplish,
Query_Pve_Schedule = Query_Pve_Schedule,
ContinuePve = ContinuePve,
}
|
local boxes = 0;
local mechanicDisabled = true;
local canMessage = true;
function onCreate()
if string.lower(songName):gsub(' ', '-') == 'warning' then
mechanicDisabled = false;
end
end
function onBeatHit()
if curBeat % 2 == 0 then
if canMessage and not mechanicDisabled then
boxes = boxes + 1;
makeLuaSprite('distraction' .. boxes, 'tesco/distraction', getRandomInt(0, screenWidth), getRandomInt(0, screenHeight));
addLuaSprite('distraction' .. boxes);
setObjectCamera('distraction' .. boxes, 'other');
setProperty('distraction' .. boxes .. '.alpha', 0);
setProperty('distraction' .. boxes .. '.scale.x', 0.9);
setProperty('distraction' .. boxes .. '.scale.y', 0.9);
doTweenX('distractionZoomInX' .. boxes, 'distraction' .. boxes .. '.scale', 1, 0.4, 'cubeOut');
doTweenY('distractionZoomInY' .. boxes, 'distraction' .. boxes .. '.scale', 1, 0.4, 'cubeOut');
doTweenAlpha('distractionZoomInAlpha' .. boxes, 'distraction' .. boxes, 1, 0.4, 'cubeOut');
end
end
end
function onUpdate()
if keyJustPressed('space') and not mechanicDisabled then
for i = 1,boxes do
doTweenX('distractionZoomOutX' .. i, 'distraction' .. i .. '.scale', 0.9, 0.4, 'cubeOut');
doTweenY('distractionZoomOutY' .. i, 'distraction' .. i .. '.scale', 0.9, 0.4, 'cubeOut');
doTweenAlpha('distractionZoomOutAlpha' .. i, 'distraction' .. i, 0, 0.4, 'cubeOut');
end
canMessage = false;
runTimer('boxCooldown', 1);
end
end
function onTimerCompleted(tag, loops, loopsLeft)
if tag == 'boxCooldown' then
canMessage = true;
boxes = 0;
end
end
function onTweenCompleted(tag)
for i = 1,boxes do
if tag == 'distractionZoomOutX' .. i then
removeLuaSprite('distraction' .. i);
end
end
end
|
-- File: DragonKnight.lua
-- Author: EroicaCpp (https://github.com/Eroica-cpp/dota2scripts)
-- Version: 1.0
-- Release Date: 2017/6/26
local Utility = require("Utility")
local DragonKnight = {}
local optionKillSteal = Menu.AddOption({"Hero Specific", "Dragon Knight"}, "Kill Steal", "Cast breathe fire on enemy to KS")
local optionAutoStun = Menu.AddOption({"Hero Specific", "Dragon Knight"}, "Auto Stun", "Auto stun enemy in range")
local optionAwareness = Menu.AddOption({"Hero Specific", "Dragon Knight"}, "Awareness", "Show how many hits left to kill enemy")
local font = Renderer.LoadFont("Tahoma", 30, Enum.FontWeight.EXTRABOLD)
function DragonKnight.OnUpdate()
if Menu.IsEnabled(optionKillSteal) then
DragonKnight.KillSteal()
end
if Menu.IsEnabled(optionAutoStun) then
DragonKnight.AutoStun()
end
end
function DragonKnight.OnDraw()
if not Menu.IsEnabled(optionAwareness) then return end
local myHero = Heroes.GetLocal()
if not myHero or NPC.GetUnitName(myHero) ~= "npc_dota_hero_dragon_knight" then return end
local fire_damage = 0
local fire = NPC.GetAbility(myHero, "dragon_knight_breathe_fire")
if fire and Ability.IsCastable(fire, NPC.GetMana(myHero)) then
fire_damage = 20 + 70 * Ability.GetLevel(fire)
end
for i = 1, Heroes.Count() do
local enemy = Heroes.Get(i)
if not NPC.IsIllusion(enemy) and not Entity.IsSameTeam(myHero, enemy) and not Entity.IsDormant(enemy) and Entity.IsAlive(enemy) then
local enemyHp = Entity.GetHealth(enemy)
local physical_damage = NPC.GetDamageMultiplierVersus(myHero, enemy) * NPC.GetTrueDamage(myHero) * NPC.GetArmorDamageMultiplier(enemy)
local magical_damage = fire_damage * NPC.GetMagicalArmorDamageMultiplier(enemy)
local enemyHpLeft = enemyHp - magical_damage
local hitsLeft = math.ceil(enemyHpLeft / (physical_damage + 1))
-- draw
local pos = Entity.GetAbsOrigin(enemy)
local x, y, visible = Renderer.WorldToScreen(pos)
-- red : can kill; green : cant kill
if enemyHpLeft <= 0 then
Renderer.SetDrawColor(255, 0, 0, 255)
Renderer.DrawTextCentered(font, x, y, "Kill", 1)
else
Renderer.SetDrawColor(0, 255, 0, 255)
Renderer.DrawTextCentered(font, x, y, hitsLeft, 1)
end
end
end
end
function DragonKnight.KillSteal()
local myHero = Heroes.GetLocal()
if not myHero then return end
if not Utility.IsSuitableToCastSpell(myHero) then return end
local fire = NPC.GetAbility(myHero, "dragon_knight_breathe_fire")
if not fire or not Ability.IsCastable(fire, NPC.GetMana(myHero)) then return end
local damage = 20 + 70 * Ability.GetLevel(fire)
local range = 900
local enemyHeroes = NPC.GetHeroesInRadius(myHero, range, Enum.TeamType.TEAM_ENEMY)
if not enemyHeroes or #enemyHeroes <= 0 then return end
for i, enemy in ipairs(enemyHeroes) do
local true_damage = damage * NPC.GetMagicalArmorDamageMultiplier(enemy)
if not NPC.IsIllusion(enemy) and Utility.CanCastSpellOn(enemy) and Entity.GetHealth(enemy) <= true_damage then
local dir = Entity.GetAbsOrigin(enemy) - Entity.GetAbsOrigin(myHero)
local pos = Entity.GetAbsOrigin(myHero) + dir:Normalized():Scaled(450)
Ability.CastPosition(fire, pos)
return
end
end
end
function DragonKnight.AutoStun()
local myHero = Heroes.GetLocal()
if not myHero then return end
if not Utility.IsSuitableToCastSpell(myHero) then return end
local stun = NPC.GetAbility(myHero, "dragon_knight_dragon_tail")
if not stun or not Ability.IsCastable(stun, NPC.GetMana(myHero)) then return end
local range = 150
if NPC.HasModifier(myHero, "modifier_dragon_knight_dragon_form") then range = 400 end
local enemyHeroes = NPC.GetHeroesInRadius(myHero, range, Enum.TeamType.TEAM_ENEMY)
if not enemyHeroes or #enemyHeroes <= 0 then return end
for i, enemy in ipairs(enemyHeroes) do
if not NPC.IsIllusion(enemy) and Utility.CanCastSpellOn(enemy) and not Utility.IsLotusProtected(enemy) and not Utility.IsDisabled(enemy) then
Ability.CastTarget(stun, enemy)
return
end
end
end
return DragonKnight
|
-- permisje
ADMIN_LEVEL_SPT2 = -2
ADMIN_LEVEL_SPT3 = -3
ADMIN_LEVEL_ADM = 1
ADMIN_LEVEL_NONE = 0
-- Serwer
SERVER_VERSION = "LS-RP.net v0.7 \n[ALPHA Preview]"
-- Status debug
DEBUG_MODE = false
function getDebugStatus()
return DEBUG_MODE
end
-- Nazwy rang
rank = {}
rank[0] = "Gracz"
rank[1] = "Administrator"
rank[2] = "Gamemaster"
rank[3] = "Supporter"
rank[4] = "Moderator serwera"
rank[5] = "Operator [BETA]"
-- Kolor rang
rank_col = {}
rank_col[0] = "#CCCCCC"
rank_col[1] = "#FF574F"
rank_col[2] = "#339933"
rank_col[3] = "#3399CC"
rank_col[4] = "#330000"
rank_col[5] = "#CCFF99"
-- Obiekty broni
weaponsOb = {}
weaponsOb[1] = 331
weaponsOb[2] = 333
weaponsOb[3] = 334
weaponsOb[4] = 335
weaponsOb[5] = 336
weaponsOb[6] = 337
weaponsOb[7] = 338
weaponsOb[8] = 339
weaponsOb[9] = 341
weaponsOb[10] = 321
weaponsOb[11] = 322
weaponsOb[12] = 323
weaponsOb[14] = 325
weaponsOb[15] = 326
weaponsOb[16] = 342
weaponsOb[17] = 343
weaponsOb[18] = 344
weaponsOb[22] = 346
weaponsOb[23] = 347
weaponsOb[24] = 348
weaponsOb[25] = 349
weaponsOb[26] = 350
weaponsOb[27] = 351
weaponsOb[28] = 352
weaponsOb[29] = 353
weaponsOb[30] = 355
weaponsOb[31] = 356
weaponsOb[32] = 372
weaponsOb[33] = 357
weaponsOb[34] = 358
weaponsOb[35] = 359
-- Mainplayertable
mainplayertable = {}
|
-- By Tingle
TOOL.Category = "SBEP"
TOOL.Tab = "Spacebuild"
TOOL.Name = "#Part Assembler"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.ClientConVar["skin"] = 0
TOOL.ClientConVar["mode"] = 1
TOOL.ClientConVar["nocollide"] = 0
TOOL.SPR = {}
TOOL.SPE = {}
if SERVER then
local function AddMaterials()
local files, directories = file.Find("materials/sprites/sbep_assembler_tool/*", "GAME" )
for k,v in pairs(files) do
local sFile = "materials/sprites/sbep_assembler_tool/"..v
resource.AddFile(sFile)
end
end
AddMaterials()
util.AddNetworkString( "SBEP_PA_LeftClick" )
util.AddNetworkString( "SBEP_PA_RightClick" )
util.AddNetworkString( "SBEP_PA_Reload" )
util.AddNetworkString( "SBEP_PA_Holster" )
util.AddNetworkString( "SBEP_ClSelectionRemoved" )
util.AddNetworkString( "SBEP_ClSelected" )
util.AddNetworkString( "SBEP_ClMerge" )
function TOOL:LeftClick( trace )
local xPlayer = self:GetOwner()
net.Start( "SBEP_PA_LeftClick" )
net.WriteInt( self:GetStage(), 2 )
net.Send( xPlayer )
end
function TOOL:RightClick( trace )
local xPlayer = self:GetOwner()
net.Start( "SBEP_PA_RightClick" )
net.WriteInt( self:GetStage(), 2 )
net.Send( xPlayer )
end
function TOOL:Reload( trace )
local xPlayer = self:GetOwner()
net.Start( "SBEP_PA_Reload" )
net.WriteInt( self:GetStage(), 2 )
net.Send( xPlayer )
if( self:GetStage() == 1 ) then
self:SetStage( 0 )
end
end
function TOOL:Holster( wep )
local xPlayer = self:GetOwner()
self:SetStage( 0 )
net.Start( "SBEP_PA_Holster" )
net.Send( xPlayer )
end
local function SelectionRemoved( len, xPlayer )
xPlayer:GetTool():SetStage( 0 )
end
net.Receive( "SBEP_ClSelectionRemoved", SelectionRemoved )
local function Selected( len, xPlayer )
xPlayer:GetTool():SetStage( 1 )
end
net.Receive( "SBEP_ClSelected", Selected )
local function Merge( len, xPlayer )
xPlayer:GetTool():SetStage( 0 )
local bNoCollide = xPlayer:GetInfoNum( "sbep_part_assembler_nocollide", 0 )
local bWeld = xPlayer:GetInfoNum( "sbep_part_assembler_weld", 0 )
local xAEntity = net.ReadEntity()
local vALocalPos = net.ReadVector()
local vALocalAng = net.ReadAngle()
local xBEntity = net.ReadEntity()
local vBLocalPos = net.ReadVector()
local vBLocalAng = net.ReadAngle()
local vOldPos = xBEntity:GetPos()
local vOldAng = xBEntity:GetAngles()
xBEntity:SetAngles( xBEntity:AlignAngles( xBEntity:LocalToWorldAngles( vBLocalAng ), xAEntity:LocalToWorldAngles( (-vALocalAng:Forward()):Angle() ) ) )
local vAPos = Vector( vALocalPos.x, vALocalPos.y, vALocalPos.z )
vAPos:Rotate( xAEntity:GetAngles() )
vAPos = vAPos + xAEntity:GetPos()
local vBPos = Vector( vBLocalPos.x, vBLocalPos.y, vBLocalPos.z )
vBPos:Rotate( xBEntity:GetAngles() )
vBPos = vBPos + xBEntity:GetPos()
local vDiff = vAPos - vBPos
xBEntity:SetPos( xBEntity:GetPos() + vDiff )
xAEntity:GetPhysicsObject():EnableMotion( false )
xBEntity:GetPhysicsObject():EnableMotion( false )
local function MoveUndo( Undo, xEntity, vPos , vAng )
if( xEntity:IsValid() ) then
xEntity:SetAngles( vAng )
xEntity:SetPos( vPos )
end
end
undo.Create( "SBEP Part Assembly" )
undo.SetPlayer( xPlayer )
undo.AddFunction( MoveUndo, xBEntity, vOldPos, vOldAng )
if( bNoCollide == 1 ) then
local xNoCollide = constraint.NoCollide( xAEntity, xBEntity, 0, 0 );
undo.AddEntity( xNoCollide )
end
if( bWeld == 1 ) then
local xWeld = constraint.Weld( xAEntity, xBEntity, 0, 0, 0, true )
undo.AddEntity( xWeld )
end
undo.Finish()
end
net.Receive( "SBEP_ClMerge", Merge )
end
if CLIENT then
CreateClientConVar("sbep_part_assembler_nocollide", 0, true, true)
CreateClientConVar("sbep_part_assembler_weld", 0, true, true)
language.Add( "tool.sbep_part_assembler.name" , "Part Assembly Tool" )
language.Add( "tool.sbep_part_assembler.desc" , "Easily assemble SBEP parts. Tingle's Remake" )
language.Add( "tool.sbep_part_assembler.0" , "(1) Left-click an attachment point. Right-click to show/hide attachment points. Reload to hide all attachment points. Shift + Right click to toggle between Part Spawner and Part Assembler Tool." )
language.Add( "tool.sbep_part_assembler.1" , "(2) Left-click another attachement point to connect to. Right-click to show/hide attachment points. Reload to cancel." )
language.Add( "undone_SBEP Part Assembly" , "Undone SBEP Part Assembly" )
local PAD = list.Get( "SBEP_PartAssemblyData" )
local xMaterialsInfo = {
SWSH = { Material( "sprites/sbep_assembler_tool/swshblue" ) , { 42 , 30 } } ,
SWSH_MO = { Material( "sprites/sbep_assembler_tool/swshblue_mo" ) , { 42 , 30 } } ,
SWSH_S = { Material( "sprites/sbep_assembler_tool/swshblue_s" ) , { 42 , 30 } } ,
SWDH = { Material( "sprites/sbep_assembler_tool/swdhgreen" ) , { 21 , 30 } } ,
SWDH_MO = { Material( "sprites/sbep_assembler_tool/swdhgreen_mo" ) , { 21 , 30 } } ,
SWDH_S = { Material( "sprites/sbep_assembler_tool/swdhgreen_s" ) , { 21 , 30 } } ,
DWSH = { Material( "sprites/sbep_assembler_tool/dwshred" ) , { 42 , 15 } } ,
DWSH_MO = { Material( "sprites/sbep_assembler_tool/dwshred_mo" ) , { 42 , 15 } } ,
DWSH_S = { Material( "sprites/sbep_assembler_tool/dwshred_s" ) , { 42 , 15 } } ,
DWDH = { Material( "sprites/sbep_assembler_tool/dwdhyellow" ) , { 42 , 30 } } ,
DWDH_MO = { Material( "sprites/sbep_assembler_tool/dwdhyellow_mo" ) , { 42 , 30 } } ,
DWDH_S = { Material( "sprites/sbep_assembler_tool/dwdhyellow_s" ) , { 42 , 30 } } ,
INSR = { Material( "sprites/sbep_assembler_tool/insert" ) , { 42 , 30 } } ,
INSR_MO = { Material( "sprites/sbep_assembler_tool/swshblue_mo" ) , { 42 , 30 } } ,
INSR_S = { Material( "sprites/sbep_assembler_tool/swshblue_s" ) , { 42 , 30 } } ,
ESML = { Material( "sprites/sbep_assembler_tool/esml" ) , { 35 , 35 } } ,
ESML_MO = { Material( "sprites/sbep_assembler_tool/esml_mo" ) , { 35 , 35 } } ,
ESML_S = { Material( "sprites/sbep_assembler_tool/esml_s" ) , { 35 , 35 } } ,
ELRG = { Material( "sprites/sbep_assembler_tool/elrg" ) , { 35 , 35 } } ,
ELRG_MO = { Material( "sprites/sbep_assembler_tool/elrg_mo" ) , { 35 , 35 } } ,
ELRG_S = { Material( "sprites/sbep_assembler_tool/elrg_s" ) , { 35 , 35 } } ,
LRC1 = { Material( "sprites/sbep_assembler_tool/lrc1" ) , { 42 , 30 } } ,
LRC1_MO = { Material( "sprites/sbep_assembler_tool/lrc1_mo" ) , { 42 , 30 } } ,
LRC1_S = { Material( "sprites/sbep_assembler_tool/lrc1_s" ) , { 42 , 30 } } ,
LRC2 = { Material( "sprites/sbep_assembler_tool/lrc1" ) , { 42 , 30 } } ,
LRC2_MO = { Material( "sprites/sbep_assembler_tool/lrc1_mo" ) , { 42 , 30 } } ,
LRC2_S = { Material( "sprites/sbep_assembler_tool/lrc1_s" ) , { 42 , 30 } } ,
LRC3 = { Material( "sprites/sbep_assembler_tool/lrc3" ) , { 42 , 30 } } ,
LRC3_MO = { Material( "sprites/sbep_assembler_tool/lrc3_mo" ) , { 42 , 30 } } ,
LRC3_S = { Material( "sprites/sbep_assembler_tool/lrc3_s" ) , { 42 , 30 } } ,
LRC4 = { Material( "sprites/sbep_assembler_tool/lrc3" ) , { 42 , 30 } } ,
LRC4_MO = { Material( "sprites/sbep_assembler_tool/lrc3_mo" ) , { 42 , 30 } } ,
LRC4_S = { Material( "sprites/sbep_assembler_tool/lrc3_s" ) , { 42 , 30 } } ,
LRC5 = { Material( "sprites/sbep_assembler_tool/lrc5" ) , { 21 , 30 } } ,
LRC5_MO = { Material( "sprites/sbep_assembler_tool/lrc5_mo" ) , { 21 , 30 } } ,
LRC5_S = { Material( "sprites/sbep_assembler_tool/lrc5_s" ) , { 21 , 30 } } ,
LRC6 = { Material( "sprites/sbep_assembler_tool/lrc5" ) , { 21 , 30 } } ,
LRC6_MO = { Material( "sprites/sbep_assembler_tool/lrc5_mo" ) , { 21 , 30 } } ,
LRC6_S = { Material( "sprites/sbep_assembler_tool/lrc5_s" ) , { 21 , 30 } } ,
MBSH = { Material( "sprites/sbep_assembler_tool/mbsh" ) , { 35 , 35 } } ,
MBSH_MO = { Material( "sprites/sbep_assembler_tool/mbsh_mo" ) , { 35 , 35 } } ,
MBSH_S = { Material( "sprites/sbep_assembler_tool/mbsh_s" ) , { 35 , 35 } } ,
MOD1x1 = { Material( "sprites/sbep_assembler_tool/mod1x1" ) , { 35 , 35 } } ,
MOD1x1_MO = { Material( "sprites/sbep_assembler_tool/mod1x1_mo" ) , { 35 , 35 } } ,
MOD1x1_S = { Material( "sprites/sbep_assembler_tool/mod1x1_s" ) , { 35 , 35 } } ,
MOD2x1 = { Material( "sprites/sbep_assembler_tool/mod2x1" ) , { 35 , 35 } } ,
MOD2x1_MO = { Material( "sprites/sbep_assembler_tool/mod2x1_mo" ) , { 35 , 35 } } ,
MOD2x1_S = { Material( "sprites/sbep_assembler_tool/mod2x1_s" ) , { 35 , 35 } } ,
MOD3x1 = { Material( "sprites/sbep_assembler_tool/mod3x1" ) , { 35 , 35 } } ,
MOD3x1_MO = { Material( "sprites/sbep_assembler_tool/mod3x1_mo" ) , { 35 , 35 } } ,
MOD3x1_S = { Material( "sprites/sbep_assembler_tool/mod3x1_s" ) , { 35 , 35 } } ,
MOD3x2 = { Material( "sprites/sbep_assembler_tool/mod3x2" ) , { 35 , 35 } } ,
MOD3x2_MO = { Material( "sprites/sbep_assembler_tool/mod3x2_mo" ) , { 35 , 35 } } ,
MOD3x2_S = { Material( "sprites/sbep_assembler_tool/mod3x2_s" ) , { 35 , 35 } } ,
MOD1x1e = { Material( "sprites/sbep_assembler_tool/esml" ) , { 35 , 35 } } ,
MOD1x1e_MO = { Material( "sprites/sbep_assembler_tool/esml_mo" ) , { 35 , 35 } } ,
MOD1x1e_S = { Material( "sprites/sbep_assembler_tool/esml_s" ) , { 35 , 35 } } ,
MOD3x2e = { Material( "sprites/sbep_assembler_tool/elrg" ) , { 35 , 35 } } ,
MOD3x2e_MO = { Material( "sprites/sbep_assembler_tool/elrg_mo" ) , { 35 , 35 } } ,
MOD3x2e_S = { Material( "sprites/sbep_assembler_tool/elrg_s" ) , { 35 , 35 } } }
local nToolStage = 0
local aSelectedEntities = {}
local xFirstSelection = nil
local function GetSpriteWorldPos( xSprite )
local vPos = Vector( xSprite.vLocalPos.x, xSprite.vLocalPos.y, xSprite.vLocalPos.z )
vPos:Rotate( xSprite.xEntity:GetAngles() )
vPos = vPos + xSprite.xEntity:GetPos()
return vPos
end
local function IsLookingAtSprite( xSprite )
local vPos = GetSpriteWorldPos( xSprite )
local vA = vPos - LocalPlayer():EyePos()
local vB = LocalPlayer():EyeAngles():Forward() * vA:Length()
local vC = vA - vB
local fDist = vC:Length()
local fWidth, fHeight = xMaterialsInfo[xSprite.sType][2][1], xMaterialsInfo[xSprite.sType][2][2]
local fRad = math.sqrt((fWidth*fWidth)+(fHeight*fHeight)) / 2
if( fDist < fRad ) then
return true
else
return false
end
end
local function GetClosestLookingAtSprite()
local xClosest = nil
local fDist = 0
for i, xSprite in pairs( aSelectedEntities ) do
if( IsLookingAtSprite( xSprite ) ) then
local vPos = GetSpriteWorldPos( xSprite )
local fTempDist = LocalPlayer():GetPos():Distance( vPos )
if( fTempDist < fDist || fDist == 0 ) then
fDist = fTempDist
xClosest = xSprite
end
end
end
return xClosest
end
local function ClLeftClick( len )
nToolStage = net.ReadInt(2)
local xSprite = GetClosestLookingAtSprite()
if( xSprite ) then
if( !xFirstSelection ) then
nToolStage = 1
xSprite.bSelected = true
xFirstSelection = xSprite
net.Start("SBEP_ClSelected")
net.SendToServer()
LocalPlayer():EmitSound( "buttons/button14.wav", 100, 100 )
else
if( xSprite.sType == xFirstSelection.sType && xSprite.xEntity != xFirstSelection.xEntity ) then
net.Start("SBEP_ClMerge")
net.WriteEntity( xSprite.xEntity )
net.WriteVector( xSprite.vLocalPos )
net.WriteAngle( xSprite.vLocalAng )
net.WriteEntity( xFirstSelection.xEntity )
net.WriteVector( xFirstSelection.vLocalPos )
net.WriteAngle( xFirstSelection.vLocalAng )
net.SendToServer()
nToolStage = 0
aSelectedEntities = {}
xFirstSelection = nil
LocalPlayer():EmitSound( "buttons/button14.wav", 100, 100 )
end
end
end
end
net.Receive("SBEP_PA_LeftClick", ClLeftClick)
local function ClRightClick( len )
if input.IsShiftDown() then
RunConsoleCommand("gmod_tool", "sbep_part_spawner")
return false
end
nToolStage = net.ReadInt(2)
local xEntity = LocalPlayer():GetEyeTrace().Entity
if( !IsValid( xEntity ) ) then return end
local xPADData = PAD[ string.lower( xEntity:GetModel() ) ]
if !xPADData then return end
local bSelected = false
local bUnSelect = false
for i in ipairs( aSelectedEntities ) do
if( aSelectedEntities[i].xEntity == xEntity ) then
bUnSelect = true
if( aSelectedEntities[i].bSelected ) then
bSelected = true
end
end
end
if( !bSelected ) then
if( bUnSelect ) then
for i in ipairs( aSelectedEntities ) do
if( aSelectedEntities[i].xEntity == xEntity ) then
aSelectedEntities[i] = nil
end
end
local aCleanArray = {}
for i, xElement in pairs( aSelectedEntities ) do
table.insert( aCleanArray, xElement )
end
aSelectedEntities = aCleanArray
LocalPlayer():EmitSound( "buttons/lightswitch2.wav", 100, 100 )
else
for i, xPointData in ipairs( xPADData ) do
local xSprite = {}
xSprite.xEntity = xEntity
xSprite.sType = xPointData.type
xSprite.vLocalPos = xPointData.pos
xSprite.vLocalAng = xPointData.dir
xSprite.bSelected = false
table.insert( aSelectedEntities, xSprite )
LocalPlayer():EmitSound( "buttons/lightswitch2.wav", 100, 100 )
end
end
end
end
net.Receive("SBEP_PA_RightClick", ClRightClick)
local function ClReload( len )
nToolStage = net.ReadInt(2)
if( nToolStage == 0 && next( aSelectedEntities ) != nil ) then
aSelectedEntities = {}
LocalPlayer():EmitSound( "buttons/lightswitch2.wav", 100, 100 )
elseif( nToolStage == 1 && xFirstSelection ) then
xFirstSelection = nil
for i, xSprite in ipairs( aSelectedEntities ) do
xSprite.bSelected = false
end
LocalPlayer():EmitSound( "buttons/button15.wav", 100, 100 )
end
end
net.Receive("SBEP_PA_Reload", ClReload)
local function ClHolster( xEntity )
nToolStage = net.ReadInt(2)
aSelectedEntities = {}
xFirstSelection = nil
end
net.Receive("SBEP_PA_Holster", ClHolster)
local function CompareSprites( a, b )
local vAPos = GetSpriteWorldPos( a )
local vBPos = Vector( b.vLocalPos.x, b.vLocalPos.y, b.vLocalPos.z )
vBPos:Rotate( b.xEntity:GetAngles() )
vBPos = vBPos + b.xEntity:GetPos()
return LocalPlayer():EyePos():Distance( vAPos ) > LocalPlayer():EyePos():Distance( vBPos )
end
local function DrawSprites()
table.sort( aSelectedEntities, CompareSprites )
local xClosestLookingAtSprite = GetClosestLookingAtSprite()
for i, xSprite in ipairs( aSelectedEntities ) do
local xSpriteInfo = nil
if( !xSprite.bSelected ) then
if( xClosestLookingAtSprite == xSprite ) then
xSpriteInfo = xMaterialsInfo[xSprite.sType .. "_MO"]
else
xSpriteInfo = xMaterialsInfo[xSprite.sType]
end
else
xSpriteInfo = xMaterialsInfo[xSprite.sType .. "_S"]
end
local vPos = GetSpriteWorldPos( xSprite )
cam.Start3D( LocalPlayer():EyePos(), LocalPlayer():EyeAngles() )
render.SetMaterial( xSpriteInfo[1] )
render.DrawQuadEasy( vPos, LocalPlayer():GetAimVector() * -1, xSpriteInfo[2][1], xSpriteInfo[2][2], Color( 255 , 255, 255, 255 ), 180 )
cam.End3D()
end
end
hook.Add( "HUDPaint", "DrawAssemblerSprites", DrawSprites )
local function OnEntityRemoved( xEntity )
local bUnSelect = false
for i in ipairs( aSelectedEntities ) do
if( aSelectedEntities[i].xEntity == xEntity ) then
if( aSelectedEntities[i].bSelected ) then
xFirstSelection = nil
net.Start("SBEP_ClSelectionRemoved")
net.SendToServer()
end
aSelectedEntities[i] = nil
bUnSelect = true
end
end
if( bUnSelect ) then
local aCleanArray = {}
for i, xElement in pairs( aSelectedEntities ) do
table.insert( aCleanArray, xElement )
end
aSelectedEntities = aCleanArray
end
end
hook.Add( "EntityRemoved", "OnEntityRemoved", OnEntityRemoved )
function TOOL.BuildCPanel( panel )
panel:SetName( "SBEP Part Assembler" )
panel:DockPadding(2,2,2,2)
panel:DockMargin(2,2,2,2)
local UseCheckBoxA = vgui.Create( "DCheckBoxLabel", panel )
UseCheckBoxA:DockMargin( 5,5,5,5 )
UseCheckBoxA:Dock(TOP)
UseCheckBoxA:SetText( "No Collide Parts" )
UseCheckBoxA:SetTextColor( Color( 0,0,0,255 ) )
UseCheckBoxA:SetConVar( "sbep_part_assembler_nocollide" )
UseCheckBoxA:SetValue( 0 )
local UseCheckBoxB = vgui.Create( "DCheckBoxLabel", panel )
UseCheckBoxB:DockMargin( 5,5,5,5 )
UseCheckBoxB:Dock(TOP)
UseCheckBoxB:SetText( "Weld Parts" )
UseCheckBoxB:SetTextColor( Color( 0,0,0,255 ) )
UseCheckBoxB:SetConVar( "sbep_part_assembler_weld" )
UseCheckBoxB:SetValue( 0 )
end
end
|
function onCreate()
-- background shit
makeLuaSprite('nightsky', 'nightsky', -700, -200);
setScrollFactor('nightsky', 0.9, 0.9);
makeLuaSprite('final dest', 'final dest', -750, -200);
setScrollFactor('final dest', 1.0, 1.0);
addLuaSprite('nightsky', false);
addLuaSprite('final dest', false);
close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage
end
|
--[[
Day 25: Turing Tape
]]
print("---------------- Day 25 ----------------")
function Day25(input)
local states = {}
local current_state, max_steps
local val, state, ifval -- Temporaries during reading
local MOVE = {left = -1, right = 1}
-- Read States into states array
for _, line in pairs(input) do
local _, _, val = line:find('Begin in state (.-)%.')
if (val) then current_state = val end
local _, _, val = line:find('Perform a diagnostic checksum after (%d-) steps.')
if (val) then max_steps = tonumber(val) end
local _, _, val = line:find('In state (.-):')
if (val) then state = val states[state] = {} end
local _, _, val = line:find('If the current value is (.-):')
if (val) then ifval = tonumber(val) states[state][ifval] = {} end
local _, _, val = line:find('Write the value (%d+)%.')
if (val) then states[state][ifval].write = tonumber(val) end
local _, _, val = line:find('- Move one slot to the (.-)%.')
if (val) then states[state][ifval].move = MOVE[val] end
local _, _, val = line:find('- Continue with state (.-)%.')
if (val) then states[state][ifval].newstate = val end
end
-- Play state machine max_steps...
local tape = {}
local cur_pos = 0
local min, max = 0, 0
for i = 1, max_steps do
-- Read value under cursor
local cur_val = tape[cur_pos] or 0 -- cells default to 0
-- Get state actions for value and current state
local state = states[current_state]
local actions = state[cur_val]
tape[cur_pos] = actions.write -- Write
cur_pos = cur_pos + actions.move -- Move
current_state = actions.newstate -- New State
-- Track min/max positions on tape, for calculating checksum later...
if cur_pos > max then max = cur_pos end
if cur_pos < min then min = cur_pos end
end
-- Calculate checksum...
local checksum = 0
for i = min, max do
checksum = checksum + tape[i]
end
return checksum
end
-- Read Inputs...
TEST = {}
table.insert(TEST, "")
table.insert(TEST, "Begin in state A.")
table.insert(TEST, "Perform a diagnostic checksum after 6 steps.")
table.insert(TEST, "")
table.insert(TEST, "In state A:")
table.insert(TEST, "If the current value is 0:")
table.insert(TEST, "- Write the value 1.")
table.insert(TEST, "- Move one slot to the right.")
table.insert(TEST, "- Continue with state B.")
table.insert(TEST, "If the current value is 1:")
table.insert(TEST, "- Write the value 0.")
table.insert(TEST, "- Move one slot to the left.")
table.insert(TEST, "- Continue with state B.")
table.insert(TEST, "")
table.insert(TEST, "In state B:")
table.insert(TEST, "If the current value is 0:")
table.insert(TEST, "- Write the value 1.")
table.insert(TEST, "- Move one slot to the left.")
table.insert(TEST, "- Continue with state A.")
table.insert(TEST, "If the current value is 1:")
table.insert(TEST, "- Write the value 1.")
table.insert(TEST, "- Move one slot to the right.")
table.insert(TEST, "- Continue with state A.")
assert(Day25(TEST) == 3)
INPUT = {}
for line in io.lines("input") do
table.insert(INPUT, line)
end
local cs = Day25(INPUT)
print('Checksum: ' .. cs)
|
local guide = require 'parser.guide'
return function (ast, offset, accept)
local len = math.huge
local result
guide.eachSourceContain(ast.ast, offset, function (source)
local start, finish = guide.getStartFinish(source)
if finish - start < len and accept[source.type] then
result = source
len = finish - start
end
end)
return result
end
|
ATTRIBUTE.name = "Cooking"
ATTRIBUTE.category = "Proffesions"
ATTRIBUTE.description = "The ability to cook like a chef."
|
local _, NeP = ...
-- Locals
local LibStub = LibStub
local strupper = strupper
local CreateFrame = CreateFrame
local DiesalGUI = LibStub("DiesalGUI-1.0")
local DiesalTools = LibStub("DiesalTools-1.0")
local SharedMedia = LibStub("LibSharedMedia-3.0")
function NeP.Interface:Header(element, parent, offset, table)
local tmp = DiesalGUI:Create("FontString")
tmp:SetParent(parent.content)
parent:AddChild(tmp)
tmp = tmp.fontString
tmp:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset)
tmp:SetText('|cff'..table.color..element.text)
if element.justify then
tmp:SetJustifyH(element.justify)
else
tmp:SetJustifyH('LEFT')
end
tmp:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 13)
tmp:SetWidth(parent.content:GetWidth()-10)
if element.align then
tmp:SetJustifyH(strupper(element.align))
end
if element.key then
self.usedGUIs[table.key].elements[element.key] = tmp
end
end
function NeP.Interface:Text(element, parent, offset, table)
local tmp = DiesalGUI:Create("FontString")
tmp:SetParent(parent.content)
parent:AddChild(tmp)
tmp = tmp.fontString
tmp:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset)
tmp:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset)
tmp:SetText(element.text)
tmp:SetJustifyH('LEFT')
tmp:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), element.size or 10)
tmp:SetWidth(parent.content:GetWidth()-10)
if not element.offset then
element.offset = tmp:GetStringHeight()
end
if element.align then
tmp:SetJustifyH(strupper(element.align))
end
if element.key then
self.usedGUIs[table.key].elements[element.key] = tmp
end
end
function NeP.Interface:Rule(element, parent, offset, table)
local tmp = DiesalGUI:Create('Rule')
parent:AddChild(tmp)
tmp:SetParent(parent.content)
tmp.frame:SetPoint('TOPLEFT', parent.content, 'TOPLEFT', 5, offset-3)
tmp.frame:SetPoint('BOTTOMRIGHT', parent.content, 'BOTTOMRIGHT', -5, offset-3)
if element.key then
self.usedGUIs[table.key].elements[element.key] = tmp
end
end
function NeP.Interface:Texture(element, parent, offset, table)
local tmp = CreateFrame('Frame')
tmp:SetParent(parent.content)
if element.center then
tmp:SetPoint('CENTER', parent.content, 'CENTER', (element.x or 0), offset-(element.y or 0))
else
tmp:SetPoint('TOPLEFT', parent.content, 'TOPLEFT', 5+(element.x or 0), offset-3+(element.y or 0))
end
tmp:SetWidth(parent:GetWidth()-10)
tmp:SetHeight(element.height)
tmp:SetWidth(element.width)
tmp.texture = tmp:CreateTexture()
tmp.texture:SetTexture(element.texture)
tmp.texture:SetAllPoints(tmp)
if element.key then
self.usedGUIs[table.key].elements[element.key] = tmp
end
end
function NeP.Interface:Checkbox(element, parent, offset, table)
local tmp = DiesalGUI:Create('CheckBox')
parent:AddChild(tmp)
tmp:SetParent(parent.content)
tmp:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset)
tmp:SetEventListener('OnValueChanged', function(_, _, checked)
NeP.Config:Write(table.key, element.key, checked)
end)
tmp:SetChecked(NeP.Config:Read(table.key, element.key, element.default or false))
local tmp_text = DiesalGUI:Create("FontString")
tmp_text:SetParent(parent.content)
parent:AddChild(tmp_text)
tmp_text = tmp_text.fontString
tmp_text:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 20, offset-1)
tmp_text:SetText(element.text)
tmp_text:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 10)
if element.desc then
local tmp_desc = DiesalGUI:Create("FontString")
tmp_desc:SetParent(parent.content)
parent:AddChild(tmp_desc)
tmp_desc = tmp_desc.fontString
tmp_desc:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-15)
tmp_desc:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset-15)
tmp_desc:SetText(element.desc)
tmp_desc:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 9)
tmp_desc:SetWidth(parent.content:GetWidth()-10)
tmp_desc:SetJustifyH('LEFT')
element.push = tmp_desc:GetStringHeight() + 5
end
if element.key then
self.usedGUIs[table.key].elements[element.key..'Text'] = tmp_text
self.usedGUIs[table.key].elements[element.key] = tmp
end
end
function NeP.Interface:Spinner(element, parent, offset, table)
local tmp_spin = DiesalGUI:Create('Spinner')
parent:AddChild(tmp_spin)
tmp_spin:SetParent(parent.content)
tmp_spin:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset)
tmp_spin:SetNumber(
NeP.Config:Read(table.key, element.key, element.default)
)
if element.width then
tmp_spin.settings.width = element.width
end
if element.min then
tmp_spin.settings.min = element.min
end
if element.max then
tmp_spin.settings.max = element.max
end
if element.step then
tmp_spin.settings.step = element.step
end
if element.shiftStep then
tmp_spin.settings.shiftStep = element.shiftStep
end
tmp_spin:ApplySettings()
tmp_spin:SetStylesheet(self.spinnerStyleSheet)
tmp_spin:SetEventListener('OnValueChanged', function(_, _, userInput, number)
if not userInput then return end
NeP.Config:Write(table.key, element.key, number)
end)
local tmp_text = DiesalGUI:Create("FontString")
tmp_text:SetParent(parent.content)
parent:AddChild(tmp_text)
tmp_text = tmp_text.fontString
tmp_text:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-4)
tmp_text:SetText(element.text)
tmp_text:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 10)
tmp_text:SetJustifyH('LEFT')
tmp_text:SetWidth(parent.content:GetWidth()-10)
if element.desc then
local tmp_desc = DiesalGUI:Create("FontString")
tmp_desc:SetParent(parent.content)
parent:AddChild(tmp_desc)
tmp_desc = tmp_desc.fontString
tmp_desc:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-18)
tmp_desc:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset-18)
tmp_desc:SetText(element.desc)
tmp_desc:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 9)
tmp_desc:SetWidth(parent.content:GetWidth()-10)
tmp_desc:SetJustifyH('LEFT')
element.push = tmp_desc:GetStringHeight() + 5
end
if element.key then
self.usedGUIs[table.key].elements[element.key..'Text'] = tmp_text
self.usedGUIs[table.key].elements[element.key] = tmp_spin
end
end
function NeP.Interface:Checkspin(element, parent, offset, table)
local tmp_spin = DiesalGUI:Create('Spinner')
parent:AddChild(tmp_spin)
tmp_spin:SetParent(parent.content)
tmp_spin:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset)
if element.width then
tmp_spin.settings.width = element.width
end
if element.min then
tmp_spin.settings.min = element.min
end
if element.max then
tmp_spin.settings.max = element.max
end
if element.step then
tmp_spin.settings.step = element.step
end
if element.shiftStep then
tmp_spin.settings.shiftStep = element.shiftStep
end
tmp_spin:SetNumber(
NeP.Config:Read(table.key, element.key..'_spin', element.default_spin or 0)
)
tmp_spin:SetStylesheet(self.spinnerStyleSheet)
tmp_spin:ApplySettings()
tmp_spin:SetEventListener('OnValueChanged', function(_, _, userInput, number)
if not userInput then return end
NeP.Config:Write(table.key, element.key..'_spin', number)
end)
local tmp_check = DiesalGUI:Create('CheckBox')
parent:AddChild(tmp_check)
tmp_check:SetParent(parent.content)
tmp_check:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-2)
tmp_check:SetEventListener('OnValueChanged', function(_, _, checked)
NeP.Config:Write(table.key, element.key..'_check', checked)
end)
tmp_check:SetChecked(NeP.Config:Read(table.key, element.key..'_check', element.default_check or false))
local tmp_text = DiesalGUI:Create("FontString")
tmp_text:SetParent(parent.content)
parent:AddChild(tmp_text)
tmp_text = tmp_text.fontString
tmp_text:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 20, offset-4)
tmp_text:SetText(element.text)
tmp_text:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 10)
tmp_text:SetJustifyH('LEFT')
tmp_text:SetWidth(parent.content:GetWidth()-10)
if element.desc then
local tmp_desc = DiesalGUI:Create("FontString")
tmp_desc:SetParent(parent.content)
parent:AddChild(tmp_desc)
tmp_desc = tmp_desc.fontString
tmp_desc:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-18)
tmp_desc:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset-18)
tmp_desc:SetText(element.desc)
tmp_desc:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 9)
tmp_desc:SetWidth(parent.content:GetWidth()-10)
tmp_desc:SetJustifyH('LEFT')
element.push = tmp_desc:GetStringHeight() + 5
end
if element.key then
self.usedGUIs[table.key].elements[element.key..'Text'] = tmp_text
self.usedGUIs[table.key].elements[element.key..'Check'] = tmp_check
self.usedGUIs[table.key].elements[element.key..'Spin'] = tmp_spin
end
end
function NeP.Interface:Combo(element, parent, offset, table)
local tmp_list = DiesalGUI:Create('Dropdown')
parent:AddChild(tmp_list)
tmp_list:SetParent(parent.content)
tmp_list:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset)
local orderdKeys = { }
local list = { }
for i, value in pairs(element.list) do
orderdKeys[i] = value.key
list[value.key] = value.text
end
tmp_list:SetList(list, orderdKeys)
tmp_list:SetEventListener('OnValueChanged', function(_, _, value)
NeP.Config:Write(table.key, element.key, value)
end)
tmp_list:SetValue(NeP.Config:Read(table.key, element.key, element.default))
local tmp_text = DiesalGUI:Create("FontString")
tmp_text:SetParent(parent.content)
parent:AddChild(tmp_text)
tmp_text = tmp_text.fontString
tmp_text:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-3)
tmp_text:SetText(element.text)
tmp_text:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 10)
tmp_text:SetJustifyH('LEFT')
tmp_text:SetWidth(parent.content:GetWidth()-10)
if element.desc then
local tmp_desc = DiesalGUI:Create("FontString")
tmp_desc:SetParent(parent.content)
parent:AddChild(tmp_desc)
tmp_desc = tmp_desc.fontString
tmp_desc:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-18)
tmp_desc:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset-18)
tmp_desc:SetText(element.desc)
tmp_desc:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 9)
tmp_desc:SetWidth(parent.content:GetWidth()-10)
tmp_desc:SetJustifyH('LEFT')
element.push = tmp_desc:GetStringHeight() + 5
end
if element.key then
self.usedGUIs[table.key].elements[element.key..'Text'] = tmp_text
self.usedGUIs[table.key].elements[element.key] = tmp_list
end
end
function NeP.Interface:Button(element, parent, offset, table)
local tmp = DiesalGUI:Create("Button")
parent:AddChild(tmp)
tmp:SetParent(parent.content)
tmp:SetText(element.text)
tmp:SetWidth(element.width or parent.content:GetWidth()-10)
tmp:SetHeight(element.height or 20)
tmp:SetStylesheet(self.buttonStyleSheet)
tmp:SetEventListener("OnClick", element.callback)
if element.desc then
local tmp_desc = DiesalGUI:Create("FontString")
tmp_desc:SetParent(parent.content)
parent:AddChild(tmp_desc)
tmp_desc = tmp_desc.fontString
tmp_desc:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-element.height-3)
tmp_desc:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset-element.height-3)
tmp_desc:SetText(element.desc)
tmp_desc:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 9)
tmp_desc:SetWidth(parent.content:GetWidth()-10)
tmp_desc:SetJustifyH('LEFT')
element.push = tmp_desc:GetStringHeight() + 5
end
if element.align then
local loc = element.align
tmp:SetPoint(loc, parent.content, 0, offset)
else
tmp:SetPoint("TOP", parent.content, 0, offset)
end
if element.key then
self.usedGUIs[table.key].elements[element.key] = tmp
end
end
function NeP.Interface:Input(element, parent, offset, table)
local tmp_input = DiesalGUI:Create('Input')
parent:AddChild(tmp_input)
tmp_input:SetParent(parent.content)
tmp_input:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset)
if element.width then
tmp_input:SetWidth(element.width)
end
tmp_input:SetText(NeP.Config:Read(table.key, element.key, element.default or ''))
tmp_input:SetEventListener('OnEditFocusLost', function(this)
NeP.Config:Write(table.key, element.key, this:GetText())
end)
local tmp_text = DiesalGUI:Create("FontString")
tmp_text:SetParent(parent.content)
parent:AddChild(tmp_text)
tmp_text = tmp_text.fontString
tmp_text:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-3)
tmp_text:SetText(element.text)
tmp_text:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 10)
tmp_text:SetJustifyH('LEFT')
if element.desc then
local tmp_desc = DiesalGUI:Create("FontString")
tmp_desc:SetParent(parent.content)
parent:AddChild(tmp_desc)
tmp_desc = tmp_desc.fontString
tmp_desc:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 5, offset-18)
tmp_desc:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -5, offset-18)
tmp_desc:SetText(element.desc)
tmp_desc:SetFont(SharedMedia:Fetch('font', 'Calibri Bold'), 9)
tmp_desc:SetWidth(parent.content:GetWidth()-10)
tmp_desc:SetJustifyH('LEFT')
element.push = tmp_desc:GetStringHeight() + 5
end
if element.key then
self.usedGUIs[table.key].elements[element.key..'Text'] = tmp_text
self.usedGUIs[table.key].elements[element.key] = tmp_input
end
end
function NeP.Interface:Statusbar(element, parent, _, table)
local tmp_statusbar = DiesalGUI:Create('StatusBar')
parent:AddChild(tmp_statusbar)
tmp_statusbar:SetParent(parent.content)
tmp_statusbar.frame:SetStatusBarColor(DiesalTools:GetColor(element.color))
if element.value then
tmp_statusbar:SetValue(element.value)
end
if element.textLeft then
tmp_statusbar.frame.Left:SetText(element.textLeft)
end
if element.textRight then
tmp_statusbar.frame.Right:SetText(element.textRight)
end
if element.key then
self.usedGUIs[table.key].elements[element.key] = tmp_statusbar
end
end
|
---Exercise 30.1: Implement a filter function in C. It should receive a list and a predicate and return a new
---list with all elements from the given list that satisfy the predicate:
--- t = filter({1, 3, 20, -4, 5}, function (x) return x < 5 end) -- t = {1, 3, -4}
---(A predicate is just a function that tests some condition, returning a Boolean.)
t1 = mylib.filter({1, 3, 20, -4, 5}, function(x) return x < 5 end )
print("len:" .. #t1)
print(t1[1], t1[2], t1[3])
t2 = mylib.filter({"a","b",1,{},134.7,true}, function(x) return type(x) == 'string' end)
print("len:" .. #t2)
print(t2[1], t2[2])
---Exercise 30.2: Modify the function l_split (from Figure 30.2, “Splitting a string”) so that it can work
---with strings containing zeros. (Among other changes, it should use memchr instead of strchr.)
local str = "a|b|cccc\0|d"
print(str)
local t = mylib.split(str,'|')
for i,v in ipairs(t) do
print(v)
end
---Exercise 30.3: Reimplement the function transliterate (Exercise 10.3) in C.
---Exercise 30.4: Implement a library with a modification of transliterate so that the transliteration
---table is not given as an argument, but instead is kept by the library. Your library should offer the following
---functions:
--- lib.settrans (table) -- set the transliteration table
--- lib.gettrans () -- get the transliteration table
--- lib.transliterate(s) -- transliterate 's' according to the current table
---Use the registry to keep the transliteration table.
local char_tbl = { ["-"] = " ",["?"] = false}
mylib.settrans(char_tbl)
print(mylib.gettrans())
print(mylib.transliterate("Lua-is-a-good-language-for-me?????????"))
---Exercise 30.5: Repeat the previous exercise using an upvalue to keep the transliteration table.
mylib.settrans_up(char_tbl)
print(mylib.gettrans_up())
print(mylib.transliterate_up("Lua-is-a-good-language-for-me?????????"))
---Exercise 30.6: Do you think it is a good design to keep the transliteration table as part of the state of the
---library, instead of being a parameter to transliterate?
---是一种好的设计,如果状态不是经常改变的话可以节省函数的调用开销,也减少了对新表的构造。
|
local _2afile_2a = "fnl/conjure/extract/searchpair.fnl"
local _2amodule_name_2a = "conjure.extract.searchpair"
local _2amodule_2a
do
package.loaded[_2amodule_name_2a] = {}
_2amodule_2a = package.loaded[_2amodule_name_2a]
end
local _2amodule_locals_2a
do
_2amodule_2a["aniseed/locals"] = {}
_2amodule_locals_2a = (_2amodule_2a)["aniseed/locals"]
end
local autoload = (require("conjure.aniseed.autoload")).autoload
local a, config, nvim, str = autoload("conjure.aniseed.core"), autoload("conjure.config"), autoload("conjure.aniseed.nvim"), autoload("conjure.aniseed.string")
do end (_2amodule_locals_2a)["a"] = a
_2amodule_locals_2a["config"] = config
_2amodule_locals_2a["nvim"] = nvim
_2amodule_locals_2a["str"] = str
local function nil_pos_3f(pos)
return (not pos or (0 == unpack(pos)))
end
_2amodule_locals_2a["nil-pos?"] = nil_pos_3f
local function read_range(_1_, _3_)
local _arg_2_ = _1_
local srow = _arg_2_[1]
local scol = _arg_2_[2]
local _arg_4_ = _3_
local erow = _arg_4_[1]
local ecol = _arg_4_[2]
local lines = nvim.buf_get_lines(0, (srow - 1), erow, false)
local function _5_(s)
return string.sub(s, 0, ecol)
end
local function _6_(s)
return string.sub(s, scol)
end
return str.join("\n", a.update(a.update(lines, #lines, _5_), 1, _6_))
end
_2amodule_locals_2a["read-range"] = read_range
local function skip_match_3f()
local _let_7_ = nvim.win_get_cursor(0)
local row = _let_7_[1]
local col = _let_7_[2]
local stack = nvim.fn.synstack(row, a.inc(col))
local stack_size = #stack
local function _8_()
local name = nvim.fn.synIDattr(stack[stack_size], "name")
return (name:find("Comment$") or name:find("String$") or name:find("Regexp%?$"))
end
if (("number" == type(((stack_size > 0) and _8_()))) or ("\\" == string.sub(a.first(nvim.buf_get_lines(nvim.win_get_buf(0), (row - 1), row, false)), col, col))) then
return 1
else
return 0
end
end
_2amodule_2a["skip-match?"] = skip_match_3f
local function current_char()
local _let_10_ = nvim.win_get_cursor(0)
local row = _let_10_[1]
local col = _let_10_[2]
local _let_11_ = nvim.buf_get_lines(0, (row - 1), row, false)
local line = _let_11_[1]
local char = (col + 1)
return string.sub(line, char, char)
end
_2amodule_locals_2a["current-char"] = current_char
local function form_2a(_12_, _14_)
local _arg_13_ = _12_
local start_char = _arg_13_[1]
local end_char = _arg_13_[2]
local escape_3f = _arg_13_[3]
local _arg_15_ = _14_
local root_3f = _arg_15_["root?"]
local flags
local function _16_()
if root_3f then
return "r"
else
return ""
end
end
flags = ("Wnz" .. _16_())
local cursor_char = current_char()
local safe_start_char
if escape_3f then
safe_start_char = ("\\" .. start_char)
else
safe_start_char = start_char
end
local safe_end_char
if escape_3f then
safe_end_char = ("\\" .. end_char)
else
safe_end_char = end_char
end
local start
local function _19_()
if (cursor_char == start_char) then
return "c"
else
return ""
end
end
start = nvim.fn.searchpairpos(safe_start_char, "", safe_end_char, (flags .. "b" .. _19_()), skip_match_3f)
local _end
local function _20_()
if (cursor_char == end_char) then
return "c"
else
return ""
end
end
_end = nvim.fn.searchpairpos(safe_start_char, "", safe_end_char, (flags .. _20_()), skip_match_3f)
if (not nil_pos_3f(start) and not nil_pos_3f(_end)) then
return {range = {start = {a.first(start), a.dec(a.second(start))}, ["end"] = {a.first(_end), a.dec(a.second(_end))}}, content = read_range(start, _end)}
else
return nil
end
end
_2amodule_locals_2a["form*"] = form_2a
local function distance_gt(_22_, _24_)
local _arg_23_ = _22_
local al = _arg_23_[1]
local ac = _arg_23_[2]
local _arg_25_ = _24_
local bl = _arg_25_[1]
local bc = _arg_25_[2]
return ((al > bl) or ((al == bl) and (ac > bc)))
end
_2amodule_locals_2a["distance-gt"] = distance_gt
local function range_distance(range)
local _let_26_ = range.start
local sl = _let_26_[1]
local sc = _let_26_[2]
local _let_27_ = range["end"]
local el = _let_27_[1]
local ec = _let_27_[2]
return {(sl - el), (sc - ec)}
end
_2amodule_locals_2a["range-distance"] = range_distance
local function form(opts)
local forms
local function _28_(_241)
return form_2a(_241, opts)
end
forms = a.filter(a["table?"], a.map(_28_, config["get-in"]({"extract", "form_pairs"})))
local function _29_(_241, _242)
return distance_gt(range_distance(_241.range), range_distance(_242.range))
end
table.sort(forms, _29_)
if opts["root?"] then
return a.last(forms)
else
return a.first(forms)
end
end
_2amodule_2a["form"] = form
return _2amodule_2a
|
--[[
Goal: evaluate Lua expression.
Start: 2006-02-?? by Shmuel Zeigerman
--]]
local sd = require "far2.simpledialog"
local M = require "lf4ed_message"
local F = far.Flags
local function ErrMsg (msg)
far.Message(msg, M.MError, M.MOk, "w")
end
local function GetNearestWord (pattern)
local line = editor.GetString(nil, 2)
local pos = editor.GetInfo().CurPos
local r = regex.new(pattern)
local start = 1
while true do
local from, to, word = r:find(line, start)
if not from then break end
if pos <= to then return from, to, word end
start = to + 1
end
end
local function GetAllText()
local ei = editor.GetInfo()
if ei then
local t = {}
for n = 1, ei.TotalLines do
local str = editor.GetString(n, 2)
table.insert(t, str)
end
editor.SetPosition(ei)
return table.concat(t, "\n")
end
end
local function GetSelectedText()
local ei = editor.GetInfo()
if ei and ei.BlockType ~= F.BTYPE_NONE then
local t = {}
local n = ei.BlockStartLine
while true do
local s = editor.GetString(n, 1)
if not s or s.SelStart == 0 then
break
end
local sel = s.StringText:sub (s.SelStart, s.SelEnd)
table.insert(t, sel)
n = n + 1
end
editor.SetPosition(ei)
return table.concat(t, "\n"), n-1
end
end
local function CompileParams (s1, s2, s3, s4)
local p1 = assert(loadstring("return "..s1, "Parameter #1"))
local p2 = assert(loadstring("return "..s2, "Parameter #2"))
local p3 = assert(loadstring("return "..s3, "Parameter #3"))
local p4 = assert(loadstring("return "..s4, "Parameter #4"))
return p1, p2, p3, p4
end
local function ParamsDialog (aData)
local HIST_PARAM = "LuaFAR\\LuaScript\\Parameter"
local Items = {
width = 56;
help = "ScriptParams";
guid = "D0CDAE16-C402-4E54-9D23-7150A8D87787";
{tp="dbox"; text=M.MScriptParams; },
{tp="text"; text="&1."; ystep=2; width=2; },
{tp="edit"; name="sParam1"; ystep=0; x1=8; hist=HIST_PARAM; },
{tp="text"; text="&2."; ystep=2; width=2; },
{tp="edit"; name="sParam2"; ystep=0; x1=8; hist=HIST_PARAM; },
{tp="text"; text="&3."; ystep=2; width=2; },
{tp="edit"; name="sParam3"; ystep=0; x1=8; hist=HIST_PARAM; },
{tp="text"; text="&4."; ystep=2; width=2; },
{tp="edit"; name="sParam4"; ystep=0; x1=8; hist=HIST_PARAM; },
{tp="chbox"; name="bParamsEnable"; ystep=2; text=M.MScriptParamsEnable; },
{tp="sep"; },
{tp="butt"; text=M.MRunScript; default=1; centergroup=1; Run=1; },
{tp="butt"; text=M.MStoreParams; centergroup=1; Store=1; },
{tp="butt"; text=M.MCancel; cancel=1; centergroup=1; },
}
------------------------------------------------------------------------------
Items.closeaction = function(hDlg, par1, out)
local ok, msg = pcall(CompileParams, out.sParam1, out.sParam2, out.sParam3, out.sParam4)
if not ok then ErrMsg(msg); return 0; end
end
------------------------------------------------------------------------------
sd.LoadData(aData, Items)
local out,pos = sd.Run(Items)
if out then
sd.SaveData(out, aData)
return Items[pos].Run and "run" or Items[pos].Store and "store"
end
end
-- WARNING:
-- don't change the string literals "selection" and "all text",
-- since export.OnError relies on them being exactly such.
local function LuaScript (data)
local text, chunkname = GetSelectedText(), "selection"
if not text then
text, chunkname = GetAllText(), "all text"
if text and text:sub(1,1)=="#" then text = "--"..text end
end
if text then
local chunk, msg = loadstring(text, chunkname)
if not chunk then error(msg,3) end
if data.bParamsEnable then
local p1,p2,p3,p4 = CompileParams(data.sParam1, data.sParam2,
data.sParam3, data.sParam4)
p1 = p1(); p2 = p2(); p3 = p3(); p4 = p4()
return chunk (p1,p2,p3,p4)
else
return chunk()
end
end
end
local function ResultDialog (aHelpTopic, aData, result)
local Title = (aHelpTopic=="LuaExpression") and M.MExpr or M.MBlockSum
local XX1 = 5 + M.MResult:gsub("&",""):len() + 1
local Items = {
width = 46;
help = aHelpTopic;
{tp="dbox"; text=Title; },
{tp="text"; text=M.MResult; },
{tp="edit"; name="edtResult"; ystep=0; x1=XX1; val=result; noload=1; },
{tp="chbox"; name="cbxInsert"; text=M.MInsertText; },
{tp="chbox"; name="cbxCopy"; text=M.MCopyToClipboard; },
{tp="sep"; },
{tp="butt"; text=M.MOk; default=1; centergroup=1; },
{tp="butt"; text=M.MCancel; cancel=1; centergroup=1; },
}
------------------------------------------------------------------------------
sd.LoadData(aData, Items)
local out = sd.Run(Items)
if out then
sd.SaveData(out, aData)
return true
end
end
local function BlockSum (history)
local ei = assert(editor.GetInfo(), "EditorGetInfo failed")
local blockEndLine
local sum = 0
local x_start, x_dot, has_dots
local pattern = [[(\S[\w.]*)]]
if ei.BlockType ~= F.BTYPE_NONE then
local r = regex.new(pattern)
for n=ei.BlockStartLine, ei.TotalLines do
local s = editor.GetString (n)
if s.SelEnd == 0 or s.SelStart < 1 then
blockEndLine = n - 1
break
end
local start, fin, sel = r:find( s.StringText:sub(s.SelStart, s.SelEnd) ) -- 'start' in selection
if start then
x_start = editor.RealToTab(n, s.SelStart + start - 1) -- 'start' column in line
local num = tonumber(sel)
if num then
sum = sum + num
local x = regex.find(sel, "\\.")
if x then
has_dots = true
x_dot = x_start + x - 1 -- 'dot' column in line
else
x_dot = editor.RealToTab(n, s.SelStart + fin)
end
end
end
end
else
local start, fin, word = GetNearestWord(pattern)
if start then
x_start = editor.RealToTab(nil, start)
local num = tonumber(word)
if num then
sum = sum + num
local x = regex.find(word, "\\.")
if x then
has_dots = true
x_dot = x_start + x - 1
else
x_dot = editor.RealToTab(nil, 1 + fin)
end
end
end
end
if has_dots then
sum = tostring(sum)
local last = sum:match("%.(%d+)$")
sum = sum .. (last and ("0"):rep(2 - #last) or ".00")
end
if not ResultDialog("BlockSum", history, sum) then return end
sum = history.edtResult
if history.cbxCopy then
far.CopyToClipboard(sum)
end
if history.cbxInsert then
local y = blockEndLine or ei.CurLine -- position of the last line
local s = editor.GetString(y) -- get last line
editor.SetPosition (y, s.StringText:len()+1) -- insert a new line
editor.InsertString() -- +
local prefix = "="
if x_dot then
local x = regex.find(tostring(sum), "\\.") or #sum+1
if x then x_start = x_dot - (x - 1) end
end
if x_start then
x_start = x_start>#prefix and x_start-#prefix or 1
else
x_start = (ei.BlockType==F.BTYPE_COLUMN) and s.SelStart or 1
end
editor.SetPosition (y+1, x_start, nil, nil, ei.LeftPos)
editor.InsertText(prefix .. sum)
editor.Redraw()
else
editor.SetPosition (ei) -- restore the position
end
end
local function LuaExpr (history)
local edInfo = editor.GetInfo()
local text, numline = GetSelectedText()
if not text then
numline = edInfo.CurLine
text = editor.GetString(numline, 2)
end
local func, msg = loadstring("return " .. text)
if not func then
ErrMsg(msg) return
end
local env = {}
for k,v in pairs(math) do env[k]=v end
setmetatable(env, { __index=_G })
setfenv(func, env)
local ok, result = pcall(func)
if not ok then
ErrMsg(result) return
end
result = tostring(result)
if not ResultDialog("LuaExpression", history, result) then
return
end
result = history.edtResult
if history.cbxInsert then
local line = editor.GetString(numline)
local pos = (edInfo.BlockType==F.BTYPE_NONE) and line.StringLength or line.SelEnd
editor.SetPosition(numline, pos+1)
editor.InsertText(" = " .. result .. " ;")
editor.Redraw()
end
if history.cbxCopy then
far.CopyToClipboard(result)
end
end
local funcs = {
BlockSum = BlockSum,
LuaExpr = LuaExpr,
LuaScript = function(aData) return LuaScript(aData) end, -- keep errorlevel==3
ScriptParams = function(aData)
if ParamsDialog(aData) == "run" then return LuaScript(aData) end
end,
}
do
local op, data = ...
return assert (funcs[op])(data)
end
|
-- This is a part of uJIT's testing suite.
-- Copyright (C) 2020-2021 LuaVela Authors. See Copyright Notice in COPYRIGHT
-- Copyright (C) 2015-2020 IPONWEB Ltd. See Copyright Notice in COPYRIGHT
--
-- LuaJIT: demonstracni priklad cislo 53.
--
-- Test JITu - volani funkce
--
-- deklarace a inicializace lokalnich promennych
local x = 0
local y = 0
-- funkce, ktera se bude JITovat
local function adder()
x = x + 1
y = y + 1
end
-- programova smycka, ktera se neJITuje
for _ = 1,50 do
adder()
end
print("1")
-- programova smycka, ktera se neJITuje
for _ = 1,50 do
adder()
end
print("2")
-- programova smycka, ktera se neJITuje
for _ = 1,50 do
adder()
end
print("3")
print(x,y)
--
-- Finito.
--
|
-----------------------------------
-- Area: Open_sea_route_to_Mhaura
-- NPC: Sheadon
-- Notes: Tells ship ETA time
-- !pos 0.340 -12.232 -4.120 47
-----------------------------------
local ID = require("scripts/zones/Open_sea_route_to_Mhaura/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:messageSpecial(ID.text.ON_WAY_TO_MHAURA,0,0); -- Earth Time, Vana Hours. Needs a get-time function for boat?
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
require('lualine').setup {
options = {
icons_enabled = false,
theme = 'gruvbox_dark',
component_separators = '',
section_separators = '',
},
sections = {
lualine_a = {'mode'},
lualine_b = {},
lualine_c = {
{
'filename',
path = 1,
shorting_target = 0,
symbols = {
readonly = '[RO]',
}
}
},
lualine_x = {},
lualine_y = {'branch'},
lualine_z = {'%l:%c', '%p%%'}
}
}
|
------------------------------------------------------------------------
--[[ NarrowDictionary ]]--
-- Adapts a nn.NarrowLookupTable
------------------------------------------------------------------------
local NarrowDictionary, parent = torch.class("dp.NarrowDictionary", "dp.Dictionary")
NarrowDictionary.isNarrowDictionary = true
function NarrowDictionary:__init(config)
assert(type(config) == 'table', "Constructor requires key-value arguments")
local args, dict_size, output_size, delta_size, typename
= xlua.unpack(
{config},
'NarrowDictionary',
'adapts a nn.LookupTable',
{arg='dict_size', type='number', req=true,
help='Number of entries in the dictionary (e.g. num of words)'},
{arg='output_size', type='number', req=true,
help='Number of neurons per entry.'},
{arg='delta_size', type='number', req=true,
help='Size that each successive item in the context looses'},
{arg='typename', type='string', default='dictionary',
help='identifies Model type in reports.'}
)
assert(not config.dropout,
"NarrowDictionary doesn't work with dropout")
assert(not config.sparse_init,
"NarrowDictionary doesn't work with sparse_init")
config.sparse_init = false
self._dict_size = dict_size
self._output_size = output_size
self._delta_size = delta_size
self._lookup = nn.NarrowLookupTable(delta_size, dict_size, output_size, true)
self._module = self._lookup
config.typename = typename
config.input_type = 'torch.IntTensor'
config.tags = config.tags or {}
config.input_view = 'bt'
config.output_view = 'bf'
config.output = dp.DataView()
dp.Layer.__init(self, config)
if self._acc_update then
self._lookup:accUpdateOnly()
end
end
function NarrowDictionary:sharedClone()
local clone = torch.protoClone(self, {
dict_size = 1, output_size = 1, delta_size = 1,
typename=self._typename, gather_stats=self._gather_stats,
input_type=self._input_type, output_type=self._output_type,
module_type=self._module_type, mvstate=self.mvstate
})
clone._dict_size = self._dict_size
clone._output_size = self._output_size
clone._delta_size = self._delta_size
if self._acc_update then
clone._lookup.gradWeight:resizeAs(self._lookup.gradWeight)
end
clone._lookup.batchSize = self._lookup.batchSize
return self:share(clone, 'weight')
end
|
object_tangible_food_crafted_beastfood_cooked_fish_substitute = object_tangible_food_crafted_shared_beastfood_cooked_fish_substitute:new {
}
ObjectTemplates:addTemplate(object_tangible_food_crafted_beastfood_cooked_fish_substitute, "object/tangible/food/crafted/beastfood_cooked_fish_substitute.iff")
|
MainMenuBarLeftEndCap:Hide()
MainMenuBarRightEndCap:Hide()
|
textutils.pagedPrint([[To customize your fireworks show, StarCaster must be set to Show Type: Fancy
StarCaster randomly generates fireworks based on the parameters you supply and the inventory you've loaded into the fireworks launcher. StarCaster recognizes creative launchers and responds accordingly - no need for any ingredients.
Basic help can be found by pressing F1 or right clicking on the less 'obvious' elements of the main screen.
Logs are avaible for all shows in a session and may be viewed by clicking the button at the top, left of the main screen. Logs are not written to disk.
StarCaster will use pre-loaded stars and fireworks before generating its own, however StarCaster will not automatically load any stars or fireworks that are in inventory. This *may* change in the future.
StarCaster generates a single firework, then launches it, and repeates this process for the entire show - canceling a show early should not result in lost materials or firework rockets/stars that need to be unloaded from the launcher's buffer.
Command line options:
StarCaster [debug] [fast] [fancy] [splash]
debug = automatically start a firework show in debug mode, then exit when done - no UI
fast = start StarCaster with 'Quick' launch timing enabled
fancy = start StarCaster with 'Fancy' show type selected.
splash = start StarCaster with a splash screen - if you really like splash screens
Valid Ingredients:
Colors:
Vanilla dyes:
Light Gray
Gray
Light Blue
Cyan
Lime
Pink
Purple
Magenta
Orange
Other vanilla color ingredients:
Cactus green
Rose red
Dandelion yellow
Lapis
Ink sac
Bone meal
Cocoa beans
Shapes:
Large Ball explosion - Fire charge
Star-Shaped explosion - Gold nugget
Creeper Face Shaped explosion - MoB head (any)
Burst explosion - Feather
Effects:
Twinkle - glowstone dust
Trail effect after explosion - diamond
]])
|
local SharedMedia = LibStub("LibSharedMedia-3.0");
local default = {
displayText = "New",
outline = true,
color = {1, 1, 1, 1},
justify = "LEFT",
selfPoint = "BOTTOM",
anchorPoint = "CENTER",
xOffset = 0,
yOffset = 0,
font = "Friz Quadrata TT",
fontSize = 12,
frameStrata = 1,
customTextUpdate = "update"
};
local function create(parent)
local region = CreateFrame("FRAME", nil, parent);
region:SetMovable(true);
local text = region:CreateFontString(nil, "OVERLAY");
region.text = text;
text:SetNonSpaceWrap(true);
region.values = {};
region.duration = 0;
region.expirationTime = math.huge;
return region;
end
local function modify(parent, region, data)
local text = region.text;
if(data.frameStrata == 1) then
region:SetFrameStrata(region:GetParent():GetFrameStrata());
else
region:SetFrameStrata(WeakAuras.frame_strata_types[data.frameStrata]);
end
local fontPath = SharedMedia:Fetch("font", data.font);
text:SetFont(fontPath, data.fontSize <= 35 and data.fontSize or 35, data.outline and "OUTLINE" or nil);
text:SetTextHeight(data.fontSize);
if text:GetFont() then
text:SetText(data.displayText);
else end
text.displayText = data.displayText;
text:SetJustifyH(data.justify);
text:ClearAllPoints();
text:SetPoint("CENTER", UIParent, "CENTER");
data.width = text:GetWidth();
data.height = text:GetHeight();
region:SetWidth(data.width);
region:SetHeight(data.height);
text:ClearAllPoints();
text:SetPoint(data.justify, region, data.justify);
region:ClearAllPoints();
region:SetPoint(data.selfPoint, parent, data.anchorPoint, data.xOffset, data.yOffset);
local function UpdateText()
local textStr = data.displayText;
for symbol, v in pairs(WeakAuras.dynamic_texts) do
textStr = textStr:gsub(symbol, region.values[v.value] or "?");
end
if(textStr ~= text.displayText) then
text:SetText(textStr);
end
if(#textStr ~= #text.displayText) then
data.width = text:GetWidth();
data.height = text:GetHeight();
region:SetWidth(data.width);
region:SetHeight(data.height);
if(data.parent and WeakAuras.regions[data.parent].region.ControlChildren) then
WeakAuras.regions[data.parent].region:ControlChildren();
else
region:ClearAllPoints();
region:SetPoint(data.selfPoint, parent, data.anchorPoint, data.xOffset, data.yOffset);
end
end
text.displayText = textStr;
end
if(data.displayText:find("%%c") and data.customText) then
local customTextFunc = WeakAuras.LoadFunction("return "..data.customText)
local values = region.values;
region.UpdateCustomText = function()
local custom = customTextFunc(region.expirationTime, region.duration, values.progress, values.duration, values.name, values.icon, values.stacks);
if(custom ~= values.custom) then
values.custom = custom;
UpdateText();
end
end
if(data.customTextUpdate == "update") then
WeakAuras.RegisterCustomTextUpdates(region);
else
WeakAuras.UnregisterCustomTextUpdates(region);
end
else
region.UpdateCustomText = nil;
WeakAuras.UnregisterCustomTextUpdates(region);
end
function region:Color(r, g, b, a)
region.color_r = r;
region.color_g = g;
region.color_b = b;
region.color_a = a;
text:SetTextColor(r, g, b, a);
end
function region:GetColor()
return region.color_r or data.color[1], region.color_g or data.color[2],
region.color_b or data.color[3], region.color_a or data.color[4];
end
region:Color(data.color[1], data.color[2], data.color[3], data.color[4]);
local function UpdateTime()
local remaining = region.expirationTime - GetTime();
local progress = remaining / region.duration;
if(data.inverse) then
progress = 1 - progress;
end
progress = progress > 0.0001 and progress or 0.0001;
local remainingStr = "";
if(remaining == math.huge) then
remainingStr = " ";
elseif(remaining > 60) then
remainingStr = string.format("%i:", math.floor(remaining / 60));
remaining = remaining % 60;
remainingStr = remainingStr..string.format("%02i", remaining);
elseif(remaining > 0) then
remainingStr = remainingStr..string.format("%."..(data.progressPrecision or 1).."f", remaining);
else
remainingStr = " ";
end
region.values.progress = remainingStr;
local duration = region.duration;
local durationStr = "";
if(duration > 60) then
durationStr = string.format("%i:", math.floor(duration / 60));
duration = duration % 60;
durationStr = durationStr..string.format("%02i", duration);
elseif(duration > 0) then
durationStr = durationStr..string.format("%."..(data.totalPrecision or 1).."f", duration);
else
durationStr = "INF";
end
region.values.duration = durationStr;
UpdateText();
end
local function UpdateValue(value, total)
region.values.progress = value;
region.values.duration = total;
UpdateText();
end
local function UpdateCustom()
UpdateValue(region.customValueFunc(data.trigger));
end
function region:SetDurationInfo(d, expirationTime, customValue)
local duration = d
if not duration then duration = 0 end
local regionDuration = region.duration
if not regionDuration then regionDuration = 0 end
if(duration <= 0.01 or duration > regionDuration or not data.stickyDuration) then
region.duration = duration;
end
region.expirationTime = expirationTime;
if(customValue) then
if(type(customValue) == "function") then
local value, total = customValue(data.trigger);
if(total > 0 and value < total) then
region.customValueFunc = customValue;
region:SetScript("OnUpdate", UpdateCustom);
else
UpdateValue(duration, expirationTime);
region:SetScript("OnUpdate", nil);
UpdateText();
end
else
UpdateValue(duration, expirationTime);
region:SetScript("OnUpdate", nil);
end
else
if(duration > 0.01) then
region:SetScript("OnUpdate", UpdateTime);
else
region:SetScript("OnUpdate", nil);
UpdateText();
end
end
end
function region:SetStacks(count)
if(count and count > 0) then
region.values.stacks = count;
else
region.values.stacks = 0;
end
UpdateText();
end
function region:SetIcon(path)
local icon = (
WeakAuras.CanHaveAuto(data)
and path ~= ""
and path
or data.displayIcon
or "Interface\\Icons\\INV_Misc_QuestionMark"
);
region.values.icon = "|T"..icon..":12:12:0:0:64:64:4:60:4:60|t";
UpdateText();
end
function region:SetName(name)
region.values.name = WeakAuras.CanHaveAuto(data) and name or data.id;
UpdateText();
end
UpdateText();
end
WeakAuras.RegisterRegionType("text", create, modify, default);
|
local GetNumGroupMembers = GetNumGroupMembers;
local twipe = table.wipe;
local tonumber = tonumber;
local pairs = pairs;
local ipairs = ipairs;
local _;
VUHDO_GROUP_SIZE = 1;
VUHDO_PROFILES = { };
local VUHDO_DEFAULT_PROFILES = {
{
["NAME"] = VUHDO_I18N_DEF_BIT_O_GRID,
["CONFIG"] = {
["DIRECTION"] = {
["isAlways"] = false,
["isDistanceText"] = false,
["enable"] = true,
["isDeadOnly"] = false,
["scale"] = 50,
},
["MODE"] = 1,
["IS_SHOW_GCD"] = false,
["SHOW_PLAYER_TAGS"] = true,
["SHOW_OVERHEAL"] = true,
--["doCompress"] = true,
["EMERGENCY_TRIGGER"] = 100,
["SHOW_INCOMING"] = true,
["HIDE_EMPTY_BUTTONS"] = false,
["LOCK_CLICKS_THROUGH"] = false,
["CUSTOM_DEBUFF"] = {
["animate"] = true,
["scale"] = 0.8,
["isIcon"] = true,
["selected"] = "",
["TIMER_TEXT"] = {
["X_ADJUST"] = 20,
["USE_MONO"] = false,
["Y_ADJUST"] = 26,
["ANCHOR"] = "BOTTOMRIGHT",
["USE_OUTLINE"] = false,
["SCALE"] = 85,
["COLOR"] = {
["TG"] = 1,
["R"] = 0,
["TB"] = 1,
["G"] = 0,
["TR"] = 1,
["TO"] = 1,
["B"] = 0,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["FONT"] = "Interface\\AddOns\\VuhDo\\Fonts\\ariblk.ttf",
["USE_SHADOW"] = true,
},
["yAdjust"] = -34,
["isColor"] = false,
["isStacks"] = false,
["COUNTER_TEXT"] = {
["X_ADJUST"] = -10,
["USE_MONO"] = false,
["Y_ADJUST"] = -15,
["ANCHOR"] = "TOPLEFT",
["USE_OUTLINE"] = false,
["SCALE"] = 70,
["COLOR"] = {
["TG"] = 1,
["R"] = 0,
["TB"] = 0,
["G"] = 0,
["TR"] = 0,
["TO"] = 1,
["B"] = 0,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["FONT"] = "Interface\\AddOns\\VuhDo\\Fonts\\ariblk.ttf",
["USE_SHADOW"] = true,
},
["point"] = "TOPRIGHT",
["timer"] = true,
["isName"] = false,
["xAdjust"] = -2,
["max_num"] = 3,
},
["SPELL_TRACE"] = {
["isMine"] = true,
["isOthers"] = false,
["duration"] = 2,
["showTrailOfLight"] = false,
["selected"] = "",
},
["SHOW_TEXT_OVERHEAL"] = true,
},
["LOCKED"] = false,
["HARDLOCKED"] = true,
["PANEL_POSITIONS"] = {
{
["y"] = 458.0802990022318,
["x"] = 649.5469195970409,
["orientation"] = "TOPLEFT",
["relativePoint"] = "BOTTOMLEFT",
["scale"] = 1,
["height"] = 56,
["growth"] = "TOPLEFT",
["width"] = 56,
}, -- [1]
},
["INDICATOR_CONFIG"] = {
["CUSTOM"] = {
["THREAT_BAR"] = {
["invertGrowth"] = false,
["turnAxis"] = false,
["HEIGHT"] = 4,
["WARN_AT"] = 85,
["TEXTURE"] = "VuhDo - Polished Wood",
},
["MOUSEOVER_HIGHLIGHT"] = {
["TEXTURE"] = "LiteStepLite",
},
["AGGRO_BAR"] = {
["TEXTURE"] = "VuhDo - Polished Wood",
},
["BACKGROUND_BAR"] = {
["TEXTURE"] = "VuhDo - Gradient",
},
["CLUSTER_BORDER"] = {
["WIDTH"] = 2,
},
["SWIFTMEND_INDICATOR"] = {
["SCALE"] = 1,
},
["SIDE_RIGHT"] = {
["turnAxis"] = false,
["vertical"] = true,
["invertGrowth"] = false,
["TEXTURE"] = "VuhDo - Plain White",
},
["BAR_BORDER"] = {
["WIDTH"] = 1,
},
["HEALTH_BAR"] = {
["turnAxis"] = true,
["vertical"] = true,
["invertGrowth"] = true,
},
["MANA_BAR"] = {
["turnAxis"] = false,
["invertGrowth"] = false,
["TEXTURE"] = "VuhDo - Pipe, light",
},
["SIDE_LEFT"] = {
["turnAxis"] = false,
["vertical"] = true,
["invertGrowth"] = false,
["TEXTURE"] = "VuhDo - Plain White",
},
},
["BOUQUETS"] = {
["THREAT_BAR"] = "",
["MOUSEOVER_HIGHLIGHT"] = VUHDO_I18N_GRID_MOUSEOVER_SINGLE,
["AGGRO_BAR"] = "",
["BACKGROUND_BAR"] = VUHDO_I18N_GRID_BACKGROUND_BAR,
["HEALTH_BAR_PANEL"] = {
"", -- [1]
"", -- [2]
"", -- [3]
"", -- [4]
"", -- [5]
"", -- [6]
"", -- [7]
"", -- [8]
"", -- [9]
"", -- [10]
},
["SIDE_LEFT"] = "",
["INCOMING_BAR"] = "",
["CLUSTER_BORDER"] = "",
["THREAT_MARK"] = "",
["SIDE_RIGHT"] = "",
["MANA_BAR"] = "",
["BAR_BORDER"] = VUHDO_I18N_DEF_BOUQUET_BORDER_MULTI,
["HEALTH_BAR"] = VUHDO_I18N_DEF_BOUQUET_BAR_HEALTH_CLASS_COLOR,
["DAMAGE_FLASH_BAR"] = "",
["SWIFTMEND_INDICATOR"] = "",
},
},
["ORIGINATOR_TOON"] = "Izaak",
["PANEL_SETUP"] = {
{
["OVERHEAL_TEXT"] = {
["show"] = false,
["yAdjust"] = 0,
["point"] = "LEFT",
["scale"] = 1,
["xAdjust"] = 0,
},
["POSITION"] = {
["y"] = 458.0803,
["x"] = 649.5469,
["scale"] = 1,
["relativePoint"] = "BOTTOMLEFT",
["orientation"] = "TOPLEFT",
["height"] = 56,
["growth"] = "TOPLEFT",
["width"] = 56,
},
["RAID_ICON"] = {
["show"] = true,
["yAdjust"] = -20,
["point"] = "TOP",
["scale"] = 1,
["xAdjust"] = 0,
},
["frameStrata"] = "MEDIUM",
["MODEL"] = {
["ordering"] = 0,
["groups"] = {
1, -- [1]
2, -- [2]
3, -- [3]
4, -- [4]
5, -- [5]
6, -- [6]
7, -- [7]
8, -- [8]
},
["sort"] = 0,
["isReverse"] = false,
},
["PANEL_COLOR"] = {
["BACK"] = {
["useOpacity"] = true,
["R"] = 0.235,
["B"] = 0.235,
["G"] = 0.235,
["O"] = 0.87,
["useBackground"] = true,
},
["HEADER"] = {
["TG"] = 0.859,
["R"] = 1,
["TB"] = 0.38,
["barTexture"] = "LiteStepLite",
["G"] = 1,
["TR"] = 1,
["font"] = "Interface\\AddOns\\VuhDo\\Fonts\\Emblem.ttf",
["TO"] = 1,
["B"] = 1,
["O"] = 0.4,
["useText"] = true,
["textSize"] = 10,
["useBackground"] = true,
},
["BORDER"] = {
["edgeSize"] = 16,
["B"] = 0.458,
["G"] = 0.45,
["useOpacity"] = true,
["R"] = 0.443,
["useBackground"] = true,
["file"] = "Interface\\Tooltips\\UI-Tooltip-Border",
["O"] = 1,
["insets"] = 4,
},
["barTexture"] = "VuhDo - Gradient",
["TEXT"] = {
["outline"] = false,
["font"] = "Fonts\\FRIZQT__.TTF",
["USE_MONO"] = false,
["useText"] = true,
["textSize"] = 11,
["useOpacity"] = true,
["textSizeLife"] = 8,
["maxChars"] = 4,
},
},
["HOTS"] = {
["size"] = 36,
},
["SCALING"] = {
["headerHeight"] = 16,
["rowSpacing"] = 5,
["arrangeHorizontal"] = false,
["scale"] = 1,
["maxColumnsWhenStructured"] = 8,
["barWidth"] = 32,
["columnSpacing"] = 5,
["borderGapY"] = 12,
["targetSpacing"] = 3,
["targetOrientation"] = 1,
["ommitEmptyWhenStructured"] = true,
["showTarget"] = false,
["maxRowsWhenLoose"] = 6,
["sideLeftWidth"] = 6,
["manaBarHeight"] = 3,
["headerSpacing"] = 5,
["borderGapX"] = 12,
["sideRightWidth"] = 6,
["totSpacing"] = 3,
["isPlayerOnTop"] = true,
["showHeaders"] = false,
["totWidth"] = 30,
["showTot"] = false,
["isDamFlash"] = true,
["headerWidth"] = 100,
["isTarClassColBack"] = false,
["targetWidth"] = 30,
["isTarClassColText"] = true,
["damFlashFactor"] = 0.75,
["barHeight"] = 32,
["alignBottom"] = false,
},
["LIFE_TEXT"] = {
["show"] = true,
["hideIrrelevant"] = false,
["position"] = 4,
["showTotalHp"] = false,
["mode"] = 3,
["verbose"] = false,
},
["ID_TEXT"] = {
["showClass"] = false,
["showName"] = true,
["showTags"] = true,
["position"] = "CENTER+CENTER",
["_spacing"] = 18.99999430662054,
["showPetOwners"] = false,
},
}, -- [1]
["PANEL_COLOR"] = {
["TEXT"] = {
["TR"] = 0.965,
["TO"] = 1,
["TB"] = 0.996,
["useText"] = true,
["TG"] = 1,
},
["BARS"] = {
["useOpacity"] = true,
["R"] = 0.7,
["B"] = 0.7,
["G"] = 0.7,
["O"] = 1,
["useBackground"] = true,
},
["classColorsName"] = true,
},
["HOTS"] = {
["SLOTS"] = {
[10] = "BOUQUET_" .. VUHDO_I18N_DEF_AOE_ADVICE,
},
["BARS"] = {
["radioValue"] = 1,
["width"] = 25,
},
["TIMER_TEXT"] = {
["X_ADJUST"] = 0,
["SCALE"] = 100,
["USE_MONO"] = false,
["Y_ADJUST"] = 0,
["FONT"] = "Fonts\\ARIALN.TTF",
["USE_SHADOW"] = false,
["ANCHOR"] = "CENTER",
["USE_OUTLINE"] = true,
},
["SLOTCFG"] = {
["10"] = {
["scale"] = 1.5,
["mine"] = true,
["others"] = false,
},
},
["iconRadioValue"] = 3,
["radioValue"] = 21,
["COUNTER_TEXT"] = {
["X_ADJUST"] = -25,
["SCALE"] = 66,
["USE_MONO"] = false,
["Y_ADJUST"] = 0,
["FONT"] = "Interface\\AddOns\\VuhDo\\Fonts\\ariblk.ttf",
["USE_SHADOW"] = false,
["ANCHOR"] = "TOPLEFT",
["USE_OUTLINE"] = true,
},
["stacksRadioValue"] = 1,
},
["BAR_COLORS"] = {
["OVERHEAL_TEXT"] = {
["useOpacity"] = true,
["TO"] = 1,
["TB"] = 0.8,
["TG"] = 1,
["useText"] = true,
["TR"] = 0.8,
},
["HOT7"] = {
["useBackground"] = true,
["R"] = 1,
["B"] = 1,
["G"] = 1,
["O"] = 0.75,
},
["HOT1"] = {
["TG"] = 0.6,
["countdownMode"] = 0,
["R"] = 1,
["TB"] = 0.6,
["G"] = 0.3,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.3,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["useDebuffIconBossOnly"] = true,
["BAR_FRAMES"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 0.7,
["useBackground"] = true,
},
["HOT9"] = {
["TG"] = 1,
["countdownMode"] = 0,
["R"] = 0.3,
["TB"] = 1,
["G"] = 1,
["TR"] = 0.6,
["TO"] = 1,
["B"] = 1,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["HOT_CHARGE_3"] = {
["TG"] = 1,
["R"] = 0.3,
["TB"] = 0.6,
["G"] = 1,
["TR"] = 0.6,
["TO"] = 1,
["B"] = 0.3,
["useBackground"] = true,
["O"] = 1,
["useText"] = true,
},
["DEBUFF3"] = {
["TG"] = 0.957,
["R"] = 0.4,
["TB"] = 1,
["G"] = 0.4,
["TR"] = 0.329,
["TO"] = 1,
["B"] = 0.8,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["INCOMING"] = {
["TG"] = 0.8254,
["R"] = 0,
["TB"] = 0,
["G"] = 0,
["TR"] = 1,
["TO"] = 1,
["B"] = 0,
["useBackground"] = false,
["useText"] = false,
["O"] = 0.33,
["useOpacity"] = true,
},
["DEBUFF4"] = {
["TG"] = 0,
["R"] = 0.7,
["TB"] = 1,
["G"] = 0,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.7,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["DEBUFF6"] = {
["TG"] = 0.5,
["R"] = 0.6,
["TB"] = 0,
["G"] = 0.3,
["TR"] = 0.8,
["TO"] = 1,
["B"] = 0,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["HOT5"] = {
["TG"] = 0.6,
["countdownMode"] = 0,
["R"] = 1,
["TB"] = 1,
["G"] = 0.3,
["TR"] = 1,
["TO"] = 1,
["B"] = 1,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["HOTS"] = {
["useColorText"] = true,
["useColorBack"] = true,
["isPumpDivineAegis"] = false,
["isFadeOut"] = false,
["isFlashWhenLow"] = false,
["showShieldAbsorb"] = true,
["WARNING"] = {
["enabled"] = false,
["lowSecs"] = 3,
["R"] = 0.5,
["TB"] = 0.6,
["G"] = 0.2,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.2,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["TG"] = 0.6,
},
},
["HOT2"] = {
["TG"] = 1,
["countdownMode"] = 0,
["R"] = 1,
["TB"] = 0.6,
["G"] = 1,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.3,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["DEAD"] = {
["TG"] = 0.5,
["R"] = 0.3,
["TB"] = 0.5,
["G"] = 0.3,
["TR"] = 0.5,
["TO"] = 1,
["B"] = 0.3,
["useBackground"] = true,
["useText"] = true,
["O"] = 0.5,
["useOpacity"] = true,
},
["useDebuffIcon"] = false,
["OFFLINE"] = {
["TG"] = 0.5760533102985354,
["R"] = 0.298,
["TB"] = 0.576,
["G"] = 0.298,
["TR"] = 0.5760535455434231,
["TO"] = 0.58,
["B"] = 0.298,
["useBackground"] = true,
["useText"] = true,
["O"] = 0.21,
["useOpacity"] = true,
},
["OUTRANGED"] = {
["TG"] = 0,
["R"] = 0,
["TB"] = 0,
["G"] = 0,
["TR"] = 0,
["TO"] = 0.5,
["B"] = 0,
["useBackground"] = false,
["useText"] = false,
["O"] = 0.2,
["useOpacity"] = true,
},
["CHARMED"] = {
["TG"] = 0.31,
["R"] = 0.51,
["TB"] = 0.31,
["G"] = 0.08254,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.263,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["HOT3"] = {
["TG"] = 1,
["countdownMode"] = 0,
["R"] = 0,
["TB"] = 1,
["G"] = 1,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.1765,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["HOT4"] = {
["TG"] = 0.815,
["countdownMode"] = 0,
["R"] = 0.301,
["TB"] = 1,
["G"] = 0.301,
["TR"] = 0.7881,
["TO"] = 1,
["B"] = 1,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["DEBUFF2"] = {
["TG"] = 0,
["R"] = 0.8,
["TB"] = 0,
["G"] = 0.4,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.4,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["DEBUFF0"] = {
["useBackground"] = false,
["useText"] = false,
["useOpacity"] = false,
},
["HOT8"] = {
["useBackground"] = true,
["R"] = 1,
["B"] = 1,
["G"] = 1,
["O"] = 0.75,
},
["HOT10"] = {
["TG"] = 1,
["countdownMode"] = 0,
["R"] = 0.3,
["TB"] = 0.3,
["G"] = 1,
["TR"] = 0.6,
["TO"] = 1,
["B"] = 0.3,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["HOT_CHARGE_4"] = {
["TG"] = 1,
["R"] = 0.8,
["TB"] = 1,
["G"] = 0.8,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.8,
["useBackground"] = true,
["O"] = 1,
["useText"] = true,
},
["DEBUFF1"] = {
["TG"] = 1,
["R"] = 0,
["TB"] = 0.6861,
["G"] = 0.592,
["TR"] = 0,
["TO"] = 1,
["B"] = 0.8,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["HOT_CHARGE_2"] = {
["TG"] = 1,
["R"] = 1,
["TB"] = 0.6,
["G"] = 1,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.3,
["useBackground"] = true,
["O"] = 1,
["useText"] = true,
},
},
},
["ORIGINATOR_CLASS"] = "PRIEST",
}, -- [1]
{
["NAME"] = VUHDO_I18N_DEF_VUHDO_ESQUE,
["CONFIG"] = {
["DIRECTION"] = {
["isAlways"] = false,
["isDistanceText"] = false,
["enable"] = true,
["isDeadOnly"] = false,
["scale"] = 75,
},
["MODE"] = 1,
["IS_SHOW_GCD"] = false,
["SHOW_PLAYER_TAGS"] = true,
["SHOW_OVERHEAL"] = true,
--["doCompress"] = true,
["EMERGENCY_TRIGGER"] = 100,
["SHOW_INCOMING"] = true,
["HIDE_EMPTY_BUTTONS"] = false,
["LOCK_CLICKS_THROUGH"] = false,
["SHOW_TEXT_OVERHEAL"] = true,
["SPELL_TRACE"] = {
["isMine"] = true,
["isOthers"] = false,
["duration"] = 2,
["showTrailOfLight"] = false,
["selected"] = "",
},
},
["LOCKED"] = false,
["HARDLOCKED"] = true,
["PANEL_POSITIONS"] = {
{
["y"] = 731.9998928801197,
["x"] = 42.82658437085802,
["scale"] = 1,
["relativePoint"] = "BOTTOMLEFT",
["orientation"] = "TOPLEFT",
["height"] = 55.9999836930366,
["growth"] = "TOPLEFT",
["width"] = 84.99999950797955,
}, -- [1]
{
["y"] = 733.706721371843,
["x"] = 131.5732897843692,
["scale"] = 1,
["relativePoint"] = "BOTTOMLEFT",
["orientation"] = "TOPLEFT",
["height"] = 30.99993554532138,
["growth"] = "TOPLEFT",
["width"] = 143.0000131439748,
}, -- [2]
{
["y"] = 668.8535725358685,
["x"] = 44.53297651073297,
["scale"] = 1,
["relativePoint"] = "BOTTOMLEFT",
["orientation"] = "TOPLEFT",
["height"] = 19.99999353344555,
["growth"] = "TOPLEFT",
["width"] = 84.99999051103423,
}, -- [3]
{
["y"] = 685.2200237420952,
["x"] = 140.9599377973693,
["scale"] = 1,
["relativePoint"] = "BOTTOMLEFT",
["orientation"] = "TOPLEFT",
["height"] = 82.99997856196622,
["growth"] = "TOPLEFT",
["width"] = 118.0000032332772,
}, -- [4]
{
["y"] = 668,
["x"] = 100,
["scale"] = 1,
["relativePoint"] = "BOTTOMLEFT",
["orientation"] = "TOPLEFT",
["height"] = 200,
["growth"] = "TOPLEFT",
["width"] = 200,
}
},
["INDICATOR_CONFIG"] = {
["CUSTOM"] = {
["THREAT_BAR"] = {
["invertGrowth"] = false,
["turnAxis"] = false,
["HEIGHT"] = 4,
["WARN_AT"] = 85,
["TEXTURE"] = "VuhDo - Polished Wood",
},
["MOUSEOVER_HIGHLIGHT"] = {
["TEXTURE"] = "VuhDo - Aluminium",
},
["AGGRO_BAR"] = {
["TEXTURE"] = "VuhDo - Polished Wood",
},
["BACKGROUND_BAR"] = {
["TEXTURE"] = "VuhDo - Minimalist",
},
["CLUSTER_BORDER"] = {
["WIDTH"] = 2,
},
["SWIFTMEND_INDICATOR"] = {
["SCALE"] = 1,
},
["SIDE_RIGHT"] = {
["turnAxis"] = false,
["vertical"] = true,
["invertGrowth"] = false,
["TEXTURE"] = "VuhDo - Plain White",
},
["BAR_BORDER"] = {
["WIDTH"] = 1,
},
["HEALTH_BAR"] = {
["turnAxis"] = false,
["vertical"] = false,
["invertGrowth"] = false,
},
["MANA_BAR"] = {
["turnAxis"] = false,
["invertGrowth"] = false,
["TEXTURE"] = "VuhDo - Pipe, light",
},
["SIDE_LEFT"] = {
["turnAxis"] = false,
["vertical"] = true,
["invertGrowth"] = false,
["TEXTURE"] = "VuhDo - Plain White",
},
},
["BOUQUETS"] = {
["THREAT_BAR"] = "",
["MOUSEOVER_HIGHLIGHT"] = "",
["AGGRO_BAR"] = "",
["BACKGROUND_BAR"] = VUHDO_I18N_DEF_BAR_BACKGROUND_SOLID,
["HEALTH_BAR_PANEL"] = {
"", -- [1]
"", -- [2]
"", -- [3]
"", -- [4]
"", -- [5]
"", -- [6]
"", -- [7]
"", -- [8]
"", -- [9]
"", -- [10]
},
["SIDE_LEFT"] = "",
["INCOMING_BAR"] = "",
["CLUSTER_BORDER"] = "",
["THREAT_MARK"] = "",
["SIDE_RIGHT"] = "",
["MANA_BAR"] = VUHDO_I18N_DEF_BOUQUET_BAR_MANA_ONLY,
["BAR_BORDER"] = VUHDO_I18N_DEF_BOUQUET_BORDER_MULTI_AGGRO,
["HEALTH_BAR"] = VUHDO_I18N_DEF_BOUQUET_BAR_HEALTH,
["DAMAGE_FLASH_BAR"] = "",
["SWIFTMEND_INDICATOR"] = VUHDO_I18N_DEF_BOUQUET_ROLE_AND_SUMMON,
},
},
["ORIGINATOR_TOON"] = "Izaak",
["PANEL_SETUP"] = {
{
["OVERHEAL_TEXT"] = {
["show"] = true,
["yAdjust"] = 0,
["point"] = "LEFT",
["scale"] = 1,
["xAdjust"] = 0,
},
["POSITION"] = {
["y"] = 731.9998928801197,
["x"] = 42.82658437085802,
["orientation"] = "TOPLEFT",
["relativePoint"] = "BOTTOMLEFT",
["scale"] = 1,
["height"] = 55.9999836930366,
["growth"] = "TOPLEFT",
["width"] = 84.99999950797955,
},
["RAID_ICON"] = {
["show"] = true,
["yAdjust"] = -20,
["point"] = "TOP",
["scale"] = 1,
["xAdjust"] = 0,
},
["frameStrata"] = "MEDIUM",
["MODEL"] = {
["ordering"] = 0,
["groups"] = {
1, -- [1]
2, -- [2]
3, -- [3]
4, -- [4]
5, -- [5]
6, -- [6]
7, -- [7]
8, -- [8]
},
["sort"] = 0,
["isReverse"] = false,
},
["TOOLTIP"] = {
["BACKGROUND"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 1,
["useBackground"] = true,
},
["inFight"] = false,
["BORDER"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 1,
["useBackground"] = true,
},
["showBuffs"] = false,
["show"] = true,
["x"] = 100,
["position"] = 2,
["SCALE"] = 1,
["y"] = -100,
["point"] = "TOPLEFT",
["relativePoint"] = "TOPLEFT",
},
["PANEL_COLOR"] = {
["BACK"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 0.4,
["useBackground"] = true,
},
["HEADER"] = {
["TG"] = 0.859,
["R"] = 1,
["TB"] = 0.38,
["barTexture"] = "LiteStepLite",
["G"] = 1,
["TR"] = 1,
["font"] = "Interface\\AddOns\\VuhDo\\Fonts\\Emblem.ttf",
["TO"] = 1,
["B"] = 1,
["O"] = 0.4,
["useText"] = true,
["textSize"] = 10,
["useBackground"] = true,
},
["BORDER"] = {
["edgeSize"] = 8,
["B"] = 0,
["G"] = 0,
["useOpacity"] = true,
["R"] = 0,
["useBackground"] = true,
["file"] = "Interface\\Tooltips\\UI-Tooltip-Border",
["O"] = 0.46,
["insets"] = 1,
},
["barTexture"] = "VuhDo - Polished Wood",
["TEXT"] = {
["outline"] = false,
["font"] = "Interface\\AddOns\\VuhDo\\Fonts\\Emblem.ttf",
["USE_MONO"] = false,
["useText"] = true,
["textSize"] = 10,
["useOpacity"] = true,
["textSizeLife"] = 8,
["maxChars"] = 0,
},
},
["HOTS"] = {
["size"] = 76,
},
["SCALING"] = {
["headerHeight"] = 16,
["rowSpacing"] = 2,
["arrangeHorizontal"] = false,
["scale"] = 1,
["maxColumnsWhenStructured"] = 8,
["barWidth"] = 75,
["columnSpacing"] = 5,
["borderGapY"] = 5,
["targetSpacing"] = 3,
["targetOrientation"] = 1,
["ommitEmptyWhenStructured"] = true,
["showTarget"] = false,
["maxRowsWhenLoose"] = 6,
["sideLeftWidth"] = 6,
["manaBarHeight"] = 3,
["headerSpacing"] = 5,
["borderGapX"] = 5,
["sideRightWidth"] = 6,
["totSpacing"] = 3,
["isPlayerOnTop"] = true,
["showHeaders"] = true,
["totWidth"] = 30,
["showTot"] = false,
["isDamFlash"] = true,
["headerWidth"] = 100,
["isTarClassColBack"] = false,
["targetWidth"] = 30,
["isTarClassColText"] = true,
["damFlashFactor"] = 0.75,
["barHeight"] = 25,
["alignBottom"] = false,
},
["LIFE_TEXT"] = {
["show"] = true,
["hideIrrelevant"] = false,
["position"] = 3,
["showTotalHp"] = false,
["mode"] = 1,
["verbose"] = false,
},
["ID_TEXT"] = {
["showClass"] = false,
["showName"] = true,
["showTags"] = true,
["position"] = "BOTTOMRIGHT+BOTTOMRIGHT",
["_spacing"] = 17.99999507979553,
["showPetOwners"] = true,
},
}, -- [1]
{
["OVERHEAL_TEXT"] = {
["show"] = true,
["yAdjust"] = 0,
["point"] = "LEFT",
["scale"] = 1,
["xAdjust"] = 0,
},
["POSITION"] = {
["y"] = 733.706721371843,
["x"] = 131.5732897843692,
["orientation"] = "TOPLEFT",
["relativePoint"] = "BOTTOMLEFT",
["scale"] = 1,
["height"] = 30.99993554532138,
["growth"] = "TOPLEFT",
["width"] = 143.0000131439748,
},
["RAID_ICON"] = {
["show"] = true,
["yAdjust"] = -20,
["point"] = "TOP",
["scale"] = 1,
["xAdjust"] = 0,
},
["frameStrata"] = "MEDIUM",
["MODEL"] = {
["ordering"] = 0,
["groups"] = {
41, -- [1]
},
["sort"] = 0,
["isReverse"] = false,
},
["TOOLTIP"] = {
["BACKGROUND"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 1,
["useBackground"] = true,
},
["inFight"] = false,
["BORDER"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 1,
["useBackground"] = true,
},
["showBuffs"] = false,
["show"] = true,
["x"] = 100,
["position"] = 2,
["SCALE"] = 1,
["y"] = -100,
["point"] = "TOPLEFT",
["relativePoint"] = "TOPLEFT",
},
["PANEL_COLOR"] = {
["BACK"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 0.4,
["useBackground"] = true,
},
["HEADER"] = {
["TG"] = 0.859,
["R"] = 1,
["TB"] = 0.38,
["barTexture"] = "LiteStepLite",
["G"] = 1,
["TR"] = 1,
["font"] = "Interface\\AddOns\\VuhDo\\Fonts\\Emblem.ttf",
["TO"] = 1,
["B"] = 1,
["O"] = 0.4,
["useText"] = true,
["textSize"] = 10,
["useBackground"] = true,
},
["BORDER"] = {
["edgeSize"] = 8,
["B"] = 0,
["G"] = 0,
["useOpacity"] = true,
["R"] = 0,
["useBackground"] = true,
["file"] = "Interface\\Tooltips\\UI-Tooltip-Border",
["O"] = 0.46,
["insets"] = 1,
},
["barTexture"] = "VuhDo - Polished Wood",
["TEXT"] = {
["outline"] = false,
["font"] = "Interface\\AddOns\\VuhDo\\Fonts\\Emblem.ttf",
["USE_MONO"] = false,
["useText"] = true,
["textSize"] = 12,
["useOpacity"] = true,
["textSizeLife"] = 8,
["maxChars"] = 0,
},
},
["HOTS"] = {
["size"] = 76,
},
["SCALING"] = {
["headerHeight"] = 16,
["rowSpacing"] = 2,
["arrangeHorizontal"] = false,
["scale"] = 1,
["maxColumnsWhenStructured"] = 8,
["barWidth"] = 100,
["columnSpacing"] = 5,
["borderGapY"] = 5,
["targetSpacing"] = 3,
["targetOrientation"] = 1,
["ommitEmptyWhenStructured"] = false,
["showTarget"] = true,
["maxRowsWhenLoose"] = 6,
["sideLeftWidth"] = 6,
["manaBarHeight"] = 3,
["headerSpacing"] = 5,
["borderGapX"] = 5,
["sideRightWidth"] = 6,
["totSpacing"] = 3,
["isPlayerOnTop"] = true,
["showHeaders"] = true,
["totWidth"] = 30,
["showTot"] = false,
["isDamFlash"] = true,
["headerWidth"] = 100,
["isTarClassColBack"] = false,
["targetWidth"] = 30,
["isTarClassColText"] = true,
["damFlashFactor"] = 0.75,
["barHeight"] = 26,
["alignBottom"] = false,
},
["LIFE_TEXT"] = {
["show"] = true,
["hideIrrelevant"] = false,
["position"] = 3,
["showTotalHp"] = false,
["mode"] = 1,
["verbose"] = false,
},
["ID_TEXT"] = {
["showClass"] = false,
["showName"] = true,
["showTags"] = true,
["position"] = "BOTTOMRIGHT+BOTTOMRIGHT",
["showPetOwners"] = true,
},
}, -- [2]
{
["OVERHEAL_TEXT"] = {
["show"] = true,
["yAdjust"] = 0,
["point"] = "LEFT",
["scale"] = 1,
["xAdjust"] = 0,
},
["POSITION"] = {
["y"] = 668.8535725358685,
["x"] = 44.53297651073297,
["orientation"] = "TOPLEFT",
["relativePoint"] = "BOTTOMLEFT",
["scale"] = 1,
["height"] = 19.99999353344555,
["growth"] = "TOPLEFT",
["width"] = 84.99999051103423,
},
["RAID_ICON"] = {
["show"] = true,
["yAdjust"] = -20,
["point"] = "TOP",
["scale"] = 1,
["xAdjust"] = 0,
},
["frameStrata"] = "MEDIUM",
["MODEL"] = {
["ordering"] = 1,
["groups"] = {
40, -- [1]
},
["sort"] = 0,
["isReverse"] = false,
},
["TOOLTIP"] = {
["BACKGROUND"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 1,
["useBackground"] = true,
},
["inFight"] = false,
["BORDER"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 1,
["useBackground"] = true,
},
["showBuffs"] = false,
["show"] = true,
["x"] = 100,
["position"] = 2,
["SCALE"] = 1,
["y"] = -100,
["point"] = "TOPLEFT",
["relativePoint"] = "TOPLEFT",
},
["PANEL_COLOR"] = {
["BACK"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 0.4,
["useBackground"] = true,
},
["HEADER"] = {
["TG"] = 0.859,
["R"] = 1,
["TB"] = 0.38,
["barTexture"] = "LiteStepLite",
["G"] = 1,
["TR"] = 1,
["font"] = "Interface\\AddOns\\VuhDo\\Fonts\\Emblem.ttf",
["TO"] = 1,
["B"] = 1,
["O"] = 0.4,
["useText"] = true,
["textSize"] = 10,
["useBackground"] = true,
},
["BORDER"] = {
["edgeSize"] = 8,
["B"] = 0,
["G"] = 0,
["useOpacity"] = true,
["R"] = 0,
["useBackground"] = true,
["file"] = "Interface\\Tooltips\\UI-Tooltip-Border",
["O"] = 0.46,
["insets"] = 1,
},
["barTexture"] = "VuhDo - Polished Wood",
["TEXT"] = {
["outline"] = false,
["font"] = "Interface\\AddOns\\VuhDo\\Fonts\\Emblem.ttf",
["USE_MONO"] = false,
["useText"] = true,
["textSize"] = 10,
["useOpacity"] = true,
["textSizeLife"] = 8,
["maxChars"] = 0,
},
},
["HOTS"] = {
["size"] = 76,
},
["SCALING"] = {
["headerHeight"] = 16,
["rowSpacing"] = 2,
["arrangeHorizontal"] = false,
["scale"] = 1,
["maxColumnsWhenStructured"] = 8,
["barWidth"] = 75,
["columnSpacing"] = 5,
["borderGapY"] = 5,
["targetSpacing"] = 3,
["targetOrientation"] = 1,
["ommitEmptyWhenStructured"] = false,
["showTarget"] = false,
["maxRowsWhenLoose"] = 6,
["sideLeftWidth"] = 6,
["manaBarHeight"] = 3,
["headerSpacing"] = 5,
["borderGapX"] = 5,
["sideRightWidth"] = 6,
["totSpacing"] = 3,
["isPlayerOnTop"] = true,
["showHeaders"] = true,
["totWidth"] = 30,
["showTot"] = false,
["isDamFlash"] = true,
["headerWidth"] = 100,
["isTarClassColBack"] = false,
["targetWidth"] = 30,
["isTarClassColText"] = true,
["damFlashFactor"] = 0.75,
["barHeight"] = 25,
["alignBottom"] = false,
},
["LIFE_TEXT"] = {
["show"] = true,
["hideIrrelevant"] = false,
["position"] = 3,
["showTotalHp"] = false,
["mode"] = 1,
["verbose"] = false,
},
["ID_TEXT"] = {
["showClass"] = false,
["showName"] = true,
["showTags"] = true,
["position"] = "BOTTOMRIGHT+BOTTOMRIGHT",
["showPetOwners"] = true,
},
}, -- [3]
{
["OVERHEAL_TEXT"] = {
["show"] = true,
["yAdjust"] = 0,
["point"] = "LEFT",
["scale"] = 1,
["xAdjust"] = 0,
},
["POSITION"] = {
["y"] = 685.2200237420952,
["x"] = 140.9599377973693,
["orientation"] = "TOPLEFT",
["relativePoint"] = "BOTTOMLEFT",
["scale"] = 1,
["height"] = 82.99997856196622,
["growth"] = "TOPLEFT",
["width"] = 118.0000032332772,
},
["RAID_ICON"] = {
["show"] = true,
["yAdjust"] = -20,
["point"] = "TOP",
["scale"] = 1,
["xAdjust"] = 0,
},
["frameStrata"] = "MEDIUM",
["MODEL"] = {
["ordering"] = 0,
["groups"] = {
42, -- [1]
},
["sort"] = 0,
["isReverse"] = false,
},
["TOOLTIP"] = {
["BACKGROUND"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 1,
["useBackground"] = true,
},
["inFight"] = false,
["BORDER"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 1,
["useBackground"] = true,
},
["showBuffs"] = false,
["show"] = true,
["x"] = 100,
["position"] = 2,
["SCALE"] = 1,
["y"] = -100,
["point"] = "TOPLEFT",
["relativePoint"] = "TOPLEFT",
},
["PANEL_COLOR"] = {
["BACK"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 0.4,
["useBackground"] = true,
},
["HEADER"] = {
["TG"] = 0.859,
["R"] = 1,
["TB"] = 0.38,
["barTexture"] = "LiteStepLite",
["G"] = 1,
["TR"] = 1,
["font"] = "Interface\\AddOns\\VuhDo\\Fonts\\Emblem.ttf",
["TO"] = 1,
["B"] = 1,
["O"] = 0.4,
["useText"] = true,
["textSize"] = 10,
["useBackground"] = true,
},
["BORDER"] = {
["edgeSize"] = 8,
["B"] = 0,
["G"] = 0,
["useOpacity"] = true,
["R"] = 0,
["useBackground"] = true,
["file"] = "Interface\\Tooltips\\UI-Tooltip-Border",
["O"] = 0.46,
["insets"] = 1,
},
["barTexture"] = "VuhDo - Polished Wood",
["TEXT"] = {
["outline"] = false,
["font"] = "Interface\\AddOns\\VuhDo\\Fonts\\Emblem.ttf",
["USE_MONO"] = false,
["useText"] = true,
["textSize"] = 10,
["useOpacity"] = true,
["textSizeLife"] = 8,
["maxChars"] = 0,
},
},
["HOTS"] = {
["size"] = 76,
},
["SCALING"] = {
["headerHeight"] = 16,
["rowSpacing"] = 2,
["arrangeHorizontal"] = false,
["scale"] = 1,
["maxColumnsWhenStructured"] = 8,
["barWidth"] = 75,
["columnSpacing"] = 5,
["borderGapY"] = 5,
["targetSpacing"] = 3,
["targetOrientation"] = 1,
["ommitEmptyWhenStructured"] = false,
["showTarget"] = true,
["maxRowsWhenLoose"] = 6,
["sideLeftWidth"] = 6,
["manaBarHeight"] = 3,
["headerSpacing"] = 5,
["borderGapX"] = 5,
["sideRightWidth"] = 6,
["totSpacing"] = 3,
["isPlayerOnTop"] = true,
["showHeaders"] = true,
["totWidth"] = 30,
["showTot"] = false,
["isDamFlash"] = true,
["headerWidth"] = 100,
["isTarClassColBack"] = false,
["targetWidth"] = 30,
["isTarClassColText"] = true,
["damFlashFactor"] = 0.75,
["barHeight"] = 25,
["alignBottom"] = false,
},
["LIFE_TEXT"] = {
["show"] = true,
["hideIrrelevant"] = false,
["position"] = 3,
["showTotalHp"] = false,
["mode"] = 1,
["verbose"] = false,
},
["ID_TEXT"] = {
["showClass"] = false,
["showName"] = true,
["showTags"] = true,
["position"] = "BOTTOMRIGHT+BOTTOMRIGHT",
["_spacing"] = 17.99999507979553,
["showPetOwners"] = true,
},
}, -- [4]
["PANEL_COLOR"] = {
["TEXT"] = {
["TR"] = 1,
["TO"] = 1,
["TB"] = 0,
["useText"] = true,
["TG"] = 0.82,
},
["BARS"] = {
["useOpacity"] = true,
["R"] = 0.7,
["B"] = 0.7,
["G"] = 0.7,
["O"] = 1,
["useBackground"] = true,
},
["classColorsName"] = false,
},
["HOTS"] = {
["SLOTS"] = {
[10] = "BOUQUET_" .. VUHDO_I18N_DEF_AOE_ADVICE,
},
["BARS"] = {
["radioValue"] = 1,
["width"] = 25,
},
["TIMER_TEXT"] = {
["X_ADJUST"] = 25,
["SCALE"] = 60,
["USE_MONO"] = false,
["Y_ADJUST"] = 0,
["FONT"] = "Interface\\AddOns\\VuhDo\\Fonts\\ariblk.ttf",
["USE_SHADOW"] = false,
["ANCHOR"] = "BOTTOMRIGHT",
["USE_OUTLINE"] = true,
},
["iconRadioValue"] = 2,
["radioValue"] = 20,
["COUNTER_TEXT"] = {
["X_ADJUST"] = -25,
["SCALE"] = 66,
["USE_MONO"] = false,
["Y_ADJUST"] = 0,
["FONT"] = "Interface\\AddOns\\VuhDo\\Fonts\\ariblk.ttf",
["USE_SHADOW"] = false,
["ANCHOR"] = "TOPLEFT",
["USE_OUTLINE"] = true,
},
["stacksRadioValue"] = 3,
},
["BAR_COLORS"] = {
["OVERHEAL_TEXT"] = {
["useOpacity"] = true,
["TO"] = 1,
["TB"] = 0.8,
["TG"] = 1,
["useText"] = true,
["TR"] = 0.8,
},
["HOT7"] = {
["useBackground"] = true,
["R"] = 1,
["B"] = 1,
["G"] = 1,
["O"] = 0.75,
},
["CLUSTER_FAIR"] = {
["TG"] = 1,
["R"] = 0.8,
["TB"] = 0,
["G"] = 0.8,
["TR"] = 1,
["TO"] = 1,
["B"] = 0,
["useBackground"] = true,
["O"] = 1,
["useText"] = true,
},
["HOT1"] = {
["TG"] = 0.6,
["countdownMode"] = 1,
["R"] = 1,
["TB"] = 0.6,
["G"] = 0.3,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.3,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["useDebuffIconBossOnly"] = true,
["EMERGENCY"] = {
["TG"] = 0.82,
["R"] = 1,
["TB"] = 0,
["G"] = 0,
["TR"] = 1,
["TO"] = 1,
["B"] = 0,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["BAR_FRAMES"] = {
["useOpacity"] = true,
["R"] = 0,
["B"] = 0,
["G"] = 0,
["O"] = 0.7,
["useBackground"] = true,
},
["HOT9"] = {
["TG"] = 1,
["countdownMode"] = 1,
["R"] = 0.3,
["TB"] = 1,
["G"] = 1,
["TR"] = 0.6,
["TO"] = 1,
["B"] = 1,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["HOT_CHARGE_3"] = {
["TG"] = 1,
["R"] = 0.3,
["TB"] = 0.6,
["G"] = 1,
["TR"] = 0.6,
["TO"] = 1,
["B"] = 0.3,
["useBackground"] = true,
["O"] = 1,
["useText"] = true,
},
["DEBUFF3"] = {
["TG"] = 0.957,
["R"] = 0.4,
["TB"] = 1,
["G"] = 0.4,
["TR"] = 0.329,
["TO"] = 1,
["B"] = 0.8,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["INCOMING"] = {
["TG"] = 0.82,
["R"] = 0,
["TB"] = 0,
["G"] = 0,
["TR"] = 1,
["TO"] = 1,
["B"] = 0,
["useBackground"] = false,
["useText"] = false,
["O"] = 0.33,
["useOpacity"] = true,
},
["HOT6"] = {
["useBackground"] = true,
["R"] = 1,
["B"] = 1,
["G"] = 1,
["O"] = 0.75,
},
["DEBUFF4"] = {
["TG"] = 0,
["R"] = 0.7,
["TB"] = 1,
["G"] = 0,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.7,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["DEBUFF6"] = {
["TG"] = 0.5,
["R"] = 0.6,
["TB"] = 0,
["G"] = 0.3,
["TR"] = 0.8,
["TO"] = 1,
["B"] = 0,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["HOT5"] = {
["TG"] = 0.6,
["countdownMode"] = 1,
["R"] = 1,
["TB"] = 1,
["G"] = 0.3,
["TR"] = 1,
["TO"] = 1,
["B"] = 1,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["HOTS"] = {
["useColorText"] = true,
["useColorBack"] = true,
["isPumpDivineAegis"] = false,
["isFadeOut"] = false,
["isFlashWhenLow"] = false,
["showShieldAbsorb"] = true,
["WARNING"] = {
["enabled"] = false,
["lowSecs"] = 3,
["R"] = 0.5,
["TB"] = 0.6,
["G"] = 0.2,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.2,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["TG"] = 0.6,
},
},
["HOT2"] = {
["TG"] = 1,
["countdownMode"] = 1,
["R"] = 1,
["TB"] = 0.6,
["G"] = 1,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.3,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["DEAD"] = {
["TG"] = 0.5,
["R"] = 0.3,
["TB"] = 0.5,
["G"] = 0.3,
["TR"] = 0.5,
["TO"] = 1,
["B"] = 0.3,
["useBackground"] = true,
["useText"] = true,
["O"] = 0.5,
["useOpacity"] = true,
},
["useDebuffIcon"] = false,
["OFFLINE"] = {
["TG"] = 0.576,
["R"] = 0.298,
["TB"] = 0.576,
["G"] = 0.298,
["TR"] = 0.576,
["TO"] = 0.58,
["B"] = 0.298,
["useBackground"] = true,
["useText"] = true,
["O"] = 0.21,
["useOpacity"] = true,
},
["OUTRANGED"] = {
["TG"] = 0,
["R"] = 0,
["TB"] = 0,
["G"] = 0,
["TR"] = 0,
["TO"] = 0.5,
["B"] = 0,
["useBackground"] = false,
["useText"] = false,
["O"] = 0.25,
["useOpacity"] = true,
},
["CHARMED"] = {
["TG"] = 0.31,
["R"] = 0.51,
["TB"] = 0.31,
["G"] = 0.082,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.263,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["HOT3"] = {
["TG"] = 1,
["countdownMode"] = 1,
["R"] = 1,
["TB"] = 1,
["G"] = 1,
["TR"] = 1,
["TO"] = 1,
["B"] = 1,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["HOT4"] = {
["TG"] = 0.6,
["countdownMode"] = 1,
["R"] = 0.3,
["TB"] = 1,
["G"] = 0.3,
["TR"] = 0.6,
["TO"] = 1,
["B"] = 1,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["DEBUFF2"] = {
["TG"] = 0,
["R"] = 0.8,
["TB"] = 0,
["G"] = 0.4,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.4,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["DEBUFF0"] = {
["useBackground"] = false,
["useText"] = false,
["useOpacity"] = false,
},
["HOT8"] = {
["useBackground"] = true,
["R"] = 1,
["B"] = 1,
["G"] = 1,
["O"] = 0.75,
},
["HOT10"] = {
["TG"] = 1,
["countdownMode"] = 1,
["R"] = 0.3,
["TB"] = 0.3,
["G"] = 1,
["TR"] = 0.6,
["TO"] = 1,
["B"] = 0.3,
["O"] = 1,
["useBackground"] = true,
["isFullDuration"] = false,
["useText"] = true,
},
["HOT_CHARGE_4"] = {
["TG"] = 1,
["R"] = 0.8,
["TB"] = 1,
["G"] = 0.8,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.8,
["useBackground"] = true,
["O"] = 1,
["useText"] = true,
},
["DEBUFF1"] = {
["TG"] = 1,
["R"] = 0,
["TB"] = 0.6860000000000001,
["G"] = 0.592,
["TR"] = 0,
["TO"] = 1,
["B"] = 0.8,
["useBackground"] = true,
["useText"] = true,
["O"] = 1,
["useOpacity"] = true,
},
["HOT_CHARGE_2"] = {
["TG"] = 1,
["R"] = 1,
["TB"] = 0.6,
["G"] = 1,
["TR"] = 1,
["TO"] = 1,
["B"] = 0.3,
["useBackground"] = true,
["O"] = 1,
["useText"] = true,
},
},
},
["ORIGINATOR_CLASS"] = "PRIEST",
}, -- [2]
};
--
local function VUHDO_compressAllProfileParts(aProfile)
aProfile["CONFIG"] = VUHDO_compressTable(aProfile["CONFIG"]);
aProfile["PANEL_SETUP"] = VUHDO_compressTable(aProfile["PANEL_SETUP"]);
aProfile["POWER_TYPE_COLORS"] = VUHDO_compressTable(aProfile["POWER_TYPE_COLORS"]);
aProfile["SPELL_CONFIG"] = VUHDO_compressTable(aProfile["SPELL_CONFIG"]);
aProfile["BUFF_SETTINGS"] = VUHDO_compressTable(aProfile["BUFF_SETTINGS"]);
aProfile["BUFF_ORDER"] = VUHDO_compressTable(aProfile["BUFF_ORDER"]);
aProfile["INDICATOR_CONFIG"] = VUHDO_compressTable(aProfile["INDICATOR_CONFIG"]);
end
--
local tAutoProfileIndices = { "1", "5", "10", "15", "20", "25", "30", "40" };
local tKey;
local function VUHDO_getBestProfileForSpecAndSize(aSpec, aSize)
for _, tIndex in ipairs(tAutoProfileIndices) do
tKey = "SPEC_" .. aSpec .. "_" .. tIndex;
if VUHDO_CONFIG["AUTO_PROFILES"][tKey] and aSize <= tonumber(tIndex) then
return VUHDO_CONFIG["AUTO_PROFILES"][tKey];
end
end
return nil;
end
--
local function VUHDO_getBestProfileForSpec(aSpec)
return VUHDO_CONFIG["AUTO_PROFILES"]["SPEC_" .. aSpec];
end
--
local function VUHDO_getBestProfileForSize(aSize)
for _, tIndex in ipairs(tAutoProfileIndices) do
if VUHDO_CONFIG["AUTO_PROFILES"][tIndex] and aSize <= tonumber(tIndex) then
return VUHDO_CONFIG["AUTO_PROFILES"][tIndex];
end
end
return nil;
end
--
local tSpec;
function VUHDO_getBestProfileAfterSpecChange()
tSpec = GetSpecialization();
return VUHDO_getBestProfileForSpecAndSize(tSpec, VUHDO_GROUP_SIZE)
or VUHDO_getBestProfileForSpec(tSpec)
or VUHDO_getBestProfileForSize(VUHDO_GROUP_SIZE);
end
--
function VUHDO_getBestProfileAfterSizeChange()
tSpec = GetSpecialization();
return VUHDO_getBestProfileForSpecAndSize(tSpec, VUHDO_GROUP_SIZE)
or VUHDO_getBestProfileForSize(VUHDO_GROUP_SIZE)
or VUHDO_getBestProfileForSpec(tSpec);
end
--
VUHDO_DEBUG_AUTO_PROFILE = nil;
VUHDO_IS_SHOWN_BY_GROUP = true;
local tIndex;
local VUHDO_PROFILE_CFG;
--
local tIsInPetBattle = false;
function VUHDO_setPetBattle(anIsStarted)
tIsInPetBattle = anIsStarted and VUHDO_CONFIG["HIDE_PANELS_PET_BATTLE"];
if VuhDoBuffWatchMainFrame and VUHDO_CONFIG["HIDE_PANELS_PET_BATTLE"] then
VUHDO_setBuffWatchForceHide(anIsStarted);
if anIsStarted then
VuhDoBuffWatchMainFrame:Hide();
else
VUHDO_reloadBuffPanel();
end
end
end
--
local tGroupSize;
local tProfile;
local tGroupType;
function VUHDO_getAutoProfile()
tGroupType = VUHDO_getCurrentGroupType();
if VUHDO_DEBUG_AUTO_PROFILE then
tGroupSize = VUHDO_DEBUG_AUTO_PROFILE;
elseif VUHDO_GROUP_TYPE_RAID == tGroupType or VUHDO_IS_CONFIG then
tGroupSize = GetNumGroupMembers();
if not VUHDO_IS_SHOWN_BY_GROUP and VUHDO_CONFIG["SHOW_PANELS"] and not tIsInPetBattle then
VUHDO_IS_SHOWN_BY_GROUP = true;
VUHDO_timeReloadUI(0.1);
end
elseif VUHDO_GROUP_TYPE_PARTY == tGroupType then
tGroupSize = GetNumGroupMembers();
if not VUHDO_IS_SHOWN_BY_GROUP then
if not VUHDO_CONFIG["HIDE_PANELS_PARTY"] and VUHDO_CONFIG["SHOW_PANELS"] and not tIsInPetBattle then
VUHDO_IS_SHOWN_BY_GROUP = true;
VUHDO_timeReloadUI(0.1);
end
elseif VUHDO_CONFIG["HIDE_PANELS_PARTY"] or tIsInPetBattle then
VUHDO_IS_SHOWN_BY_GROUP = false;
VUHDO_timeReloadUI(0.1);
end
else
tGroupSize = 1;
twipe(VUHDO_MAINTANK_NAMES);
if not VUHDO_IS_SHOWN_BY_GROUP then
if not VUHDO_CONFIG["HIDE_PANELS_SOLO"] and VUHDO_CONFIG["SHOW_PANELS"] and not tIsInPetBattle then
VUHDO_IS_SHOWN_BY_GROUP = true;
VUHDO_timeReloadUI(0.1);
end
elseif VUHDO_CONFIG["HIDE_PANELS_SOLO"] or tIsInPetBattle then
VUHDO_IS_SHOWN_BY_GROUP = false;
VUHDO_timeReloadUI(0.1);
end
end
if VUHDO_GROUP_SIZE ~= tGroupSize and tGroupSize > 0 then
VUHDO_GROUP_SIZE = tGroupSize;
tProfile = VUHDO_getBestProfileAfterSizeChange();
if tProfile ~= VUHDO_CONFIG["CURRENT_PROFILE"] then
return tProfile, tGroupSize;
end
end
return nil, nil;
end
---------------------------------------------------------------------------------
VUHDO_PROFILE_MODEL_MATCH_ALL = 0;
VUHDO_PROFILE_MODEL_MATCH_CLASS = 1;
VUHDO_PROFILE_MODEL_MATCH_TOON = 2;
VUHDO_PROFILE_MODEL_MATCH_NEVER = 99;
--
function VUHDO_getProfileNamedCompressed(aName)
for tIndex, tValue in pairs(VUHDO_PROFILES) do
if tValue["NAME"] == aName then
return tIndex, tValue;
end
end
return nil, nil;
end
--
function VUHDO_getProfileNamed(aName)
for tIndex, tValue in pairs(VUHDO_PROFILES) do
if (tValue["NAME"] == aName) then
local tNewValue = {
["NAME"] = tValue["NAME"],
["LOCKED"] = tValue["LOCKED"],
["HARDLOCKED"] = tValue["HARDLOCKED"],
["ORIGINATOR_CLASS"] = tValue["ORIGINATOR_CLASS"],
["ORIGINATOR_TOON"] = tValue["ORIGINATOR_TOON"],
["CONFIG"] = VUHDO_decompressIfCompressed(tValue["CONFIG"]),
["PANEL_SETUP"] = VUHDO_decompressIfCompressed(tValue["PANEL_SETUP"]),
["POWER_TYPE_COLORS"] = VUHDO_decompressIfCompressed(tValue["POWER_TYPE_COLORS"]),
["SPELL_CONFIG"] = VUHDO_decompressIfCompressed(tValue["SPELL_CONFIG"]),
["BUFF_SETTINGS"] = VUHDO_decompressIfCompressed(tValue["BUFF_SETTINGS"]),
["BUFF_ORDER"] = VUHDO_decompressIfCompressed(tValue["BUFF_ORDER"]),
["INDICATOR_CONFIG"] = VUHDO_decompressIfCompressed(tValue["INDICATOR_CONFIG"]),
["PANEL_POSITIONS"] = tValue["PANEL_POSITIONS"]
};
return tIndex, tNewValue;
end
end
return nil, nil;
end
--
local function VUHDO_createNewProfile(aName)
local _, tProfile = VUHDO_getProfileNamedCompressed(VUHDO_CONFIG["CURRENT_PROFILE"]);
local tPanelPositions = { };
for tCnt = 1, 10 do -- VUHDO_MAX_PANELS
tPanelPositions[tCnt] = VUHDO_deepCopyTable(VUHDO_PANEL_SETUP[tCnt]["POSITION"]);
end
local tProfile = {
["NAME"] = aName,
["LOCKED"] = tProfile ~= nil and tProfile["LOCKED"],
["HARDLOCKED"] = false,
["ORIGINATOR_CLASS"] = VUHDO_PLAYER_CLASS,
["ORIGINATOR_TOON"] = VUHDO_PLAYER_NAME,
["CONFIG"] = VUHDO_CONFIG,
["PANEL_SETUP"] = VUHDO_PANEL_SETUP,
["POWER_TYPE_COLORS"] = VUHDO_POWER_TYPE_COLORS,
["SPELL_CONFIG"] = VUHDO_SPELL_CONFIG,
["BUFF_SETTINGS"] = VUHDO_BUFF_SETTINGS,
["BUFF_ORDER"] = VUHDO_BUFF_ORDER,
["INDICATOR_CONFIG"] = VUHDO_INDICATOR_CONFIG,
["PANEL_POSITIONS"] = tPanelPositions;
};
VUHDO_compressAllProfileParts(tProfile);
return tProfile;
end
--
function VUHDO_createNewProfileName(aName, aUnitName)
local tIdx = 1;
local tProfile = { };
local tPrefix = aUnitName .. ": ";
while tProfile do
tNewName = tPrefix .. aName;
_, tProfile = VUHDO_getProfileNamedCompressed(tNewName);
tIdx = tIdx + 1;
tPrefix = aUnitName .. "(" .. tIdx .. "): ";
end
return tNewName;
end
--
function VUHDO_createNewLayoutName(aName, aUnitName)
local tIdx = 1;
local tLayout = { };
local tPrefix = aUnitName .. ": ";
while tLayout do
tNewName = tPrefix .. aName;
tLayout = VUHDO_SPELL_LAYOUTS[tNewName];
tIdx = tIdx + 1;
tPrefix = aUnitName .. "(" .. tIdx .. "): ";
end
return tNewName;
end
--
local VUHDO_TARGET_PROFILE_NAME = nil;
local function VUHDO_askSaveProfileCallback(aButtonNum)
local _, tProfile = VUHDO_getProfileNamedCompressed(VUHDO_TARGET_PROFILE_NAME);
if tProfile and aButtonNum == 2 and tProfile["HARDLOCKED"] then
VUHDO_Msg("This profile is hardlocked. It has been copied locally.");
aButtonNum = 1;
end
if 1 == aButtonNum then -- Copy
VUHDO_TARGET_PROFILE_NAME = VUHDO_createNewProfileName(VUHDO_TARGET_PROFILE_NAME, VUHDO_PLAYER_NAME);
VUHDO_CONFIG["CURRENT_PROFILE"] = VUHDO_TARGET_PROFILE_NAME;
VUHDO_CURRENT_PROFILE = VUHDO_TARGET_PROFILE_NAME;
VUHDO_IS_DEFAULT_PROFILE = false;
if (VUHDO_CURR_LAYOUT ~= nil) then
VUHDO_CURR_LAYOUT = VUHDO_createNewLayoutName(VUHDO_CURR_LAYOUT, VUHDO_PLAYER_NAME);
VUHDO_SPEC_LAYOUTS["selected"] = VUHDO_CURR_LAYOUT;
VUHDO_IS_DEFAULT_LAYOUT = false;
end
elseif 2 == aButtonNum then -- Overwrite
elseif 3 == aButtonNum then-- Discard
return;
end
local tIndex, _ = VUHDO_getProfileNamedCompressed(VUHDO_TARGET_PROFILE_NAME);
if not tIndex then
tIndex = #VUHDO_PROFILES + 1;
end
VUHDO_PROFILES[tIndex] = VUHDO_createNewProfile(VUHDO_TARGET_PROFILE_NAME);
if 1 == aButtonNum then
VUHDO_PROFILES[tIndex]["HARDLOCKED"] = false;
end
if VUHDO_IS_DEFAULT_PROFILE then
VUHDO_DEFAULT_PROFILE = VUHDO_PROFILES[tIndex]["NAME"];
elseif VUHDO_DEFAULT_PROFILE == VUHDO_PROFILES[tIndex]["NAME"] then
VUHDO_DEFAULT_PROFILE = nil;
end
VUHDO_Msg(VUHDO_I18N_PROFILE_SAVED .. "\"" .. VUHDO_TARGET_PROFILE_NAME .. "\".");
VUHDO_updateProfileSelectCombo();
if ((VUHDO_CURR_LAYOUT or "") == "") then
VUHDO_SPEC_LAYOUTS["selected"] = "";
elseif ((VUHDO_SPEC_LAYOUTS["selected"] or "") ~= "") then
VUHDO_CURR_LAYOUT = VUHDO_SPEC_LAYOUTS["selected"];
VUHDO_saveKeyLayoutCallback(VUHDO_YES);
end
end
--
function VUHDO_saveProfile(aName)
local tExistingIndex, tExistingProfile = VUHDO_getProfileNamedCompressed(aName);
if tExistingProfile then
VUHDO_TARGET_PROFILE_NAME = aName;
if tExistingProfile["ORIGINATOR_TOON"] ~= VUHDO_PLAYER_NAME and not VUHDO_CONFIG["IS_ALWAYS_OVERWRITE_PROFILE"] then
VuhDoThreeSelectFrameText:SetText(
VUHDO_I18N_PROFILE_OVERWRITE_1 .. " \"" .. aName .. "\" "
.. VUHDO_I18N_PROFILE_OVERWRITE_2 .. " (" .. tExistingProfile["ORIGINATOR_TOON"] .. ")."
.. VUHDO_I18N_PROFILE_OVERWRITE_3
);
VuhDoThreeSelectFrameButton1:SetText(VUHDO_I18N_COPY);
VuhDoThreeSelectFrameButton2:SetText(VUHDO_I18N_OVERWRITE);
VuhDoThreeSelectFrameButton3:SetText(VUHDO_I18N_DISCARD);
VuhDoThreeSelectFrame:SetAttribute("callback", VUHDO_askSaveProfileCallback);
VuhDoThreeSelectFrame:Show();
else
VUHDO_askSaveProfileCallback(2);
end
else
VUHDO_TARGET_PROFILE_NAME = aName;
VUHDO_askSaveProfileCallback(2);
end
end
--
function VUHDO_saveCurrentProfile()
local _, tProfile = VUHDO_getProfileNamedCompressed(VUHDO_CONFIG["CURRENT_PROFILE"]);
if tProfile and not tProfile["LOCKED"] then
VUHDO_saveProfile(VUHDO_CONFIG["CURRENT_PROFILE"]);
end
end
--
function VUHDO_saveCurrentProfilePanelPosition(aPanelNum)
local _, tProfile = VUHDO_getProfileNamedCompressed(VUHDO_CONFIG["CURRENT_PROFILE"]);
if tProfile then
if not tProfile["PANEL_POSITIONS"] then
tProfile["PANEL_POSITIONS"] = { };
end
tProfile["PANEL_POSITIONS"][aPanelNum] = VUHDO_deepCopyTable(VUHDO_PANEL_SETUP[aPanelNum]["POSITION"]);
end
end
--
local function VUHDO_isProfileRuleAllowed(tRule, aClass, aToon)
if VUHDO_PROFILE_MODEL_MATCH_ALL == tRule then
return true;
elseif VUHDO_PROFILE_MODEL_MATCH_CLASS == tRule then
return VUHDO_PLAYER_CLASS == aClass;
elseif VUHDO_PROFILE_MODEL_MATCH_TOON == tRule then
return VUHDO_PLAYER_NAME == aToon;
elseif VUHDO_PROFILE_MODEL_MATCH_NEVER == tRule then
return false;
else
return true;
end
end
local VUHDO_PER_PANEL_PROFILE_MODEL = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_ALL,
}
local VUHDO_PROFILE_MODEL = {
["CONFIG"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_ALL,
["RANGE_SPELL"] = VUHDO_PROFILE_MODEL_MATCH_NEVER,
["RANGE_PESSIMISTIC"] = VUHDO_PROFILE_MODEL_MATCH_NEVER,
["CURRENT_PROFILE"] = VUHDO_PROFILE_MODEL_MATCH_NEVER,
["IS_CLIQUE_COMPAT_MODE"] = VUHDO_PROFILE_MODEL_MATCH_NEVER,
["IS_CLIQUE_PASSTHROUGH"] = VUHDO_PROFILE_MODEL_MATCH_NEVER,
["AUTO_PROFILES"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_NEVER,
},
["CLUSTER"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_CLASS,
},
["AOE_ADVISOR"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_CLASS,
},
},
["PANEL_SETUP"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_ALL,
["HOTS"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_ALL,
["SLOTS"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_CLASS,
},
["SLOTCFG"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_CLASS,
},
},
[1] = VUHDO_PER_PANEL_PROFILE_MODEL,
[2] = VUHDO_PER_PANEL_PROFILE_MODEL,
[3] = VUHDO_PER_PANEL_PROFILE_MODEL,
[4] = VUHDO_PER_PANEL_PROFILE_MODEL,
[5] = VUHDO_PER_PANEL_PROFILE_MODEL,
[6] = VUHDO_PER_PANEL_PROFILE_MODEL,
[7] = VUHDO_PER_PANEL_PROFILE_MODEL,
[8] = VUHDO_PER_PANEL_PROFILE_MODEL,
[9] = VUHDO_PER_PANEL_PROFILE_MODEL,
[10] = VUHDO_PER_PANEL_PROFILE_MODEL,
},
["POWER_TYPE_COLORS"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_ALL,
},
["SPELL_CONFIG"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_TOON,
},
["BUFF_SETTINGS"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_CLASS,
["CONFIG"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_ALL,
},
},
["BUFF_ORDER"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_CLASS,
},
["INDICATOR_CONFIG"] = {
["-root-"] = VUHDO_PROFILE_MODEL_MATCH_ALL,
},
};
--
local tOriginatorClass = nil;
local tOriginatorToon = nil;
local function VUHDO_smartLoadFromProfile(aDestArray, aSourceArray, aProfileModel, aDerivedRule)
if not aSourceArray then
return aDestArray;
end
if aSourceArray["ORIGINATOR_CLASS"] then
tOriginatorClass = aSourceArray["ORIGINATOR_CLASS"];
end
if aSourceArray["ORIGINATOR_TOON"] then
tOriginatorToon = aSourceArray["ORIGINATOR_TOON"];
end
local tRootRule;
if aProfileModel then
tRootRule = aProfileModel["-root-"];
else
tRootRule = nil;
end
local tSourceValue;
for tKey, tDestValue in pairs(aDestArray) do
tSourceValue = aSourceArray[tKey];
if (tSourceValue ~= nil) then
local tSubModel = (aProfileModel or { })[tKey];
if "table" == type(tSourceValue) then
if "table" == type(tDestValue) then
aDestArray[tKey] = VUHDO_smartLoadFromProfile(aDestArray[tKey], aSourceArray[tKey], tSubModel, tRootRule or aDerivedRule);
else
VUHDO_Msg("Data structures incompatible in field: " .. tKey);
end
else -- Flacher Wert
local tRule = tSubModel or tRootRule or aDerivedRule;
if VUHDO_isProfileRuleAllowed(tRule, tOriginatorClass, tOriginatorToon) then
aDestArray[tKey] = aSourceArray[tKey];
--else
--VUHDO_Msg("Prohibit: " .. tKey);
end
end
end
end
return aDestArray;
end
--
local function VUHDO_fixDominantProfileSettings(aProfile)
for tCnt = 1, VUHDO_MAX_PANELS do
if aProfile["PANEL_SETUP"][tCnt] then
if (aProfile["PANEL_SETUP"][tCnt]["MODEL"].groups == nil) then
VUHDO_PANEL_SETUP[tCnt]["MODEL"].groups = nil;
else
VUHDO_PANEL_SETUP[tCnt]["MODEL"].groups = VUHDO_deepCopyTable(aProfile["PANEL_SETUP"][tCnt]["MODEL"].groups);
end
else
VUHDO_PANEL_SETUP[tCnt]["MODEL"].groups = nil;
end
end
end
--
function VUHDO_loadProfileNoInit(aName)
local tIndex, tProfile = VUHDO_getProfileNamed(aName);
local tPanelPositions;
if not tIndex then
VUHDO_Msg(VUHDO_I18N_ERROR_NO_PROFILE .. "\"" .. aName .. "\" !", 1, 0.4, 0.4);
return;
end
tOriginatorClass = tProfile["ORIGINATOR_CLASS"];
tOriginatorToon = tProfile["ORIGINATOR_TOON"];
VUHDO_CONFIG = VUHDO_smartLoadFromProfile(VUHDO_CONFIG, tProfile["CONFIG"], VUHDO_PROFILE_MODEL["CONFIG"], VUHDO_PROFILE_MODEL_MATCH_ALL);
VUHDO_PANEL_SETUP = VUHDO_smartLoadFromProfile(VUHDO_PANEL_SETUP, tProfile["PANEL_SETUP"], VUHDO_PROFILE_MODEL["PANEL_SETUP"], VUHDO_PROFILE_MODEL_MATCH_ALL);
VUHDO_POWER_TYPE_COLORS = VUHDO_smartLoadFromProfile(VUHDO_POWER_TYPE_COLORS, tProfile["POWER_TYPE_COLORS"], VUHDO_PROFILE_MODEL["POWER_TYPE_COLORS"], VUHDO_PROFILE_MODEL_MATCH_ALL);
VUHDO_SPELL_CONFIG = VUHDO_smartLoadFromProfile(VUHDO_SPELL_CONFIG, tProfile["SPELL_CONFIG"], VUHDO_PROFILE_MODEL["SPELL_CONFIG"], VUHDO_PROFILE_MODEL_MATCH_ALL);
VUHDO_BUFF_SETTINGS = VUHDO_smartLoadFromProfile(VUHDO_BUFF_SETTINGS, tProfile["BUFF_SETTINGS"], VUHDO_PROFILE_MODEL["BUFF_SETTINGS"], VUHDO_PROFILE_MODEL_MATCH_ALL);
VUHDO_BUFF_ORDER = VUHDO_smartLoadFromProfile(VUHDO_BUFF_ORDER, tProfile["BUFF_ORDER"], VUHDO_PROFILE_MODEL["BUFF_ORDER"], VUHDO_PROFILE_MODEL_MATCH_ALL);
VUHDO_INDICATOR_CONFIG = VUHDO_smartLoadFromProfile(VUHDO_INDICATOR_CONFIG, tProfile["INDICATOR_CONFIG"], VUHDO_PROFILE_MODEL["INDICATOR_CONFIG"], VUHDO_PROFILE_MODEL_MATCH_ALL);
tPanelPositions = tProfile["PANEL_POSITIONS"];
if tPanelPositions then
for tCnt = 1, 10 do -- VUHDO_MAX_PANELS
if tPanelPositions[tCnt] then
VUHDO_PANEL_SETUP[tCnt]["POSITION"] = VUHDO_deepCopyTable(tPanelPositions[tCnt]);
end
end
end
-- @TODO: Warum werden die nicht direkt geladen (ipairs-Problem?)
if tProfile["CONFIG"]["CUSTOM_DEBUFF"] and tProfile["CONFIG"]["CUSTOM_DEBUFF"]["STORED"] and VUHDO_CONFIG["CUSTOM_DEBUFF"] then
VUHDO_CONFIG["CUSTOM_DEBUFF"]["STORED"] = VUHDO_deepCopyTable(tProfile["CONFIG"]["CUSTOM_DEBUFF"]["STORED"]);
end
if tProfile["CONFIG"]["SPELL_TRACE"] and VUHDO_CONFIG["SPELL_TRACE"] then
VUHDO_CONFIG["SPELL_TRACE"] = VUHDO_deepCopyTable(tProfile["CONFIG"]["SPELL_TRACE"]);
end
VUHDO_fixDominantProfileSettings(tProfile);
VUHDO_CONFIG["CURRENT_PROFILE"] = aName;
VUHDO_Msg(VUHDO_I18N_PROFILE_LOADED .. aName);
end
--
function VUHDO_loadProfile(aName)
VUHDO_loadProfileNoInit(aName);
VUHDO_initAllBurstCaches();
VUHDO_loadVariables();
VUHDO_initPanelModels();
VUHDO_initDynamicPanelModels();
VUHDO_registerAllBouquets(false);
VUHDO_initAllEventBouquets();
VUHDO_initDebuffs();
VUHDO_reloadUI(true);
VUHDO_resetTooltip();
VUHDO_initBlizzFrames();
VUHDO_bouqetsChanged();
if (VUHDO_initCustomDebuffComboModel ~= nil) then
VUHDO_initCustomDebuffComboModel();
end
if (VUHDO_initSpellTraceComboModel ~= nil) then
VUHDO_initSpellTraceComboModel();
end
collectgarbage('collect');
end
--
function VUHDO_initDefaultProfiles()
if (VUHDO_GLOBAL_CONFIG["PROFILES_VERSION"] or 1) < 3 then
VUHDO_GLOBAL_CONFIG["PROFILES_VERSION"] = 3;
for _, tProfile in ipairs(VUHDO_DEFAULT_PROFILES) do
VUHDO_compressAllProfileParts(tProfile);
tinsert(VUHDO_PROFILES, tProfile);
end
end
VUHDO_DEFAULT_PROFILES = nil;
end
|
local default_config = {
cwd = vim.fn.stdpath("data").."/sessions",
force_overwrite = false,
force_delete = false,
bdelete = false,
verbose = true,
}
local config = vim.deepcopy(default_config)
local mt = {}
mt.__index = mt
mt.__newindex = function(self, k, v)
error("Assigning new values is not allowed !")
end
mt.update = function(self, new_config)
local new_config = new_config or {}
for k, v in pairs(self) do
if new_config[k] ~= nil then self[k] = new_config[k] end
end
return self
end
mt.reset = function(self)
for k, v in pairs(default_config) do self[k] = v end
return self
end
return setmetatable(config, mt)
|
local LogService = game:GetService("LogService")
local HttpService = game:GetService("HttpService")
--Create Toolbar
local toolbar = plugin:CreateToolbar("Roblox Package Index")
local button = toolbar:CreateButton("Roblox Package Index", 'Run "rpi help" in the command line to get started.', "rbxassetid://4458901886")
--"Clear Output" function (Adds empty lines)
--[[
ARGS:
lines - number: Number of empty lines
]]--
local function clearOutput(lines)
print(("\n"):rep(lines))
end
--Install Package Function
--[[
ARGS:
pkgName - string: Package Name
ver - number: Version
]]--
local function installPackage(pkgName, ver)
--Check for package name
if (pkgName == nil) then
warn('[RPI]-[ERROR]: No package name found, aborting...')
return "failed"
end
--The code for instalation
local Install = nil
warn('[RPI]-[INSTALL]: Searching for "'.. pkgName ..'" at version "'.. ver ..'" in the Roblox Package Index...')
--Check for Package Existance
local function checkPackage()
local check = pcall(function()
local Branch = HttpService:GetAsync("https://raw.githubusercontent.com/ErikMCM/RobloxPackageIndex/"..pkgName.."/Main.lua")
end)
return check
end
--Check for Package Version Existance
local function checkPackageVer()
local check = pcall(function()
local PackageVer = HttpService:GetAsync("https://raw.githubusercontent.com/ErikMCM/RobloxPackageIndex/"..pkgName.."/v".. ver .."/Main.lua")
end)
return check
end
--Package Existance Check
if checkPackage() == false then
warn('[RPI]-[ERROR]: Package not found, aborting...')
return "failed"
end
--If the version isnt latest, check the version and set install to that version
if (ver ~= "latest") then
if checkPackageVer() == false then
warn('[RPI]-[ERROR]: Package "'.. pkgName..'" was found, but the version "'..ver..'" was not. Aborting...')
return "failed"
end
Install = HttpService:GetAsync("https://raw.githubusercontent.com/ErikMCM/RobloxPackageIndex/"..pkgName.."/v".. ver .."/Main.lua")
else
--Sets install to the latest version not in a folder
Install = HttpService:GetAsync("https://raw.githubusercontent.com/ErikMCM/RobloxPackageIndex/"..pkgName.."/Main.lua")
end
--Notifies that the Package was found
warn('[RPI]-[INSTALL]: Package "'..pkgName..'" was found at version "'..ver..'".')
--Checking for ServerScriptService/RPI_Modules/<PackageName>
if not (game.ServerScriptService:FindFirstChild("RPI_Modules")) then
local folder = Instance.new("Folder", game.ServerScriptService)
folder.Name = "RPI_Modules"
end
if not (game.ServerScriptService.RPI_Modules:FindFirstChild(pkgName)) then
local folder = Instance.new("Folder", game.ServerScriptService.RPI_Modules)
folder.Name = pkgName
end
--Notifies installation is occuring
warn('[RPI]-[INSTALL]: Installing...')
--Clears all items in old folder for that package
game.ServerScriptService.RPI_Modules[pkgName]:ClearAllChildren()
--Creates the module script + sets it's source
local module = Instance.new("ModuleScript", game.ServerScriptService.RPI_Modules[pkgName])
module.Name = "Main"
module.Source = Install
--Notifies completed installation
warn('[RPI]-[INSTALL]: Complete!')
warn('[RPI]-[INSTALL]: Successfully installed "'..pkgName..'" at version "'..ver..'"!')
end
--MessageOut happens when a command in the toolbar is ran
LogService.MessageOut:Connect(function(Message, Type)
if string.find(Message, "^rpi") then
warn("[RPI]-[IGNORE]: Ignore the Roblox Studio Error above, Roblox doesn't have official support for Custom Studio Command Bar commands.")
clearOutput(25)
--Stops at the : in the error that gets reported to log service | no package name or option will have :
local placement = string.split(tostring(string.find(Message, ":")), " ")
local finalMessage = string.sub(Message, 1, tonumber(placement[1]) - 1)
local Arguments = string.split(finalMessage, " ")
--Variables for options
local ver = "latest"
local pkgName = nil
--Checks if the command regards installation
if Arguments[2] == "install" or Arguments[2] == "i" then
--Checks if the command regards options
if Arguments[3] == "-v" then
--We check if the 4th args is a number for the version
if tonumber(Arguments[4]) then
ver = Arguments[4]
end
--Arguments 3 isnt a command, so its a package @latest
elseif Arguments[3] ~= nil then
pkgName = Arguments[3]
end
--Arguments 5 will only happen if there's options, set it to the package name
if Arguments[5] then
pkgName = Arguments[5]
end
--Install the package
installPackage(pkgName, ver)
end
--Checks if the command regards help
if Arguments[2] == "help" or Arguments[2] == "h" then
warn("[RPI]-[HELP]:\nHello there! Welcome to the wonderful world of the Roblox Package Index. All packages on the Roblox Package Index have been reviewed by offical moderators to make sure no scripts are harmful to your games.\n\nCommands:\nrpi install [Package Name]")
end
end
end)
|
return {
summary = 'A fixed distance joint.',
description = [[
A DistanceJoint is a type of `Joint` that tries to keep two colliders a fixed distance apart.
The distance is determined by the initial distance between the anchor points. The joint allows
for rotation on the anchor points.
]],
extends = 'Joint',
constructors = {
'lovr.physics.newDistanceJoint'
},
related = {
'Collider'
}
}
|
-----------------------------------------------
-- Sample of SlibJfont.lua for W4.00.03
-- Copyright (c) 2019, Saya
-- All rights reserved.
-- 2019/05/15 rev.0.02
-----------------------------------------------
function chkBreak(n)
sleep(n or 0)
if fa.sharedmemory("read", 0x00, 0x01, "") == "!" then
error("Break!",2)
end
end
fa.sharedmemory("write", 0x00, 0x01, "-")
function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
-- main
local myDir = script_path()
local libDir = myDir.."lib/"
local jfont = require(libDir .. "SlibJfont")
local k12x10 = jfont:open("k12x10.sef")
local k6x10 = jfont:open("k6x10.sef")
local str={
"UTF8→EUC 全角日本語漢字変換テスト表",
"、。〃¢‐ 一倅怎瀁耀退!¥熙~",
"※〒℃⇒⇔♪Ωαβγθπφ●○◎◆◇■□★☆", --よく使われる記号
"①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ", --JIS 13区文字
"㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡〝〟№㏍℡", --JIS 13区文字
"㊤㊥㊦㊧㊨㈱㈲㈹㍾㍽㍼㍻∮∑∟⊿∪∩∠⊥≡≒√∵∫", --JIS 13区文字
"半角/ABC 全角/ABC 半角カナ/アカサタナワヲン ガパ ァィゥェォャュョ"
}
local EUC_file = "sample_out.txt"
local fpw = io.open(myDir..EUC_file, "w")
local strUTF8, strEUC, euc_length
local bitmap, fh, fw, s, p, kmax
local be = bit32.extract
jfont:setFont(k6x10,k12x10)
kmax = jfont.font2.height
for key,strUTF8 in ipairs(str) do
strEUC, euc_length = jfont:utf82euc(strUTF8)
s = {}
for k=1, kmax do
s[k] = ""
end
p=1
while p<=#strEUC do
bitmap,fh,fw,p = jfont:getFont(strEUC, p)
for j=1, fw do
for k=1, kmax do
s[k] = s[k] .. ((be(bitmap[j],k-1)>0) and "@" or ".")
end
end
end
for k=1, kmax do
fpw:write(s[k], "\n")
end
fpw:write("\n")
chkBreak()
collectgarbage()
end
fpw:close()
jfont:close()
return
|
local thispath = select('1', ...):match(".+%.") or ""
require(thispath.."testSkeletorBasicLoading")
require(thispath.."testSkeletorBone")
require(thispath.."testSkeletorComplexLoading")
require(thispath.."testSkeletorDraw")
require(thispath.."testSkeletorGettersSetters")
require(thispath.."testSkeletorSkeleton")
require(thispath.."testUtils")
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('XTemplate', {
group = "PreGame",
id = "PGTutorialNew",
PlaceObj('XTemplateWindow', nil, {
PlaceObj('XTemplateWindow', {
'__class', "XAspectWindow",
'Fit', "smallest",
}, {
PlaceObj('XTemplateLayer', {
'layer', "PGVideoBackground",
}),
PlaceObj('XTemplateWindow', {
'Margins', box(60, 68, 0, 25),
'LayoutMethod', "VList",
}, {
PlaceObj('XTemplateFunc', {
'name', "Open",
'func', function (self, ...)
XWindow.Open(self, ...)
self:SetMargins(GetSafeMargins(self:GetMargins()))
end,
}),
PlaceObj('XTemplateTemplate', {
'__template', "DialogTitleNew",
'Margins', box(55, 0, 0, 0),
'Title', T(577305258682, --[[XTemplate PGTutorialNew Title]] "Tutorials"),
'Subtitle', T(797581848776, --[[XTemplate PGTutorialNew Subtitle]] "Completed (0/5)"),
}, {
PlaceObj('XTemplateCode', {
'run', function (self, parent, context)
parent:ResolveId("node"):SetSubtitle(T{11443, "Completed (<completed>/<max>)", completed = CountCompletedTutorials(),max = CountTotalTutorials})
end,
}),
}),
PlaceObj('XTemplateWindow', {
'comment', "buttons list",
'Id', "idButtonsList",
'Margins', box(55, 120, 0, 0),
'LayoutMethod', "HList",
'LayoutHSpacing', 15,
}, {
PlaceObj('XTemplateForEach', {
'array', function (parent, context) return Presets.TutorialPreset.Default end,
'__context', function (parent, context, item, i, n) return item end,
'run_after', function (child, context, item, i, n)
child.idText:SetText(item.pregame_title)
child.idButton:SetFocusOrder(point(n, 0))
child.idButton:SetImage(item.image)
child.idDownImage:SetFlipX(n%2==0)
child.idButton.itemid = item.id
child.idTextRollover:SetText(item.description)
if n == 1 and GetUIStyleGamepad() then
child:CreateThread("FocusThread", function()
child.idButton:SetFocus()
end)
end
child.idTextRollover:SetVisible(false)
end,
}, {
PlaceObj('XTemplateWindow', {
'IdNode', true,
'VAlign', "top",
'RolloverZoom', 1050,
'RolloverDrawOnTop', true,
}, {
PlaceObj('XTemplateWindow', {
'comment', "button",
'__class', "XTextButton",
'Id', "idButton",
'IdNode', false,
'HAlign', "center",
'VAlign', "center",
'MinWidth', 243,
'MinHeight', 243,
'MouseCursor', "UI/Cursors/Rollover.tga",
'FXMouseIn', "MainMenuItemHover",
'FXPress', "MainMenuItemClick",
'FXPressDisabled', "UIDisabledButtonPressed",
'DisabledBackground', RGBA(120, 120, 120, 255),
'OnPress', function (self, gamepad)
CreateRealTimeThread(StartTutorial, self.itemid)
end,
}, {
PlaceObj('XTemplateFunc', {
'name', "SetEnabled(self, enabled)",
'func', function (self, enabled)
XTextButton.SetEnabled(self, enabled)
self.parent.idText:SetEnabled(enabled)
if not enabled then
self.parent:AddInterpolation{id = "desat", type = const.intDesaturation, startValue = 255}
self.parent.GetEnabled = function() return false end
end
end,
}),
PlaceObj('XTemplateFunc', {
'name', "SetRollover(self, rollover)",
'func', function (self, rollover)
self.parent:SetRollover(rollover)
XTextButton.SetRollover(self, rollover)
local duration = 200
local frame = self.parent:ResolveId("idFrame")
local image = self.parent:ResolveId("idDownImage")
local textContainer = self.parent:ResolveId("idTextContainer")
local rText = self.parent:ResolveId("idTextRollover")
frame:AddInterpolation{
id = "move",
type = const.intRect,
duration = duration,
targetRect = sizebox(frame.box:minx(), frame.box:miny() - rText.box:sizey(), frame.box:sizex(), frame.box:sizey() + 1+ rText.box:sizey()),
originalRect = frame.box,
flags = (not rollover) and const.intfInverse or nil,
}
rText:SetVisible(rollover)
rText:AddInterpolation{
id = "move",
type = const.intRect,
start = GetPreciseTicks() + duration/2,
duration = duration/2,
originalRect = rText.box,
targetRect = sizebox(image.box:minx(),image.box:miny(),rText.box:sizex(),0),
flags =rollover and const.intfInverse or nil,
}
textContainer:SetRollover(rollover)
textContainer:AddInterpolation{
id = "move",
type = const.intRect,
duration = duration,
targetRect = Offset(textContainer.box,0, -rText.box:sizey()),
originalRect = textContainer.box,
flags = (not rollover) and const.intfInverse or nil,
}
end,
}),
PlaceObj('XTemplateWindow', {
'__class', "XImage",
'Id', "idDownImage",
'Dock', "bottom",
'VAlign', "bottom",
'MinWidth', 243,
'MaxWidth', 243,
'Visible', false,
'Image', "UI/CommonNew/mm_rollover1.tga",
}),
PlaceObj('XTemplateWindow', {
'Id', "idRolloverWnd",
'Dock', "box",
'HAlign', "center",
'VAlign', "bottom",
'MinWidth', 243,
'MaxWidth', 243,
'LayoutMethod', "VList",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XFrame",
'Id', "idFrame",
'IdNode', false,
'Dock', "box",
'Image', "UI/CommonNew/mm_rollover2.tga",
}),
PlaceObj('XTemplateWindow', {
'Id', "idTextContainer",
'Margins', box(20, 0, 0, -30),
'HAlign', "left",
'VAlign', "bottom",
'LayoutMethod', "HList",
'LayoutHSpacing', 10,
}, {
PlaceObj('XTemplateWindow', nil, {
PlaceObj('XTemplateWindow', {
'__class', "XImage",
'Id', "idCheckBack",
'Image', "UI/CommonNew/check_slot_hex.tga",
'ImageScale', point(600, 600),
}),
PlaceObj('XTemplateWindow', {
'__class', "XImage",
'Id', "idCheck",
'Image', "UI/Common/mission_yes.tga",
'ImageScale', point(800, 800),
}, {
PlaceObj('XTemplateCode', {
'run', function (self, parent, context)
parent:SetVisible(AccountStorage and AccountStorage.CompletedTutorials and AccountStorage.CompletedTutorials[context.id])
end,
}),
}),
}),
PlaceObj('XTemplateTemplate', {
'__template', "MainMenuButtonText",
'Id', "idText",
'Padding', box(2, 4, 2, 4),
'VAlign', "center",
'Translate', true,
}),
}),
}),
PlaceObj('XTemplateWindow', {
'Dock', "box",
'MinWidth', 243,
'MaxWidth', 243,
}, {
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Id', "idTextRollover",
'IdNode', false,
'Margins', box(0, 30, 0, -18),
'Padding', box(10, 10, 10, 0),
'HAlign', "center",
'VAlign', "bottom",
'MinWidth', 243,
'MaxWidth', 243,
'FadeInTime', 300,
'FadeOutTime', 100,
'TextStyle', "RolloverTextStyle",
'Translate', true,
'HideOnEmpty', true,
}),
}),
}),
PlaceObj('XTemplateFunc', {
'name', "Open",
'func', function (self, ...)
XWindow.Open(self, ...)
self.idTextRollover:SetVisible(false)
end,
}),
}),
}),
PlaceObj('XTemplateFunc', {
'name', "OnShortcut(self, shortcut, source)",
'func', function (self, shortcut, source)
if shortcut == "DPadLeft" or shortcut == "LeftThumbLeft" then
local focus = self.desktop:GetKeyboardFocus()
if focus:IsWithin(self) and focus:GetFocusOrder():x() == 1 then
self:GetRelativeFocus(point(#self,0), "exact"):SetFocus(true)
return "break"
end
elseif shortcut == "DPadRight" or shortcut == "LeftThumbRight" then
local focus = self.desktop:GetKeyboardFocus()
if focus:IsWithin(self) and focus:GetFocusOrder():x() == #self then
self:GetRelativeFocus(point(1,0), "exact"):SetFocus(true)
return "break"
end
end
return XWindow.OnShortcut(self, shortcut, source)
end,
}),
}),
PlaceObj('XTemplateAction', {
'ActionId', "back",
'ActionName', T(4254, --[[XTemplate PGTutorialNew ActionName]] "BACK"),
'ActionToolbar', "ActionBar",
'ActionShortcut', "Escape",
'ActionGamepad', "ButtonB",
'OnActionEffect', "back",
}),
PlaceObj('XTemplateTemplate', {
'__template', "ActionBarNew",
'Margins', box(55, 0, 0, 0),
}),
}),
}),
}),
})
|
local W = require 'winapi'
local r,w = W.pipe()
local m = W.mutex()
function lprint(...)
m:lock()
print(...)
m:release()
end
function long(name)
lprint('hello',name)
for i = 1,2 do
m:lock()
w:write(name..i)
m:release()
for i = 1,1e8 do end
end
end
r:read_async(function(s)
lprint(s)
end)
T = {}
T[1] = W.thread(long,'john')
T[2] = W.thread(long,'jane')
T[3] = W.thread(long,'june')
W.wait_for_processes(T,true)
print 'finish'
|
--- 下载dirid目录zip
local http = require("resty.http")
local inheaders = ngx.req.get_headers()
local inmethod = ngx.var.request_method
local fileManager = "http://127.0.0.1:8081/"
-- 读取get请求参数
local local_args = ngx.req.get_uri_args()
-- dirid参数传入所在目录名称
local dirid = local_args["dirid"]
if nil == dirid then
ngx.say("dirid参数不能为空!\n")
end
-- 下载dirid目录zip
local httpc = http:new()
local res, err = httpc:request_uri(
fileManager,
{
path = fileManager .. dirid .. "/?format=zip",
method = inmethod,
headers = inheaders
}
)
if res.status ~= ngx.HTTP_OK then
ngx.exit(res.status)
end
ngx.print(res.body)
|
return {
uv_buf_t = require 'uv/ctypes/uv_buf_t',
uv_check_t = require 'uv/ctypes/uv_check_t',
uv_connect_t = require 'uv/ctypes/uv_connect_t',
uv_fs_t = require 'uv/ctypes/uv_fs_t',
uv_getaddrinfo_t = require 'uv/ctypes/uv_getaddrinfo_t',
uv_handle_t = require 'uv/ctypes/uv_handle_t',
uv_idle_t = require 'uv/ctypes/uv_idle_t',
uv_loop_t = require 'uv/ctypes/uv_loop_t',
uv_prepare_t = require 'uv/ctypes/uv_prepare_t',
uv_process_t = require 'uv/ctypes/uv_process_t',
uv_process_options_t = require 'uv/ctypes/uv_process_options_t',
uv_signal_t = require 'uv/ctypes/uv_signal_t',
uv_stream_t = require 'uv/ctypes/uv_stream_t',
uv_tcp_t = require 'uv/ctypes/uv_tcp_t',
uv_timer_t = require 'uv/ctypes/uv_timer_t',
uv_write_t = require 'uv/ctypes/uv_write_t',
}
|
return require('maintenance_mode')
|
local FollowGenerator = {}
FollowGenerator.__index = FollowGenerator
function FollowGenerator:new(productions, first)
assert(productions, "Need a productions table to make follow table")
return setmetatable({
productions = productions,
producers = {},
first = first,
follow = {},
concatenateList = {},
startSymbol = nil
}, FollowGenerator)
end
--[[Method to identify who produce every production in list--]]
function FollowGenerator:productedBy()
for key, value in pairs(self.productions) do
for _, allProductions in pairs(value) do
for __, production in pairs(allProductions) do
if production:match("<.*>") then
if not self.producers[production] then self.producers[production] = {} end
self.producers[production][key] = true
end
end
end
end
end
function FollowGenerator:concatenateTables(main, secondary)
if secondary then
for index, value in pairs(secondary) do
if index ~= "''" then
main[index] = true
end
end
end
return main
end
function FollowGenerator:giveMeFirst(from)
if not from then return nil end
if from:match("<.*>") then
return self.first[from]
end
local newFirst = {}; newFirst[from] = true
return newFirst
end
function FollowGenerator:toConcatenate(main, secondary)
if not self.concatenateList[main] then self.concatenateList[main] = {} end
table.insert(self.concatenateList[main], secondary)
end
function FollowGenerator:of(production, hasToo)
if self.follow[production] then return self.follow[production] end
self.follow[production] = self:concatenateTables({}, hasToo)
if not self.producers[production] then
if production == self.startSymbol then
return self.follow[production]
else
error(string.format("Production %s is not used, please fix it", production))
end
end
for key, _ in pairs(self.producers[production]) do
for count = 1, #self.productions[key] do
for index = 1, #self.productions[key][count] do
local value = self.productions[key][count][index]
if value == production then
if index == #self.productions[key][count] then
self:toConcatenate(self.follow[production], self:of(key))
elseif index > 1 then
self:toConcatenate(self.follow[production], self.first[key])
if self.first[key]["''"] then
self:toConcatenate(self.follow[production], self:of(key))
end
else
local newFirst = self:giveMeFirst(self.productions[key][count][index + 1])
self:toConcatenate(self.follow[production], newFirst)
end
index = #self.productions[key][count] + 1
end
end
end
end
return self.follow[production]
end
function FollowGenerator:concatenateAll()
for main, _ in pairs(self.concatenateList) do
for index, value in pairs(self.concatenateList[main]) do
self:concatenateTables(main, value)
end
end
end
function FollowGenerator:start(startSymbol)
self.startSymbol = startSymbol
self:productedBy()
self:of(startSymbol, {["'$'"] = true})
for production, value in pairs(self.productions) do
self:of(production)
end
self:concatenateAll(); self:concatenateAll()
end
return FollowGenerator
|
-----------------------------------------------------------------------------------------------------------------------
-- Third-party applications keys sheet --
-----------------------------------------------------------------------------------------------------------------------
-- This file provides table to build hotkeys helpers for third-party applications.
-- The key lists here are purely descriptive, have nothing to do with real application configs.
local appkeys = {}
appkeys["urxvt"] = {
style = { column = 2, geometry = { width = 1200, height = 660 } },
pack = {
{
{ "Control" }, "l", nil,
{ description = "Clear the screen", group = "Control" }
},
{
{ "Control" }, "s", nil,
{ description = "Stops the output to the screen", group = "Control" }
},
{
{ "Control" }, "q", nil,
{ description = "Allow output to the screen", group = "Control" }
},
{
{ "Control" }, "c", nil,
{ description = "Terminate the command", group = "Control" }
},
{
{ "Control" }, "z", nil,
{ description = "Suspend/stop the command", group = "Control" }
},
{
{ "Control" }, "a", nil,
{ description = "Go to the start of the command line", group = "Editing" }
},
{
{ "Control" }, "e", nil,
{ description = "Go to the end of the command line", group = "Editing" }
},
{
{ "Control" }, "k", nil,
{ description = "Delete from cursor to the end of the command line", group = "Editing" }
},
{
{ "Control" }, "u", nil,
{ description = "Delete from cursor to the start of the command line", group = "Editing" }
},
{
{ "Control" }, "w", nil,
{ description = "Delete from cursor to start of word ", group = "Editing" }
},
{
{ "Control" }, "y", nil,
{ description = "Paste word or text", group = "Editing" }
},
{
{ "Control" }, "xx", nil,
{ description = "Move between start of command line and cursor", group = "Editing" }
},
{
{ "Alt" }, "b", nil,
{ description = "Move backward one word", group = "Editing" }
},
{
{ "Alt" }, "f", nil,
{ description = "Move forward one word", group = "Editing" }
},
{
{ "Alt" }, "d", nil,
{ description = "Delete to end of word starting at cursor", group = "Editing" }
},
{
{ "Alt" }, "c", nil,
{ description = "Capitalize to end of word starting at cursor", group = "Editing" }
},
{
{ "Alt" }, "u", nil,
{ description = "Make uppercase from cursor to end of word", group = "Editing" }
},
{
{ "Alt" }, "l", nil,
{ description = "Make lowercase from cursor to end of word", group = "Editing" }
},
{
{ "Alt" }, "t", nil,
{ description = "Swap current word with previous", group = "Editing" }
},
{
{ "Control" }, "f", nil,
{ description = "Move forward one character", group = "Editing" }
},
{
{ "Control" }, "b", nil,
{ description = "Move backward one character", group = "Editing" }
},
{
{ "Control" }, "d", nil,
{ description = "Delete character under the cursor", group = "Editing" }
},
{
{ "Control" }, "h", nil,
{ description = "Delete character before the cursor", group = "Editing" }
},
{
{ "Control" }, "t", nil,
{ description = "Swap character under cursor with the previous one", group = "Editing" }
},
{
{ "Control" }, "r", nil,
{ description = "Search the history backwards", group = "Recall" }
},
{
{ "Control" }, "g", nil,
{ description = "Escape from history searching mode", group = "Recall" }
},
{
{ "Control" }, "p", nil,
{ description = "Previous command in history", group = "Recall" }
},
{
{ "Control" }, "n", nil,
{ description = "Next command in history", group = "Recall" }
},
{
{ "Alt" }, ".", nil,
{ description = "Use the last word of the previous command", group = "Recall" }
},
{
{}, "!!", nil,
{ description = "Run last command", group = "Bang" }
},
{
{}, "!blah", nil,
{ description = "Run the most recent command that starts with ‘blah’", group = "Bang" }
},
{
{}, "!blah:p", nil,
{ description = "Print out the command that !blah would run", group = "Bang" }
},
{
{}, "!$", nil,
{ description = "The last word of the previous command", group = "Bang" }
},
{
{}, "!$:p", nil,
{ description = "Print out the word that !$ would substitute", group = "Bang" }
},
{
{}, "!*", nil,
{ description = "The previous command except for the last word", group = "Bang" }
},
{
{}, "!*:p", nil,
{ description = "Print out what !* would substitute", group = "Bang" }
},
}
}
appkeys["mpv"] = {
style = { column = 3, geometry = { width = 1600, height = 720 } },
pack = {
{
{}, "f", nil,
{ description = "Toggle fullscreen", group = "General" }
},
{
{}, "s", nil,
{ description = "Take a screenshot", group = "General" }
},
{
{ "Shift" }, "s", nil,
{ description = "Take a screenshot without subtitles", group = "General" }
},
{
{}, "q", nil,
{ description = "Quit", group = "General" }
},
{
{ "Shift" }, "q", nil,
{ description = "Quit saving current position", group = "General" }
},
{
{}, "o", nil,
{ description = "Show progress", group = "General" }
},
{
{ "Shift" }, "o", nil,
{ description = "Toggle show progress", group = "General" }
},
{
{}, "F9", nil,
{ description = "Show the list of audio and subtitle", group = "General" }
},
{
{"Shift"}, "a", nil,
{ description = "Cycle aspect ratio", group = "General" }
},
{
{}, "F8", nil,
{ description = "Show the playlist", group = "Playlist" }
},
{
{ "Shift" }, ",", nil,
{ description = "Forward in playlist", group = "Playlist" }
},
{
{ "Shift" }, ".", nil,
{ description = "Backward in playlist", group = "Playlist" }
},
{
{}, "Space", nil,
{ description = "Play/pause", group = "Playback" }
},
{
{}, "[", nil,
{ description = "Decrease speed", group = "Playback" }
},
{
{}, "]", nil,
{ description = "Increase speed", group = "Playback" }
},
{
{}, "{", nil,
{ description = "Halve current speed", group = "Playback" }
},
{
{}, "}", nil,
{ description = "Double current speed", group = "Playback" }
},
{
{}, "l", nil,
{ description = "Set/clear A-B loop points", group = "Playback" }
},
{
{ "Shift" }, "l", nil,
{ description = "Toggle infinite looping", group = "Playback" }
},
{
{}, "Backspace", nil,
{ description = "Reset speed to normal", group = "Playback" }
},
{
{}, "m", nil,
{ description = "Mute/unmute", group = "Audio" }
},
{
{}, "9", nil,
{ description = "Decrease volume", group = "Audio" }
},
{
{}, "0", nil,
{ description = "Increase volume", group = "Audio" }
},
{
{ "Control" }, "-", nil,
{ description = "Decrease audio delay", group = "Audio" }
},
{
{ "Control" }, "+", nil,
{ description = "Increase audio delay", group = "Audio" }
},
{
{}, "#", nil,
{ description = "Cycle through audio tracks", group = "Audio" }
},
{
{}, "PageUp", nil,
{ description = "Next chapter", group = "Navigation" }
},
{
{}, "PageDn", nil,
{ description = "Previous chapter", group = "Navigation" }
},
{
{}, ",", nil,
{ description = "Previous frame", group = "Navigation" }
},
{
{}, ".", nil,
{ description = "Next frame", group = "Navigation" }
},
{
{}, "Right", nil,
{ description = "Forward 5 seconds", group = "Navigation" }
},
{
{}, "Left", nil,
{ description = "Backward 5 seconds", group = "Navigation" }
},
{
{}, "Up", nil,
{ description = "Forward 60 seconds", group = "Navigation" }
},
{
{}, "Down", nil,
{ description = "Backward 60 seconds", group = "Navigation" }
},
{
{ "Control" }, "Left", nil,
{ description = "Seek to the previous subtitle", group = "Navigation" }
},
{
{ "Control" }, "Right", nil,
{ description = "Seek to the next subtitle", group = "Navigation" }
},
{
{ "Shift" }, "Backspace", nil,
{ description = "Undo the last seek", group = "Navigation" }
},
{
{ "Control", "Shift" }, "Backspace", nil,
{ description = "Mark the current position", group = "Navigation" }
},
{
{}, "v", nil,
{ description = "Show/hide subtitles", group = "Subtitles" }
},
{
{}, "j", nil,
{ description = "Next subtitle", group = "Subtitles" }
},
{
{ "Shift" }, "j", nil,
{ description = "Previous subtitle", group = "Subtitles" }
},
{
{}, "z", nil,
{ description = "Increase subtitle delay", group = "Subtitles" }
},
{
{}, "x", nil,
{ description = "Decrease subtitle delay", group = "Subtitles" }
},
{
{}, "r", nil,
{ description = "Move subtitles up", group = "Subtitles" }
},
{
{}, "t", nil,
{ description = "Move subtitles down", group = "Subtitles" }
},
{
{}, "u", nil,
{ description = "Style overrides on/off", group = "Subtitles" }
},
{
{}, "1", nil,
{ description = "Decrease contrast", group = "Video" }
},
{
{}, "2", nil,
{ description = "Increase contrast", group = "Video" }
},
{
{}, "3", nil,
{ description = "Decrease brightness", group = "Video" }
},
{
{}, "4", nil,
{ description = "Increase brightness", group = "Video" }
},
{
{}, "5", nil,
{ description = "Decrease gamma", group = "Video" }
},
{
{}, "6", nil,
{ description = "Increase gamma", group = "Video" }
},
{
{}, "7", nil,
{ description = "Decrease saturation", group = "Video" }
},
{
{}, "8", nil,
{ description = "Increase saturation", group = "Video" }
},
{
{}, "w", nil,
{ description = "Decrease pan-and-scan range", group = "Zoom" }
},
{
{}, "e", nil,
{ description = "Increase pan-and-scan range", group = "Zoom" }
},
{
{ "Alt" }, "-", nil,
{ description = "Decrease zoom", group = "Zoom" }
},
{
{ "Alt" }, "+", nil,
{ description = "Increase zoom", group = "Zoom" }
},
{
{ "Alt" }, "Backspace", nil,
{ description = "Reset zoom", group = "Zoom" }
},
{
{ "Alt" }, "Arrow", nil,
{ description = "Move the video rectangle", group = "Zoom" }
},
}
}
return appkeys
|
return { {
code = 1,
rgb = { 0, 0, 0 }
}, {
code = 2,
rgb = { 128, 0, 0 }
}, {
code = 3,
rgb = { 0, 128, 0 }
}, {
code = 4,
rgb = { 128, 128, 0 }
}, {
code = 5,
rgb = { 0, 0, 128 }
}, {
code = 6,
rgb = { 128, 0, 128 }
}, {
code = 7,
rgb = { 0, 128, 128 }
}, {
code = 8,
rgb = { 192, 192, 192 }
}, {
code = 9,
rgb = { 128, 128, 128 }
}, {
code = 10,
rgb = { 255, 0, 0 }
}, {
code = 11,
rgb = { 0, 255, 0 }
}, {
code = 12,
rgb = { 255, 255, 0 }
}, {
code = 13,
rgb = { 0, 0, 255 }
}, {
code = 14,
rgb = { 255, 0, 255 }
}, {
code = 15,
rgb = { 0, 255, 255 }
}, {
code = 16,
rgb = { 255, 255, 255 }
}, {
code = 17,
rgb = { 0, 0, 0 }
}, {
code = 18,
rgb = { 0, 0, 95 }
}, {
code = 19,
rgb = { 0, 0, 135 }
}, {
code = 20,
rgb = { 0, 0, 175 }
}, {
code = 21,
rgb = { 0, 0, 215 }
}, {
code = 22,
rgb = { 0, 0, 255 }
}, {
code = 23,
rgb = { 0, 95, 0 }
}, {
code = 24,
rgb = { 0, 95, 95 }
}, {
code = 25,
rgb = { 0, 95, 135 }
}, {
code = 26,
rgb = { 0, 95, 175 }
}, {
code = 27,
rgb = { 0, 95, 215 }
}, {
code = 28,
rgb = { 0, 95, 255 }
}, {
code = 29,
rgb = { 0, 135, 0 }
}, {
code = 30,
rgb = { 0, 135, 95 }
}, {
code = 31,
rgb = { 0, 135, 135 }
}, {
code = 32,
rgb = { 0, 135, 175 }
}, {
code = 33,
rgb = { 0, 135, 215 }
}, {
code = 34,
rgb = { 0, 135, 255 }
}, {
code = 35,
rgb = { 0, 175, 0 }
}, {
code = 36,
rgb = { 0, 175, 95 }
}, {
code = 37,
rgb = { 0, 175, 135 }
}, {
code = 38,
rgb = { 0, 175, 175 }
}, {
code = 39,
rgb = { 0, 175, 215 }
}, {
code = 40,
rgb = { 0, 175, 255 }
}, {
code = 41,
rgb = { 0, 215, 0 }
}, {
code = 42,
rgb = { 0, 215, 95 }
}, {
code = 43,
rgb = { 0, 215, 135 }
}, {
code = 44,
rgb = { 0, 215, 175 }
}, {
code = 45,
rgb = { 0, 215, 215 }
}, {
code = 46,
rgb = { 0, 215, 255 }
}, {
code = 47,
rgb = { 0, 255, 0 }
}, {
code = 48,
rgb = { 0, 255, 95 }
}, {
code = 49,
rgb = { 0, 255, 135 }
}, {
code = 50,
rgb = { 0, 255, 175 }
}, {
code = 51,
rgb = { 0, 255, 215 }
}, {
code = 52,
rgb = { 0, 255, 255 }
}, {
code = 53,
rgb = { 95, 0, 0 }
}, {
code = 54,
rgb = { 95, 0, 95 }
}, {
code = 55,
rgb = { 95, 0, 135 }
}, {
code = 56,
rgb = { 95, 0, 175 }
}, {
code = 57,
rgb = { 95, 0, 215 }
}, {
code = 58,
rgb = { 95, 0, 255 }
}, {
code = 59,
rgb = { 95, 95, 0 }
}, {
code = 60,
rgb = { 95, 95, 95 }
}, {
code = 61,
rgb = { 95, 95, 135 }
}, {
code = 62,
rgb = { 95, 95, 175 }
}, {
code = 63,
rgb = { 95, 95, 215 }
}, {
code = 64,
rgb = { 95, 95, 255 }
}, {
code = 65,
rgb = { 95, 135, 0 }
}, {
code = 66,
rgb = { 95, 135, 95 }
}, {
code = 67,
rgb = { 95, 135, 135 }
}, {
code = 68,
rgb = { 95, 135, 175 }
}, {
code = 69,
rgb = { 95, 135, 215 }
}, {
code = 70,
rgb = { 95, 135, 255 }
}, {
code = 71,
rgb = { 95, 175, 0 }
}, {
code = 72,
rgb = { 95, 175, 95 }
}, {
code = 73,
rgb = { 95, 175, 135 }
}, {
code = 74,
rgb = { 95, 175, 175 }
}, {
code = 75,
rgb = { 95, 175, 215 }
}, {
code = 76,
rgb = { 95, 175, 255 }
}, {
code = 77,
rgb = { 95, 215, 0 }
}, {
code = 78,
rgb = { 95, 215, 95 }
}, {
code = 79,
rgb = { 95, 215, 135 }
}, {
code = 80,
rgb = { 95, 215, 175 }
}, {
code = 81,
rgb = { 95, 215, 215 }
}, {
code = 82,
rgb = { 95, 215, 255 }
}, {
code = 83,
rgb = { 95, 255, 0 }
}, {
code = 84,
rgb = { 95, 255, 95 }
}, {
code = 85,
rgb = { 95, 255, 135 }
}, {
code = 86,
rgb = { 95, 255, 175 }
}, {
code = 87,
rgb = { 95, 255, 215 }
}, {
code = 88,
rgb = { 95, 255, 255 }
}, {
code = 89,
rgb = { 135, 0, 0 }
}, {
code = 90,
rgb = { 135, 0, 95 }
}, {
code = 91,
rgb = { 135, 0, 135 }
}, {
code = 92,
rgb = { 135, 0, 175 }
}, {
code = 93,
rgb = { 135, 0, 215 }
}, {
code = 94,
rgb = { 135, 0, 255 }
}, {
code = 95,
rgb = { 135, 95, 0 }
}, {
code = 96,
rgb = { 135, 95, 95 }
}, {
code = 97,
rgb = { 135, 95, 135 }
}, {
code = 98,
rgb = { 135, 95, 175 }
}, {
code = 99,
rgb = { 135, 95, 215 }
}, {
code = 100,
rgb = { 135, 95, 255 }
}, {
code = 101,
rgb = { 135, 135, 0 }
}, {
code = 102,
rgb = { 135, 135, 95 }
}, {
code = 103,
rgb = { 135, 135, 135 }
}, {
code = 104,
rgb = { 135, 135, 175 }
}, {
code = 105,
rgb = { 135, 135, 215 }
}, {
code = 106,
rgb = { 135, 135, 255 }
}, {
code = 107,
rgb = { 135, 175, 0 }
}, {
code = 108,
rgb = { 135, 175, 95 }
}, {
code = 109,
rgb = { 135, 175, 135 }
}, {
code = 110,
rgb = { 135, 175, 175 }
}, {
code = 111,
rgb = { 135, 175, 215 }
}, {
code = 112,
rgb = { 135, 175, 255 }
}, {
code = 113,
rgb = { 135, 215, 0 }
}, {
code = 114,
rgb = { 135, 215, 95 }
}, {
code = 115,
rgb = { 135, 215, 135 }
}, {
code = 116,
rgb = { 135, 215, 175 }
}, {
code = 117,
rgb = { 135, 215, 215 }
}, {
code = 118,
rgb = { 135, 215, 255 }
}, {
code = 119,
rgb = { 135, 255, 0 }
}, {
code = 120,
rgb = { 135, 255, 95 }
}, {
code = 121,
rgb = { 135, 255, 135 }
}, {
code = 122,
rgb = { 135, 255, 175 }
}, {
code = 123,
rgb = { 135, 255, 215 }
}, {
code = 124,
rgb = { 135, 255, 255 }
}, {
code = 125,
rgb = { 175, 0, 0 }
}, {
code = 126,
rgb = { 175, 0, 95 }
}, {
code = 127,
rgb = { 175, 0, 135 }
}, {
code = 128,
rgb = { 175, 0, 175 }
}, {
code = 129,
rgb = { 175, 0, 215 }
}, {
code = 130,
rgb = { 175, 0, 255 }
}, {
code = 131,
rgb = { 175, 95, 0 }
}, {
code = 132,
rgb = { 175, 95, 95 }
}, {
code = 133,
rgb = { 175, 95, 135 }
}, {
code = 134,
rgb = { 175, 95, 175 }
}, {
code = 135,
rgb = { 175, 95, 215 }
}, {
code = 136,
rgb = { 175, 95, 255 }
}, {
code = 137,
rgb = { 175, 135, 0 }
}, {
code = 138,
rgb = { 175, 135, 95 }
}, {
code = 139,
rgb = { 175, 135, 135 }
}, {
code = 140,
rgb = { 175, 135, 175 }
}, {
code = 141,
rgb = { 175, 135, 215 }
}, {
code = 142,
rgb = { 175, 135, 255 }
}, {
code = 143,
rgb = { 175, 175, 0 }
}, {
code = 144,
rgb = { 175, 175, 95 }
}, {
code = 145,
rgb = { 175, 175, 135 }
}, {
code = 146,
rgb = { 175, 175, 175 }
}, {
code = 147,
rgb = { 175, 175, 215 }
}, {
code = 148,
rgb = { 175, 175, 255 }
}, {
code = 149,
rgb = { 175, 215, 0 }
}, {
code = 150,
rgb = { 175, 215, 95 }
}, {
code = 151,
rgb = { 175, 215, 135 }
}, {
code = 152,
rgb = { 175, 215, 175 }
}, {
code = 153,
rgb = { 175, 215, 215 }
}, {
code = 154,
rgb = { 175, 215, 255 }
}, {
code = 155,
rgb = { 175, 255, 0 }
}, {
code = 156,
rgb = { 175, 255, 95 }
}, {
code = 157,
rgb = { 175, 255, 135 }
}, {
code = 158,
rgb = { 175, 255, 175 }
}, {
code = 159,
rgb = { 175, 255, 215 }
}, {
code = 160,
rgb = { 175, 255, 255 }
}, {
code = 161,
rgb = { 215, 0, 0 }
}, {
code = 162,
rgb = { 215, 0, 95 }
}, {
code = 163,
rgb = { 215, 0, 135 }
}, {
code = 164,
rgb = { 215, 0, 175 }
}, {
code = 165,
rgb = { 215, 0, 215 }
}, {
code = 166,
rgb = { 215, 0, 255 }
}, {
code = 167,
rgb = { 215, 95, 0 }
}, {
code = 168,
rgb = { 215, 95, 95 }
}, {
code = 169,
rgb = { 215, 95, 135 }
}, {
code = 170,
rgb = { 215, 95, 175 }
}, {
code = 171,
rgb = { 215, 95, 215 }
}, {
code = 172,
rgb = { 215, 95, 255 }
}, {
code = 173,
rgb = { 215, 135, 0 }
}, {
code = 174,
rgb = { 215, 135, 95 }
}, {
code = 175,
rgb = { 215, 135, 135 }
}, {
code = 176,
rgb = { 215, 135, 175 }
}, {
code = 177,
rgb = { 215, 135, 215 }
}, {
code = 178,
rgb = { 215, 135, 255 }
}, {
code = 179,
rgb = { 215, 175, 0 }
}, {
code = 180,
rgb = { 215, 175, 95 }
}, {
code = 181,
rgb = { 215, 175, 135 }
}, {
code = 182,
rgb = { 215, 175, 175 }
}, {
code = 183,
rgb = { 215, 175, 215 }
}, {
code = 184,
rgb = { 215, 175, 255 }
}, {
code = 185,
rgb = { 215, 215, 0 }
}, {
code = 186,
rgb = { 215, 215, 95 }
}, {
code = 187,
rgb = { 215, 215, 135 }
}, {
code = 188,
rgb = { 215, 215, 175 }
}, {
code = 189,
rgb = { 215, 215, 215 }
}, {
code = 190,
rgb = { 215, 215, 255 }
}, {
code = 191,
rgb = { 215, 255, 0 }
}, {
code = 192,
rgb = { 215, 255, 95 }
}, {
code = 193,
rgb = { 215, 255, 135 }
}, {
code = 194,
rgb = { 215, 255, 175 }
}, {
code = 195,
rgb = { 215, 255, 215 }
}, {
code = 196,
rgb = { 215, 255, 255 }
}, {
code = 197,
rgb = { 255, 0, 0 }
}, {
code = 198,
rgb = { 255, 0, 95 }
}, {
code = 199,
rgb = { 255, 0, 135 }
}, {
code = 200,
rgb = { 255, 0, 175 }
}, {
code = 201,
rgb = { 255, 0, 215 }
}, {
code = 202,
rgb = { 255, 0, 255 }
}, {
code = 203,
rgb = { 255, 95, 0 }
}, {
code = 204,
rgb = { 255, 95, 95 }
}, {
code = 205,
rgb = { 255, 95, 135 }
}, {
code = 206,
rgb = { 255, 95, 175 }
}, {
code = 207,
rgb = { 255, 95, 215 }
}, {
code = 208,
rgb = { 255, 95, 255 }
}, {
code = 209,
rgb = { 255, 135, 0 }
}, {
code = 210,
rgb = { 255, 135, 95 }
}, {
code = 211,
rgb = { 255, 135, 135 }
}, {
code = 212,
rgb = { 255, 135, 175 }
}, {
code = 213,
rgb = { 255, 135, 215 }
}, {
code = 214,
rgb = { 255, 135, 255 }
}, {
code = 215,
rgb = { 255, 175, 0 }
}, {
code = 216,
rgb = { 255, 175, 95 }
}, {
code = 217,
rgb = { 255, 175, 135 }
}, {
code = 218,
rgb = { 255, 175, 175 }
}, {
code = 219,
rgb = { 255, 175, 215 }
}, {
code = 220,
rgb = { 255, 175, 255 }
}, {
code = 221,
rgb = { 255, 215, 0 }
}, {
code = 222,
rgb = { 255, 215, 95 }
}, {
code = 223,
rgb = { 255, 215, 135 }
}, {
code = 224,
rgb = { 255, 215, 175 }
}, {
code = 225,
rgb = { 255, 215, 215 }
}, {
code = 226,
rgb = { 255, 215, 255 }
}, {
code = 227,
rgb = { 255, 255, 0 }
}, {
code = 228,
rgb = { 255, 255, 95 }
}, {
code = 229,
rgb = { 255, 255, 135 }
}, {
code = 230,
rgb = { 255, 255, 175 }
}, {
code = 231,
rgb = { 255, 255, 215 }
}, {
code = 232,
rgb = { 255, 255, 255 }
}, {
code = 233,
rgb = { 8, 8, 8 }
}, {
code = 234,
rgb = { 18, 18, 18 }
}, {
code = 235,
rgb = { 28, 28, 28 }
}, {
code = 236,
rgb = { 38, 38, 38 }
}, {
code = 237,
rgb = { 48, 48, 48 }
}, {
code = 238,
rgb = { 58, 58, 58 }
}, {
code = 239,
rgb = { 68, 68, 68 }
}, {
code = 240,
rgb = { 78, 78, 78 }
}, {
code = 241,
rgb = { 88, 88, 88 }
}, {
code = 242,
rgb = { 98, 98, 98 }
}, {
code = 243,
rgb = { 108, 108, 108 }
}, {
code = 244,
rgb = { 118, 118, 118 }
}, {
code = 245,
rgb = { 128, 128, 128 }
}, {
code = 246,
rgb = { 138, 138, 138 }
}, {
code = 247,
rgb = { 148, 148, 148 }
}, {
code = 248,
rgb = { 158, 158, 158 }
}, {
code = 249,
rgb = { 168, 168, 168 }
}, {
code = 250,
rgb = { 178, 178, 178 }
}, {
code = 251,
rgb = { 188, 188, 188 }
}, {
code = 252,
rgb = { 198, 198, 198 }
}, {
code = 253,
rgb = { 208, 208, 208 }
}, {
code = 254,
rgb = { 218, 218, 218 }
}, {
code = 255,
rgb = { 228, 228, 228 }
}, {
code = 256,
rgb = { 238, 238, 238 }
} }
|
#!/usr/bin/env lua
local fl = require( "fltk4lua" )
local window = fl.Window( 200, 105 )
function window:callback()
local hotspot = fl.message_hotspot()
fl.message_hotspot( false )
local rep = fl.choice( "Are you sure you want to quit?",
"Cancel", "Quit", "Dunno" )
fl.message_hotspot( hotspot )
if rep == "Quit" then
--os.exit( 0 ) -- bad style
self:hide()
elseif rep == "Dunno" then
fl.message( "Well, maybe you should know before we quit." )
end
end
local b = fl.Return_Button( 20, 10, 160, 35, "Test text" )
function b:callback()
local input = fl.input( "Input:", self.label )
if input then
self.label = input
self:redraw()
end
end
local b2 = fl.Button( 20, 50, 160, 35, "MyPassword" )
function b2:callback()
local input = fl.password( "Input PWD:", self.label )
if input then
self.label = input
self:redraw()
end
end
window:end_group()
--window.resizable = b -- looks bad on a tiling window manager
window:show( arg )
fl.run()
|
--# selene: allow(unused_variable)
---@diagnostic disable: unused-local
-- Simple controls for the MiLight LED WiFi bridge (also known as LimitlessLED and EasyBulb)
---@class hs.milight
local M = {}
hs.milight = M
-- Deletes an `hs.milight` object
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
function M:delete() end
-- Cycles through the disco modes
--
-- Parameters:
-- * None
--
-- Returns:
-- * True if the command was sent correctly, otherwise false
---@return boolean
function M:disco() end
-- Specifies the maximum brightness value that can be used. Defaults to 25
M.maxBrightness = nil
-- Specifies the minimum brightness value that can be used. Defaults to 0
M.minBrightness = nil
-- Creates a new bridge object, which will be connected to the supplied IP address and port
--
-- Parameters:
-- * ip - A string containing the IP address of the MiLight WiFi bridge device. For convenience this can be the broadcast address of your network (e.g. 192.168.0.255)
-- * port - An optional number containing the UDP port to talk to the bridge on. Defaults to 8899
--
-- Returns:
-- * An `hs.milight` object
--
-- Notes:
-- * You can not use 255.255.255.255 as the IP address, to do so requires elevated privileges for the Hammerspoon process
function M.new(ip, port, ...) end
-- Sends a command to the bridge
--
-- Parameters:
-- * cmd - A command from the `hs.milight.cmd` table
-- * value - An optional value, if appropriate for the command (defaults to 0x00)
--
-- Returns:
-- * True if the command was sent, otherwise false
--
-- Notes:
-- * This is a low level command, you typically should use a specific method for the operation you want to perform
---@return boolean
function M:send(cmd, value, ...) end
-- Sets brightness for the specified zone
--
-- Parameters:
-- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
-- * value - A number containing the brightness level to set, between `hs.milight.minBrightness` and `hs.milight.maxBrightness`
--
-- Returns:
-- * A number containing the value that was sent to the WiFi bridge, or -1 if an error occurred
---@return number
function M:zoneBrightness(zone, value, ...) end
-- Sets RGB color for the specified zone
--
-- Parameters:
-- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
-- * value - A number between 0 and 255 that represents a color
--
-- Returns:
-- * True if the command was sent correctly, otherwise false
--
-- Notes:
-- * The color value is not a normal RGB colour, but rather a lookup in an internal table in the light hardware. While any number between 0 and 255 is valid, there are some useful values worth knowing:
-- * 00 - Violet
-- * 16 - Royal Blue
-- * 32 - Baby Blue
-- * 48 - Aqua
-- * 64 - Mint Green
-- * 80 - Seafoam Green
-- * 96 - Green
-- * 112 - Lime Green
-- * 128 - Yellow
-- * 144 - Yellowy Orange
-- * 160 - Orange
-- * 176 - Red
-- * 194 - Pink
-- * 210 - Fuscia
-- * 226 - Lilac
-- * 240 - Lavendar
---@return boolean
function M:zoneColor(zone, value, ...) end
-- Turns off the specified zone
--
-- Parameters:
-- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
--
-- Returns:
-- * True if the command was sent correctly, otherwise false
---@return boolean
function M:zoneOff(zone, ...) end
-- Turns on the specified zone
--
-- Parameters:
-- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
--
-- Returns:
-- * True if the command was sent correctly, otherwise false
---@return boolean
function M:zoneOn(zone, ...) end
-- Sets the specified zone to white
--
-- Parameters:
-- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
--
-- Returns:
-- * True if the command was sent correctly, otherwise false
---@return boolean
function M:zoneWhite(zone, ...) end
|
net.Receive("se_event", function(len)
local event = net.ReadString()
local compress = net.ReadBool()
local args = {}
if compress then
local len = net.ReadInt(32)
args = net.ReadData(len)
args = util.JSONToTable( util.Decompress( args ) )
else
args = net.ReadTable()
end
hook.Run("se_event_"..event, unpack(args))
end)
function se_send_event(event, args)
net.Start("se_event")
net.WriteString(event)
net.WriteTable(args)
net.SendToServer()
end
|
include("plat/build.lua")
headermap = {}
packagemap = {}
local function addheader(h)
headermap[h] = "./"..h
packagemap["$(PLATIND)/cpm/include/"..h] = "./"..h
end
addheader("ack/plat.h")
addheader("ack/file.h")
addheader("sys/types.h")
addheader("cpm.h")
acklibrary {
name = "headers",
hdrs = headermap
}
installable {
name = "pkg",
map = packagemap
}
|
-------------------------------------------------------------------------------
--[[FDOC
@id TppTrapCheckIntrude
@category TppTrap
Intrude用Trap実行可能かどうかの確認のScript
]]
--------------------------------------------------------------------------------
TppTrapCheckIntrude = {
--- 条件関数
-- 入った人にPlayerタグがついていたら実行
Check = function( info )
for key, value in pairs( info.moverTags ) do
--Fox.Log("Check : " .. tostring(key))
-- 渡辺さんに聞いた所、moverTags規約が決まってないのでLocatorの名前らしい
if key == "PlayerLocator" then
--Fox.Log("return 1")
return 1
end
end
return 0
end,
}
|
local path = "UserPrefs/" .. THEME:GetThemeDisplayName() .. "/"
-- Hook called during profile load
function LoadProfileCustom(profile, dir, isEdit)
local PrefPath = dir .. path
if isEdit ~= true then
local pn
-- we've been passed a profile object as the variable "profile"
-- see if it matches against anything returned by PROFILEMAN:GetProfile(pn)
local Players = GAMESTATE:GetHumanPlayers()
if Players then
for player in ivalues(Players) do
if profile == PROFILEMAN:GetProfile(player) then
pn = player;
end
end
end
-- ...and then, if a player profile exists, read .cfg files from it
if pn then
local pns = pname(pn); --pn = PlayerNumber_PX, pns = PX
local f = RageFileUtil.CreateRageFile()
local setting
--This uses the ActiveModifiers table from PlayerOptions.lua
for k,v in pairs( ActiveModifiers[pns] ) do
local fullFilename = PrefPath..k..".cfg"
if f:Open(fullFilename,1) then
-- RageFile's Read() method always returns a string
setting = f:Read()
-- but maybe we don't want a string; attempt to convert
if setting == "true" then setting = true
elseif setting == "false" then setting = false
end
ActiveModifiers[pns][k] = setting
else
local fError = f:GetError()
Trace( "[FileUtils] Error reading ".. fullFilename ..": ".. fError )
f:ClearError()
end
end
--Custom profile icon handling
--Check for icons inside the profile directory first (local profile, USB stick, whatever)
local profileIcon = getLocalProfileIcon(dir)
if profileIcon then
setenv("profile_icon_"..pns,profileIcon);
else --None found, check if it's a built in profile icon in the ActiveModifiers table
--Will return nil if there isn't a profile icon, but if there was one we want to check that the icon hasn't been removed or renamed
if ActiveModifiers[pns]["ProfileIcon"] and FILEMAN:DoesFileExist(THEME:GetPathG("","USB_stuff/avatars").."/"..ActiveModifiers[pns]["ProfileIcon"]) then
setenv("profile_icon_"..pns,THEME:GetPathG("","USB_stuff/avatars").."/"..ActiveModifiers[pns]["ProfileIcon"]);
else --Still none found, just pick a random one
setenv("profile_icon_"..pns,getRandomProfileIcon(pn));
end;
end;
-- don't destroy the RageFile until we've tried to load all custom options
-- and set them to the env table to make them accessible from anywhere in SM
f:destroy()
end
--Special handling for editing profiles from operator menu because neither P1 or P2 is joined.
else
local f = RageFileUtil.CreateRageFile()
local setting
--This uses the ActiveModifiers table from PlayerOptions.lua
for k,v in pairs( ActiveModifiers["EDIT"] ) do
local fullFilename = PrefPath..k..".cfg"
if f:Open(fullFilename,1) then
-- RageFile's Read() method always returns a string
setting = f:Read()
-- but maybe we don't want a string; attempt to convert
if setting == "true" then setting = true
elseif setting == "false" then setting = false
end
ActiveModifiers["EDIT"][k] = setting
else
local fError = f:GetError()
Trace( "[FileUtils] Error reading ".. fullFilename ..": ".. fError )
f:ClearError()
end
end
-- don't destroy the RageFile until we've tried to load all custom options
-- and set them to the env table to make them accessible from anywhere in SM
f:destroy()
end;
return true
end
-- Hook called during profile save
function SaveProfileCustom(profile, dir, isEdit)
local PrefPath = dir .. path
if isEdit ~= true then
local pn
local Players = GAMESTATE:GetHumanPlayers()
for player in ivalues(Players) do
if profile == PROFILEMAN:GetProfile(player) then
pn = ToEnumShortString(player)
end
end
if pn then
-- a generic ragefile (?)
local f = RageFileUtil.CreateRageFile()
-- then loop through the prefs, saving one .cfg file per available setting
-- if a particular value is nil, nothing gets written
for k,v in pairs( ActiveModifiers[pn] ) do
local fullFilename = PrefPath..k..".cfg"
if f:Open(fullFilename, 2) then
--Warn("[FileUtils] Writing to"..fullFilename);
-- if a setting exists (it should) write that to the .cfg file
if v ~= nil then
f:Write( tostring( v ) )
end
else
local fError = f:GetError()
Trace( "[FileUtils] Error writing to ".. fullFilename ..": ".. fError )
f:ClearError()
end
end
-- again, don't destroy the file until after we're done looping
-- through all possible custom options
f:destroy()
end
else --Same as above function
-- a generic ragefile (?)
local f = RageFileUtil.CreateRageFile()
-- then loop through the prefs, saving one .cfg file per available setting
-- if a particular value is nil, nothing gets written
for k,v in pairs( ActiveModifiers["EDIT"] ) do
local fullFilename = PrefPath..k..".cfg"
if f:Open(fullFilename, 2) then
--Warn("[FileUtils] Writing to"..fullFilename);
-- if a setting exists (it should) write that to the .cfg file
if v ~= nil then
f:Write( tostring( v ) )
end
else
local fError = f:GetError()
Trace( "[FileUtils] Error writing to ".. fullFilename ..": ".. fError )
f:ClearError()
end
end
-- again, don't destroy the file until after we're done looping
-- through all possible custom options
f:destroy()
end;
return true
end
Trace("[CustomProfiles] Loaded functions.")
|
--Basic module
local logger = require("utilities.logger")
local telegram = require("telegram")
local localization = require("utilities.localization")
local supportedLanguages = localization.supportedLanguages()
local InlineKeyboardButton = telegram.structures.InlineKeyboardButton
local InlineKeyboardMarkup = telegram.structures.InlineKeyboardMarkup
local function promptForLanguage(chat, from)
local keyboard = {}
for id, title in pairs(supportedLanguages) do
local button = InlineKeyboardButton(title)
button.callbackData = "set_language:"..id
table.insert(keyboard, {button})
end
local markup = InlineKeyboardMarkup(keyboard)
chat:sendMessage(localization.formatLanguage(from.languageCode, "language_select"), nil, nil, nil, nil, markup)
end
local function sendHelp(chat, from)
chat:sendMessage(localization.format(from.id, "basic_help"))
end
--The module's commands array
local commands = {}
--------------------------------[[ /start command ]]--------------------------------
function commands.start(message)
if not message then return end
promptForLanguage(message.chat, message.from)
end
--------------------------------[[ /language command ]]--------------------------------
function commands.language(message)
if not message then return "Select the language of the bot 🌐" end
promptForLanguage(message.chat, message.from)
end
--------------------------------[[ /help command ]]--------------------------------
function commands.help(message)
if not message then return "What can this bot do? 🤔" end
sendHelp(message.chat, message.from)
end
--------------------------------[[ /faq command ]]--------------------------------
function commands.faq(message)
if not message then return "Frequently asked questions 📖" end
message.chat:sendMessage(localization.format(message.from.id, "basic_faq"), "Markdown")
end
--------------------------------[[ /ping command ]]--------------------------------
function commands.ping(message)
if not message then return end
message.chat:sendMessage("Pong 🏓")
end
--------------------------------[[ Raw updates handler ]]--------------------------------
local function callbackQueryHandler(query)
local data = query.data
if data and data:match("^set_language:") then
local lang = data:gsub("^set_language:", "")
localization.setLanguage(query.from.id, lang)
STATSD:increment("language.selected,lang="..tostring(lang))
if query.message then
query.message:deleteMessage()
query:answerCallbackQuery(localization.format(query.from.id, "language_selected"))
sendHelp(query.message.chat, query.from)
else
query:answerCallbackQuery(localization.format(query.from.id, "language_selected"))
end
end
end
--The module's update handler
local function updateHandler(update)
if update.callbackQuery then
local ok, err = pcall(callbackQueryHandler, update.callbackQuery)
if not ok then logger.critical("Failed to execute the callback query handler:", err) end
end
end
return {commands, updateHandler}
|
require "class"
local G = 6.67408e-11
particle_system = class:new()
function particle_system:init()
self.particles = {}
end
function particle_system:calculate_acceleration(p)
local ax, ay = 0, 0
for i=1, #self.particles do
local pp = self.particles[i]
if pp ~= p then
local dx = p.x - pp.x
local dy = p.y - pp.y
local r3 = math.sqrt(dx*dx + dy*dy)^3
local G_mass_r3 = G * pp.mass / r3
ax = ax + G_mass_r3 * dx
ay = ay + G_mass_r3 * dy
end
end
return -ax, -ay
end
function particle_system:update_velocity(p, dt)
local ax, ay = self:calculate_acceleration(p)
p.velx = p.velx + ax * dt
p.vely = p.vely + ay * dt
end
function particle_system:update_position(p, dt)
p.x = p.x + p.velx * dt
p.y = p.y + p.vely * dt
end
function particle_system:spawn_particle(x, y, mass, velx, vely, radius, position_ratio, col)
self.particles[#self.particles + 1] = {
x = x,
y = y,
mass = mass,
velx = velx,
vely = vely,
radius = radius,
-- ensure that large universe simulations fit into single window
position_ratio = position_ratio,
col = col
}
end
function particle_system:update(dt)
for i=1, #self.particles do
self:update_velocity(self.particles[i], dt)
end
for i=1, #self.particles do
self:update_position(self.particles[i], dt)
end
end
function particle_system:draw_particle(p)
love.graphics.setColor(p.col.r, p.col.g, p.col.b)
--print(p.x * p.position_ratio, p.y * p.position_ratio)
love.graphics.circle("fill", p.x * p.position_ratio, p.y * p.position_ratio, p.radius, 20)
end
function particle_system:draw()
for i=1, #self.particles do
self:draw_particle(self.particles[i])
end
end
|
local message_pin_map = require("qnFiles/qnPlist/hall/message_pin");
local noticeLayout=
{
name="noticeLayout",type=0,typeName="View",time=0,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft,
{
name="bg_top",type=1,typeName="Image",time=77358592,report=0,x=0,y=0,width=0,height=123,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignTop,file="hall/common/scene_top.png"
},
{
name="bg_bottom",type=1,typeName="Image",time=88933025,report=0,x=0,y=0,width=0,height=0,fillTopLeftX=0,fillTopLeftY=85,fillBottomRightX=0,fillBottomRightY=0,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignBottom,file="hall/common/scene_bg.png"
},
{
name="bg",type=0,typeName="View",time=88933030,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft,
{
name="topView",type=0,typeName="View",time=88933031,report=0,x=0,y=0,width=1280,height=90,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignTop,
{
name="returnBtn",type=2,typeName="Button",time=88933033,report=0,x=26,y=14,width=71,height=71,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,file="hall/common/btn_return.png"
},
{
name="topBg",type=1,typeName="Image",time=88933034,report=0,x=0,y=-45,width=430,height=147,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="hall/common/title_bg.png",
{
name="title",type=1,typeName="Image",time=88933035,report=0,x=0,y=65,width=200,height=52,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file=message_pin_map['sys_msg.png']
}
}
},
{
name="contentView",type=0,typeName="View",time=88933038,report=0,x=15,y=120,width=1250,height=643,fillTopLeftX=18,fillTopLeftY=98,fillBottomRightX=18,fillBottomRightY=0,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,
{
name="listArea",type=0,typeName="View",time=88933039,report=0,x=0,y=0,width=1240,height=670,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,
{
name="listView",type=0,typeName="ListView",time=88933040,report=0,x=0,y=0,width=1250,height=585,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTop
}
},
{
name="text",type=4,typeName="Text",time=88933041,report=0,x=0,y=0,width=0,height=0,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=36,textAlign=kAlignLeft,colorRed=143,colorGreen=94,colorBlue=38,string=[[暂无公告]]
}
}
}
}
return noticeLayout;
|
local awful = require("awful")
local gears = require("gears")
local beautiful = require("beautiful")
local wibox = require("wibox")
-- Get theme variables
local floating_color = beautiful.desktop_mode_color_floating or "#1D8CD2"
local tile_color = beautiful.desktop_mode_color_tile or "#2DD283"
local max_color = beautiful.desktop_mode_color_max or "#D21D43"
local floating_text = beautiful.desktop_mode_text_floating or "(fl)"
local tile_text = beautiful.desktop_mode_text_tile or "(ti)"
local max_text = beautiful.desktop_mode_text_max or "(ma)"
--local desktop_mode_widget = wibox.widget.textbox("")
--desktop_mode_widget.font = beautiful.font
--desktop_mode_widget.align = "center"
local desktop_mode_widget = wibox.widget{
font = 'monospace',
markup = ' ',
align = 'center',
valign = 'center',
widget = wibox.widget.textbox
}
-- Mouse control
desktop_mode_widget:buttons(gears.table.join(
-- Old Left click: toggle between tile and floating + toggle titlebars
-- Left click: toggle titlebar for focused client
awful.button({ }, 1, function ()
--switch_modes()
if client.focus ~= nil then
awful.titlebar.toggle(client.focus, beautiful.titlebar_position)
end
end),
-- Right click: Toggle titlebars in all visible clients
awful.button({ }, 3, function ()
local clients = awful.screen.focused().clients
for _, c in pairs(clients) do
-- Don't toggle if titlebars are used as borders
if not beautiful.titlebars_imitate_borders then
awful.titlebar.toggle(c, beautiful.titlebar_position)
end
end
end),
-- TODO
awful.button({ }, 4, function ()
awful.layout.inc(-1)
--local clients = awful.screen.focused().clients
--for _, c in pairs(clients) do
--awful.titlebar.show(c, beautiful.titlebar_position)
--end
end),
awful.button({ }, 5, function ()
awful.layout.inc(1)
--local clients = awful.screen.focused().clients
--for _, c in pairs(clients) do
---- Don't hide if titlebars are used as borders
--if not beautiful.titlebars_imitate_borders then
--awful.titlebar.hide(c, beautiful.titlebar_position)
--end
--end
end)
))
function switch_modes()
local current_layout = awful.layout.getname(awful.layout.get(awful.screen.focused()))
if current_layout == "floating" then
local clients = awful.screen.focused().clients
for _, c in pairs(clients) do
-- Don't hide if titlebars are used as borders
if not beautiful.titlebars_imitate_borders then
awful.titlebar.hide(c, beautiful.titlebar_position)
end
end
awful.layout.set(awful.layout.suit.tile)
else
--elseif current_layout == "tile" then
local clients = awful.screen.focused().clients
for _, c in pairs(clients) do
awful.titlebar.show(c, beautiful.titlebar_position)
end
-- Delay so that the windows will first be resized properly
-- by the tiling layout
gears.timer.delayed_call(function()
awful.layout.set(awful.layout.suit.floating)
end)
end
end
local function update_widget()
local current_layout = awful.layout.getname(awful.layout.get(awful.screen.focused()))
local color
local txt
if current_layout == "max" then
color = max_color
txt = max_text
elseif current_layout == "tile" then
color = tile_color
txt = tile_text
elseif current_layout == "floating" then
color = floating_color
txt = floating_text
else
--default
color = tile_color
txt = tile_text
end
desktop_mode_widget.markup = "<span foreground='" .. color .."'>" .. txt .. "</span>"
end
-- Signals
awful.tag.attached_connect_signal(s, "property::selected", function ()
update_widget()
end)
awful.tag.attached_connect_signal(s, "property::layout", function ()
update_widget()
end)
return desktop_mode_widget
|
-- {"regionName", xCenter, yCenter, shape and size, tier, {"spawnGroup1", ...}, maxSpawnLimit}
-- Shape and size is a table with the following format depending on the shape of the area:
-- - Circle: {1, radius}
-- - Rectangle: {2, width, height}
-- - Ring: {3, inner radius, outer radius}
-- Tier is a bit mask with the following possible values where each hexadecimal position is one possible configuration.
-- That means that it is not possible to have both a spawn area and a no spawn area in the same region, but
-- a spawn area that is also a no build zone is possible.
require("scripts.managers.spawn_manager.regions")
kashyyyk_regions = {
{"world_spawner",0,0,{1,-1},SPAWNAREA + WORLDSPAWNAREA,{"kashyyyk_world"},2048},
{"kachirho",0,0,{2,2000,2000},NOSPAWNAREA + NOBUILDZONEAREA},
{"sea1",-6500,6500,{1,2000},NOSPAWNAREA},
{"sea2",-6500,4500,{1,2000},NOSPAWNAREA},
{"sea3",-7000,0,{1,2500},NOSPAWNAREA},
{"village1",-2000,0,{1,300},NOSPAWNAREA + NOBUILDZONEAREA},
{"hunting",0,-3000,{2,2800,2000},NOSPAWNAREA + NOBUILDZONEAREA},
{"dead_forest",-1500,1500,{2,1000,1000},NOSPAWNAREA + NOBUILDZONEAREA},
{"bocctyy",2300,0,{2,600,600},NOSPAWNAREA + NOBUILDZONEAREA},
{"hracca",-1100,3500,{2,1000,1000},NOSPAWNAREA + NOBUILDZONEAREA},
{"slaver",-3300,3300,{2,1000,1000},NOSPAWNAREA + NOBUILDZONEAREA},
{"arena",1775,-1825,{1,200},NOSPAWNAREA + NOBUILDZONEAREA},
{"desert",7000,7000,{1,2000},NOSPAWNAREA + NOBUILDZONEAREA},
{"deepwoods",6000,-6000,{1,3000},NOSPAWNAREA + NOBUILDZONEAREA},
}
|
SILE.registerCommand("thisframeLTR", function(options, content)
SILE.typesetter.frame.direction = "LTR"
SILE.typesetter:leaveHmode()
SILE.typesetter.frame:newLine()
end)
SILE.registerCommand("thisframedirection", function(options, content)
SILE.typesetter.frame.direction = SU.required(options, "direction", "frame direction")
SILE.typesetter:leaveHmode()
SILE.typesetter.frame:init()
end)
SILE.registerCommand("thisframeRTL", function(options, content)
SILE.typesetter.frame.direction = "RTL"
SILE.typesetter:leaveHmode()
SILE.typesetter.frame:newLine()
end)
local function reverse_portion(tbl, s,e)
rv = {}
for i = 1,s-1 do rv[#rv+1] = tbl[i] end
for i = e,s,-1 do rv[#rv+1] = tbl[i] end
for i = e+1, #tbl do rv[#rv+1] = tbl[i] end
return rv
end
local function create_matrix(line, base_level)
-- L2; create a transformation matrix of elements
-- such that output[matrix[i]] = input[i]
-- e.g. No reversions required: [1,2,3,4,5]
-- Levels [0,0,0,1,1] -> [1,2,3,5,4]
local max_level = 0
local matrix = {}
for i,c in next, line do
if c.level > max_level then max_level = c.level end
matrix[i] = i
end
for level = base_level+1, max_level do
local level_start, level_limit
for i,_ in next, line do
if line[i].level >= level then
if not level_start then
level_start = i
elseif i == #line then
level_end = i
matrix = reverse_portion(matrix, level_start, level_end)
level_start = nil
end
else
if level_start then
level_end = i-1
matrix = reverse_portion(matrix, level_start, level_end)
level_start = nil
end
end
end
end
return matrix
end
local reverse_each_node = function(nodelist)
for j =1,#nodelist do
if nodelist[j].type =="hbox" then
if nodelist[j].value.items then table.flip(nodelist[j].value.items) end
table.flip(nodelist[j].value.glyphString)
end
end
end
local reorder = function(n, self)
local nl = n.nodes
local newNl = {}
local matrix = {}
local levels = {}
local base_level = self.frame:writingDirection() == "RTL" and 1 or 0
for i=1,#nl do
if nl[i].options and nl[i].options.bidilevel then
levels[i] = { level = nl[i].options.bidilevel }
end
end
for i=1,#nl do if not levels[i] then
-- resolve neutrals
local left_level, right_level, left, right
for left = i-1,1,-1 do if nl[left].options and nl[left].options.bidilevel then
left_level = nl[left].options.bidilevel
break
end end
for right = i+1,#nl do if nl[right].options and nl[right].options.bidilevel then
right_level = nl[right].options.bidilevel
break
end end
levels[i] = {level = (left_level == right_level and left_level or 0) }
end end
local matrix = create_matrix(levels,0)
local rv = {}
-- for i = 1,#nl do print(i,nl[i],levels[i]) end
for i = 1, #nl do
if nl[i]:isNnode() and levels[i].level %2 ~= base_level then
table.flip(nl[i].nodes)
reverse_each_node(nl[i].nodes)
elseif nl[i]:isDiscretionary() and levels[i].level %2 ~= base_level and not nl[i].bidiDone then
for j = 1,#(nl[i].replacement) do
if nl[i].replacement[j]:isNnode() then
table.flip(nl[i].replacement[j].nodes)
reverse_each_node(nl[i].replacement[j].nodes)
end
end
for j = 1,#(nl[i].prebreak) do
if nl[i].prebreak[j]:isNnode() then
table.flip(nl[i].prebreak[j].nodes)
reverse_each_node(nl[i].prebreak[j].nodes)
end
end
for j = 1,#(nl[i].postbreak) do
if nl[i].postbreak[j]:isNnode() then
table.flip(nl[i].postbreak[j].nodes)
reverse_each_node(nl[i].postbreak[j].nodes)
end
end
end
rv[matrix[i]] = nl[i]
nl[i].bidiDone = true
-- rv[i] = nl[i]
end
n.nodes = SU.compress(rv)
end
local nodeListToText = function (nl)
local owners, text = {}, {}
local p = 1
for i = 1,#nl do local n = nl[i]
if n.text then
local utfchars = SU.splitUtf8(n.text)
for j = 1,#utfchars do
owners[p] = { node = n, pos = j }
text[p] = utfchars[j]
p = p + 1
end
else
owners[p] = { node = n }
text[p] = SU.utf8char(0xFFFC)
p = p + 1
end
end
return owners, text
end
local splitNodeAtPos = function (n,splitstart, p)
if n:isUnshaped() then
local utf8chars = SU.splitUtf8(n.text)
local n2 = SILE.nodefactory.newUnshaped({ text = "", options = table.clone(n.options) })
local n1 = SILE.nodefactory.newUnshaped({ text = "", options = table.clone(n.options) })
for i = splitstart,#utf8chars do
if i <= p then n1.text = n1.text .. utf8chars[i]
else n2.text = n2.text .. utf8chars[i]
end
end
return n1,n2
else
SU.error("Unsure how to split node "..n.." at position "..p,1)
end
end
local splitNodelistIntoBidiRuns = function (self)
local nl = self.state.nodes
if #nl == 0 then return nl end
local owners, text = nodeListToText(nl)
local base_level = self.frame:writingDirection() == "RTL" and 1 or 0
local runs = { icu.bidi_runs(table.concat(text), self.frame:writingDirection()) }
runs = table.sort(runs, function (a,b) return a.start < b.start end)
local newNl = {}
-- Split nodes on run boundaries
for i = 1,#runs do
local run = runs[i]
local thisOwner = owners[run.start+run.length]
local nextOwner = owners[run.start+1+run.length]
-- print(thisOwner, nextOwner)
if nextOwner and thisOwner.node == nextOwner.node then
local before,after = splitNodeAtPos(nextOwner.node, 1,nextOwner.pos-1)
-- print(before,after)
local start = nil
for j = run.start+1, run.start+run.length do
if owners[j].node==nextOwner.node then
if not start then start = j end
owners[j]={node=before,pos=j-start+1}
end
end
for j = run.start+1+run.length,#owners do
if owners[j].node==nextOwner.node then
owners[j] = {node = after, pos=j-(run.start+run.length)}
end
end
end
end
-- Assign direction/level to nodes
for i = 1,#runs do
local runstart = runs[i].start+1
local runend = runstart + runs[i].length-1
for j= runstart,runend do
if owners[j].node and owners[j].node.options then
owners[j].node.options.direction = runs[i].dir
owners[j].node.options.bidilevel = runs[i].level - base_level
end
end
end
-- String together nodelist
nl={}
for i=1,#owners do
if #nl and nl[#nl] ~= owners[i].node then
nl[#nl+1] = owners[i].node
-- print(nl[#nl], nl[#nl].options)
end
end
-- for i = 1,#nl do print(i,nl[i]) end
return nl
end
local bidiBoxupNodes = function (self)
local allDone = true
for i=1,#self.state.nodes do
if not self.state.nodes[i].bidiDone then allDone = false end
end
if allDone then return SILE.defaultTypesetter.boxUpNodes(self) end
local newNodeList = splitNodelistIntoBidiRuns(self)
self:shapeAllNodes(newNodeList)
self.state.nodes = newNodeList
local vboxlist = SILE.defaultTypesetter.boxUpNodes(self)
-- Scan for out-of-direction material
for i=1,#vboxlist do local v = vboxlist[i]
if v:isVbox() then reorder(v, self) end
end
return vboxlist
end
SILE.typesetter.boxUpNodes = bidiBoxupNodes
SILE.registerCommand("bidi-on", function(options, content)
SILE.typesetter.boxUpNodes = bidiBoxupNodes
end)
SILE.registerCommand("bidi-off", function(options, content)
SILE.typesetter.boxUpNodes = SILE.defaultTypesetter.boxUpNodes
end)
return {
reorder = reorder,
documentation = [[\begin{document}
Scripts like the Latin alphabet you are currently reading are normally written left to
right; however, some scripts, such as Arabic and Hebrew, are written right to left.
The \code{bidi} package, which is loaded by default, provides SILE with the ability to
correctly typeset right-to-left text and also documents which mix right-to-left and
left-to-right typesetting. Because it is loaded by default, you can use both
LTR and RTL text within a paragraph and SILE will ensure that the output
characters appear in the correct order.
The \code{bidi} package provides two commands, \command{\\thisframeLTR} and
\command{\\thisframeRTL}, which set the default text direction for the current frame.
That is, if you tell SILE that a frame is RTL, the text will start in the right margin
and proceed leftward. It also provides the commands \command{\\bidi-off} and
\command{\\bidi-on}, which allow you to trade off bidirectional support for a dubious
increase in speed.
\end{document}]] }
|
RemoteEvent:FireServer()
RemoteEvent.OnServerEvent:Connect(function(player)
--Statements
end)
RemoteEvent:FireClient(player) --Sends signal to single client
RemoteEvent:FireAllClients() --Sends signal to all clients
--server
wait(5)
RemoteEvent:FireAllClients("Game over!", "Blue team has won!")
--client
local starterGui = game:GetService("StarterGui")
RemoteEvent.OnClientEvent:Connect(function(title, text)
starterGui:SetCore("SendNotification", {
Title = title;
Text = text;
})
end)
RemoteFunction:InvokeServer()
RemoteFunction.OnServerInvoke = function(player)
return --optional but use a RemoteEvent for subroutines
end
RemoteFunction:InvokeClient(player)
--server
local clientCamCFrame = RemoteFunction:InvokeClient(player)
--client
local cam = workspace.CurrentCamera
local function getCamCFrame()
return cam.CFrame
end
RemoteFunction.OnClientInvoke = getCamCFrame
--script 1
local function sum(...)
local sum = 0
local nums = {...}
for _, num in pairs(nums) do
sum = sum + num
end
return sum
end
Function.OnInvoke = sum
--script 2
local sum = Function:Invoke(2, 4, 11)
print(sum)
|
local BasePlugin = require "kong.plugins.base_plugin"
local CustomHandler = BasePlugin:extend()
CustomHandler.PRIORITY = 10
function CustomHandler:new()
CustomHandler.super.new(self, "conditional-upstream")
end
function CustomHandler:init_worker(config)
-- Eventually, execute the parent implementation
-- (will log that your plugin is entering this context)
CustomHandler.super.init_worker(self)
-- Implement any custom logic here
end
function CustomHandler:certificate(config)
-- Eventually, execute the parent implementation
-- (will log that your plugin is entering this context)
CustomHandler.super.certificate(self)
-- Implement any custom logic here
end
function CustomHandler:rewrite(config)
-- Eventually, execute the parent implementation
-- (will log that your plugin is entering this context)
CustomHandler.super.rewrite(self)
-- Implement any custom logic here
end
function CustomHandler:access(config)
-- Eventually, execute the parent implementation
-- (will log that your plugin is entering this context)
CustomHandler.super.access(self)
-- Implement any custom logic here
end
function CustomHandler:header_filter(config)
-- Eventually, execute the parent implementation
-- (will log that your plugin is entering this context)
CustomHandler.super.header_filter(self)
-- Implement any custom logic here
end
function CustomHandler:body_filter(config)
-- Eventually, execute the parent implementation
-- (will log that your plugin is entering this context)
CustomHandler.super.body_filter(self)
-- Implement any custom logic here
end
function CustomHandler:log(config)
-- Eventually, execute the parent implementation
-- (will log that your plugin is entering this context)
CustomHandler.super.log(self)
-- Implement any custom logic here
end
-- This module needs to return the created table, so that Kong
-- can execute those functions.
return CustomHandler
|
local Proxy = module("vrp", "lib/Proxy")
local Tunnel = module("vrp", "lib/Tunnel")
vRP = Proxy.getInterface("vRP")
vRPclient = Tunnel.getInterface("vRP","vrp_stationaryRadars")
RegisterServerEvent('cobrarMulta')
AddEventHandler('cobrarMulta', function()
local user_id = vRP.getUserId({source})
local player = vRP.getUserSource({user_id})
local multa = 350
if vRP.hasPermission({user_id,"radar.pass"}) then
vRPclient.notify(player,{"~r~Sem multas para você! Obrigado por seus serviços!"})
else
vRP.tryFullPayment({user_id,multa})
end
end)
|
Sprite_TitleCommand = Sprite:extend("Sprite_TitleCommand")
function Sprite_TitleCommand.prototype:constructor(index, image, command)
Sprite.prototype.constructor(self, image)
local w, h = image:getDimensions()
self.index = index
self.command = command
self.position:set((Game_Camera.width - w) / 2, Game_Camera.height - h * (4 - index) + 32)
self.srcRect:set(0, 0, w, h)
end
|
--[[
MIT License
Copyright (c) 2019 Michael Wiesendanger
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]--
local mod = gm
local me = {}
mod.quickChange = me
me.tag = "QuickChange"
--[[
Save new quick change rule
@param (number) changeFromId
item to switch from
@param (number) changeToId
item to switch to
@param {number} delay
time to wait before changing an item
@return (nil)
]]--
function me.AddQuickChangeRule(changeFromId, changeToId, delay)
local quickChangeRule = {}
local slotId
changeFromName, _, itemFromQuality, _, _, _, _, equipFromSlot, itemFromTexture = GetItemInfo(changeFromId)
changeToName, _, itemToQuality, _, _, _, _, equipToSlot, itemToTexture = GetItemInfo(changeToId)
for _, item in pairs(GM_CONSTANTS.ITEM_CATEGORIES) do
for i = 1, table.getn(item.type) do
if equipFromSlot == item.type[i] then
slotId = item.slotId
end
end
end
quickChangeRule.slotId = slotId
quickChangeRule.changeFromName = changeFromName
quickChangeRule.changeFromId = tonumber(changeFromId)
quickChangeRule.changeToName = changeToName
quickChangeRule.changeToId = tonumber(changeToId)
quickChangeRule.changeDelay = delay
mod.addonOptions.AddQuickChangeRule(quickChangeRule)
-- update rule list
mod.quickChangeMenu.QuickChangeRuleListOnUpdate()
end
--[[
@param {number} position
]]--
function me.RemoveQuickChangeRule(position)
mod.addonOptions.RemoveQuickChangeRule(position)
-- update rule list
mod.quickChangeMenu.QuickChangeRuleListOnUpdate()
end
--[[
@param {number} slotId
]]--
function me.UpdateQuickChange(slotId)
local quickChangeRules = mod.addonOptions.GetQuickChangeRules()
for i = 1, table.getn(quickChangeRules) do
for it = 1, table.getn(quickChangeRules[i].slotId) do
if slotId == quickChangeRules[i].slotId[it] then
local itemId = mod.itemHelper.GetItemIdBySlot(slotId)
if tonumber(itemId) == quickChangeRules[i].changeFromId then
-- found a quick change rule that matches - prepare for switching
me.SwitchItems(quickChangeRules[i], slotId)
end
end
end
end
end
--[[
Check if an items was successfully used before kicking off Quick Change
@param {number} slotId
]]--
function me.CheckItemUse(slotId)
-- wait a bit then check if there is a startime for the cooldown on the item
local checkItemUseStatusCallback = function ()
local start, duration, enable = GetInventoryItemCooldown("player", slotId)
-- 1 meaning item has an onUse effect
if enable == 1 and start ~= 0 then
-- inform quick change about used item
mod.quickChange.UpdateQuickChange(slotId)
elseif enable == 0 then
mod.quickChange.UpdateQuickChange(slotId)
end
mod.timer.StopTimer("checkItemUseStatus")
end
mod.timer.CreateTimer("checkItemUseStatus", checkItemUseStatusCallback, 0.25, 0.25)
mod.timer.StartTimer("checkItemUseStatus")
end
--[[
Switch items for a found rule
@param {table} rule
@param {number} slotId
]]--
function me.SwitchItems(rule, slotId)
local timerName = "QuickChange_" .. math.floor(math.random() * 100000000000000)
local quickChangeSwitchCallback = function()
mod.timer.StopTimer(timerName)
mod.logger.LogDebug(me.tag, "ChangeToName: " .. rule.changeToName .. " slotId: " .. slotId)
mod.combatQueue.AddToQueue(rule.changeToId, slotId)
-- kick off combat queue
mod.combatQueue.ProcessQueue()
end
if rule.changeDelay ~= 0 then
mod.timer.CreateTimer(timerName, quickChangeSwitchCallback, rule.changeDelay, 0.25)
mod.timer.StartTimer(timerName)
else
mod.timer.CreateTimer(timerName, quickChangeSwitchCallback, 0.25, 0.25)
-- start a timer before switching the item. An immediate change is blocked by the ui
mod.timer.StartTimer(timerName) -- default delay
end
end
|
-- oUF_SimpleConfig: tags
-- zork, 2016
-----------------------------
-- Variables
-----------------------------
local A, L = ...
-----------------------------
-- Tags
-----------------------------
local floor = floor
--tag method: oUF_SimpleConfig:status
L.C.tagMethods["oUF_SimpleConfig:status"] = function(unit,...)
if UnitAffectingCombat(unit) then
return "|TInterface\\CharacterFrame\\UI-StateIcon:20:20:0:0:64:64:33:64:0:31|t"
elseif unit == "player" and IsResting() then
return "|TInterface\\CharacterFrame\\UI-StateIcon:20:20:0:0:64:64:0:31:0:31|t"
end
end
--tag event: oUF_Simple:status
L.C.tagEvents["oUF_SimpleConfig:status"] = "PLAYER_REGEN_DISABLED PLAYER_REGEN_ENABLED PLAYER_UPDATE_RESTING"
|
local buf = require('lib.buf')
local M = {}
M.__index = M
-- local config = {
-- relative = 'editor' | 'win' | 'cursor' | '',
-- win = winid,
-- anchor = 'NW' | 'NE' | 'SW' | 'SE',
-- width = 0,
-- height = 0,
-- row = 0,
-- col = 0,
-- focusable = true,
-- zindex = 100,
-- border = 'rounded',
-- noautocmd = false,
-- }
function M.New(opts)
opts = opts or {}
local w = setmetatable({}, M)
w.name = opts.name
w.winid = nil
w.winnr = nil
w.enter = opts.enter or false
w.config = opts.config or { relative = 'cursor', width = 1, height = 1}
w.options = opts.options or {}
w.buffer = opts.buffer
return w
end
function M:GetOption(key)
if vim.fn.exists('+'..key) == 0 then
return nil
end
if not self:Visible() then
return self.options[key]
else
return vim.api.nvim_win_get_option(self.winid, key)
end
end
function M:SetOption(key, val)
if vim.fn.exists('+'..key) == 0 or val == nil then
return
end
self.options[key] = val
if self:Visible() then
vim.api.nvim_win_set_option(self.winid, key, val)
end
end
function M:SetOptions(opts)
for k, v in pairs(opts) do
self:SetOption(k, v)
end
end
function M:Visible()
return self.winid and vim.api.nvim_win_is_valid(self.winid)
end
function M:Open()
if self:Visible() then
return
end
if self.config.width < 1 or self.config.height < 1 then
return
end
if not self.buffer:Valid() then
self.buffer = buf.New()
end
self.winid = vim.api.nvim_open_win(self.buffer.bufnr, self.enter, self.config)
self:SetOptions(self.options)
self:Update()
end
function M:Update()
if not self:Visible() then
return
end
vim.api.nvim_win_set_config(self.winid, self.config)
end
function M:Close()
if not self:Visible() then
return
end
vim.api.nvim_win_hide(self.winid)
self.winid = nil
end
local testWin = M.New({
name = 'TestWin',
enter = true,
config = {
relative = 'cursor',
width = 8,
height = 8,
row = 1,
col = 1,
border = 'rounded'
},
options = {
}
})
testWin:Open()
return M
|
slot2 = "CheckSplashCompleteBean"
CheckSplashCompleteBean = class(slot1)
CheckSplashCompleteBean.ctor = function (slot0)
slot4 = AbstractBean
ClassUtil.extends(slot2, slot0)
end
CheckSplashCompleteBean.start = function (slot0)
if ProxyClientSplash then
slot3 = ProxyClientSplash
if not ProxyClientSplash.isComplete(slot2) then
slot3 = ProxyClientSplash
slot7 = slot0.onSplashComplete
ProxyClientSplash.pushCompleteCallback(slot2, handler(slot5, slot0))
end
else
slot3 = slot0
slot0.finish(slot2)
end
end
CheckSplashCompleteBean.onSplashComplete = function (slot0)
slot3 = slot0
slot0.finish(slot2)
end
return
|
-- Natural Selection 2 Competitive Mod
-- Source located at - https://github.com/xToken/CompMod
-- lua\CompMod\Structures\Alien\Veil\client.lua
-- - Dragon
local originalVeilOnUpdate
originalVeilOnUpdate = Class_ReplaceMethod("Veil", "OnUpdate",
function(self, deltaTime)
originalVeilOnUpdate(self, deltaTime)
if self.isTeleporting ~= self.lastisTeleporting then
-- This isnt good coding, but these are all over the place in vanilla
if not self.isTeleporting and self.lastisTeleporting then
-- We are not teleporting, trigger clear, then infest start.
self:CleanupInfestation()
end
self.lastisTeleporting = self.isTeleporting
end
end
)
|
--------------------------------------------------------------------------------
---------------------- ## ##### ##### ###### -----------------------
---------------------- ## ## ## ## ## ## ## -----------------------
---------------------- ## ## ## ## ## ###### -----------------------
---------------------- ## ## ## ## ## ## -----------------------
---------------------- ###### ##### ##### ## -----------------------
---------------------- -----------------------
----------------------- Lua Object-Oriented Programming ------------------------
--------------------------------------------------------------------------------
-- Project: LOOP Class Library --
-- Release: 2.3 beta --
-- Title : Cooperative Threads Scheduler with Integrated I/O --
-- Author : Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
--[[VERBOSE]] local rawget = rawget
--[[VERBOSE]] local tostring = tostring
local ipairs = ipairs
local getmetatable = getmetatable
local math = require "math"
local oo = require "loop.simple"
local MapWithArrayOfKeys = require "loop.collection.MapWithArrayOfKeys"
local Scheduler = require "loop.thread.Scheduler"
module "loop.thread.IOScheduler"
oo.class(_M, Scheduler)
--------------------------------------------------------------------------------
-- Initialization Code ---------------------------------------------------------
--------------------------------------------------------------------------------
function __init(class, self)
self = Scheduler.__init(class, self)
self.reading = MapWithArrayOfKeys()
self.writing = MapWithArrayOfKeys()
return self
end
__init(getmetatable(_M), _M)
--------------------------------------------------------------------------------
-- Internal Functions ----------------------------------------------------------
--------------------------------------------------------------------------------
function signalall(self, timeout) --[[VERBOSE]] local verbose = self.verbose
if timeout then timeout = math.max(timeout - self:time(), 0) end
local reading, writing = self.reading, self.writing
if #reading > 0 or #writing > 0 then --[[VERBOSE]] verbose:scheduler(true, "signaling blocked threads for ",timeout," seconds")
local running = self.running
local readok, writeok = self.select(reading, writing, timeout)
local index = 1
while index <= #reading do
local channel = reading[index]
if readok[channel] then --[[VERBOSE]] verbose:threads("unblocking reading ",reading[channel])
running:enqueue(reading[channel])
reading:removeat(index)
else
index = index + 1
end
end
index = 1
while index <= #writing do
local channel = writing[index]
if writeok[channel] then --[[VERBOSE]] verbose:threads("unblocking writing ", writing[channel])
running:enqueue(writing[channel])
writing:removeat(index)
else
index = index + 1
end
end --[[VERBOSE]] verbose:scheduler(false, "blocked threads signaled")
return true
elseif timeout and timeout > 0 then --[[VERBOSE]] verbose:scheduler("no threads blocked, sleeping for ",timeout," seconds")
self.sleep(timeout)
end
return false
end
--------------------------------------------------------------------------------
-- Customizable Behavior -------------------------------------------------------
--------------------------------------------------------------------------------
idle = signalall
--------------------------------------------------------------------------------
-- Exported API ----------------------------------------------------------------
--------------------------------------------------------------------------------
function register(self, routine, previous)
local reading, writing = self.reading, self.writing
for _, channel in ipairs(reading) do
if reading[channel] == routine then return end
end
for _, channel in ipairs(writing) do
if writing[channel] == routine then return end
end
return Scheduler.register(self, routine, previous)
end
local function handleremoved(self, routine, removed, ...)
local reading, writing = self.reading, self.writing
local index = 1
while index <= #reading do
local channel = reading[index]
if reading[channel] == routine then
reading:removeat(index)
removed = routine
else
index = index + 1
end
end
index = 1
while index <= #writing do
local channel = writing[index]
if writing[channel] == routine then
writing:removeat(index)
removed = routine
else
index = index + 1
end
end
return removed, ...
end
function remove(self, routine)
return handleremoved(self, routine, Scheduler.remove(self, routine))
end
--------------------------------------------------------------------------------
-- Control Functions -----------------------------------------------------------
--------------------------------------------------------------------------------
function step(self, ...) --[[VERBOSE]] local verbose = self.verbose; verbose:scheduler(true, "performing scheduling step")
local signaled = self:signalall(0)
local wokenup = self:wakeupall()
local resumed = self:resumeall(nil, ...) --[[VERBOSE]] verbose:scheduler(false, "scheduling step performed")
return signaled or wokenup or resumed
end
--------------------------------------------------------------------------------
-- Verbose Support -------------------------------------------------------------
--------------------------------------------------------------------------------
--[[VERBOSE]] local oldfunc = verbose.custom.threads
--[[VERBOSE]] function verbose.custom:threads(...)
--[[VERBOSE]] local viewer = self.viewer
--[[VERBOSE]] local output = self.viewer.output
--[[VERBOSE]]
--[[VERBOSE]] oldfunc(self, ...)
--[[VERBOSE]]
--[[VERBOSE]] local scheduler = rawget(self, "schedulerdetails")
--[[VERBOSE]] if scheduler then
--[[VERBOSE]] local newline = "\n"..viewer.prefix..viewer.indentation
--[[VERBOSE]]
--[[VERBOSE]] output:write(newline)
--[[VERBOSE]] output:write("Reading:")
--[[VERBOSE]] for _, current in ipairs(scheduler.reading) do
--[[VERBOSE]] current = scheduler.reading[current]
--[[VERBOSE]] output:write(" ")
--[[VERBOSE]] output:write(tostring(self.labels[current]))
--[[VERBOSE]] end
--[[VERBOSE]]
--[[VERBOSE]] output:write(newline)
--[[VERBOSE]] output:write("Writing:")
--[[VERBOSE]] for _, current in ipairs(scheduler.writing) do
--[[VERBOSE]] current = scheduler.writing[current]
--[[VERBOSE]] output:write(" ")
--[[VERBOSE]] output:write(tostring(self.labels[current]))
--[[VERBOSE]] end
--[[VERBOSE]] end
--[[VERBOSE]] end
|
package.path = "../?.lua;"..package.path
local ffi = require("ffi")
local bea = require("lj2beaengine.beaengine")
local code = "\x62\x02\x05\x40\x00\x44\x33\x22"
local pDisAsm = ffi.new("DISASM")
pDisAsm.EIP = ffi.cast("UInt64", code);
local res = bea.Disasm(pDisAsm)
print("Result: ", res)
print("OP: ", ffi.string(pDisAsm.CompleteInstr))
|
Object = require "classic"
Hitspark = Object.extend(Object)
local frames = {
love.graphics.newImage("stills/sonicExplosion00.png"),
love.graphics.newImage("stills/sonicExplosion00.png"),
love.graphics.newImage("stills/sonicExplosion01.png"),
love.graphics.newImage("stills/sonicExplosion01.png"),
love.graphics.newImage("stills/sonicExplosion02.png"),
love.graphics.newImage("stills/sonicExplosion02.png"),
love.graphics.newImage("stills/sonicExplosion03.png"),
love.graphics.newImage("stills/sonicExplosion03.png"),
love.graphics.newImage("stills/sonicExplosion04.png"),
love.graphics.newImage("stills/sonicExplosion04.png"),
love.graphics.newImage("stills/sonicExplosion05.png"),
love.graphics.newImage("stills/sonicExplosion05.png"),
love.graphics.newImage("stills/sonicExplosion06.png"),
love.graphics.newImage("stills/sonicExplosion06.png"),
love.graphics.newImage("stills/sonicExplosion07.png"),
love.graphics.newImage("stills/sonicExplosion07.png"),
love.graphics.newImage("stills/sonicExplosion08.png"),
love.graphics.newImage("stills/sonicExplosion08.png")
}
function Hitspark.new(self, x, y)
self.x = x
self.y = y
self.frames_shown = 0
end
function Hitspark.draw(self)
love.graphics.setColor(1, 1, 1)
local frame = frames[self.frames_shown + 1]
-- this will need an offset
love.graphics.draw(frame,
self.x - frame:getWidth()/4,
self.y - frame:getHeight()/4,
0, 0.5, 0.5)
end
function Hitspark.update(self)
self.frames_shown = self.frames_shown + 1
if frames[self.frames_shown + 1] == nil then
return false
end
return true
end
return Hitspark
|
local ngx = {}
describe("index construction", function()
package.path = package.path .. ";./lib/resty/gozerian/?.lua"
local index = require('lua-gozerian')
it('init',function()
index.init()
end)
it('body',function()
index.body_filter()
end)
it('header',function()
index.header_filter()
end)
it('request',function()
index.process_request()
end)
end)
|
--------------------------------
-- @module TableView
-- @extend ScrollView,ScrollViewDelegate
-- @parent_module cc
--------------------------------
-- Updates the content of the cell at a given index.<br>
-- param idx index to find a cell
-- @function [parent=#TableView] updateCellAtIndex
-- @param self
-- @param #long idx
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
-- determines how cell is ordered and filled in the view.
-- @function [parent=#TableView] setVerticalFillOrder
-- @param self
-- @param #int order
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
--
-- @function [parent=#TableView] scrollViewDidZoom
-- @param self
-- @param #cc.ScrollView view
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
--
-- @function [parent=#TableView] _updateContentSize
-- @param self
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
--
-- @function [parent=#TableView] getVerticalFillOrder
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- Removes a cell at a given index<br>
-- param idx index to find a cell
-- @function [parent=#TableView] removeCellAtIndex
-- @param self
-- @param #long idx
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
--
-- @function [parent=#TableView] initWithViewSize
-- @param self
-- @param #size_table size
-- @param #cc.Node container
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#TableView] scrollViewDidScroll
-- @param self
-- @param #cc.ScrollView view
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
-- reloads data from data source. the view will be refreshed.
-- @function [parent=#TableView] reloadData
-- @param self
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
-- Inserts a new cell at a given index<br>
-- param idx location to insert
-- @function [parent=#TableView] insertCellAtIndex
-- @param self
-- @param #long idx
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
-- Returns an existing cell at a given index. Returns nil if a cell is nonexistent at the moment of query.<br>
-- param idx index<br>
-- return a cell at a given index
-- @function [parent=#TableView] cellAtIndex
-- @param self
-- @param #long idx
-- @return TableViewCell#TableViewCell ret (return value: cc.TableViewCell)
--------------------------------
-- Dequeues a free cell if available. nil if not.<br>
-- return free cell
-- @function [parent=#TableView] dequeueCell
-- @param self
-- @return TableViewCell#TableViewCell ret (return value: cc.TableViewCell)
--------------------------------
--
-- @function [parent=#TableView] onTouchMoved
-- @param self
-- @param #cc.Touch pTouch
-- @param #cc.Event pEvent
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
--
-- @function [parent=#TableView] onTouchEnded
-- @param self
-- @param #cc.Touch pTouch
-- @param #cc.Event pEvent
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
--
-- @function [parent=#TableView] onTouchCancelled
-- @param self
-- @param #cc.Touch pTouch
-- @param #cc.Event pEvent
-- @return TableView#TableView self (return value: cc.TableView)
--------------------------------
--
-- @function [parent=#TableView] onTouchBegan
-- @param self
-- @param #cc.Touch pTouch
-- @param #cc.Event pEvent
-- @return bool#bool ret (return value: bool)
--------------------------------
-- js ctor<br>
-- lua new
-- @function [parent=#TableView] TableView
-- @param self
-- @return TableView#TableView self (return value: cc.TableView)
return nil
|
function _update()
if game_state == 'running' then
for wall in all(walls) do
wall_update(wall)
end
end
end
function wall_update(self)
if not self.enabled then
self.delay -= 1
if self.delay <= 0 then
self.enabled = true
end
return
end
self.x -= 2.5
if self.x <= -16 then
wall_restart(self)
end
end
function wall_restart(self)
self.x = 128
self.enabled = false
self.delay = 30 + flr(rnd(10))
end
|
local function xml_esc (s)
s = string.gsub(s, "<", "<")
s = string.gsub(s, ">", ">")
s = string.gsub(s, "&", "&")
return s
end
local function table_keys (t)
local keyset = {}
local n = 0
for k in pairs(t) do
n = n + 1
keyset[n] = k
end
table.sort(keyset)
return keyset
end
--for k, v in ipairs(table_keys({a = 1, b = 2})) do print(v) end
local function table_size (t)
local n = 0
for _, _ in pairs(t) do
n = n + 1
end
return n
end
--print(table_size({1, 3, 5}))
local function is_array (x)
if type(x) ~= "table" then return nil end
local n = table_size(x)
local ni = 0
for _, _ in ipairs(x) do
ni = ni + 1
end
return n == ni
end
--print(is_array(true))
--print(is_array({1, 3, 5}))
--print(is_array({1, 3, a = 5}))
preamble_string = [[<?xml version="1.0" encoding="UTF-8"?><Contacts>]]
postamble_string = [[</Contacts>]]
local function datum_to_string (e)
if type(e) == "string" then
return xml_esc(e)
elseif type(e) == "table" then
if is_array(e) then
local s = ""
for _, v in ipairs(e) do
s = s .. string.format([[<element>%s</element>]], v)
end
return s
else
local s = ""
local ks = table_keys(e)
for i, k in ipairs(ks) do
s = s .. string.format([[<%s>%s</%s>]], k, datum_to_string(e[k]), k)
end
return s
end
else
error("unsupported type " + type(e))
end
end
local function details_to_string (ds)
local s = ""
table.sort(ds, function (x, y)
return x["DefinitionName"] < y["DefinitionName"]
end)
for k, v in ipairs(ds) do
s = s .. [[<ContactDetail>]] ..
datum_to_string(v) .. [[</ContactDetail>]]
end
return s
end
function entry_to_string (e)
local s = [[<Contact>]]
s = s .. details_to_string(e)
s = s .. [[</Contact>]]
return s
end
|
meta.name = "Inventory Example"
meta.version = "0.1"
meta.description = "Examples for using player inventory."
meta.author = "jeremyhay"
local names = {}
for i,v in pairs(ENT_TYPE) do
names[v] = i
end
-- display the items and the powerups in the player's inventory
set_callback(function(draw_ctx)
if players and players[1] then
x, y, l = get_position(players[1].uid)
-- you may want to mask only the items and logical (powerups)
-- here so you don't get any unwanted FX
-- note that ITEM_WHIP shows up while you are whipping
local ANY_ITEM = 0
local items = entity_get_items_by(players[1].uid, ANY_ITEM, MASK.ITEM | MASK.LOGICAL)
local str = ""
for i, uid in ipairs(items) do
local entity = get_entity(uid)
local type = get_type(entity.type.id)
str = str .. " " .. names[entity.type.id]
end
sx, sy = screen_position(x, y-1)
draw_ctx:draw_text(sx, sy, 0, str, rgba(255, 255, 255, 255))
end
end, ON.GUIFRAME)
-- Auto drop broken arrows
set_callback(function(draw_ctx)
if players and players[1] then
local items = entity_get_items_by(players[1].uid, ENT_TYPE.ITEM_BROKEN_ARROW, 0)
if (#items > 0) then
for i, uid in ipairs(items) do
entity_remove_item(players[1].uid, uid)
end
end
end
end, ON.GAMEFRAME)
|
require "tests/testsuite"
Cmd.InsertStringIntoParagraph("The quick brown fox jumps")
Cmd.SplitCurrentParagraph()
Cmd.ChangeParagraphStyle("RAW")
Cmd.InsertStringIntoParagraph("over the lazy")
Cmd.SplitCurrentParagraph()
Cmd.ChangeParagraphStyle("P")
Cmd.InsertStringIntoParagraph("dog.")
Cmd.GotoBeginningOfDocument()
Cmd.GotoNextCharW()
Cmd.SetMark()
Cmd.GotoEndOfDocument()
Cmd.GotoPreviousCharW()
Cmd.Copy()
Cmd.UnsetMark()
AssertEquals(3, #DocumentSet.clipboard)
local filename = os.tmpname()
AssertEquals(Cmd.SaveCurrentDocumentAs(filename), true)
AssertEquals(Cmd.LoadDocumentSet(filename), true)
AssertEquals(3, #DocumentSet.clipboard)
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
-- Provide a time stamp counter suitable for measuring time intervals.
module(...,package.seeall)
local lib = require("core.lib")
local C = require("ffi").C
require("core.lib_h")
default_source = 'rdtsc'
local calibration_interval = 5e8
-- Return the value of the CPU's TSC register
local rdtsc_code
rdtsc = require('dynasm').loadstring [[
local ffi = require('ffi')
local dasm = require('dasm')
|.arch x64
|.actionlist actions
local Dst = dasm.new(actions)
| rdtsc
| shl rdx, 32
| or rax, rdx
| ret
rdtsc_code = Dst:build()
return ffi.cast('uint64_t (*)()', rdtsc_code)
]]()
local cpuinfo = lib.readfile("/proc/cpuinfo", "*a")
assert(cpuinfo, "failed to read /proc/cpuinfo for tsc check")
local have_usable_rdtsc = (cpuinfo:match("constant_tsc") and
cpuinfo:match("nonstop_tsc"))
local time_sources = {
rdtsc = {
time_fn = rdtsc,
calibrate_fn = function ()
local start_ns = C.get_time_ns()
local start_ticks = rdtsc()
for _ = 1, calibration_interval do end
local end_ticks = rdtsc()
local end_ns = C.get_time_ns()
return tonumber(end_ticks - start_ticks)/tonumber(end_ns - start_ns)
* 1000000000 + 0ULL
end
},
system = {
time_fn = C.get_time_ns,
calibrate_fn = function ()
return 1000000000ULL
end
}
}
local tsc = {}
function new (arg)
local config = lib.parse(arg, { source = { default = default_source } })
local o = {}
if config.source == 'rdtsc' and not have_usable_rdtsc then
print("tsc: rdtsc is unusable on this system, "
.. "falling back to system time source")
config.source = 'system'
end
o._source = config.source
local source = assert(time_sources[o._source],
"tsc: unknown time source '" .. o._source .."'")
o._time_fn = source.time_fn
-- Ticks per second (uint64)
o._tps = source.calibrate_fn()
-- Nanoseconds per tick (Lua number)
o._nspt = 1/tonumber(o._tps) * 1000000000
return setmetatable( o, { __index = tsc })
end
function tsc:source ()
return self._source
end
function tsc:time_fn ()
return self._time_fn
end
function tsc:stamp ()
return self._time_fn()
end
function tsc:tps ()
return self._tps
end
function tsc:to_ns (ticks)
if self._source == 'system' then
return ticks
else
return tonumber(ticks) * self._nspt + 0ULL
end
end
function selftest()
local function check(tsc)
for _ = 1, 10 do
local start_ns = C.get_time_ns()
local start_tsc = tsc:stamp()
for _ = 1, calibration_interval do end
local end_ns = C.get_time_ns()
local end_tsc = tsc:stamp()
local diff_ns = tonumber(end_ns - start_ns)
local diff_tsc = tonumber(tsc:to_ns(end_tsc) - tsc:to_ns(start_tsc))
local diff = diff_ns - diff_tsc
assert(math.abs(diff/diff_ns) < 1e-3, tsc:source())
end
end
check(new({ source = 'rdtsc' }))
check(new({ source = 'system' }))
end
|
--=========== Copyright © 2020, Planimeter, All rights reserved. ===========--
--
-- Purpose:
--
--==========================================================================--
--[[
* Copyright (c) 2006-2018 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
]]
local GL = require( "opengl" )
local ffi = require( "ffi" )
local jit = jit
local print = print
local require = require
local type = type
local framework = framework
_G.love = framework
local function notimplemented( key, level )
level = level or 2
local ar = debug.getinfo( level, "Sl" ) --[[ get info about it ]]
local ret = nil
if ( ar.currentline > 0 ) then --[[ is there info? ]]
ret = string.format( "%s: %s:%d: " ..
"attempt to index nil value '%s' " ..
"(not implemented)", arg[ -1 ],
ar.short_src, ar.currentline, key )
end
print( debug.traceback( ret, level ) )
end
local function love_audio()
module( "love.audio" )
return _M
end
local function love_filesystem()
module( "love.filesystem" )
function getRequirePath()
return "./?.lua;lua/?.lua;lua/?/init.lua;"
end
function setIdentity()
notimplemented( "setIdentity", 3 )
end
function getInfo( filename )
if ( not framework.filesystem.exists( filename ) ) then
return nil
end
return {
modtime = 0
}
end
return _M
end
local function love_graphics()
require( "framework.graphics" )
local unpack = unpack
local select = select
require( "framework.graphics.framebuffer" )
local _R = debug.getregistry()
_R.Canvas = framework.graphics.framebuffer
module( "love.graphics" )
_blendMode = _blendMode or "alpha"
_alphaMode = _alphaMode or "alphamultiply"
function getBlendMode()
return _blendMode, _alphaMode
end
getCanvas = framework.graphics.getFramebuffer
_getColor = _getColor or framework.graphics.getColor
function getColor()
return unpack( _getColor() )
end
function getDPIScale()
return 1
end
function getWidth()
return select( 1, framework.graphics.getSize() )
end
function getHeight()
return select( 2, framework.graphics.getSize() )
end
function newCanvas( width, height )
return framework.graphics.newFramebuffer( "color", width, height )
end
function printf( ... )
framework.graphics.print( ... )
notimplemented( "printf", 3 )
end
_setBackgroundColor = _setBackgroundColor or framework.graphics.setBackgroundColor
function setBackgroundColor( r, g, b, a )
if ( type( r ) ~= "table" ) then
_setBackgroundColor( { r, g, b, a } )
return
end
_setBackgroundColor( r )
end
function setBlendMode( mode, alphamode )
alphamode = alphamode or "alphamultiply"
local func = GL.GL_FUNC_ADD
local srcRGB = GL.GL_ONE
local srcA = GL.GL_ONE
local dstRGB = GL.GL_ZERO
local dstA = GL.GL_ZERO
if ( mode == "alpha" ) then
srcRGB = GL.GL_ONE
srcA = GL.GL_ONE
dstRGB = GL.GL_ONE_MINUS_SRC_ALPHA
dstA = GL.GL_ONE_MINUS_SRC_ALPHA
elseif ( mode == "multiply" ) then
srcRGB = GL.GL_DST_COLOR
srcA = GL.GL_DST_COLOR
dstRGB = GL.GL_ZERO
dstA = GL.GL_ZERO
elseif ( mode == "subtract" ) then
func = GL.GL_FUNC_REVERSE_SUBTRACT
elseif( mode == "add" ) then
srcRGB = GL.GL_ONE
srcA = GL.GL_ZERO
dstRGB = GL.GL_ONE
dstA = GL.GL_ONE
elseif ( mode == "lighten" ) then
func = GL.GL_MAX
elseif ( mode == "darken" ) then
func = GL.GL_MIN
elseif ( mode == "screen" ) then
srcRGB = GL.GL_ONE
srcA = GL.GL_ONE
dstRGB = GL.GL_ONE_MINUS_SRC_COLOR
dstA = GL.GL_ONE_MINUS_SRC_COLOR
-- elseif ( mode == "replace" or mode == "none" ) then
else
srcRGB = GL.GL_ONE
srcA = GL.GL_ONE
dstRGB = GL.GL_ZERO
dstA = GL.GL_ZERO
end
-- We can only do alpha-multiplication when srcRGB would have been unmodified.
if (srcRGB == GL.GL_ONE and alphamode == "alphamultiply" and mode ~= "none" ) then
srcRGB = GL.GL_SRC_ALPHA
end
GL.glBlendEquation( func )
GL.glBlendFuncSeparate( srcRGB, dstRGB, srcA, dstA )
_blendMode = mode
_alphaMode = alphamode
end
_setColor = _setColor or framework.graphics.setColor
function setColor( r, g, b, a )
if ( type( r ) ~= "table" ) then
_setColor( { r, g, b, a } )
return
end
_setColor( r )
end
function setDefaultFilter( min, mag, anisotropy )
notimplemented( "setDefaultFilter", 3 )
end
function setCanvas( canvas )
if ( canvas and canvas.stencil ) then
framework.graphics.setFramebuffer( canvas[ 1 ] )
else
framework.graphics.setFramebuffer( canvas )
end
end
function setStencilTest()
notimplemented( "setStencilTest", 3 )
end
function stencil()
notimplemented( "stencil", 3 )
end
return _M
end
local function love_image()
require( "framework.graphics.image" )
module( "love.image" )
local image = framework.graphics.image
return _M
end
local function love_keyboard()
require( "framework.keyboard" )
module( "love.keyboard" )
isDown = framework.keyboard.isPressed
return _M
end
local function love_mouse()
module( "love.mouse" )
return _M
end
local function love_physics()
require( "framework.physics" )
module( "love.physics" )
newWorld = framework.physics.newSpace
return _M
end
local function love_system()
module( "love.system" )
function getOS()
if ( jit.os == "OSX" ) then
return "OS X"
elseif ( jit.os == "Other" ) then
return "Unknown"
else
return jit.os
end
end
return _M
end
local function love_timer()
require( "framework.timer" )
module( "love.timer" )
getTime = framework.timer.getTime
return _M
end
local function love_window()
module( "love.window" )
function getDPIScale()
return 1
end
function getFullscreenModes()
notimplemented( "getFullscreenModes", 3 )
return {
{ width = 800, height = 600 }
}
end
function setMode()
notimplemented( "setMode", 3 )
end
return _M
end
-- From https://bitbucket.org/rude/love/src/8c6f6a0ca1f0d880c6aa73aaeff0bc510370f737/src/modules/love/love.cpp#lines-147
local modules = {
[ "love.audio" ] = love_audio,
[ "love.filesystem" ] = love_filesystem,
[ "love.graphics" ] = love_graphics,
[ "love.image" ] = love_image,
[ "love.keyboard" ] = love_keyboard,
[ "love.mouse" ] = love_mouse,
[ "love.physics" ] = love_physics,
[ "love.system" ] = love_system,
[ "love.timer" ] = love_timer,
[ "love.window" ] = love_window
}
-- Preload module loaders.
for name, func in pairs( modules ) do
package.preload[ name ] = func()
end
function love.createhandlers()
-- Standard callback handlers.
love.handlers = setmetatable({
keypressed = function (b,s,r)
if love.keypressed then return love.keypressed(b,s,r) end
end,
keyreleased = function (b,s)
if love.keyreleased then return love.keyreleased(b,s) end
end,
textinput = function (t)
if love.textinput then return love.textinput(t) end
end,
textedited = function (t,s,l)
if love.textedited then return love.textedited(t,s,l) end
end,
mousemoved = function (x,y,dx,dy,t)
if love.mousemoved then return love.mousemoved(x,y,dx,dy,t) end
end,
mousepressed = function (x,y,b,t,c)
if love.mousepressed then return love.mousepressed(x,y,b,t,c) end
end,
mousereleased = function (x,y,b,t,c)
if love.mousereleased then return love.mousereleased(x,y,b,t,c) end
end,
wheelmoved = function (x,y)
if love.wheelmoved then return love.wheelmoved(x,y) end
end,
touchpressed = function (id,x,y,dx,dy,p)
if love.touchpressed then return love.touchpressed(id,x,y,dx,dy,p) end
end,
touchreleased = function (id,x,y,dx,dy,p)
if love.touchreleased then return love.touchreleased(id,x,y,dx,dy,p) end
end,
touchmoved = function (id,x,y,dx,dy,p)
if love.touchmoved then return love.touchmoved(id,x,y,dx,dy,p) end
end,
joystickpressed = function (j,b)
if love.joystickpressed then return love.joystickpressed(j,b) end
end,
joystickreleased = function (j,b)
if love.joystickreleased then return love.joystickreleased(j,b) end
end,
joystickaxis = function (j,a,v)
if love.joystickaxis then return love.joystickaxis(j,a,v) end
end,
joystickhat = function (j,h,v)
if love.joystickhat then return love.joystickhat(j,h,v) end
end,
gamepadpressed = function (j,b)
if love.gamepadpressed then return love.gamepadpressed(j,b) end
end,
gamepadreleased = function (j,b)
if love.gamepadreleased then return love.gamepadreleased(j,b) end
end,
gamepadaxis = function (j,a,v)
if love.gamepadaxis then return love.gamepadaxis(j,a,v) end
end,
joystickadded = function (j)
if love.joystickadded then return love.joystickadded(j) end
end,
joystickremoved = function (j)
if love.joystickremoved then return love.joystickremoved(j) end
end,
focus = function (f)
if love.focus then return love.focus(f) end
end,
mousefocus = function (f)
if love.mousefocus then return love.mousefocus(f) end
end,
visible = function (v)
if love.visible then return love.visible(v) end
end,
quit = function ()
return
end,
threaderror = function (t, err)
if love.threaderror then return love.threaderror(t, err) end
end,
resize = function (w, h)
if love.resize then return love.resize(w, h) end
end,
filedropped = function (f)
if love.filedropped then return love.filedropped(f) end
end,
directorydropped = function (dir)
if love.directorydropped then return love.directorydropped(dir) end
end,
lowmemory = function ()
if love.lowmemory then love.lowmemory() end
collectgarbage()
collectgarbage()
end,
}, {
__index = function(self, name)
error("Unknown event: " .. name)
end,
})
end
love.createhandlers()
|
-- Change the preferences of a unit.
--@ module = true
local help = [====[
assign-preferences
==================
A script to change the preferences of a unit.
Preferences are classified into 12 types. The first 9 are:
* like material;
* like creature;
* like food;
* hate creature;
* like item;
* like plant;
* like tree;
* like colour;
* like shape.
These can be changed using this script.
The remaining three are not currently managed by this script,
and are: like poetic form, like musical form, like dance form.
To produce the correct description in the "thoughts and preferences"
page, you must specify the particular type of preference. For
each type, a description is provided in the section below.
You will need to know the token of the object you want your dwarf to like.
Unless told otherwise, the best way to get those tokens is to activate
the plugin `stonesense`, load a world and let the plugin generate a file
named "MatList.csv" in the root DF folder. Browse this file (import it
as a .csv file with Excel or similar program) to get the desired token
(in the "id" column). Otherwise, in the folder "/raw/objects/" under
the main DF directory you will find all the raws defined in the game.
For more information:
https://dwarffortresswiki.org/index.php/DF2014:Preferences
Usage:
``-help``:
print the help page.
``-unit <UNIT_ID>``:
set the target unit ID. If not present, the
currently selected unit will be the target.
``-likematerial [ <TOKEN> <TOKEN> <...> ]``:
usually a type of stone, a type of metal and a type
of gem, plus it can also be a type of wood, a type of
glass, a type of leather, a type of horn, a type of
pearl, a type of ivory, a decoration material - coral
or amber, a type of bone, a type of shell, a type
of silk, a type of yarn, or a type of plant cloth.
Write the tokens as found in the "id" column of the
file "MatList.csv", generated as explained above.
There must be a space before and after each square
bracket.
``-likecreature [ <TOKEN> <TOKEN> <...> ]``:
one or more creatures liked by the unit. You can
just list the species: if you are using the file
"MatList.csv" as explained above, the creature token
will be something similar to ``CREATURE:SPARROW:SKIN``,
so the name of the species will be ``SPARROW``. Nothing
will stop you to write the full token, if you want: the
script will just ignore the first and the last parts.
There must be a space before and after each square
bracket.
``-likefood [ <TOKEN> <TOKEN> <...> ]``:
usually a type of alcohol, plus it can be a type of
meat, a type of fish, a type of cheese, a type of edible
plant, a cookable plant/creature extract, a cookable
mill powder, a cookable plant seed or a cookable plant
leaf. Write the tokens as found in the "id" column of
the file "MatList.csv", generated as explained above.
There must be a space before and after each square
bracket.
``-hatecreature [ <TOKEN> <TOKEN> <...> ]``:
works the same way as ``-likecreature``, but this time
it's one or more creatures that the unit detests. They
should be a type of ``HATEABLE`` vermin which isn't already
explicitly liked, but no check is performed about this.
Like before, you can just list the creature species.
There must be a space before and after each square
bracket.
``-likeitem [ <TOKEN> <TOKEN> <...> ]``:
a kind of weapon, a kind of ammo, a kind of piece of
armor, a piece of clothing (including backpacks or
quivers), a type of furniture (doors, floodgates, beds,
chairs, windows, cages, barrels, tables, coffins,
statues, boxes, armor stands, weapon racks, cabinets,
bins, hatch covers, grates, querns, millstones, traction
benches, or slabs), a kind of craft (figurines, amulets,
scepters, crowns, rings, earrings, bracelets, or large
gems), or a kind of miscellaneous item (catapult parts,
ballista parts, a type of siege ammo, a trap component,
coins, anvils, totems, chains, flasks, goblets,
buckets, animal traps, an instrument, a toy, splints,
crutches, or a tool). The item tokens can be found here:
https://dwarffortresswiki.org/index.php/DF2014:Item_token
If you want to specify an item subtype, look into the files
listed under the column "Subtype" of the wiki page (they are
in the "/raw/ojects/" folder), then specify the items using
the full tokens found in those files (see examples below).
There must be a space before and after each square
bracket.
``-likeplant [ <TOKEN> <TOKEN> <...> ]``:
works in a similar way as ``-likecreature``, this time
with plants. You can just List the plant species (the
middle part of the token as listed in "MatList.csv").
There must be a space before and after each square
bracket.
``-liketree [ <TOKEN> <TOKEN> <...> ]``:
works exactly as ``-likeplant``. I think this
preference type is here for backward compatibility (?).
You can still use it, however. As before,
you can just list the tree (plant) species.
There must be a space before and after each square
bracket.
``-likecolor [ <TOKEN> <TOKEN> <...> ]``:
you can find the color tokens here:
https://dwarffortresswiki.org/index.php/DF2014:Color#Color_tokens
or inside the "descriptor_color_standard.txt" file
(in the "/raw/ojects/" folder). You can use the full token or
just the color name.
There must be a space before and after each square
bracket.
``-likeshape [ <TOKEN> <TOKEN> <...> ]``:
I couldn't find a list of shape tokens in the wiki, but you
can find them inside the "descriptor_shape_standard.txt"
file (in the "/raw/ojects/" folder). You can
use the full token or just the shape name.
There must be a space before and after each square
bracket.
``-reset``:
clear all preferences. If the script is called
with both this option and one or more preferences,
first all the unit preferences will be cleared
and then the listed preferences will be added.
Examples:
* "likes alabaster and willow wood"::
assign-preferences -reset -likematerial [ INORGANIC:ALABASTER PLANT:WILLOW:WOOD ]
* "likes sparrows for their ..."::
assign-preferences -reset -likecreature SPARROW
* "prefers to consume dwarven wine and olives"::
assign-preferences -reset -likefood [ PLANT:MUSHROOM_HELMET_PLUMP:DRINK PLANT:OLIVE:FRUIT ]
* "absolutely detests jumping spiders::
assign-preferences -reset -hatecreature SPIDER_JUMPING
* "likes logs and battle axes"::
assign-preferences -reset -likeitem [ WOOD ITEM_WEAPON:ITEM_WEAPON_AXE_BATTLE ]
* "likes straberry plants for their ..."::
assign-preferences -reset -likeplant BERRIES_STRAW
* "likes oaks for their ..."::
assign-preferences -reset -liketree OAK
* "likes the color aqua"::
assign-preferences -reset -likecolor AQUA
* "likes stars"::
assign-preferences -reset -likeshape STAR
]====]
local utils = require("utils")
local valid_args = utils.invert({
'help',
'unit',
'likematerial',
'likecreature',
'likefood',
'hatecreature',
'likeitem',
'likeplant',
'liketree',
'likecolor',
'likeshape',
'reset',
})
-- ----------------------------------------------- UTILITY FUNCTIONS ------------------------------------------------ --
local function print_yellow(text)
dfhack.color(COLOR_YELLOW)
print(text)
dfhack.color(-1)
end
-- initialise random number generator
local rng = dfhack.random.new()
-- ----------------------------------------------- ASSIGN PREFERENCES ----------------------------------------------- --
--[[
This table stores all the information needed to instantiate a new df.unit_preference object.
The keys are the names of the different types of preferences, the values are functions that
return a table with all the fields of a df.unit_preference object and their values.
I find it easier to just overwrite every single field instead of keeping track of the default
values assigned to the field at object creation.
--]]
local preference_functions = {
-- ---------------- LIKEMATERIAL ---------------- --
LIKEMATERIAL = function(token)
local mat_info = dfhack.matinfo.find(token)
local ret = {}
if mat_info then
ret = { --luacheck:retype
type = df.unit_preference.T_type.LikeMaterial,
item_type = -1,
creature_id = -1,
color_id = -1,
shape_id = -1,
plant_id = -1,
poetic_form_id = -1,
musical_form_id = -1,
dance_form_id = -1,
item_subtype = -1,
mattype = mat_info.type,
matindex = mat_info.index,
mat_state = 0,
active = true,
prefstring_seed = rng:random()
}
else
print_yellow("WARNING: '" .. token .. "' does not seem to be a valid material token. Skipping...")
end
return ret
end,
-- ---------------- LIKECREATURE ---------------- --
LIKECREATURE = function(token)
local creature_id
local parts = utils.split_string(token, ":")
if #parts == 1 then
creature_id = parts[1]
else
creature_id = parts[2]
end
local index = utils.linear_index(df.global.world.raws.creatures.all, creature_id, "creature_id")
if index then
return {
type = df.unit_preference.T_type.LikeCreature,
item_type = index,
creature_id = index,
color_id = index,
shape_id = index,
plant_id = index,
poetic_form_id = index,
musical_form_id = index,
dance_form_id = index,
item_subtype = -1,
mattype = -1,
matindex = -1,
mat_state = 0,
active = true,
prefstring_seed = rng:random()
}
else
print_yellow("WARNING: '" .. token .. "' does not seem to be a valid creature token. Skipping...")
return {}
end
end,
-- ---------------- LIKEFOOD ---------------- --
LIKEFOOD = function(token)
local mat_info = dfhack.matinfo.find(token)
if not mat_info then
goto error
end
do
local item_type
local item_subtype = -1
local food_mat_index = mat_info.material.food_mat_index
-- FIXME: is fish missing? Apparently it's considered meat...
-- FIXME: maybe automatize this process instead of using a chain of if-elseif statements?
if food_mat_index.Meat > -1 then
item_type = df.item_type.MEAT
elseif food_mat_index.EdibleCheese > -1 then
item_type = df.item_type.CHEESE
elseif food_mat_index.EdiblePlant > -1 then
item_type = df.item_type.PLANT
elseif food_mat_index.AnyDrink > -1 then
item_type = df.item_type.DRINK
elseif food_mat_index.CookableLiquid > -1 then
item_type = df.item_type.LIQUID_MISC
elseif food_mat_index.CookablePowder > -1 then
item_type = df.item_type.POWDER_MISC
elseif food_mat_index.CookableSeed > -1 then
item_type = df.item_type.SEEDS
elseif food_mat_index.CookableLeaf > -1 then
--[[
In case of plant growths, "mat_info" stores the item type as a specific subtype ("FLOWER", or "FRUIT",
etc.) instead of the generic "PLANT_GROWTH" item type. Also, the IDs of the different types of growths
are sometimes stored in the plural form and sometimes in the singular form, so we need to know what to
look for when we try to associate the item_type to the growth_id.
--]]
local growths = {
-- item_id = growth_id, as returned by dfhack.matinfo.find()
BULB = "BULBS",
FLOWER = "FLOWER",
LEAF = "LEAVES",
NUT = "NUT",
POD = "POD",
FRUIT = "FRUIT",
}
local item_type_str = mat_info.material.id
if growths[item_type_str] then
local growth_id = growths[item_type_str]
for _, growth in ipairs(mat_info.plant.growths) do
if growth_id == growth.id then
item_type = growth.item_type
item_subtype = growth.item_subtype
end
end
end
end
if item_type then
return {
type = df.unit_preference.T_type.LikeFood,
item_type = item_type,
creature_id = item_type,
color_id = item_type,
shape_id = item_type,
plant_id = item_type,
poetic_form_id = item_type,
musical_form_id = item_type,
dance_form_id = item_type,
item_subtype = item_subtype,
mattype = mat_info.type,
matindex = mat_info.index,
mat_state = 1,
active = true,
prefstring_seed = rng:random()
}
end
end
:: error ::
print_yellow("WARNING: '" .. token .. "' does not seem to be a valid food token. Skipping...")
return {}
end,
-- ---------------- HATECREATURE ---------------- --
HATECREATURE = function(token)
local creature_id
local parts = utils.split_string(token, ":")
if #parts == 1 then
creature_id = parts[1]
else
creature_id = parts[2]
end
local index = utils.linear_index(df.global.world.raws.creatures.all, creature_id, "creature_id")
if index then
return {
type = df.unit_preference.T_type.HateCreature,
item_type = index,
creature_id = index,
color_id = index,
shape_id = index,
plant_id = index,
poetic_form_id = index,
musical_form_id = index,
dance_form_id = index,
item_subtype = -1,
mattype = -1,
matindex = -1,
mat_state = 0,
active = true,
prefstring_seed = rng:random()
}
else
print_yellow("WARNING: '" .. token .. "' does not seem to be a valid creature token. Skipping...")
return {}
end
end,
-- ---------------- LIKEITEM ---------------- --
LIKEITEM = function(token)
local item_type
local item_subtype = -1
local parts = utils.split_string(token, ":")
if #parts == 1 then
item_type = df.item_type[parts[1]]
else
-- the token is someting like ITEM_WEAPON:ITEM_WEAPON_AXE_BATTLE
item_type = df.item_type[string.gsub(parts[1], "^ITEM_", "")]
local _, item = utils.linear_index(df.global.world.raws.itemdefs.all, parts[2], "id")
if item then
item_subtype = item.subtype
else
goto error
end
end
do
if item_type then
return {
type = df.unit_preference.T_type.LikeItem,
item_type = item_type,
creature_id = item_type,
color_id = item_type,
shape_id = item_type,
plant_id = item_type,
poetic_form_id = item_type,
musical_form_id = item_type,
dance_form_id = item_type,
item_subtype = item_subtype,
mattype = -1,
matindex = -1,
mat_state = 0,
active = true,
prefstring_seed = rng:random()
}
end
end
:: error ::
print_yellow("WARNING: '" .. token .. "' does not seem to be a valid item token. Skipping...")
return {}
end,
-- ---------------- LIKEPLANT ---------------- --
LIKEPLANT = function(token)
local plant_id
local parts = utils.split_string(token, ":")
if #parts == 1 then
plant_id = parts[1]
else
plant_id = parts[2]
end
local index = utils.linear_index(df.global.world.raws.plants.all, plant_id, "id")
if index then
return {
type = df.unit_preference.T_type.LikePlant,
item_type = index,
creature_id = index,
color_id = index,
shape_id = index,
plant_id = index,
poetic_form_id = index,
musical_form_id = index,
dance_form_id = index,
item_subtype = -1,
mattype = -1,
matindex = -1,
mat_state = 0,
active = true,
prefstring_seed = rng:random()
}
else
print_yellow("WARNING: '" .. token .. "' does not seem to be a valid plant token. Skipping...")
return {}
end
end,
-- ---------------- LIKETREE ---------------- --
LIKETREE = function(token)
local plant_id
local parts = utils.split_string(token, ":")
if #parts == 1 then
plant_id = parts[1]
else
plant_id = parts[2]
end
local index = utils.linear_index(df.global.world.raws.plants.all, plant_id, "id")
if index then
return {
type = df.unit_preference.T_type.LikeTree,
item_type = index,
creature_id = index,
color_id = index,
shape_id = index,
plant_id = index,
poetic_form_id = index,
musical_form_id = index,
dance_form_id = index,
item_subtype = -1,
mattype = -1,
matindex = -1,
mat_state = 0,
active = true,
prefstring_seed = rng:random()
}
else
print_yellow("WARNING: '" .. token .. "' does not seem to be a valid plant token. Skipping...")
return {}
end
end,
-- ---------------- LIKECOLOR ---------------- --
LIKECOLOR = function(token)
local color_name
local parts = utils.split_string(token, ":")
if #parts == 1 then
color_name = parts[1]
else
color_name = parts[2]
end
-- f.global.world.raws.descriptors.colors is ordered by id, we can use binary search
local _, found, index = utils.binsearch(df.global.world.raws.descriptors.colors, color_name, "id")
if found then
return {
type = df.unit_preference.T_type.LikeColor,
item_type = index,
creature_id = index,
color_id = index,
shape_id = index,
plant_id = index,
poetic_form_id = index,
musical_form_id = index,
dance_form_id = index,
item_subtype = -1,
mattype = -1,
matindex = -1,
mat_state = 0,
active = true,
prefstring_seed = rng:random()
}
else
print_yellow("WARNING: '" .. token .. "' does not seem to be a valid color token. Skipping...")
return {}
end
end,
-- ---------------- LIKESHAPE ---------------- --
LIKESHAPE = function(token)
local shape_name
local parts = utils.split_string(token, ":")
if #parts == 1 then
shape_name = parts[1]
else
shape_name = parts[2]
end
local index, _ = utils.linear_index(df.global.world.raws.descriptors.shapes, shape_name, "id")
if index then
return {
type = df.unit_preference.T_type.LikeShape,
item_type = index,
creature_id = index,
color_id = index,
shape_id = index,
plant_id = index,
poetic_form_id = index,
musical_form_id = index,
dance_form_id = index,
item_subtype = -1,
mattype = -1,
matindex = -1,
mat_state = 0,
active = true,
prefstring_seed = rng:random()
}
else
print_yellow("WARNING: '" .. token .. "' does not seem to be a valid shape token. Skipping...")
return {}
end
end,
}
--- Assign the given preferences to a unit, clearing all the other preferences if requested.
--- :preferences: nil, or a table. The fields have the preference type as key and an array of preference tokens
--- as value. If the token is just one, the field can be in a simple key=value format.
--- :unit: a valid unit id, a df.unit object, or nil. If nil, the currently selected unit will be targeted.
--- :reset: boolean, or nil.
function assign(preferences, unit, reset)
assert(not preferences or type(preferences) == "table")
assert(not unit or type(unit) == "number" or df.unit:is_instance(unit))
assert(not reset or type(reset) == "boolean")
local preferences = preferences or {} --as:string[][]
reset = reset or false
if type(unit) == "number" then
unit = df.unit.find(tonumber(unit)) --luacheck:retype
end
unit = unit or dfhack.gui.getSelectedUnit(true)
if not unit then
qerror("No unit found.")
end
-- clear preferences
if reset then
unit.status.current_soul.preferences = {}
end
-- assign preferences
local unit_preferences = unit.status.current_soul.preferences -- store the userdata in a variable for convenience
for preference_type, preference_tokens in pairs(preferences) do
assert(type(preference_tokens) == "table" or type(preference_tokens) == "string")
local funct = preference_functions[preference_type:upper()]
if type(preference_tokens) == "string" then --luacheck:skip
preference_tokens = {preference_tokens}
end
for _, token in ipairs(preference_tokens) do
assert(type(token) == "string")
local new_preference = df.unit_preference:new()
local values = funct(token:upper())
for field, value in pairs(values) do
if value then
new_preference[field] = value
else
print_yellow("WARNING: unable to calculate a value for field '" .. field .. "'. Skipping...")
goto next_preference
end
end
-- TODO: should we insert preferences following the order in which DF presents them?
unit_preferences:insert(#unit_preferences, new_preference)
end
:: next_preference ::
end
end
-- ------------------------------------------------------ MAIN ------------------------------------------------------ --
local function main(...)
local args = utils.processArgs({ ... }, valid_args)
if args.help then
print(help)
return
end
local unit
if args.unit then
unit = tonumber(args.unit)
if not unit then
qerror("'" .. args.unit .. "' is not a valid unit ID.")
end
end
local reset = false
if args.reset then
reset = true
end
-- parse preferences
args.unit = nil -- remove from args table
args.reset = nil -- remove from args table
local preferences = {}
utils.assign(preferences, args)
assign(preferences, unit, reset)
end
if not dfhack_flags.module then
main(...)
end
|
local exit_query = {
{
name = "no",
label = "No",
kind = "action",
handler = function() end
},
{
name = "yes",
label = "Yes",
description = "This will close external connections, any unsaved data will be lost",
kind = "action",
dangerous = true,
handler = function() shutdown(); end
},
{
name = "silent",
label = "Silent",
description = "Shutdown, but don't tell external connections to terminate",
kind = "action",
dangerous = true,
handler = function()
gconfig_mask_temp(true);
shutdown("", EXIT_SILENT);
end
}
};
-- Lockscreen States:
-- [Idle-setup] -(idle_wakeup)-> [lock_query] -> (cancel: Idle-setup,
-- ok/verify: Idle-restore, ok/fail: Idle-setup)
local ef = function() end;
local idle_wakeup = ef;
local idle_setup = function(val, failed)
if (failed > 0) then
local fp = gconfig_get("lock_fail_" .. tostring(failed));
if (fp) then
dispatch_symbol(fp);
end
end
active_display():set_input_lock(ef, "idle");
timer_add_idle("idle_wakeup", 10, true, ef, function()
idle_wakeup(val, failed);
end);
end
local function idle_restore()
durden_input_sethandler()
for d in all_tilers_iter() do
show_image(d.anchor);
end
active_display():set_input_lock();
end
idle_wakeup = function(key, failed)
local bar = active_display():lbar(
function(ctx, msg, done, lastset)
if (not done) then
return true;
end
-- accept, note that this comparison is early-out timing side channel
-- sensitive, but for the threat model here it does not really matter
if (msg == key) then
idle_restore();
if (gconfig_get("lock_ok")) then
dispatch_symbol(gconfig_get("lock_ok"));
end
else
idle_setup(key, failed + 1);
end
iostatem_restore();
end,
{}, {label = string.format(
failed > 0 and
"Enter Unlock Key (%d Failed Attempts):" or
"Enter Unlock Key:", failed),
password_mask = gconfig_get("passmask")
}
);
bar.on_cancel = function()
idle_setup(key, failed);
end
end
local function lock_value(ctx, val)
-- don't go through the normal input lock as events could then
-- still be forwarded to the selected window, input should trigger
-- lbar that, on escape, immediately jumps into idle state.
if (not durden_input_sethandler(durden_locked_input, "global/system/lock")) then
return;
end
iostatem_save();
-- this doesn't allow things like a background image / "screensaver"
for d in all_tilers_iter() do
hide_image(d.anchor);
end
local fn = gconfig_get("lock_on");
if (fn) then
dispatch_symbol(fn);
end
idle_setup(val, 0);
end
local function gen_appl_menu()
local res = {};
local tbl = glob_resource("*", SYS_APPL_RESOURCE);
for i,v in ipairs(tbl) do
table.insert(res, {
name = "switch_" .. tostring(i);
label = v,
description = "Change the active set of scripts, data or external clients may be lost",
dangerous = true,
kind = "action",
handler = function()
durden_shutdown();
system_collapse(v);
end,
});
end
return res;
end
local reset_query = {
{
name = "no",
label = "No",
kind = "action",
handler = function() end
},
{
name = "yes",
label = "Yes",
description = "Reset / Reload Durden? Unsaved data may be lost",
kind = "action",
dangerous = true,
handler = function()
durden_shutdown();
system_collapse();
end
},
{
name = "switch",
label = "Switch Appl",
kind = "action",
description = "Change the currently active window management scripts",
submenu = true,
eval = function() return #glob_resource("*", SYS_APPL_RESOURCE) > 0; end,
handler = gen_appl_menu
}
};
local counter = 0;
local system_menu = {
{
name = "shutdown",
label = "Shutdown",
kind = "action",
submenu = true,
description = "Perform a clean shutdown",
handler = exit_query
},
{
name = "reset",
label = "Reset",
kind = "action",
submenu = true,
description = "Rebuild the WM state machine",
handler = reset_query
},
{
name = "status_msg",
label = "Status-Message",
kind = "value",
invisible = true,
description = "Add a custom string to the statusbar message area",
validator = function(val) return true; end,
handler = function(ctx, val)
active_display():message(val and val or "");
end
},
{
name = "debug",
label = "Debug",
kind = "action",
eval = function() return DEBUGLEVEL > 0; end,
submenu = true,
handler = system_load("menus/global/debug.lua")(),
},
{
name = "lock",
label = "Lock",
kind = "value",
description = "Query for a temporary unlock key and then lock the display",
dangerous = true,
password_mask = gconfig_get("passmask"),
hint = "(unlock key)",
validator = function(val) return string.len(val) > 0; end,
handler = lock_value
}
};
return system_menu;
|
--!strict
--[[
Defers and orders UI data binding updates.
]]
local RunService = game:GetService("RunService")
local Package = script.Parent.Parent
local None = require(Package.Utility.None)
type Set<T> = {[T]: any}
local Scheduler = {}
local willUpdate = false
local propertyChanges: {[Instance]: {[string]: any}} = {}
local callbacks: Set<() -> ()> = {}
--[[
Enqueues an instance property to be updated next render step.
]]
function Scheduler.enqueueProperty(instance: Instance, propertyName: string, newValue: any)
willUpdate = true
-- we can't iterate over nil values of tables, so use a symbol instead
if newValue == nil then
newValue = None
end
local propertyTable = propertyChanges[instance]
if propertyTable == nil then
propertyChanges[instance] = {
[propertyName] = newValue
}
else
propertyTable[propertyName] = newValue
end
end
--[[
Enqueues a callback to be run next render step.
]]
function Scheduler.enqueueCallback(callback: () -> ())
willUpdate = true
callbacks[callback] = true
end
--[[
Executes all enqueued tasks, and clears out the task lists ready for new
tasks.
]]
function Scheduler.runTasks()
-- if no tasks were enqueued, exit early
if not willUpdate then
return
end
-- execute property changes
for instance, propertyTable in pairs(propertyChanges) do
for property, value in pairs(propertyTable) do
if value == None then
value = nil
end
-- FIXME: Typed Luau doesn't understand this yet
(instance :: any)[property] = value
end
end
-- run deferred callbacks
for callback in pairs(callbacks) do
callback()
end
willUpdate = false
table.clear(propertyChanges)
table.clear(callbacks)
end
RunService:BindToRenderStep(
"__FusionUIScheduler",
Enum.RenderPriority.Last.Value,
Scheduler.runTasks
)
return Scheduler
|
-- DFL - Data Flow Language in final tagless style
--
-- Context is pure event-driven data flow systen design, with
-- simulation in lua + compilation to C with static metadata.
local dfl = {
-- semantics objects
eval = {},
comp = {},
}
-- A choice is made to stick to lua semantics and make all function
-- variadic. Going against that will introduce a lot of red tape.
-- The only downside seems to be that, when compiling a function, the
-- arity needs to be specified.
function dfl.compile(syntax, arity)
-- Initialize compilation context
local comp = {
next_node = 1,
nodes = {},
inputs = {},
arity = arity,
}
setmetatable(comp, { __index = dfl.comp })
-- Create input nodes.
for i=1,arity do
table.insert(comp.inputs, comp:node())
end
-- Invoke higher order abstract syntax object to produce
-- intermediate nodes as a side effect, and return a list of output
-- nodes.
function pack(...) return {...} end
comp.output = pack(syntax(comp, unpack(comp.inputs)))
return comp
end
function dfl.comp:node(opcode, operands)
if not opcode then opcode = "input" end
if not operands then operands = {} end
local node = { opcode = opcode, operands = operands }
local ref = self.next_node
self.nodes[ref] = node
self.next_node = ref + 1
return ref
end
-- It's convenient to define compile and eval semantics at the same
-- time, by reusing function names for compile time semantics.
local f = {}
function f.add(a,b) return a+b end
function f.sub(a,b) return a-b end
function f.mul(a,b) return a*b end
function f.div(a,b) return a/b end
-- Create semantics functions for eval and comp semantics from this table.
for name, func in pairs(f) do
dfl.eval[name] = function(self, ...)
-- Evaluation applies the function to the arguments directly.
return func(...)
end
dfl.comp[name] = function(self, ...)
-- Compilation creates a new node that represents the function's
-- target language code.
return self:node(name, {...})
end
end
-- C code gen assumes a context object. This will likely be necessary
-- later, and avoids issues with comma generation here.
function dfl.print(dag, fun_name)
local out = {}
local t = "int"
local tab = " "
local ctx = "_"
local function w(str) table.insert(out, str) end
w(t); w(" "); w(fun_name); w("(void*"); w(ctx)
for i,input in ipairs(dag.inputs) do
w(", "); w(t); w(" "); w("r"); w(input);
end
w(") {\n")
for i, n in ipairs(dag.nodes) do
if n.opcode ~= "input" then
w(tab); w(t); w(" r"); w(i); w(" = "); w(n.opcode);
w("("); w(ctx);
for j,operand in ipairs(n.operands) do
w(", r"); w(operand);
end
w(")\n")
end
end
w(tab); w("return r"); w(dag.output[1]); w(";\n")
w("}\n")
return table.concat(out)
end
return dfl
|
local function genCode(handler)
local settings = handler.project:GetSettings("Publish").codeGeneration
local codePkgName = handler:ToFilename(handler.pkg.name); --convert chinese to pinyin, remove special chars etc.
local exportCodePath = handler.exportCodePath..'/'..codePkgName
local namespaceName = codePkgName
local binderName = codePkgName..'Binder'
if settings.packageName~=nil and settings.packageName~='' then
namespaceName = settings.packageName..'.'..namespaceName;
end
--CollectClasses(stripeMemeber, stripeClass, fguiNamespace)
local classes = handler:CollectClasses(settings.ignoreNoname, settings.ignoreNoname, nil)
handler:SetupCodeFolder(exportCodePath, "cpp,h") --check if target folder exists, and delete old files
local getMemberByName = settings.getMemberByName
local classCnt = classes.Count
local writer = CodeWriter.new()
for i=0,classCnt-1 do
local classInfo = classes[i]
local members = classInfo.members
local references = classInfo.references
writer:reset()
writer:writeln('#ifndef __%s_%s_H__', codePkgName, classInfo.className)
writer:writeln('#define __%s_%s_H__', codePkgName, classInfo.className)
writer:writeln()
writer:writeln('#include "FairyGUI.h"')
writer:writeln()
writer:writeln('namespace %s', namespaceName)
writer:startBlock()
local refCount = references.Count
if refCount>0 then
for j=0,refCount-1 do
local ref = references[j]
writer:writeln('class %s;', ref)
end
end
writer:writeln('class %s : public %s', classInfo.className, classInfo.superClassName)
writer:startBlock()
writer:writeln('public:')
writer:incIndent()
writer:writeln('static const std::string URL;')
writer:writeln('static %s* create();', classInfo.className)
writer:writeln()
local memberCnt = members.Count
for j=0,memberCnt-1 do
local memberInfo = members[j]
writer:writeln('%s* %s;', memberInfo.type, memberInfo.varName)
end
writer:decIndent()
writer:writeln()
writer:writeln('protected:')
writer:incIndent()
writer:writeln('virtual void onConstruct() override;')
writer:decIndent()
writer:writeln()
writer:writeln('private:')
writer:incIndent()
writer:writeln('static %s* createByBinder();', classInfo.className)
writer:writeln('friend class %s;', binderName)
writer:decIndent()
writer:endBlock()
writer:endBlock()
writer:writeln()
writer:writeln('#endif')
writer:save(exportCodePath..'/'..classInfo.className..'.h')
----------------
writer:reset()
writer:writeln('#include "%s.h"', binderName)
writer:writeln()
writer:writeln('namespace %s', namespaceName)
writer:startBlock()
writer:writeln('USING_NS_FGUI;')
writer:writeln()
writer:writeln('const std::string %s::URL = "ui://%s%s";', classInfo.className, handler.pkg.id, classInfo.resId)
writer:writeln()
writer:writeln('%s* %s:create()', classInfo.className, classInfo.className)
writer:startBlock()
writer:writeln('return dynamic_cast<%s*>(UIPackage::createObject("%s", "%s"));', classInfo.className, handler.pkg.name, classInfo.resName)
writer:endBlock()
writer:writeln()
writer:writeln('%s* %s::createByBinder()', classInfo.className, classInfo.className)
writer:startBlock()
writer:writeln('%s *pRet = new(std::nothrow) %s();', classInfo.className, classInfo.className)
writer:writeln('if (pRet && pRet->init())')
writer:startBlock()
writer:writeln('pRet->autorelease();')
writer:writeln('return pRet;')
writer:endBlock()
writer:writeln('else')
writer:startBlock()
writer:writeln('delete pRet;')
writer:writeln('pRet = nullptr;')
writer:writeln('return nullptr;')
writer:endBlock()
writer:endBlock()
writer:writeln()
writer:writeln('void %s::onConstruct()', classInfo.className)
writer:startBlock()
for j=0,memberCnt-1 do
local memberInfo = members[j]
if memberInfo.group==0 then
if getMemberByName then
writer:writeln('%s = dynamic_cast<%s*>(getChild("%s"));', memberInfo.varName, memberInfo.type, memberInfo.name)
else
writer:writeln('%s = dynamic_cast<%s*>(getChildAt(%s));', memberInfo.varName, memberInfo.type, memberInfo.index)
end
elseif memberInfo.group==1 then
if getMemberByName then
writer:writeln('%s = getController("%s");', memberInfo.varName, memberInfo.name)
else
writer:writeln('%s = getControllerAt(%s);', memberInfo.varName, memberInfo.index)
end
else
if getMemberByName then
writer:writeln('%s = getTransition("%s");', memberInfo.varName, memberInfo.name)
else
writer:writeln('%s = getTransitionAt(%s);', memberInfo.varName, memberInfo.index)
end
end
end
writer:endBlock()
writer:endBlock()
writer:save(exportCodePath..'/'..classInfo.className..'.cpp')
end
writer:reset()
writer:writeln('#ifndef __%s_%s_H__', codePkgName, binderName)
writer:writeln('#define __%s_%s_H__', codePkgName, binderName)
writer:writeln()
writer:writeln('#include "FairyGUI.h"')
for i=0,classCnt-1 do
local classInfo = classes[i]
writer:writeln('#include "%s.h";', classInfo.className)
end
writer:writeln()
writer:writeln('namespace %s', namespaceName)
writer:startBlock()
writer:writeln('class %s', binderName)
writer:startBlock()
writer:writeln('public:')
writer:incIndent()
writer:writeln('static void bindAll();')
writer:decIndent()
writer:endBlock()
writer:endBlock()
writer:writeln()
writer:writeln('#endif')
writer:save(exportCodePath..'/'..binderName..'.h')
-----------------------------------
writer:reset()
writer:writeln('#include "%s.h"', binderName)
writer:writeln()
writer:writeln('namespace %s', namespaceName)
writer:startBlock()
writer:writeln('USING_NS_FGUI;')
writer:writeln()
writer:writeln('void %s:bindAll()', binderName)
writer:startBlock()
for i=0,classCnt-1 do
local classInfo = classes[i]
writer:writeln('UIObjectFactory::setExtension(%s::URL, std::bind(&%s::createByBinder));', classInfo.className, classInfo.className)
end
writer:endBlock()
writer:endBlock()
writer:save(exportCodePath..'/'..binderName..'.cpp')
end
return genCode
|
package.cpath = "bin/?.dll"
local iup = require "iuplua"
local bgfx = require "bgfx"
local util = require "util"
local math3d = require "math3d"
local settings = {
speed = 0.37,
middleGray = 0.18,
white = 1.1,
threshold = 1.5,
}
local function slider(name, title, min, max)
local value = assert(settings[name])
local label = iup.label { title = tostring(value) }
local function update_value(self)
local v = tonumber(self.value)
settings[name] = v
label.title = string.format("%.2f",v)
end
local s = iup.frame {
iup.hbox {
iup.val {
"HORIZONTAL";
min = min,
max = max,
value = value,
valuechanged_cb = update_value,
},
label
},
title = title,
}
return s
end
local ctx = {
canvas = iup.canvas {},
}
local lumAvgLabel = iup.label { SIZE = "100x" } -- { expand="HORIZONTAL" }
local function update_lumarg()
local v0,v1,v2,v3 = string.unpack("BBBB", settings.lumAvg)
local exponent = v3 - 128
local lumAvg = v2/255 * 2 ^ exponent
lumAvgLabel.title = string.format("lum Avg : %.2f", lumAvg)
end
local ctrl = iup.frame {
iup.vbox {
slider("speed", "Speed", 0, 1),
slider("middleGray", "Middle gray", 0.1, 1),
slider("white", "White point", 0.1, 2),
slider("threshold", "Threshold", 0.1, 2),
lumAvgLabel,
},
title = "Settings",
-- margin = "10x10",
size = "60",
}
local dlg = iup.dialog {
iup.hbox {
iup.vbox {
ctrl,
margin = "10x10",
},
ctx.canvas,
},
title = "09-hdr",
size = "HALFxHALF",
}
local view_order = { 0,1,2,3,4,5,6,7,8,9 }
local function shuffle()
for i=1,9 do
local a = math.random(i, 10)
local b = math.random(i, 10)
view_order[a] , view_order[b] = view_order[b], view_order[a]
end
end
local function screenSpaceQuad(textureWidth, textureHeight, originBottomLeft)
local width = 1
local height = 1
ctx.tvb:alloc(3, ctx.vdecl)
local zz = 0
local minx = -width
local maxx = width
local miny = 0
local maxy = height*2
local texelHalfW = ctx.s_texelHalf/textureWidth
local texelHalfH = ctx.s_texelHalf/textureHeight
local minu = -1 + texelHalfW
local maxu = 1 + texelHalfW
local minv = texelHalfH
local maxv = 2 + texelHalfH
if originBottomLeft then
minv,maxv = maxv, minv
minv = minv - 1
maxv = maxv - 1
end
ctx.tvb(0, minx, miny, zz, 0xffffffff, minu, minv)
ctx.tvb(1, maxx, miny, zz, 0xffffffff, maxu, minv)
ctx.tvb(2, maxx, maxy, zz, 0xffffffff, maxu, maxv)
ctx.tvb:set()
end
local offsets = {}
local function setOffsets2x2Lum(handle, width, height)
local du = 1/width
local dv = 1/height
local num = 0
local h = ctx.s_texelHalf
for yy = 0, 2 do
for xx = 0, 2 do
num = num + 1
offsets[num] = { (xx - h) * du,(yy - h) * dv , 0, 0 }
end
end
bgfx.set_uniform(handle, table.unpack(offsets))
end
local function setOffsets4x4Lum(handle, width, height)
local du = 1/width
local dv = 1/height
local num = 0
local h = ctx.s_texelHalf
for yy = 0, 3 do
for xx = 0, 3 do
num = num + 1
offsets[num] = { (xx - 1 - h) * du,(yy - 1 - h) * dv, 0, 0 }
end
end
bgfx.set_uniform(handle, table.unpack(offsets))
end
local time = 0
local function mainloop()
math3d.reset()
bgfx.touch(0)
time = time + 0.02 * settings.speed
shuffle()
local hdrSkybox, hdrMesh, hdrLuminance, hdrLumScale0, hdrLumScale1,
hdrLumScale2, hdrLumScale3, hdrBrightness, hdrVBlur, hdrHBlurTonemap = table.unpack(view_order)
bgfx.set_view_name(hdrSkybox, "Skybox")
bgfx.set_view_clear(hdrSkybox, "CD", 0x303030ff, 1.0, 0)
bgfx.set_view_rect(hdrSkybox, 0, 0)
bgfx.set_view_frame_buffer(hdrSkybox, ctx.m_fbh)
bgfx.set_view_name(hdrMesh, "Mesh")
bgfx.set_view_clear(hdrMesh, "ds")
bgfx.set_view_rect(hdrMesh, 0, 0)
bgfx.set_view_frame_buffer(hdrMesh, ctx.m_fbh)
bgfx.set_view_name(hdrLuminance, "Luminance")
bgfx.set_view_rect(hdrLuminance, 0, 0, 128, 128)
bgfx.set_view_frame_buffer(hdrLuminance, ctx.m_lum[1])
bgfx.set_view_name(hdrLumScale0, "Downscale luminance 0")
bgfx.set_view_rect(hdrLumScale0, 0, 0, 64, 64)
bgfx.set_view_frame_buffer(hdrLumScale0, ctx.m_lum[2])
bgfx.set_view_name(hdrLumScale1, "Downscale luminance 1")
bgfx.set_view_rect(hdrLumScale1, 0, 0, 16, 16)
bgfx.set_view_frame_buffer(hdrLumScale1, ctx.m_lum[3])
bgfx.set_view_name(hdrLumScale2, "Downscale luminance 2")
bgfx.set_view_rect(hdrLumScale2, 0, 0, 4, 4)
bgfx.set_view_frame_buffer(hdrLumScale2, ctx.m_lum[4])
bgfx.set_view_name(hdrLumScale3, "Downscale luminance 3")
bgfx.set_view_rect(hdrLumScale3, 0, 0, 1, 1)
bgfx.set_view_frame_buffer(hdrLumScale3, ctx.m_lum[5])
bgfx.set_view_name(hdrBrightness, "Brightness")
bgfx.set_view_rect(hdrBrightness, 0, 0, "1/2")
bgfx.set_view_frame_buffer(hdrBrightness, ctx.m_bright)
bgfx.set_view_name(hdrVBlur, "Blur vertical")
bgfx.set_view_rect(hdrVBlur, 0, 0, "1/8")
bgfx.set_view_frame_buffer(hdrVBlur, ctx.m_blur)
bgfx.set_view_name(hdrHBlurTonemap, "Blur horizontal + tonemap")
bgfx.set_view_rect(hdrHBlurTonemap, 0, 0)
bgfx.set_view_frame_buffer(hdrHBlurTonemap) -- bgfx::setViewFrameBuffer(hdrHBlurTonemap, BGFX_INVALID_HANDLE)
bgfx.set_view_order(view_order)
for i=0,#view_order-1 do
bgfx.set_view_transform(i, nil, ctx.ortho)
end
local mtx = math3d.matrix { r = { 0, time, 0 } }
local view = math3d.lookat( math3d.transform(mtx, math3d.vector( 0,1,-2.5) , 1) , { 0,1,0 })
bgfx.set_view_transform(hdrMesh, view, ctx.proj)
-- Render skybox into view hdrSkybox.
bgfx.set_texture(0, ctx.s_texCube, ctx.m_uffizi)
bgfx.set_state(ctx.state)
bgfx.set_uniform(ctx.u_mtx, mtx)
screenSpaceQuad( ctx.width, ctx.height, true)
bgfx.submit(hdrSkybox, ctx.m_skyProgram)
local tonemap = math3d.vector ( settings.middleGray, settings.white ^ 2, settings.threshold, time )
local originBottomLeft = util.caps.originBottomLeft
-- Render m_mesh into view hdrMesh.
bgfx.set_texture(0, ctx.s_texCube, ctx.m_uffizi)
bgfx.set_uniform(ctx.u_tonemap, tonemap)
bgfx.set_state(ctx.mesh_state)
util.meshSubmit(ctx.m_mesh, hdrMesh, ctx.m_meshProgram)
-- Calculate luminance.
setOffsets2x2Lum(ctx.u_offset, 128, 128)
bgfx.set_texture(0, ctx.s_texColor, ctx.m_fbtextures[1])
bgfx.set_state(ctx.state)
screenSpaceQuad(128.0, 128.0, originBottomLeft)
bgfx.submit(hdrLuminance, ctx.m_lumProgram)
-- Downscale luminance 0.
setOffsets4x4Lum(ctx.u_offset, 128, 128)
bgfx.set_texture(0, ctx.s_texColor, bgfx.get_texture(ctx.m_lum[1]))
bgfx.set_state(ctx.state)
screenSpaceQuad(64.0, 64.0, originBottomLeft)
bgfx.submit(hdrLumScale0, ctx.m_lumAvgProgram)
-- Downscale luminance 1.
setOffsets4x4Lum(ctx.u_offset, 64, 64)
bgfx.set_texture(0, ctx.s_texColor, bgfx.get_texture(ctx.m_lum[2]))
bgfx.set_state(ctx.state)
screenSpaceQuad(16, 16, originBottomLeft)
bgfx.submit(hdrLumScale1, ctx.m_lumAvgProgram)
-- Downscale luminance 2.
setOffsets4x4Lum(ctx.u_offset, 16, 16)
bgfx.set_texture(0, ctx.s_texColor, bgfx.get_texture(ctx.m_lum[3]))
bgfx.set_state(ctx.state)
screenSpaceQuad(4, 4, originBottomLeft)
bgfx.submit(hdrLumScale2, ctx.m_lumAvgProgram)
-- Downscale luminance 3.
setOffsets4x4Lum(ctx.u_offset, 4, 4)
bgfx.set_texture(0, ctx.s_texColor, bgfx.get_texture(ctx.m_lum[4]))
bgfx.set_state(ctx.state)
screenSpaceQuad(1, 1, originBottomLeft)
bgfx.submit(hdrLumScale3, ctx.m_lumAvgProgram)
-- m_bright pass m_threshold is tonemap[3].
setOffsets4x4Lum(ctx.u_offset, ctx.width/2, ctx.height/2)
bgfx.set_texture(0, ctx.s_texColor, ctx.m_fbtextures[1])
bgfx.set_texture(1, ctx.s_texLum, bgfx.get_texture(ctx.m_lum[5]))
bgfx.set_state(ctx.state)
bgfx.set_uniform(ctx.u_tonemap, tonemap)
screenSpaceQuad( ctx.width/2, ctx.height/2, originBottomLeft)
bgfx.submit(hdrBrightness, ctx.m_brightProgram)
-- m_blur m_bright pass vertically.
bgfx.set_texture(0, ctx.s_texColor, bgfx.get_texture(ctx.m_bright))
bgfx.set_state(ctx.state)
bgfx.set_uniform(ctx.u_tonemap, tonemap)
screenSpaceQuad(ctx.width/8, ctx.height/8, originBottomLeft)
bgfx.submit(hdrVBlur, ctx.m_blurProgram)
-- m_blur m_bright pass horizontally, do tonemaping and combine.
bgfx.set_texture(0, ctx.s_texColor, ctx.m_fbtextures[1])
bgfx.set_texture(1, ctx.s_texLum, bgfx.get_texture(ctx.m_lum[5]) )
bgfx.set_texture(2, ctx.s_texBlur, bgfx.get_texture(ctx.m_blur) )
bgfx.set_state(ctx.state)
screenSpaceQuad( ctx.width, ctx.height, originBottomLeft)
bgfx.submit(hdrHBlurTonemap, ctx.m_tonemapProgram)
if ctx.m_rb then
bgfx.blit(hdrHBlurTonemap, ctx.m_rb, 0, 0, bgfx.get_texture(ctx.m_lum[5]) )
bgfx.read_texture(ctx.m_rb, ctx.lumAvg_data)
settings.lumAvg = tostring(ctx.lumAvg_data)
update_lumarg()
end
bgfx.frame()
end
function ctx.init()
ctx.vdecl = bgfx.vertex_layout {
{ "POSITION", 3, "FLOAT" },
{ "COLOR0", 4, "UINT8", true },
{ "TEXCOORD0", 2, "FLOAT" },
}
ctx.tvb = bgfx.transient_buffer "fffdff"
ctx.state = bgfx.make_state {
WRITE_MASK = "RGBA",
MSAA = false,
}
ctx.mesh_state = bgfx.make_state {
WRITE_MASK = "RGBAZ",
DEPTH_TEST = "LESS",
CULL = "CCW",
MSAA = true,
}
ctx.m_uffizi = util.textureLoad("textures/uffizi.dds", 0, "ucvcwc") -- BGFX_TEXTURE_U_CLAMP | BGFX_TEXTURE_V_CLAMP | BGFX_TEXTURE_W_CLAMP
ctx.m_skyProgram = util.programLoad("vs_hdr_skybox", "fs_hdr_skybox")
ctx.m_lumProgram = util.programLoad("vs_hdr_lum", "fs_hdr_lum")
ctx.m_lumAvgProgram = util.programLoad("vs_hdr_lumavg", "fs_hdr_lumavg")
ctx.m_blurProgram = util.programLoad("vs_hdr_blur", "fs_hdr_blur")
ctx.m_brightProgram = util.programLoad("vs_hdr_bright", "fs_hdr_bright")
ctx.m_meshProgram = util.programLoad("vs_hdr_mesh", "fs_hdr_mesh")
ctx.m_tonemapProgram = util.programLoad("vs_hdr_tonemap", "fs_hdr_tonemap")
ctx.s_texCube = bgfx.create_uniform("s_texCube", "s")
ctx.s_texColor = bgfx.create_uniform("s_texColor", "s")
ctx.s_texLum = bgfx.create_uniform("s_texLum", "s")
ctx.s_texBlur = bgfx.create_uniform("s_texBlur", "s")
ctx.u_mtx = bgfx.create_uniform("u_mtx", "m4")
ctx.u_tonemap = bgfx.create_uniform("u_tonemap", "v4")
ctx.u_offset = bgfx.create_uniform("u_offset", "v4", 16)
ctx.m_mesh = util.meshLoad "meshes/bunny.bin"
ctx.m_fbh = nil -- frame buffer
ctx.s_texelHalf = util.caps.rendererType == "DIRECT3D9" and 0.5 or 0
ctx.m_lum = {
bgfx.create_frame_buffer(128, 128, "BGRA8"),
bgfx.create_frame_buffer(64, 64, "BGRA8"),
bgfx.create_frame_buffer(16, 16, "BGRA8"),
bgfx.create_frame_buffer(4, 4, "BGRA8"),
bgfx.create_frame_buffer(1, 1, "BGRA8"),
}
ctx.m_bright = bgfx.create_frame_buffer("1/2", "BGRA8")
ctx.m_blur = bgfx.create_frame_buffer("1/8", "BGRA8")
if util.caps.supported.TEXTURE_BLIT and util.caps.supported.TEXTURE_READ_BACK then
ctx.m_rb = bgfx.create_texture2d(1, 1, false, 1, "BGRA8", "br") -- BGFX_TEXTURE_READ_BACK
end
ctx.ortho = math3d.ref(math3d.projmat { ortho = true, l = 0, r= 1, b = 1, t = 0, n = 100, f = 0 } )
ctx.m_fbtextures = {}
ctx.lumAvg_data = bgfx.memory_texture(4)
end
function ctx.resize(w,h)
ctx.width = w
ctx.height = h
bgfx.reset(w,h, "v")
bgfx.destroy(ctx.m_fbh)
local fbtextures = ctx.m_fbtextures
fbtextures[1] = bgfx.create_texture2d(ctx.width, ctx.height,false, 1, "BGRA8", "rtucvc") -- BGFX_TEXTURE_RT | BGFX_TEXTURE_U_CLAMP | BGFX_TEXTURE_V_CLAMP
local textureFlags = "rwrt"
local depthFormat = bgfx.is_texture_valid(0, false, 1, "D16", textureFlags) and "D16" or
(bgfx.is_texture_valid(0, false, 1, "D24S8", textureFlags) and "D24S8" or "D32")
fbtextures[2] = bgfx.create_texture2d(ctx.width, ctx.height, false, 1, depthFormat, textureFlags)
ctx.m_fbh = bgfx.create_frame_buffer(fbtextures, true)
ctx.proj = math3d.ref (math3d.projmat { fov = 60, aspect = w/h , n = 0.1, f = 100 })
end
util.init(ctx)
dlg:showxy(iup.CENTER,iup.CENTER)
dlg.usersize = nil
util.run(mainloop)
|
CaveBot.Editor.ExampleFunctions = {}
local function addExampleFunction(title, text)
return table.insert(CaveBot.Editor.ExampleFunctions, {title, text:trim()})
end
addExampleFunction("Click to browse example functions", [[
-- available functions/variables:
-- prev - result of previous action (true or false)
-- retries - number of retries of current function, goes up by one when you return "retry"
-- delay(number) - delays bot next action, value in milliseconds
-- gotoLabel(string) - goes to specific label, return true if label exists
-- you can easily access bot extensions, Depositer.run() instead of CaveBot.Extensions.Depositer.run()
-- also you can access bot global variables, like CaveBot, TargetBot
-- use storage variable to store date between calls
-- function should return false, true or "retry"
-- if "retry" is returned, function will be executed again in 20 ms (so better call delay before)
return true
]])
addExampleFunction("buy 200 mana potion from npc Eryn", [[
--buy 200 mana potions
local npc = getCreatureByName("Eryn")
if not npc then
return false
end
if retries > 10 then
return false
end
local pos = player:getPosition()
local npcPos = npc:getPosition()
if math.max(math.abs(pos.x - npcPos.x), math.abs(pos.y - npcPos.y)) > 3 then
autoWalk(npcPos, {precision=3})
delay(300)
return "retry"
end
if not NPC.isTrading() then
NPC.say("hi")
NPC.say("trade")
delay(200)
return "retry"
end
NPC.buy(268, 100)
schedule(1000, function()
-- buy again in 1s
NPC.buy(268, 100)
NPC.closeTrade()
NPC.say("bye")
end)
delay(1200)
return true
]])
addExampleFunction("Say hello 5 times with some delay", [[
--say hello
if retries > 5 then
return true -- finish
end
say("hello")
delay(100 + retries * 100)
return "retry"
]])
addExampleFunction("Disable TargetBot", [[
TargetBot.setOff()
return true
]])
addExampleFunction("Enable TargetBot", [[
TargetBot.setOn()
return true
]])
addExampleFunction("Enable TargetBot luring", [[
TargetBot.enableLuring()
return true
]])
addExampleFunction("Disable TargetBot luring", [[
TargetBot.disableLuring()
return true
]])
addExampleFunction("Logout", [[
g_game.safeLogout()
delay(1000)
return "retry"
]])
|
local K = unpack(select(2, ...))
local table_wipe = table.wipe
function K.LoadSkadaProfile()
if SkadaDB then
table_wipe(SkadaDB)
end
SkadaDB = {
["profiles"] = {
["Default"] = {
["showself"] = false,
["autostop"] = true,
["modules"] = {
["notankwarnings"] = true,
},
["windows"] = {
{
["classicons"] = false,
["barslocked"] = true,
["y"] = 6,
["barfont"] = "KkthnxUI_Normal",
["title"] = {
["color"] = {
["a"] = 0,
["b"] = 0.3,
["g"] = 0.1,
["r"] = 0.1,
},
["font"] = "KkthnxUI_Normal",
["fontsize"] = 12,
["height"] = 17,
["texture"] = "KkthnxUI_StatusBar",
},
["point"] = "BOTTOMRIGHT",
["barbgcolor"] = {
["a"] = 0,
["r"] = 0.3,
["g"] = 0.3,
["b"] = 0.3,
},
["barcolor"] = {
["r"] = 0.05,
["g"] = 0.05,
["b"] = 0.05,
},
["barfontsize"] = 12,
["smoothing"] = true,
["mode"] = "DPS",
["spark"] = false,
["bartexture"] = "KkthnxUI_StatusBar",
["barwidth"] = 200,
["x"] = -300,
["background"] = {
["height"] = 152,
["color"] = {
["a"] = 0,
["b"] = 0.5,
},
},
}, -- [1]
},
["icon"] = {
["hide"] = true,
},
["report"] = {
["channel"] = "Guild",
},
["columns"] = {
["Healing_Healing"] = false,
["Damage_Damage"] = false,
},
["hidesolo"] = true,
["hidedisables"] = false,
["onlykeepbosses"] = true,
},
},
}
Skada.db:SetProfile("Default") -- Automatically set the profile
end
|
-- weapon extension
require "/lib/stardust/weaponutil.lua"
local follow = false
local armAngle = 0
local setArmAngle = activeItem.setArmAngle
function activeItem.setArmAngle(angle, f)
follow = not not f
if follow then angle = angle - mcontroller.rotation() * mcontroller.facingDirection() end
armAngle = angle
return setArmAngle(armAngle)
end
local handPosition = activeItem.handPosition
function activeItem.handPosition(off)
if not follow then return handPosition(off) end
setArmAngle(armAngle + mcontroller.rotation() * mcontroller.facingDirection())
local vec = handPosition(off)
setArmAngle(armAngle)
return vec
end
local function rotatePoly(p, rot, off)
--off = off or {0, 0}
if not p then return nil end
if rot == 0 and (not off or vec2.eq(off, {0, 0})) then return p end
local np = { }
for k, v in pairs(p) do
if off then v = vec2.add(v, off) end
np[k] = vec2.rotate(v, rot)
end
return np
end
local function imbue(src, imb)
local res = util.mergeTable({ }, src or { }) -- copy
util.appendLists(res, imb) -- and append
if res[1] then return res end
return nil
end
local setDamageSources = activeItem.setDamageSources
function activeItem.setDamageSources(lst)
local nl
if lst then
local rot = mcontroller.rotation()
--if rot == 0 then return setDamageSources(lst) end -- early out if not rotated
local imbues = weaponUtil.getStatusImbue()
nl = { }
for _, s in pairs(lst) do
local ms = util.mergeTable({ }, s)
table.insert(nl, ms)
ms.poly = rotatePoly(ms.poly, rot)
ms.line = rotatePoly(ms.line, rot)
ms.statusEffects = imbue(ms.statusEffects, imbues)
end
end
return setDamageSources(nl)
end
local setItemDamageSources = activeItem.setItemDamageSources
function activeItem.setItemDamageSources(lst)
local nl
if lst then
local rot = mcontroller.rotation() * mcontroller.facingDirection()
--if rot == 0 then return setItemDamageSources(lst) end -- early out if not rotated
local imbues = weaponUtil.getStatusImbue()
--local off = handPosition()
nl = { }
for _, s in pairs(lst) do
local ms = util.mergeTable({ }, s)
table.insert(nl, ms)
ms.poly = rotatePoly(ms.poly, rot, off)
ms.line = rotatePoly(ms.line, rot, off)
ms.statusEffects = imbue(ms.statusEffects, imbues)
end
end
return setItemDamageSources(nl)
end
-- imbue projectiles
-- TODO: make sure this only applies to projectiles that *hit enemies*
-- TODO: maybe make this apply to explosions as well (actionOnReap stuff)
local spawnProjectile = world.spawnProjectile
function world.spawnProjectile(name, pos, src, dir, track, params)
local imbues = weaponUtil.getStatusImbue()
local cfg = (name ~= "") and root.projectileConfig(name) or { }
params = params or { }
params.statusEffects = imbue(params.statusEffects or cfg.statusEffects, imbues)
return spawnProjectile(name, pos, src, dir, track, params)
end
|
-- general utility functions:
-- exponential table lookup:
-- goes from 0 to 1, 1002 entries. 0 is scaled to be .001 in the real e^-x
--function
-- should be read going from 2 to 1001 (for cubic interpolation)
local exptab = {}
for i=1, 1002 do
exptab[i] = (math.exp((i-1001)*0.00691466994893) - 0.001)/0.999
end
--clip input between low and high
local function clip(input, low, high)
input = input or 0
return math.min(math.max(input, low), high)
end
-- reads interpolated index in array that starts at 1
-- (cubic lagrange)
local function lagrange(index, tab)
local max = #tab - 1
if index >= max then return tab[max]
elseif index <= 2 then return tab[2] end
local iindex = math.floor(index)
index = index - iindex
local a = tab[iindex - 1]
local b = tab[iindex]
local c = tab[iindex + 1] - b
local d = tab[iindex + 2]
return b + index*(c - 0.166666667*(1 - index)*(
(d - a - 3*c)*index + (d + 2*a - 3*b)))
end
-- exponentially map range 0-1 (clipped). uses lagrange interpolation
local function unexp(input)
input = input * 999 + 2
--close enough
if input <= 2 then return 0 end
return lagrange(input, exptab)
end
--scale a range from (0, 1) to (add, add+scale)
local function sfrom(input, scale, add)
scale = scale or 1
add = add or 0
return input*scale + add
end
--scale input with range of lower, upper or 0, upper if no 3rd arg
--to be in the range (0, 1)
--if lower = upper, resolves to fractional part of input
local function sto(input, lower, upper)
if not lower then return 1
elseif not upper then
upper = lower
lower = 0
end
if upper < lower then
upper, lower = lower, upper
elseif upper == lower then
return input % 1
end
return (input - lower)/(upper - lower)
end
--scale from range a, b to range c, d
local function scalef(input, a, b, c, d)
d = d - c
input = scaletou(input, a, b)
return scalefromu(input, d, c)
end
--[[
--random number between 2 values at a certain interval, inclusive
-- interval defaults to 1
local function randinter(a, b, inter)
inter = inter or 1
if not b then
b = a
a = 0
end
local num = math.floor((a - b)/inter)
num = math.random(num + 1)
return num*(inter - 1) + a
end
]]--
--reflect value in range(low, high)
local function reflect(val, low, high)
if not low then error("reflect: must pass 2nd argument") end
if not high then
low, high = 0, low
end
if low > high then low, high = high, low end
local range = high - low
val = range - ((val - low) % (range*2))
return high - math.abs(val)
end
--wrap value in range(low, high)
local function frange(val, low, high)
if not low then error("wrap: must pass 2nd argument") end
if not high then
low, high = 0, low
end
if low > high then low, high = high, low end
return ((val - low) % (high - low)) + low
end
local function ltype(obj)
local thistype = type(obj)
if thistype == 'table' then
return obj.type or thistype
else return thistype end
end
--from Moses:
--- Maps function `f(key, value)` on all key-value pairs. Collects
-- and returns the results as a table.
local function map(t, f, ...)
local lt = {}
for index,value in pairs(t) do
lt[index] = f(index,value,...)
end
return lt
end
local function log2(exp)
return math.log(exp)/math.log(2)
end
--turn a function into a thunk (1-arg function)
-- args must be a table
local function promise(f, args)
args = args or {}
return function()
return f(unpack(args))
end
end
--returns tr if input > random value between 0 and 1
--else returns fa
local function odds(input, tr, fa)
tr = tr or true
fa = fa or false
if input > math.random() then
return tr
else return fa end
end
--pick a random member of a table of integer indices
local function pick(table)
return(table[math.random(#table)])
end
--shuffle table, from Moses
local function shuffle(t, seed)
if seed then math.randomseed(seed) end
local shuffled = {}
comp.each(t, function(index,value)
local randPos = math.floor(math.random()*index)+1
shuffled[index] = shuffled[randPos]
shuffled[randPos] = value
end)
return shuffled
end
-------- from moses library---------------------------------
-- http://yonaba.github.io/Moses/
local function isstring(obj)
return type(obj) == 'string'
end
local function isfunction(obj)
return type(obj) == 'function'
end
local function isnil(obj)
return obj==nil
end
local function isnumber(obj)
return type(obj) == 'number'
end
local function istable(t)
return type(t) == 'table'
end
-- recursive map on f(value, ...)
-- by S. Shader, needed to put after istable()
local function rmap(table, f, ...)
-- need to pass varargs here because upvalue doesn't work
if istable(table) then return map(table, function(index, value, ...)
return rmap(value, f, ...)
end)
else return f(table, ...) end
end
--- Checks if the given argument is an array. Assumes `obj` is an array
-- if is a table with integer numbers starting at 1.
-- @name isArray
-- @tparam table obj an object
-- @treturn boolean `true` or `false`
local function isarray(obj)
if not istable(obj) then return false end
-- Thanks @Wojak and @Enrique García Cota for suggesting this
-- See : http://love2d.org/forums/viewtopic.php?f=3&t=77255&start=40#p163624
local i = 0
for __ in pairs(obj) do
i = i + 1
if isnil(obj[i]) then return false end
end
return true
end
local function isnot(value) return not value end
local function isboolean(obj)
return type(obj) == 'boolean'
end
local function isinteger(obj)
return isnumber(obj) and math.floor(obj)==obj
end
--- Counts occurrences of a given value in a table. Uses @{isEqual} to compare values.
-- @name count
-- @tparam table t a table
-- @tparam[opt] value value a value to be searched in the table. If not given, the @{size} of the table will be returned
-- @treturn number the count of occurrences of `value`
local function countn(t, value)
if isnil(value) then return size(t) end
local count = 0
each(t, function(k,v)
if isequal(v, value) then count = count + 1 end
end)
return count
end
--- Counts the number of values in a collection. If being passed more than one args
-- it will return the count of all passed-in args.
local function size(...)
local args = {...}
local arg1 = args[1]
if isnil(arg1) then
return 0
elseif istable(arg1) then
return count(args[1])
else
return count(args)
end
end
--- Performs a deep comparison test between two objects. Can compare strings, functions
-- (by reference), nil, booleans. Compares tables by reference or by values. If `useMt`
-- is passed, the equality operator `==` will be used if one of the given objects has a
-- metatable implementing `__eq`.
local function isequal(objA, objB, useMt)
local typeObjA = type(objA)
local typeObjB = type(objB)
if typeObjA~=typeObjB then return false end
if typeObjA~='table' then return (objA==objB) end
local mtA = getmetatable(objA)
local mtB = getmetatable(objB)
if useMt then
if (mtA or mtB) and (mtA.__eq or mtB.__eq) then
return mtA.__eq(objA, objB) or mtB.__eq(objB, objA) or (objA==objB)
end
end
if size(objA)~=size(objB) then return false end
for i,v1 in pairs(objA) do
local v2 = objB[i]
if isnil(v2) or not isequal(v1,v2,useMt) then return false end
end
for i,v1 in pairs(objB) do
local v2 = objA[i]
if sinil(v2) then return false end
end
return true
end
-- calls f(key, value) for each member in t
local function each(t, f, ...)
for index,value in pairs(t) do
f(index,value,...)
end
end
--Reduces a table, left-to-right. Folds the table from the first element to the last element
-- to into a single value, with respect to a given iterator and an initial state.
-- The given function takes a state and a value and returns a new state.
local function reduce(t, f, state)
for __,value in pairs(t) do
if state == nil then state = value
else state = f(state,value)
end
end
return state
end
local function detect(t, value)
local iter = isfunction(value) and value or isequal
for key,arg in pairs(t) do
if iter(arg,value) then return key end
end
end
local function f_max(a,b) return a>b end
local function f_min(a,b) return a<b end
local function identity(value) return value end
local function extract(list,comp,transform,...) -- extracts value from a list
local ans
local transform = transform or identity
for index,value in pairs(list) do
if not ans then ans = transform(value,...)
else
local value = transform(value,...)
ans = comp(ans,value) and ans or value
end
end
return _ans
end
--- Clones a table while dropping values passing an iterator test.
-- <br/><em>Aliased as `discard`</em>
-- @name reject
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn table the remaining values
local function reject(t, f, ...)
local mapped = map(t,f,...)
local lt = {}
for index,value in pairs (mapped) do
if not value then lt[#lt+1] = t[index] end
end
return lt
end
local function lselect(t, f, ...)
local mapped = map(t, f, ...)
local lt = {}
for index,value in pairs(_mapped) do
if value then lt[#lt+1] = t[index] end
end
return lt
end
--- Extracts property-values from a table of values.
-- @name pluck
-- @tparam table t a table
-- @tparam string a property, will be used to index in each value: `value[property]`
-- @treturn table an array of values for the specified property
local function pluck(t, property)
return reject(map(t,function(__,value)
return value[property]
end), isnot)
end
--- Returns the max/min value in a collection. If an transformation function is passed, it will
-- be used to extract the value by which all objects will be sorted.
-- @tparam[opt] function transform an transformation function, prototyped as `transform(value,...)`, defaults to @{identity}
-- @tparam[optchain] vararg ... Optional extra-args to be passed to function `transform`
local function max(t, transform, ...)
return extract(t, f_max, transform, ...)
end
function min(t, transform, ...)
return extract(t, f_min, transform, ...)
end
--- Chunks together consecutive values. Values are chunked on the basis of the return
-- value of a provided predicate `f(key, value, ...)`. Consecutive elements which return
-- the same value are chunked together. Leaves the first argument untouched if it is not an array.
-- @name chunk
-- @tparam table array an array
-- @tparam function f an iterator function prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn table a table of chunks (arrays)
local function chunk(array, f, ...)
if not isarray(array) then return array end
local ch, ck, prev = {}, 0
local mask = map(array, f,...)
each(mask, function(k,v)
prev = (prev==nil) and v or prev
ck = ((v~=prev) and (ck+1) or ck)
if not ch[ck] then
ch[ck] = {array[k]}
else
ch[ck][#ch[ck]+1] = array[k]
end
prev = v
end)
return ch
end
--- Slices values indexed within `[start, finish]` range.
-- @name slice
-- @tparam table array an array
-- @tparam[opt] number start the lower bound index, defaults to the first index in the array.
-- @tparam[optchain] number finish the upper bound index, defaults to the array length.
-- @treturn table a new array
local function slice(array, start, finish)
return lselect(array, function(index)
return (index >= (start or next(array)) and index <= (finish or #array))
end)
end
--- Returns the first N values in an array.
-- @tparam table array an array
-- @tparam[opt] number n the number of values to be collected, defaults to 1.
-- @treturn table a new array
local function first(array, n)
local n = n or 1
return slice(array,1, min(n,#array))
end
--- Returns the last N values in an array.
-- @name last
-- @tparam table array an array
-- @tparam[opt] number n the number of values to be collected, defaults to the array length.
-- @treturn table a new array
local function last(array,n)
if n and n <= 0 then return end
return slice(array,n and #array-min(n-1,#array-1) or 2,#array)
end
--- Flattens a nested array. Passing `shallow` will only flatten at the first level.
-- @name flatten
-- @tparam table array an array
-- @tparam[opt] boolean shallow specifies the flattening depth
-- @treturn table a new array, flattened
local function flatten(array, shallow)
local shallow = shallow or false
local new_flattened
local flat = {}
for key,value in pairs(array) do
if istable(value) then
new_flattened = shallow and value or flatten (value)
each(new_flattened, function(_,item) flat[#flat+1] = item end)
else flat[#flat+1] = value
end
end
return flat
end
--- Merges values of each of the passed-in arrays in subsets.
-- Only values indexed with the same key in the given arrays are merged in the same subset.
-- @name zip
-- @tparam vararg ... a variable number of array arguments
-- @treturn table a new array
local function zip(...)
local arg = {...}
local len = max(map(arg,function(i,v)
return #v
end))
local ans = {}
for i = 1,len do
ans[i] = pluck(arg,i)
end
return ans
end
--- Clones `array` and appends `other` values.
-- @name append
-- @tparam table array an array
-- @tparam table other an array
-- @treturn table a new array
local function append(array, other)
local t = {}
for i,v in ipairs(array) do t[i] = v end
for i,v in ipairs(other) do t[#t+1] = v end
return t
end
--- Interleaves arrays. It returns a single array made of values from all
-- passed in arrays in their given order, interleaved.
-- @name interleave
-- @tparam vararg ... a variable list of arrays
-- @treturn table a new array
-- @see interpose
local function interleave(...) return flatten(zip(...)) end
--- Produce a flexible list of numbers. If one positive value is passed, will count from 0 to that value,
-- with a default step of 1. If two values are passed, will count from the first one to the second one, with the
-- same default step of 1. A third passed value will be considered a step value.
-- @name range
-- @tparam[opt] number from the initial value of the range
-- @tparam[optchain] number to the final value of the range
-- @tparam[optchain] number step the count step value
-- @treturn table a new array of numbers
local function range(...)
local arg = {...}
local start, stop, step
if #arg==0 then return {}
elseif #arg==1 then _stop,_start,_step = arg[1],0,1
elseif #arg==2 then _start,_stop,_step = arg[1],arg[2],1
elseif #arg == 3 then _start,_stop,_step = arg[1],arg[2],arg[3]
end
if (step and step==0) then return {} end
local ranged = {}
local steps = math.max(math.floor((stop-start)/step),0)
for i=1,steps do ranged[#ranged+1] = start+step*i end
if #ranged>0 then table.insert(ranged,1,start) end
return ranged
end
--- Creates an array list of `n` values, repeated.
-- @name rep
-- @tparam value value a value to be repeated
-- @tparam number n the number of repetitions of the given `value`.
-- @treturn table a new array of `n` values
local function rep(value, n)
local ret = {}
for i = 1, n do ret[#ret+1] = value end
return ret
end
--- Reverses values in a given array. The passed-in array should not be sparse.
-- @name reverse
-- @tparam table array an array
-- @treturn table a copy of the given array, reversed
local function reverse(array)
local larray = {}
for i = #array,1,-1 do
larray[#larray+1] = array[i]
end
return larray
end
-- binary search of sorted array,
-- get should get numerical items to compare
-- from the table. val is already "got"ten
-- returns negative number of last index to the right if unfound,
-- and index if found
-- from Sedgewick
local function bsearch(tbl, val, get)
get = get or identity
local l = 1
local r = #tbl
local index
-- get real value
repeat
index = math.floor((l + r)/2)
if val == get(tbl[index]) then return index
elseif val < get(tbl[index]) then r = index - 1
else l = index + 1 end
until r < l
return -r - 1
end
--pick a random member of a table of integer indices
local function pick(table)
return(table[math.random(#table)])
end
--shuffle table, from Moses
local function shuffle(t, seed)
if seed then math.randomseed(seed) end
local shuffled = {}
comp.each(t, function(index,value)
local randPos = math.floor(math.random()*index)+1
shuffled[index] = shuffled[randPos]
shuffled[randPos] = value
end)
return shuffled
end
-- one time weighting of table in format:
-- {{item1, weight1}, {item2, weight2}, etc}
-- where weights are positive numbers, defaulting to 1 if absent
local function wonce(intable)
local sums = {}
local sum = 0.0
local add
for i=1, #intable do
add = intable[i][2] or 1
sum = sum + math.abs(add)
sums[i] = sum
end
sum = math.random()*sum
sum = math.abs(bsearch(sums, sum))
return intable[sum][1]
end
--- Composes functions. Each passed-in function consumes the return value of the function that follows.
-- In math terms, composing the functions `f`, `g`, and `h` produces the function `f(g(h(...)))`.
-- @name compose
-- @tparam vararg ... a variable number of functions
-- @treturn function a new function
-- @see pipe
local function compose(...)
local f = reverse {...}
return function (...)
local temp
for i, func in ipairs(f) do
temp = temp and func(temp) or func(...)
end
return temp
end
end
--- Pipes a value through a series of functions. In math terms,
-- given some functions `f`, `g`, and `h` in that order, it returns `f(g(h(value)))`.
-- @name pipe
-- @tparam value value a value
-- @tparam vararg ... a variable number of functions
-- @treturn value the result of the composition of function calls.
-- @see compose
local function pipe(value, ...)
return compose(...)(value)
end
--- Wraps `f` inside of the `wrapper` function. It passes `f` as the first argument to `wrapper`.
-- This allows the wrapper to execute code before and after `f` runs,
-- adjust the arguments, and execute it conditionally.
-- @name wrap
-- @tparam function f a function to be wrapped, prototyped as `f(...)`
-- @tparam function wrapper a wrapper function, prototyped as `wrapper(f,...)`
-- @treturn function a new function
local function wrap(f, wrapper)
return function (...) return wrapper(f,...) end
end
--- Binds `v` to be the first argument to function `f`. As a result,
-- calling `f(...)` will result to `f(v, ...)`.
-- @name bind
-- @tparam function f a function
-- @tparam value v a value
-- @treturn function a function
-- @see bindn
local function bind(f, v)
return function (...)
return f(v,...)
end
end
--- Binds `...` to be the N-first arguments to function `f`. As a result,
-- calling `f(a1, a2, ..., aN)` will result to `f(..., a1, a2, ...,aN)`.
-- @name bindn
-- @tparam function f a function
-- @tparam vararg ... a variable number of arguments
-- @treturn function a function
-- @see bind
local function bindn(f, ...)
local iarg = {...}
return function (...)
return f(unpack(append(iarg,{...})))
end
end
local function count(t) -- raw count of items in an map-table
local i = 0
for k,v in pairs(t) do i = i + 1 end
return i
end
---------------------------- from abclua:
-- return the greatest common divisor of a and b
local function gcd(a, b)
while a ~= 0 do
a,b = (b%a),a
end
return b
end
local function copyar(orig)
-- copy an array (only integer keys are copied)
local copy = {}
for i=1,#orig do
copy[i] = orig[i]
end
return copy
end
local function copytab(orig)
-- shallow copy a table (does not copy the contents)
local copy = {}
for i,v in pairs(orig) do
copy[i] = v
end
return copy
end
-- copy a table completely (excluding metatables)
-- don't copy keys, just values
local function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[orig_key] = deepcopy(orig_value)
end
else -- number, string, boolean, etc
copy = orig
end
return copy
end
--function to do something many times
local function domult (times, f, ...)
for i=1, (times - 1) do
f(...)
end
return f(...)
end
-- takes an array representation of a function call and calls it:
-- {function, arg1, arg2, etc...}
local function fcall(intable)
local f = intable[1]
return f(unpack(intable, 2))
end
-- arg is a table, if arg[1] is a function then calls it with fcall
-- else, does arg[1][arg[3]] = arg[2]
-- if addarg and switch are provided, the arg is inserted
-- in the switchth spot. switch can be an array, in which case
-- arrays are traversed by index: for instance, a switch value of
-- {4, 2, 3} would insert addarg into intable[4][2][3]
-- default {2}
local function route(intable, addarg, switch)
if addarg then
switch = switch or 2
if type(switch) == "number" then
switch = {switch}
end
local trav = intable
local ltable
local lindex
for i, v in ipairs(switch) do
-- if an index doesn't exist, create it
if type(trav) ~= "table" then
trav = {}
table.insert(ltable, lindex, trav)
end
ltable = trav
lindex = v
trav = ltable[lindex]
end
table.insert(ltable, lindex, addarg)
end
if isfunction(intable[1]) then
return fcall(intable)
else intable[1][intable[3]] = intable[2] end
end
--call all promises or structures for route in a table
local function callall (intable)
local val
for i, v in pairs(intable) do
if isfunction(v) then v()
elseif istable(v) then route(v) end
end
end
--[[uses fcall on args, but also stores array
returns an object with members:
call(): call args with fcall
setcall(item, index): set an arg at index and call
--]]
local function storargs(intable)
local obj = {type = "stargs", args = intable}
obj.call = function()
fcall(obj.args)
end
obj.setcall = function(item, index)
args[index] = item
obj.call()
end
return obj
end
-- cyclic counter maker
local function ccount(limit)
local count = 1
return function()
local ret = count
count = count + 1
if count > limit then count = 1 end
return ret
end
end
-- http://lua-users.org/wiki/SplitJoin
local function split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
comp = {
log2 = log2,
clip = clip,
lagrange = lagrange,
unexp = unexp,
sto = sto,
sfrom = sfrom,
reflect = reflect,
frange = frange,
scalef = scalef,
each = each,
map = map,
rmap = rmap,
identity = identity,
reduce = reduce,
count = countn,
size = size,
reject = reject,
select = lselect,
pluck = pluck,
chunk = chunk,
slice = slice,
first = first,
last = last,
flatten = flatten,
zip = zip,
append = append,
interleave = interleave,
range = range,
rep = rep,
reverse = reverse,
bsearch = bsearch,
compose = compose,
pipe = pipe,
wrap = wrap,
bind = bind,
bindn = bindn,
isequal = isequal,
detect = detect,
max = max,
min = min,
isnot = isnot,
isstring = isstring,
isfunction = isfunction,
isnil = isnil,
isnumber = isnumber,
isboolean = isboolean,
isinteger = isinteger,
istable = istable,
type = ltype,
gcd = gcd,
copyar = copyar,
copytab = copytab,
deepcopy = deepcopy,
domult = domult,
promise = promise,
odds = odds,
route = route,
pick = pick,
shuffle = shuffle,
wonce = wonce,
fcall = fcall,
stargs = storargs,
callall = callall,
ccount = ccount,
split = split
}
return comp
|
-- Copyright (c) 2021 Kirazy
-- Part of Artisanal Reskins: Bob's Mods
--
-- See LICENSE in the project directory for license information.
-- Requires
local migration = require("__reskins-library__.prototypes.functions.migration")
local function on_configuration_changed(data)
for _, player in pairs(game.connected_players) do
if player.admin then
if player.mod_settings["reskins-lib-display-notifications"].value == true then
-- Notify of changes when updated in a save we were already present in
if data.mod_changes and data.mod_changes["reskins-bobs"] and data.mod_changes["reskins-bobs"].old_version then
-- 1.0.7 update
if migration.is_version_or_older(data.mod_changes["reskins-bobs"].old_version, "1.0.7") then
player.print({"", "[", {"reskins-library.reskins-suite-name"}, "] ", {"reskins-updates.reskins-bobs-1-0-7-update", {"mod-setting-name.reskins-bobs-do-bobelectronics-circuit-style"}}})
end
end
end
end
end
end
script.on_configuration_changed(on_configuration_changed)
|
#!/usr/local/bin/lua
--
-- This is part of the release script.
--
-- See release.sh for more explanation.
--
deimos = dofile("./deimos.lua")
print(deimos.version)
|
;; [Write]
|
workspace "ace"
configurations { "Debug", "Release" }
platforms { "x64", "x86" }
startproject "example-app"
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
filter { "platforms:x86" }
architecture "x86"
filter { "platforms:x64" }
architecture "x86_64"
filter{}
defines{ "PLATFORM_DESKTOP", "GRAPHICS_API_OPENGL_21" }
project "raylib"
filter "configurations:Debug OR Release"
kind "StaticLib"
filter "action:vs*"
defines{ "_WINSOCK_DEPRECATED_NO_WARNINGS", "_CRT_SECURE_NO_WARNINGS", "_WIN32" }
links { "winmm" }
filter "action:gmake*"
links { "pthread", "GL", "m", "dl", "rt", "X11" }
filter{}
language "C++"
targetdir "Addons/raylib/build/%{cfg.buildcfg}/%{cfg.platform}"
cppdialect "C++17"
files { "Addons/raylib/src/*.h", "Addons/raylib/src/*.c" }
vpaths {
["Header Files"] = { "Addons/raylib/src/**.h" },
["Source Files/*"] = { "Addons/raylib/src/**.c" },
}
includedirs { "Addons/raylib/src", "Addons/raylib/src/external/glfw/include" }
project "ace"
filter "configurations:Debug OR Release"
kind "StaticLib"
filter "action:gmake*"
links { "pthread", "GL", "m", "dl", "rt", "X11" }
filter{}
language "C++"
targetdir "build/%{cfg.buildcfg}/%{cfg.platform}"
cppdialect "C++17"
files { "src/**.h", "src/**.c", "src/**.cpp", "addons/zstd/lib/**.h", "addons/zstd/lib/**.c",
"addons/zstd/programs/util.*", "addons/zstd/programs/timefn.*",
"addons/zstd/programs/platform.*", "addons/zstd/lib/common/*.*", "addons/md5/*.*" }
removefiles { "addons/zstd/programs/dibio.*" }
vpaths {
["Header Files"] = { "**.h" },
["Source Files/*"] = { "**.c", "**.cpp" },
}
includedirs { "addons/zstd/lib", "addons/zstd/programs", "addons/raylib/src", "addons/md5" }
project "example-app"
kind "ConsoleApp"
language "C++"
targetdir "bin/%{cfg.buildcfg}/%{cfg.platform}"
cppdialect "C++17"
-- Files included in the solution
files { "example/**.c", "example/**.cpp", "example/**.h" }
vpaths {
["Header Files"] = { "**.h" },
["Source Files"] = { "**.c", "**.cpp" },
}
links { "raylib", "ace" }
-- Additional include >>directories<< - easier access!
includedirs { "addons/zstd/lib", "addons/zstd/programs", "addons/raylib/src", "src" }
defines{ "PLATFORM_DESKTOP", "GRAPHICS_API_OPENGL_21" }
filter "action:vs*"
defines{ "_WINSOCK_DEPRECATED_NO_WARNINGS", "_CRT_SECURE_NO_WARNINGS", "_WIN32" }
dependson { "raylib", "ace" }
links { "raylib.lib", "winmm", "kernel32", "ace.lib" }
libdirs { "addons/raylib/build/%{cfg.buildcfg}/%{cfg.platform}", "build/%{cfg.buildcfg}/%{cfg.platform}" }
filter "action:gmake*"
links { "pthread", "GL", "m", "dl", "rt", "X11" }
|
#!/usr/local/bin/lua
io.output("simple-io.out")
msg = [[
我爱中国
黄土高坡
]]
io.write(msg)
|
package.path = './?.lua;./scripts/?.lua;' -- could add .. package.path
package.cpath = './?.dll;./scripts/?.dll;' -- could add .. package.cpath
--io.write( package.path .. '\n\n')
--io.write( package.cpath .. '\n\n')
--require("mobdebug").start()
local defs = require("usb_defs")
local stdRequestMod = require("usb_std_request")
local descriptorMod = require("usb_descriptor")
local format = string.format -- save a bit of typing :)
--============================================
function myAdd(a, b)
return a+b
end
--============================================
function getParent(parent)
if parent then return getNode(parent) else return nil end
end
--============================================
function reset_decode(params)
local duration = params["duration"]
--local idleTicks = params["idleTicks"]
local dur, units = duration * 1000/12, "ns"
if dur > 1000 then
dur = dur/1000; units = "mus"
if dur > 1000 then
dur = dur/1000; units = "ms"
if dur > 1000 then
dur = dur/1000; units = "s"
end
end
end
local t = {}
t[#t + 1] = "S" -- string
t[#t + 1] = format("A USB Reset for %d ticks ", duration)
t[#t + 1] = format("(%.3f %s).\n\n", dur, units)
t[#t + 1] = "The host signals a valid Reset by pulling both USB lines"
t[#t + 1] = " (D+ and D-) low for at least 10ms."
t[#t + 1] = " Short Resets are invalid and often occur when a device is"
t[#t + 1] = " plugged in or powered up."
return table.concat(t);
end
--============================================
function sof_decode(params)
--local handle = params["handle"]
--local parent = params["parent"]
--local frame = params["frame"]
--local crc5 = params["crc5"]
local crcOK = params["crcOK"]
local t = {}
t[#t + 1] = "S" -- string
t[#t + 1] = "A single SOF (Start Of Frame) packet."
if not crcOK then
t[#t + 1] = "\n\nCRC is incorrect."
end
return table.concat(t);
end
--============================================
function token_decode(params)
--local handle = params["handle"]
--local parent = params["parent"]
local pid = params["pid"]
--local addr = params["addr"]
--local endp = params["endp"]
--local crc5 = params["crc5"]
local crcOK = params["crcOK"]
local t = {}
t[#t + 1] = "S" -- string
if pid == defs.PID_SETUP then t[#t + 1] = "A SETUP"
elseif pid == defs.PID_IN then t[#t + 1] = "An IN"
elseif pid == defs.PID_OUT then t[#t + 1] = "An OUT"
else t[#t + 1] = "An unrecognized"
end
t[#t + 1] = " token packet."
if not crcOK then
t[#t + 1] = "\n\nCRC is incorrect."
end
return table.concat(t);
end
--============================================
function data_decode(params)
--local handle = params["handle"]
local parent = params["parent"]
local pid = params["pid"]
local data = params["data"]
--local crc16 = params["crc16"]
local crcOK = params["crcOK"]
local t = {}
t[#t + 1] = "S" -- string
if pid == defs.PID_DATA0 then t[#t + 1] = "A DATA0"
elseif pid == defs.PID_DATA1 then t[#t + 1] = "A DATA1"
elseif pid == defs.PID_DATA2 then t[#t + 1] = "A DATA2"
elseif pid == defs.PID_MDATA then t[#t + 1] = "An MDATA"
else t[#t + 1] = "An unrecognized"
end
t[#t + 1] = " data packet"
if pid == defs.PID_DATA0 then t[#t + 1] = " (data toggle = 0)"
elseif pid == defs.PID_DATA1 then t[#t + 1] = " (data toggle = 1)"
end
t[#t + 1] = ". The raw data in this packet is shown in the Data pane.";
if not crcOK then
t[#t + 1] = "\n\nCRC is incorrect."
end
local owner = getParent(parent)
if owner and (owner["type"]=="transaction")
and (owner["subType"] == "SETUP") then
t[#t + 1] = "\nThe packet carries the 8 data bytes for a SETUP transaction"
t[#t + 1] = " - click on the transaction to see the data bytes decoded."
t[#t + 1] = ";"
t[#t + 1] = stdRequestMod.stdRequest(data)
end
return table.concat(t);
end
--============================================
function handshake_decode(params)
--local handle = params["handle"]
--local parent = params["parent"]
local pid = params["pid"]
local t = {}
t[#t + 1] = "S" -- string
if pid == defs.PID_ACK then t[#t + 1] = "An ACK"
elseif pid == defs.PID_NAK then t[#t + 1] = "A NAK"
elseif pid == defs.PID_STALL then t[#t + 1] = "A STALL"
elseif pid == defs.PID_NYET then t[#t + 1] = "A NYET"
else t[#t + 1] = "An unrecognized"
end
t[#t + 1] = " handshake packet."
return table.concat(t);
end
--============================================
local function transaxIsAck(transax)
if transax and (transax.type == "transaction") then
local children = transax["children"]
for ix = 1, #children do
local child = getNode(children[ix])
if child and (child.type == "handshake") then
return child.pid == defs.PID_ACK
end
end
end
return false
end
--============================================
local function transferGetTransax(transfer, subType)
if transfer and (transfer.type == "transfer") then
local children = transfer["children"]
for ix = 1, #children do
local child = getNode(children[ix])
if child and (child.type == "transaction")
and (child.subType == subType)
and transaxIsAck(child) then
return child
end
end
end
return nil
end
--============================================
local function transaxGetPacket(transax, packetType)
if transax and (transax.type == "transaction") then
local children = transax["children"]
for ix = 1, #children do
local child = getNode(children[ix])
if child and (child.type == packetType) then
return child
end
end
end
return nil
end
--============================================
function transaction_decode(params)
--local handle = params["handle" ]
local parent = params["parent" ]
local children = params["children"]
local subType = params["subType" ]
local t = {}
t[#t + 1] = "S" -- string
t[#t + 1] = subType .. " transaction\n"
t[#t + 1] = ";"
if transaxIsAck(params) then
if subType == "SETUP" then
for ix = 1, #children do
local child = getNode(children[ix])
if child and (child.type == 'data') then
t[#t + 1] = stdRequestMod.stdRequest(child.data)
break
end
end
elseif subType == "IN" then
local stringIndex = 0
local setup = transferGetTransax(getParent(parent), "SETUP")
local sdata = transaxGetPacket(setup, "data")
if sdata and sdata.data and (#sdata.data == 8) then
stringIndex = sdata.data[3]
end
local inData = transaxGetPacket(params, "data")
if inData then
t[#t + 1] = descriptorMod.descriptorStr(inData.data, stringIndex)
end
end
end
return table.concat(t)
end
--============================================
function transfer_decode(params)
--local handle = params["handle" ]
--local parent = params["parent" ]
--local children = params["children"]
local subType = params["subType" ]
local t = {}
t[#t + 1] = "S" -- string
t[#t + 1] = subType .. " transfer\n"
t[#t + 1] = ";"
if subType ~= "CONTROL" then
return table.concat(t)
end
local stringIndex = 0
local setupTransax = transferGetTransax(params, "SETUP")
local setupDataPkt = transaxGetPacket(setupTransax, "data")
local d2h = false
if setupDataPkt and setupDataPkt.data and (#setupDataPkt.data == 8) then
t[#t + 1] = stdRequestMod.stdRequest(setupDataPkt.data)
t[#t + 1] = ";"
d2h = bit32.btest(setupDataPkt.data[1], 0x80)
stringIndex = setupDataPkt.data[3]
end
if d2h then
local inTransax = transferGetTransax(params, "IN")
local inDataPkt = transaxGetPacket(inTransax, "data")
if inDataPkt then
t[#t + 1] = descriptorMod.descriptorStr(inDataPkt.data, stringIndex)
t[#t + 1] = ";"
end
end
return table.concat(t)
end
-- EOF ---------------------------------------
--[[
local v = {0x80, 0x06, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00}
local s = stdRequestMod.stdRequest(v)
print(s)
local v2 = {0x12, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x40,
0x81, 0x07, 0x67, 0x55, 0x27, 0x01, 0x01, 0x02,
0x03, 0x01}
local s2 = descriptorMod.descriptorStr(v2, 0)
print(s2)
--]]
|
local pretty = require 'pl.pretty'
local utils = require 'pl.utils'
local test = require 'pl.test'
local asserteq, assertmatch = test.asserteq, test.assertmatch
t1 = {
'one','two','three',{1,2,3},
alpha=1,beta=2,gamma=3,['&']=true,[0]=false,
_fred = {true,true},
s = [[
hello dolly
you're so fine
]]
}
s = pretty.write(t1) --,' ',true)
t2,err = pretty.read(s)
if err then return print(err) end
asserteq(t1,t2)
res,err = pretty.read [[
{
['function'] = true,
['do'] = true,
}
]]
assert(res)
res,err = pretty.read [[
{
['function'] = true,
['do'] = function() return end
}
]]
assertmatch(err,'cannot have functions in table definition')
res,err = pretty.load([[
-- comments are ok
a = 2
bonzo = 'dog'
t = {1,2,3}
]])
asserteq(res,{a=2,bonzo='dog',t={1,2,3}})
--- another potential problem is string functions called implicitly as methods--
res,err = pretty.read [[
{s = ('woo'):gsub('w','wwwwww'):gsub('w','wwwwww')}
]]
assertmatch(err,utils.lua51 and 'attempt to index a string value' or "attempt to index constant 'woo'")
---- pretty.load has a _paranoid_ option
res,err = pretty.load([[
k = 0
for i = 1,1e12 do k = k + 1 end
]],{},true)
assertmatch(err,'looping not allowed')
-- Check to make sure that no spaces exist when write is told not to
local tbl = { "a", 2, "c", false, 23, 453, "poot", 34 }
asserteq( pretty.write( tbl, "" ), [[{"a",2,"c",false,23,453,"poot",34}]] )
-- Check that write correctly prevents cycles
local t1,t2 = {},{}
t1[1] = t1
asserteq( pretty.write(t1,""), [[{<cycle>}]] )
t1[1],t1[2],t2[1] = 42,t2,t1
asserteq( pretty.write(t1,""), [[{42,{<cycle>}}]] )
-- Check false positives in write's cycles prevention
t2 = {}
t1[1],t1[2] = t2,t2
asserteq( pretty.write(t1,""), [[{{},{}}]] )
function testm(x,s)
asserteq(pretty.number(x,'M'),s)
end
testm(123,'123B')
testm(1234,'1.2KiB')
testm(10*1024,'10.0KiB')
testm(1024*1024,'1.0MiB')
function testn(x,s)
asserteq(pretty.number(x,'N',2),s)
end
testn(123,'123')
testn(1234,'1.23K')
testn(10*1024,'10.24K')
testn(1024*1024,'1.05M')
testn(1024*1024*1024,'1.07B')
function testc(x,s)
asserteq(pretty.number(x,'T'),s)
end
testc(123,'123')
testc(1234,'1,234')
testc(12345,'12,345')
testc(123456,'123,456')
testc(1234567,'1,234,567')
testc(12345678,'12,345,678')
asserteq(pretty.number(1e12,'N'),'1000.0B')
|
local E, L, V, P, G, _ = unpack(select(2, ...)); --Inport: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
--NamePlate
P['nameplates_v1'] = {
['statusbar'] = 'ElvUI Norm',
['font'] = 'PT Sans Narrow',
['fontSize'] = 11,
['fontOutline'] = 'OUTLINE',
['healthFont'] = 'PT Sans Narrow',
['healthFontSize'] = 11,
['healthFontOutline'] = 'OUTLINE',
['durationPosition'] = 'CENTER',
['stackFont'] = 'PT Sans Narrow',
['stackFontSize'] = 9,
['stackFontOutline'] = 'OUTLINE',
['useTargetScale'] = true,
['targetScale'] = 1.15,
['nonTargetTransparency'] = 0.35,
['motionType'] = 'STACKED',
['displayStyle'] = 'ALL',
['lowHealthThreshold'] = 0.4,
['showFriendlyCombat'] = 'DISABLED',
['showEnemyCombat'] = 'DISABLED',
['hideBlizzardPlates'] = false,
['showNPCTitles'] = true,
['clampToScreen'] = false,
['loadDistance'] = 40,
['targetGlow'] = 'style2',
['glowColor'] = { r = 77/255, g = 179/255, b = 255/255, a = 1 },
['nameColoredGlow'] = false,
['cutawayHealth'] = false,
['cutawayHealthLength'] = 0.3,
['cutawayHealthFadeOutTime'] = 0.6,
['alwaysShowTargetHealth'] = true,
['questIcon'] = true,
['questIconSize'] = 16,
['questIconText'] = true,
['questIconPosition'] = 'LEFT', --by eui.cc
['questIconXOffset'] = 4,--by eui.cc
['questIconYOffset'] = 0,
['cooldown'] = {
['threshold'] = 4,
['override'] = true,
['reverse'] = false,
['hideBlizzard'] = false,
['expiringColor'] = { r = 1, g = 0, b = 0 },
['secondsColor'] = { r = 1, g = 1, b = 1 },
['minutesColor'] = { r = 1, g = 1, b = 1 },
['hoursColor'] = { r = 1, g = 1, b = 1 },
['daysColor'] = { r = 1, g = 1, b = 1 },
['checkSeconds'] = false,
['hhmmColor'] = { r = 1, g = 1, b = 1 },
['mmssColor'] = { r = 1, g = 1, b = 1 },
['hhmmThreshold'] = -1,
['mmssThreshold'] = -1,
['fonts'] = {
['enable'] = false,
['font'] = 'PT Sans Narrow',
['fontOutline'] = 'OUTLINE',
['fontSize'] = 10,
},
},
['classbar'] = {
['enable'] = true,
['scale'] = 1,
['attachTo'] = 'TARGET',
['position'] = 'ABOVE'
},
['castColor'] = { r = 1,g = 208/255,b = 0 },
['castNoInterruptColor'] = { r = 0.78, g = 0.25, b = 0.25 },
['reactions'] = {
['tapped'] = {r = 0.6, g = 0.6, b = 0.6},
['good'] = {r = 75/255, g = 175/255, b = 76/255},
['neutral'] = { r = 218/255, g = 197/255, b = 92/255 },
['bad'] = { r = 0.78, g = 0.25, b = 0.25 },
['offline'] = {r = 0.3, g = 0.3, b = 0.3},
},
['healPrediction'] = {
['personal'] = {r = 0, g = 1, b = 0.5, a = 0.25},
['others'] = {r = 0, g = 1, b = 0, a = 0.25},
['absorbs'] = {r = 1, g = 1, b = 0, a = 0.25},
['healAbsorbs'] = {r = 1, g = 0, b = 0, a = 0.25},
['overabsorbs'] = {r = 1, g = 1, b = 0, a = 0.25},
['overhealabsorbs'] = {r = 1, g = 0, b = 0, a = 0.25},
},
['threat'] = {
['goodColor'] = {r = 75/255, g = 175/255, b = 76/255},
['badColor'] = {r = 0.78, g = 0.25, b = 0.25},
['goodTransition'] = { r = 218/255, g = 197/255, b = 92/255 },
['badTransition'] ={ r = 235/255, g = 163/255, b = 40/255 },
['beingTankedByTankColor'] = {r =.8, g = 0.1,b = 1},
['beingTankedByTank'] = true,
['goodScale'] = 0.8,
['badScale'] = 1.2,
['useThreatColor'] = true,
},
['filters'] = {
['Boss'] = {
['triggers'] = {
['enable'] = false,
},
},
},
['clickableWidth'] = 150,
['clickableHeight'] = 50,
['clickThrough'] = {
['personal'] = false,
['friendly'] = false,
['enemy'] = false,
},
['units'] = {
['PLAYER'] = {
['enable'] = false,
['useStaticPosition'] = false,
['clickthrough'] = false,
['portrait'] = {
['enable'] = false,
['width'] = 30,
['height'] = 24,
},
['visibility'] = {
['showAlways'] = false,
['showInCombat'] = true,
['showWithTarget'] = false,
['hideDelay'] = 3,
},
['healthbar'] = {
['enable'] = true,
['height'] = 10,
['width'] = 150,
['healPrediction'] = true,
['glowStyle'] = 'TARGET_THREAT',
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
['useClassColor'] = true,
},
['showName'] = false,
['showLevel'] = false,
['powerbar'] = {
['enable'] = true,
['hideWhenEmpty'] = false,
['costPrediction'] = true,
['height'] = 8,
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
},
['castbar'] = {
['enable'] = true,
['height'] = 8,
['sourceInterrupt'] = false,
['sourceInterruptClassColor'] = true,
['displayTarget'] = false,
['hideSpellName'] = false,
['hideTime'] = false,
['castTimeFormat'] = 'CURRENT',
['channelTimeFormat'] = 'CURRENT',
['timeToHold'] = 0,
['iconPosition'] = 'RIGHT',
},
['buffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 300,
['priority'] = 'Blacklist,blockNoDuration,Personal,TurtleBuffs,PlayerBuffs' --NamePlate Player Buffs
},
},
['debuffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,blockNoDuration,Personal,Boss,CCDebuffs,RaidDebuffs,Dispellable' --NamePlate Player Debuffs
},
},
['name'] = {
['useClassColor'] = true,
},
},
['HEALER'] = {
['portrait'] = {
['enable'] = false,
['width'] = 30,
['height'] = 24,
},
['healthbar'] = {
['enable'] = true,
['height'] = 10,
['width'] = 150,
['healPrediction'] = true,
['glowStyle'] = 'TARGET_THREAT',
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
['useClassColor'] = true,
},
['showName'] = true,
['showLevel'] = false,
['powerbar'] = {
['enable'] = true,
['hideWhenEmpty'] = false,
['costPrediction'] = true,
['height'] = 8,
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
},
['castbar'] = {
['enable'] = true,
['height'] = 8,
['sourceInterrupt'] = false,
['sourceInterruptClassColor'] = true,
['displayTarget'] = false,
['hideSpellName'] = false,
['hideTime'] = false,
['castTimeFormat'] = 'CURRENT',
['channelTimeFormat'] = 'CURRENT',
['timeToHold'] = 0,
['iconPosition'] = 'RIGHT',
},
['buffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,blockNoDuration,Personal,TurtleBuffs' --NamePlate Healer Buffs
},
},
['debuffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,Dispellable,blockNoDuration,Personal,Boss,CCDebuffs' --NamePlate Healer Debuffs
},
},
['name'] = {
['useClassColor'] = true,
},
},
['FRIENDLY_PLAYER'] = {
['portrait'] = {
['enable'] = false,
['width'] = 30,
['height'] = 24,
},
['minions'] = false,
['healthbar'] = {
['enable'] = false,
['height'] = 10,
['width'] = 150,
['healPrediction'] = true,
['glowStyle'] = 'TARGET_THREAT',
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
['useClassColor'] = true,
},
['showName'] = true,
['showLevel'] = false,
['powerbar'] = {
['enable'] = false,
['hideWhenEmpty'] = false,
['costPrediction'] = true,
['height'] = 8,
['baseHeight'] = 18,
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
},
['castbar'] = {
['enable'] = true,
['height'] = 8,
['sourceInterrupt'] = false,
['sourceInterruptClassColor'] = true,
['displayTarget'] = false,
['hideSpellName'] = false,
['hideTime'] = false,
['castTimeFormat'] = 'CURRENT',
['channelTimeFormat'] = 'CURRENT',
['timeToHold'] = 0,
['iconPosition'] = 'RIGHT',
},
['buffs'] = {
['enable'] = true,
['numAuras'] = 4,
["baseHeight"] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,blockNoDuration,Personal,TurtleBuffs' --NamePlate FriendlyPlayer Buffs
},
},
['debuffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,Dispellable,blockNoDuration,Personal,Boss,CCDebuffs' --NamePlate FriendlyPlayer Debuffs
},
},
['name'] = {
['useClassColor'] = true,
},
},
['ENEMY_PLAYER'] = {
['portrait'] = {
['enable'] = false,
['width'] = 30,
['height'] = 24,
},
['minions'] = false,
['markHealers'] = true,
['healthbar'] = {
['enable'] = true,
['height'] = 10,
['width'] = 150,
['healPrediction'] = true,
['glowStyle'] = 'TARGET_THREAT',
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
['useClassColor'] = true,
},
['showName'] = true,
['showLevel'] = true,
['powerbar'] = {
['enable'] = false,
['hideWhenEmpty'] = false,
['costPrediction'] = true,
['height'] = 8,
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
},
['castbar'] = {
['enable'] = true,
['height'] = 8,
['sourceInterrupt'] = false,
['sourceInterruptClassColor'] = true,
['displayTarget'] = false,
['hideSpellName'] = false,
['hideTime'] = false,
['castTimeFormat'] = 'CURRENT',
['channelTimeFormat'] = 'CURRENT',
['timeToHold'] = 0,
['iconPosition'] = 'RIGHT',
},
['buffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 300,
['priority'] = 'Blacklist,Dispellable,PlayerBuffs,TurtleBuffs' --NamePlate EnemyPlayer Buffs
},
},
['debuffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,blockNoDuration,Personal,Boss,CCDebuffs,RaidDebuffs' --NamePlate EnemyPlayer Debuffs
},
},
['name'] = {
['useClassColor'] = true,
},
},
['FRIENDLY_NPC'] = {
['portrait'] = {
['enable'] = false,
['width'] = 30,
['height'] = 24,
},
['healthbar'] = {
['enable'] = false,
['height'] = 10,
['width'] = 150,
['healPrediction'] = true,
['glowStyle'] = 'TARGET_THREAT',
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
},
['showName'] = true,
['showLevel'] = true,
['powerbar'] = {
['enable'] = false,
['hideWhenEmpty'] = false,
['costPrediction'] = true,
['height'] = 8,
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
},
['castbar'] = {
['enable'] = false,
['height'] = 8,
['sourceInterrupt'] = false,
['sourceInterruptClassColor'] = true,
['displayTarget'] = false,
['hideSpellName'] = false,
['hideTime'] = false,
['castTimeFormat'] = 'CURRENT',
['channelTimeFormat'] = 'CURRENT',
['timeToHold'] = 0,
['iconPosition'] = 'RIGHT',
},
['buffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,blockNoDuration,Personal,TurtleBuffs' --NamePlate FriendlyNPC Buffs
},
},
['debuffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,Boss,CCDebuffs,RaidDebuffs,Dispellable' --NamePlate FriendlyNPC Debuffs
},
},
['eliteIcon'] = {
['enable'] = false,
['size'] = 20,
['position'] = 'RIGHT',
['xOffset'] = 15,
['yOffset'] = 0,
},
},
['ENEMY_NPC'] = {
['portrait'] = {
['enable'] = false,
['width'] = 30,
['height'] = 24,
},
['minors'] = true,
['healthbar'] = {
['enable'] = true,
['height'] = 10,
['width'] = 150,
['healPrediction'] = true,
['glowStyle'] = 'TARGET_THREAT',
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
},
['showName'] = true,
['showLevel'] = true,
['powerbar'] = {
['enable'] = false,
['hideWhenEmpty'] = false,
['costPrediction'] = true,
['height'] = 8,
['text'] = {
['enable'] = false,
['format'] = 'CURRENT',
},
},
['castbar'] = {
['enable'] = true,
['height'] = 8,
['sourceInterrupt'] = false,
['sourceInterruptClassColor'] = true,
['displayTarget'] = false,
['hideSpellName'] = false,
['hideTime'] = false,
['castTimeFormat'] = 'CURRENT',
['channelTimeFormat'] = 'CURRENT',
['timeToHold'] = 0,
['iconPosition'] = 'RIGHT',
},
['buffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,RaidBuffsElvUI,blockNoDuration,PlayerBuffs,TurtleBuffs,CastByUnit' --NamePlate EnemyNPC Buffs
},
},
['debuffs'] = {
['enable'] = true,
['numAuras'] = 4,
['baseHeight'] = 18,
["widthOverride"] = 0,
['filters'] = {
['minDuration'] = 0,
['maxDuration'] = 0,
['priority'] = 'Blacklist,Personal,CCDebuffs' --NamePlate EnemyNPC Debuffs
},
},
['eliteIcon'] = {
['enable'] = false,
['size'] = 20,
['position'] = 'RIGHT',
['xOffset'] = 15,
['yOffset'] = 0,
},
['detection'] = {
['enable'] = true,
},
},
},
};
P['nameplates_v1']["nameplateOverlapH"] = 0.3
P['nameplates_v1']["nameplateOverlapV"] = 0.7
P['nameplates_v1']["font"] = 'EUI'
P['nameplates_v1']["durationFont"] = 'EUI'
P['nameplates_v1']["stackFont"] = 'EUI'
P['nameplates_v1']["motionType"] = 'OVERLAP'
P['nameplates_v1']["clampToScreen"] = true
P['nameplates_v1']["units"]['PLAYER']['healthbar']['text']['enable'] = true
P['nameplates_v1']["units"]['PLAYER']['healthbar']['text']['format'] = 'CURRENT_MAX'
P['nameplates_v1']["units"]['PLAYER']['buffs']['numAuras'] = 6
P['nameplates_v1']["units"]['PLAYER']['buffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['PLAYER']['debuffs']['numAuras'] = 6
P['nameplates_v1']["units"]['PLAYER']['debuffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['HEALER']['healthbar']['text']['enable'] = true
P['nameplates_v1']["units"]['HEALER']['healthbar']['text']['format'] = 'CURRENT_MAX'
P['nameplates_v1']["units"]['HEALER']['buffs']['numAuras'] = 6
P['nameplates_v1']["units"]['HEALER']['buffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['HEALER']['debuffs']['numAuras'] = 6
P['nameplates_v1']["units"]['HEALER']['debuffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['FRIENDLY_PLAYER']['healthbar']['text']['enable'] = true
P['nameplates_v1']["units"]['FRIENDLY_PLAYER']['healthbar']['text']['format'] = 'CURRENT_MAX'
P['nameplates_v1']["units"]['FRIENDLY_PLAYER']['buffs']['numAuras'] = 6
P['nameplates_v1']["units"]['FRIENDLY_PLAYER']['buffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['FRIENDLY_PLAYER']['debuffs']['numAuras'] = 6
P['nameplates_v1']["units"]['FRIENDLY_PLAYER']['debuffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['ENEMY_PLAYER']['healthbar']['text']['enable'] = true
P['nameplates_v1']["units"]['ENEMY_PLAYER']['healthbar']['text']['format'] = 'CURRENT_MAX'
P['nameplates_v1']["units"]['ENEMY_PLAYER']['buffs']['numAuras'] = 6
P['nameplates_v1']["units"]['ENEMY_PLAYER']['buffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['ENEMY_PLAYER']['debuffs']['numAuras'] = 6
P['nameplates_v1']["units"]['ENEMY_PLAYER']['debuffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['FRIENDLY_NPC']['healthbar']['text']['enable'] = true
P['nameplates_v1']["units"]['FRIENDLY_NPC']['healthbar']['text']['format'] = 'CURRENT_MAX'
P['nameplates_v1']["units"]['FRIENDLY_NPC']['buffs']['numAuras'] = 6
P['nameplates_v1']["units"]['FRIENDLY_NPC']['buffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['FRIENDLY_NPC']['debuffs']['numAuras'] = 6
P['nameplates_v1']["units"]['FRIENDLY_NPC']['debuffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['ENEMY_NPC']['healthbar']['text']['enable'] = true
P['nameplates_v1']["units"]['ENEMY_NPC']['healthbar']['text']['format'] = 'CURRENT_MAX'
P['nameplates_v1']["units"]['ENEMY_NPC']['buffs']['numAuras'] = 6
P['nameplates_v1']["units"]['ENEMY_NPC']['buffs']['baseHeight'] = 26
P['nameplates_v1']["units"]['ENEMY_NPC']['debuffs']['numAuras'] = 6
P['nameplates_v1']["units"]['ENEMY_NPC']['debuffs']['baseHeight'] = 26
P['nameplates_v1'].font = "EUI"
P['nameplates_v1'].fontSize = 12
P['nameplates_v1'].fontOutline = 'OUTLINE'
P['nameplates_v1'].auraTimeOffsetX = 1
P['nameplates_v1'].auraTimeOffsetY = 1
P['nameplates_v1'].auraCountOffsetX = 0
P['nameplates_v1'].auraCountOffsetY = 0
P['nameplates_v1']['targetGlow_y'] = 4;
P['nameplates_v1']['targetGlow_x'] = 4;
P['nameplates_v1']['targetGlow_y_size'] = 45;
P['nameplates_v1']['targetGlow_x_size'] = 45;
P['nameplates_v1']['topArrowType'] = 'nameplateTargetIndicator';
P['nameplates_v1']['leftArrowType'] = '';
P['nameplates_v1']['targetIndicator'] = {
['enable'] = false,
['style'] = 'arrow',
['color'] = {r= 1, g = 1, b = 1},
['width'] = 50,
['height'] = 50,
['yOffset'] = 0,
['xOffset'] = 0
}
P['nameplates_v1'].QuestIcon = {
['enable'] = true,
['xOffset'] = 2,
['yOffset'] = 0,
['size'] = 22,
}
G["profileCopy"]["nameplates_v1"] = {
["general"] = true,
["cooldown"] = true,
["classbar"] = true,
["reactions"] = true,
["healPrediction"] = true,
["threat"] = true,
["units"] = {
["PLAYER"] = true,
["HEALER"] = true,
["FRIENDLY_PLAYER"] = true,
["ENEMY_PLAYER"] = true,
["FRIENDLY_NPC"] = true,
["ENEMY_NPC"] = true,
},
}
V['nameplates_v1'] = {
['enable'] = false,
}
|
require 'lib.middleclass'
require 'TextInput'
require "level1"
require "level2"
require "level3"
http = require("socket.http")
function love.load()
time = 0
startingtime = 60
countdown = startingtime
restarttime = 0
score = 0
level = 1
gameOver = false
hasMustache = false
inputActive = false
HighScores = {};
getHighScores();
love.physics.setMeter(64) --the height of a meter our worlds will be 64px
objects = {}
blockobjects = {}
world = level1(level);
--initial graphics setup
love.graphics.setBackgroundColor(0.1, 0.1, 0.8)
love.window.setMode(650, 650) --set the window dimensions to 650 by 650
-- Physics callbacks
world:setCallbacks( beginContact, endContact, preSolve, postSolve )
keysicon = love.graphics.newImage( "keys.png" )
adicon = love.graphics.newImage( "ad.png" )
bigMustache = love.graphics.newImage( "Mustache.png" )
smallMustache = love.graphics.newImage( "SmallMustache.png" )
hasMustache = false;
-- Sounds
bounce = love.audio.newSource("319760__zmobie__basketball-6.wav", "static")
tonk = love.audio.newSource("3543__eliasheuninck__tonk3.wav", "static")
yeah = love.audio.newSource("437656__dersuperanton__yeah-deep-voice-vocal.wav", "static")
newBounce = true
gameOver = false
-- input
state = "none"
textbox = TextInput(
love.graphics.getWidth()/2 - 150,
love.graphics.getHeight()/2 - 150,
11,
300,
function ()
state = "done"
end
)
love.keyboard.setKeyRepeat(true) -- This is required if you want to hold down keys to spam them
-- Font
mainFont = love.graphics.newFont(32)
smallFont = love.graphics.newFont(24)
-- Shader
color_shader = love.graphics.newShader([[
vec4 effect ( vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords ) {
vec4 pixel = Texel(texture, texture_coords );
return vec4(color.r, color.g, color.b, pixel.a);
}
]])
gradient_shader = love.graphics.newShader([[
vec4 effect ( vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords ) {
vec4 pixel = Texel(texture, texture_coords );
float factor = screen_coords.y/love_ScreenSize.y;
return vec4(color.r * factor, color.g * factor, color.b * factor, pixel.a);
}
]])
glow_shader = love.graphics.newShader([[
extern vec2 size = vec2(170, 85);
extern number factor = 0;
vec2 clamp(vec2 pos) {
number x = pos.x;
number y = pos.y;
if (x < 0.0) x = 0.0;
if (y < 0.0) y = 0.0;
if (x > 1.0) x = 1.0;
if (y > 1.0) y = 1.0;
return vec2(x, y);
}
vec4 effect ( vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords ) {
number distance = 1.0;
vec4 pixelcolor = Texel(texture, texture_coords );
if (pixelcolor.a == 0) {
for (number x = -6.0 ; x <= 6.0; x++)
for (number y = -6.0 ; y <= 6.0; y++) {
vec4 surrondingcolor = Texel(texture, clamp(vec2(texture_coords.x + x/size.x, texture_coords.y + y/size.y)));
if (surrondingcolor.a > 0.0) {
number x1 = x/size.x;
number y1 = y/size.y;
number dist = sqrt( x1*x1 + y1*y1 ) * (size.x / 4);
if (dist < distance) {
distance = dist;
}
}
}
if (distance < 1.0)
distance = distance * factor;
return vec4(color.r,color.g - distance/2,color.b,1.0 - distance);
} else {
return Texel(texture, texture_coords );;
}
}
]])
end
function fistLevel()
selectlevel = clamp(1, level % 4, 3);
if selectlevel == 1 then level1_delete(world);
elseif selectlevel == 2 then level2_delete(world)
elseif selectlevel == 3 then level3_delete(world)
end
level = 1
objects = {}
blockobjects = {}
world = level1(level);
score = 0;
-- Physics callbacks
world:setCallbacks( beginContact, endContact, preSolve, postSolve )
time = 0
startingtime = 60 - level
countdown = startingtime
restarttime = 0
gameOver = false
hasMustache = false
state = "none"
end
function nextLevel()
selectlevel = clamp(1, level % 4, 3);
if selectlevel == 1 then level1_delete(world);
elseif selectlevel == 2 then level2_delete(world)
elseif selectlevel == 3 then level3_delete(world)
end
level = level + 1
objects = {}
blockobjects = {}
selectlevel = clamp(1, level % 4, 3);
if selectlevel == 1 then world = level1(level);
elseif selectlevel == 2 then world = level2(level)
elseif selectlevel == 3 then world = level3(level)
end
-- Physics callbacks
world:setCallbacks( beginContact, endContact, preSolve, postSolve )
time = 0
startingtime = 60 - level
countdown = startingtime
restarttime = 0
gameOver = false
hasMustache = false
end
function love.update(dt)
time = time + dt;
world:update(dt) --this puts the world into motion
if state == "input" then
textbox:step(dt)
return
elseif state == "done" then
player = textbox.text
table.insert(HighScores, {player, score})
table.sort(HighScores, scoresort)
state = "highscores"
restarttime = time
sendHighScore(player, score)
getHighScores()
elseif state == "highscores" then
if (time - restarttime > 3.0) then
fistLevel()
end
return
end
--here we are going to create some keyboard events
if love.keyboard.isDown("right") then --press the right arrow key to push the ball to the right
objects.ball.body:applyForce(100000*dt, 0)
elseif love.keyboard.isDown("left") then --press the left arrow key to push the ball to the left
objects.ball.body:applyForce(-100000*dt, 0)
end
lastblock = blockobjects[#blockobjects]
if lastblock then
vx, vy = lastblock.body:getLinearVelocity()
--if (vy < -10) then -- falling
if love.keyboard.isDown("a") then --press the right arrow key to push the ball to the right
lastblock.body:applyAngularImpulse( -20000*dt )
elseif love.keyboard.isDown("d") then --press the left arrow key to push the ball to the left
lastblock.body:applyAngularImpulse( 20000*dt )
end
lastblock.body:setAngularVelocity(clamp(-100, lastblock.body:getAngularVelocity(), 100))
--end
end
vx, vy = objects.ball.body:getLinearVelocity()
objects.ball.body:setLinearVelocity(clamp(-200, vx, 200), vy);
if objects.ball.body:getY() > 650 then
GameOver()
elseif objects.ball.body:getY() < 80 and objects.ball.body:getX() > 275 and objects.ball.body:getX() < 375 then
LevelWon()
end
if (hasMustache) then
glow_shader:send("factor",0.0)
else
local factor = math.abs(math.cos(time + time * time/(startingtime*2))); --so it keeps going/repeating
glow_shader:send("factor",factor)
end
if gameOver or hasMustache then
if (time - restarttime > 3.0) then
if gameOver then CheckHighScore()
else nextLevel()
end
end
elseif countdown > 0 then
countdown = math.ceil(startingtime - time)
if countdown == 0 then
GameOver()
end
end
end
function love.draw()
love.graphics.setColor(0.1, 0.1, 0.8)
love.graphics.setShader(gradient_shader)
love.graphics.rectangle("fill", 0, 0, 650, 650)
love.graphics.setShader()
love.graphics.setFont(smallFont)
love.graphics.setColor(0, 0.7, 0, 1)
love.graphics.print("Score: "..score, 10, 10, 0, 1)
if (#HighScores) > 1 then
love.graphics.print(HighScores[1][1]..": "..HighScores[1][2], 10, 40, 0, 1)
end
love.graphics.print("Time: "..countdown, 500, 10, 0, 1)
love.graphics.print("Level: "..level, 500, 40, 0, 1)
love.graphics.setFont(mainFont)
if (hasMustache) then
love.graphics.setColor(0, 0.5, 0, 1)
love.graphics.print("Oh Yeah!", 250, 200, 0, 1)
elseif (gameOver) then
love.graphics.setColor(0.5, 0, 0, 1)
love.graphics.setShader(glow_shader)
love.graphics.print("Game Over", 250, 200, 0, 1)
love.graphics.setShader()
elseif (time < 3.0) then
love.graphics.setColor(0, 0.5, 0, (3.0 - time))
love.graphics.print("Get that mustache!", 180, 130, 0, 1)
if (level == 1) then
love.graphics.setColor(0.5, 0.5, 0.5, (2.0 - time))
love.graphics.draw(adicon, 75, 125)
love.graphics.draw(keysicon, 75, 250)
end
end
love.graphics.setLineWidth( 2.0 )
love.graphics.setColor(0.0, 1.0, 0.0) -- set the drawing color to green for the ground
love.graphics.polygon("fill", objects.ground.body:getWorldPoints(objects.ground.shape:getPoints())) -- draw a "filled in" polygon using the ground's coordinates
love.graphics.setColor(0.0, 1.0, 0.0) -- set the drawing color to green for the landscape
love.graphics.polygon("fill", objects.landscape.body:getWorldPoints(objects.landscape.shape:getPoints()))
love.graphics.polygon("fill", objects.landscape2.body:getWorldPoints(objects.landscape2.shape:getPoints()))
love.graphics.setColor(1.0, 0.5, 0.0) --set the drawing color to orange for the ball
love.graphics.circle("fill", objects.ball.body:getX(), objects.ball.body:getY(), objects.ball.shape:getRadius())
love.graphics.setColor(0.0, 1.0, 1.0) -- set the drawing color to cyan for the blocks
for k,v in pairs(blockobjects) do
love.graphics.polygon("line", v.body:getWorldPoints(v.shape:getPoints()))
end
if (hasMustache) then
love.graphics.setColor(0.5, 0.5, 0.1, 1.0)
--love.graphics.setShader(color_shader)
glow_shader:send("size", {smallMustache:getDimensions()})
love.graphics.draw(smallMustache, objects.ball.body:getX()-20, objects.ball.body:getY())
--love.graphics.setShader()
else
love.graphics.setColor(1.0, 0.5, 0.1, 1.0)
love.graphics.setShader(glow_shader)
glow_shader:send("size", {bigMustache:getDimensions()})
love.graphics.draw(bigMustache, (650-170)/2, 10)
love.graphics.setShader()
end
if state == "input" then
textbox:draw()
elseif state == "highscores" then
love.graphics.setColor(0.3, 0.4, 0.1, 0.9)
love.graphics.setShader(gradient_shader)
love.graphics.rectangle("fill", 100 , 100 , 450, 400)
love.graphics.setShader()
texty = 120
love.graphics.printf("Top Scores", 120, texty ,300)
texty = texty + 50
for i,v in ipairs(HighScores) do
if i < 10 then
love.graphics.printf(v[1], 120, texty ,300)
love.graphics.printf(v[2], 420, texty ,300)
texty = texty + 35
else
HighScores[i] = nil
end
end
end
end
function love.textinput( text )
if state == "input" then
textbox:textinput(text)
end
end
function love.keypressed(key)
if state == "input" then
textbox:keypressed(key)
return
end
if key == 'up' and newBounce then
newBounce = false;
objects.ball.body:applyLinearImpulse(0, -400)
vx, vy = objects.ball.body:getLinearVelocity()
objects.ball.body:setLinearVelocity(vx, clamp(-500, vy, -450));
end
if key == 'down' or key == 's' then
newblock = {}
newblock.body = love.physics.newBody(world, objects.ball.body:getX() -50 + love.math.random( ) * 100, 100, "dynamic")
rand = love.math.random()
if rand > 0.6 then
newblock.shape = love.physics.newRectangleShape(0, 0, 150, 25)
elseif rand > 0.3 then
newblock.shape = love.physics.newRectangleShape(0, 0, 25, 75)
else
newblock.shape = love.physics.newRectangleShape(0, 0, 50, 50)
end
newblock.fixture = love.physics.newFixture(newblock.body, newblock.shape, 2 + level)
newblock.fixture:setFriction(0.5)
newblock.fixture:setRestitution(0.4)
table.insert(blockobjects, newblock)
end
if key == "escape" then
love.event.quit()
end
end
function clamp(min, val, max)
return math.max(min, math.min(val, max));
end
function beginContact(a, b, coll)
if (a == objects.ball.fixture or b == objects.ball.fixture) then
if (a == objects.mustache.fixture or b == objects.mustache.fixture) then
LevelWon()
else
newBounce = true
vx, vy = objects.ball.body:getLinearVelocity()
bounce:setVolume(math.sqrt(vy*vy+vx*vx)/500)
bounce:play()
end
else
vx1, vy1 = a:getBody():getLinearVelocity()
vx2, vy2 = b:getBody():getLinearVelocity()
speed1 = math.sqrt(vy1*vy1+vx1*vx1)
speed2 = math.sqrt(vy2*vy2+vx2*vx2)
tonk:setVolume(math.max(speed1, speed2)/500)
tonk:play()
end
end
function GameOver()
if gameOver == false and hasMustache == false then
gameOver = true
restarttime = time
end
end
function LevelWon()
if gameOver == false and hasMustache == false then
hasMustache = true
restarttime = time;
score = score + countdown;
yeah:play()
end
end
function CheckHighScore()
if score > 0 and (#HighScores < 10 or score > HighScores[10][2]) then
state = "input"
elseif (#HighScores) > 1 then
state = "highscores"
restarttime = time
else
fistLevel()
end
end
function scoresort(object1, object2)
return object1[2] > object2[2]
end
function string.explode(str, div)
--assert(type(str) == "string" and type(div) == "string", "invalid arguments")
local o = {}
while true do
local pos1,pos2 = str:find(div)
if not pos1 then
o[#o+1] = str
break
end
o[#o+1],str = str:sub(1,pos1-1),str:sub(pos2+1)
end
return o
end
function sendHighScore(player, score)
b, c, h = http.request {
url = "http://dreamlo.com/lb/NvaMfr7wn0GGV678xG-WUQ2_pjxJv3q0ijo0J8JUC-MA/add/"..player.."/"..score
}
end
function getHighScores()
b, c, h = http.request ("http://dreamlo.com/lb/5bf9359bb6397e00e093a29e/pipe/10")
lines = string.explode(b, "\n")
for i,v in pairs(lines) do
tbl = string.explode(v, "|")
if (tbl[1] ~= nil and tbl[2] ~= nil) then
HighScores[i] = {tbl[1],tonumber(tbl[2])}
end
end
end
|
MP = {}
MP.Config = {}
MP.Config.Locales = {
['alreadyRobbed'] = "¡Ya me han robado y ~r~no ~w~me queda dinero!",
['cashrecieved'] = 'Has robado:',
['currency'] = '€',
['no_cops'] = '~r~No ~w~hay suficientes ~b~policías',
['cop_msg'] = 'La cámara de seguridad ha tomado una foto del ladrón',
['kill_msg'] = 'La cámara de seguridad ha tomado una foto del asesino',
['set_waypoint'] = 'Establecer la ruta en el GPS',
['robbery'] = 'Robo en progreso',
['kill'] = 'Asesinato',
['too_far_bag'] = 'Estás demasiado lejos de la bolsa y las ratas te han robado el dinero',
['walked_too_far'] = 'Has salido de la zona del robo'
}
local city = GetConvar("city", "")
if city == "Paleto Bay" then
MP.Config.Locations = {
["24/7"] = {
[1] = {
name = "24/7 Paleto",
coords = vector3(1727.57, 6415.1, 34.04),
heading = 237.46,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[2] = {
name = "LTD Grapeseed",
coords = vector3(1696.76, 4923.38, 41.06),
heading = 329.61,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[3] = {
name = "24/7 Palominio",
coords = vector3(2678.39, 3278.73, 54.24),
heading = 333.75,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[4] = {
name = "24/7 Paleto",
coords = vector3(160.21, 6641.65, 30.71),
heading = 225.06,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[5] = {
name = "Paleto Liquor",
coords = vector3(-161.03, 6321.16, 30.59),
heading = 316.35,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[6] = {
name = "24/7 Great Ocean",
coords = vector3(-2539.1, 2314.13, 32.41),
heading = 92.61,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
},
["Bank"] = {
[1] = {
name = "",
coords = vector3(0.0, 0.0, 0.0),
reward = 0,
time = 0,
waitTime = 0,
policeRequired = 0,
itemsRequired = {}
},
},
["GrandBank"] = {
[1] = {
name = "",
coords = vector3(0.0, 0.0, 0.0),
reward = 0,
time = 0,
waitTime = 0,
policeRequired = 0,
itemsRequired = {}
},
}
}
elseif city == "Los Santos" then
MP.Config.Locations = {
["24/7"] = {
[1] = {
name = "24/7 Paleto",
coords = vector3(-1486.29, -378.02, 39.16),
heading = 139.41,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[2] = {
name = "LTD Grapeseed",
coords = vector3(-1221.97, -908.29, 11.33),
heading = 29.16,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[3] = {
name = "24/7 Palominio",
coords = vector3(-706.13, -913.56, 18.22),
heading = 91.18,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[4] = {
name = "24/7 Paleto",
coords = vector3(-46.63, -1757.85, 28.42),
heading = 43.45,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[5] = {
name = "Paleto Liquor",
coords = vector3(24.48, -1347.24, 28.5),
heading = 260.75,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[6] = {
name = "24/7 Great Ocean",
coords = vector3(1134.16, -982.55, 45.42),
heading = 275.62,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[7] = {
name = "24/7 Great Ocean",
coords = vector3(1164.74, -322.63, 68.21),
heading = 102.17,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[8] = {
name = "24/7 Great Ocean",
coords = vector3(372.49, 326.39, 102.57),
heading = 256.84,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[9] = {
name = "24/7 Great Ocean",
coords = vector3(-2966.41, 390.99, 14.04),
heading = 85.62,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
[10] = {
name = "24/7 Great Ocean",
coords = vector3(2557.2, 380.76, 107.62),
heading = 352.01,
reward = {2500, 5000},
coolDown = 1800000,
policeRequired = 3,
robbed = false,
robbing = false,
},
},
["Bank"] = {
[1] = {
name = "",
coords = vector3(0.0, 0.0, 0.0),
reward = 0,
time = 0,
waitTime = 0,
policeRequired = 0,
itemsRequired = {}
},
},
["GrandBank"] = {
[1] = {
name = "",
coords = vector3(0.0, 0.0, 0.0),
reward = 0,
time = 0,
waitTime = 0,
policeRequired = 0,
itemsRequired = {}
},
}
}
end
|
local SceneEntityState = require "njli.statemachine.sceneentitystate"
local BoardselectSceneEntityState = {}
BoardselectSceneEntityState.__index = BoardselectSceneEntityState
local json = require('json')
setmetatable(BoardselectSceneEntityState, {
__index = SceneEntityState,
__call = function (cls, ...)
local self = setmetatable({}, cls)
self:create(...)
return self
end,
})
function BoardselectSceneEntityState:className()
return "BoardselectSceneEntityState"
end
function BoardselectSceneEntityState:class()
return self
end
function BoardselectSceneEntityState:superClass()
return SceneEntityState
end
function BoardselectSceneEntityState:isa(theClass)
local b_isa = false
local cur_class = theClass:class()
while ( nil ~= cur_class ) and ( false == b_isa ) do
if cur_class == theClass then
b_isa = true
else
cur_class = cur_class:superClass()
end
end
return b_isa
end
function BoardselectSceneEntityState:destroy()
print("BoardselectSceneEntityState:load()")
BoardselectSceneEntityState.__gc(self)
SceneEntityState.destroy(self)
end
function BoardselectSceneEntityState:create(init)
SceneEntityState.create(self, init)
print("BoardselectSceneEntityState:load()")
end
function BoardselectSceneEntityState:__gc()
end
function BoardselectSceneEntityState:__tostring()
return json:stringify(self)
end
function BoardselectSceneEntityState:getSceneState()
return SceneEntityState.getSceneState(self)
end
function BoardselectSceneEntityState:getEntityOwner()
return SceneEntityState.getEntityOwner(self)
end
function BoardselectSceneEntityState:isLoaded()
return SceneEntityState.isLoaded(self)
end
function BoardselectSceneEntityState:load()
SceneEntityState.load(self)
print("BoardselectSceneEntityState:load()")
end
function BoardselectSceneEntityState:unLoad()
SceneEntityState.unLoad(self)
print("BoardselectSceneEntityState:load()")
end
function BoardselectSceneEntityState:push()
SceneEntityState.push(self)
end
function BoardselectSceneEntityState:isIn()
return SceneEntityState.isIn(self)
end
function BoardselectSceneEntityState:enter()
print("BoardselectSceneEntityState:enter()")
end
function BoardselectSceneEntityState:update(timeStep)
print("BoardselectSceneEntityState:update("..timeStep..")")
end
function BoardselectSceneEntityState:exit()
print("BoardselectSceneEntityState:exit()")
end
function BoardselectSceneEntityState:onMessage(message)
print("BoardselectSceneEntityState:onMessage("..tostring(message)..")")
end
function BoardselectSceneEntityState:touchDown(touches)
print("BoardselectSceneEntityState:touchDown("..tostring(touches)..")")
end
function BoardselectSceneEntityState:touchUp(touches)
print("BoardselectSceneEntityState:touchUp("..tostring(touches)..")")
end
function BoardselectSceneEntityState:touchMove(touches)
print("BoardselectSceneEntityState:touchMove("..tostring(touches)..")")
end
function BoardselectSceneEntityState:touchCancelled(touches)
print("BoardselectSceneEntityState:touchCancelled("..tostring(touches)..")")
end
function BoardselectSceneEntityState:renderHUD()
print("BoardselectSceneEntityState:renderHUD()")
end
function BoardselectSceneEntityState:pause()
print("BoardselectSceneEntityState:pause()")
end
function BoardselectSceneEntityState:unPause()
print("BoardselectSceneEntityState:unPause()")
end
return BoardselectSceneEntityState
|
--
-- Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
-- Edition) available.
-- Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://opensource.org/licenses/MIT
--
-- 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 core = require("apisix.core")
local ck = require("resty.cookie")
local stringx = require('pl.stringx')
local jwt = require("apisix.plugins.bcs-auth.jwt")
local bklogin = require("apisix.plugins.bcs-auth.bklogin")
local resty_jwt = require("resty.jwt")
local ngx_decode_base64 = ngx.decode_base64
local RUN_ON_CE = "ce" -- 表示社区版
local TOKEN_TYPE_APIGW = "apigw"
local TOKEN_TYPE_BCS = "bcs"
local bcs_token_user_map_cache = core.lrucache.new({
ttl = 300,
count = 1000,
})
------------ LoginTicketAuthentication start ------------
local LoginTicketAuthentication = {}
-- 获取 cookie 中的用户凭证信息
function LoginTicketAuthentication:fetch_credential(conf, ctx)
local cookie, err = ck:new()
if not cookie then
return nil, err
end
local bk_ticket, err = cookie:get("bk_ticket")
if not bk_ticket then
if err and not stringx.startswith(err, "no cookie") then
core.log.error("failed to fetch bk_ticket: ", err)
end
end
local bk_uid, err = cookie:get("bk_uid")
if not bk_uid then
if err and not stringx.startswith(err, "no cookie") then
core.log.error("failed to fetch bk_uid: ", err)
end
end
return {user_token = bk_ticket, username = bk_uid}
end
function LoginTicketAuthentication:injected_user_info(credential, jwt_str, conf, ctx)
return {username = credential.username, usertype = "user"}
end
function LoginTicketAuthentication:get_jwt(credential, conf)
return jwt:get_jwt_from_redis(credential, conf, "bcs_auth:session_id:", true, bklogin.get_username_for_ticket)
end
------------ LoginTicketAuthentication end ------------
------------ LoginTokenAuthentication start ------------
local LoginTokenAuthentication = {}
-- 获取 cookie 中的用户凭证信息
function LoginTokenAuthentication:fetch_credential(conf, ctx)
local cookie, err = ck:new()
if not cookie then
return nil, err
end
local bk_token, err = cookie:get("bk_token")
if not bk_token then
if err and not stringx.startswith(err, "no cookie") then
core.log.error("failed to fetch bk_token: ", err)
end
end
return {user_token = bk_token}
end
function LoginTokenAuthentication:injected_user_info(credential, jwt_str, conf, ctx)
return {username = bklogin.get_username_for_token(credential, conf.bk_login_host), usertype = "user"}
end
function LoginTokenAuthentication:get_jwt(credential, conf)
return jwt:get_jwt_from_redis(credential, conf, "bcs_auth:session_id:", true, bklogin.get_username_for_token)
end
------------ LoginTokenAuthentication end ------------
------------ TokenAuthentication start ------------
local TokenAuthentication = {}
function TokenAuthentication:fetch_credential(conf, ctx)
local auth_header = core.request.header(ctx, "Authorization")
if not auth_header then
return {user_token = nil}
end
local m, err = ngx.re.match(auth_header, "Bearer\\s(.+)", "jo")
if err then
-- error authorization
return {user_token = nil}
end
return {user_token = m[1], token_type = TOKEN_TYPE_BCS}
end
local function get_username_by_TokenAuthentication_jwt(jwt_str)
local jwt_obj = resty_jwt:load_jwt(jwt_str)
if not jwt_obj then
core.log.error("load jwt from apigw jwt token failed, jwt token:"..jwt_str)
return nil, ""
end
return jwt_obj.payload, nil
end
function TokenAuthentication:injected_user_info(credential, jwt_str, conf, ctx)
local payload = bcs_token_user_map_cache(credential.user_token, nil, get_username_by_TokenAuthentication_jwt, jwt_str)
if not payload or not payload.sub_type then
core.log.warn("no username can be found for token " .. req.user_token .. ",payload: " .. core.json.encode(payload, true))
end
local retV = {}
retV["usertype"] = payload.sub_type
if payload.username and #payload.username > 0 then
retV["username"] = payload.username
else
retV["username"] = payload.client_id
end
return retV
end
function TokenAuthentication:get_jwt(credential, conf)
return jwt:get_jwt_from_redis(credential, conf, "bcs_auth:token:", false)
end
------------ TokenAuthentication end ------------
------------ APIGWAuthentication start ------------
local APIGWAuthentication = {}
-- 获取 cookie 中的用户凭证信息
function APIGWAuthentication:fetch_credential(conf, ctx)
local jwt_str = core.request.header(ctx, "X-Bkapi-JWT")
if not jwt_str then
return TokenAuthentication:fetch_credential(conf, ctx)
end
local key = conf.bkapigw_jwt_verify_key
local jwt_obj = resty_jwt:load_jwt(jwt_str)
if not jwt_obj then
core.log.error("load jwt from apigw jwt token failed, jwt token:"..jwt_str)
core.response.exit(401, "Bad Bkapi JWT token")
end
if not key then
core.log.error("no verify key for apigw jwt token, jwt token:"..jwt_str)
core.response.exit(500, "BCS Auth Plugin Error")
end
local decode_res = ngx_decode_base64(key)
if decode_res ~= nil then
key = decode_res
end
local jwt_obj = resty_jwt:verify_jwt_obj(key, jwt_obj)
if not jwt_obj or not jwt_obj.verified or not jwt_obj.valid then
core.log.error("verify apigw jwt token failed, jwt token:"..jwt_str)
if jwt_obj then
core.log.error("verify apigw jwt token failed, reason:"..jwt_obj.reason)
end
core.response.exit(401, "Bad Bkapi JWT token")
end
-- situation that anonymous requests from bkapigw will carry a token with all fields unverified, fallback to bcs token auth
if jwt_obj.payload.app and not jwt_obj.payload.app.verified and jwt_obj.payload.user and not jwt_obj.payload.user.verified then
core.log.warn("Neither app nor user has been verified, jwt obj: " .. core.json.encode(jwt_obj))
return TokenAuthentication:fetch_credential(conf, ctx)
end
local redis_key = jwt_obj.payload.app.app_code
local credential = {token_type = TOKEN_TYPE_APIGW}
credential["user_token"] = {
bk_app_code = jwt_obj.payload.app.app_code
}
if jwt_obj.payload.user and jwt_obj.payload.user.verified then
credential["user_token"]["username"] = jwt_obj.payload.user.username
redis_key = redis_key .. "," .. jwt_obj.payload.user.username
end
credential["redis_key"] = redis_key
core.request.set_header(ctx, "X-Bkapi-JWT", nil)
return credential
end
function APIGWAuthentication.get_userinfo(credential, useless)
return credential.user_token
end
function APIGWAuthentication:injected_user_info(credential, jwt_str, conf, ctx)
if credential.token_type == TOKEN_TYPE_BCS then
return TokenAuthentication:injected_user_info(credential, jwt_str, conf, ctx)
end
if credential.user_token.username then
return {username = credential.user_token.username, usertype = "user"}
end
return {username = credential.user_token.bk_app_code, usertype = "bk_app"}
end
function APIGWAuthentication:get_jwt(credential, conf)
if not credential or not credential.user_token then
return nil
end
if credential.token_type == TOKEN_TYPE_BCS then
return TokenAuthentication:get_jwt(credential, conf)
end
return jwt:get_jwt_from_redis(credential, conf, "bcs_auth:apigw:", true, APIGWAuthentication.get_userinfo)
end
------------ APIGWAuthentication end ------------
local _M = {}
function _M:new(use_login, run_env)
local o = {}
setmetatable(o, self)
self.__index = self
if not use_login then
self.backend = APIGWAuthentication
return o
end
if run_env == RUN_ON_CE then
self.backend = LoginTokenAuthentication
else
self.backend = LoginTicketAuthentication
end
return o
end
function _M:authenticate(conf, ctx)
local credential = self.backend:fetch_credential(conf, ctx)
if not credential or not credential.user_token then
return nil
end
local jwt_str = self.backend:get_jwt(credential, conf)
-- 向上下文注入用户信息
if jwt_str then
local userinfo = self.backend:injected_user_info(credential, jwt_str, conf, ctx)
if not userinfo then
core.log.error("generate userinfo failed with credential " .. core.json.encode(credential) .. ", jwt: " .. jwt_str)
return jwt_str
end
ctx.var["bcs_usertype"] = userinfo.usertype
ctx.var["bcs_username"] = userinfo.username
core.ctx.register_var("bcs_username", function(ctx)
return ctx.var.bcs_username
end)
core.ctx.register_var("bcs_usertype", function(ctx)
return ctx.var.bcs_usertype
end)
end
return jwt_str
end
return _M
|
--[[
libFlashTime v0.2
Copyright (c) 2015, GPS_NMEA
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--]]
local FlashTime = {}
--FAT形式のファイルアクセス時間を生成する
function FlashTime.GetFATtimeFromLocalTime(Year,Month,Day,Hour,min,sec)
local Year_bit = bit32.band((Year - 1980),0x7F);
local Month_bit = bit32.band(Month,0x0F);
local Day_bit = bit32.band(Day,0x3F);
local Hour_bit = bit32.band(Hour,0x1F);
local min_bit = bit32.band(min,0x3F);
local sec_bit = bit32.band(sec/2,0x1F);
local YMD_bits = bit32.bor(bit32.lshift(Year_bit,9),bit32.lshift(Month_bit,5),Day_bit);
local HMS_bits = bit32.bor(bit32.lshift(Hour_bit,11),bit32.lshift(min_bit,5),sec_bit);
return YMD_bits,HMS_bits;
end
--FAT形式のファイルアクセス時間を分解する
function FlashTime.GetLocalTimeFromFATtime(Fat_binary_time)
local Year = bit32.band (bit32.rshift(Fat_binary_time, 9+16),0x7F) + 1980;
local Month = bit32.band (bit32.rshift(Fat_binary_time, 5+16),0x0F);
local Day = bit32.band (bit32.rshift(Fat_binary_time,0+16),0x1F);
local Hour = bit32.band (bit32.rshift(Fat_binary_time, 11),0x1F);
local min = bit32.band (bit32.rshift(Fat_binary_time, 5),0x3F);
local sec = bit32.band (Fat_binary_time,0x1F)*2; --FAT時間は秒数が2秒刻み
return Year,Month,Day,Hour,min,sec;
end
--FlashAirのRTCに登録
function FlashTime.SetTime(Year,Month,Day,Hour,min,sec)
local YMD,HMS = FlashTime.GetFATtimeFromLocalTime(Year,Month,Day,Hour,min,sec);
fa.SetCurrentTime(YMD,HMS);
end
--適当なファイルを生成して時間を得る
function FlashTime.GetTime()
local time_file = io.open("GetFatTimeTemporaryFile","w");
time_file:close();
local now_fat_time = lfs.attributes("GetFatTimeTemporaryFile")
local Year,Month,Day,Hour,min,sec = FlashTime.GetLocalTimeFromFATtime(now_fat_time.modification);
fa.remove("GetFatTimeTemporaryFile");
return Year,Month,Day,Hour,min,sec;
end
--時間を日本形式で表示
function FlashTime.ShowTime()
Year,Month,Day,Hour,min,sec = FlashTime.GetTime();
print(Year.."年"..Month.."月"..Day.."日"..Hour.."時"..min.."分"..sec.."秒");
end
--NICT 国立研究開発法人 情報通信研究機構の日本標準時配信サーバー(HTTP版)を使って時刻合わせする。
function FlashTime.SetNICT()
local b,s,h;
local i;
for i=0,10 do
b,s,h = fa.request("http://ntp-a1.nict.go.jp/cgi-bin/time");
if(s == 200)then break; end;
sleep(1000);
end
if(s ~= 200)then return nil; end;
local itr = string.gmatch (b,"%g+");
local DOTW= itr();
local str_moth= itr();
local Day= itr();
local hms= itr();
local itr_hms = string.gmatch (hms,"[^:]+");
local Hour = itr_hms();
local min = itr_hms();
local sec = itr_hms();
local Year= itr();
local month_table = {Jan=1,Feb=2,Mar=3,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9,Oct=10,Nov=11,Dec=12};
local Month = month_table[str_moth];
FlashTime.SetTime(Year,Month,Day,Hour,min,sec);
return true;
end
return FlashTime;
--[[
--FlashAirに任意の時刻を設定する
FlashTime.SetTime(2009,5,30,8,30,00);
FlashTime.ShowTime();
--FlashAirに自動で現在時刻を設定する(要STAモード)
FlashTime.SetNICT();
FlashTime.ShowTime();
--ファイルタイムスタンプを生成する
fattime,fattime2 = FlashTime.GetFATtimeFromLocalTime(2009,5,30,8,30,00);
print(fattime,fattime2);
--ファイルタイムスタンプから時刻を得る
Year,Month,Day,Hour,min,sec = FlashTime.GetLocalTimeFromFATtime(bit32.bor(bit32.lshift(fattime,16),fattime2));
print(Year.."年"..Month.."月"..Day.."日"..Hour.."時"..min.."分"..sec.."秒");
]]
|
-- Script for getting resources from github
local args = {...}
if #args < 3 or #args > 4 then
print("Usage: github <user> <repo> <folder> [branch]")
return
end
local gh_username = args[1]
local gh_repo = args[2]
local gh_folder = args[3]
local gh_branch = nil
if args[4] then gh_branch = args[4] end
-- Construct url for raw github content
local gh_url = nil
if gh_branch then
gh_url = "https://raw.githubusercontent.com/" .. gh_username .. "/" ..
gh_repo .. "/" .. gh_branch .. "/" .. gh_folder .. "/"
else
gh_url = "https://raw.githubusercontent.com/" .. gh_username .. "/" ..
gh_repo .. "/main/" .. gh_folder .. "/"
end
print("Loading module from: " .. gh_url .. "fetch.lua")
-- Download fetch file
shell.run("delete fetch.lua")
shell.run("wget " .. gh_url .. "fetch.lua" .. " fetch.lua")
-- Load module information
local fetch = require("fetch")
-- Move to the modules specified location
shell.run("mkdir " .. gh_folder)
shell.run("cd " .. gh_folder)
-- Install module files
for i = 1, #fetch.files, 1 do
shell.run("delete " .. fetch.files[i])
shell.run("wget " .. gh_url .. fetch.files[i] .. " " .. fetch.files[i])
end
-- Create aliases for exposed lua files
shell.run("cd /")
for i = 1, #fetch.exposed, 1 do
local cmd = fetch.exposed[i]
shell.run("alias " .. cmd .. "/" .. gh_folder .. "/" .. cmd)
end
-- Install dependencies
for i = 1, #fetch.dependencies, 1 do
shell.run("/github " .. fetch.dependencies[i])
end
|
---
-- Premake script-side program entry point.
---
_EMPTY = setmetatable({}, {
__newindex = function ()
error('attempted to modify `_EMPTY`')
end
})
forceRequire('_G')
forceRequire('string')
forceRequire('table')
forceRequire('os')
forceRequire('io')
local main = require('main')
function _premake_main()
main.run()
end
|
if wmChat then
if IsValid(wmChat.dFrameHtml) then
wmChat.dFrameHtml:Remove()
end
end
GM = GM or GAMEMODE
local CONFIG = wmChat.config
wmChat.dFrameHtml = vgui.Create("DFrame")
if !IsValid(wmChat.dFrameHtml) then
wmChat.ChatLoaded = false
return
end
wmChat.ChatLoaded = true
wmChat.dFrameHtml.Paint = function(self) end
wmChat.dFrameHtml:SetTitle("")
wmChat.dFrameHtml:SetDraggable(false)
wmChat.dFrameHtml:SetDeleteOnClose(false)
wmChat.dFrameHtml:ShowCloseButton(false)
wmChat.dFrame = vgui.Create("DFrame", wmChat.dFrameHtml)
local top = 24
local bottom = 32
local sideThickness = 2
wmChat.dFrame.Paint = function(self, w, h)
// The top of the chatbox
draw.RoundedBoxEx(4, 0, 0, w, top, Color(50, 50, 50, 255), true, true, false, false)
// The bottom of the chatbox
draw.RoundedBoxEx(4, 0, h-bottom, w, bottom, Color(80, 80, 80, 220), false, false, true, true)
local totalHeightOfChat = h - (top+bottom)
// The sides of the chatbox
surface.SetDrawColor(Color(80, 80, 80, 220))
surface.DrawRect(0, top, sideThickness, totalHeightOfChat)
surface.DrawRect(w-sideThickness, top, sideThickness, totalHeightOfChat)
// The body of the chatbox
surface.SetDrawColor(Color(80, 80, 80, 150))
surface.DrawRect(sideThickness, top, w - sideThickness*2, totalHeightOfChat)
end
wmChat.dFrame:SetTitle(CONFIG.ChatBoxTitle)
wmChat.dFrame:SetDraggable(false)
wmChat.dFrame:SetDeleteOnClose(false)
wmChat.dFrame:ShowCloseButton(false)
local x, y = chat.GetChatBoxPos()
local length, height = chat.GetChatBoxSize()
wmChat.dFrame:SetSize(length, height)
wmChat.dFrameHtml:SetSize(length, height)
wmChat.dFrameHtml:SetPos(x, y)
wmChat.dTextEntry = vgui.Create("DTextEntry", wmChat.dFrame)
wmChat.dTextEntry:Dock(BOTTOM)
wmChat.dTextEntry.OnKeyCodeTyped = function(self, code)
if code == KEY_ESCAPE then
gui.HideGameUI()
wmChat.Close()
return true
end
if code == KEY_FIRST then
gui.HideGameUI()
end
if code == KEY_ENTER then
if string.Trim( self:GetText() ) != "" then
LocalPlayer():ConCommand("say \""..self:GetText().."\"")
end
wmChat.Close()
return true
end
end
wmChat.dTextEntry.AllowInput = function(self, char)
local value = self:GetValue()
if #value >= 255 then
return true
end
end
wmChat.dTextEntry:SetDrawBackground(false)
wmChat.dTextEntry.Paint = function(self, w, h)
surface.SetDrawColor(Color(225, 225, 225, 220))
surface.DrawRect(0, 0, w, h)
derma.SkinHook( "Paint", "TextEntry", self, w, h )
end
wmChat.dHtml = vgui.Create("DHTML", wmChat.dFrameHtml)
function wmChat.dHtml:Think()
self:MoveToAfter(wmChat.dFrame)
end
wmChat.dHtml:SetAllowLua(true)
wmChat.dHtml:Dock(TOP)
wmChat.dHtml:SetSize(length, height-(top+bottom+10))
wmChat.dHtml:OpenURL("asset://garrysmod/lua/wmChat/html/chat.lua")
wmChat.chatOpen = false
function wmChat.dFrame:Think()
wmChat.dFrame:MoveToBefore(wmChat.dHtml)
end
hook.Add("HUDShouldDraw", "wmOverrideHUD", function( name )
if name == "CHudChat" then
return false
end
end)
function wmChat.dFrame:Think()
if wmChat.chatOpen then
self.fadeVar = Lerp(RealFrameTime() * 30, self.fadeVar or 0, 255)
self:SetAlpha(self.fadeVar)
else
self.fadeVar = Lerp(RealFrameTime() * 30, self.fadeVar or 255, 0)
self:SetAlpha(self.fadeVar)
end
end
hook.Add("PlayerBindPress", "wmOverrideChatBind", function(ply, bind, pressed)
local bPublic = false
if bind != "messagemode" and bind != "messagemode2" then
return
elseif bind == "messagemode" then
bPublic = true
end
wmChat.Open(tonumber(bPublic))
return true
end)
function GM:ChatText( index, name, text, type )
local MessageConfig = wmChat.config.ConsoleMessageServer
MsgC(MessageConfig.head, MessageConfig.name .. " ", MessageConfig.body, text .. "\n")
local ServerMessageMetadata = {
["font-weight"] = "bold",
["color"] = wmChat.config.ServerMessageColor,
}
chat.AddText(ServerMessageMetadata, text)
end
|
local helpers = require('test.functional.helpers')(after_each)
local Screen = require('test.functional.ui.screen')
local clear, command = helpers.clear, helpers.command
local eval = helpers.eval
local eq = helpers.eq
local exc_exec = helpers.exc_exec
describe("'fillchars'", function()
local screen
before_each(function()
clear()
screen = Screen.new(25, 5)
screen:attach()
end)
after_each(function()
screen:detach()
end)
local function shouldfail(val,errval)
errval = errval or val
eq('Vim(set):E474: Invalid argument: fillchars='..errval,
exc_exec('set fillchars='..val))
end
describe('"eob" flag', function()
it("uses '~' by default", function()
eq('', eval('&fillchars'))
screen:expect([[
^ |
~ |
~ |
~ |
|
]])
end)
it('supports whitespace', function()
command('set fillchars=eob:\\ ')
screen:expect([[
^ |
|
|
|
|
]])
end)
it('supports multibyte char', function()
command('set fillchars=eob:ñ')
screen:expect([[
^ |
ñ |
ñ |
ñ |
|
]])
end)
it('handles invalid values', function()
shouldfail('eob:') -- empty string
shouldfail('eob:馬') -- doublewidth char
shouldfail('eob:å̲') -- composing chars
shouldfail('eob:xy') -- two ascii chars
shouldfail('eob:\255', 'eob:<ff>') -- invalid UTF-8
end)
end)
end)
|
#!/usr/bin/env lua
local sys = require"sys"
local thread = sys.thread
thread.init()
local NFORKS = 5
local NPHILOSOPHERS = NFORKS
local NSPAGHETTI = 3
-- Forks
local forks
do
forks = assert(thread.data_pool())
for i = 1, NFORKS do
forks:put(1)
end
end
-- Philosophers
do
local n = NPHILOSOPHERS
local rand = assert(sys.random())
local function philosopher(num)
print(num, "begin")
for i = 1, NSPAGHETTI do
forks:get()
if forks:get(0) then
print(num, "eat")
forks:put(1)
else
print(num, "skip")
end
forks:put(1)
thread.sleep(rand(10))
end
print(num, "end.")
n = n - 1
if n == 0 then
print"The End."
end
end
for i = 1, NPHILOSOPHERS do
assert(thread.run(philosopher, i))
end
end
assert(thread.self():wait())
|
-- KEYS[1]: full path of entry
local fullpath = KEYS[1]
-- KEYS[2]: full path of entry
local fullpath_list_key = KEYS[2]
-- KEYS[3]: dir of the entry
local dir_list_key = KEYS[3]
-- ARGV[1]: isSuperLargeDirectory
local isSuperLargeDirectory = ARGV[1] == "1"
-- ARGV[2]: name of the entry
local name = ARGV[2]
redis.call("DEL", fullpath, fullpath_list_key)
if not isSuperLargeDirectory and name ~= "" then
redis.call("ZREM", dir_list_key, name)
end
return 0
|
-- Copyright (c) 2017-present, Facebook, Inc.
-- All rights reserved.
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
local f = io.open(arg[1])
local unigram
repeat
local line = f:read('*line')
local n = tonumber(line:match('ngram%s+1%=(%S+)'))
if n then
unigram = n
io.stderr:write('#unigram ' .. unigram .. '\n')
io.stderr:flush()
end
if line:match('\\1%-grams%:') then
break
end
until not line
local words = {}
for i=1,unigram do
local line = f:read('*line')
local word = line:match('%S+%s+(%S+)')
if words[word] then
error('ouch')
end
if not word:match('<') then
words[word] = true
end
end
local sortedwords = {}
for word, _ in pairs(words) do
table.insert(sortedwords, word)
end
table.sort(
sortedwords,
function(a, b)
return a < b
end
)
for _, word in ipairs(sortedwords) do
print(word)
end
|
local json = config.json
return {
handler = function(context)
pcall(function()
context.input = json.decode(context.request.body)
end)
end,
options = {
predicate = function(context)
if config.default then
return true
end
local content = context.request.headers["content-type"]
if context.request.body then
if content then
return content:find("application/json")
else
return true
end
end
return false
end
}
}
|
local disable = function() cancelEvent() end
local pickupsDisabled = false
addEventHandler ( "onResourceStart", getResourceRootElement(getThisResource()),
function()
for i,player in ipairs(getElementsByType"player") do
spawnPlayer ( player, 2483, -1666, 21, 0, 0, 0, getWorkingDimension() )
end
disablePickups(true)
end
)
addEventHandler ( "onPlayerJoin", getRootElement(),
function()
if not g_in_test then
spawnPlayer ( source, 2483, -1666, 21, 0, 0, 0, getWorkingDimension() )
end
end
)
function disablePickups(bool)
if bool and not pickupsDisabled then
pickupsDisabled = true
addEventHandler ( "onPickupHit", getRootElement(), disable )
else
pickupsDisabled = false
removeEventHandler ( "onPickupHit", getRootElement(), disable )
end
end
|
local check = require "../src/check"
describe("The check module", function()
it("has a check directory predefined on the module", function()
local expected = os.getenv("HOME") .. "/.config/check-republic/checks"
local actual = check.directory
assert.are.equal(expected, actual)
end)
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.