repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
Vadavim/jsr-darkstar | scripts/globals/spells/bluemagic/seedspray.lua | 1 | 2409 | -----------------------------------------
-- Spell: Seedspray
-- Delivers a threefold attack. Additional effect: Weakens defense. Chance of effect varies with TP
-- Spell cost: 61 MP
-- Monster Type: Plantoids
-- Spell Type: Physical (Slashing)
-- Blue Magic Points: 2
-- Stat Bonus: VIT+1
-- Level: 61
-- Casting Time: 4 seconds
-- Recast Time: 35 seconds
-- Skillchain Element(s): Ice (Primary) and Wind (Secondary) - (can open Impaction, Compression, Fragmentation, Scission or Gravitation; can close Induration or Detonation)
-- Combos: Beast Killer
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_CRITICAL;
params.dmgtype = DMGTYPE_SLASH;
params.scattr = SC_GRAVITATION;
params.numhits = 3;
params.multiplier = 1.2;
params.tp150 = 2;
params.tp300 = 3.2;
params.azuretp = 1.25;
params.duppercap = 75;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.3;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
params.offcratiomod = MOD_RATT;
damage = BluePhysicalSpell(caster, target, spell, params);
local distance = utils.clamp(caster:checkDistance(target), 0, 100);
printf("distance: %f\n", distance);
damage = damage * (1 + (distance / 36));
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
local resist = applyResistance(caster,spell,target,30,BLUE_SKILL);
if (damage > 0 and resist >= 0.25) then
local typeEffect = EFFECT_DEFENSE_DOWN;
target:delStatusEffect(typeEffect);
target:addStatusEffect(typeEffect,15 + getSystemBonus(caster,target,spell) * 4,0,60 * resist);
target:setPendingMessage(278, EFFECT_DEFENSE_DOWN);
end
return damage;
end; | gpl-3.0 |
RJRetro/mame | 3rdparty/genie/tests/base/test_config_bug.lua | 9 | 3732 | T.config_bug_report = { }
local config_bug = T.config_bug_report
local vs10_helpers = premake.vstudio.vs10_helpers
local sln, prjA,prjB,prjC,prjD
function config_bug.teardown()
sln = nil
prjA = nil
prjB = nil
prjC = nil
prjD = nil
end
function config_bug.setup()
end
local config_bug_updated = function ()
local setCommonLibraryConfig = function()
configuration "Debug or Release"
kind "StaticLib"
configuration "DebugDLL or ReleaseDLL"
kind "SharedLib"
end
sln = solution "Test"
configurations { "Debug", "Release", "DebugDLL", "ReleaseDLL" }
language "C++"
prjA = project "A"
files { "a.cpp" }
setCommonLibraryConfig()
prjB = project "B"
files { "b.cpp" }
setCommonLibraryConfig()
configuration "SharedLib"
links { "A" }
prjC = project "C"
files { "c.cpp" }
setCommonLibraryConfig()
configuration "SharedLib"
links { "A", "B" }
prjD = project "Executable"
kind "WindowedApp"
links { "A", "B", "C" }
end
local kindSetOnConfiguration_and_linkSetOnSharedLibProjB = function (config_kind)
sln = solution "DontCare"
configurations { "DebugDLL"}
configuration "DebugDLL"
kind(config_kind)
prjA = project "A"
prjB = project "B"
configuration { config_kind }
links { "A" }
end
local sharedLibKindSetOnProject_and_linkSetOnSharedLibProjB = function ()
sln = solution "DontCare"
configurations { "DebugDLL" }
project "A"
prjB = project "B"
configuration "DebugDLL"
kind "SharedLib"
configuration "SharedLib"
links { "A" }
defines {"defineSet"}
end
function kind_set_on_project_config_block()
sln = solution "DontCare"
configurations { "DebugDLL" }
local A = project "A"
configuration "DebugDLL"
kind "SharedLib"
defines {"defineSet"}
return A
end
function config_bug.bugUpdated_prjBLinksContainsA()
config_bug_updated()
premake.bake.buildconfigs()
local conf = premake.getconfig(prjB,"DebugDLL","Native")
test.isnotnil(conf.links.A)
end
function config_bug.kindSetOnProjectConfigBlock_projKindEqualsSharedLib()
local proj = kind_set_on_project_config_block()
premake.bake.buildconfigs()
local conf = premake.getconfig(proj,"DebugDLL","Native")
test.isequal("SharedLib",conf.kind)
end
function config_bug.defineSetOnProjectConfigBlock_projDefineSetIsNotNil()
local proj = kind_set_on_project_config_block()
premake.bake.buildconfigs()
local conf = premake.getconfig(proj,"DebugDLL","Native")
test.isnotnil(conf.defines.defineSet)
end
function config_bug.defineSetInBlockInsideProject ()
sharedLibKindSetOnProject_and_linkSetOnSharedLibProjB()
premake.bake.buildconfigs()
local conf = premake.getconfig(prjB,"DebugDLL","Native")
test.isnotnil(conf.defines.defineSet)
end
function config_bug.whenKindSetOnProject_PrjBLinksContainsA()
sharedLibKindSetOnProject_and_linkSetOnSharedLibProjB()
premake.bake.buildconfigs()
local conf = premake.getconfig(prjB,"DebugDLL","Native")
test.isnotnil(conf.links.A)
end
function config_bug.whenKindSetOnConfiguration_prjBLinksContainsA_StaticLib()
-- sharedLibKindSetOnConfiguration_and_linkSetOnSharedLibProjB()
kindSetOnConfiguration_and_linkSetOnSharedLibProjB("StaticLib")
premake.bake.buildconfigs()
local config = premake.getconfig(prjB,"DebugDLL","Native")
test.isnotnil(config.links.A)
end
function config_bug.whenKindSetOnConfiguration_prjBLinksContainsA()
-- sharedLibKindSetOnConfiguration_and_linkSetOnSharedLibProjB()
kindSetOnConfiguration_and_linkSetOnSharedLibProjB("SharedLib")
premake.bake.buildconfigs()
local config = premake.getconfig(prjB,"DebugDLL","Native")
test.isnotnil(config.links.A)
end
| gpl-2.0 |
Vadavim/jsr-darkstar | scripts/zones/Bastok_Markets_[S]/TextIDs.lua | 7 | 1077 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 11215; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6384; -- Obtained: <item>
GIL_OBTAINED = 6385; -- Obtained <number> gil
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>
FISHING_MESSAGE_OFFSET = 7045; -- You can't fish here
-- Other Texts
KARLOTTE_DELIVERY_DIALOG = 10855; -- I am here to help with all your parcel delivery needs.
WELDON_DELIVERY_DIALOG = 10856; -- Do you have something you wish to send?
-- Shop Texts
BLINGBRIX_SHOP_DIALOG = 7195; -- Blingbrix good Gobbie from Boodlix's! Boodlix's Emporium help fighting fighters and maging mages. Gil okay, okay
SILKE_SHOP_DIALOG = 12796; -- You wouldn't happen to be a fellow scholar, by any chance? The contents of these pages are beyond me, but perhaps you might glean something from them. They could be yours...for a nominal fee.
-- Porter Moogle
RETRIEVE_DIALOG_ID = 14708; -- You retrieve$ from the porter moogle's care.
| gpl-3.0 |
AssassinTG/Fast | plugins/supergroup.lua | 1 | 101214 | --Begin supergrpup.lua
--Check members #Add supergroup
local function check_member_super(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
if success == 0 then
send_large_msg(receiver, "Promote me to admin first!")
end
for k,v in pairs(result) do
local member_id = v.peer_id
if member_id ~= our_id then
-- SuperGroup configuration
data[tostring(msg.to.id)] = {
group_type = 'SuperGroup',
long_id = msg.to.peer_id,
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.title, '_', ' '),
lock_arabic = 'no',
lock_link = "no",
flood = 'yes',
lock_spam = 'yes',
lock_sticker = 'no',
member = 'no',
public = 'no',
lock_rtl = 'no',
lock_tgservice = 'yes',
lock_contacts = 'no',
strict = 'no'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
local text = 'SuperGroup has been added!'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Check Members #rem supergroup
local function check_member_superrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local text = 'SuperGroup has been removed!'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Function to Add supergroup
local function superadd(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg})
end
--Function to remove supergroup
local function superrem(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg})
end
--Get and output admins and bots in supergroup
local function callback(cb_extra, success, result)
local i = 1
local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ")
local member_type = cb_extra.member_type
local text = member_type.." for "..chat_name..":\n"
for k,v in pairsByKeys(result) do
if not v.first_name then
name = " "
else
vname = v.first_name:gsub("", "")
name = vname:gsub("_", " ")
end
text = text.."\n"..i.." - "..name.."["..v.peer_id.."]"
i = i + 1
end
send_large_msg(cb_extra.receiver, text)
end
--Get and output info about supergroup
local function callback_info(cb_extra, success, result)
local title ="Info for SuperGroup: ["..result.title.."]\n\n"
local admin_num = "Admin count: "..result.admins_count.."\n"
local user_num = "User count: "..result.participants_count.."\n"
local kicked_num = "Kicked user count: "..result.kicked_count.."\n"
local channel_id = "ID: "..result.peer_id.."\n"
if result.username then
channel_username = "Username: @"..result.username
else
channel_username = ""
end
local text = title..admin_num..user_num..kicked_num..channel_id..channel_username
send_large_msg(cb_extra.receiver, text)
end
--Get and output members of supergroup
local function callback_who(cb_extra, success, result)
local text = "members for "..cb_extra.receiver
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
username = " @"..v.username
else
username = ""
end
text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n"
--text = text.."\n"..username
i = i + 1
end
local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false)
post_msg(cb_extra.receiver, text, ok_cb, false)
end
--Get and output list of kicked users for supergroup
local function callback_kicked(cb_extra, success, result)
--vardump(result)
local text = "kicked Members for SuperGroup "..cb_extra.receiver.."\n\n"
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
name = name.." @"..v.username
end
text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n"
i = i + 1
end
local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false)
--send_large_msg(cb_extra.receiver, text)
end
--Begin supergroup locks
local function lock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return "Link posting is already locked"
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return "Link posting has been locked"
end
end
local function unlock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'Link posting is not locked'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'Link posting has been unlocked'
end
end
local function lock_group_all(msg, data, target)
if not is_momod(msg) then
return
end
local group_all_lock = data[tostring(target)]['settings']['all']
if group_all_lock == 'yes' then
return 'All settings is already locked'
else
data[tostring(target)]['settings']['all'] = 'yes'
save_data(_config.moderation.data, data)
return 'All settinds has been locked'
end
end
local function unlock_group_all(msg, data, target)
if not is_momod(msg) then
return
end
local group_all_lock = data[tostring(target)]['settings']['all']
if group_all_lock == 'no' then
return 'All settings is not locked'
else
data[tostring(target)]['settings']['all'] = 'no'
save_data(_config.moderation.data, data)
return 'All settings has been unlocked'
end
end
local function lock_group_etehad(msg, data, target)
if not is_momod(msg) then
return
end
local group_etehad_lock = data[tostring(target)]['settings']['etehad']
if group_etehad_lock == 'yes' then
return "Etehad setting is already locked"
else
data[tostring(target)]['settings']['etehad'] = 'yes'
save_data(_config.moderation.data, data)
return "Etehad setting has been locked"
end
end
local function unlock_group_etehad(msg, data, target)
if not is_momod(msg) then
return
end
local group_etehad_lock = data[tostring(target)]['settings']['etehad']
if group_etehad_lock == 'no' then
return ' Etehad setting is not locked'
else
data[tostring(target)]['settings']['etehad'] = 'no'
save_data(_config.moderation.data, data)
return 'Etehad setting has been unlocked'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return
end
local group_leave_lock = data[tostring(target)]['settings']['leave']
if group_leave_lock == 'yes' then
return 'leave is already locked'
else
data[tostring(target)]['settings']['leave'] = 'yes'
save_data(_config.moderation.data, data)
return 'leave has been locked'
end
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return
end
local group_leave_lock = data[tostring(target)]['settings']['leave']
if group_leave_lock == 'no' then
return 'leave is not locked'
else
data[tostring(target)]['settings']['leave'] = 'no'
save_data(_config.moderation.data, data)
return 'leave has been unlocked'
end
end
local function lock_group_operator(msg, data, target)
if not is_momod(msg) then
return
end
local group_operator_lock = data[tostring(target)]['settings']['operator']
if group_operator_lock == 'yes' then
return "operator is already locked"
else
data[tostring(target)]['settings']['operator'] = 'yes'
save_data(_config.moderation.data, data)
return "operator has been locked"
end
end
local function unlock_group_operator(msg, data, target)
if not is_momod(msg) then
return
end
local group_operator_lock = data[tostring(target)]['settings']['operator']
if group_operator_lock == 'no' then
return 'operator is not locked'
else
data[tostring(target)]['settings']['operator'] = 'no'
save_data(_config.moderation.data, data)
return 'operator has been unlocked'
end
end
local function lock_group_reply(msg, data, target)
if not is_momod(msg) then
return
end
local group_reply_lock = data[tostring(target)]['settings']['reply']
if group_reply_lock == 'yes' then
return "reply is already locked"
else
data[tostring(target)]['settings']['reply'] = 'yes'
save_data(_config.moderation.data, data)
return "reply has been locked"
end
end
local function unlock_group_reply(msg, data, target)
if not is_momod(msg) then
return
end
local group_reply_lock = data[tostring(target)]['settings']['reply']
if group_reply_lock == 'no' then
return 'reply is not locked'
else
data[tostring(target)]['settings']['reply'] = 'no'
save_data(_config.moderation.data, data)
return 'reply has been unlocked '
end
end
local function lock_group_username(msg, data, target)
if not is_momod(msg) then
return
end
local group_username_lock = data[tostring(target)]['settings']['username']
if group_username_lock == 'yes' then
return "username is already locked"
else
data[tostring(target)]['settings']['username'] = 'yes'
save_data(_config.moderation.data, data)
return "username has been locked"
end
end
local function unlock_group_username(msg, data, target)
if not is_momod(msg) then
return
end
local group_username_lock = data[tostring(target)]['settings']['username']
if group_username_lock == 'no' then
return 'username is not locked'
else
data[tostring(target)]['settings']['username'] = 'no'
save_data(_config.moderation.data, data)
return 'username has been unlocked'
end
end
local function lock_group_media(msg, data, target)
if not is_momod(msg) then
return
end
local group_media_lock = data[tostring(target)]['settings']['media']
if group_media_lock == 'yes' then
return "media is already locked"
else
data[tostring(target)]['settings']['media'] = 'yes'
save_data(_config.moderation.data, data)
return "media has been locked"
end
end
local function unlock_group_media(msg, data, target)
if not is_momod(msg) then
return
end
local group_media_lock = data[tostring(target)]['settings']['media']
if group_media_lock == 'no' then
return 'media is not locked'
else
data[tostring(target)]['settings']['media'] = 'no'
save_data(_config.moderation.data, data)
return 'media has been unlocked!'
end
end
local function lock_group_fosh(msg, data, target)
if not is_momod(msg) then
return
end
local group_fosh_lock = data[tostring(target)]['settings']['fosh']
if group_fosh_lock == 'yes' then
return "fosh is already locked"
else
data[tostring(target)]['settings']['fosh'] = 'yes'
save_data(_config.moderation.data, data)
return "fosh has been locked"
end
end
local function unlock_group_fosh(msg, data, target)
if not is_momod(msg) then
return
end
local group_fosh_lock = data[tostring(target)]['settings']['fosh']
if group_fosh_lock == 'no' then
return 'fosh is not locked'
else
data[tostring(target)]['settings']['fosh'] = 'no'
save_data(_config.moderation.data, data)
return 'fosh has been unlocked'
end
end
local function lock_group_join(msg, data, target)
if not is_momod(msg) then
return
end
local group_join_lock = data[tostring(target)]['settings']['join']
if group_join_lock == 'yes' then
return "join is already locked"
else
data[tostring(target)]['settings']['join'] = 'yes'
save_data(_config.moderation.data, data)
return "join has been locked"
end
end
local function unlock_group_join(msg, data, target)
if not is_momod(msg) then
return
end
local group_join_lock = data[tostring(target)]['settings']['join']
if group_join_lock == 'no' then
return 'join is not locked'
else
data[tostring(target)]['settings']['join'] = 'no'
save_data(_config.moderation.data, data)
return 'join has been unlocked'
end
end
local function lock_group_fwd(msg, data, target)
if not is_momod(msg) then
return
end
local group_fwd_lock = data[tostring(target)]['settings']['fwd']
if group_fwd_lock == 'yes' then
return "fwd is already locked"
else
data[tostring(target)]['settings']['fwd'] = 'yes'
save_data(_config.moderation.data, data)
return "fwd has been locked"
end
end
local function unlock_group_fwd(msg, data, target)
if not is_momod(msg) then
return
end
local group_fwd_lock = data[tostring(target)]['settings']['fwd']
if group_fwd_lock == 'no' then
return 'fwd is not locked'
else
data[tostring(target)]['settings']['fwd'] = 'no'
save_data(_config.moderation.data, data)
return 'fwd has been unlocked'
end
end
local function lock_group_english(msg, data, target)
if not is_momod(msg) then
return
end
local group_english_lock = data[tostring(target)]['settings']['english']
if group_english_lock == 'yes' then
return "english is already locked"
else
data[tostring(target)]['settings']['english'] = 'yes'
save_data(_config.moderation.data, data)
return "english has been locked"
end
end
local function unlock_group_english(msg, data, target)
if not is_momod(msg) then
return
end
local group_english_lock = data[tostring(target)]['settings']['english']
if group_english_lock == 'no' then
return 'english is not locked'
else
data[tostring(target)]['settings']['english'] = 'no'
save_data(_config.moderation.data, data)
return 'english has been unlocked'
end
end
local function lock_group_emoji(msg, data, target)
if not is_momod(msg) then
return
end
local group_emoji_lock = data[tostring(target)]['settings']['emoji']
if group_emoji_lock == 'yes' then
return 'emoji is already locked'
else
data[tostring(target)]['settings']['emoji'] = 'yes'
save_data(_config.moderation.data, data)
return 'emoji has been locked'
end
end
local function unlock_group_emoji(msg, data, target)
if not is_momod(msg) then
return
end
local group_emoji_lock = data[tostring(target)]['settings']['emoji']
if group_emoji_lock == 'no' then
return 'emoji is not locked'
else
data[tostring(target)]['settings']['emoji'] = 'no'
save_data(_config.moderation.data, data)
return 'emoji has been unlocked'
end
end
local function lock_group_tag(msg, data, target)
if not is_momod(msg) then
return
end
local group_tag_lock = data[tostring(target)]['settings']['tag']
if group_tag_lock == 'yes' then
return 'tag is already locked'
else
data[tostring(target)]['settings']['tag'] = 'yes'
save_data(_config.moderation.data, data)
return 'tag has been locked'
end
end
local function unlock_group_tag(msg, data, target)
if not is_momod(msg) then
return
end
local group_tag_lock = data[tostring(target)]['settings']['tag']
if group_tag_lock == 'no' then
return 'tag is not locked'
else
data[tostring(target)]['settings']['tag'] = 'no'
save_data(_config.moderation.data, data)
return 'tag has been unlocked'
end
end
local function unlock_group_all(msg, data, target)
if not is_momod(msg) then
return
end
local group_all_lock = data[tostring(target)]['settings']['all']
if group_all_lock == 'no' then
return 'all setting is not locked'
else
data[tostring(target)]['settings']['all'] = 'no'
save_data(_config.moderation.data, data)
return 'all setting has been unlocked'
end
end
local function lock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Owners only!"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'SuperGroup spam is already locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been locked'
end
end
local function unlock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'SuperGroup spam is not locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Flood is already locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Flood has been unlocked'
end
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic/Persian is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic/Persian has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'SuperGroup members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'SuperGroup members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'SuperGroup members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup members has been unlocked'
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'RTl is already locked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'RTL has been locked'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'RTL is already unlocked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'RTL has been unlocked'
end
end
local function lock_group_tgservice(msg, data, target)
if not is_momod(msg) then
return
end
local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice']
if group_tgservice_lock == 'yes' then
return 'Tgservice is already locked'
else
data[tostring(target)]['settings']['lock_tgservice'] = 'yes'
save_data(_config.moderation.data, data)
return 'Tgservice has been locked'
end
end
local function unlock_group_tgservice(msg, data, target)
if not is_momod(msg) then
return
end
local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice']
if group_tgservice_lock == 'no' then
return 'TgService Is Not Locked!'
else
data[tostring(target)]['settings']['lock_tgservice'] = 'no'
save_data(_config.moderation.data, data)
return 'Tgservice has been unlocked'
end
end
local function lock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'Sticker posting is already locked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'Sticker posting has been locked'
end
end
local function unlock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'Sticker posting is already unlocked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'Sticker posting has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'yes' then
return 'Contact posting is already locked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'Contact posting has been locked'
end
end
local function unlock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'no' then
return 'Contact posting is already unlocked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'Contact posting has been unlocked'
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'yes' then
return 'Settings are already strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'Settings will be strictly enforced'
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'no' then
return 'Settings are not strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'Settings will not be strictly enforced'
end
end
--End supergroup locks
--'Set supergroup rules' function
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'SuperGroup rules set'
end
--'Get supergroup rules' function
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local group_name = data[tostring(msg.to.id)]['settings']['set_name']
local rules = group_name..' rules:\n\n'..rules:gsub("/n", " ")
return rules
end
--Set supergroup to public or not public function
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'SuperGroup is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
data[tostring(target)]['long_id'] = msg.to.long_id
save_data(_config.moderation.data, data)
return 'SuperGroup is now: not public'
end
end
--Show supergroup settings; function
function show_supergroup_settingsmod(msg, target)
if not is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 4
end
end
local bots_protection = "yes"
if data[tostring(target)]['settings']['lock_bots'] then
bots_protection = data[tostring(target)]['settings']['lock_bots']
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_tgservice'] then
data[tostring(target)]['settings']['lock_tgservice'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['tag'] then
data[tostring(target)]['settings']['tag'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['emoji'] then
data[tostring(target)]['settings']['emoji'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['english'] then
data[tostring(target)]['settings']['english'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['fwd'] then
data[tostring(target)]['settings']['fwd'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['reply'] then
data[tostring(target)]['settings']['reply'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['join'] then
data[tostring(target)]['settings']['join'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['fosh'] then
data[tostring(target)]['settings']['fosh'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['username'] then
data[tostring(target)]['settings']['username'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['media'] then
data[tostring(target)]['settings']['media'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['leave'] then
data[tostring(target)]['settings']['leave'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['all'] then
data[tostring(target)]['settings']['all'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['operator'] then
data[tostring(target)]['settings']['operator'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['etehad'] then
data[tostring(target)]['settings']['etehad'] = 'no'
end
end
local gp_type = data[tostring(msg.to.id)]['group_type']
local expiretime = redis:hget('expiretime', get_receiver(msg))
local expire = ''
if not expiretime then
expire = expire..'Not Found!'
else
local now = tonumber(os.time())
expire = expire..math.floor((tonumber(expiretime) - tonumber(now)) / 86400) + 1
end
local settings = data[tostring(target)]['settings']
local text = "➖➖➖➖➖➖➖➖➖➖\n⚙SuperGroup settings⚙ \n➖➖➖➖➖➖➖➖➖➖\n♨️Lock Links: "..settings.lock_link.."\n♨️Lock Contacts: "..settings.lock_contacts.."\n♨️Lock Flood: "..settings.flood.."\n♨️Flood Sensitivity : |"..NUM_MSG_MAX.."|\n♨️Lock Spam: "..settings.lock_spam.."\n♨️Lock Arabic: "..settings.lock_arabic.."\n♨️Lock Member: "..settings.lock_member.."\n♨️Lock RTL: "..settings.lock_rtl.."\n♨️Lock Tgservice: "..settings.lock_tgservice.."\n♨️Lock Sticker: "..settings.lock_sticker.."\n♨️Lock Tag[#⃣]: "..settings.tag.."\n♨️Lock Emoji: "..settings.emoji.."\n♨️Lock English: "..settings.english.."\n♨️Lock Fwd[forward]: "..settings.fwd.."\n♨️Lock Reply: "..settings.reply.."\n♨️Lock Join: "..settings.join.."\n♨️Lock Username[@]: "..settings.username.."\n♨️Lock Media: "..settings.media.."\n♨️Lock Fosh: "..settings.fosh.."\n♨️Lock Leave: "..settings.leave.."\n♨️Lock Bots: "..bots_protection.."\n♨️Lock Operator: "..settings.operator.."\n➖➖➖➖➖➖➖➖➖➖\n🔧Easy Sweet & Faster Switch🔧 \n➖➖➖➖➖➖➖➖➖➖\n🔰Model Etehad: "..settings.etehad.."\n🔰Lock all: "..settings.all.."\n➖➖➖➖➖➖➖➖➖➖\n❗️About Group❗️\n➖➖➖➖➖➖➖➖➖➖\n🔘Group Type: |"..gp_type.."|\n🔘Public: "..settings.public.."\n🔘Strict Settings: "..settings.strict.."\n🔘Charge: |"..expire.."|\n➖➖➖➖➖➖➖➖➖➖\n📈Bot Version: 📍1.1\n〔Mя.Fαรт β๑т〕\nTelegram.Me/MrFastTeam"
if string.match(text, 'no') then text = string.gsub(text, 'no', '|🔓|') end
if string.match(text, 'yes') then text = string.gsub(text, 'yes', '|🔐|') end
return text
end
local function promote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
end
local function demote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..' is not a moderator.')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
end
local function promote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return send_large_msg(receiver, 'SuperGroup is not added.')
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..' has been promoted.')
end
local function demote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..' is not a moderator.')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..' has been demoted.')
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'SuperGroup is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
-- Start by reply actions
function get_message_callback(extra, success, result)
local get_cmd = extra.get_cmd
local msg = extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
if get_cmd == "id" and not result.action then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]")
id1 = send_large_msg(channel, result.from.peer_id)
elseif get_cmd == 'id' and result.action then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
else
user_id = result.peer_id
end
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]")
id1 = send_large_msg(channel, user_id)
end
elseif get_cmd == "idfrom" then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]")
id2 = send_large_msg(channel, result.fwd_from.peer_id)
elseif get_cmd == 'channel_block' and not result.action then
local member_id = result.from.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
--savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply")
kick_user(member_id, channel_id)
elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then
local user_id = result.action.user.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.")
kick_user(user_id, channel_id)
elseif get_cmd == "del" then
delete_msg(result.id, ok_cb, false)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply")
elseif get_cmd == "setadmin" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." set as an admin"
else
text = "[ "..user_id.." ]set as an admin"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "demoteadmin" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
if is_admin2(result.from.peer_id) then
return send_large_msg(channel_id, "You can't demote global admins!")
end
channel_demote(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." has been demoted from admin"
else
text = "[ "..user_id.." ] has been demoted from admin"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "setowner" then
local group_owner = data[tostring(result.to.peer_id)]['set_owner']
if group_owner then
local channel_id = 'channel#id'..result.to.peer_id
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(channel_id, user, ok_cb, false)
end
local user_id = "user#id"..result.from.peer_id
channel_set_admin(channel_id, user_id, ok_cb, false)
data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply")
if result.from.username then
text = "@"..result.from.username.." [ "..result.from.peer_id.." ] added as owner"
else
text = "[ "..result.from.peer_id.." ] added as owner"
end
send_large_msg(channel_id, text)
end
elseif get_cmd == "promote" then
local receiver = result.to.peer_id
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
if result.to.peer_type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply")
promote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_set_mod(channel_id, user, ok_cb, false)
end
elseif get_cmd == "demote" then
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
--local user = "user#id"..result.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..user_id.."] by reply")
demote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_demote(channel_id, user, ok_cb, false)
elseif get_cmd == 'mute_user' then
if result.service then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
end
end
if action == 'chat_add_user_link' then
if result.from then
user_id = result.from.peer_id
end
end
else
user_id = result.from.peer_id
end
local receiver = extra.receiver
local chat_id = msg.to.id
print(user_id)
print(chat_id)
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, "["..user_id.."] removed from the muted user list")
elseif is_admin1(msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to the muted user list")
end
end
end
-- End by reply actions
--By ID actions
local function cb_user_info(extra, success, result)
local receiver = extra.receiver
local user_id = result.peer_id
local get_cmd = extra.get_cmd
local data = load_data(_config.moderation.data)
--[[if get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
else
text = "[ "..result.peer_id.." ] has been set as an admin"
end
send_large_msg(receiver, text)]]
if get_cmd == "demoteadmin" then
if is_admin2(result.peer_id) then
return send_large_msg(receiver, "You can't demote global admins!")
end
local user_id = "user#id"..result.peer_id
channel_demote(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been demoted from admin"
send_large_msg(receiver, text)
else
text = "[ "..result.peer_id.." ] has been demoted from admin"
send_large_msg(receiver, text)
end
elseif get_cmd == "promote" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
promote2(receiver, member_username, user_id)
elseif get_cmd == "demote" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
demote2(receiver, member_username, user_id)
end
end
-- Begin resolve username actions
local function callbackres(extra, success, result)
local member_id = result.peer_id
local member_username = "@"..result.username
local get_cmd = extra.get_cmd
if get_cmd == "res" then
local user = result.peer_id
local name = string.gsub(result.print_name, "_", " ")
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user..'\n'..name)
return 'ID'..user
elseif get_cmd == "id" then
local user = result.peer_id
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user)
return 'ID'..user
elseif get_cmd == "invite" then
local receiver = extra.channel
local user_id = "user#id"..result.peer_id
channel_invite(receiver, user_id, ok_cb, false)
--[[elseif get_cmd == "channel_block" then
local user_id = result.peer_id
local channel_id = extra.channelid
local sender = extra.sender
if member_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
kick_user(user_id, channel_id)
elseif get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
channel_set_admin(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." has been set as an admin"
send_large_msg(channel_id, text)
end
elseif get_cmd == "setowner" then
local receiver = extra.channel
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = extra.from_id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
local user = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(result.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username")
if result.username then
text = member_username.." [ "..result.peer_id.." ] added as owner"
else
text = "[ "..result.peer_id.." ] added as owner"
end
send_large_msg(receiver, text)
end]]
elseif get_cmd == "promote" then
local receiver = extra.channel
local user_id = result.peer_id
--local user = "user#id"..result.peer_id
promote2(receiver, member_username, user_id)
--channel_set_mod(receiver, user, ok_cb, false)
elseif get_cmd == "demote" then
local receiver = extra.channel
local user_id = result.peer_id
local user = "user#id"..result.peer_id
demote2(receiver, member_username, user_id)
elseif get_cmd == "demoteadmin" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
if is_admin2(result.peer_id) then
return send_large_msg(channel_id, "You can't demote global admins!")
end
channel_demote(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been demoted from admin"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." has been demoted from admin"
send_large_msg(channel_id, text)
end
local receiver = extra.channel
local user_id = result.peer_id
demote_admin(receiver, member_username, user_id)
elseif get_cmd == 'mute_user' then
local user_id = result.peer_id
local receiver = extra.receiver
local chat_id = string.gsub(receiver, 'channel#id', '')
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] removed from muted user list")
elseif is_owner(extra.msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to muted user list")
end
end
end
--End resolve username actions
--Begin non-channel_invite username actions
local function in_channel_cb(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local msg = cb_extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(cb_extra.msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local member = cb_extra.username
local memberid = cb_extra.user_id
if member then
text = 'No user @'..member..' in this SuperGroup.'
else
text = 'No user ['..memberid..'] in this SuperGroup.'
end
if get_cmd == "channel_block" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = v.peer_id
local channel_id = cb_extra.msg.to.id
local sender = cb_extra.msg.from.id
if user_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(user_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(user_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
if v.username then
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]")
else
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]")
end
kick_user(user_id, channel_id)
return
end
end
elseif get_cmd == "setadmin" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = "user#id"..v.peer_id
local channel_id = "channel#id"..cb_extra.msg.to.id
channel_set_admin(channel_id, user_id, ok_cb, false)
if v.username then
text = "@"..v.username.." ["..v.peer_id.."] has been set as an admin"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]")
else
text = "["..v.peer_id.."] has been set as an admin"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id)
end
if v.username then
member_username = "@"..v.username
else
member_username = string.gsub(v.print_name, '_', ' ')
end
local receiver = channel_id
local user_id = v.peer_id
promote_admin(receiver, member_username, user_id)
end
send_large_msg(channel_id, text)
return
end
elseif get_cmd == 'setowner' then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..v.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(v.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username")
if result.username then
text = member_username.." ["..v.peer_id.."] added as owner"
else
text = "["..v.peer_id.."] added as owner"
end
end
elseif memberid and vusername ~= member and vpeer_id ~= memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
data[tostring(channel)]['set_owner'] = tostring(memberid)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username")
text = "["..memberid.."] added as owner"
end
end
end
end
send_large_msg(receiver, text)
end
--End non-channel_invite username actions
--'Set supergroup photo' function
local function set_supergroup_photo(msg, success, result)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return
end
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
channel_set_photo(receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
--Run function
local function run(msg, matches)
if msg.to.type == 'chat' then
if matches[1] == 'upchat' then
if not is_admin1(msg) then
return
end
local receiver = get_receiver(msg)
chat_upgrade(receiver, ok_cb, false)
end
elseif msg.to.type == 'channel'then
if matches[1] == 'upchat' then
if not is_admin1(msg) then
return
end
return "Already a SuperGroup"
end
end
if msg.to.type == 'channel' then
local support_id = msg.from.id
local receiver = get_receiver(msg)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local data = load_data(_config.moderation.data)
if matches[1] == 'add' and not matches[2] then
if not is_admin1(msg) and not is_support(support_id) then
return
end
if is_super_group(msg) then
return reply_msg(msg.id, 'SuperGroup is already added.', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup")
superadd(msg)
set_mutes(msg.to.id)
channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false)
end
if matches[1] == 'rem' and is_admin1(msg) and not matches[2] then
if not is_super_group(msg) then
return reply_msg(msg.id, 'SuperGroup is not added.', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed")
superrem(msg)
rem_mutes(msg.to.id)
end
if not data[tostring(msg.to.id)] then
return
end
if matches[1] == "gpinfo" then
if not is_owner(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info")
channel_info(receiver, callback_info, {receiver = receiver, msg = msg})
end
if matches[1] == "admins" then
if not is_owner(msg) and not is_support(msg.from.id) then
return
end
member_type = 'Admins'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list")
admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "owner" then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your SuperGroup"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "SuperGroup owner is ["..group_owner..']'
end
if matches[1] == "modlist" then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
-- channel_get_admins(receiver,callback, {receiver = receiver})
end
if matches[1] == "bots" and is_momod(msg) then
member_type = 'Bots'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list")
channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "who" and not matches[2] and is_momod(msg) then
local user_id = msg.from.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list")
channel_get_users(receiver, callback_who, {receiver = receiver})
end
if matches[1] == "kicked" and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list")
channel_get_kicked(receiver, callback_kicked, {receiver = receiver})
end
if matches[1] == 'del' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'del',
msg = msg
}
delete_msg(msg.id, ok_cb, false)
get_message(msg.reply_id, get_message_callback, cbreply_extra)
end
end
if matches[1] == 'block' or matches[1] == 'kick' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'channel_block',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'block' or matches[1] == 'kick' and string.match(matches[2], '^%d+$') then
--[[local user_id = matches[2]
local channel_id = msg.to.id
if is_momod2(user_id, channel_id) and not is_admin2(user_id) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]")
kick_user(user_id, channel_id)]]
local get_cmd = 'channel_block'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif msg.text:match("@[%a%d]") then
--[[local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'channel_block',
sender = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'channel_block'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'id' then
if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then
local cbreply_extra = {
get_cmd = 'id',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then
local cbreply_extra = {
get_cmd = 'idfrom',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif msg.text:match("@[%a%d]") then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'id'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username)
resolve_username(username, callbackres, cbres_extra)
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID")
return ""
end
end
if matches[1] == 'kickme' then
if msg.to.type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme")
channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if matches[1] == 'newlink' and is_momod(msg)then
local function callback_link (extra , success, result)
local receiver = get_receiver(msg)
if success == 0 then
send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it')
data[tostring(msg.to.id)]['settings']['set_link'] = nil
save_data(_config.moderation.data, data)
else
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link")
export_channel_link(receiver, callback_link, false)
end
if matches[1] == 'setlink' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send the new group link now'
end
if msg.text then
if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = msg.text
save_data(_config.moderation.data, data)
return "New link set"
end
end
if matches[1] == 'link' then
if not is_momod(msg) then
return
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first!\n\nOr if I am not creator use /setlink to set your link"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == "invite" and is_sudo(msg) then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = "invite"
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username)
resolve_username(username, callbackres, cbres_extra)
end
if matches[1] == 'res' and is_owner(msg) then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'res'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username)
resolve_username(username, callbackres, cbres_extra)
end
--[[if matches[1] == 'kick' and is_momod(msg) then
local receiver = channel..matches[3]
local user = "user#id"..matches[2]
chaannel_kick(receiver, user, ok_cb, false)
end]]
if matches[1] == 'setadmin' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'setadmin',
msg = msg
}
setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'setadmin' and string.match(matches[2], '^%d+$') then
--[[] local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'setadmin'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]]
local get_cmd = 'setadmin'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'setadmin' and not string.match(matches[2], '^%d+$') then
--[[local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'setadmin'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'setadmin'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'demoteadmin' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'demoteadmin',
msg = msg
}
demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'demoteadmin' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'demoteadmin'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'demoteadmin' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'demoteadmin'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username)
resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'setowner' and is_owner(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'setowner',
msg = msg
}
setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'setowner' and string.match(matches[2], '^%d+$') then
--[[ local group_owner = data[tostring(msg.to.id)]['set_owner']
if group_owner then
local receiver = get_receiver(msg)
local user_id = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user_id, ok_cb, false)
end
local user = "user#id"..matches[2]
channel_set_admin(receiver, user, ok_cb, false)
data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2])
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = "[ "..matches[2].." ] added as owner"
return text
end]]
local get_cmd = 'setowner'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'setowner' and not string.match(matches[2], '^%d+$') then
local get_cmd = 'setowner'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'promote' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner/admin can promote"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'promote',
msg = msg
}
promote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'promote' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'promote' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'promote',
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'mp' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_set_mod(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'md' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_demote(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'demote' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner/support/admin can promote"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'demote',
msg = msg
}
demote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'demote' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'demote'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == "setname" and is_momod(msg) then
local receiver = get_receiver(msg)
local set_name = string.gsub(matches[2], '_', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2])
rename_channel(receiver, set_name, ok_cb, false)
end
if msg.service and msg.action.type == 'chat_rename' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title)
data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title
save_data(_config.moderation.data, data)
end
if matches[1] == "setabout" and is_momod(msg) then
local receiver = get_receiver(msg)
local about_text = matches[2]
local data_cat = 'description'
local target = msg.to.id
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text)
channel_set_about(receiver, about_text, ok_cb, false)
return "Description has been set.\n\nSelect the chat again to see the changes."
end
if matches[1] == "setusername" and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.")
elseif success == 0 then
send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.")
end
end
local username = string.gsub(matches[2], '@', '')
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
if matches[1] == 'setrules' and is_momod(msg) then
rules = matches[2]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]")
return set_rulesmod(msg, data, target)
end
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo")
load_photo(msg.id, set_supergroup_photo, msg)
return
end
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo")
return 'Please send the new group photo now'
end
if matches[1] == 'clean' then
if not is_momod(msg) then
return
end
if not is_momod(msg) then
return "Only owner can clean"
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return 'No moderator(s) in this SuperGroup.'
end
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
return 'Modlist has been cleaned'
end
if matches[2] == 'rules' then
local data_cat = 'rules'
if data[tostring(msg.to.id)][data_cat] == nil then
return "Rules have not been set"
end
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
return 'Rules have been cleaned'
end
if matches[2] == 'about' then
local receiver = get_receiver(msg)
local about_text = ' '
local data_cat = 'description'
if data[tostring(msg.to.id)][data_cat] == nil then
return 'About is not set'
end
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
channel_set_about(receiver, about_text, ok_cb, false)
return "About has been cleaned"
end
if matches[2] == 'silentlist' then
chat_id = msg.to.id
local hash = 'mute_user:'..chat_id
redis:del(hash)
return "silentlist Cleaned"
end
if matches[2] == 'username' and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "SuperGroup username cleaned.")
elseif success == 0 then
send_large_msg(receiver, "Failed to clean SuperGroup username.")
end
end
local username = ""
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
end
if matches[1] == 'lock' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'all' then
local safemode ={
lock_group_links(msg, data, target),
lock_group_tag(msg, data, target),
lock_group_spam(msg, data, target),
lock_group_flood(msg, data, target),
lock_group_arabic(msg, data, target),
lock_group_membermod(msg, data, target),
lock_group_rtl(msg, data, target),
lock_group_tgservice(msg, data, target),
lock_group_sticker(msg, data, target),
lock_group_contacts(msg, data, target),
lock_group_english(msg, data, target),
lock_group_fwd(msg, data, target),
lock_group_reply(msg, data, target),
lock_group_join(msg, data, target),
lock_group_emoji(msg, data, target),
lock_group_username(msg, data, target),
lock_group_fosh(msg, data, target),
lock_group_media(msg, data, target),
lock_group_leave(msg, data, target),
lock_group_bots(msg, data, target),
lock_group_operator(msg, data, target),
}
return lock_group_all(msg, data, target), safemode
end
if matches[2] == 'etehad' then
local etehad ={
unlock_group_links(msg, data, target),
lock_group_tag(msg, data, target),
lock_group_spam(msg, data, target),
lock_group_flood(msg, data, target),
unlock_group_arabic(msg, data, target),
lock_group_membermod(msg, data, target),
unlock_group_rtl(msg, data, target),
lock_group_tgservice(msg, data, target),
lock_group_sticker(msg, data, target),
unlock_group_contacts(msg, data, target),
unlock_group_english(msg, data, target),
unlock_group_fwd(msg, data, target),
unlock_group_reply(msg, data, target),
lock_group_join(msg, data, target),
unlock_group_emoji(msg, data, target),
unlock_group_username(msg, data, target),
lock_group_fosh(msg, data, target),
unlock_group_media(msg, data, target),
lock_group_leave(msg, data, target),
lock_group_bots(msg, data, target),
unlock_group_operator(msg, data, target),
}
return lock_group_etehad(msg, data, target), etehad
end
if matches[2] == 'links' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ")
return lock_group_links(msg, data, target)
end
if matches[2] == 'join' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked join ")
return lock_group_join(msg, data, target)
end
if matches[2] == 'tag' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ")
return lock_group_tag(msg, data, target)
end
if matches[2] == 'spam' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ")
return lock_group_spam(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_flood(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'rtl' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names")
return lock_group_rtl(msg, data, target)
end
if matches[2] == 'tgservice' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions")
return lock_group_tgservice(msg, data, target)
end
if matches[2] == 'sticker' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting")
return lock_group_sticker(msg, data, target)
end
if matches[2] == 'contacts' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(msg, data, target)
end
if matches[2] == 'strict' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings")
return enable_strict_rules(msg, data, target)
end
if matches[2] == 'english' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english")
return lock_group_english(msg, data, target)
end
if matches[2] == 'fwd' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fwd")
return lock_group_fwd(msg, data, target)
end
if matches[2] == 'reply' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked reply")
return lock_group_reply(msg, data, target)
end
if matches[2] == 'emoji' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked emoji")
return lock_group_emoji(msg, data, target)
end
if matches[2] == 'fosh' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fosh")
return lock_group_fosh(msg, data, target)
end
if matches[2] == 'media' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked media")
return lock_group_media(msg, data, target)
end
if matches[2] == 'username' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked username")
return lock_group_username(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leave")
return lock_group_leave(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'operator' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked operator")
return lock_group_operator(msg, data, target)
end
end
if matches[1] == 'unlock' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'all' then
local dsafemode ={
unlock_group_links(msg, data, target),
unlock_group_tag(msg, data, target),
unlock_group_spam(msg, data, target),
unlock_group_flood(msg, data, target),
unlock_group_arabic(msg, data, target),
unlock_group_membermod(msg, data, target),
unlock_group_rtl(msg, data, target),
unlock_group_tgservice(msg, data, target),
unlock_group_sticker(msg, data, target),
unlock_group_contacts(msg, data, target),
unlock_group_english(msg, data, target),
unlock_group_fwd(msg, data, target),
unlock_group_reply(msg, data, target),
unlock_group_join(msg, data, target),
unlock_group_emoji(msg, data, target),
unlock_group_username(msg, data, target),
unlock_group_fosh(msg, data, target),
unlock_group_media(msg, data, target),
unlock_group_leave(msg, data, target),
unlock_group_bots(msg, data, target),
unlock_group_operator(msg, data, target),
}
return unlock_group_all(msg, data, target), dsafemode
end
if matches[2] == 'etehad' then
local detehad ={
lock_group_links(msg, data, target),
unlock_group_tag(msg, data, target),
lock_group_spam(msg, data, target),
lock_group_flood(msg, data, target),
unlock_group_arabic(msg, data, target),
unlock_group_membermod(msg, data, target),
unlock_group_rtl(msg, data, target),
unlock_group_tgservice(msg, data, target),
unlock_group_sticker(msg, data, target),
unlock_group_contacts(msg, data, target),
unlock_group_english(msg, data, target),
unlock_group_fwd(msg, data, target),
unlock_group_reply(msg, data, target),
unlock_group_join(msg, data, target),
unlock_group_emoji(msg, data, target),
unlock_group_username(msg, data, target),
unlock_group_fosh(msg, data, target),
unlock_group_media(msg, data, target),
unlock_group_leave(msg, data, target),
unlock_group_bots(msg, data, target),
unlock_group_operator(msg, data, target),
}
return unlock_group_etehad(msg, data, target), detehad
end
if matches[2] == 'links' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting")
return unlock_group_links(msg, data, target)
end
if matches[2] == 'join' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked join")
return unlock_group_join(msg, data, target)
end
if matches[2] == 'tag' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag")
return unlock_group_tag(msg, data, target)
end
if matches[2] == 'spam' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam")
return unlock_group_spam(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood")
return unlock_group_flood(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'rtl' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[2] == 'tgservice' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions")
return unlock_group_tgservice(msg, data, target)
end
if matches[2] == 'sticker' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting")
return unlock_group_sticker(msg, data, target)
end
if matches[2] == 'contacts' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting")
return unlock_group_contacts(msg, data, target)
end
if matches[2] == 'strict' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings")
return disable_strict_rules(msg, data, target)
end
if matches[2] == 'english' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english")
return unlock_group_english(msg, data, target)
end
if matches[2] == 'fwd' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fwd")
return unlock_group_fwd(msg, data, target)
end
if matches[2] == 'reply' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked reply")
return unlock_group_reply(msg, data, target)
end
if matches[2] == 'emoji' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled emoji")
return unlock_group_emoji(msg, data, target)
end
if matches[2] == 'fosh' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fosh")
return unlock_group_fosh(msg, data, target)
end
if matches[2] == 'media' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked media")
return unlock_group_media(msg, data, target)
end
if matches[2] == 'username' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled username")
return unlock_group_username(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leave")
return unlock_group_leave(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'operator' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked operator")
return unlock_group_operator(msg, data, target)
end
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return
end
if tonumber(matches[2]) < 1 or tonumber(matches[2]) > 200 then
return "Wrong number,range is [1-200]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Flood has been set to: '..matches[2]
end
if matches[1] == 'public' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public")
return unset_public_membermod(msg, data, target)
end
end
if matches[1] == 'mute' and is_owner(msg) then
local chat_id = msg.to.id
if matches[2] == 'audio' then
local msg_type = 'Audio'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'photo' then
local msg_type = 'Photo'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'video' then
local msg_type = 'Video'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'gifs' then
local msg_type = 'Gifs'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'documents' then
local msg_type = 'Documents'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'text' then
local msg_type = 'Text'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "Mute "..msg_type.." is already on"
end
end
if matches[2] == '' then
local msg_type = 'All'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return "Mute "..msg_type.." has been enabled"
else
return "Mute "..msg_type.." is already on"
end
end
end
if matches[1] == 'unmute' and is_momod(msg) then
local chat_id = msg.to.id
if matches[2] == 'audio' then
local msg_type = 'Audio'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'photo' then
local msg_type = 'Photo'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'video' then
local msg_type = 'Video'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'gifs' then
local msg_type = 'Gifs'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'documents' then
local msg_type = 'Documents'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'text' then
local msg_type = 'Text'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message")
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute text is already off"
end
end
if matches[2] == '' then
local msg_type = 'All'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return "Mute "..msg_type.." has been disabled"
else
return "Mute "..msg_type.." is already disabled"
end
end
end
if matches[1] == "silent" or matches[1] == "unsilent" and is_momod(msg) then
local chat_id = msg.to.id
local hash = "mute_user"..chat_id
local user_id = ""
if type(msg.reply_id) ~= "nil" then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg})
elseif matches[1] == "silent" or matches[1] == "unsilent" and string.match(matches[2], '^%d+$') then
local user_id = matches[2]
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list")
return "["..user_id.."] removed from the muted users list"
elseif is_momod(msg) then
mute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list")
return "["..user_id.."] added to the muted user list"
end
elseif matches[1] == "silent" or matches[1] == "unsilent" and not string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg})
end
end
if matches[1] == "muteslist" and is_momod(msg) then
local chat_id = msg.to.id
if not has_mutes(chat_id) then
set_mutes(chat_id)
return mutes_list(chat_id)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist")
return mutes_list(chat_id)
end
if matches[1] == "silentlist" and is_momod(msg) then
local chat_id = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist")
return muted_user_list(chat_id)
end
if matches[1] == 'settings' and is_momod(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ")
return show_supergroup_settingsmod(msg, target)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'help' and not is_owner(msg) then
text = "Join to @UltronTM For View Help Text!"
reply_msg(msg.id, text, ok_cb, false)
elseif matches[1] == 'help' and is_owner(msg) then
local name_log = user_print_name(msg.from)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp")
return super_help()
end
if matches[1]:lower() == 'echo' then
local echo = matches[2]
local echo = string.gsub(echo, '!', '')
local echo = string.gsub(echo, '#', '')
local echo = string.gsub(echo, '/', '')
return echo
end
if matches[1] == 'peer_id' and is_admin1(msg)then
text = msg.to.peer_id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
if matches[1] == 'msg.to.id' and is_admin1(msg) then
text = msg.to.id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
--Admin Join Service Message
if msg.service then
local action = msg.action.type
if action == 'chat_add_user_link' then
if is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.from.id) and not is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup")
channel_set_mod(receiver, user, ok_cb, false)
end
end
if action == 'chat_add_user' then
if is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_mod(receiver, user, ok_cb, false)
end
end
end
if matches[1] == 'msg.to.peer_id' then
post_large_msg(receiver, msg.to.peer_id)
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
return {
patterns = {
"^[#!/]([Aa]dd)$",
"^[#!/]([Rr]em)$",
"^[#!/]([Mm]ove) (.*)$",
"^[#!/]([Aa]dmins)$",
"^[#!/]([Oo]wner)$",
"^[#!/]([Mm]odlist)$",
"^[#!/]([Bb]ots)$",
"^[#!/]([Ww]ho)$",
"^[#!/]([Kk]icked)$",
"^[#!/]([Bb]lock) (.*)",
"^[#!/]([Bb]lock)",
"^[#!/]([Kk]ick) (.*)",
"^[#!/]([Kk]ick)",
"^[#!/]([Uu]pchat)$",
"^[#!/]([Ii][Dd]) (.*)$",
"^[#!/]([Kk]ickme)$",
"^[#!/]([Nn]ewlink)$",
"^[#!/]([Ss]etlink)$",
"^[#!/]([Ll]ink)$",
"^[#!/]([Rr]es) (.*)$",
"^[#!/]([Ss]etadmin) (.*)$",
"^[#!/]([Ss]etadmin)",
"^[#!/]([Dd]emoteadmin) (.*)$",
"^[#!/]([Dd]emoteadmin)",
"^[#!/]([Ss]etowner) (.*)$",
"^[#!/]([Ss]etowner)$",
"^[#!/]([Pp]romote) (.*)$",
"^[#!/]([Pp]romote)",
"^[#!/]([Dd]emote) (.*)$",
"^[#!/]([Dd]emote)",
"^[#!/]([Ss]etname) (.*)$",
"^[#!/]([Ss]etabout) (.*)$",
"^[#!/]([Ss]etrules) (.*)$",
"^[#!/]([Ss]etphoto)$",
"^[#!/]([Ss]etusername) (.*)$",
"^[#!/]([Dd]el)$",
"^[#!/]([Ll]ock) (.*)$",
"^[#!/]([Uu]nlock) (.*)$",
"^[#!/]([Mm]ute) ([^%s]+)$",
"^[#!/]([Uu]nmute) ([^%s]+)$",
"^[#!/]([Ss]ilent)$",
"^[#!/]([Ss]ilent) (.*)$",
"^[#!/]([Uu]nsilent)$",
"^[#!/]([Uu]nsilent) (.*)$",
"^[#!/]([Pp]ublic) (.*)$",
"^[#!/]([Ss]ettings)$",
"^[#!/]([Rr]ules)$",
"^[#!/]([Ss]etflood) (%d+)$",
"^[#!/]([Cc]lean) (.*)$",
"^[#!/]([Hh]elp)$",
"^[#!/]([Mm]uteslist)$",
"^[#!/]([Ss]ilentlist)$",
"^[/!#](echo)$",
"^[/!#]([Ii][Dd]) (.*)&",
"[#!/](mp) (.*)",
"[#!/](md) (.*)",
"^(https://telegram.me/joinchat/%S+)$",
"msg.to.peer_id",
"%[(document)%]",
"%[(photo)%]",
"%[(video)%]",
"%[(audio)%]",
"%[(contact)%]",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
zynjec/darkstar | scripts/zones/Ghelsba_Outpost/bcnms/wings_of_fury.lua | 9 | 1065 | -----------------------------------
-- Wings of Fury
-- Ghelsba Outpost BCNM20, Cloudy Orb
-- !additem 1551
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 2, battlefield:getLocalVar("[cs]bit"), 2)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
Mohammadjkr/spam-bot | bot/seedbot.lua | 1 | 10317 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban",
"admin"
},
sudo_users = {110626080,103649648,143723991,111020322,0,tonumber(244939302)},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[Teleseed v2 - Open Source
An advance Administration bot based on yagop/telegram-bot
https://github.com/SEEDTEAM/TeleSeed
Our team!
Alphonse (@Iwals)
I M /-\ N (@Imandaneshi)
Siyanew (@Siyanew)
Rondoozle (@Potus)
Seyedan (@Seyedan25)
Special thanks to:
Juan Potato
Siyanew
Topkecleon
Vamptacus
Our channels:
English: @TeleSeedCH
Persian: @IranSeed
]],
help_text_realm = [[
Realm Commands:
!creategroup [name]
Create a group
!createrealm [name]
Create a realm
!setname [name]
Set realm name
!setabout [group_id] [text]
Set a group's about text
!setrules [grupo_id] [text]
Set a group's rules
!lock [grupo_id] [setting]
Lock a group's setting
!unlock [grupo_id] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [grupo_id]
Kick all memebers and delete group
!kill realm [realm_id]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Get a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
» Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
Return group id or user id
!help
Get commands list
!lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
!unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
!set rules [text]
Set [text] as rules
!set about [text]
Set [text] as about
!settings
Returns group settings
!newlink
Create/revoke your group link
!link
Returns group link
!owner
Returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] [text]
Save [text] as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
Returns user id
!log
Will return group logs
!banlist
Will return group ban list
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| agpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Port_Bastok/npcs/Carmelo.lua | 14 | 4833 | -----------------------------------
-- Area: Port Bastok
-- NPC: Carmelo
-- Start & Finishes Quest: Love and Ice, A Test of True Love
-- Start Quest: Lovers in the Dusk
-- Involved in Quest: The Siren's Tear
-- @zone 236
-- @pos -146.476 -7.48 -10.889
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local SirensTear = player:getQuestStatus(BASTOK,THE_SIREN_S_TEAR);
local SirensTearProgress = player:getVar("SirensTear");
local TheStarsOfIfrit = player:getQuestStatus(BASTOK,THE_STARS_OF_IFRIT);
local LoveAndIce = player:getQuestStatus(BASTOK,LOVE_AND_ICE);
local LoveAndIceProgress = player:getVar("LoveAndIceProgress");
local ATestOfTrueLove = player:getQuestStatus(BASTOK,A_TEST_OF_TRUE_LOVE);
local ATestOfTrueLoveProgress = player:getVar("ATestOfTrueLoveProgress");
local LoversInTheDusk = player:getQuestStatus(BASTOK,LOVERS_IN_THE_DUSK);
if (SirensTear == QUEST_ACCEPTED) then
player:startEvent(0x0006);
elseif (SirensTear == QUEST_COMPLETED and player:hasItem(576) == false and SirensTearProgress < 2) then
player:startEvent(0x0013);
elseif (LoveAndIce == QUEST_AVAILABLE and SirensTear == QUEST_COMPLETED and SirensTear == QUEST_COMPLETED) then
if (player:getFameLevel(BASTOK) >= 5 and player:seenKeyItem(CARRIER_PIGEON_LETTER) == true) then
player:startEvent(0x00b9);
else
player:startEvent(0x00bb);
end
elseif (LoveAndIce == QUEST_ACCEPTED and LoveAndIceProgress == 1) then
player:startEvent(0x00ba);
elseif (player:getFameLevel(BASTOK) >= 7 and ATestOfTrueLove == QUEST_AVAILABLE and LoveAndIce == QUEST_COMPLETED and player:needToZone() == false) then
player:startEvent(0x010e);
elseif (ATestOfTrueLove == QUEST_ACCEPTED and ATestOfTrueLoveProgress < 3) then
player:startEvent(0x010f);
elseif (ATestOfTrueLove == QUEST_ACCEPTED and ATestOfTrueLoveProgress == 3) then
player:startEvent(0x0110);
elseif (ATestOfTrueLove == QUEST_ACCEPTED and ATestOfTrueLoveProgress == 4 and player:needToZone() == true) then
player:startEvent(0x0111);
elseif (ATestOfTrueLove == QUEST_ACCEPTED and ATestOfTrueLoveProgress == 4 and player:needToZone() == false) then
player:startEvent(0x0112);
elseif (LoversInTheDusk == QUEST_AVAILABLE and ATestOfTrueLove == QUEST_COMPLETED and player:needToZone() == false) then
player:startEvent(0x0113);
elseif (LoversInTheDusk == QUEST_ACCEPTED) then
player:startEvent(0x0114);
elseif (LoversInTheDusk == QUEST_COMPLETED) then
player:startEvent(0x0115);
else
player:startEvent(0x00b6);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0006) then
player:setVar("SirensTear",1);
elseif (csid == 0x0013) then
player:setVar("SirensTear",2);
elseif (csid == 0x00b9) then
player:addQuest(BASTOK,LOVE_AND_ICE);
player:addKeyItem(CARMELOS_SONG_SHEET);
player:messageSpecial(KEYITEM_OBTAINED,CARMELOS_SONG_SHEET);
elseif (csid == 0x00ba) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17356);
else
player:setVar("LoveAndIceProgress",0);
player:needToZone(true);
player:addTitle(SORROW_DROWNER);
player:addItem(17356);
player:messageSpecial(ITEM_OBTAINED,17356); -- Lamia Harp
player:addFame(BASTOK,120);
player:completeQuest(BASTOK,LOVE_AND_ICE);
end
elseif (csid == 0x010e) then
player:addQuest(BASTOK,A_TEST_OF_TRUE_LOVE);
elseif (csid == 0x0110) then
player:setVar("ATestOfTrueLoveProgress",4);
player:needToZone(true);
elseif (csid == 0x0112) then
player:setVar("ATestOfTrueLoveProgress",0);
player:needToZone(true);
player:addFame(BASTOK,120);
player:completeQuest(BASTOK,A_TEST_OF_TRUE_LOVE);
elseif (csid == 0x0113) then
player:addQuest(BASTOK,LOVERS_IN_THE_DUSK);
player:addKeyItem(CHANSON_DE_LIBERTE);
player:messageSpecial(KEYITEM_OBTAINED,CHANSON_DE_LIBERTE);
end
end; | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Southern_San_dOria/npcs/Phillone.lua | 17 | 1459 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Phillone
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01D);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Colettechan/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Fubruhn.lua | 13 | 5845 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Fubruhn
-- Mog Locker NPC
--
-- Event IDs:
-- 0x0258 = Not a mercenary + mog locker options
-- 1st arg = Amount of time left on lease, as seconds past 2001/12/31 15:00:00.
-- If this is 0, it shows the not a mecenary message instead.
-- If this is -1, it shows the lease as expired.
-- 2nd arg = Valid areas, 0=alzahbi only, 1=all areas
-- 3rd arg = The number of earth days a lease extension is valid for (7)
-- 4th arg = How big your locker is
-- 5th arg =
-- 6th arg =
-- 7th arg =
-- 8th arg = The number of days your lease is currently valid for
--
-- 0x0259 = Lease increased
-- 1st arg = number of seconds from 2001/12/31 15:00:00 it is valid till.
--
-- 0x025A = Expansion increased
-- 4th arg = new size of locker
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/status");
require("scripts/globals/missions");
require("scripts/globals/moghouse");
function getNumberOfCoinsToUpgradeSize(size)
if (size == 30) then
return 4;
elseif (size == 40) then
return 2;
elseif (size == 50) then
return 3;
elseif (size == 60) then
return 5;
elseif (size == 70) then
return 10;
elseif (size == 80) then
return 0;
end
end
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local numBronze = trade:getItemQty(2184);
local numMythril = trade:getItemQty(2186);
local numGold = trade:getItemQty(2187);
if (player:getCurrentMission(TOAU) >= 2) then
if (numBronze > 0 and numMythril == 0 and numGold == 0) then
if (addMogLockerExpiryTime(player, numBronze)) then
-- remove bronze
player:tradeComplete();
-- send event
player:startEvent(0x0259, getMogLockerExpiryTimestamp(player));
-- print("Expanded lease with "..numBronze.." bronze.");
end
elseif (numGold > 0 or numMythril > 0) then
-- see if we can expand the size
local slotSize = player:getContainerSize(LOC_MOGLOCKER);
if (slotSize == 30 and numMythril == 4 and numGold == 0) then
player:changeContainerSize(LOC_MOGLOCKER, 10);
player:tradeComplete();
player:startEvent(0x025A,0,0,0,40);
elseif (slotSize == 40 and numMythril == 0 and numGold == 2) then
player:changeContainerSize(LOC_MOGLOCKER, 10);
player:tradeComplete();
player:startEvent(0x025A,0,0,0,50);
elseif (slotSize == 50 and numMythril == 0 and numGold == 3) then
player:changeContainerSize(LOC_MOGLOCKER, 10);
player:tradeComplete();
player:startEvent(0x025A,0,0,0,60);
elseif (slotSize == 60 and numMythril == 0 and numGold == 5) then
player:changeContainerSize(LOC_MOGLOCKER, 10);
player:tradeComplete();
player:startEvent(0x025A,0,0,0,70);
elseif (slotSize == 70 and numMythril == 0 and numGold == 10) then
player:changeContainerSize(LOC_MOGLOCKER, 10);
player:tradeComplete();
player:startEvent(0x025A,0,0,0,80);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- TODO: Check if they are >= Mission 2
-- if < mission 2 then
-- player:startEvent(0x0258);
-- else
if (player:getCurrentMission(TOAU) >= 2) then
local accessType = getMogLockerAccessType(player);
local mogLockerExpiryTimestamp = getMogLockerExpiryTimestamp(player);
if (mogLockerExpiryTimestamp == nil) then
-- a nil timestamp means they haven't unlocked it yet. We're going to unlock it by merely talking to this NPC.
--print("Unlocking mog locker for "..player:getName());
mogLockerExpiryTimestamp = unlockMogLocker(player);
accessType = setMogLockerAccessType(player, MOGLOCKER_ACCESS_TYPE_ALLAREAS);
end
player:startEvent(0x0258,mogLockerExpiryTimestamp,accessType,
MOGLOCKER_ALZAHBI_VALID_DAYS,player:getContainerSize(LOC_MOGLOCKER),
getNumberOfCoinsToUpgradeSize(player:getContainerSize(LOC_MOGLOCKER)),2,3,
MOGLOCKER_ALLAREAS_VALID_DAYS);
else
player:startEvent(0x0258);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("fCSID: %u",csid);
--printf("fRESULT: %u",option);
if (csid == 600 and option == 3) then
local accessType = player:getVar(MOGLOCKER_PLAYERVAR_ACCESS_TYPE);
if (accessType == MOGLOCKER_ACCESS_TYPE_ALLAREAS) then
-- they want to restrict their access to alzahbi only
setMogLockerAccessType(player, MOGLOCKER_ACCESS_TYPE_ALZAHBI);
elseif (accessType == MOGLOCKER_ACCESS_TYPE_ALZAHBI) then
-- they want to expand their access to all areas.
setMogLockerAccessType(player, MOGLOCKER_ACCESS_TYPE_ALLAREAS);
else
print("Unknown mog locker access type: "..accessType);
end
end
end;
| gpl-3.0 |
Colettechan/darkstar | scripts/zones/The_Garden_of_RuHmet/bcnms/when_angels_fall.lua | 30 | 2268 | -----------------------------------
-- Area: The_Garden_of_RuHmet
-- Name: when_angels_fall
-----------------------------------
package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/The_Garden_of_RuHmet/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==4) then
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0);
player:setVar("PromathiaStatus",5);
else
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); --
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
--printf("leavecode: %u",leavecode);
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid== 0x7d01) then
player:setPos(420,0,445,192);
end
end; | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Tavnazian_Safehold/npcs/Suzel.lua | 14 | 1058 | ----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Suzel
-- Type: Item Deliverer
-- @zone 26
-- @pos -72.701 -20.25 -64.058
--
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, ITEM_DELIVERY_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
aleksijuvani/premake-core | tests/tools/test_msc.lua | 2 | 9664 | --
-- tests/test_msc.lua
-- Automated test suite for the Microsoft C toolset interface.
-- Copyright (c) 2012-2013 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("tools_msc")
local msc = p.tools.msc
--
-- Setup/teardown
--
local wks, prj, cfg
function suite.setup()
wks, prj = test.createWorkspace()
kind "SharedLib"
end
local function prepare()
cfg = test.getconfig(prj, "Debug")
end
--
-- Check the optimization flags.
--
function suite.cflags_onNoOptimize()
optimize "Off"
prepare()
test.contains("/Od", msc.getcflags(cfg))
end
function suite.cflags_onOptimize()
optimize "On"
prepare()
test.contains("/Ot", msc.getcflags(cfg))
end
function suite.cflags_onOptimizeSize()
optimize "Size"
prepare()
test.contains("/O1", msc.getcflags(cfg))
end
function suite.cflags_onOptimizeSpeed()
optimize "Speed"
prepare()
test.contains("/O2", msc.getcflags(cfg))
end
function suite.cflags_onOptimizeFull()
optimize "Full"
prepare()
test.contains("/Ox", msc.getcflags(cfg))
end
function suite.cflags_onOptimizeDebug()
optimize "Debug"
prepare()
test.contains("/Od", msc.getcflags(cfg))
end
function suite.cflags_onNoFramePointers()
flags "NoFramePointer"
prepare()
test.contains("/Oy", msc.getcflags(cfg))
end
function suite.ldflags_onLinkTimeOptimizations()
flags "LinkTimeOptimization"
prepare()
test.contains("/GL", msc.getldflags(cfg))
end
function suite.cflags_onStringPoolingOn()
stringpooling "On"
prepare()
test.contains("/GF", msc.getcflags(cfg))
end
function suite.cflags_onStringPoolingOff()
stringpooling "Off"
prepare()
test.contains("/GF-", msc.getcflags(cfg))
end
function suite.cflags_onStringPoolingNotSpecified()
prepare()
test.excludes("/GF", msc.getcflags(cfg))
test.excludes("/GF-", msc.getcflags(cfg))
end
function suite.cflags_onFloatingPointExceptionsOn()
floatingpointexceptions "On"
prepare()
test.contains("/fp:except", msc.getcflags(cfg))
end
function suite.cflags_onFloatingPointExceptionsOff()
floatingpointexceptions "Off"
prepare()
test.contains("/fp:except-", msc.getcflags(cfg))
end
function suite.cflags_onFloatingPointExceptionsNotSpecified()
prepare()
test.excludes("/fp:except", msc.getcflags(cfg))
test.excludes("/fp:except-", msc.getcflags(cfg))
end
function suite.cflags_onFunctionLevelLinkingOn()
functionlevellinking "On"
prepare()
test.contains("/Gy", msc.getcflags(cfg))
end
function suite.cflags_onFunctionLevelLinkingOff()
functionlevellinking "Off"
prepare()
test.contains("/Gy-", msc.getcflags(cfg))
end
function suite.cflags_onFunctionLevelLinkingNotSpecified()
prepare()
test.excludes("/Gy", msc.getcflags(cfg))
test.excludes("/Gy-", msc.getcflags(cfg))
end
function suite.cflags_onIntrinsicsOn()
intrinsics "On"
prepare()
test.contains("/Oi", msc.getcflags(cfg))
end
--
-- Check the translation of symbols.
--
function suite.cflags_onDefaultSymbols()
prepare()
test.excludes({ "/Z7" }, msc.getcflags(cfg))
end
function suite.cflags_onNoSymbols()
symbols "Off"
prepare()
test.excludes({ "/Z7" }, msc.getcflags(cfg))
end
function suite.cflags_onSymbols()
symbols "On"
prepare()
test.contains({ "/Z7" }, msc.getcflags(cfg))
end
--
-- Check handling of debugging support.
--
function suite.ldflags_onSymbols()
symbols "On"
prepare()
test.contains("/DEBUG", msc.getldflags(cfg))
end
--
-- Check handling warnings and errors.
--
function suite.cflags_OnNoWarnings()
warnings "Off"
prepare()
test.contains("/W0", msc.getcflags(cfg))
end
function suite.cflags_OnHighWarnings()
warnings "High"
prepare()
test.contains("/W4", msc.getcflags(cfg))
end
function suite.cflags_OnExtraWarnings()
warnings "Extra"
prepare()
test.contains("/W4", msc.getcflags(cfg))
end
function suite.cflags_OnFatalWarnings()
flags "FatalWarnings"
prepare()
test.contains("/WX", msc.getcflags(cfg))
end
function suite.cflags_onSpecificWarnings()
enablewarnings { "enable" }
disablewarnings { "disable" }
fatalwarnings { "fatal" }
prepare()
test.contains({ '/wd"disable"', '/we"fatal"' }, msc.getcflags(cfg))
end
function suite.ldflags_OnFatalWarnings()
flags "FatalWarnings"
prepare()
test.contains("/WX", msc.getldflags(cfg))
end
--
-- Check handling of library search paths.
--
function suite.libdirs_onLibdirs()
libdirs { "../libs" }
prepare()
test.contains('/LIBPATH:"../libs"', msc.getLibraryDirectories(cfg))
end
--
-- Check handling of forced includes.
--
function suite.forcedIncludeFiles()
forceincludes { "include/sys.h" }
prepare()
test.contains('/FIinclude/sys.h', msc.getforceincludes(cfg))
end
--
-- Check handling of floating point modifiers.
--
function suite.cflags_onFloatingPointFast()
floatingpoint "Fast"
prepare()
test.contains("/fp:fast", msc.getcflags(cfg))
end
function suite.cflags_onFloatingPointStrict()
floatingpoint "Strict"
prepare()
test.contains("/fp:strict", msc.getcflags(cfg))
end
function suite.cflags_onSSE()
vectorextensions "SSE"
prepare()
test.contains("/arch:SSE", msc.getcflags(cfg))
end
function suite.cflags_onSSE2()
vectorextensions "SSE2"
prepare()
test.contains("/arch:SSE2", msc.getcflags(cfg))
end
function suite.cflags_onAVX()
vectorextensions "AVX"
prepare()
test.contains("/arch:AVX", msc.getcflags(cfg))
end
function suite.cflags_onAVX2()
vectorextensions "AVX2"
prepare()
test.contains("/arch:AVX2", msc.getcflags(cfg))
end
--
-- Check the defines and undefines.
--
function suite.defines()
defines "DEF"
prepare()
test.contains({ '/D"DEF"' }, msc.getdefines(cfg.defines, cfg))
end
function suite.undefines()
undefines "UNDEF"
prepare()
test.contains({ '/U"UNDEF"' }, msc.getundefines(cfg.undefines))
end
--
-- Check compilation options.
--
function suite.cflags_onNoMinimalRebuild()
flags "NoMinimalRebuild"
prepare()
test.contains("/Gm-", msc.getcflags(cfg))
end
function suite.cflags_onMultiProcessorCompile()
flags "MultiProcessorCompile"
prepare()
test.contains("/MP", msc.getcflags(cfg))
end
--
-- Check handling of C++ language features.
--
function suite.cxxflags_onExceptions()
exceptionhandling "on"
prepare()
test.contains("/EHsc", msc.getcxxflags(cfg))
end
function suite.cxxflags_onSEH()
exceptionhandling "SEH"
prepare()
test.contains("/EHa", msc.getcxxflags(cfg))
end
function suite.cxxflags_onNoExceptions()
exceptionhandling "Off"
prepare()
test.missing("/EHsc", msc.getcxxflags(cfg))
end
function suite.cxxflags_onNoRTTI()
rtti "Off"
prepare()
test.contains("/GR-", msc.getcxxflags(cfg))
end
--
-- Check handling of additional linker options.
--
function suite.ldflags_onOmitDefaultLibrary()
flags "OmitDefaultLibrary"
prepare()
test.contains("/NODEFAULTLIB", msc.getldflags(cfg))
end
function suite.ldflags_onNoIncrementalLink()
flags "NoIncrementalLink"
prepare()
test.contains("/INCREMENTAL:NO", msc.getldflags(cfg))
end
function suite.ldflags_onNoManifest()
flags "NoManifest"
prepare()
test.contains("/MANIFEST:NO", msc.getldflags(cfg))
end
function suite.ldflags_onDLL()
kind "SharedLib"
prepare()
test.contains("/DLL", msc.getldflags(cfg))
end
--
-- Check handling of CLR settings.
--
function suite.cflags_onClrOn()
clr "On"
prepare()
test.contains("/clr", msc.getcflags(cfg))
end
function suite.cflags_onClrUnsafe()
clr "Unsafe"
prepare()
test.contains("/clr", msc.getcflags(cfg))
end
function suite.cflags_onClrSafe()
clr "Safe"
prepare()
test.contains("/clr:safe", msc.getcflags(cfg))
end
function suite.cflags_onClrPure()
clr "Pure"
prepare()
test.contains("/clr:pure", msc.getcflags(cfg))
end
--
-- Check handling of character set switches
--
function suite.cflags_onCharSetDefault()
prepare()
test.contains('/D"_UNICODE"', msc.getdefines(cfg.defines, cfg))
end
function suite.cflags_onCharSetUnicode()
characterset "Unicode"
prepare()
test.contains('/D"_UNICODE"', msc.getdefines(cfg.defines, cfg))
end
function suite.cflags_onCharSetMBCS()
characterset "MBCS"
prepare()
test.contains('/D"_MBCS"', msc.getdefines(cfg.defines, cfg))
end
function suite.cflags_onCharSetASCII()
characterset "ASCII"
prepare()
test.excludes({'/D"_MBCS"', '/D"_UNICODE"'}, msc.getdefines(cfg.defines, cfg))
end
--
-- Check handling of system search paths.
--
function suite.includeDirs_onSysIncludeDirs()
sysincludedirs { "/usr/local/include" }
prepare()
test.contains("-I/usr/local/include", msc.getincludedirs(cfg, cfg.includedirs, cfg.sysincludedirs))
end
function suite.libDirs_onSysLibDirs()
syslibdirs { "/usr/local/lib" }
prepare()
test.contains('/LIBPATH:"/usr/local/lib"', msc.getLibraryDirectories(cfg))
end
--
-- Check handling of ignore default libraries
--
function suite.ignoreDefaultLibraries_WithExtensions()
ignoredefaultlibraries { "lib1.lib" }
prepare()
test.contains('/NODEFAULTLIB:lib1.lib', msc.getldflags(cfg))
end
function suite.ignoreDefaultLibraries_WithoutExtensions()
ignoredefaultlibraries { "lib1" }
prepare()
test.contains('/NODEFAULTLIB:lib1.lib', msc.getldflags(cfg))
end
--
-- Check handling of shared C/C++ flags.
--
function suite.mixedToolFlags_onCFlags()
flags { "FatalCompileWarnings" }
prepare()
test.isequal({ "/WX", "/MD" }, msc.getcflags(cfg))
end
function suite.mixedToolFlags_onCxxFlags()
flags { "FatalCompileWarnings" }
prepare()
test.isequal({ "/WX", "/MD", "/EHsc" }, msc.getcxxflags(cfg))
end
| bsd-3-clause |
Vadavim/jsr-darkstar | scripts/globals/spells/armys_paeon_vi.lua | 1 | 1499 | -----------------------------------------
-- Spell: Army's Paeon VI
-- Gradually restores target's HP.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iType = caster:getWeaponSkillType(SLOT_RANGED);
local iLvl = 0;
if (iType == SKILL_WND or iType == SKILL_STR) then
iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
end
local power = 6;
if (sLvl+iLvl > 450) then
power = power + 1;
end
local iBoost = caster:getMod(MOD_PAEON_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 600;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_PAEON,power,0,duration,caster:getID(), 0, 6)) then
spell:setMsg(75);
end
return EFFECT_PAEON;
end; | gpl-3.0 |
zynjec/darkstar | scripts/globals/items/dish_of_spaghetti_carbonara.lua | 11 | 1545 | -----------------------------------------
-- ID: 5190
-- Item: dish_of_spaghetti_carbonara
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health % 14
-- Health Cap 175
-- Magic 10
-- Strength 4
-- Vitality 2
-- Intelligence -3
-- Attack % 17
-- Attack Cap 65
-- Store TP 6
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5190)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.FOOD_HPP, 14)
target:addMod(dsp.mod.FOOD_HP_CAP, 175)
target:addMod(dsp.mod.MP, 10)
target:addMod(dsp.mod.STR, 4)
target:addMod(dsp.mod.VIT, 2)
target:addMod(dsp.mod.INT, -3)
target:addMod(dsp.mod.FOOD_ATTP, 17)
target:addMod(dsp.mod.FOOD_ATT_CAP, 65)
target:addMod(dsp.mod.STORETP, 6)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 14)
target:delMod(dsp.mod.FOOD_HP_CAP, 175)
target:delMod(dsp.mod.MP, 10)
target:delMod(dsp.mod.STR, 4)
target:delMod(dsp.mod.VIT, 2)
target:delMod(dsp.mod.INT, -3)
target:delMod(dsp.mod.FOOD_ATTP, 17)
target:delMod(dsp.mod.FOOD_ATT_CAP, 65)
target:delMod(dsp.mod.STORETP, 6)
end
| gpl-3.0 |
zynjec/darkstar | scripts/commands/animation.lua | 14 | 1156 | ---------------------------------------------------------------------------------------------------
-- func: animation
-- desc: Sets the players current animation.
---------------------------------------------------------------------------------------------------
require("scripts/globals/status");
cmdprops =
{
permission = 1,
parameters = "s"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!animation {animationID}");
end;
function onTrigger(player, animationId)
local oldAnimation = player:getAnimation();
if (animationId == nil) then
player:PrintToPlayer(string.format("Current player animation: %d", oldAnimation));
return;
end
-- validate animationId
animationId = tonumber(animationId) or dsp.anim[string.upper(animationId)];
if (animationId == nil or animationId < 0) then
error(player, "Invalid animationId.");
return;
end
-- set player animation
player:setAnimation(animationId);
player:PrintToPlayer(string.format("%s | Old animation: %i | New animation: %i\n", player:getName(), oldAnimation, animationId));
end
| gpl-3.0 |
Vadavim/jsr-darkstar | scripts/globals/mobskills/Cocoon.lua | 1 | 1310 | ---------------------------------------------------
-- Cocoon
-- Enhances defense.
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local hard = mob:getMobMod(MOBMOD_HARD_MODE);
local tp = skill:getTP();
local duration = 35 * fTP(tp, 1, 1.5, 2) * (1 + hard / 5)
local typeEffect = EFFECT_DEFENSE_BOOST;
skill:setMsg(MobBuffMove(mob, typeEffect, 50 + hard * 3, 0, duration));
local effect = mob:getStatusEffect(EFFECT_DEFENSE_BOOST);
if (effect ~= niil) then
effect:addMod(MOD_FIREDEF, -60);
target:addMod(MOD_FIREDEF, -60);
effect:addMod(MOD_EARTHDEF, 60);
target:addMod(MOD_EARTHDEF, 60);
end
if (hard > 0 ) then
if (effect ~= nil) then
local power = 1 + (mob:getMainLvl() / 4) * (1 + hard / 5);
effect:addMod(MOD_SPIKES, 8);
target:addMod(MOD_SPIKES, 8);
effect:addMod(MOD_SPIKES_DMG, power);
target:addMod(MOD_SPIKES_DMG, power);
end
end
return typeEffect;
end;
| gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Windurst_Waters/npcs/Amagusa-Chigurusa.lua | 14 | 1468 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Amagusa-Chigurusa
-- Type: Standard NPC
-- @pos -28.746 -4.5 61.954 238
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,12) == false) then
player:startEvent(0x03a9);
else
player:startEvent(0x0232);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x03a9) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",12,true);
end
end;
| gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Windurst_Woods/npcs/Kuzah_Hpirohpon.lua | 27 | 1199 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Kuzah Hpirohpon
-- Guild Merchant NPC: Clothcrafting Guild
-- @pos -80.068 -3.25 -127.686 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(5152,6,21,0)) then
player:showText(npc,KUZAH_HPIROHPON_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Colettechan/darkstar | scripts/zones/The_Boyahda_Tree/npcs/HomePoint#1.lua | 27 | 1273 | -----------------------------------
-- Area: The Boyahda Tree
-- NPC: HomePoint#1
-- @pos 88 -15 -217 153
-----------------------------------
package.loaded["scripts/zones/The_Boyahda_Tree/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/The_Boyahda_Tree/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 92);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
Joker-development/Joker_development | plugins/welcome.lua | 4 | 3920 | --[[
# For More Information ....!
# Developer : Aziz < @devss_bot > #Dev
# our channel: @help_tele
]]
local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nAbout :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "HI🍷🌝 "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use help for see bot commands\n"
local text = sambutan.."and You can see rules 🙏🏿 "
local text = text..""
local text = text.." "
local text = text.."Out of the group kickme ☹️"
local text = text.."\n"
local text = text.."CHANNEL BOT : @help_tele"
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Good Bye My Friend '..bye_name
end
end
return {
description = "Welcoming Message",
usage = "send message to new member",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
} | gpl-2.0 |
Colettechan/darkstar | scripts/globals/abilities/ice_maneuver.lua | 19 | 1600 | -----------------------------------
-- Ability: Ice Maneuver
-- Enhances the effect of ice attachments. Must have animator equipped.
-- Obtained: Puppetmaster level 1
-- Recast Time: 10 seconds (shared with all maneuvers)
-- Duration: 1 minute
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getWeaponSubSkillType(SLOT_RANGED) == 10 and
not player:hasStatusEffect(EFFECT_OVERLOAD)) then
return 0,0;
else
return 71,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local burden = 15;
if (target:getStat(MOD_INT) < target:getPet():getStat(MOD_INT)) then
burden = 20;
end
local overload = target:addBurden(ELE_ICE-1, burden);
if (overload ~= 0) then
target:removeAllManeuvers();
target:addStatusEffect(EFFECT_OVERLOAD, 0, 0, overload);
else
local level;
if (target:getMainJob() == JOBS.PUP) then
level = target:getMainLvl()
else
level = target:getSubLvl()
end
local bonus = 1 + (level/15) + target:getMod(MOD_MANEUVER_BONUS);
if (target:getActiveManeuvers() == 3) then
target:removeOldestManeuver();
end
target:addStatusEffect(EFFECT_ICE_MANEUVER, bonus, 0, 60);
end
return EFFECT_ICE_MANEUVER;
end; | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/globals/effects/fenrirs_favor.lua | 1 | 1266 | -----------------------------------
--
--
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DARKACC,10);
target:addMod(MOD_DARKATT,10);
target:addMod(MOD_DARKDEF,25);
target:addMod(MOD_DARKRES,40);
target:addMod(MOD_MEVA, 20);
target:addMod(MOD_SUBTLE_BLOW, 30);
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
if (not target:isPet()) then
return;
end
local owner = target:getMaster();
local party = owner:getParty(true);
if (party ~= nil) then
for i,member in ipairs(party) do
member:addStatusEffect(EFFECT_FENRIR_S_FAVOR, effect:getPower(), 0, 16);
end
end
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DARKACC,10);
target:delMod(MOD_DARKATT,10);
target:delMod(MOD_DARKDEF,25);
target:delMod(MOD_DARKRES,40);
target:delMod(MOD_MEVA, 20);
target:delMod(MOD_SUBTLE_BLOW, 30);
end; | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Balgas_Dais/mobs/Maat.lua | 14 | 1549 | -----------------------------------
-- Area: Balga Dais
-- MOB: Maat
-- Genkai 5 Fight
-----------------------------------
package.loaded["scripts/zones/Balgas_Dais/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Balgas_Dais/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob,target)
-- target:showText(mob,YOU_DECIDED_TO_SHOW_UP);
printf("Maat Balga Dais works");
-- When he take damage: target:showText(mob,THAT_LL_HURT_IN_THE_MORNING);
-- He use dragon kick or tackle: target:showText(mob,TAKE_THAT_YOU_WHIPPERSNAPPER);
-- He use spining attack: target:showText(mob,TEACH_YOU_TO_RESPECT_ELDERS);
-- If you dying: target:showText(mob,LOOKS_LIKE_YOU_WERENT_READY);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob, target)
local bf = mob:getBattlefield();
if (mob:getHPP() <20) then
bf:win();
return;
-- WHM's Maat additionally gives up if kept fighting for 5 min
elseif (target:getMainJob() == JOBS.WHM and mob:getBattleTime() > 300) then
bf:win();
return;
end
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:showText(mob,YOUVE_COME_A_LONG_WAY);
end;
| gpl-3.0 |
Colettechan/darkstar | scripts/zones/Lower_Jeuno/npcs/_l04.lua | 13 | 1553 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- @zone 245
-- @pos -73.039 6 -95.633
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
if (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then
if (player:getVar("cService") == 7) then
player:setVar("cService",8);
end
elseif (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (player:getVar("cService") == 20) then
player:setVar("cService",21);
end
end
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Colettechan/darkstar | scripts/globals/items/remedy.lua | 17 | 1283 | -----------------------------------------
-- ID: 4155
-- Item: Remedy
-- Item Effect: This potion remedies status ailments.
-- Works on paralysis, silence, blindness, poison, and disease.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
return 0;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
if (target:hasStatusEffect(EFFECT_SILENCE) == true) then
target:delStatusEffect(EFFECT_SILENCE);
end
if (target:hasStatusEffect(EFFECT_BLINDNESS) == true) then
target:delStatusEffect(EFFECT_BLINDNESS);
end
if (target:hasStatusEffect(EFFECT_POISON) == true) then
target:delStatusEffect(EFFECT_POISON);
end
if (target:hasStatusEffect(EFFECT_PARALYSIS) == true) then
target:delStatusEffect(EFFECT_PARALYSIS);
end
rDisease = math.random(1,2) -- Disease is not garunteed to be cured, 1 means removed 2 means fail. 50% chance
if (rDisease == 1 and target:hasStatusEffect(EFFECT_DISEASE) == true) then
target:delStatusEffect(EFFECT_DISEASE);
end
end;
| gpl-3.0 |
Colettechan/darkstar | scripts/globals/mobskills/Miasma.lua | 33 | 1139 | ---------------------------------------------
-- Miasma
--
-- Description: Releases a toxic cloud on nearby targets. Additional effects: Slow + Poison + Plague
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows?
-- Range: Less than or equal to 10.0
-- Notes: Only used by Gulool Ja Ja.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local duration = 180;
MobStatusEffectMove(mob, target, EFFECT_POISON, mob:getMainLvl()/3, 3, 60);
MobStatusEffectMove(mob, target, EFFECT_SLOW, 128, 3, 120);
MobStatusEffectMove(mob, target, EFFECT_PLAGUE, 5, 3, 60);
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*4,ELE_EARTH,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_EARTH,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
reaperrr/OpenRA | mods/ra/maps/production-disruption/production-disruption.lua | 7 | 8379 | --[[
Copyright 2007-2022 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
TimerTicks = DateTime.Minutes(12)
LSTType = "lst.reinforcement"
RifleSquad1 = { Rifle1, Rifle2, Rifle3 }
RifleSquad2 = { Rifle4, Rifle5, Rifle6 }
Heavys = { Heavy1, Heavy2 }
FlameTowerWall = { FlameTower1, FlameTower2 }
DemoEngiPath = { WaterEntry1.Location, Beach1.Location }
DemoEngiTeam = { "dtrk", "dtrk", "e6", "e6", "e6" }
SovietWaterEntry1 = { WaterEntry2.Location, Beach2.Location }
SovietWaterEntry2 = { WaterEntry2.Location, Beach3.Location }
SovietSquad = { "e1", "e1", "e1", "e4", "e4" }
V2Squad = { "v2rl", "v2rl" }
SubEscapePath = { SubPath1, SubPath2, SubPath3 }
MissionStart = function()
LZCamera = Actor.Create("camera", true, { Owner = Greece, Location = LZ.Location })
Chalk1.TargetParatroopers(LZ.CenterPosition, Angle.New(740))
if Difficulty == "normal" then
Actor.Create("tsla", true, { Owner = USSR, Location = EasyCamera.Location })
Actor.Create("4tnk", true, { Owner = USSR, Facing = Angle.South, Location = Mammoth.Location })
Actor.Create("4tnk", true, { Owner = USSR, Facing = Angle.South, Location = Mammoth.Location + CVec.New(1,0) })
Actor.Create("v2rl", true, { Owner = USSR, Facing = Angle.South, Location = V2.Location })
end
Trigger.AfterDelay(DateTime.Seconds(1), function()
Chalk2.TargetParatroopers(LZ.CenterPosition, Angle.New(780))
end)
Trigger.AfterDelay(DateTime.Seconds(5), function()
UnitsArrived = true
TeslaCamera = Actor.Create("camera", true, { Owner = Greece, Location = TeslaCam.Location })
end)
Trigger.AfterDelay(DateTime.Seconds(10), function()
LZCamera.Destroy()
Utils.Do(RifleSquad1, function(actor)
if not actor.IsDead then
actor.AttackMove(LZ.Location)
IdleHunt(actor)
end
end)
end)
Trigger.AfterDelay(DateTime.Seconds(15), function()
TeslaCamera.Destroy()
Utils.Do(RifleSquad2, function(actor)
if not actor.IsDead then
actor.AttackMove(LZ.Location)
IdleHunt(actor)
end
end)
end)
end
SetupTriggers = function()
Trigger.OnDamaged(SubPen, function()
Utils.Do(Heavys, function(actor)
if not actor.IsDead then
IdleHunt(actor)
end
end)
end)
Trigger.OnKilled(Church, function()
Actor.Create("healcrate", true, { Owner = Greece, Location = ChurchCrate.Location })
end)
Trigger.OnKilled(ObjectiveDome, function()
if not DomeCaptured == true then
Greece.MarkFailedObjective(CaptureDome)
end
end)
Trigger.OnAllKilled(FlameTowerWall, function()
DomeCam = Actor.Create("camera", true, { Owner = Greece, Location = RadarCam.Location })
Trigger.AfterDelay(DateTime.Seconds(5), function()
DomeCam.Destroy()
end)
end)
Trigger.OnKilledOrCaptured(SubPen, function()
Greece.MarkCompletedObjective(StopProduction)
end)
end
PowerDown = false
PowerDownTeslas = function()
if not PowerDown then
CaptureDome = Greece.AddObjective("Capture the enemy radar dome.", "Secondary", false)
Greece.MarkCompletedObjective(PowerDownTeslaCoils)
Media.PlaySpeechNotification(Greece, "ReinforcementsArrived")
PowerDown = true
local bridge = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "bridge1" end)[1]
if not bridge.IsDead then
bridge.Kill()
end
local demoEngis = Reinforcements.ReinforceWithTransport(Greece, LSTType, DemoEngiTeam, DemoEngiPath, { DemoEngiPath[1] })[2]
Trigger.OnAllRemovedFromWorld(Utils.Where(demoEngis, function(a) return a.Type == "e6" end), function()
if not DomeCaptured then
Greece.MarkFailedObjective(CaptureDome)
end
if not DomeCaptured and bridge.IsDead then
Greece.MarkFailedObjective(StopProduction)
end
end)
Trigger.OnCapture(ObjectiveDome, function()
DomeCaptured = true
Greece.MarkCompletedObjective(CaptureDome)
SendChronos()
end)
FlameTowersCam = Actor.Create("camera", true, { Owner = Greece, Location = FlameCam.Location })
Trigger.AfterDelay(DateTime.Seconds(10), function()
FlameTowersCam.Destroy()
end)
end
end
SendChronos = function()
Trigger.AfterDelay(DateTime.Seconds(3), function()
local sovietWaterSquad1 = Reinforcements.ReinforceWithTransport(USSR, "lst", SovietSquad, { WaterEntry2.Location, Beach2.Location }, { WaterEntry2.Location })[2]
Utils.Do(sovietWaterSquad1, function(a)
Trigger.OnAddedToWorld(a, function()
IdleHunt(a)
end)
end)
Actor.Create("ctnk", true, { Owner = Greece, Location = ChronoSpawn1.Location })
Actor.Create("ctnk", true, { Owner = Greece, Location = ChronoSpawn2.Location })
Actor.Create("ctnk", true, { Owner = Greece, Location = ChronoSpawn3.Location })
Actor.Create("camera", true, { Owner = Greece, Location = EasyCamera.Location })
Media.PlaySound("chrono2.aud")
end)
Trigger.AfterDelay(DateTime.Seconds(5), function()
local sovietWaterSquad2 = Reinforcements.ReinforceWithTransport(USSR, "lst", SovietSquad, { WaterEntry2.Location, Beach3.Location }, { WaterEntry2.Location })[2]
Utils.Do(sovietWaterSquad2, function(a)
Trigger.OnAddedToWorld(a, function()
a.AttackMove(FlameCam.Location)
IdleHunt(a)
end)
end)
end)
Trigger.AfterDelay(DateTime.Seconds(13), function()
local sovietWaterSquad2 = Reinforcements.ReinforceWithTransport(USSR, "lst", V2Squad, { WaterEntry2.Location, Beach2.Location }, { WaterEntry2.Location })[2]
Utils.Do(sovietWaterSquad2, function(a)
Trigger.OnAddedToWorld(a, function()
a.AttackMove(FlameCam.Location)
IdleHunt(a)
end)
end)
end)
end
MissileSubEscape = function()
local missileSub = Actor.Create("msub", true, { Owner = USSR, Location = MissileSubSpawn.Location })
Actor.Create("camera", true, { Owner = Greece, Location = SubPath2.Location })
DestroySub = Greece.AddPrimaryObjective("Destroy the submarine before it escapes!.")
Utils.Do(SubEscapePath, function(waypoint)
missileSub.Move(waypoint.Location)
end)
Trigger.OnEnteredFootprint({ SubPath3.Location }, function(a, id)
if a.Owner == USSR and a.Type == "msub" then
Trigger.RemoveFootprintTrigger(id)
USSR.MarkCompletedObjective(EscapeWithSub)
end
end)
Trigger.OnKilled(missileSub, function()
Greece.MarkCompletedObjective(DestroySub)
end)
end
FinishTimer = function()
for i = 0, 5 do
local c = TimerColor
if i % 2 == 0 then
c = HSLColor.White
end
Trigger.AfterDelay(DateTime.Seconds(i), function() UserInterface.SetMissionText("The sub is heading for open sea!", c) end)
end
Trigger.AfterDelay(DateTime.Seconds(6), function() UserInterface.SetMissionText("") end)
end
UnitsArrived = false
TimerFinished = false
ticked = TimerTicks
Tick = function()
if BadGuy.PowerState ~= "Normal" then
PowerDownTeslas()
end
if Greece.HasNoRequiredUnits() and UnitsArrived then
USSR.MarkCompletedObjective(EscapeWithSub)
end
if ticked > 0 then
UserInterface.SetMissionText("Submarine completes in " .. Utils.FormatTime(ticked), TimerColor)
ticked = ticked - 1
elseif ticked == 0 and not TimerFinished then
MissileSubEscape()
TimerFinished = true
end
end
WorldLoaded = function()
Greece = Player.GetPlayer("Greece")
USSR = Player.GetPlayer("USSR")
BadGuy = Player.GetPlayer("BadGuy")
EscapeWithSub = USSR.AddObjective("Get a missile sub to open waters.")
StopProduction = Greece.AddObjective("Destroy the Soviet sub pen.")
PowerDownTeslaCoils = Greece.AddObjective("Take down power to the tesla coils.")
InitObjectives(Greece)
Trigger.AfterDelay(DateTime.Minutes(2), function()
Media.PlaySpeechNotification(Greece, "TenMinutesRemaining")
end)
Trigger.AfterDelay(DateTime.Minutes(7), function()
Media.PlaySpeechNotification(Greece, "WarningFiveMinutesRemaining")
end)
Trigger.AfterDelay(DateTime.Minutes(9), function()
Media.PlaySpeechNotification(Greece, "WarningThreeMinutesRemaining")
end)
Trigger.AfterDelay(DateTime.Minutes(11), function()
Media.PlaySpeechNotification(Greece, "WarningOneMinuteRemaining")
end)
Camera.Position = DefaultCameraPosition.CenterPosition
TimerColor = USSR.Color
Chalk1 = Actor.Create("chalk1", false, { Owner = Greece })
Chalk2 = Actor.Create("chalk2", false, { Owner = Greece })
MissionStart()
SetupTriggers()
end
| gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Bastok_Markets/npcs/Zhikkom.lua | 15 | 1475 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Zhikkom
-- Standard Merchant NPC
--
-- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ZHIKKOM_SHOP_DIALOG);
stock = {
0x4097, 241,3, --Bronze Sword
0x4098,7128,3, --Iron Sword
0x4085,9201,3, --Degen
0x40A7, 698,3, --Sapara
0x40A8,4072,3, --Scimitar
0x4092, 618,3, --Xiphos
0x40B5,1674,3, --Spatha
0x4080,3215,3 --Bilbo (value may be off)
}
showNationShop(player, NATION_BASTOK, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
pedja1/aNmap | dSploit/jni/nmap/ncat/scripts/conditional.lua | 4 | 1435 | --This is another --lua-exec demo. It displays a menu to a user, waits for her
--input and makes a decision according to what the user entered. All happens
--in an infinite loop.
--This function reads a line of at most 8096 bytes (or whatever the first
--parameter says) from standard input. Returns the string and a boolean value
--that is true if we hit the newline (defined as "\n") or false if the line had
--to be truncated. This is here because io.stdin:read("*line") could lead to
--memory exhaustion if we received gigabytes of characters with no newline.
function read_line(max_len)
local ret = ""
for i = 1, (max_len or 8096) do
local chr = io.read(1)
if chr == "\n" then
return ret, true
end
ret = ret .. chr
end
return ret, false
end
while true do
print "Here's a menu for you: "
print "1. Repeat the menu."
print "0. Exit."
io.write "Please enter your choice: "
io.flush(io.stdout)
i = read_line()
--WARNING! Without this line, the script will go into an infinite loop
--that keeps consuming system resources when the connection gets broken.
--Ncat's subprocesses are NOT killed in this case!
if i == nil then
break
end
print("You wrote: ", i, ".")
if i == "0" then
break
elseif i == "1" then
print "As you wish."
else
print "No idea what you meant. Please try again."
end
print() --print a newline
end
| gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Apollyon/mobs/Fire_Elemental.lua | 119 | 2740 | -----------------------------------
-- Area: Apollyon SW
-- NPC: elemental
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
-- print(mobID);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1;
local correctelement=false;
switch (elementalday): caseof {
[0] = function (x)
if (mobID==16932913 or mobID==16932921 or mobID==16932929) then
correctelement=true;
end
end ,
[1] = function (x)
if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then
correctelement=true;
end
end ,
[2] = function (x)
if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then
correctelement=true;
end
end ,
[3] = function (x)
if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then
correctelement=true;
end
end ,
[4] = function (x)
if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then
correctelement=true;
end
end ,
[5] = function (x)
if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then
correctelement=true;
end
end ,
[6] = function (x)
if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then
correctelement=true;
end
end ,
[7] = function (x)
if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then
correctelement=true;
end
end ,
};
if (correctelement==true and IselementalDayAreDead()==true) then
GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+313):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/globals/abilities/pets/axe_kick.lua | 1 | 1049 | ---------------------------------------------------
-- Axe Kick M=3.5
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/summon");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
ability:setRecast(20);
return 0,0;
end;
function onPetAbility(target, pet, skill, master)
local numhits = 1; local accmod = 1.25; local strRatio = 1.0;
local dmgmod = summoningDamageBonus(master, 18, 0.75, 60);
skill:setSkillchain(50); -- Frostbite: Induration
pet:addTP(200 + skill:getTP()); -- Add TP for using physical skill
local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,0,strRatio);
local totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,numhits);
target:delHP(totaldamage);
target:updateEnmityFromDamage(pet,totaldamage);
return totaldamage;
end | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Konschtat_Highlands/npcs/qm1.lua | 14 | 1374 | -----------------------------------
-- Area: Konschtat Highlands
-- NPC: qm1 (???)
-- Continues Quests: Past Perfect
-- @pos -201 16 80 108
-----------------------------------
package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Konschtat_Highlands/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local PastPerfect = player:getQuestStatus(BASTOK,PAST_PERFECT);
if (PastPerfect == QUEST_ACCEPTED) then
player:addKeyItem(0x6d);
player:messageSpecial(KEYITEM_OBTAINED,0x6d); -- Tattered Mission Orders
else
player:messageSpecial(FIND_NOTHING);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
darklost/quick-ng | cocos/scripting/lua-bindings/auto/api/AtlasNode.lua | 7 | 3990 |
--------------------------------
-- @module AtlasNode
-- @extend Node,TextureProtocol
-- @parent_module cc
--------------------------------
-- updates the Atlas (indexed vertex array).<br>
-- Shall be overridden in subclasses.
-- @function [parent=#AtlasNode] updateAtlasValues
-- @param self
-- @return AtlasNode#AtlasNode self (return value: cc.AtlasNode)
--------------------------------
--
-- @function [parent=#AtlasNode] getTexture
-- @param self
-- @return Texture2D#Texture2D ret (return value: cc.Texture2D)
--------------------------------
-- Set an buffer manager of the texture vertex.
-- @function [parent=#AtlasNode] setTextureAtlas
-- @param self
-- @param #cc.TextureAtlas textureAtlas
-- @return AtlasNode#AtlasNode self (return value: cc.AtlasNode)
--------------------------------
-- code<br>
-- When this function bound into js or lua,the parameter will be changed<br>
-- In js: var setBlendFunc(var src, var dst)<br>
-- endcode<br>
-- lua NA
-- @function [parent=#AtlasNode] setBlendFunc
-- @param self
-- @param #cc.BlendFunc blendFunc
-- @return AtlasNode#AtlasNode self (return value: cc.AtlasNode)
--------------------------------
-- Return the buffer manager of the texture vertex. <br>
-- return Return A TextureAtlas.
-- @function [parent=#AtlasNode] getTextureAtlas
-- @param self
-- @return TextureAtlas#TextureAtlas ret (return value: cc.TextureAtlas)
--------------------------------
-- lua NA
-- @function [parent=#AtlasNode] getBlendFunc
-- @param self
-- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc)
--------------------------------
--
-- @function [parent=#AtlasNode] getQuadsToDraw
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
--
-- @function [parent=#AtlasNode] setTexture
-- @param self
-- @param #cc.Texture2D texture
-- @return AtlasNode#AtlasNode self (return value: cc.AtlasNode)
--------------------------------
--
-- @function [parent=#AtlasNode] setQuadsToDraw
-- @param self
-- @param #long quadsToDraw
-- @return AtlasNode#AtlasNode self (return value: cc.AtlasNode)
--------------------------------
-- creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render.<br>
-- param filename The path of Atlas file.<br>
-- param tileWidth The width of the item.<br>
-- param tileHeight The height of the item.<br>
-- param itemsToRender The quantity of items to render.
-- @function [parent=#AtlasNode] create
-- @param self
-- @param #string filename
-- @param #int tileWidth
-- @param #int tileHeight
-- @param #int itemsToRender
-- @return AtlasNode#AtlasNode ret (return value: cc.AtlasNode)
--------------------------------
--
-- @function [parent=#AtlasNode] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
-- @return AtlasNode#AtlasNode self (return value: cc.AtlasNode)
--------------------------------
--
-- @function [parent=#AtlasNode] isOpacityModifyRGB
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#AtlasNode] setColor
-- @param self
-- @param #color3b_table color
-- @return AtlasNode#AtlasNode self (return value: cc.AtlasNode)
--------------------------------
--
-- @function [parent=#AtlasNode] getColor
-- @param self
-- @return color3b_table#color3b_table ret (return value: color3b_table)
--------------------------------
--
-- @function [parent=#AtlasNode] setOpacityModifyRGB
-- @param self
-- @param #bool isOpacityModifyRGB
-- @return AtlasNode#AtlasNode self (return value: cc.AtlasNode)
--------------------------------
--
-- @function [parent=#AtlasNode] setOpacity
-- @param self
-- @param #unsigned char opacity
-- @return AtlasNode#AtlasNode self (return value: cc.AtlasNode)
return nil
| mit |
Vadavim/jsr-darkstar | scripts/zones/Gusgen_Mines/npcs/Clay.lua | 14 | 1229 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: Clay
-- Involved in Quest: A Potter's Preference
-- @pos 117 -21 432 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:addItem(569,1); --569 - dish_of_gusgen_clay
player:messageSpecial(ITEM_OBTAINED,569); -- dish_of_gusgen_clay
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
darklost/quick-ng | cocos/scripting/lua-bindings/script/cocos2d/DrawPrimitives.lua | 98 | 12024 |
local dp_initialized = false
local dp_shader = nil
local dp_colorLocation = -1
local dp_color = { 1.0, 1.0, 1.0, 1.0 }
local dp_pointSizeLocation = -1
local dp_pointSize = 1.0
local SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor"
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
local function lazy_init()
if not dp_initialized then
dp_shader = cc.ShaderCache:getInstance():getProgram(SHADER_NAME_POSITION_U_COLOR)
--dp_shader:retain()
if nil ~= dp_shader then
dp_colorLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_color")
dp_pointSizeLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_pointSize")
dp_Initialized = true
end
end
if nil == dp_shader then
print("Error:dp_shader is nil!")
return false
end
return true
end
local function setDrawProperty()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, dp_color, 1)
end
function ccDrawInit()
lazy_init()
end
function ccDrawFree()
dp_initialized = false
end
function ccDrawColor4f(r,g,b,a)
dp_color[1] = r
dp_color[2] = g
dp_color[3] = b
dp_color[4] = a
end
function ccPointSize(pointSize)
dp_pointSize = pointSize * cc.Director:getInstance():getContentScaleFactor()
end
function ccDrawColor4B(r,g,b,a)
dp_color[1] = r / 255.0
dp_color[2] = g / 255.0
dp_color[3] = b / 255.0
dp_color[4] = a / 255.0
end
function ccDrawPoint(point)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
local vertices = { point.x,point.y}
gl.bufferData(gl.ARRAY_BUFFER,2,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoints(points,numOfPoint)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoint do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoint * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,numOfPoint)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawLine(origin,destination)
if not lazy_init() then
return
end
local vertexBuffer = {}
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = { origin.x, origin.y, destination.x, destination.y}
gl.bufferData(gl.ARRAY_BUFFER,4,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINES ,0,2)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoly(points,numOfPoints,closePolygon)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
if closePolygon then
gl.drawArrays(gl.LINE_LOOP , 0, numOfPoints)
else
gl.drawArrays(gl.LINE_STRIP, 0, numOfPoints)
end
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawSolidPoly(points,numOfPoints,color)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, color, 1)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, numOfPoints)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawRect(origin,destination)
ccDrawLine(CCPoint:__call(origin.x, origin.y), CCPoint:__call(destination.x, origin.y))
ccDrawLine(CCPoint:__call(destination.x, origin.y), CCPoint:__call(destination.x, destination.y))
ccDrawLine(CCPoint:__call(destination.x, destination.y), CCPoint:__call(origin.x, destination.y))
ccDrawLine(CCPoint:__call(origin.x, destination.y), CCPoint:__call(origin.x, origin.y))
end
function ccDrawSolidRect( origin,destination,color )
local vertices = { origin, CCPoint:__call(destination.x, origin.y) , destination, CCPoint:__call(origin.x, destination.y) }
ccDrawSolidPoly(vertices,4,color)
end
function ccDrawCircleScale( center, radius, angle, segments,drawLineToCenter,scaleX,scaleY)
if not lazy_init() then
return
end
local additionalSegment = 1
if drawLineToCenter then
additionalSegment = additionalSegment + 1
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + additionalSegment)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCircle(center, radius, angle, segments, drawLineToCenter)
ccDrawCircleScale(center, radius, angle, segments, drawLineToCenter, 1.0, 1.0)
end
function ccDrawSolidCircle(center, radius, angle, segments,scaleX,scaleY)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawQuadBezier(origin, control, destination, segments)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local i = 1
local t = 0.0
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x
vertices[2 * i] = math.pow(1 - t,2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCubicBezier(origin, control1, control2, destination, segments)
if not lazy_init then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local t = 0
local i = 1
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,3) * origin.x + 3.0 * math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x
vertices[2 * i] = math.pow(1 - t,3) * origin.y + 3.0 * math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
| mit |
lcf8858/Sample_Lua | frameworks/cocos2d-x/cocos/scripting/lua-bindings/script/cocos2d/DrawPrimitives.lua | 98 | 12024 |
local dp_initialized = false
local dp_shader = nil
local dp_colorLocation = -1
local dp_color = { 1.0, 1.0, 1.0, 1.0 }
local dp_pointSizeLocation = -1
local dp_pointSize = 1.0
local SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor"
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
local function lazy_init()
if not dp_initialized then
dp_shader = cc.ShaderCache:getInstance():getProgram(SHADER_NAME_POSITION_U_COLOR)
--dp_shader:retain()
if nil ~= dp_shader then
dp_colorLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_color")
dp_pointSizeLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_pointSize")
dp_Initialized = true
end
end
if nil == dp_shader then
print("Error:dp_shader is nil!")
return false
end
return true
end
local function setDrawProperty()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, dp_color, 1)
end
function ccDrawInit()
lazy_init()
end
function ccDrawFree()
dp_initialized = false
end
function ccDrawColor4f(r,g,b,a)
dp_color[1] = r
dp_color[2] = g
dp_color[3] = b
dp_color[4] = a
end
function ccPointSize(pointSize)
dp_pointSize = pointSize * cc.Director:getInstance():getContentScaleFactor()
end
function ccDrawColor4B(r,g,b,a)
dp_color[1] = r / 255.0
dp_color[2] = g / 255.0
dp_color[3] = b / 255.0
dp_color[4] = a / 255.0
end
function ccDrawPoint(point)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
local vertices = { point.x,point.y}
gl.bufferData(gl.ARRAY_BUFFER,2,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoints(points,numOfPoint)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoint do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoint * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,numOfPoint)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawLine(origin,destination)
if not lazy_init() then
return
end
local vertexBuffer = {}
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = { origin.x, origin.y, destination.x, destination.y}
gl.bufferData(gl.ARRAY_BUFFER,4,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINES ,0,2)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoly(points,numOfPoints,closePolygon)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
if closePolygon then
gl.drawArrays(gl.LINE_LOOP , 0, numOfPoints)
else
gl.drawArrays(gl.LINE_STRIP, 0, numOfPoints)
end
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawSolidPoly(points,numOfPoints,color)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, color, 1)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, numOfPoints)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawRect(origin,destination)
ccDrawLine(CCPoint:__call(origin.x, origin.y), CCPoint:__call(destination.x, origin.y))
ccDrawLine(CCPoint:__call(destination.x, origin.y), CCPoint:__call(destination.x, destination.y))
ccDrawLine(CCPoint:__call(destination.x, destination.y), CCPoint:__call(origin.x, destination.y))
ccDrawLine(CCPoint:__call(origin.x, destination.y), CCPoint:__call(origin.x, origin.y))
end
function ccDrawSolidRect( origin,destination,color )
local vertices = { origin, CCPoint:__call(destination.x, origin.y) , destination, CCPoint:__call(origin.x, destination.y) }
ccDrawSolidPoly(vertices,4,color)
end
function ccDrawCircleScale( center, radius, angle, segments,drawLineToCenter,scaleX,scaleY)
if not lazy_init() then
return
end
local additionalSegment = 1
if drawLineToCenter then
additionalSegment = additionalSegment + 1
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + additionalSegment)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCircle(center, radius, angle, segments, drawLineToCenter)
ccDrawCircleScale(center, radius, angle, segments, drawLineToCenter, 1.0, 1.0)
end
function ccDrawSolidCircle(center, radius, angle, segments,scaleX,scaleY)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawQuadBezier(origin, control, destination, segments)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local i = 1
local t = 0.0
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x
vertices[2 * i] = math.pow(1 - t,2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCubicBezier(origin, control1, control2, destination, segments)
if not lazy_init then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local t = 0
local i = 1
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,3) * origin.x + 3.0 * math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x
vertices[2 * i] = math.pow(1 - t,3) * origin.y + 3.0 * math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
| mit |
Colettechan/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Enaremand.lua | 13 | 1062 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Enaremand
-- Type: Standard NPC
-- @zone: 26
-- @pos 95.962 -42.003 51.613
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0219);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
lcf8858/Sample_Lua | frameworks/cocos2d-x/tests/lua-tests/src/RenderTextureTest/RenderTextureTest.lua | 15 | 17966 | -- Test #1 by Jason Booth (slipster216)
-- Test #3 by David Deaco (ddeaco)
--/**
-- * Impelmentation of RenderTextureSave
--*/
local function RenderTextureSave()
local ret = createTestLayer("Touch the screen",
"Press 'Save Image' to create an snapshot of the render texture")
local s = cc.Director:getInstance():getWinSize()
local target = nil
local counter = 0
local brushes = {}
local function clearImage(tag, pSender)
target:clear(math.random(), math.random(), math.random(), math.random())
end
local function saveImage(tag, pSender)
local png = string.format("image-%d.png", counter)
local jpg = string.format("image-%d.jpg", counter)
target:saveToFile(png, cc.IMAGE_FORMAT_PNG)
target:saveToFile(jpg, cc.IMAGE_FORMAT_JPEG)
local pImage = target:newImage()
local tex = cc.Director:getInstance():getTextureCache():addUIImage(pImage, png)
pImage:release()
local sprite = cc.Sprite:createWithTexture(tex)
sprite:setScale(0.3)
ret:addChild(sprite)
sprite:setPosition(cc.p(40, 40))
sprite:setRotation(counter * 3)
cclog("Image saved %s and %s", png, jpg)
counter = counter + 1
end
local function onNodeEvent(event)
if event == "exit" then
target:release()
cc.Director:getInstance():getTextureCache():removeUnusedTextures()
end
end
ret:registerScriptHandler(onNodeEvent)
-- create a render texture, this is what we are going to draw into
target = cc.RenderTexture:create(s.width, s.height, cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
target:retain()
target:setPosition(cc.p(s.width / 2, s.height / 2))
-- note that the render texture is a cc.Node, and contains a sprite of its texture for convience,
-- so we can just parent it to the scene like any other cc.Node
ret:addChild(target, -1)
local function onTouchesMoved(touches, event)
local start = touches[1]:getLocation()
local ended = touches[1]:getPreviousLocation()
target:begin()
local distance = cc.pGetDistance(start, ended)
if distance > 1 then
brushes = {}
local d = distance
local i = 0
for i = 0,d -1 do
-- create a brush image to draw into the texture with
local sprite = cc.Sprite:create("Images/fire.png")
sprite:setColor(cc.c3b(255, 0, 0))
sprite:setOpacity(20)
brushes[i + 1] = sprite
end
for i = 0,d -1 do
local difx = ended.x - start.x
local dify = ended.y - start.y
local delta = i / distance
brushes[i + 1]:setPosition(cc.p(start.x + (difx * delta), start.y + (dify * delta)))
brushes[i + 1]:setRotation(math.random(0, 359))
local r = math.random(0, 49) / 50.0 + 0.25
brushes[i + 1]:setScale(r)
-- Use cc.RANDOM_0_1() will cause error when loading libtests.so on android, I don't know why.
brushes[i + 1]:setColor(cc.c3b(math.random(0, 126) + 128, 255, 255))
-- Call visit to draw the brush, don't call draw..
brushes[i + 1]:visit()
end
end
-- finish drawing and return context back to the screen
target:endToLua()
end
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED )
local eventDispatcher = ret:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret)
-- Save Image menu
cc.MenuItemFont:setFontSize(16)
local item1 = cc.MenuItemFont:create("Save Image")
item1:registerScriptTapHandler(saveImage)
local item2 = cc.MenuItemFont:create("Clear")
item2:registerScriptTapHandler(clearImage)
local menu = cc.Menu:create(item1, item2)
ret:addChild(menu)
menu:alignItemsVertically()
menu:setPosition(cc.p(VisibleRect:rightTop().x - 80, VisibleRect:rightTop().y - 30))
return ret
end
--/**
-- * Impelmentation of RenderTextureIssue937
--*/
-- local function RenderTextureIssue937()
-- /*
-- * 1 2
-- * A: A1 A2
-- *
-- * B: B1 B2
-- *
-- * A1: premulti sprite
-- * A2: premulti render
-- *
-- * B1: non-premulti sprite
-- * B2: non-premulti render
-- */
-- local background = cc.LayerColor:create(cc.c4b(200,200,200,255))
-- addChild(background)
-- local spr_premulti = cc.Sprite:create("Images/fire.png")
-- spr_premulti:setPosition(cc.p(16,48))
-- local spr_nonpremulti = cc.Sprite:create("Images/fire.png")
-- spr_nonpremulti:setPosition(cc.p(16,16))
-- /* A2 & B2 setup */
-- local rend = cc.RenderTexture:create(32, 64, cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
-- if (NULL == rend)
-- return
-- end
-- -- It's possible to modify the RenderTexture blending function by
-- -- [[rend sprite] setBlendFunc:(BlendFunc) GL_ONE, GL_ONE_MINUS_SRC_ALPHAend]
-- rend:begin()
-- spr_premulti:visit()
-- spr_nonpremulti:visit()
-- rend:end()
-- local s = cc.Director:getInstance():getWinSize()
-- --/* A1: setup */
-- spr_premulti:setPosition(cc.p(s.width/2-16, s.height/2+16))
-- --/* B1: setup */
-- spr_nonpremulti:setPosition(cc.p(s.width/2-16, s.height/2-16))
-- rend:setPosition(cc.p(s.width/2+16, s.height/2))
-- addChild(spr_nonpremulti)
-- addChild(spr_premulti)
-- addChild(rend)
-- end
-- local function title()
-- return "Testing issue #937"
-- end
-- local function subtitle()
-- return "All images should be equal..."
-- end
-- local function runThisTest()
-- local pLayer = nextTestCase()
-- addChild(pLayer)
-- cc.Director:getInstance():replaceScene(this)
-- end
-- --/**
-- -- * Impelmentation of RenderTextureZbuffer
-- --*/
-- local function RenderTextureZbuffer()
-- this:setTouchEnabled(true)
-- local size = cc.Director:getInstance():getWinSize()
-- local label = cc.LabelTTF:create("vertexZ = 50", "Marker Felt", 64)
-- label:setPosition(cc.p(size.width / 2, size.height * 0.25))
-- this:addChild(label)
-- local label2 = cc.LabelTTF:create("vertexZ = 0", "Marker Felt", 64)
-- label2:setPosition(cc.p(size.width / 2, size.height * 0.5))
-- this:addChild(label2)
-- local label3 = cc.LabelTTF:create("vertexZ = -50", "Marker Felt", 64)
-- label3:setPosition(cc.p(size.width / 2, size.height * 0.75))
-- this:addChild(label3)
-- label:setVertexZ(50)
-- label2:setVertexZ(0)
-- label3:setVertexZ(-50)
-- cc.SpriteFrameCache:getInstance():addSpriteFramesWithFile("Images/bugs/circle.plist")
-- mgr = cc.SpriteBatchNode:create("Images/bugs/circle.png", 9)
-- this:addChild(mgr)
-- sp1 = cc.Sprite:createWithSpriteFrameName("circle.png")
-- sp2 = cc.Sprite:createWithSpriteFrameName("circle.png")
-- sp3 = cc.Sprite:createWithSpriteFrameName("circle.png")
-- sp4 = cc.Sprite:createWithSpriteFrameName("circle.png")
-- sp5 = cc.Sprite:createWithSpriteFrameName("circle.png")
-- sp6 = cc.Sprite:createWithSpriteFrameName("circle.png")
-- sp7 = cc.Sprite:createWithSpriteFrameName("circle.png")
-- sp8 = cc.Sprite:createWithSpriteFrameName("circle.png")
-- sp9 = cc.Sprite:createWithSpriteFrameName("circle.png")
-- mgr:addChild(sp1, 9)
-- mgr:addChild(sp2, 8)
-- mgr:addChild(sp3, 7)
-- mgr:addChild(sp4, 6)
-- mgr:addChild(sp5, 5)
-- mgr:addChild(sp6, 4)
-- mgr:addChild(sp7, 3)
-- mgr:addChild(sp8, 2)
-- mgr:addChild(sp9, 1)
-- sp1:setVertexZ(400)
-- sp2:setVertexZ(300)
-- sp3:setVertexZ(200)
-- sp4:setVertexZ(100)
-- sp5:setVertexZ(0)
-- sp6:setVertexZ(-100)
-- sp7:setVertexZ(-200)
-- sp8:setVertexZ(-300)
-- sp9:setVertexZ(-400)
-- sp9:setScale(2)
-- sp9:setColor(cc.c3b::YELLOW)
-- end
-- local function title()
-- return "Testing Z Buffer in Render Texture"
-- end
-- local function subtitle()
-- return "Touch screen. It should be green"
-- end
-- local function ccTouchesBegan(cocos2d:cc.Set *touches, cocos2d:cc.Event *event)
-- cc.SetIterator iter
-- cc.Touch *touch
-- for (iter = touches:begin() iter != touches:end() ++iter)
-- touch = (cc.Touch *)(*iter)
-- local location = touch:getLocation()
-- sp1:setPosition(location)
-- sp2:setPosition(location)
-- sp3:setPosition(location)
-- sp4:setPosition(location)
-- sp5:setPosition(location)
-- sp6:setPosition(location)
-- sp7:setPosition(location)
-- sp8:setPosition(location)
-- sp9:setPosition(location)
-- end
-- end
-- local function ccTouchesMoved(cc.const std::vector<Touch*>& touches, cc.Event* event)
-- cc.SetIterator iter
-- cc.Touch *touch
-- for (iter = touches:begin() iter != touches:end() ++iter)
-- touch = (cc.Touch *)(*iter)
-- local location = touch:getLocation()
-- sp1:setPosition(location)
-- sp2:setPosition(location)
-- sp3:setPosition(location)
-- sp4:setPosition(location)
-- sp5:setPosition(location)
-- sp6:setPosition(location)
-- sp7:setPosition(location)
-- sp8:setPosition(location)
-- sp9:setPosition(location)
-- end
-- end
-- local function ccTouchesEnded(cc.const std::vector<Touch*>& touches, cc.Event* event)
-- this:renderScreenShot()
-- end
-- local function renderScreenShot()
-- local texture = cc.RenderTexture:create(512, 512)
-- if (NULL == texture)
-- return
-- end
-- texture:setAnchorPoint(cc.p(0, 0))
-- texture:begin()
-- this:visit()
-- texture:end()
-- local sprite = cc.Sprite:createWithTexture(texture:getSprite():getTexture())
-- sprite:setPosition(cc.p(256, 256))
-- sprite:setOpacity(182)
-- sprite:setFlipY(1)
-- this:addChild(sprite, 999999)
-- sprite:setColor(cc.c3b::GREEN)
-- sprite:runAction(cc.Sequence:create(cc.FadeTo:create(2, 0),
-- cc.Hide:create(),
-- NULL))
-- end
-- -- RenderTextureTestDepthStencil
-- local function RenderTextureTestDepthStencil()
-- local s = cc.Director:getInstance():getWinSize()
-- local sprite = cc.Sprite:create("Images/fire.png")
-- sprite:setPosition(cc.p(s.width * 0.25, 0))
-- sprite:setScale(10)
-- local rend = cc.RenderTexture:create(s.width, s.height, kcc.Texture2DPixelFormat_RGBA4444, GL_DEPTH24_STENCIL8)
-- glStencilMask(0xFF)
-- rend:beginWithClear(0, 0, 0, 0, 0, 0)
-- --! mark sprite quad into stencil buffer
-- glEnable(GL_STENCIL_TEST)
-- glStencilFunc(GL_ALWAYS, 1, 0xFF)
-- glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)
-- glColorMask(0, 0, 0, 1)
-- sprite:visit()
-- --! move sprite half width and height, and draw only where not marked
-- sprite:setPosition(cc.p__add(sprite:getPosition(), cc.p__mul(cc.p(sprite:getContentSize().width * sprite:getScale(), sprite:getContentSize().height * sprite:getScale()), 0.5)))
-- glStencilFunc(GL_NOTEQUAL, 1, 0xFF)
-- glColorMask(1, 1, 1, 1)
-- sprite:visit()
-- rend:end()
-- glDisable(GL_STENCIL_TEST)
-- rend:setPosition(cc.p(s.width * 0.5, s.height * 0.5))
-- this:addChild(rend)
-- end
-- local function title()
-- return "Testing depthStencil attachment"
-- end
-- local function subtitle()
-- return "Circle should be missing 1/4 of its region"
-- end
-- -- RenderTextureTest
-- local function RenderTextureTargetNode()
-- /*
-- * 1 2
-- * A: A1 A2
-- *
-- * B: B1 B2
-- *
-- * A1: premulti sprite
-- * A2: premulti render
-- *
-- * B1: non-premulti sprite
-- * B2: non-premulti render
-- */
-- local background = cc.LayerColor:create(cc.c4b(40,40,40,255))
-- addChild(background)
-- -- sprite 1
-- sprite1 = cc.Sprite:create("Images/fire.png")
-- -- sprite 2
-- sprite2 = cc.Sprite:create("Images/fire_rgba8888.pvr")
-- local s = cc.Director:getInstance():getWinSize()
-- /* Create the render texture */
-- local renderTexture = cc.RenderTexture:create(s.width, s.height, kcc.Texture2DPixelFormat_RGBA4444)
-- this:renderTexture = renderTexture
-- renderTexture:setPosition(cc.p(s.width/2, s.height/2))
-- renderTexture:setScale(2.0)
-- /* add the sprites to the render texture */
-- renderTexture:addChild(sprite1)
-- renderTexture:addChild(sprite2)
-- renderTexture:setClearColor(cc.c4f(0, 0, 0, 0))
-- renderTexture:setClearFlags(GL_COLOR_BUFFER_BIT)
-- /* add the render texture to the scene */
-- addChild(renderTexture)
-- renderTexture:setAutoDraw(true)
-- scheduleUpdate()
-- -- Toggle clear on / off
-- local item = cc.MenuItemFont:create("Clear On/Off", this, menu_selector(RenderTextureTargetNode:touched))
-- local menu = cc.Menu:create(item, NULL)
-- addChild(menu)
-- menu:setPosition(cc.p(s.width/2, s.height/2))
-- end
-- local function touched(cc.Object* sender)
-- if (renderTexture:getClearFlags() == 0)
-- renderTexture:setClearFlags(GL_COLOR_BUFFER_BIT)
-- end
-- else
-- renderTexture:setClearFlags(0)
-- renderTexture:setClearColor(cc.c4f( cc.RANDOM_0_1(), cc.RANDOM_0_1(), cc.RANDOM_0_1(), 1))
-- end
-- end
-- local function update(float dt)
-- static float time = 0
-- float r = 80
-- sprite1:setPosition(cc.p(cosf(time * 2) * r, sinf(time * 2) * r))
-- sprite2:setPosition(cc.p(sinf(time * 2) * r, cosf(time * 2) * r))
-- time += dt
-- end
-- local function title()
-- return "Testing Render Target Node"
-- end
-- local function subtitle()
-- return "Sprites should be equal and move with each frame"
-- end
-- -- SpriteRenderTextureBug
-- local function SimpleSprite() : rt(nullptr) {}
-- local function SimpleSprite* SpriteRenderTextureBug:SimpleSprite:create(const char* filename, const cc.rect &rect)
-- SimpleSprite *sprite = new SimpleSprite()
-- if (sprite && sprite:initWithFile(filename, rect))
-- sprite:autorelease()
-- end
-- else
-- cc._SAFE_DELETE(sprite)
-- end
-- return sprite
-- end
-- local function SimpleSprite:draw()
-- if (rt == NULL)
-- local s = cc.Director:getInstance():getWinSize()
-- rt = new cc.RenderTexture()
-- rt:initWithWidthAndHeight(s.width, s.height, cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
-- end
-- rt:beginWithClear(0.0, 0.0, 0.0, 1.0)
-- rt:end()
-- cc._NODE_DRAW_SETUP()
-- BlendFunc blend = getBlendFunc()
-- ccGLBlendFunc(blend.src, blend.dst)
-- ccGLBindTexture2D(getTexture():getName())
-- --
-- -- Attributes
-- --
-- ccGLEnableVertexAttribs(kcc.VertexAttribFlag_PosColorTex)
-- #define kQuadSize sizeof(m_sQuad.bl)
-- long offset = (long)&m_sQuad
-- -- vertex
-- int diff = offsetof( V3F_C4B_T2F, vertices)
-- glVertexAttribPointer(kcc.VertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff))
-- -- texCoods
-- diff = offsetof( V3F_C4B_T2F, texCoords)
-- glVertexAttribPointer(kcc.VertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff))
-- -- color
-- diff = offsetof( V3F_C4B_T2F, colors)
-- glVertexAttribPointer(kcc.VertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff))
-- glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)
-- end
-- local function SpriteRenderTextureBug()
-- setTouchEnabled(true)
-- local s = cc.Director:getInstance():getWinSize()
-- addNewSpriteWithCoords(cc.p(s.width/2, s.height/2))
-- end
-- local function SimpleSprite* SpriteRenderTextureBug:addNewSpriteWithCoords(const cc.p& p)
-- int idx = cc.RANDOM_0_1() * 1400 / 100
-- int x = (idx%5) * 85
-- int y = (idx/5) * 121
-- SpriteRenderTextureBug:SimpleSprite *sprite = SpriteRenderTextureBug:SimpleSprite:create("Images/grossini_dance_atlas.png",
-- cc.rect(x,y,85,121))
-- addChild(sprite)
-- sprite:setPosition(p)
-- local action = NULL
-- float rd = cc.RANDOM_0_1()
-- if (rd < 0.20)
-- action = cc.ScaleBy:create(3, 2)
-- else if (rd < 0.40)
-- action = cc.RotateBy:create(3, 360)
-- else if (rd < 0.60)
-- action = cc.Blink:create(1, 3)
-- else if (rd < 0.8 )
-- action = cc.TintBy:create(2, 0, -255, -255)
-- else
-- action = cc.FadeOut:create(2)
-- local action_back = action:reverse()
-- local seq = cc.Sequence:create(action, action_back, NULL)
-- sprite:runAction(cc.RepeatForever:create(seq))
-- --return sprite
-- return NULL
-- end
-- local function ccTouchesEnded(cc.const std::vector<Touch*>& touches, cc.Event* event)
-- cc.SetIterator iter = touches:begin()
-- for( iter != touches:end() ++iter)
-- local location = ((cc.Touch*)(*iter)):getLocation()
-- addNewSpriteWithCoords(location)
-- end
-- end
-- local function title()
-- return "SpriteRenderTextureBug"
-- end
-- local function subtitle()
-- return "Touch the screen. Sprite should appear on under the touch"
-- end
function RenderTextureTestMain()
cclog("RenderTextureTestMain")
Helper.index = 1
local scene = cc.Scene:create()
Helper.createFunctionTable = {
RenderTextureSave,
-- RenderTextureIssue937,
-- RenderTextureZbuffer,
-- RenderTextureTestDepthStencil,
-- RenderTextureTargetNode,
-- SpriteRenderTextureBug
}
scene:addChild(RenderTextureSave())
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
Vadavim/jsr-darkstar | scripts/globals/items/magma_steak_+1.lua | 18 | 1597 | -----------------------------------------
-- ID: 6072
-- Item: Magma Steak +1
-- Food Effect: 240 Min, All Races
-----------------------------------------
-- Strength +9
-- Attack +24% Cap 185
-- Ranged Attack +24% Cap 185
-- Vermin Killer +6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,6072);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 9);
target:addMod(MOD_FOOD_ATTP, 24);
target:addMod(MOD_FOOD_ATT_CAP, 185);
target:addMod(MOD_FOOD_RATTP, 24);
target:addMod(MOD_FOOD_RATT_CAP, 185);
target:addMod(MOD_VERMIN_KILLER, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 9);
target:delMod(MOD_FOOD_ATTP, 24);
target:delMod(MOD_FOOD_ATT_CAP, 185);
target:delMod(MOD_FOOD_RATTP, 24);
target:delMod(MOD_FOOD_RATT_CAP, 185);
target:delMod(MOD_VERMIN_KILLER, 6);
end;
| gpl-3.0 |
Vadavim/jsr-darkstar | scripts/globals/weaponskills/bora_axe.lua | 1 | 2053 | -----------------------------------
-- Bora Axe
-- Axe weapon skill
-- Skill level: 290
-- Delivers a single-hit ranged attack at a maximum distance of 15.7'. Chance of binding varies with TP
-- Bind doesn't always break from hitting mob.
-- This Weapon Skill's first hit params.ftp is duplicated for all additional hits
-- Not natively available to RNG
-- Aligned with the ?? Gorget.
-- Element: Ice
-- Modifiers: DEX 60% -- http://wiki.bluegartr.com/bg/Bora_Axe
-- 100%TP 200%TP 300%TP
-- 1.0 1.0 1.0
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/magic");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 1.0; params.ftp200 = 1.0; params.ftp300 = 1.0;
params.str_wsc = 0.0; params.dex_wsc = 0.6; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 2;
params.ele = ELE_ICE;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1; params.ftp200 = 1.75; params.ftp300 = 2.5;
params.agi_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
local resist = applyResistanceWeaponskill(player, target, params, tp, ELE_ICE, SKILL_AXE);
if (damage > 0 and resist >= 0.25) then
target:addStatusEffect(EFFECT_BIND, 1, 0, 30);
target:setPendingMessage(277, EFFECT_BIND);
target:addStatusEffect(EFFECT_AGI_DOWN, 25, 0, fTP(tp, 60, 120, 240));
target:setPendingMessage(278, EFFECT_AGI_DOWN);
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
darklost/quick-ng | quick/framework/transition.lua | 20 | 19757 | --[[
Copyright (c) 2011-2014 chukong-inc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
--------------------------------
-- @module transition
--[[--
为图像创造效果
]]
local transition = {}
local ACTION_EASING = {}
ACTION_EASING["BACKIN"] = {cc.EaseBackIn, 1}
ACTION_EASING["BACKINOUT"] = {cc.EaseBackInOut, 1}
ACTION_EASING["BACKOUT"] = {cc.EaseBackOut, 1}
ACTION_EASING["BOUNCE"] = {cc.EaseBounce, 1}
ACTION_EASING["BOUNCEIN"] = {cc.EaseBounceIn, 1}
ACTION_EASING["BOUNCEINOUT"] = {cc.EaseBounceInOut, 1}
ACTION_EASING["BOUNCEOUT"] = {cc.EaseBounceOut, 1}
ACTION_EASING["ELASTIC"] = {cc.EaseElastic, 2, 0.3}
ACTION_EASING["ELASTICIN"] = {cc.EaseElasticIn, 2, 0.3}
ACTION_EASING["ELASTICINOUT"] = {cc.EaseElasticInOut, 2, 0.3}
ACTION_EASING["ELASTICOUT"] = {cc.EaseElasticOut, 2, 0.3}
ACTION_EASING["EXPONENTIALIN"] = {cc.EaseExponentialIn, 1}
ACTION_EASING["EXPONENTIALINOUT"] = {cc.EaseExponentialInOut, 1}
ACTION_EASING["EXPONENTIALOUT"] = {cc.EaseExponentialOut, 1}
ACTION_EASING["IN"] = {cc.EaseIn, 2, 1}
ACTION_EASING["INOUT"] = {cc.EaseInOut, 2, 1}
ACTION_EASING["OUT"] = {cc.EaseOut, 2, 1}
ACTION_EASING["RATEACTION"] = {cc.EaseRateAction, 2, 1}
ACTION_EASING["SINEIN"] = {cc.EaseSineIn, 1}
ACTION_EASING["SINEINOUT"] = {cc.EaseSineInOut, 1}
ACTION_EASING["SINEOUT"] = {cc.EaseSineOut, 1}
local actionManager = cc.Director:getInstance():getActionManager()
-- start --
--------------------------------
-- 创建一个缓动效果
-- @function [parent=#transition] newEasing
-- @param Action action 动作对象
-- @param string easingName 缓冲效果的名字, 具体参考 transition.execute() 方法
-- @param mixed more 创建缓冲效果的参数
-- @return mixed#mixed ret (return value: mixed) 结果
-- end --
function transition.newEasing(action, easingName, more)
local key = string.upper(tostring(easingName))
if string.sub(key, 1, 6) == "CCEASE" then
key = string.sub(key, 7)
end
local easing
if ACTION_EASING[key] then
local cls, count, default = unpack(ACTION_EASING[key])
if count == 2 then
easing = cls:create(action, more or default)
else
easing = cls:create(action)
end
end
return easing or action
end
-- start --
--------------------------------
-- 创建一个动作效果
-- @function [parent=#transition] create
-- @param Action action 动作对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
-- end --
function transition.create(action, args)
args = checktable(args)
if args.easing then
if type(args.easing) == "table" then
action = transition.newEasing(action, unpack(args.easing))
else
action = transition.newEasing(action, args.easing)
end
end
local actions = {}
local delay = checknumber(args.delay)
if delay > 0 then
actions[#actions + 1] = cc.DelayTime:create(delay)
end
actions[#actions + 1] = action
local onComplete = args.onComplete
if type(onComplete) ~= "function" then onComplete = nil end
if onComplete then
actions[#actions + 1] = cc.CallFunc:create(onComplete)
end
if #actions > 1 then
return transition.sequence(actions)
else
return actions[1]
end
end
-- start --
--------------------------------
-- 执行一个动作效果
-- @function [parent=#transition] execute
-- @param cc.Node target 显示对象
-- @param Action action 动作对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
执行一个动作效果
~~~ lua
-- 等待 1.0 后开始移动对象
-- 耗时 1.5 秒,将对象移动到屏幕中央
-- 移动使用 backout 缓动效果
-- 移动结束后执行函数,显示 move completed
transition.execute(sprite, MoveTo:create(1.5, cc.p(display.cx, display.cy)), {
delay = 1.0,
easing = "backout",
onComplete = function()
print("move completed")
end,
})
~~~
transition.execute() 是一个强大的工具,可以为原本单一的动作添加各种附加特性。
transition.execute() 的参数表格支持下列参数:
- delay: 等待多长时间后开始执行动作
- easing: 缓动效果的名字及可选的附加参数,效果名字不区分大小写
- onComplete: 动作执行完成后要调用的函数
- time: 执行动作需要的时间
transition.execute() 支持的缓动效果:
- backIn
- backInOut
- backOut
- bounce
- bounceIn
- bounceInOut
- bounceOut
- elastic, 附加参数默认为 0.3
- elasticIn, 附加参数默认为 0.3
- elasticInOut, 附加参数默认为 0.3
- elasticOut, 附加参数默认为 0.3
- exponentialIn, 附加参数默认为 1.0
- exponentialInOut, 附加参数默认为 1.0
- exponentialOut, 附加参数默认为 1.0
- In, 附加参数默认为 1.0
- InOut, 附加参数默认为 1.0
- Out, 附加参数默认为 1.0
- rateaction, 附加参数默认为 1.0
- sineIn
- sineInOut
- sineOut
]]
-- end --
function transition.execute(target, action, args)
assert(not tolua.isnull(target), "transition.execute() - target is not cc.Node")
local action = transition.create(action, args)
target:runAction(action)
return action
end
-- start --
--------------------------------
-- 将显示对象旋转到指定角度,并返回 Action 动作对象。
-- @function [parent=#transition] rotateTo
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象旋转到指定角度,并返回 Action 动作对象。
~~~ lua
-- 耗时 0.5 秒将 sprite 旋转到 180 度
transition.rotateTo(sprite, {rotate = 180, time = 0.5})
~~~
]]
-- end --
function transition.rotateTo(target, args)
assert(not tolua.isnull(target), "transition.rotateTo() - target is not cc.Node")
-- local rotation = args.rotate
local action = cc.RotateTo:create(args.time, args.rotate)
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 将显示对象移动到指定位置,并返回 Action 动作对象。
-- @function [parent=#transition] moveTo
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象移动到指定位置,并返回 Action 动作对象。
~~~ lua
-- 移动到屏幕中心
transition.moveTo(sprite, {x = display.cx, y = display.cy, time = 1.5})
-- 移动到屏幕左边,不改变 y
transition.moveTo(sprite, {x = display.left, time = 1.5})
-- 移动到屏幕底部,不改变 x
transition.moveTo(sprite, {y = display.bottom, time = 1.5})
~~~
]]
-- end --
function transition.moveTo(target, args)
assert(not tolua.isnull(target), "transition.moveTo() - target is not cc.Node")
local tx, ty = target:getPosition()
local x = args.x or tx
local y = args.y or ty
local action = cc.MoveTo:create(args.time, cc.p(x, y))
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 将显示对象移动一定距离,并返回 Action 动作对象。
-- @function [parent=#transition] moveBy
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象移动一定距离,并返回 Action 动作对象。
~~~ lua
-- 向右移动 100 点,向上移动 100 点
transition.moveBy(sprite, {x = 100, y = 100, time = 1.5})
-- 向左移动 100 点,不改变 y
transition.moveBy(sprite, {x = -100, time = 1.5})
-- 向下移动 100 点,不改变 x
transition.moveBy(sprite, {y = -100, time = 1.5})
~~~
]]
-- end --
function transition.moveBy(target, args)
assert(not tolua.isnull(target), "transition.moveBy() - target is not cc.Node")
local x = args.x or 0
local y = args.y or 0
local action = cc.MoveBy:create(args.time, cc.p(x, y))
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 淡入显示对象,并返回 Action 动作对象。
-- @function [parent=#transition] fadeIn
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
淡入显示对象,并返回 Action 动作对象。
fadeIn 操作会首先将对象的透明度设置为 0(0%,完全透明),然后再逐步增加为 255(100%,完全不透明)。
如果不希望改变对象当前的透明度,应该用 fadeTo()。
~~~ lua
action = transition.fadeIn(sprite, {time = 1.5})
~~~
]]
-- end --
function transition.fadeIn(target, args)
assert(not tolua.isnull(target), "transition.fadeIn() - target is not cc.Node")
local action = cc.FadeIn:create(args.time)
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 淡出显示对象,并返回 Action 动作对象。
-- @function [parent=#transition] fadeOut
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
淡出显示对象,并返回 Action 动作对象。
fadeOut 操作会首先将对象的透明度设置为 255(100%,完全不透明),然后再逐步减少为 0(0%,完全透明)。
如果不希望改变对象当前的透明度,应该用 fadeTo()。
~~~ lua
action = transition.fadeOut(sprite, {time = 1.5})
~~~
]]
-- end --
function transition.fadeOut(target, args)
assert(not tolua.isnull(target), "transition.fadeOut() - target is not cc.Node")
local action = cc.FadeOut:create(args.time)
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 将显示对象的透明度改变为指定值,并返回 Action 动作对象。
-- @function [parent=#transition] fadeTo
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象的透明度改变为指定值,并返回 Action 动作对象。
~~~ lua
-- 不管显示对象当前的透明度是多少,最终设置为 128
transition.fadeTo(sprite, {opacity = 128, time = 1.5})
~~~
]]
-- end --
function transition.fadeTo(target, args)
assert(not tolua.isnull(target), "transition.fadeTo() - target is not cc.Node")
local opacity = checkint(args.opacity)
if opacity < 0 then
opacity = 0
elseif opacity > 255 then
opacity = 255
end
local action = cc.FadeTo:create(args.time, opacity)
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 将显示对象缩放到指定比例,并返回 Action 动作对象。
-- @function [parent=#transition] scaleTo
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象缩放到指定比例,并返回 Action 动作对象。
~~~ lua
-- 整体缩放为 50%
transition.scaleTo(sprite, {scale = 0.5, time = 1.5})
-- 单独水平缩放
transition.scaleTo(sprite, {scaleX = 0.5, time = 1.5})
-- 单独垂直缩放
transition.scaleTo(sprite, {scaleY = 0.5, time = 1.5})
~~~
]]
-- end --
function transition.scaleTo(target, args)
assert(not tolua.isnull(target), "transition.scaleTo() - target is not cc.Node")
local action
if args.scale then
action = cc.ScaleTo:create(checknumber(args.time), checknumber(args.scale))
elseif args.scaleX or args.scaleY then
local scaleX, scaleY
if args.scaleX then
scaleX = checknumber(args.scaleX)
else
scaleX = target:getScaleX()
end
if args.scaleY then
scaleY = checknumber(args.scaleY)
else
scaleY = target:getScaleY()
end
action = cc.ScaleTo:create(checknumber(args.time), scaleX, scaleY)
end
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 创建一个动作序列对象。
-- @function [parent=#transition] sequence
-- @param table args 动作的表格对象
-- @return Sequence#Sequence ret (return value: cc.Sequence) 动作序列对象
--[[--
创建一个动作序列对象。
~~~ lua
local sequence = transition.sequence({
cc.MoveTo:create(0.5, cc.p(display.cx, display.cy)),
cc.FadeOut:create(0.2),
cc.DelayTime:create(0.5),
cc.FadeIn:create(0.3),
})
sprite:runAction(sequence)
~~~
]]
-- end --
function transition.sequence(actions)
if #actions < 1 then return end
if #actions < 2 then return actions[1] end
local prev = actions[1]
for i = 2, #actions do
prev = cc.Sequence:create(prev, actions[i])
end
return prev
end
-- start --
--------------------------------
-- 在显示对象上播放一次动画,并返回 Action 动作对象。
-- @function [parent=#transition] playAnimationOnce
-- @param cc.Node target 显示对象
-- @param cc.Node animation 动作对象
-- @param boolean removeWhenFinished 播放完成后删除显示对象
-- @param function onComplete 播放完成后要执行的函数
-- @param number delay 播放前等待的时间
-- @return table#table ret (return value: table) 动作表格对象
--[[--
在显示对象上播放一次动画,并返回 Action 动作对象。
~~~ lua
local frames = display.newFrames("Walk%04d.png", 1, 20)
local animation = display.newAnimation(frames, 0.5 / 20) -- 0.5s play 20 frames
transition.playAnimationOnce(sprite, animation)
~~~
还可以用 Sprite 对象的 playAnimationOnce() 方法来直接播放动画:
~~~ lua
local frames = display.newFrames("Walk%04d.png", 1, 20)
local animation = display.newAnimation(frames, 0.5 / 20) -- 0.5s play 20 frames
sprite:playAnimationOnce(animation)
~~~
playAnimationOnce() 提供了丰富的功能,例如在动画播放完成后就删除用于播放动画的 Sprite 对象。例如一个爆炸效果:
~~~ lua
local frames = display.newFrames("Boom%04d.png", 1, 8)
local boom = display.newSprite(frames[1])
-- playAnimationOnce() 第二个参数为 true 表示动画播放完后删除 boom 这个 Sprite 对象
-- 这样爆炸动画播放完毕,就自动清理了不需要的显示对象
boom:playAnimationOnce(display.newAnimation(frames, 0.3/ 8), true)
~~~
此外,playAnimationOnce() 还允许在动画播放完成后执行一个指定的函数,以及播放动画前等待一段时间。合理运用这些功能,可以大大简化我们的游戏代码。
]]
-- end --
function transition.playAnimationOnce(target, animation, removeWhenFinished, onComplete, delay)
local actions = {}
if type(delay) == "number" and delay > 0 then
target:setVisible(false)
actions[#actions + 1] = cc.DelayTime:create(delay)
actions[#actions + 1] = cc.Show:create()
end
actions[#actions + 1] = cc.Animate:create(animation)
if removeWhenFinished then
actions[#actions + 1] = cc.RemoveSelf:create()
end
if onComplete then
actions[#actions + 1] = cc.CallFunc:create(onComplete)
end
local action
if #actions > 1 then
action = transition.sequence(actions)
else
action = actions[1]
end
target:runAction(action)
return action
end
-- start --
--------------------------------
-- 在显示对象上循环播放动画,并返回 Action 动作对象。
-- @function [parent=#transition] playAnimationForever
-- @param cc.Node target 显示对象
-- @param cc.Node animation 动作对象
-- @param number delay 播放前等待的时间
-- @return table#table ret (return value: table) 动作表格对象
--[[--
在显示对象上循环播放动画,并返回 Action 动作对象。
~~~ lua
local frames = display.newFrames("Walk%04d.png", 1, 20)
local animation = display.newAnimation(frames, 0.5 / 20) -- 0.5s play 20 frames
sprite:playAnimationForever(animation)
~~~
]]
-- end --
function transition.playAnimationForever(target, animation, delay)
local animate = cc.Animate:create(animation)
local action
if type(delay) == "number" and delay > 0 then
target:setVisible(false)
local sequence = transition.sequence({
cc.DelayTime:create(delay),
cc.Show:create(),
animate,
})
action = cc.RepeatForever:create(sequence)
else
action = cc.RepeatForever:create(animate)
end
target:runAction(action)
return action
end
-- start --
--------------------------------
-- 停止一个正在执行的动作
-- @function [parent=#transition] removeAction
-- @param mixed target
--[[--
停止一个正在执行的动作
~~~ lua
-- 开始移动
local action = transition.moveTo(sprite, {time = 2.0, x = 100, y = 100})
....
transition.removeAction(action) -- 停止移动
~~~
]]
-- end --
function transition.removeAction(action)
if not tolua.isnull(action) then
actionManager:removeAction(action)
end
end
-- start --
--------------------------------
-- 停止一个显示对象上所有正在执行的动作
-- @function [parent=#transition] stopTarget
-- @param mixed target
--[[--
停止一个显示对象上所有正在执行的动作
~~~ lua
-- 开始移动
transition.moveTo(sprite, {time = 2.0, x = 100, y = 100})
transition.fadeOut(sprite, {time = 2.0})
....
transition.stopTarget(sprite)
~~~
注意:显示对象的 performWithDelay() 方法是用动作来实现延时回调操作的,所以如果停止显示对象上的所有动作,会清除该对象上的延时回调操作。
]]
-- end --
function transition.stopTarget(target)
if not tolua.isnull(target) then
actionManager:removeAllActionsFromTarget(target)
end
end
-- start --
--------------------------------
-- 暂停显示对象上所有正在执行的动作
-- @function [parent=#transition] pauseTarget
-- @param mixed target
-- end --
function transition.pauseTarget(target)
if not tolua.isnull(target) then
actionManager:pauseTarget(target)
end
end
-- start --
--------------------------------
-- 恢复显示对象上所有暂停的动作
-- @function [parent=#transition] resumeTarget
-- @param mixed target
-- end --
function transition.resumeTarget(target)
if not tolua.isnull(target) then
actionManager:resumeTarget(target)
end
end
return transition
| mit |
Vadavim/jsr-darkstar | scripts/zones/Abyssea-La_Theine/Zone.lua | 33 | 1482 | -----------------------------------
--
-- Zone: Abyssea - La_Theine
--
-----------------------------------
package.loaded["scripts/zones/Abyssea-La_Theine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Abyssea-La_Theine/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-480.5,-0.5,794,62);
end
if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED
and player:getVar("1stTimeAyssea") == 0) then
player:setVar("1stTimeAyssea",1);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Al_Zahbi/npcs/Gameem.lua | 14 | 1032 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Gameem
-- Type: Standard NPC
-- @zone 48
-- @pos 18.813 -7 11.298
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00ec);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
zynjec/darkstar | scripts/zones/FeiYin/npcs/Underground_Pool.lua | 9 | 1702 | -----------------------------------
-- Area: FeiYin
-- NPC: Underground Pool
-- Involved In Quest: Scattered into Shadow
-- Offset 0 (H-5) !pos 7 0 247 204
-- Offset 1 (F-5) !pos -168 0 247 204
-- Offset 2 (H-8) !pos 7 0 32 204
-----------------------------------
local ID = require("scripts/zones/FeiYin/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local offset = npc:getID() - ID.npc.UNDERGROUND_POOL_OFFSET
if player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.SCATTERED_INTO_SHADOW) == QUEST_ACCEPTED then
if offset == 0 and player:hasKeyItem(dsp.ki.AQUAFLORA2) then
player:startEvent(20)
elseif offset == 1 and player:getCharVar("DabotzKilled") == 1 then
player:startEvent(18)
elseif offset == 1 and player:hasKeyItem(dsp.ki.AQUAFLORA3) and not GetMobByID(ID.mob.DABOTZS_GHOST):isSpawned() then
SpawnMob(ID.mob.DABOTZS_GHOST):updateClaim(player)
elseif offset == 2 and player:hasKeyItem(dsp.ki.AQUAFLORA1) then
player:startEvent(21)
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 18 then
player:delKeyItem(dsp.ki.AQUAFLORA3)
player:setCharVar("DabotzKilled", 0)
elseif csid == 21 then
player:delKeyItem(dsp.ki.AQUAFLORA1)
elseif csid == 20 then
player:delKeyItem(dsp.ki.AQUAFLORA2)
end
end
| gpl-3.0 |
Vadavim/jsr-darkstar | scripts/globals/weaponskills/onslaught.lua | 19 | 2069 | -----------------------------------
-- Onslaught
-- Axe weapon skill
-- Skill Level: N/A
-- Lowers target's params.accuracy. Additional effect: temporarily increases Attack.
-- Available only when equipped with the Relic Weapons Ogre Killer (Dynamis use only) or Guttler or Cleofun Axe (with Latent active).
-- These Relic Weapons are only available to Beastmasters, so only they can use this Weapon Skill.
-- One hit attack despite of non single-hit animation
-- The attack increase seems to be 10%.
-- Aligned with the Shadow Gorget & Soil Gorget.
-- Aligned with the Shadow Belt & Soil Belt.
-- Element: None
-- Modifiers: DEX:80%
-- 100%TP 200%TP 300%TP
-- 2.75 2.75 2.75
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75;
params.str_wsc = 0.0; params.dex_wsc = 0.6; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.dex_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
-- TODO: Whoever codes those level 85 weapons with the latent that grants this WS needs to code a check to not give the aftermath effect.
if (damage > 0) then
local amDuration = 20 * math.floor(tp/1000);
player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, amDuration, 0, 4);
target:addStatusEffect(EFFECT_ACCURACY_DOWN, 20, 0, 60);
end
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Windurst_Walls/npcs/Naih_Arihmepp.lua | 14 | 1471 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Naih Arihmepp
-- Type: Standard NPC
-- @pos -64.578 -13.465 202.147 239
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,9) == false) then
player:startEvent(0x01f4);
else
player:startEvent(0x0146);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x01f4) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",9,true);
end
end;
| gpl-3.0 |
Vadavim/jsr-darkstar | scripts/globals/items/cup_of_chocomilk.lua | 18 | 1139 | -----------------------------------------
-- ID: 4498
-- Item: cup_of_chocomilk
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Magic Regen While Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4498);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 3);
end;
| gpl-3.0 |
davidcarlisle/luaotfload | src/fontloader/misc/fontloader-font-tfm.lua | 1 | 8509 | if not modules then modules = { } end modules ['font-tfm'] = {
version = 1.001,
comment = "companion to font-ini.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
local next = next
local match = string.match
local trace_defining = false trackers.register("fonts.defining", function(v) trace_defining = v end)
local trace_features = false trackers.register("tfm.features", function(v) trace_features = v end)
local report_defining = logs.reporter("fonts","defining")
local report_tfm = logs.reporter("fonts","tfm loading")
local findbinfile = resolvers.findbinfile
local fonts = fonts
local handlers = fonts.handlers
local readers = fonts.readers
local constructors = fonts.constructors
local encodings = fonts.encodings
local tfm = constructors.newhandler("tfm")
tfm.version = 1.000
tfm.maxnestingdepth = 5
tfm.maxnestingsize = 65536*1024
local tfmfeatures = constructors.newfeatures("tfm")
local registertfmfeature = tfmfeatures.register
constructors.resolvevirtualtoo = false -- wil be set in font-ctx.lua
fonts.formats.tfm = "type1" -- we need to have at least a value here
--[[ldx--
<p>The next function encapsulates the standard <l n='tfm'/> loader as
supplied by <l n='luatex'/>.</p>
--ldx]]--
-- this might change: not scaling and then apply features and do scaling in the
-- usual way with dummy descriptions but on the other hand .. we no longer use
-- tfm so why bother
-- ofm directive blocks local path search unless set; btw, in context we
-- don't support ofm files anyway as this format is obsolete
-- we need to deal with nested virtual fonts, but because we load in the
-- frontend we also need to make sure we don't nest too deep (esp when sizes
-- get large)
--
-- (VTITLE Example of a recursion)
-- (MAPFONT D 0 (FONTNAME recurse)(FONTAT D 2))
-- (CHARACTER C A (CHARWD D 1)(CHARHT D 1)(MAP (SETRULE D 1 D 1)))
-- (CHARACTER C B (CHARWD D 2)(CHARHT D 2)(MAP (SETCHAR C A)))
-- (CHARACTER C C (CHARWD D 4)(CHARHT D 4)(MAP (SETCHAR C B)))
--
-- we added the same checks as below to the luatex engine
function tfm.setfeatures(tfmdata,features)
local okay = constructors.initializefeatures("tfm",tfmdata,features,trace_features,report_tfm)
if okay then
return constructors.collectprocessors("tfm",tfmdata,features,trace_features,report_tfm)
else
return { } -- will become false
end
end
local depth = { } -- table.setmetatableindex("number")
local function read_from_tfm(specification)
local filename = specification.filename
local size = specification.size
depth[filename] = (depth[filename] or 0) + 1
if trace_defining then
report_defining("loading tfm file %a at size %s",filename,size)
end
local tfmdata = font.read_tfm(filename,size) -- not cached, fast enough
if tfmdata then
local features = specification.features and specification.features.normal or { }
local resources = tfmdata.resources or { }
local properties = tfmdata.properties or { }
local parameters = tfmdata.parameters or { }
local shared = tfmdata.shared or { }
properties.name = tfmdata.name
properties.fontname = tfmdata.fontname
properties.psname = tfmdata.psname
properties.filename = specification.filename
properties.format = fonts.formats.tfm -- better than nothing
parameters.size = size
--
tfmdata.properties = properties
tfmdata.resources = resources
tfmdata.parameters = parameters
tfmdata.shared = shared
--
shared.rawdata = { }
shared.features = features
shared.processes = next(features) and tfm.setfeatures(tfmdata,features) or nil
parameters.slant = parameters.slant or parameters[1] or 0
parameters.space = parameters.space or parameters[2] or 0
parameters.space_stretch = parameters.space_stretch or parameters[3] or 0
parameters.space_shrink = parameters.space_shrink or parameters[4] or 0
parameters.x_height = parameters.x_height or parameters[5] or 0
parameters.quad = parameters.quad or parameters[6] or 0
parameters.extra_space = parameters.extra_space or parameters[7] or 0
--
constructors.enhanceparameters(parameters) -- official copies for us
--
if constructors.resolvevirtualtoo then
fonts.loggers.register(tfmdata,file.suffix(filename),specification) -- strange, why here
local vfname = findbinfile(specification.name, 'ovf')
if vfname and vfname ~= "" then
local vfdata = font.read_vf(vfname,size) -- not cached, fast enough
if vfdata then
local chars = tfmdata.characters
for k,v in next, vfdata.characters do
chars[k].commands = v.commands
end
properties.virtualized = true
tfmdata.fonts = vfdata.fonts
tfmdata.type = "virtual" -- else nested calls with cummulative scaling
local fontlist = vfdata.fonts
local name = file.nameonly(filename)
for i=1,#fontlist do
local n = fontlist[i].name
local s = fontlist[i].size
local d = depth[filename]
s = constructors.scaled(s,vfdata.designsize)
if d > tfm.maxnestingdepth then
report_defining("too deeply nested virtual font %a with size %a, max nesting depth %s",n,s,tfm.maxnestingdepth)
fontlist[i] = { id = 0 }
elseif (d > 1) and (s > tfm.maxnestingsize) then
report_defining("virtual font %a exceeds size %s",n,s)
fontlist[i] = { id = 0 }
else
local t, id = fonts.constructors.readanddefine(n,s)
fontlist[i] = { id = id }
end
end
end
end
end
--
local allfeatures = tfmdata.shared.features or specification.features.normal
constructors.applymanipulators("tfm",tfmdata,allfeatures.normal,trace_features,report_tfm)
if not features.encoding then
local encoding, filename = match(properties.filename,"^(.-)%-(.*)$") -- context: encoding-name.*
if filename and encoding and encodings.known and encodings.known[encoding] then
features.encoding = encoding
end
end
-- let's play safe:
properties.haskerns = true
properties.haslogatures = true
resources.unicodes = { }
resources.lookuptags = { }
--
depth[filename] = depth[filename] - 1
return tfmdata
else
depth[filename] = depth[filename] - 1
end
end
local function check_tfm(specification,fullname) -- we could split up like afm/otf
local foundname = findbinfile(fullname, 'tfm') or ""
if foundname == "" then
foundname = findbinfile(fullname, 'ofm') or "" -- not needed in context
end
if foundname == "" then
foundname = fonts.names.getfilename(fullname,"tfm") or ""
end
if foundname ~= "" then
specification.filename = foundname
specification.format = "ofm"
return read_from_tfm(specification)
elseif trace_defining then
report_defining("loading tfm with name %a fails",specification.name)
end
end
readers.check_tfm = check_tfm
function readers.tfm(specification)
local fullname = specification.filename or ""
if fullname == "" then
local forced = specification.forced or ""
if forced ~= "" then
fullname = specification.name .. "." .. forced
else
fullname = specification.name
end
end
return check_tfm(specification,fullname)
end
| gpl-2.0 |
RJRetro/mame | scripts/src/sound.lua | 2 | 34977 | -- license:BSD-3-Clause
-- copyright-holders:MAMEdev Team
---------------------------------------------------------------------------
--
-- sound.lua
--
-- Rules for building sound cores
--
----------------------------------------------------------------------------
---------------------------------------------------
-- DACs
--@src/devices/sound/dac.h,SOUNDS["DAC"] = true
--@src/devices/sound/dmadac.h,SOUNDS["DMADAC"] = true
--@src/devices/sound/speaker.h,SOUNDS["SPEAKER"] = true
--@src/devices/sound/beep.h,SOUNDS["BEEP"] = true
---------------------------------------------------
if (SOUNDS["DAC"]~=null) then
files {
MAME_DIR .. "src/devices/sound/dac.cpp",
MAME_DIR .. "src/devices/sound/dac.h",
}
end
if (SOUNDS["DMADAC"]~=null) then
files {
MAME_DIR .. "src/devices/sound/dmadac.cpp",
MAME_DIR .. "src/devices/sound/dmadac.h",
}
end
if (SOUNDS["SPEAKER"]~=null) then
files {
MAME_DIR .. "src/devices/sound/speaker.cpp",
MAME_DIR .. "src/devices/sound/speaker.h",
}
end
if (SOUNDS["BEEP"]~=null) then
files {
MAME_DIR .. "src/devices/sound/beep.cpp",
MAME_DIR .. "src/devices/sound/beep.h",
}
end
---------------------------------------------------
-- CD audio
--@src/devices/sound/cdda.h,SOUNDS["CDDA"] = true
---------------------------------------------------
if (SOUNDS["CDDA"]~=null) then
files {
MAME_DIR .. "src/devices/sound/cdda.cpp",
MAME_DIR .. "src/devices/sound/cdda.h",
}
end
---------------------------------------------------
-- Discrete component audio
--@src/devices/sound/discrete.h,SOUNDS["DISCRETE"] = true
---------------------------------------------------
if (SOUNDS["DISCRETE"]~=null) then
files {
MAME_DIR .. "src/devices/sound/discrete.cpp",
MAME_DIR .. "src/devices/sound/discrete.h",
MAME_DIR .. "src/devices/sound/disc_cls.h",
MAME_DIR .. "src/devices/sound/disc_dev.h",
MAME_DIR .. "src/devices/sound/disc_dev.inc",
MAME_DIR .. "src/devices/sound/disc_flt.h",
MAME_DIR .. "src/devices/sound/disc_flt.inc",
MAME_DIR .. "src/devices/sound/disc_inp.inc",
MAME_DIR .. "src/devices/sound/disc_mth.h",
MAME_DIR .. "src/devices/sound/disc_mth.inc",
MAME_DIR .. "src/devices/sound/disc_sys.inc",
MAME_DIR .. "src/devices/sound/disc_wav.h",
MAME_DIR .. "src/devices/sound/disc_wav.inc",
}
end
---------------------------------------------------
-- AC97
--@src/devices/sound/pic-ac97.h,SOUNDS["AC97"] = true
---------------------------------------------------
if (SOUNDS["AC97"]~=null) then
files {
MAME_DIR .. "src/devices/sound/pci-ac97.cpp",
MAME_DIR .. "src/devices/sound/pci-ac97.h",
}
end
---------------------------------------------------
-- Apple custom sound chips
--@src/devices/sound/asc.h,SOUNDS["ASC"] = true
--@src/devices/sound/awacs.h,SOUNDS["AWACS"] = true
---------------------------------------------------
if (SOUNDS["ASC"]~=null) then
files {
MAME_DIR .. "src/devices/sound/asc.cpp",
MAME_DIR .. "src/devices/sound/asc.h",
}
end
if (SOUNDS["AWACS"]~=null) then
files {
MAME_DIR .. "src/devices/sound/awacs.cpp",
MAME_DIR .. "src/devices/sound/awacs.h",
}
end
---------------------------------------------------
-- Atari custom sound chips
--@src/devices/sound/pokey.h,SOUNDS["POKEY"] = true
--@src/devices/sound/tiaintf.h,SOUNDS["TIA"] = true
---------------------------------------------------
if (SOUNDS["POKEY"]~=null) then
files {
MAME_DIR .. "src/devices/sound/pokey.cpp",
MAME_DIR .. "src/devices/sound/pokey.h",
}
end
if (SOUNDS["TIA"]~=null) then
files {
MAME_DIR .. "src/devices/sound/tiasound.cpp",
MAME_DIR .. "src/devices/sound/tiasound.h",
MAME_DIR .. "src/devices/sound/tiaintf.cpp",
MAME_DIR .. "src/devices/sound/tiaintf.h",
}
end
---------------------------------------------------
-- Amiga audio hardware
--@src/devices/sound/amiga.h,SOUNDS["AMIGA"] = true
---------------------------------------------------
if (SOUNDS["AMIGA"]~=null) then
files {
MAME_DIR .. "src/devices/sound/amiga.cpp",
MAME_DIR .. "src/devices/sound/amiga.h",
}
end
---------------------------------------------------
-- Bally Astrocade sound system
--@src/devices/sound/astrocde.h,SOUNDS["ASTROCADE"] = true
---------------------------------------------------
if (SOUNDS["ASTROCADE"]~=null) then
files {
MAME_DIR .. "src/devices/sound/astrocde.cpp",
MAME_DIR .. "src/devices/sound/astrocde.h",
}
end
---------------------------------------------------
---------------------------------------------------
-- AC97
--@src/devices/sound/pic-ac97.h,SOUNDS["AC97"] = true
---------------------------------------------------
if (SOUNDS["AC97"]~=null) then
files {
MAME_DIR .. "src/devices/sound/pci-ac97.cpp",
MAME_DIR .. "src/devices/sound/pci-ac97.h",
}
end
-- CEM 3394 analog synthesizer chip
--@src/devices/sound/cem3394.h,SOUNDS["CEM3394"] = true
---------------------------------------------------
if (SOUNDS["CEM3394"]~=null) then
files {
MAME_DIR .. "src/devices/sound/cem3394.cpp",
MAME_DIR .. "src/devices/sound/cem3394.h",
}
end
---------------------------------------------------
-- Creative Labs SB0400 Audigy2 Value
--@src/devices/sound/sb0400.h,SOUNDS["SB0400"] = true
---------------------------------------------------
if (SOUNDS["SB0400"]~=null) then
files {
MAME_DIR .. "src/devices/sound/sb0400.cpp",
MAME_DIR .. "src/devices/sound/sb0400.h",
}
end
--------------------------------------------------
-- Creative Labs Ensonic AudioPCI97 ES1373
--@src/devices/sound/es1373.h,SOUNDS["ES1373"] = true
--------------------------------------------------
if (SOUNDS["ES1373"]~=null) then
files {
MAME_DIR .. "src/devices/sound/es1373.cpp",
MAME_DIR .. "src/devices/sound/es1373.h",
}
end
---------------------------------------------------
-- Data East custom sound chips
--@src/devices/sound/bsmt2000.h,SOUNDS["BSMT2000"] = true
---------------------------------------------------
if (SOUNDS["BSMT2000"]~=null) then
files {
MAME_DIR .. "src/devices/sound/bsmt2000.cpp",
MAME_DIR .. "src/devices/sound/bsmt2000.h",
}
end
---------------------------------------------------
-- Ensoniq 5503 (Apple IIgs)
--@src/devices/sound/es5503.h,SOUNDS["ES5503"] = true
---------------------------------------------------
if (SOUNDS["ES5503"]~=null) then
files {
MAME_DIR .. "src/devices/sound/es5503.cpp",
MAME_DIR .. "src/devices/sound/es5503.h",
}
end
---------------------------------------------------
-- Ensoniq 5505/5506
--@src/devices/sound/es5506.h,SOUNDS["ES5505"] = true
---------------------------------------------------
if (SOUNDS["ES5505"]~=null or SOUNDS["ES5506"]~=null) then
files {
MAME_DIR .. "src/devices/sound/es5506.cpp",
MAME_DIR .. "src/devices/sound/es5506.h",
}
end
---------------------------------------------------
-- Ensoniq "pump" device, interfaces 5505/5506 with 5510
--@src/devices/sound/esqpump.h,SOUNDS["ESQPUMP"] = true
---------------------------------------------------
if (SOUNDS["ESQPUMP"]~=null) then
files {
MAME_DIR .. "src/devices/sound/esqpump.cpp",
MAME_DIR .. "src/devices/sound/esqpump.h",
}
end
---------------------------------------------------
-- Excellent Systems ADPCM sound chip
--@src/devices/sound/es8712.h,SOUNDS["ES8712"] = true
---------------------------------------------------
if (SOUNDS["ES8712"]~=null) then
files {
MAME_DIR .. "src/devices/sound/es8712.cpp",
MAME_DIR .. "src/devices/sound/es8712.h",
}
end
---------------------------------------------------
-- Gaelco custom sound chips
--@src/devices/sound/gaelco.h,SOUNDS["GAELCO_CG1V"] = true
---------------------------------------------------
if (SOUNDS["GAELCO_CG1V"]~=null or SOUNDS["GAELCO_GAE1"]~=null) then
files {
MAME_DIR .. "src/devices/sound/gaelco.cpp",
MAME_DIR .. "src/devices/sound/gaelco.h",
}
end
---------------------------------------------------
-- RCA CDP1863
--@src/devices/sound/cdp1863.h,SOUNDS["CDP1863"] = true
---------------------------------------------------
if (SOUNDS["CDP1863"]~=null) then
files {
MAME_DIR .. "src/devices/sound/cdp1863.cpp",
MAME_DIR .. "src/devices/sound/cdp1863.h",
}
end
---------------------------------------------------
-- RCA CDP1864
--@src/devices/sound/cdp1864.h,SOUNDS["CDP1864"] = true
---------------------------------------------------
if (SOUNDS["CDP1864"]~=null) then
files {
MAME_DIR .. "src/devices/sound/cdp1864.cpp",
MAME_DIR .. "src/devices/sound/cdp1864.h",
}
end
---------------------------------------------------
-- RCA CDP1869
--@src/devices/sound/cdp1869.h,SOUNDS["CDP1869"] = true
---------------------------------------------------
if (SOUNDS["CDP1869"]~=null) then
files {
MAME_DIR .. "src/devices/sound/cdp1869.cpp",
MAME_DIR .. "src/devices/sound/cdp1869.h",
}
end
---------------------------------------------------
-- GI AY-8910
--@src/devices/sound/ay8910.h,SOUNDS["AY8910"] = true
---------------------------------------------------
if (SOUNDS["AY8910"]~=null) then
files {
MAME_DIR .. "src/devices/sound/ay8910.cpp",
MAME_DIR .. "src/devices/sound/ay8910.h",
}
end
---------------------------------------------------
-- Harris HC55516 CVSD
--@src/devices/sound/hc55516.h,SOUNDS["HC55516"] = true
---------------------------------------------------
if (SOUNDS["HC55516"]~=null) then
files {
MAME_DIR .. "src/devices/sound/hc55516.cpp",
MAME_DIR .. "src/devices/sound/hc55516.h",
}
end
---------------------------------------------------
-- Hudsonsoft C6280 sound chip
--@src/devices/sound/c6280.h,SOUNDS["C6280"] = true
---------------------------------------------------
if (SOUNDS["C6280"]~=null) then
files {
MAME_DIR .. "src/devices/sound/c6280.cpp",
MAME_DIR .. "src/devices/sound/c6280.h",
}
end
---------------------------------------------------
-- ICS2115 sound chip
--@src/devices/sound/ics2115.h,SOUNDS["ICS2115"] = true
---------------------------------------------------
if (SOUNDS["ICS2115"]~=null) then
files {
MAME_DIR .. "src/devices/sound/ics2115.cpp",
MAME_DIR .. "src/devices/sound/ics2115.h",
}
end
---------------------------------------------------
-- Imagetek I5000 sound
--@src/devices/sound/i5000.h,SOUNDS["I5000_SND"] = true
---------------------------------------------------
if (SOUNDS["I5000_SND"]~=null) then
files {
MAME_DIR .. "src/devices/sound/i5000.cpp",
MAME_DIR .. "src/devices/sound/i5000.h",
}
end
---------------------------------------------------
-- Irem custom sound chips
--@src/devices/sound/iremga20.h,SOUNDS["IREMGA20"] = true
---------------------------------------------------
if (SOUNDS["IREMGA20"]~=null) then
files {
MAME_DIR .. "src/devices/sound/iremga20.cpp",
MAME_DIR .. "src/devices/sound/iremga20.h",
}
end
---------------------------------------------------
-- Konami custom sound chips
--@src/devices/sound/k005289.h,SOUNDS["K005289"] = true
--@src/devices/sound/k007232.h,SOUNDS["K007232"] = true
--@src/devices/sound/k051649.h,SOUNDS["K051649"] = true
--@src/devices/sound/k053260.h,SOUNDS["K053260"] = true
--@src/devices/sound/k054539.h,SOUNDS["K054539"] = true
--@src/devices/sound/k056800.h,SOUNDS["K056800"] = true
---------------------------------------------------
if (SOUNDS["K005289"]~=null) then
files {
MAME_DIR .. "src/devices/sound/k005289.cpp",
MAME_DIR .. "src/devices/sound/k005289.h",
}
end
if (SOUNDS["K007232"]~=null) then
files {
MAME_DIR .. "src/devices/sound/k007232.cpp",
MAME_DIR .. "src/devices/sound/k007232.h",
}
end
if (SOUNDS["K051649"]~=null) then
files {
MAME_DIR .. "src/devices/sound/k051649.cpp",
MAME_DIR .. "src/devices/sound/k051649.h",
}
end
if (SOUNDS["K053260"]~=null) then
files {
MAME_DIR .. "src/devices/sound/k053260.cpp",
MAME_DIR .. "src/devices/sound/k053260.h",
}
end
if (SOUNDS["K054539"]~=null) then
files {
MAME_DIR .. "src/devices/sound/k054539.cpp",
MAME_DIR .. "src/devices/sound/k054539.h",
}
end
if (SOUNDS["K056800"]~=null) then
files {
MAME_DIR .. "src/devices/sound/k056800.cpp",
MAME_DIR .. "src/devices/sound/k056800.h",
}
end
---------------------------------------------------
-- L7A1045 L6028 DSP-A
--@src/devices/sound/l7a1045_l6028_dsp_a.h,SOUNDS["L7A1045"] = true
---------------------------------------------------
if (SOUNDS["L7A1045"]~=null) then
files {
MAME_DIR .. "src/devices/sound/l7a1045_l6028_dsp_a.cpp",
MAME_DIR .. "src/devices/sound/l7a1045_l6028_dsp_a.h",
}
end
---------------------------------------------------
-- LMC1992 mixer chip
--@src/devices/sound/lmc1992.h,SOUNDS["LMC1992"] = true
---------------------------------------------------
if (SOUNDS["LMC1992"]~=null) then
files {
MAME_DIR .. "src/devices/sound/lmc1992.cpp",
MAME_DIR .. "src/devices/sound/lmc1992.h",
}
end
---------------------------------------------------
-- MAS 3507D MPEG 1/2 Layer 2/3 Audio Decoder
--@src/devices/sound/mas3507d.h,SOUNDS["MAS3507D"] = true
---------------------------------------------------
if (SOUNDS["MAS3507D"]~=null) then
files {
MAME_DIR .. "src/devices/sound/mas3507d.cpp",
MAME_DIR .. "src/devices/sound/mas3507d.h",
}
end
---------------------------------------------------
-- MOS 6560VIC
--@src/devices/sound/mos6560.h,SOUNDS["MOS656X"] = true
---------------------------------------------------
if (SOUNDS["MOS656X"]~=null) then
files {
MAME_DIR .. "src/devices/sound/mos6560.cpp",
MAME_DIR .. "src/devices/sound/mos6560.h",
}
end
---------------------------------------------------
-- MOS 7360 TED
--@src/devices/sound/mos7360.h,SOUNDS["MOS7360"] = true
---------------------------------------------------
if (SOUNDS["MOS7360"]~=null) then
files {
MAME_DIR .. "src/devices/sound/mos7360.cpp",
MAME_DIR .. "src/devices/sound/mos7360.h",
}
end
---------------------------------------------------
-- Namco custom sound chips
--@src/devices/sound/namco.h,SOUNDS["NAMCO"] = true
--@src/devices/sound/n63701x.h,SOUNDS["NAMCO_63701X"] = true
--@src/devices/sound/c140.h,SOUNDS["C140"] = true
--@src/devices/sound/c352.h,SOUNDS["C352"] = true
---------------------------------------------------
if (SOUNDS["NAMCO"]~=null or SOUNDS["NAMCO_15XX"]~=null or SOUNDS["NAMCO_CUS30"]~=null) then
files {
MAME_DIR .. "src/devices/sound/namco.cpp",
MAME_DIR .. "src/devices/sound/namco.h",
}
end
if (SOUNDS["NAMCO_63701X"]~=null) then
files {
MAME_DIR .. "src/devices/sound/n63701x.cpp",
MAME_DIR .. "src/devices/sound/n63701x.h",
}
end
if (SOUNDS["C140"]~=null) then
files {
MAME_DIR .. "src/devices/sound/c140.cpp",
MAME_DIR .. "src/devices/sound/c140.h",
}
end
if (SOUNDS["C352"]~=null) then
files {
MAME_DIR .. "src/devices/sound/c352.cpp",
MAME_DIR .. "src/devices/sound/c352.h",
}
end
---------------------------------------------------
-- National Semiconductor Digitalker
--@src/devices/sound/digitalk.h,SOUNDS["DIGITALKER"] = true
---------------------------------------------------
if (SOUNDS["DIGITALKER"]~=null) then
files {
MAME_DIR .. "src/devices/sound/digitalk.cpp",
MAME_DIR .. "src/devices/sound/digitalk.h",
}
end
---------------------------------------------------
-- Nintendo custom sound chips
--@src/devices/sound/nes_apu.h,SOUNDS["NES_APU"] = true
---------------------------------------------------
if (SOUNDS["NES_APU"]~=null) then
files {
MAME_DIR .. "src/devices/sound/nes_apu.cpp",
MAME_DIR .. "src/devices/sound/nes_apu.h",
MAME_DIR .. "src/devices/sound/nes_defs.h",
}
end
---------------------------------------------------
-- NEC uPD7759 ADPCM sample player
--@src/devices/sound/upd7759.h,SOUNDS["UPD7759"] = true
---------------------------------------------------
if (SOUNDS["UPD7759"]~=null) then
files {
MAME_DIR .. "src/devices/sound/upd7759.cpp",
MAME_DIR .. "src/devices/sound/upd7759.h",
MAME_DIR .. "src/devices/sound/315-5641.cpp",
MAME_DIR .. "src/devices/sound/315-5641.h",
}
end
---------------------------------------------------
-- OKI ADPCM sample players
--@src/devices/sound/okim6258.h,SOUNDS["OKIM6258"] = true
--@src/devices/sound/msm5205.h,SOUNDS["MSM5205"] = true
--@src/devices/sound/msm5232.h,SOUNDS["MSM5232"] = true
--@src/devices/sound/okim6376.h,SOUNDS["OKIM6376"] = true
--@src/devices/sound/okim6295.h,SOUNDS["OKIM6295"] = true
--@src/devices/sound/okim9810.h,SOUNDS["OKIM9810"] = true
---------------------------------------------------
if (SOUNDS["OKIM6258"]~=null or SOUNDS["OKIM6295"]~=null or SOUNDS["OKIM9810"]~=null or SOUNDS["I5000_SND"]~=null) then
files {
MAME_DIR .. "src/devices/sound/okiadpcm.cpp",
MAME_DIR .. "src/devices/sound/okiadpcm.h",
}
end
if (SOUNDS["MSM5205"]~=null or SOUNDS["MSM6585"]~=null) then
files {
MAME_DIR .. "src/devices/sound/msm5205.cpp",
MAME_DIR .. "src/devices/sound/msm5205.h",
}
end
if (SOUNDS["MSM5232"]~=null) then
files {
MAME_DIR .. "src/devices/sound/msm5232.cpp",
MAME_DIR .. "src/devices/sound/msm5232.h",
}
end
if (SOUNDS["OKIM6376"]~=null) then
files {
MAME_DIR .. "src/devices/sound/okim6376.cpp",
MAME_DIR .. "src/devices/sound/okim6376.h",
}
end
if (SOUNDS["OKIM6295"]~=null) then
files {
MAME_DIR .. "src/devices/sound/okim6295.cpp",
MAME_DIR .. "src/devices/sound/okim6295.h",
}
end
if (SOUNDS["OKIM6258"]~=null) then
files {
MAME_DIR .. "src/devices/sound/okim6258.cpp",
MAME_DIR .. "src/devices/sound/okim6258.h",
}
end
if (SOUNDS["OKIM9810"]~=null) then
files {
MAME_DIR .. "src/devices/sound/okim9810.cpp",
MAME_DIR .. "src/devices/sound/okim9810.h",
}
end
---------------------------------------------------
-- Philips SAA1099
--@src/devices/sound/saa1099.h,SOUNDS["SAA1099"] = true
---------------------------------------------------
if (SOUNDS["SAA1099"]~=null) then
files {
MAME_DIR .. "src/devices/sound/saa1099.cpp",
MAME_DIR .. "src/devices/sound/saa1099.h",
}
end
---------------------------------------------------
-- AdMOS QS1000
--@src/devices/sound/qs1000.h,SOUNDS["QS1000"] = true
---------------------------------------------------
if (SOUNDS["QS1000"]~=null) then
files {
MAME_DIR .. "src/devices/sound/qs1000.cpp",
MAME_DIR .. "src/devices/sound/qs1000.h",
}
end
---------------------------------------------------
-- QSound sample player
--@src/devices/sound/qsound.h,SOUNDS["QSOUND"] = true
---------------------------------------------------
if (SOUNDS["QSOUND"]~=null) then
files {
MAME_DIR .. "src/devices/sound/qsound.cpp",
MAME_DIR .. "src/devices/sound/qsound.h",
MAME_DIR .. "src/devices/cpu/dsp16/dsp16.cpp",
MAME_DIR .. "src/devices/cpu/dsp16/dsp16.h",
MAME_DIR .. "src/devices/cpu/dsp16/dsp16dis.cpp",
}
end
---------------------------------------------------
-- Ricoh sample players
--@src/devices/sound/rf5c68.h,SOUNDS["RF5C68"] = true
--@src/devices/sound/rf5c400.h,SOUNDS["RF5C400"] = true
---------------------------------------------------
if (SOUNDS["RF5C68"]~=null) then
files {
MAME_DIR .. "src/devices/sound/rf5c68.cpp",
MAME_DIR .. "src/devices/sound/rf5c68.h",
}
end
if (SOUNDS["RF5C400"]~=null) then
files {
MAME_DIR .. "src/devices/sound/rf5c400.cpp",
MAME_DIR .. "src/devices/sound/rf5c400.h",
}
end
---------------------------------------------------
-- Sega custom sound chips
--@src/devices/sound/segapcm.h,SOUNDS["SEGAPCM"] = true
--@src/devices/sound/multipcm.h,SOUNDS["MULTIPCM"] = true
--@src/devices/sound/scsp.h,SOUNDS["SCSP"] = true
--@src/devices/sound/aica.h,SOUNDS["AICA"] = true
---------------------------------------------------
if (SOUNDS["SEGAPCM"]~=null) then
files {
MAME_DIR .. "src/devices/sound/segapcm.cpp",
MAME_DIR .. "src/devices/sound/segapcm.h",
}
end
if (SOUNDS["MULTIPCM"]~=null) then
files {
MAME_DIR .. "src/devices/sound/multipcm.cpp",
MAME_DIR .. "src/devices/sound/multipcm.h",
}
end
if (SOUNDS["SCSP"]~=null) then
files {
MAME_DIR .. "src/devices/sound/scsp.cpp",
MAME_DIR .. "src/devices/sound/scsp.h",
MAME_DIR .. "src/devices/sound/scspdsp.cpp",
MAME_DIR .. "src/devices/sound/scspdsp.h",
}
end
if (SOUNDS["AICA"]~=null) then
files {
MAME_DIR .. "src/devices/sound/aica.cpp",
MAME_DIR .. "src/devices/sound/aica.h",
MAME_DIR .. "src/devices/sound/aicadsp.cpp",
MAME_DIR .. "src/devices/sound/aicadsp.h",
}
end
---------------------------------------------------
-- Seta custom sound chips
--@src/devices/sound/st0016.h,SOUNDS["ST0016"] = true
--@src/devices/sound/nile.h,SOUNDS["NILE"] = true
--@src/devices/sound/x1_010.h,SOUNDS["X1_010"] = true
---------------------------------------------------
if (SOUNDS["ST0016"]~=null) then
files {
MAME_DIR .. "src/devices/sound/st0016.cpp",
MAME_DIR .. "src/devices/sound/st0016.h",
}
end
if (SOUNDS["NILE"]~=null) then
files {
MAME_DIR .. "src/devices/sound/nile.cpp",
MAME_DIR .. "src/devices/sound/nile.h",
}
end
if (SOUNDS["X1_010"]~=null) then
files {
MAME_DIR .. "src/devices/sound/x1_010.cpp",
MAME_DIR .. "src/devices/sound/x1_010.h",
}
end
---------------------------------------------------
-- SID custom sound chips
--@src/devices/sound/mos6581.h,SOUNDS["SID6581"] = true
---------------------------------------------------
if (SOUNDS["SID6581"]~=null or SOUNDS["SID8580"]~=null) then
files {
MAME_DIR .. "src/devices/sound/mos6581.cpp",
MAME_DIR .. "src/devices/sound/mos6581.h",
MAME_DIR .. "src/devices/sound/sid.cpp",
MAME_DIR .. "src/devices/sound/sid.h",
MAME_DIR .. "src/devices/sound/sidenvel.cpp",
MAME_DIR .. "src/devices/sound/sidenvel.h",
MAME_DIR .. "src/devices/sound/sidvoice.cpp",
MAME_DIR .. "src/devices/sound/sidvoice.h",
MAME_DIR .. "src/devices/sound/side6581.h",
MAME_DIR .. "src/devices/sound/sidw6581.h",
MAME_DIR .. "src/devices/sound/sidw8580.h",
}
end
---------------------------------------------------
-- SNK(?) custom stereo sn76489a clone
--@src/devices/sound/t6w28.h,SOUNDS["T6W28"] = true
---------------------------------------------------
if (SOUNDS["T6W28"]~=null) then
files {
MAME_DIR .. "src/devices/sound/t6w28.cpp",
MAME_DIR .. "src/devices/sound/t6w28.h",
}
end
---------------------------------------------------
-- SNK custom wave generator
--@src/devices/sound/snkwave.h,SOUNDS["SNKWAVE"] = true
---------------------------------------------------
if (SOUNDS["SNKWAVE"]~=null) then
files {
MAME_DIR .. "src/devices/sound/snkwave.cpp",
MAME_DIR .. "src/devices/sound/snkwave.h",
}
end
---------------------------------------------------
-- Sony custom sound chips
--@src/devices/sound/spu.h,SOUNDS["SPU"] = true
---------------------------------------------------
if (SOUNDS["SPU"]~=null) then
files {
MAME_DIR .. "src/devices/sound/spu.cpp",
MAME_DIR .. "src/devices/sound/spu.h",
MAME_DIR .. "src/devices/sound/spu_tables.cpp",
MAME_DIR .. "src/devices/sound/spureverb.cpp",
MAME_DIR .. "src/devices/sound/spureverb.h",
}
end
---------------------------------------------------
-- SP0256 speech synthesizer
--@src/devices/sound/sp0256.h,SOUNDS["SP0256"] = true
---------------------------------------------------
if (SOUNDS["SP0256"]~=null) then
files {
MAME_DIR .. "src/devices/sound/sp0256.cpp",
MAME_DIR .. "src/devices/sound/sp0256.h",
}
end
---------------------------------------------------
-- SP0250 speech synthesizer
--@src/devices/sound/sp0250.h,SOUNDS["SP0250"] = true
---------------------------------------------------
if (SOUNDS["SP0250"]~=null) then
files {
MAME_DIR .. "src/devices/sound/sp0250.cpp",
MAME_DIR .. "src/devices/sound/sp0250.h",
}
end
---------------------------------------------------
-- S14001A speech synthesizer
--@src/devices/sound/s14001a.h,SOUNDS["S14001A"] = true
---------------------------------------------------
if (SOUNDS["S14001A"]~=null) then
files {
MAME_DIR .. "src/devices/sound/s14001a.cpp",
MAME_DIR .. "src/devices/sound/s14001a.h",
}
end
---------------------------------------------------
-- Texas Instruments SN76477 analog chip
--@src/devices/sound/sn76477.h,SOUNDS["SN76477"] = true
---------------------------------------------------
if (SOUNDS["SN76477"]~=null) then
files {
MAME_DIR .. "src/devices/sound/sn76477.cpp",
MAME_DIR .. "src/devices/sound/sn76477.h",
}
end
---------------------------------------------------
-- Texas Instruments SN76496
--@src/devices/sound/sn76496.h,SOUNDS["SN76496"] = true
---------------------------------------------------
if (SOUNDS["SN76496"]~=null) then
files {
MAME_DIR .. "src/devices/sound/sn76496.cpp",
MAME_DIR .. "src/devices/sound/sn76496.h",
}
end
---------------------------------------------------
-- Texas Instruments TMS36xx doorbell chime
--@src/devices/sound/tms36xx.h,SOUNDS["TMS36XX"] = true
---------------------------------------------------
if (SOUNDS["TMS36XX"]~=null) then
files {
MAME_DIR .. "src/devices/sound/tms36xx.cpp",
MAME_DIR .. "src/devices/sound/tms36xx.h",
}
end
---------------------------------------------------
-- Texas Instruments TMS3615 Octave Multiple Tone Synthesizer
--@src/devices/sound/tms3615.h,SOUNDS["TMS3615"] = true
---------------------------------------------------
if (SOUNDS["TMS3615"]~=null) then
files {
MAME_DIR .. "src/devices/sound/tms3615.cpp",
MAME_DIR .. "src/devices/sound/tms3615.h",
}
end
---------------------------------------------------
-- Texas Instruments TMS5100-series speech synthesizers
--@src/devices/sound/tms5110.h,SOUNDS["TMS5110"] = true
---------------------------------------------------
if (SOUNDS["TMS5110"]~=null) then
files {
MAME_DIR .. "src/devices/sound/tms5110.cpp",
MAME_DIR .. "src/devices/sound/tms5110.h",
MAME_DIR .. "src/devices/sound/tms5110r.inc",
}
end
---------------------------------------------------
-- Texas Instruments TMS5200-series speech synthesizers
--@src/devices/sound/tms5220.h,SOUNDS["TMS5220"] = true
---------------------------------------------------
if (SOUNDS["TMS5220"]~=null) then
files {
MAME_DIR .. "src/devices/sound/tms5220.cpp",
MAME_DIR .. "src/devices/sound/tms5220.h",
MAME_DIR .. "src/devices/sound/tms5110r.inc",
MAME_DIR .. "src/devices/machine/spchrom.cpp",
MAME_DIR .. "src/devices/machine/spchrom.h",
}
end
---------------------------------------------------
-- Toshiba T6721A voice synthesizer
--@src/devices/sound/t6721a.h,SOUNDS["T6721A"] = true
---------------------------------------------------
if (SOUNDS["T6721A"]~=null) then
files {
MAME_DIR .. "src/devices/sound/t6721a.cpp",
MAME_DIR .. "src/devices/sound/t6721a.h",
}
end
---------------------------------------------------
-- Toshiba TC8830F sample player/recorder
--@src/devices/sound/tc8830f.h,SOUNDS["TC8830F"] = true
---------------------------------------------------
if (SOUNDS["TC8830F"]~=null) then
files {
MAME_DIR .. "src/devices/sound/tc8830f.cpp",
MAME_DIR .. "src/devices/sound/tc8830f.h",
}
end
---------------------------------------------------
-- NEC uPD7752
--@src/devices/sound/upd7752.h,SOUNDS["UPD7752"] = true
---------------------------------------------------
if (SOUNDS["UPD7752"]~=null) then
files {
MAME_DIR .. "src/devices/sound/upd7752.cpp",
MAME_DIR .. "src/devices/sound/upd7752.h",
}
end
---------------------------------------------------
-- VLM5030 speech synthesizer
--@src/devices/sound/vlm5030.h,SOUNDS["VLM5030"] = true
---------------------------------------------------
if (SOUNDS["VLM5030"]~=null) then
files {
MAME_DIR .. "src/devices/sound/vlm5030.cpp",
MAME_DIR .. "src/devices/sound/vlm5030.h",
MAME_DIR .. "src/devices/sound/tms5110r.inc",
}
end
---------------------------------------------------
-- Votrax speech synthesizer
--@src/devices/sound/votrax.h,SOUNDS["VOTRAX"] = true
---------------------------------------------------
if (SOUNDS["VOTRAX"]~=null) then
files {
MAME_DIR .. "src/devices/sound/votrax.cpp",
MAME_DIR .. "src/devices/sound/votrax.h",
}
end
---------------------------------------------------
-- VRender0 custom sound chip
--@src/devices/sound/vrender0.h,SOUNDS["VRENDER0"] = true
---------------------------------------------------
if (SOUNDS["VRENDER0"]~=null) then
files {
MAME_DIR .. "src/devices/sound/vrender0.cpp",
MAME_DIR .. "src/devices/sound/vrender0.h",
}
end
---------------------------------------------------
-- WAVE file (used for MESS cassette)
--@src/devices/sound/wave.h,SOUNDS["WAVE"] = true
---------------------------------------------------
if (SOUNDS["WAVE"]~=null) then
files {
MAME_DIR .. "src/devices/sound/wave.cpp",
MAME_DIR .. "src/devices/sound/wave.h",
}
end
---------------------------------------------------
-- Yamaha FM synthesizers
--@src/devices/sound/2151intf.h,SOUNDS["YM2151"] = true
--@src/devices/sound/2203intf.h,SOUNDS["YM2203"] = true
--@src/devices/sound/2413intf.h,SOUNDS["YM2413"] = true
--@src/devices/sound/2608intf.h,SOUNDS["YM2608"] = true
--@src/devices/sound/2610intf.h,SOUNDS["YM2610"] = true
--@src/devices/sound/2612intf.h,SOUNDS["YM2612"] = true
--@src/devices/sound/3812intf.h,SOUNDS["YM3812"] = true
--@src/devices/sound/3526intf.h,SOUNDS["YM3526"] = true
--@src/devices/sound/8950intf.h,SOUNDS["Y8950"] = true
--@src/devices/sound/ymf262.h,SOUNDS["YMF262"] = true
--@src/devices/sound/ymf271.h,SOUNDS["YMF271"] = true
--@src/devices/sound/ymf278b.h,SOUNDS["YMF278B"] = true
--@src/devices/sound/262intf.h,SOUNDS["YMF262"] = true
---------------------------------------------------
if (SOUNDS["YM2151"]~=null) then
files {
MAME_DIR .. "src/devices/sound/2151intf.cpp",
MAME_DIR .. "src/devices/sound/2151intf.h",
MAME_DIR .. "src/devices/sound/ym2151.cpp",
MAME_DIR .. "src/devices/sound/ym2151.h",
}
end
if (SOUNDS["YM2413"]~=null) then
files {
MAME_DIR .. "src/devices/sound/2413intf.cpp",
MAME_DIR .. "src/devices/sound/2413intf.h",
MAME_DIR .. "src/devices/sound/ym2413.cpp",
MAME_DIR .. "src/devices/sound/ym2413.h",
}
end
if (SOUNDS["YM2203"]~=null or SOUNDS["YM2608"]~=null or SOUNDS["YM2610"]~=null or SOUNDS["YM2610B"]~=null or SOUNDS["YM2612"]~=null or SOUNDS["YM3438"]~=null) then
--if (SOUNDS["YM2203"]~=null) then
files {
MAME_DIR .. "src/devices/sound/2203intf.cpp",
MAME_DIR .. "src/devices/sound/2203intf.h",
MAME_DIR .. "src/devices/sound/ay8910.cpp",
MAME_DIR .. "src/devices/sound/ay8910.h",
MAME_DIR .. "src/devices/sound/fm.cpp",
MAME_DIR .. "src/devices/sound/fm.h",
}
--end
--if (SOUNDS["YM2608"]~=null) then
files {
MAME_DIR .. "src/devices/sound/2608intf.cpp",
MAME_DIR .. "src/devices/sound/2608intf.h",
MAME_DIR .. "src/devices/sound/ay8910.cpp",
MAME_DIR .. "src/devices/sound/ay8910.h",
MAME_DIR .. "src/devices/sound/fm.cpp",
MAME_DIR .. "src/devices/sound/fm.h",
MAME_DIR .. "src/devices/sound/ymdeltat.cpp",
MAME_DIR .. "src/devices/sound/ymdeltat.h",
}
--end
--if (SOUNDS["YM2610"]~=null or SOUNDS["YM2610B"]~=null) then
files {
MAME_DIR .. "src/devices/sound/2610intf.cpp",
MAME_DIR .. "src/devices/sound/2610intf.h",
MAME_DIR .. "src/devices/sound/ay8910.cpp",
MAME_DIR .. "src/devices/sound/ay8910.h",
MAME_DIR .. "src/devices/sound/fm.cpp",
MAME_DIR .. "src/devices/sound/fm.h",
MAME_DIR .. "src/devices/sound/ymdeltat.cpp",
MAME_DIR .. "src/devices/sound/ymdeltat.h",
}
--end
--if (SOUNDS["YM2612"]~=null or SOUNDS["YM3438"]~=null) then
files {
MAME_DIR .. "src/devices/sound/2612intf.cpp",
MAME_DIR .. "src/devices/sound/2612intf.h",
MAME_DIR .. "src/devices/sound/ay8910.cpp",
MAME_DIR .. "src/devices/sound/ay8910.h",
MAME_DIR .. "src/devices/sound/fm2612.cpp",
}
--end
end
if (SOUNDS["YM3812"]~=null or SOUNDS["YM3526"]~=null or SOUNDS["Y8950"]~=null) then
--if (SOUNDS["YM3812"]~=null) then
files {
MAME_DIR .. "src/devices/sound/3812intf.cpp",
MAME_DIR .. "src/devices/sound/3812intf.h",
MAME_DIR .. "src/devices/sound/fmopl.cpp",
MAME_DIR .. "src/devices/sound/fmopl.h",
MAME_DIR .. "src/devices/sound/ymdeltat.cpp",
MAME_DIR .. "src/devices/sound/ymdeltat.h",
}
--end
--if (SOUNDS["YM3526"]~=null) then
files {
MAME_DIR .. "src/devices/sound/3526intf.cpp",
MAME_DIR .. "src/devices/sound/3526intf.h",
MAME_DIR .. "src/devices/sound/fmopl.cpp",
MAME_DIR .. "src/devices/sound/fmopl.h",
MAME_DIR .. "src/devices/sound/ymdeltat.cpp",
MAME_DIR .. "src/devices/sound/ymdeltat.h",
}
--end
--if (SOUNDS["Y8950"]~=null) then
files {
MAME_DIR .. "src/devices/sound/8950intf.cpp",
MAME_DIR .. "src/devices/sound/8950intf.h",
MAME_DIR .. "src/devices/sound/fmopl.cpp",
MAME_DIR .. "src/devices/sound/fmopl.h",
MAME_DIR .. "src/devices/sound/ymdeltat.cpp",
MAME_DIR .. "src/devices/sound/ymdeltat.h",
}
--end
end
if (SOUNDS["YMF262"]~=null) then
files {
MAME_DIR .. "src/devices/sound/ymf262.cpp",
MAME_DIR .. "src/devices/sound/ymf262.h",
MAME_DIR .. "src/devices/sound/262intf.cpp",
MAME_DIR .. "src/devices/sound/262intf.h",
}
end
if (SOUNDS["YMF271"]~=null) then
files {
MAME_DIR .. "src/devices/sound/ymf271.cpp",
MAME_DIR .. "src/devices/sound/ymf271.h",
}
end
if (SOUNDS["YMF278B"]~=null) then
files {
MAME_DIR .. "src/devices/sound/ymf278b.cpp",
MAME_DIR .. "src/devices/sound/ymf278b.h",
}
end
---------------------------------------------------
-- Yamaha YMZ280B ADPCM
--@src/devices/sound/ymz280b.h,SOUNDS["YMZ280B"] = true
---------------------------------------------------
if (SOUNDS["YMZ280B"]~=null) then
files {
MAME_DIR .. "src/devices/sound/ymz280b.cpp",
MAME_DIR .. "src/devices/sound/ymz280b.h",
}
end
---------------------------------------------------
-- Yamaha YMZ770 AMM
--@src/devices/sound/ymz770.h,SOUNDS["YMZ770"] = true
---------------------------------------------------
if (SOUNDS["YMZ770"]~=null) then
files {
MAME_DIR .. "src/devices/sound/ymz770.cpp",
MAME_DIR .. "src/devices/sound/ymz770.h",
}
end
---------------------------------------------------
-- MPEG AUDIO
--@src/devices/sound/mpeg_audio.h,SOUNDS["MPEG_AUDIO"] = true
---------------------------------------------------
if (SOUNDS["MPEG_AUDIO"]~=null) then
files {
MAME_DIR .. "src/devices/sound/mpeg_audio.cpp",
MAME_DIR .. "src/devices/sound/mpeg_audio.h",
}
end
---------------------------------------------------
-- ZOOM ZSG-2
--@src/devices/sound/zsg2.h,SOUNDS["ZSG2"] = true
---------------------------------------------------
if (SOUNDS["ZSG2"]~=null) then
files {
MAME_DIR .. "src/devices/sound/zsg2.cpp",
MAME_DIR .. "src/devices/sound/zsg2.h",
}
end
---------------------------------------------------
-- VRC6
--@src/devices/sound/vrc6.h,SOUNDS["VRC6"] = true
---------------------------------------------------
if (SOUNDS["VRC6"]~=null) then
files {
MAME_DIR .. "src/devices/sound/vrc6.cpp",
MAME_DIR .. "src/devices/sound/vrc6.h",
}
end
---------------------------------------------------
-- AD1848
--@src/devices/sound/ad1848.h,SOUNDS["AD1848"] = true
---------------------------------------------------
if (SOUNDS["AD1848"]~=null) then
files {
MAME_DIR .. "src/devices/sound/ad1848.cpp",
MAME_DIR .. "src/devices/sound/ad1848.h",
}
end
| gpl-2.0 |
Colettechan/darkstar | scripts/zones/Arrapago_Reef/npcs/qm1.lua | 30 | 1331 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: ??? (Spawn Lil'Apkallu(ZNM T1))
-- @pos 488 -1 166 54
-----------------------------------
package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Arrapago_Reef/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local mobID = 16998871;
if (trade:hasItemQty(2601,1) and trade:getItemCount() == 1) then -- Trade Greenling
if (GetMobAction(mobID) == ACTION_NONE) then
player:tradeComplete();
SpawnMob(mobID):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
PhearZero/phear-scanner | bin/nmap-openshift/nselib/rsync.lua | 8 | 5267 | ---
-- A minimalist RSYNC (remote file sync) library
--
-- @author "Patrik Karlsson <patrik@cqure.net>"
local base64 = require "base64"
local bin = require "bin"
local match = require "match"
local nmap = require "nmap"
local stdnse = require "stdnse"
local table = require "table"
local openssl = stdnse.silent_require "openssl"
_ENV = stdnse.module("rsync", stdnse.seeall)
-- The Helper class serves as the main interface for script writers
Helper = {
-- Creates a new instance of the Helper class
-- @param host table as received by the action function
-- @param port table as received by the action function
-- @param options table containing any additional options
-- @return o instance of Helper
new = function(self, host, port, options)
local o = { host = host, port = port, options = options or {} }
assert(o.options.module, "No rsync module was specified, aborting ...")
setmetatable(o, self)
self.__index = self
return o
end,
-- Handles send and receive of control messages
-- @param data string containing the command to send
-- @return status true on success, false on failure
-- @return data containing the response from the server
-- err string, if status is false
ctrl_exch = function(self, data)
local status, err = self.socket:send(data.."\n")
if ( not(status) ) then
return false, err
end
local status, data = self.socket:receive_buf("\n", false)
if( not(status) ) then
return false, err
end
return true, data
end,
-- Connects to the rsync server
-- @return status, true on success, false on failure
-- @return err string containing an error message if status is false
connect = function(self)
self.socket = nmap.new_socket()
self.socket:set_timeout(self.options.timeout or 5000)
local status, err = self.socket:connect(self.host, self.port)
if ( not(status) ) then
return false, err
end
local data
status, data = self:ctrl_exch("@RSYNCD: 29")
if ( not(status) ) then
return false, data
end
if ( not(data:match("^@RSYNCD: [%.%d]+$")) ) then
return false, "Protocol error"
end
return true
end,
-- Authenticates against the rsync module. If no username is given, assume
-- no authentication is required.
-- @param username [optional] string containing the username
-- @param password [optional] string containing the password
login = function(self, username, password)
password = password or ""
local status, data = self:ctrl_exch(self.options.module)
if (not(status)) then
return false, data
end
local chall
if ( data:match("@RSYNCD: OK") ) then
return true, "No authentication was required"
else
chall = data:match("^@RSYNCD: AUTHREQD (.*)$")
if ( not(chall) and data:match("^@ERROR: Unknown module") ) then
return false, data:match("^@ERROR: (.*)$")
elseif ( not(chall) ) then
return false, "Failed to retrieve challenge"
end
end
if ( chall and not(username) ) then
return false, "Authentication required"
end
local md4 = openssl.md4("\0\0\0\0" .. password .. chall)
local resp = base64.enc(md4):sub(1,-3)
status, data = self:ctrl_exch(username .. " " .. resp)
if (not(status)) then
return false, data
end
if ( data == "@RSYNCD: OK" ) then
return true, "Authentication successful"
end
return false, "Authentication failed"
end,
-- Lists accessible modules from the rsync server
-- @return status true on success, false on failure
-- @return modules table containing a list of modules
listModules = function(self)
local status, data = self.socket:send("\n")
if (not(status)) then
return false, data
end
local modules = {}
while(true) do
status, data = self.socket:receive_buf("\n", false)
if (not(status)) then
return false, data
end
if ( data == "@RSYNCD: EXIT" ) then
break
else
table.insert(modules, data)
end
end
return true, modules
end,
-- Lists the files available for the directory/module
-- TODO: Add support for parsing results, seemed straight forward at
-- first, but wasn't.
listFiles = function(self)
-- list recursively and enable MD4 checksums
local data = ("--server\n--sender\n-rc\n.\n%s\n\n"):format(self.options.module)
local status, data = self.socket:send(data)
if ( not(status) ) then
return false, data
end
status, data = self.socket:receive_bytes(4)
if ( not(status) ) then
return false, data
end
status, data = self.socket:send("\0\0\0\0")
if ( not(status) ) then
return false, data
end
status, data = self.socket:receive_buf(match.numbytes(4), false)
if ( not(status) ) then
return false, data
end
local pos, len = bin.unpack("<S", data)
status, data = self.socket:receive_buf(match.numbytes(len), false)
if ( not(status) ) then
return false, data
end
-- Parsing goes here
end,
-- Disconnects from the rsync server
-- @return status true on success, false on failure
disconnect = function(self) return self.socket:close() end,
}
return _ENV;
| mit |
pedja1/aNmap | dSploit/jni/nmap/nselib/rsync.lua | 8 | 5267 | ---
-- A minimalist RSYNC (remote file sync) library
--
-- @author "Patrik Karlsson <patrik@cqure.net>"
local base64 = require "base64"
local bin = require "bin"
local match = require "match"
local nmap = require "nmap"
local stdnse = require "stdnse"
local table = require "table"
local openssl = stdnse.silent_require "openssl"
_ENV = stdnse.module("rsync", stdnse.seeall)
-- The Helper class serves as the main interface for script writers
Helper = {
-- Creates a new instance of the Helper class
-- @param host table as received by the action function
-- @param port table as received by the action function
-- @param options table containing any additional options
-- @return o instance of Helper
new = function(self, host, port, options)
local o = { host = host, port = port, options = options or {} }
assert(o.options.module, "No rsync module was specified, aborting ...")
setmetatable(o, self)
self.__index = self
return o
end,
-- Handles send and receive of control messages
-- @param data string containing the command to send
-- @return status true on success, false on failure
-- @return data containing the response from the server
-- err string, if status is false
ctrl_exch = function(self, data)
local status, err = self.socket:send(data.."\n")
if ( not(status) ) then
return false, err
end
local status, data = self.socket:receive_buf("\n", false)
if( not(status) ) then
return false, err
end
return true, data
end,
-- Connects to the rsync server
-- @return status, true on success, false on failure
-- @return err string containing an error message if status is false
connect = function(self)
self.socket = nmap.new_socket()
self.socket:set_timeout(self.options.timeout or 5000)
local status, err = self.socket:connect(self.host, self.port)
if ( not(status) ) then
return false, err
end
local data
status, data = self:ctrl_exch("@RSYNCD: 29")
if ( not(status) ) then
return false, data
end
if ( not(data:match("^@RSYNCD: [%.%d]+$")) ) then
return false, "Protocol error"
end
return true
end,
-- Authenticates against the rsync module. If no username is given, assume
-- no authentication is required.
-- @param username [optional] string containing the username
-- @param password [optional] string containing the password
login = function(self, username, password)
password = password or ""
local status, data = self:ctrl_exch(self.options.module)
if (not(status)) then
return false, data
end
local chall
if ( data:match("@RSYNCD: OK") ) then
return true, "No authentication was required"
else
chall = data:match("^@RSYNCD: AUTHREQD (.*)$")
if ( not(chall) and data:match("^@ERROR: Unknown module") ) then
return false, data:match("^@ERROR: (.*)$")
elseif ( not(chall) ) then
return false, "Failed to retrieve challenge"
end
end
if ( chall and not(username) ) then
return false, "Authentication required"
end
local md4 = openssl.md4("\0\0\0\0" .. password .. chall)
local resp = base64.enc(md4):sub(1,-3)
status, data = self:ctrl_exch(username .. " " .. resp)
if (not(status)) then
return false, data
end
if ( data == "@RSYNCD: OK" ) then
return true, "Authentication successful"
end
return false, "Authentication failed"
end,
-- Lists accessible modules from the rsync server
-- @return status true on success, false on failure
-- @return modules table containing a list of modules
listModules = function(self)
local status, data = self.socket:send("\n")
if (not(status)) then
return false, data
end
local modules = {}
while(true) do
status, data = self.socket:receive_buf("\n", false)
if (not(status)) then
return false, data
end
if ( data == "@RSYNCD: EXIT" ) then
break
else
table.insert(modules, data)
end
end
return true, modules
end,
-- Lists the files available for the directory/module
-- TODO: Add support for parsing results, seemed straight forward at
-- first, but wasn't.
listFiles = function(self)
-- list recursively and enable MD4 checksums
local data = ("--server\n--sender\n-rc\n.\n%s\n\n"):format(self.options.module)
local status, data = self.socket:send(data)
if ( not(status) ) then
return false, data
end
status, data = self.socket:receive_bytes(4)
if ( not(status) ) then
return false, data
end
status, data = self.socket:send("\0\0\0\0")
if ( not(status) ) then
return false, data
end
status, data = self.socket:receive_buf(match.numbytes(4), false)
if ( not(status) ) then
return false, data
end
local pos, len = bin.unpack("<S", data)
status, data = self.socket:receive_buf(match.numbytes(len), false)
if ( not(status) ) then
return false, data
end
-- Parsing goes here
end,
-- Disconnects from the rsync server
-- @return status true on success, false on failure
disconnect = function(self) return self.socket:close() end,
}
return _ENV;
| gpl-3.0 |
zynjec/darkstar | scripts/zones/Bastok_Mines/npcs/Sieglinde.lua | 12 | 1207 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Sieglinde
-- Alchemy Synthesis Image Support
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
local ID = require("scripts/zones/Bastok_Mines/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local guildMember = isGuildMember(player,1);
local SkillCap = getCraftSkillCap(player,dsp.skill.SMITHING);
local SkillLevel = player:getSkillLevel(dsp.skill.SMITHING);
if (guildMember == 1) then
if (player:hasStatusEffect(dsp.effect.ALCHEMY_IMAGERY) == false) then
player:startEvent(124,SkillCap,SkillLevel,2,201,player:getGil(),0,4095,0);
else
player:startEvent(124,SkillCap,SkillLevel,2,201,player:getGil(),7009,4095,0);
end
else
player:startEvent(124);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 124 and option == 1) then
player:messageSpecial(ID.text.ALCHEMY_SUPPORT,0,7,2);
player:addStatusEffect(dsp.effect.ALCHEMY_IMAGERY,1,0,120);
end
end; | gpl-3.0 |
Joker-development/Joker_development | plugins/ar-boomzain.lua | 6 | 2218 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY jOker ▀▄ ▄▀
▀▄ ▄▀ BY joker (@fuck_8_you) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY joker ▀▄ ▄▀
▀▄ ▄▀ broadcast : كلمه ضد الجيوش ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
-- only enable one of them
local Kick = true;
local Warn = false;
do
local function run(msg, matches)
if ( kick == true ) then
Warn = false;
elseif ( Warn == true ) then
Kick = false;
end
-- check if the user is owner
if ( is_realm(msg) and is_admin(msg)or is_sudo(msg) or is_momod(msg) ) then
-- if he is a owner then exit out of the code
return
end
-- load the data
local data = load_data(_config.moderation.data)
-- get the receiver and set the variable chat to it
local chat = get_receiver(msg)
-- get the sender id and set the variable user to it
local user = "user#id"..msg.from.id
-- check if the data 'LockFuck' from the table 'settings' is "yes"
if ( data[tostring(msg.to.id)]['settings']['LockFuck'] == "yes" ) then
-- send a message
send_large_msg(chat, "ممنوع التكلم عن الجيوش هنا☹️🖐🏻")
-- kick the user who sent the message
if ( Kick == true ) then
chat_del_user(chat, user, ok_cb, true)
elseif ( Warn == true ) then
send_large_msg( get_receiver(msg), "ممنوع ❌ التكلم عن الجيوش هنا 😪🖐🏻 @" .. msg.from.username )
end
end
end
return {
patterns = {
"AHK",
"TNT",
"TIQ",
"tut",
"vip",
"جيش",
"الهلاك",
"تي اي كيو",
"تكساس",
"في اي بي",
"تي ان تي",
"افلش",
"تفليش",
},
run = run
}
end | gpl-2.0 |
hedgewars/hw | share/hedgewars/Data/Missions/Scenario/User_Mission_-_Teamwork_2.lua | 1 | 3409 | -- Teamwork 2
-- Original scenario by Arkhnen
HedgewarsScriptLoad("Scripts/Locale.lua")
local player = nil
local hlayer = nil
local enemy = nil
local Pack = nil
local help = false
local GameOver = false
local playerTeamName
function onGameInit()
Seed = 0
GameFlags = gfDisableWind
TurnTime = MAX_TURN_TIME
CaseFreq = 0
MinesNum = 0
MinesTime = 0
-- Disable Sudden Death
HealthDecrease = 0
WaterRise = 0
Explosives = 0
Map = "CrazyMission"
Theme = "CrazyMission"
playerTeamName = AddMissionTeam(-1)
player = AddMissionHog(30)
hlayer = AddMissionHog(40)
AddTeam(loc("Cybernetic Empire"), -6, "ring", "Island", "Robot_qau", "cm_binary")
enemy = AddHog(loc("WatchBot 4000"), 5, 50, "cyborg1")
SetGearPosition(player, 180, 555)
SetGearPosition(enemy, 1500, 914)
SetGearPosition(hlayer, 333, 555)
end
function onGameStart()
Pack = SpawnSupplyCrate(40, 888, amPickHammer)
SpawnSupplyCrate(90, 888, amBaseballBat)
SpawnSupplyCrate(822, 750, amBlowTorch)
SpawnSupplyCrate(700, 580, amJetpack)
SpawnSupplyCrate(1400, 425, amParachute)
SpawnSupplyCrate(1900, 770, amDynamite)
SpawnSupplyCrate(1794, 970, amDynamite)
ShowMission(loc("Teamwork 2"), loc("Scenario"), loc("Eliminate WatchBot 4000.") .. "|" .. loc("Both your hedgehogs must survive.") .. "|" .. loc("Land mines explode instantly."), -amBaseballBat, 0)
AddGear(355, 822, gtSMine, 0, 0, 0, 0)
AddGear(515, 525, gtSMine, 0, 0, 0, 0)
AddGear(1080, 821, gtMine, 0, 0, 0, 0)
AddGear(1055, 821, gtMine, 0, 0, 0, 0)
AddGear(930, 587, gtMine, 0, 0, 0, 0)
AddGear(955, 556, gtMine, 0, 0, 0, 0)
AddGear(980, 556, gtMine, 0, 0, 0, 0)
AddGear(1005, 556, gtMine, 0, 0, 0, 0)
AddGear(710, 790, gtMine, 0, 0, 0, 0)
AddGear(685, 790, gtMine, 0, 0, 0, 0)
AddGear(660, 790, gtMine, 0, 0, 0, 0)
AddGear(1560, 540, gtMine, 0, 0, 0, 0)
AddGear(1610, 600, gtMine, 0, 0, 0, 0)
AddGear(1660, 655, gtMine, 0, 0, 0, 0)
AddGear(713, 707, gtMine, 0, 0, 0, 0)
AddGear(1668, 969, gtExplosives, 0, 0, 0, 0)
AddGear(1668, 906, gtExplosives, 0, 0, 0, 0)
AddGear(1668, 842, gtExplosives, 0, 0, 0, 0)
AddGear(1713, 969, gtExplosives, 0, 0, 0, 0)
SetWind(90)
-- The enemy has no weapons and can only skip
for i=0, AmmoTypeMax do
if i ~= amNothing and i ~= amSkip then
AddAmmo(enemy, i, 0)
end
end
end
function onGearAdd(gear)
if GetGearType(gear) == gtJetpack then
SetHealth(gear, 300)
end
end
function onAmmoStoreInit()
SetAmmo(amParachute, 1, 0, 0, 2)
SetAmmo(amSwitch, 9, 0, 0, 0)
SetAmmo(amSkip, 9, 0, 0, 0)
SetAmmo(amPickHammer, 0, 0, 0, 1)
SetAmmo(amBaseballBat, 0, 0, 0, 1)
SetAmmo(amBlowTorch, 0, 0, 0, 2)
SetAmmo(amJetpack, 0, 0, 0, 1)
SetAmmo(amDynamite, 0, 0, 0, 1)
end
function onGearDelete(gear)
if gear == Pack then
HogSay(CurrentHedgehog, loc("This will certainly come in handy."), SAY_THINK)
end
-- Note: The victory sequence is done automatically by Hedgewars
if ( ((gear == player) or (gear == hlayer)) and (GameOver == false)) then
GameOver = true
SetHealth(hlayer, 0)
SetHealth(player, 0)
end
end
function onGameResult(winner)
if winner == GetTeamClan(playerTeamName) then
SaveMissionVar("Won", "true")
SendStat(siGameResult, loc("Mission succeeded!"))
GameOver = true
else
SendStat(siGameResult, loc("Mission failed!"))
GameOver = true
end
end
| gpl-2.0 |
Colettechan/darkstar | scripts/zones/Mount_Zhayolm/mobs/Brass_Borer.lua | 29 | 1544 | -----------------------------------
-- Area: Mount Zhayolm
-- MOB: Brass Borer
-----------------------------------
require("scripts/globals/status");
-- TODO: Damage resistances in streched and curled stances. Halting movement during stance change.
-----------------------------------
-- OnMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("formTime", os.time() + math.random(43,47));
end;
-----------------------------------
-- onMobRoam Action
-- Autochange stance
-----------------------------------
function onMobRoam(mob)
local roamTime = mob:getLocalVar("formTime");
if (mob:AnimationSub() == 0 and os.time() > roamTime) then
mob:AnimationSub(1);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
elseif (mob:AnimationSub() == 1 and os.time() > roamTime) then
mob:AnimationSub(0);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
end
end;
-----------------------------------
-- OnMobFight Action
-- Stance change in battle
-----------------------------------
function onMobFight(mob,target)
local fightTime = mob:getLocalVar("formTime");
if (mob:AnimationSub() == 0 and os.time() > fightTime) then
mob:AnimationSub(1);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
elseif (mob:AnimationSub() == 1 and os.time() > fightTime) then
mob:AnimationSub(0);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
end
end;
function onMobDeath(mob)
end; | gpl-3.0 |
zynjec/darkstar | scripts/zones/Port_Windurst/npcs/Erabu-Fumulubu.lua | 12 | 1300 | -----------------------------------
-- Area: Port Windurst
-- NPC: Erabu-Fumulubu
-- Type: Fishing Synthesis Image Support
-- !pos -178.900 -2.789 76.200 240
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
local ID = require("scripts/zones/Port_Windurst/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local guildMember = isGuildMember(player,5);
local SkillCap = getCraftSkillCap(player,dsp.skill.FISHING);
local SkillLevel = player:getSkillLevel(dsp.skill.FISHING);
if (guildMember == 1) then
if (player:hasStatusEffect(dsp.effect.FISHING_IMAGERY) == false) then
player:startEvent(10012,SkillCap,SkillLevel,1,239,player:getGil(),0,0,0); -- p1 = skill level
else
player:startEvent(10012,SkillCap,SkillLevel,1,239,player:getGil(),19194,4031,0);
end
else
player:startEvent(10012); -- Standard Dialogue
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 10012 and option == 1) then
player:messageSpecial(ID.text.FISHING_SUPPORT,0,0,1);
player:addStatusEffect(dsp.effect.FISHING_IMAGERY,1,0,3600);
end
end; | gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/East_Ronfaure/npcs/Logging_Point.lua | 17 | 1085 | -----------------------------------
-- Area: East Ronfaure
-- NPC: Logging Point
-----------------------------------
package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/logging");
require("scripts/zones/East_Ronfaure/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startLogging(player,player:getZoneID(),npc,trade,0x0385);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Colettechan/darkstar | scripts/zones/Caedarva_Mire/npcs/Nuimahn.lua | 13 | 1386 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: Nuimahn
-- Type: Alzadaal Undersea Ruins
-- @pos -380 0 -381 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then
player:tradeComplete();
player:startEvent(0x00cb);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getZPos() < -281) then
player:startEvent(0x00cc); -- leaving
else
player:startEvent(0x00ca); -- entering
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00cb) then
player:setPos(-515,-6.5,740,0,72);
end
end; | gpl-3.0 |
Colettechan/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Mikhe_Aryohcha.lua | 13 | 1139 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Mikhe Aryohcha
-- Type: Standard NPC
-- @zone: 94
-- @pos -56.645 -4.5 13.014
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, MIKHE_ARYOHCHA_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
zynjec/darkstar | scripts/zones/Castle_Zvahl_Baileys/IDs.lua | 9 | 1725 | -----------------------------------
-- Area: Castle_Zvahl_Baileys
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.CASTLE_ZVAHL_BAILEYS] =
{
text =
{
CONQUEST_BASE = 0, -- Tallying conquest results...
ITEM_CANNOT_BE_OBTAINED = 6541, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6547, -- Obtained: <item>.
GIL_OBTAINED = 6548, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6550, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6561, -- There is nothing out of the ordinary here.
SENSE_OF_FOREBODING = 6562, -- You are suddenly overcome with a sense of foreboding...
CHEST_UNLOCKED = 7223, -- You unlock the chest!
COMMON_SENSE_SURVIVAL = 7598, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
MARQUIS_SABNOCK_PH =
{
[17436879] = 17436881,
[17436882] = 17436881,
},
LIKHO = 17436714,
MARQUIS_ALLOCEN = 17436913,
MARQUIS_AMON = 17436918,
DUKE_HABORYM = 17436923,
GRAND_DUKE_BATYM = 17436927,
DARK_SPARK = 17436964,
MIMIC = 17436965,
},
npc =
{
TORCH_OFFSET = 17436984,
TREASURE_CHEST = 17436997,
TREASURE_COFFER = 17436998,
},
}
return zones[dsp.zone.CASTLE_ZVAHL_BAILEYS] | gpl-3.0 |
zynjec/darkstar | scripts/globals/weaponskills/blade_ei.lua | 10 | 1231 | -----------------------------------
-- Blade Ei
-- Katana weapon skill
-- Skill Level: 175
-- Delivers a dark elemental attack. Damage varies with TP.
-- Aligned with the Shadow Gorget.
-- Aligned with the Shadow Belt.
-- Element: Dark
-- Modifiers: STR:30% INT:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.50 2.00
-----------------------------------
require("scripts/globals/magic")
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.ftp100 = 1 params.ftp200 = 1.5 params.ftp300 = 2
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.3 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.ele = dsp.magic.ele.DARK
params.skill = dsp.skill.KATANA
params.includemab = true
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4 params.int_wsc = 0.4
end
local damage, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, action, primary)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
runswithd6s/awesome-configs | rc.lua | 1 | 13849 | -- Standard awesome library
require("awful")
require("awful.autofocus")
require("awful.rules")
-- Theme handling library
require("beautiful")
-- Notification library
require("naughty")
-- Load Debian menu entries
require("debian.menu")
-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, there were errors during startup!",
text = awesome.startup_errors })
end
-- Handle runtime errors after startup
do
local in_error = false
awesome.add_signal("debug::error", function (err)
-- Make sure we don't go into an endless error loop
if in_error then return end
in_error = true
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, an error happened!",
text = err })
in_error = false
end)
end
-- }}}
-- Custom Libraries
--require("autostart")
--require("runonce")
require("volume")
require("battery")
-- {{{ Variable definitions
-- Themes define colours, icons, and wallpapers
beautiful.init("/usr/share/awesome/themes/default/theme.lua")
-- This is used later as the default terminal and editor to run.
--terminal = "x-terminal-emulator"
terminal = "urxvtc"
editor = os.getenv("EDITOR") or "editor"
editor_cmd = terminal .. " -e " .. editor
-- Default modkey.
-- Usually, Mod4 is the key with a logo between Control and Alt.
-- If you do not like this or do not have such a key,
-- I suggest you to remap Mod4 to another key using xmodmap or other tools.
-- However, you can use another modifier like Mod1, but it may interact with others.
modkey = "Mod4"
-- Table of layouts to cover with awful.layout.inc, order matters.
layouts =
{
awful.layout.suit.floating,
awful.layout.suit.tile,
awful.layout.suit.tile.left,
awful.layout.suit.tile.bottom,
awful.layout.suit.tile.top,
awful.layout.suit.fair,
awful.layout.suit.fair.horizontal,
awful.layout.suit.spiral,
awful.layout.suit.spiral.dwindle,
awful.layout.suit.max,
awful.layout.suit.max.fullscreen,
awful.layout.suit.magnifier
}
-- }}}
-- {{{ Tags
-- Define a tag table which hold all screen tags.
tags = {}
for s = 1, screen.count() do
-- Each screen has its own tag table.
tags[s] = awful.tag({ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, s, layouts[1])
end
-- }}}
-- {{{ Menu
-- Create a laucher widget and a main menu
myawesomemenu = {
{ "manual", terminal .. " -e man awesome" },
{ "edit config", editor_cmd .. " " .. awesome.conffile },
{ "restart", awesome.restart },
{ "quit", awesome.quit }
}
mymainmenu = awful.menu({ items = { { "awesome", myawesomemenu, beautiful.awesome_icon },
{ "Debian", debian.menu.Debian_menu.Debian },
{ "open terminal", terminal }
}
})
mylauncher = awful.widget.launcher({ image = image(beautiful.awesome_icon),
menu = mymainmenu })
-- }}}
-- {{{ Wibox
-- Create a textclock widget
mytextclock = awful.widget.textclock({ align = "right" })
-- Battery
batterywidget = widget({type = "textbox", name = "batterywidget", align = "right" })
bat_clo = battery.batclosure("BAT0")
batterywidget.text = bat_clo()
battimer = timer({ timeout = 30 })
battimer:add_signal("timeout", function() batterywidget.text = bat_clo() end)
battimer:start()
-- Create a systray
mysystray = widget({ type = "systray" })
-- Create a wibox for each screen and add it
mywibox = {}
mypromptbox = {}
mylayoutbox = {}
mytaglist = {}
mytaglist.buttons = awful.util.table.join(
awful.button({ }, 1, awful.tag.viewonly),
awful.button({ modkey }, 1, awful.client.movetotag),
awful.button({ }, 3, awful.tag.viewtoggle),
awful.button({ modkey }, 3, awful.client.toggletag),
awful.button({ }, 4, awful.tag.viewnext),
awful.button({ }, 5, awful.tag.viewprev)
)
mytasklist = {}
mytasklist.buttons = awful.util.table.join(
awful.button({ }, 1, function (c)
if c == client.focus then
c.minimized = true
else
if not c:isvisible() then
awful.tag.viewonly(c:tags()[1])
end
-- This will also un-minimize
-- the client, if needed
client.focus = c
c:raise()
end
end),
awful.button({ }, 3, function ()
if instance then
instance:hide()
instance = nil
else
instance = awful.menu.clients({ width=250 })
end
end),
awful.button({ }, 4, function ()
awful.client.focus.byidx(1)
if client.focus then client.focus:raise() end
end),
awful.button({ }, 5, function ()
awful.client.focus.byidx(-1)
if client.focus then client.focus:raise() end
end))
for s = 1, screen.count() do
-- Create a promptbox for each screen
mypromptbox[s] = awful.widget.prompt({ layout = awful.widget.layout.horizontal.leftright })
-- Create an imagebox widget which will contains an icon indicating which layout we're using.
-- We need one layoutbox per screen.
mylayoutbox[s] = awful.widget.layoutbox(s)
mylayoutbox[s]:buttons(awful.util.table.join(
awful.button({ }, 1, function () awful.layout.inc(layouts, 1) end),
awful.button({ }, 3, function () awful.layout.inc(layouts, -1) end),
awful.button({ }, 4, function () awful.layout.inc(layouts, 1) end),
awful.button({ }, 5, function () awful.layout.inc(layouts, -1) end)))
-- Create a taglist widget
mytaglist[s] = awful.widget.taglist(s, awful.widget.taglist.label.all, mytaglist.buttons)
-- Create a tasklist widget
mytasklist[s] = awful.widget.tasklist(function(c)
return awful.widget.tasklist.label.currenttags(c, s)
end, mytasklist.buttons)
-- Create the wibox
mywibox[s] = awful.wibox({ position = "top", screen = s })
-- Add widgets to the wibox - order matters
mywibox[s].widgets = {
{
mylauncher,
mytaglist[s],
mypromptbox[s],
layout = awful.widget.layout.horizontal.leftright
},
mylayoutbox[s],
mytextclock,
batterywidget,
volume_widget,
s == 1 and mysystray or nil,
mytasklist[s],
layout = awful.widget.layout.horizontal.rightleft
}
end
-- }}}
-- {{{ Mouse bindings
root.buttons(awful.util.table.join(
awful.button({ }, 3, function () mymainmenu:toggle() end),
awful.button({ }, 4, awful.tag.viewnext),
awful.button({ }, 5, awful.tag.viewprev)
))
-- }}}
-- {{{ Key bindings
globalkeys = awful.util.table.join(
awful.key({ modkey, }, "Left", awful.tag.viewprev ),
awful.key({ modkey, }, "Right", awful.tag.viewnext ),
awful.key({ modkey, }, "Escape", awful.tag.history.restore),
awful.key({ modkey, }, "j",
function ()
awful.client.focus.byidx( 1)
if client.focus then client.focus:raise() end
end),
awful.key({ modkey, }, "k",
function ()
awful.client.focus.byidx(-1)
if client.focus then client.focus:raise() end
end),
awful.key({ modkey, }, "w", function () mymainmenu:show({keygrabber=true}) end),
-- Layout manipulation
awful.key({ modkey, "Shift" }, "j", function () awful.client.swap.byidx( 1) end),
awful.key({ modkey, "Shift" }, "k", function () awful.client.swap.byidx( -1) end),
awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end),
awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end),
awful.key({ modkey, }, "u", awful.client.urgent.jumpto),
awful.key({ modkey, }, "Tab",
function ()
awful.client.focus.history.previous()
if client.focus then
client.focus:raise()
end
end),
-- Standard program
awful.key({ modkey, }, "Return", function () awful.util.spawn(terminal) end),
awful.key({ modkey, "Control" }, "r", awesome.restart),
awful.key({ modkey, "Shift" }, "q", awesome.quit),
awful.key({ modkey, }, "l", function () awful.tag.incmwfact( 0.05) end),
awful.key({ modkey, }, "h", function () awful.tag.incmwfact(-0.05) end),
awful.key({ modkey, "Shift" }, "h", function () awful.tag.incnmaster( 1) end),
awful.key({ modkey, "Shift" }, "l", function () awful.tag.incnmaster(-1) end),
awful.key({ modkey, "Control" }, "h", function () awful.tag.incncol( 1) end),
awful.key({ modkey, "Control" }, "l", function () awful.tag.incncol(-1) end),
awful.key({ modkey, }, "space", function () awful.layout.inc(layouts, 1) end),
awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(layouts, -1) end),
awful.key({ modkey, "Control" }, "n", awful.client.restore),
-- Prompt
awful.key({ modkey }, "r", function () mypromptbox[mouse.screen]:run() end),
awful.key({ modkey }, "x",
function ()
awful.prompt.run({ prompt = "Run Lua code: " },
mypromptbox[mouse.screen].widget,
awful.util.eval, nil,
awful.util.getdir("cache") .. "/history_eval")
end),
-- Volume Keys (see ~/.config/awesome/volume.lua)
volume_up,
volume_down,
volume_mute,
-- Brightness
awful.key({ }, "XF86MonBrightnessDown", function () awful.util.spawn("xbacklight -dec 15") end),
awful.key({ }, "XF86MonBrightnessUp", function () awful.util.spawn("xbacklight -inc 15") end)
)
clientkeys = awful.util.table.join(
awful.key({ modkey, }, "f", function (c) c.fullscreen = not c.fullscreen end),
awful.key({ modkey, "Shift" }, "c", function (c) c:kill() end),
awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle ),
awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end),
awful.key({ modkey, }, "o", awful.client.movetoscreen ),
awful.key({ modkey, "Shift" }, "r", function (c) c:redraw() end),
awful.key({ modkey, }, "t", function (c) c.ontop = not c.ontop end),
awful.key({ modkey, }, "n",
function (c)
-- The client currently has the input focus, so it cannot be
-- minimized, since minimized clients can't have the focus.
c.minimized = true
end),
awful.key({ modkey, }, "m",
function (c)
c.maximized_horizontal = not c.maximized_horizontal
c.maximized_vertical = not c.maximized_vertical
end)
)
-- Compute the maximum number of digit we need, limited to 9
keynumber = 0
for s = 1, screen.count() do
keynumber = math.min(9, math.max(#tags[s], keynumber));
end
-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it works on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, keynumber do
globalkeys = awful.util.table.join(globalkeys,
awful.key({ modkey }, "#" .. i + 9,
function ()
local screen = mouse.screen
if tags[screen][i] then
awful.tag.viewonly(tags[screen][i])
end
end),
awful.key({ modkey, "Control" }, "#" .. i + 9,
function ()
local screen = mouse.screen
if tags[screen][i] then
awful.tag.viewtoggle(tags[screen][i])
end
end),
awful.key({ modkey, "Shift" }, "#" .. i + 9,
function ()
if client.focus and tags[client.focus.screen][i] then
awful.client.movetotag(tags[client.focus.screen][i])
end
end),
awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
function ()
if client.focus and tags[client.focus.screen][i] then
awful.client.toggletag(tags[client.focus.screen][i])
end
end))
end
clientbuttons = awful.util.table.join(
awful.button({ }, 1, function (c) client.focus = c; c:raise() end),
awful.button({ modkey }, 1, awful.mouse.client.move),
awful.button({ modkey }, 3, awful.mouse.client.resize))
-- Set keys
root.keys(globalkeys)
-- }}}
-- {{{ Rules
awful.rules.rules = {
-- All clients will match this rule.
{ rule = { },
properties = { border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = true,
keys = clientkeys,
buttons = clientbuttons } },
{ rule = { class = "MPlayer" },
properties = { floating = true } },
{ rule = { class = "pinentry" },
properties = { floating = true } },
{ rule = { class = "gimp" },
properties = { floating = true } },
-- Set Firefox to always map on tags number 2 of screen 1.
-- { rule = { class = "Firefox" },
-- properties = { tag = tags[1][2] } },
}
-- }}}
-- {{{ Signals
-- Signal function to execute when a new client appears.
client.add_signal("manage", function (c, startup)
-- Add a titlebar
-- awful.titlebar.add(c, { modkey = modkey })
-- Enable sloppy focus
c:add_signal("mouse::enter", function(c)
if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
and awful.client.focus.filter(c) then
client.focus = c
end
end)
if not startup then
-- Set the windows at the slave,
-- i.e. put it at the end of others instead of setting it master.
-- awful.client.setslave(c)
-- Put windows in a smart way, only if they does not set an initial position.
if not c.size_hints.user_position and not c.size_hints.program_position then
awful.placement.no_overlap(c)
awful.placement.no_offscreen(c)
end
end
end)
client.add_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.add_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- }}}
| gpl-3.0 |
PhearZero/phear-scanner | bin/nmap-openshift/nselib/data/psexec/drives.lua | 8 | 1334 | ---This configuration file pulls info about a given harddrive
-- Any variable in the 'config' table in smb-psexec.nse can be overriden in the
-- 'overrides' table. Most of them are not really recommended, such as the host,
-- key, etc.
overrides = {}
--overrides.timeout = 40
modules = {}
local mod
mod = {}
mod.upload = false
mod.name = "Drive type"
mod.program = "fsutil"
mod.args = "fsinfo drivetype $drive"
mod.req_args = {"drive"}
mod.maxtime = 1
table.insert(modules, mod)
mod = {}
mod.upload = false
mod.name = "Drive info"
mod.program = "fsutil"
mod.args = "fsinfo ntfsinfo $drive"
mod.req_args = {"drive"}
mod.replace = {{" :",":"}}
mod.maxtime = 1
table.insert(modules, mod)
mod = {}
mod.upload = false
mod.name = "Drive type"
mod.program = "fsutil"
mod.args = "fsinfo statistics $drive"
mod.req_args = {"drive"}
mod.replace = {{" :",":"}}
mod.maxtime = 1
table.insert(modules, mod)
mod = {}
mod.upload = false
mod.name = "Drive quota"
mod.program = "fsutil"
mod.args = "quota query $drive"
mod.req_args = {"drive"}
mod.maxtime = 1
table.insert(modules, mod)
| mit |
snail23/snailui | elements/bg_score.lua | 1 | 16524 | --
-- Copyright (C) 2012-2016 Snail <https://github.com/snail23/snailui/>
--
-- This program is free software; you can redistribute it and/or modify it
-- under the terms of the GNU General Public License as published by the
-- Free Software Foundation; either version 2 of the License, or (at your
-- option) any later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
-- more details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program. If not, see <http://www.gnu.org/licenses/>.
--
local _
function HandleBattlegroundScore()
UpdateBattlegroundScore = function(Self)
if GetConfiguration().BattlegroundScore and ExtraButton.Shown then
if InActiveBattlefield() then
Self:Show()
local PointsPattern = "(%d+)"
local PointsAndMaxPointsPattern = "(%d+)/(%d+)"
local PointsAndMaxPointsAndBasesPattern = "([a-zA-Z: ]+)(%d+)([a-zA-Z: ]+)(%d+)/(%d+)"
local function GetBattlegroundInfo(Text)
local Bases
local Points
local MaxPoints
local Zone = GetZoneText()
_, _, _, Bases, _, Points, MaxPoints = string.find(Text, PointsAndMaxPointsAndBasesPattern)
if (not Bases or (Bases and (strlen(Bases) == 0))) or (not Points or (Points and (strlen(Points) == 0))) or (not MaxPoints or (MaxPoints and (strlen(MaxPoints) == 0))) then
_, _, Points, MaxPoints = string.find(Text, PointsAndMaxPointsPattern)
Bases = nil
if (not Points or (Points and (strlen(Points) == 0))) or (not MaxPoints or (MaxPoints and (strlen(MaxPoints) == 0))) then
_, _, Points = string.find(Text, PointsPattern)
if not Points then
Points = "0"
end
Bases = nil
MaxPoints = (Zone == "Isle of Conquest") and "300" or "500"
if tonumber(Points) > tonumber(MaxPoints) then
MaxPoints = Points
end
end
end
return Bases, Points, MaxPoints
end
for I = 1, GetNumWorldStateUI() do
if I == (((GetZoneText() == "Eye of the Storm") and (not IsRatedMap())) and (Self.Index + 1) or Self.Index) then
local _, State, _, Text = GetWorldStateUIInfo(I)
if State == 2 then
Self.Icon:Show()
else
Self.Icon:Hide()
end
local Bases, Points, MaxPoints = GetBattlegroundInfo(Text)
if Points and (strlen(Points) > 0) and (GetZoneText() ~= "Strand of the Ancients") then
if Points == "0" then
Points = "0.00001"
end
Self.Bar:SetSize((GetConfiguration().BattlegroundScore.Width - 6) * (tonumber(Points) / tonumber(MaxPoints)), GetConfiguration().BattlegroundScore.Height - 6)
Self.Bar.Text:SetText(((Bases and (strlen(Bases) > 0)) and Bases .. ": " or "") .. math.floor(tonumber(Points)) .. "/" .. MaxPoints)
else
Self.Bar:SetSize(GetConfiguration().BattlegroundScore.Width - 6, GetConfiguration().BattlegroundScore.Height - 6)
Self.Bar.Text:SetText(Text)
end
end
end
else
Self:Hide()
end
end
end
if GetConfiguration().BattlegroundScore then
AllianceBattlegroundScore = CreateFrame("Frame", nil, UIParent)
AllianceBattlegroundScore:RegisterEvent("PLAYER_ENTERING_BATTLEGROUND")
AllianceBattlegroundScore:RegisterEvent("PLAYER_ENTERING_WORLD")
AllianceBattlegroundScore:RegisterEvent("UPDATE_BATTLEFIELD_SCORE")
AllianceBattlegroundScore:RegisterEvent("UPDATE_WORLD_STATES")
AllianceBattlegroundScore:SetPoint(GetConfiguration().BattlegroundScore.Anchor, GetConfiguration().BattlegroundScore.X, GetConfiguration().BattlegroundScore.Y)
AllianceBattlegroundScore:SetSize(GetConfiguration().BattlegroundScore.Width - 4, GetConfiguration().BattlegroundScore.Height - 4)
AllianceBattlegroundScore:SetScript("OnEvent", UpdateBattlegroundScore)
AllianceBattlegroundScore:SetScript("OnUpdate",
function(Self, ElapsedTime)
if not Self.Time then
Self.Time = 0
end
if (Self.Time + ElapsedTime) >= 0.1 then
UpdateBattlegroundScore(Self)
Self.Time = 0
else
Self.Time = Self.Time + ElapsedTime
end
end
)
AllianceBattlegroundScore.Background = AllianceBattlegroundScore:CreateTexture(nil, "LOW")
AllianceBattlegroundScore.Background:SetPoint("TOPLEFT", -1, 1)
AllianceBattlegroundScore.Background:SetSize(GetConfiguration().BattlegroundScore.Width - 2, GetConfiguration().BattlegroundScore.Height - 2)
AllianceBattlegroundScore.Background:SetColorTexture(PLAYER_FACTION_COLORS[1].r, PLAYER_FACTION_COLORS[1].g, PLAYER_FACTION_COLORS[1].b)
AllianceBattlegroundScore.Border = AllianceBattlegroundScore:CreateTexture(nil, "BACKGROUND")
AllianceBattlegroundScore.Border:SetPoint("TOPLEFT", -2, 2)
AllianceBattlegroundScore.Border:SetSize(GetConfiguration().BattlegroundScore.Width, GetConfiguration().BattlegroundScore.Height)
AllianceBattlegroundScore.Border:SetColorTexture(0, 0, 0)
AllianceBattlegroundScore.Bar = CreateFrame("StatusBar", nil, AllianceBattlegroundScore)
AllianceBattlegroundScore.Bar:SetPoint("TOPLEFT", 1, -1)
AllianceBattlegroundScore.Bar:SetSize(GetConfiguration().BattlegroundScore.Width - 6, GetConfiguration().BattlegroundScore.Height - 6)
AllianceBattlegroundScore.Bar:SetStatusBarTexture(Configuration.Texture)
AllianceBattlegroundScore.Bar:SetStatusBarColor(PLAYER_FACTION_COLORS[1].r, PLAYER_FACTION_COLORS[1].g, PLAYER_FACTION_COLORS[1].b)
SmoothBar(AllianceBattlegroundScore, AllianceBattlegroundScore.Bar)
AllianceBattlegroundScore.Bar.Border = AllianceBattlegroundScore.Bar:CreateTexture(nil, "BACKGROUND")
AllianceBattlegroundScore.Bar.Border:SetPoint("TOPLEFT", -1, 1)
AllianceBattlegroundScore.Bar.Border:SetSize(GetConfiguration().BattlegroundScore.Width - 4, GetConfiguration().BattlegroundScore.Height - 4)
AllianceBattlegroundScore.Bar.Border:SetColorTexture(0, 0, 0)
AllianceBattlegroundScore.Bar.Text = AllianceBattlegroundScore.Bar:CreateFontString(nil, "OVERLAY")
AllianceBattlegroundScore.Bar.Text:SetFont(Configuration.Font.Name, Configuration.Font.Size, Configuration.Font.Outline)
AllianceBattlegroundScore.Bar.Text:SetPoint("CENTER", AllianceBattlegroundScore, 1, 0)
AllianceBattlegroundScore.Bar.Text:SetTextColor(PLAYER_FACTION_COLORS[1].r * Configuration.TextColorPercentage, PLAYER_FACTION_COLORS[1].g * Configuration.TextColorPercentage, PLAYER_FACTION_COLORS[1].b * Configuration.TextColorPercentage)
AllianceBattlegroundScore.Icon = CreateFrame("Frame", nil, AllianceBattlegroundScore)
AllianceBattlegroundScore.Icon.Icon = AllianceBattlegroundScore.Icon:CreateTexture(nil, "LOW")
AllianceBattlegroundScore.Icon.Icon:SetPoint("LEFT", AllianceBattlegroundScore, -(GetConfiguration().BattlegroundScore.Height * 2) - 3, 0)
AllianceBattlegroundScore.Icon.Icon:SetSize((GetConfiguration().BattlegroundScore.Height * 2) - 6, GetConfiguration().BattlegroundScore.Height - 6)
AllianceBattlegroundScore.Icon.Icon:SetTexCoord(GetConfiguration().BattlegroundScore.TextureCoordinate.Left, GetConfiguration().BattlegroundScore.TextureCoordinate.Right, GetConfiguration().BattlegroundScore.TextureCoordinate.Top, GetConfiguration().BattlegroundScore.TextureCoordinate.Bottom)
AllianceBattlegroundScore.Icon.Icon:SetTexture("Interface/ICONS/PVPCurrency-Honor-Horde.png")
AllianceBattlegroundScore.Icon.IconBackgroundBottom = AllianceBattlegroundScore.Icon:CreateTexture(nil, "LOW")
AllianceBattlegroundScore.Icon.IconBackgroundBottom:SetPoint("BOTTOM", AllianceBattlegroundScore.Icon.Icon, 0, -2)
AllianceBattlegroundScore.Icon.IconBackgroundBottom:SetSize((GetConfiguration().BattlegroundScore.Height * 2) - 2, 1)
AllianceBattlegroundScore.Icon.IconBackgroundBottom:SetColorTexture(PLAYER_FACTION_COLORS[1].r, PLAYER_FACTION_COLORS[1].g, PLAYER_FACTION_COLORS[1].b)
AllianceBattlegroundScore.Icon.IconBackgroundLeft = AllianceBattlegroundScore.Icon:CreateTexture(nil, "LOW")
AllianceBattlegroundScore.Icon.IconBackgroundLeft:SetPoint("LEFT", AllianceBattlegroundScore.Icon.Icon, -2, 0)
AllianceBattlegroundScore.Icon.IconBackgroundLeft:SetSize(1, GetConfiguration().BattlegroundScore.Height - 4)
AllianceBattlegroundScore.Icon.IconBackgroundLeft:SetColorTexture(PLAYER_FACTION_COLORS[1].r, PLAYER_FACTION_COLORS[1].g, PLAYER_FACTION_COLORS[1].b)
AllianceBattlegroundScore.Icon.IconBackgroundRight = AllianceBattlegroundScore.Icon:CreateTexture(nil, "LOW")
AllianceBattlegroundScore.Icon.IconBackgroundRight:SetPoint("RIGHT", AllianceBattlegroundScore.Icon.Icon, 2, 0)
AllianceBattlegroundScore.Icon.IconBackgroundRight:SetSize(1, GetConfiguration().BattlegroundScore.Height - 4)
AllianceBattlegroundScore.Icon.IconBackgroundRight:SetColorTexture(PLAYER_FACTION_COLORS[1].r, PLAYER_FACTION_COLORS[1].g, PLAYER_FACTION_COLORS[1].b)
AllianceBattlegroundScore.Icon.IconBackgroundTop = AllianceBattlegroundScore.Icon:CreateTexture(nil, "LOW")
AllianceBattlegroundScore.Icon.IconBackgroundTop:SetPoint("TOP", AllianceBattlegroundScore.Icon.Icon, 0, 2)
AllianceBattlegroundScore.Icon.IconBackgroundTop:SetSize((GetConfiguration().BattlegroundScore.Height * 2) - 2, 1)
AllianceBattlegroundScore.Icon.IconBackgroundTop:SetColorTexture(PLAYER_FACTION_COLORS[1].r, PLAYER_FACTION_COLORS[1].g, PLAYER_FACTION_COLORS[1].b)
AllianceBattlegroundScore.Icon.IconBorder = AllianceBattlegroundScore.Icon:CreateTexture(nil, "BACKGROUND")
AllianceBattlegroundScore.Icon.IconBorder:SetPoint("TOPLEFT", AllianceBattlegroundScore.Icon.Icon, -3, 3)
AllianceBattlegroundScore.Icon.IconBorder:SetSize(GetConfiguration().BattlegroundScore.Height * 2, GetConfiguration().BattlegroundScore.Height)
AllianceBattlegroundScore.Icon.IconBorder:SetColorTexture(0, 0, 0)
AllianceBattlegroundScore.Index = 2
if GetConfiguration().ExtraButton then
AllianceBattlegroundScore:Hide()
end
HordeBattlegroundScore = CreateFrame("Frame", nil, UIParent)
HordeBattlegroundScore:RegisterEvent("PLAYER_ENTERING_BATTLEGROUND")
HordeBattlegroundScore:RegisterEvent("PLAYER_ENTERING_WORLD")
HordeBattlegroundScore:RegisterEvent("UPDATE_BATTLEFIELD_SCORE")
HordeBattlegroundScore:RegisterEvent("UPDATE_WORLD_STATES")
HordeBattlegroundScore:SetPoint(GetConfiguration().BattlegroundScore.Anchor, GetConfiguration().BattlegroundScore.X, (GetConfiguration().BattlegroundScore.Y - GetConfiguration().BattlegroundScore.Height) - 4)
HordeBattlegroundScore:SetSize(GetConfiguration().BattlegroundScore.Width - 4, GetConfiguration().BattlegroundScore.Height - 4)
HordeBattlegroundScore:SetScript("OnEvent", UpdateBattlegroundScore)
HordeBattlegroundScore:SetScript("OnUpdate",
function(Self, ElapsedTime)
if not Self.Time then
Self.Time = 0
end
if (Self.Time + ElapsedTime) >= 0.1 then
UpdateBattlegroundScore(Self)
Self.Time = 0
else
Self.Time = Self.Time + ElapsedTime
end
end
)
HordeBattlegroundScore.Background = HordeBattlegroundScore:CreateTexture(nil, "LOW")
HordeBattlegroundScore.Background:SetPoint("TOPLEFT", -1, 1)
HordeBattlegroundScore.Background:SetSize(GetConfiguration().BattlegroundScore.Width - 2, GetConfiguration().BattlegroundScore.Height - 2)
HordeBattlegroundScore.Background:SetColorTexture(PLAYER_FACTION_COLORS[0].r, PLAYER_FACTION_COLORS[0].g, PLAYER_FACTION_COLORS[0].b)
HordeBattlegroundScore.Border = HordeBattlegroundScore:CreateTexture(nil, "BACKGROUND")
HordeBattlegroundScore.Border:SetPoint("TOPLEFT", -2, 2)
HordeBattlegroundScore.Border:SetSize(GetConfiguration().BattlegroundScore.Width, GetConfiguration().BattlegroundScore.Height)
HordeBattlegroundScore.Border:SetColorTexture(0, 0, 0)
HordeBattlegroundScore.Bar = CreateFrame("StatusBar", nil, HordeBattlegroundScore)
HordeBattlegroundScore.Bar:SetPoint("TOPLEFT", 1, -1)
HordeBattlegroundScore.Bar:SetSize(GetConfiguration().BattlegroundScore.Width - 6, GetConfiguration().BattlegroundScore.Height - 6)
HordeBattlegroundScore.Bar:SetStatusBarTexture(Configuration.Texture)
HordeBattlegroundScore.Bar:SetStatusBarColor(PLAYER_FACTION_COLORS[0].r, PLAYER_FACTION_COLORS[0].g, PLAYER_FACTION_COLORS[0].b)
SmoothBar(HordeBattlegroundScore, HordeBattlegroundScore.Bar)
HordeBattlegroundScore.Bar.Border = HordeBattlegroundScore.Bar:CreateTexture(nil, "BACKGROUND")
HordeBattlegroundScore.Bar.Border:SetPoint("TOPLEFT", -1, 1)
HordeBattlegroundScore.Bar.Border:SetSize(GetConfiguration().BattlegroundScore.Width - 4, GetConfiguration().BattlegroundScore.Height - 4)
HordeBattlegroundScore.Bar.Border:SetColorTexture(0, 0, 0)
HordeBattlegroundScore.Bar.Text = HordeBattlegroundScore.Bar:CreateFontString(nil, "OVERLAY")
HordeBattlegroundScore.Bar.Text:SetFont(Configuration.Font.Name, Configuration.Font.Size, Configuration.Font.Outline)
HordeBattlegroundScore.Bar.Text:SetPoint("CENTER", HordeBattlegroundScore, 1, 0)
HordeBattlegroundScore.Bar.Text:SetTextColor(PLAYER_FACTION_COLORS[0].r * Configuration.TextColorPercentage, PLAYER_FACTION_COLORS[0].g * Configuration.TextColorPercentage, PLAYER_FACTION_COLORS[0].b * Configuration.TextColorPercentage)
HordeBattlegroundScore.Icon = CreateFrame("Frame", nil, HordeBattlegroundScore)
HordeBattlegroundScore.Icon.Icon = HordeBattlegroundScore.Icon:CreateTexture(nil, "LOW")
HordeBattlegroundScore.Icon.Icon:SetPoint("LEFT", HordeBattlegroundScore, -(GetConfiguration().BattlegroundScore.Height * 2) - 3, 0)
HordeBattlegroundScore.Icon.Icon:SetSize((GetConfiguration().BattlegroundScore.Height * 2) - 6, GetConfiguration().BattlegroundScore.Height - 6)
HordeBattlegroundScore.Icon.Icon:SetTexCoord(GetConfiguration().BattlegroundScore.TextureCoordinate.Left, GetConfiguration().BattlegroundScore.TextureCoordinate.Right, GetConfiguration().BattlegroundScore.TextureCoordinate.Top, GetConfiguration().BattlegroundScore.TextureCoordinate.Bottom)
HordeBattlegroundScore.Icon.Icon:SetTexture("Interface/ICONS/PVPCurrency-Honor-Alliance.png")
HordeBattlegroundScore.Icon.IconBackgroundBottom = HordeBattlegroundScore.Icon:CreateTexture(nil, "LOW")
HordeBattlegroundScore.Icon.IconBackgroundBottom:SetPoint("BOTTOM", HordeBattlegroundScore.Icon.Icon, 0, -2)
HordeBattlegroundScore.Icon.IconBackgroundBottom:SetSize((GetConfiguration().BattlegroundScore.Height * 2) - 2, 1)
HordeBattlegroundScore.Icon.IconBackgroundBottom:SetColorTexture(PLAYER_FACTION_COLORS[0].r, PLAYER_FACTION_COLORS[0].g, PLAYER_FACTION_COLORS[0].b)
HordeBattlegroundScore.Icon.IconBackgroundLeft = HordeBattlegroundScore.Icon:CreateTexture(nil, "LOW")
HordeBattlegroundScore.Icon.IconBackgroundLeft:SetPoint("LEFT", HordeBattlegroundScore.Icon.Icon, -2, 0)
HordeBattlegroundScore.Icon.IconBackgroundLeft:SetSize(1, GetConfiguration().BattlegroundScore.Height - 4)
HordeBattlegroundScore.Icon.IconBackgroundLeft:SetColorTexture(PLAYER_FACTION_COLORS[0].r, PLAYER_FACTION_COLORS[0].g, PLAYER_FACTION_COLORS[0].b)
HordeBattlegroundScore.Icon.IconBackgroundRight = HordeBattlegroundScore.Icon:CreateTexture(nil, "LOW")
HordeBattlegroundScore.Icon.IconBackgroundRight:SetPoint("RIGHT", HordeBattlegroundScore.Icon.Icon, 2, 0)
HordeBattlegroundScore.Icon.IconBackgroundRight:SetSize(1, GetConfiguration().BattlegroundScore.Height - 4)
HordeBattlegroundScore.Icon.IconBackgroundRight:SetColorTexture(PLAYER_FACTION_COLORS[0].r, PLAYER_FACTION_COLORS[0].g, PLAYER_FACTION_COLORS[0].b)
HordeBattlegroundScore.Icon.IconBackgroundTop = HordeBattlegroundScore.Icon:CreateTexture(nil, "LOW")
HordeBattlegroundScore.Icon.IconBackgroundTop:SetPoint("TOP", HordeBattlegroundScore.Icon.Icon, 0, 2)
HordeBattlegroundScore.Icon.IconBackgroundTop:SetSize((GetConfiguration().BattlegroundScore.Height * 2) - 2, 1)
HordeBattlegroundScore.Icon.IconBackgroundTop:SetColorTexture(PLAYER_FACTION_COLORS[0].r, PLAYER_FACTION_COLORS[0].g, PLAYER_FACTION_COLORS[0].b)
HordeBattlegroundScore.Icon.IconBorder = HordeBattlegroundScore.Icon:CreateTexture(nil, "BACKGROUND")
HordeBattlegroundScore.Icon.IconBorder:SetPoint("TOPLEFT", HordeBattlegroundScore.Icon.Icon, -3, 3)
HordeBattlegroundScore.Icon.IconBorder:SetSize(GetConfiguration().BattlegroundScore.Height * 2, GetConfiguration().BattlegroundScore.Height)
HordeBattlegroundScore.Icon.IconBorder:SetColorTexture(0, 0, 0)
HordeBattlegroundScore.Index = 3
if GetConfiguration().ExtraButton then
HordeBattlegroundScore:Hide()
end
end
end
| gpl-2.0 |
gpedro/forgottenserver | data/events/scripts/player.lua | 20 | 5180 | function Player:onBrowseField(position)
return true
end
function Player:onLook(thing, position, distance)
local description = "You see " .. thing:getDescription(distance)
if self:getGroup():getAccess() then
if thing:isItem() then
description = string.format("%s\nItem ID: %d", description, thing:getId())
local actionId = thing:getActionId()
if actionId ~= 0 then
description = string.format("%s, Action ID: %d", description, actionId)
end
local uniqueId = thing:getAttribute(ITEM_ATTRIBUTE_UNIQUEID)
if uniqueId > 0 and uniqueId < 65536 then
description = string.format("%s, Unique ID: %d", description, uniqueId)
end
local itemType = thing:getType()
local transformEquipId = itemType:getTransformEquipId()
local transformDeEquipId = itemType:getTransformDeEquipId()
if transformEquipId ~= 0 then
description = string.format("%s\nTransforms to: %d (onEquip)", description, transformEquipId)
elseif transformDeEquipId ~= 0 then
description = string.format("%s\nTransforms to: %d (onDeEquip)", description, transformDeEquipId)
end
local decayId = itemType:getDecayId()
if decayId ~= -1 then
description = string.format("%s\nDecays to: %d", description, decayId)
end
elseif thing:isCreature() then
local str = "%s\nHealth: %d / %d"
if thing:getMaxMana() > 0 then
str = string.format("%s, Mana: %d / %d", str, thing:getMana(), thing:getMaxMana())
end
description = string.format(str, description, thing:getHealth(), thing:getMaxHealth()) .. "."
end
local position = thing:getPosition()
description = string.format(
"%s\nPosition: %d, %d, %d",
description, position.x, position.y, position.z
)
if thing:isCreature() then
if thing:isPlayer() then
description = string.format("%s\nIP: %s.", description, Game.convertIpToString(thing:getIp()))
end
end
end
self:sendTextMessage(MESSAGE_INFO_DESCR, description)
end
function Player:onLookInBattleList(creature, distance)
local description = "You see " .. creature:getDescription(distance)
if self:getGroup():getAccess() then
local str = "%s\nHealth: %d / %d"
if creature:getMaxMana() > 0 then
str = string.format("%s, Mana: %d / %d", str, creature:getMana(), creature:getMaxMana())
end
description = string.format(str, description, creature:getHealth(), creature:getMaxHealth()) .. "."
local position = creature:getPosition()
description = string.format(
"%s\nPosition: %d, %d, %d",
description, position.x, position.y, position.z
)
if creature:isPlayer() then
description = string.format("%s\nIP: %s", description, Game.convertIpToString(creature:getIp()))
end
end
self:sendTextMessage(MESSAGE_INFO_DESCR, description)
end
function Player:onLookInTrade(partner, item, distance)
self:sendTextMessage(MESSAGE_INFO_DESCR, "You see " .. item:getDescription(distance))
end
function Player:onLookInShop(itemType, count)
return true
end
function Player:onMoveItem(item, count, fromPosition, toPosition)
return true
end
function Player:onMoveCreature(creature, fromPosition, toPosition)
return true
end
function Player:onTurn(direction)
return true
end
function Player:onTradeRequest(target, item)
return true
end
function Player:onTradeAccept(target, item, targetItem)
return true
end
local soulCondition = Condition(CONDITION_SOUL, CONDITIONID_DEFAULT)
soulCondition:setTicks(4 * 60 * 1000)
soulCondition:setParameter(CONDITION_PARAM_SOULGAIN, 1)
local function useStamina(player)
local staminaMinutes = player:getStamina()
if staminaMinutes == 0 then
return
end
local playerId = player:getId()
local currentTime = os.time()
local timePassed = currentTime - nextUseStaminaTime[playerId]
if timePassed <= 0 then
return
end
if timePassed > 60 then
if staminaMinutes > 2 then
staminaMinutes = staminaMinutes - 2
else
staminaMinutes = 0
end
nextUseStaminaTime[playerId] = currentTime + 120
else
staminaMinutes = staminaMinutes - 1
nextUseStaminaTime[playerId] = currentTime + 60
end
player:setStamina(staminaMinutes)
end
function Player:onGainExperience(source, exp, rawExp)
if not source or source:isPlayer() then
return exp
end
-- Soul regeneration
local vocation = self:getVocation()
if self:getSoul() < vocation:getMaxSoul() and exp >= self:getLevel() then
soulCondition:setParameter(CONDITION_PARAM_SOULTICKS, vocation:getSoulGainTicks() * 1000)
self:addCondition(soulCondition)
end
-- Apply experience stage multiplier
exp = exp * Game.getExperienceStage(self:getLevel())
-- Stamina modifier
if configManager.getBoolean(configKeys.STAMINA_SYSTEM) then
useStamina(self)
local staminaMinutes = self:getStamina()
if staminaMinutes > 2400 and self:isPremium() then
exp = exp * 1.5
elseif staminaMinutes <= 840 then
exp = exp * 0.5
end
end
return exp
end
function Player:onLoseExperience(exp)
return exp
end
function Player:onGainSkillTries(skill, tries)
if APPLY_SKILL_MULTIPLIER == false then
return tries
end
if skill == SKILL_MAGLEVEL then
return tries * configManager.getNumber(configKeys.RATE_MAGIC)
end
return tries * configManager.getNumber(configKeys.RATE_SKILL)
end
| gpl-2.0 |
alexandergall/snabbswitch | lib/luajit/testsuite/test/sysdep/ffi_lib_z.lua | 6 | 3348 | local ffi = require("ffi")
local compress, uncompress
if ffi.abi("win") then
ffi.cdef[[
int RtlGetCompressionWorkSpaceSize(uint16_t fmt,
unsigned long *wsbufsz, unsigned long *wsfragsz);
int RtlCompressBuffer(uint16_t fmt,
const uint8_t *src, unsigned long srclen,
uint8_t *dst, unsigned long dstsz,
unsigned long chunk, unsigned long *dstlen, void *workspace);
int RtlDecompressBuffer(uint16_t fmt,
uint8_t *dst, unsigned long dstsz,
const uint8_t *src, unsigned long srclen,
unsigned long *dstlen);
]]
local ntdll = ffi.load("ntdll")
local fmt = 0x0102
local workspace
do
local res = ffi.new("unsigned long[2]")
ntdll.RtlGetCompressionWorkSpaceSize(fmt, res, res+1)
workspace = ffi.new("uint8_t[?]", res[0])
end
function compress(txt)
local buf = ffi.new("uint8_t[?]", 4096)
local buflen = ffi.new("unsigned long[1]")
local res = ntdll.RtlCompressBuffer(fmt, txt, #txt, buf, 4096,
4096, buflen, workspace)
assert(res == 0)
return ffi.string(buf, buflen[0])
end
function uncompress(comp, n)
local buf = ffi.new("uint8_t[?]", n)
local buflen = ffi.new("unsigned long[1]")
local res = ntdll.RtlDecompressBuffer(fmt, buf, n, comp, #comp, buflen)
assert(res == 0)
return ffi.string(buf, buflen[0])
end
else
ffi.cdef[[
unsigned long compressBound(unsigned long sourceLen);
int compress2(uint8_t *dest, unsigned long *destLen,
const uint8_t *source, unsigned long sourceLen, int level);
int uncompress(uint8_t *dest, unsigned long *destLen,
const uint8_t *source, unsigned long sourceLen);
]]
local zlib = ffi.load("z")
function compress(txt)
local n = tonumber(zlib.compressBound(#txt))
local buf = ffi.new("uint8_t[?]", n)
local buflen = ffi.new("unsigned long[1]", n)
local res = zlib.compress2(buf, buflen, txt, #txt, 9)
assert(res == 0)
return ffi.string(buf, tonumber(buflen[0]))
end
function uncompress(comp, n)
local buf = ffi.new("uint8_t[?]", n)
local buflen = ffi.new("unsigned long[1]", n)
local res = zlib.uncompress(buf, buflen, comp, #comp)
assert(res == 0)
return ffi.string(buf, tonumber(buflen[0]))
end
end
local txt = [[Rebellious subjects, enemies to peace,
Profaners of this neighbour-stained steel,--
Will they not hear? What, ho! you men, you beasts,
That quench the fire of your pernicious rage
With purple fountains issuing from your veins,
On pain of torture, from those bloody hands
Throw your mistemper'd weapons to the ground,
And hear the sentence of your moved prince.
Three civil brawls, bred of an airy word,
By thee, old Capulet, and Montague,
Have thrice disturb'd the quiet of our streets,
And made Verona's ancient citizens
Cast by their grave beseeming ornaments,
To wield old partisans, in hands as old,
Canker'd with peace, to part your canker'd hate:
If ever you disturb our streets again,
Your lives shall pay the forfeit of the peace.
For this time, all the rest depart away:
You Capulet; shall go along with me:
And, Montague, come you this afternoon,
To know our further pleasure in this case,
To old Free-town, our common judgment-place.
Once more, on pain of death, all men depart.]]
txt = txt..txt..txt..txt
local c = compress(txt)
assert(2*#c < #txt)
local txt2 = uncompress(c, #txt)
assert(txt2 == txt)
| apache-2.0 |
infernal1200/infernall | plugins/gnuplot.lua | 622 | 1813 | --[[
* Gnuplot plugin by psykomantis
* dependencies:
* - gnuplot 5.00
* - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html
*
]]
-- Gnuplot needs absolute path for the plot, so i run some commands to find where we are
local outputFile = io.popen("pwd","r")
io.input(outputFile)
local _pwd = io.read("*line")
io.close(outputFile)
local _absolutePlotPath = _pwd .. "/data/plot.png"
local _scriptPath = "./data/gnuplotScript.gpl"
do
local function gnuplot(msg, fun)
local receiver = get_receiver(msg)
-- We generate the plot commands
local formattedString = [[
set grid
set terminal png
set output "]] .. _absolutePlotPath .. [["
plot ]] .. fun
local file = io.open(_scriptPath,"w");
file:write(formattedString)
file:close()
os.execute("gnuplot " .. _scriptPath)
os.remove (_scriptPath)
return _send_photo(receiver, _absolutePlotPath)
end
-- Check all dependencies before executing
local function checkDependencies()
local status = os.execute("gnuplot -h")
if(status==true) then
status = os.execute("gnuplot -e 'set terminal png'")
if(status == true) then
return 0 -- OK ready to go!
else
return 1 -- missing libgd2-xpm-dev
end
else
return 2 -- missing gnuplot
end
end
local function run(msg, matches)
local status = checkDependencies()
if(status == 0) then
return gnuplot(msg,matches[1])
elseif(status == 1) then
return "It seems that this bot miss a dependency :/"
else
return "It seems that this bot doesn't have gnuplot :/"
end
end
return {
description = "use gnuplot through telegram, only plot single variable function",
usage = "!gnuplot [single variable function]",
patterns = {"^!gnuplot (.+)$"},
run = run
}
end
| gpl-2.0 |
alastair-robertson/awesome | tests/test-urgent.lua | 3 | 3653 | --- Tests for urgent property.
local awful = require("awful")
local runner = require("_runner")
-- Some basic assertion that the tag is not marked "urgent" already.
assert(awful.tag.getproperty(awful.screen.focused().tags[2], "urgent") == nil)
-- Setup signal handler which should be called.
-- TODO: generalize and move to runner.
local urgent_cb_done
client.connect_signal("property::urgent", function (c)
urgent_cb_done = true
assert(c.class == "XTerm", "Client should be xterm!")
end)
local manage_cb_done
client.connect_signal("manage", function (c)
manage_cb_done = true
assert(c.class == "XTerm", "Client should be xterm!")
end)
-- Steps to do for this test.
local steps = {
-- Step 1: tag 2 should become urgent, when a client gets tagged via rules.
function(count)
if count == 1 then -- Setup.
urgent_cb_done = false
-- Select first tag.
awful.screen.focused().tags[1]:view_only()
runner.add_to_default_rules({ rule = { class = "XTerm" },
properties = { tag = "2", focus = true } })
awful.spawn("xterm")
end
if urgent_cb_done then
assert(awful.tag.getproperty(awful.screen.focused().tags[2], "urgent") == true)
assert(awful.tag.getproperty(awful.screen.focused().tags[2], "urgent_count") == 1)
return true
end
end,
-- Step 2: when switching to tag 2, it should not be urgent anymore.
function(count)
if count == 1 then
-- Setup: switch to tag.
root.fake_input("key_press", "Super_L")
root.fake_input("key_press", "2")
root.fake_input("key_release", "2")
root.fake_input("key_release", "Super_L")
elseif awful.screen.focused().selected_tags[1] == awful.screen.focused().tags[2] then
assert(#client.get() == 1)
local c = client.get()[1]
assert(not c.urgent, "Client is not urgent anymore.")
assert(c == client.focus, "Client is focused.")
assert(awful.tag.getproperty(awful.screen.focused().tags[2], "urgent") == false)
assert(awful.tag.getproperty(awful.screen.focused().tags[2], "urgent_count") == 0)
return true
end
end,
-- Step 3: tag 2 should not be urgent, but switched to.
function(count)
if count == 1 then -- Setup.
urgent_cb_done = false
-- Select first tag.
awful.screen.focused().tags[1]:view_only()
runner.add_to_default_rules({ rule = { class = "XTerm" },
properties = { tag = "2", focus = true, switchtotag = true }})
awful.spawn("xterm")
elseif awful.screen.focused().selected_tags[1] == awful.screen.focused().tags[2] then
assert(not urgent_cb_done)
assert(awful.tag.getproperty(awful.screen.focused().tags[2], "urgent") == false)
assert(awful.tag.getproperty(awful.screen.focused().tags[2], "urgent_count") == 0)
assert(awful.screen.focused().selected_tags[2] == nil)
return true
end
end,
-- Step 4: tag 2 should not become urgent, when a client gets tagged via
-- rules with focus=false.
function(count)
if count == 1 then -- Setup.
client.get()[1]:kill()
manage_cb_done = false
runner.add_to_default_rules({rule = { class = "XTerm" },
properties = { tag = "2", focus = false }})
awful.spawn("xterm")
end
if manage_cb_done then
assert(client.get()[1].urgent == false)
assert(awful.tag.getproperty(awful.screen.focused().tags[2], "urgent") == false)
assert(awful.tag.getproperty(awful.screen.focused().tags[2], "urgent_count") == 0)
return true
end
end,
}
runner.run_steps(steps)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
kiarash14/tg5 | plugins/id.lua | 12 | 7187 |
do
local function scan_name(extra, success, result)
local founds = {}
for k,member in pairs(result.members) do
if extra.name then
gp_member = extra.name
fields = {'first_name', 'last_name', 'print_name'}
elseif extra.user then
gp_member = string.gsub(extra.user, '@', '')
fields = {'username'}
end
for k,field in pairs(fields) do
if member[field] and type(member[field]) == 'string' then
if member[field]:match(gp_member) then
founds[tostring(member.id)] = member
end
end
end
end
if next(founds) == nil then -- Empty table
send_large_msg(extra.receiver, (extra.name or extra.user)..' در این گروه پیدا نشد')
else
local text = ''
for k,user in pairs(founds) do
text = text..'name: '..(user.first_name or '-----')..'\n'
..'Last name: '..(user.last_name or '-----')..'\n\n'
..'Username: @'..(user.username or '-----')..'\n'
..'User ID: '..(user.id or '')..'\n\n'
end
send_large_msg(extra.receiver, text)
end
end
local function action_by_reply(extra, success, result)
local text = 'Name: '..(result.from.first_name or '-----')..'\n'
..'Last name: '..(result.from.last_name or '-----')..'\n\n'
..'Username: @'..(result.from.username or '-----')..'\n'
..'User ID: '..result.from.id
send_large_msg(extra.receiver, text)
end
local function returnids(extra, success, result)
local chat_id = extra.msg.to.id
local text = '['..result.id..'] '..result.title..'.\n'
..result.members_num..' members.\n\n'
i = 0
for k,v in pairs(result.members) do
i = i+1
if v.username then
user_name = ' @'..v.username
else
user_name = ''
end
text = text..i..'. ['..v.id..'] '..user_name..' '..(v.first_name or '')..(v.last_name or '')..'\n'
end
if extra.matches == 'pm' then
send_large_msg('user#id'..extra.msg.from.id, text)
elseif extra.matches == 'txt' or extra.matches == 'pmtxt' then
local textfile = '/tmp/chat_info_'..chat_id..'_'..os.date("%y%m%d.%H%M%S")..'.txt'
local file = io.open(textfile, 'w')
file:write(text)
file:flush()
file:close()
if extra.matches == 'txt' then
send_document('chat#id'..chat_id, textfile, rmtmp_cb, {file_path=textfile})
elseif extra.matches == 'pmtxt' then
send_document('user#id'..extra.msg.from.id, textfile, rmtmp_cb, {file_path=textfile})
end
elseif not extra.matches then
send_large_msg('chat#id'..chat_id, text)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if is_chat_msg(msg) then
if msg.text == 'id' or '!id' or '/id' or 'Id' then
if msg.reply_id then
if is_mod(msg) then
msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver})
end
else
local text = 'name: '..(msg.from.first_name or '-----')..'\n'
..'Last name: '..(msg.from.last_name or '-----')..'\n\n'
..'Username @'..(msg.from.username or '-----')..'\n'
..'User ID: ' .. msg.from.id..'\n\n'
local text = text..'Group name : '..msg.to.title..'\nGroup ID : '..msg.to.id
return text
end
elseif is_mod(msg) and matches[1] == 'chat' then
if matches[2] == 'pm' or matches[2] == 'txt' or matches[2] == 'pmtxt' then
chat_info(receiver, returnids, {msg=msg, matches=matches[2]})
else
chat_info(receiver, returnids, {msg=msg})
end
elseif is_mod(msg) and string.match(matches[1], '^@.+$') then
chat_info(receiver, scan_name, {receiver=receiver, user=matches[1]})
elseif is_mod(msg) and string.gsub(matches[1], ' ', '_') then
user = string.gsub(matches[1], ' ', '_')
chat_info(receiver, scan_name, {receiver=receiver, name=matches[1]})
end
else
return
end
end
return {
description = 'Know your id or the id of a chat members.',
usage = {
user = {
'!id: Return your ID and the chat id if you are in one.'
},
moderator = {
'!id : Return ID of replied user if used by reply.',
'!id chat : Return the IDs of the current chat members.',
'!id chat txt : Return the IDs of the current chat members and send it as text file.',
'!id chat pm : Return the IDs of the current chat members and send it to PM.',
'!id chat pmtxt : Return the IDs of the current chat members, save it as text file and then send it to PM.',
'!id <id> : Return the IDs of the <id>.',
'!id @<user_name> : Return the member @<user_name> ID from the current chat.',
'!id <text> : Search for users with <text> on first_name, last_name, or print_name on current chat.'
},
},
patterns = {
"^[!/]id$",
"^[!/]id (chat) (.*)$",
"^[!/]id user (.*)$",
"^([Ii]d)$",
},
run = run
}
end
-- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
--
--
-- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
-- ||\\ //|| //\\ || //|| //\\ // || || //
-- || \\ // || // \\ || // || // \\ // || || //
-- || \\ // || // \\ || // || // \\ || || || //
-- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || //
-- || \\ // || // \\ || // || // \\ || || || || \\
-- || \\ // || // \\ || // || // \\ \\ || || || \\
-- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\
--
--
-- ||-_-_-_- || || || //-_-_-_-_-_-
-- || || || || || //
-- ||_-_-_|| || || || //
-- || || || || \\
-- || || \\ // \\
-- || || \\ // //
-- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-//
--
--By @ali_ghoghnoos
--@telemanager_ch
| gpl-2.0 |
mortezamosavy999/monster | plugins/quotes.lua | 651 | 1630 | local quotes_file = './data/quotes.lua'
local quotes_table
function read_quotes_file()
local f = io.open(quotes_file, "r+")
if f == nil then
print ('Created a new quotes file on '..quotes_file)
serialize_to_file({}, quotes_file)
else
print ('Quotes loaded: '..quotes_file)
f:close()
end
return loadfile (quotes_file)()
end
function save_quote(msg)
local to_id = tostring(msg.to.id)
if msg.text:sub(11):isempty() then
return "Usage: !addquote quote"
end
if quotes_table == nil then
quotes_table = {}
end
if quotes_table[to_id] == nil then
print ('New quote key to_id: '..to_id)
quotes_table[to_id] = {}
end
local quotes = quotes_table[to_id]
quotes[#quotes+1] = msg.text:sub(11)
serialize_to_file(quotes_table, quotes_file)
return "done!"
end
function get_quote(msg)
local to_id = tostring(msg.to.id)
local quotes_phrases
quotes_table = read_quotes_file()
quotes_phrases = quotes_table[to_id]
return quotes_phrases[math.random(1,#quotes_phrases)]
end
function run(msg, matches)
if string.match(msg.text, "!quote$") then
return get_quote(msg)
elseif string.match(msg.text, "!addquote (.+)$") then
quotes_table = read_quotes_file()
return save_quote(msg)
end
end
return {
description = "Save quote",
description = "Quote plugin, you can create and retrieve random quotes",
usage = {
"!addquote [msg]",
"!quote",
},
patterns = {
"^!addquote (.+)$",
"^!quote$",
},
run = run
}
| gpl-2.0 |
pablo93/TrinityCore | Data/Interface/FrameXML/CastingBarFrame.lua | 1 | 7953 | CASTING_BAR_ALPHA_STEP = 0.05;
CASTING_BAR_FLASH_STEP = 0.2;
CASTING_BAR_HOLD_TIME = 1;
function CastingBarFrame_OnLoad (self, unit, showTradeSkills)
self:RegisterEvent("UNIT_SPELLCAST_START");
self:RegisterEvent("UNIT_SPELLCAST_STOP");
self:RegisterEvent("UNIT_SPELLCAST_FAILED");
self:RegisterEvent("UNIT_SPELLCAST_INTERRUPTED");
self:RegisterEvent("UNIT_SPELLCAST_DELAYED");
self:RegisterEvent("UNIT_SPELLCAST_CHANNEL_START");
self:RegisterEvent("UNIT_SPELLCAST_CHANNEL_UPDATE");
self:RegisterEvent("UNIT_SPELLCAST_CHANNEL_STOP");
self:RegisterEvent("PLAYER_ENTERING_WORLD");
self.unit = unit;
self.showTradeSkills = showTradeSkills;
self.casting = nil;
self.channeling = nil;
self.holdTime = 0;
self.showCastbar = true;
local barIcon = getglobal(self:GetName().."Icon");
if ( barIcon ) then
barIcon:Hide();
end
end
function CastingBarFrame_OnShow (self)
if ( self.casting ) then
local _, _, _, _, startTime = UnitCastingInfo(self.unit);
if ( startTime ) then
self.value = (GetTime() - (startTime / 1000));
end
else
local _, _, _, _, _, endTime = UnitChannelInfo(self.unit);
if ( endTime ) then
self.value = ((endTime / 1000) - GetTime());
end
end
end
function CastingBarFrame_OnEvent (self, event, ...)
local arg1 = ...;
local unit = self.unit;
if ( event == "PLAYER_ENTERING_WORLD" ) then
local nameChannel = UnitChannelInfo(unit);
local nameSpell = UnitCastingInfo(unit);
if ( nameChannel ) then
event = "UNIT_SPELLCAST_CHANNEL_START";
arg1 = unit;
elseif ( nameSpell ) then
event = "UNIT_SPELLCAST_START";
arg1 = unit;
else
CastingBarFrame_FinishSpell(self);
end
end
if ( arg1 ~= unit ) then
return;
end
local selfName = self:GetName();
local barSpark = getglobal(selfName.."Spark");
local barText = getglobal(selfName.."Text");
local barFlash = getglobal(selfName.."Flash");
local barIcon = getglobal(selfName.."Icon");
if ( event == "UNIT_SPELLCAST_START" ) then
local name, nameSubtext, text, texture, startTime, endTime, isTradeSkill, castID = UnitCastingInfo(unit);
if ( not name or (not self.showTradeSkills and isTradeSkill)) then
self:Hide();
return;
end
self:SetStatusBarColor(1.0, 0.7, 0.0);
if ( barSpark ) then
barSpark:Show();
end
self.value = (GetTime() - (startTime / 1000));
self.maxValue = (endTime - startTime) / 1000;
self:SetMinMaxValues(0, self.maxValue);
self:SetValue(self.value);
if ( barText ) then
barText:SetText(text);
end
if ( barIcon ) then
barIcon:SetTexture(texture);
end
self:SetAlpha(1.0);
self.holdTime = 0;
self.casting = 1;
self.castID = castID;
self.channeling = nil;
self.fadeOut = nil;
if ( self.showCastbar ) then
self:Show();
end
elseif ( event == "UNIT_SPELLCAST_STOP" or event == "UNIT_SPELLCAST_CHANNEL_STOP") then
if ( not self:IsVisible() ) then
self:Hide();
end
if ( (self.casting and event == "UNIT_SPELLCAST_STOP" and select(4, ...) == self.castID) or
(self.channeling and event == "UNIT_SPELLCAST_CHANNEL_STOP") ) then
if ( barSpark ) then
barSpark:Hide();
end
if ( barFlash ) then
barFlash:SetAlpha(0.0);
barFlash:Show();
end
self:SetValue(self.maxValue);
if ( event == "UNIT_SPELLCAST_STOP" ) then
self.casting = nil;
self:SetStatusBarColor(0.0, 1.0, 0.0);
else
self.channeling = nil;
end
self.flash = 1;
self.fadeOut = 1;
self.holdTime = 0;
end
elseif ( event == "UNIT_SPELLCAST_FAILED" or event == "UNIT_SPELLCAST_INTERRUPTED" ) then
if ( self:IsShown() and
(self.casting and select(4, ...) == self.castID) and not self.fadeOut ) then
self:SetValue(self.maxValue);
self:SetStatusBarColor(1.0, 0.0, 0.0);
if ( barSpark ) then
barSpark:Hide();
end
if ( barText ) then
if ( event == "UNIT_SPELLCAST_FAILED" ) then
barText:SetText(FAILED);
else
barText:SetText(INTERRUPTED);
end
end
self.casting = nil;
self.channeling = nil;
self.fadeOut = 1;
self.holdTime = GetTime() + CASTING_BAR_HOLD_TIME;
end
elseif ( event == "UNIT_SPELLCAST_DELAYED" ) then
if ( self:IsShown() ) then
local name, nameSubtext, text, texture, startTime, endTime, isTradeSkill = UnitCastingInfo(unit);
if ( not name or (not self.showTradeSkills and isTradeSkill)) then
-- if there is no name, there is no bar
self:Hide();
return;
end
self.value = (GetTime() - (startTime / 1000));
self.maxValue = (endTime - startTime) / 1000;
self:SetMinMaxValues(0, self.maxValue);
if ( not self.casting ) then
self:SetStatusBarColor(1.0, 0.7, 0.0);
if ( barSpark ) then
barSpark:Show();
end
if ( barFlash ) then
barFlash:SetAlpha(0.0);
barFlash:Hide();
end
self.casting = 1;
self.channeling = nil;
self.flash = 0;
self.fadeOut = 0;
end
end
elseif ( event == "UNIT_SPELLCAST_CHANNEL_START" ) then
local name, nameSubtext, text, texture, startTime, endTime, isTradeSkill = UnitChannelInfo(unit);
if ( not name or (not self.showTradeSkills and isTradeSkill)) then
-- if there is no name, there is no bar
self:Hide();
return;
end
self:SetStatusBarColor(0.0, 1.0, 0.0);
self.value = ((endTime / 1000) - GetTime());
self.maxValue = (endTime - startTime) / 1000;
self:SetMinMaxValues(0, self.maxValue);
self:SetValue(self.value);
if ( barText ) then
barText:SetText(text);
end
if ( barIcon ) then
barIcon:SetTexture(texture);
end
if ( barSpark ) then
barSpark:Hide();
end
self:SetAlpha(1.0);
self.holdTime = 0;
self.casting = nil;
self.channeling = 1;
self.fadeOut = nil;
if ( self.showCastbar ) then
self:Show();
end
elseif ( event == "UNIT_SPELLCAST_CHANNEL_UPDATE" ) then
if ( self:IsShown() ) then
local name, nameSubtext, text, texture, startTime, endTime, isTradeSkill = UnitChannelInfo(unit);
if ( not name or (not self.showTradeSkills and isTradeSkill)) then
-- if there is no name, there is no bar
self:Hide();
return;
end
self.value = ((endTime / 1000) - GetTime());
self.maxValue = (endTime - startTime) / 1000;
self:SetMinMaxValues(0, self.maxValue);
self:SetValue(self.value);
end
end
end
function CastingBarFrame_OnUpdate (self, elapsed)
local barSpark = getglobal(self:GetName().."Spark");
local barFlash = getglobal(self:GetName().."Flash");
if ( self.casting ) then
self.value = self.value + elapsed;
if ( self.value >= self.maxValue ) then
self:SetValue(self.maxValue);
CastingBarFrame_FinishSpell(self, barSpark, barFlash);
return;
end
self:SetValue(self.value);
if ( barFlash ) then
barFlash:Hide();
end
if ( barSpark ) then
local sparkPosition = (self.value / self.maxValue) * self:GetWidth();
barSpark:SetPoint("CENTER", self, "LEFT", sparkPosition, 2);
end
elseif ( self.channeling ) then
self.value = self.value - elapsed;
if ( self.value <= 0 ) then
CastingBarFrame_FinishSpell(self, barSpark, barFlash);
return;
end
self:SetValue(self.value);
if ( barFlash ) then
barFlash:Hide();
end
elseif ( GetTime() < self.holdTime ) then
return;
elseif ( self.flash ) then
local alpha = 0;
if ( barFlash ) then
alpha = barFlash:GetAlpha() + CASTING_BAR_FLASH_STEP;
end
if ( alpha < 1 ) then
if ( barFlash ) then
barFlash:SetAlpha(alpha);
end
else
if ( barFlash ) then
barFlash:SetAlpha(1.0);
end
self.flash = nil;
end
elseif ( self.fadeOut ) then
local alpha = self:GetAlpha() - CASTING_BAR_ALPHA_STEP;
if ( alpha > 0 ) then
self:SetAlpha(alpha);
else
self.fadeOut = nil;
self:Hide();
end
end
end
function CastingBarFrame_FinishSpell (self, barSpark, barFlash)
self:SetStatusBarColor(0.0, 1.0, 0.0);
if ( barSpark ) then
barSpark:Hide();
end
if ( barFlash ) then
barFlash:SetAlpha(0.0);
barFlash:Show();
end
self.flash = 1;
self.fadeOut = 1;
self.casting = nil;
self.channeling = nil;
end
| gpl-2.0 |
Canaan-Creative/luci | libs/lucid-rpc/luasrc/lucid/rpc/server.lua | 52 | 8197 | --[[
LuCI - Lua Development Framework
Copyright 2009 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]
local ipairs, pairs = ipairs, pairs
local tostring, tonumber = tostring, tonumber
local pcall, assert, type, unpack = pcall, assert, type, unpack
local nixio = require "nixio"
local json = require "luci.json"
local util = require "luci.util"
local table = require "table"
local ltn12 = require "luci.ltn12"
--- RPC daemom.
-- @cstyle instance
module "luci.lucid.rpc.server"
RQLIMIT = 32 * nixio.const.buffersize
VERSION = "1.0"
ERRNO_PARSE = -32700
ERRNO_INVALID = -32600
ERRNO_UNKNOWN = -32001
ERRNO_TIMEOUT = -32000
ERRNO_NOTFOUND = -32601
ERRNO_NOACCESS = -32002
ERRNO_INTERNAL = -32603
ERRNO_NOSUPPORT = -32003
ERRMSG = {
[ERRNO_PARSE] = "Parse error.",
[ERRNO_INVALID] = "Invalid request.",
[ERRNO_TIMEOUT] = "Connection timeout.",
[ERRNO_UNKNOWN] = "Unknown error.",
[ERRNO_NOTFOUND] = "Method not found.",
[ERRNO_NOACCESS] = "Access denied.",
[ERRNO_INTERNAL] = "Internal error.",
[ERRNO_NOSUPPORT] = "Operation not supported."
}
--- Create an RPC method wrapper.
-- @class function
-- @param method Lua function
-- @param description Method description
-- @return Wrapped RPC method
Method = util.class()
--- Create an extended wrapped RPC method.
-- @class function
-- @param method Lua function
-- @param description Method description
-- @return Wrapped RPC method
function Method.extended(...)
local m = Method(...)
m.call = m.xcall
return m
end
function Method.__init__(self, method, description)
self.description = description
self.method = method
end
--- Extended call the associated function.
-- @param session Session storage
-- @param argv Request parameters
-- @return function call response
function Method.xcall(self, session, argv)
return self.method(session, unpack(argv))
end
--- Standard call the associated function.
-- @param session Session storage
-- @param argv Request parameters
-- @return function call response
function Method.call(self, session, argv)
return self.method(unpack(argv))
end
--- Process a given request and create a JSON response.
-- @param session Session storage
-- @param request Requested method
-- @param argv Request parameters
function Method.process(self, session, request, argv)
local stat, result = pcall(self.call, self, session, argv)
if stat then
return { result=result }
else
return { error={
code=ERRNO_UNKNOWN,
message=ERRMSG[ERRNO_UNKNOWN],
data=result
} }
end
end
-- Remap IPv6-IPv4-compatibility addresses to IPv4 addresses
local function remapipv6(adr)
local map = "::ffff:"
if adr:sub(1, #map) == map then
return adr:sub(#map+1)
else
return adr
end
end
--- Create an RPC module.
-- @class function
-- @param description Method description
-- @return RPC module
Module = util.class()
function Module.__init__(self, description)
self.description = description
self.handler = {}
end
--- Add a handler.
-- @param k key
-- @param v handler
function Module.add(self, k, v)
self.handler[k] = v
end
--- Add an access restriction.
-- @param restriction Restriction specification
function Module.restrict(self, restriction)
if not self.restrictions then
self.restrictions = {restriction}
else
self.restrictions[#self.restrictions+1] = restriction
end
end
--- Enforce access restrictions.
-- @param request Request object
-- @return nil or HTTP statuscode, table of headers, response source
function Module.checkrestricted(self, session, request, argv)
if not self.restrictions then
return
end
for _, r in ipairs(self.restrictions) do
local stat = true
if stat and r.interface then -- Interface restriction
if not session.localif then
for _, v in ipairs(session.env.interfaces) do
if v.addr == session.localaddr then
session.localif = v.name
break
end
end
end
if r.interface ~= session.localif then
stat = false
end
end
if stat and r.user and session.user ~= r.user then -- User restriction
stat = false
end
if stat then
return
end
end
return {error={code=ERRNO_NOACCESS, message=ERRMSG[ERRNO_NOACCESS]}}
end
--- Register a handler, submodule or function.
-- @param m entity
-- @param descr description
-- @return Module (self)
function Module.register(self, m, descr)
descr = descr or {}
for k, v in pairs(m) do
if util.instanceof(v, Method) then
self.handler[k] = v
elseif type(v) == "table" then
self.handler[k] = Module()
self.handler[k]:register(v, descr[k])
elseif type(v) == "function" then
self.handler[k] = Method(v, descr[k])
end
end
return self
end
--- Process a request.
-- @param session Session storage
-- @param request Request object
-- @param argv Request parameters
-- @return JSON response object
function Module.process(self, session, request, argv)
local first, last = request:match("^([^.]+).?(.*)$")
local stat = self:checkrestricted(session, request, argv)
if stat then -- Access Denied
return stat
end
local hndl = first and self.handler[first]
if not hndl then
return {error={code=ERRNO_NOTFOUND, message=ERRMSG[ERRNO_NOTFOUND]}}
end
session.chain[#session.chain+1] = self
return hndl:process(session, last, argv)
end
--- Create a server object.
-- @class function
-- @param root Root module
-- @return Server object
Server = util.class()
function Server.__init__(self, root)
self.root = root
end
--- Get the associated root module.
-- @return Root module
function Server.get_root(self)
return self.root
end
--- Set a new root module.
-- @param root Root module
function Server.set_root(self, root)
self.root = root
end
--- Create a JSON reply.
-- @param jsonrpc JSON-RPC version
-- @param id Message id
-- @param res Result
-- @param err Error
-- @reutrn JSON response source
function Server.reply(self, jsonrpc, id, res, err)
id = id or json.null
-- 1.0 compatibility
if jsonrpc ~= "2.0" then
jsonrpc = nil
res = res or json.null
err = err or json.null
end
return json.Encoder(
{id=id, result=res, error=err, jsonrpc=jsonrpc}, BUFSIZE
):source()
end
--- Handle a new client connection.
-- @param client client socket
-- @param env superserver environment
function Server.process(self, client, env)
local decoder
local sinkout = client:sink()
client:setopt("socket", "sndtimeo", 90)
client:setopt("socket", "rcvtimeo", 90)
local close = false
local session = {server = self, chain = {}, client = client, env = env,
localaddr = remapipv6(client:getsockname())}
local req, stat, response, result, cb
repeat
local oldchunk = decoder and decoder.chunk
decoder = json.ActiveDecoder(client:blocksource(nil, RQLIMIT))
decoder.chunk = oldchunk
result, response, cb = nil, nil, nil
-- Read one request
stat, req = pcall(decoder.get, decoder)
if stat then
if type(req) == "table" and type(req.method) == "string"
and (not req.params or type(req.params) == "table") then
req.params = req.params or {}
result, cb = self.root:process(session, req.method, req.params)
if type(result) == "table" then
if req.id ~= nil then
response = self:reply(req.jsonrpc, req.id,
result.result, result.error)
end
close = result.close
else
if req.id ~= nil then
response = self:reply(req.jsonrpc, req.id, nil,
{code=ERRNO_INTERNAL, message=ERRMSG[ERRNO_INTERNAL]})
end
end
else
response = self:reply(req.jsonrpc, req.id,
nil, {code=ERRNO_INVALID, message=ERRMSG[ERRNO_INVALID]})
end
else
if nixio.errno() ~= nixio.const.EAGAIN then
response = self:reply("2.0", nil,
nil, {code=ERRNO_PARSE, message=ERRMSG[ERRNO_PARSE]})
--[[else
response = self:reply("2.0", nil,
nil, {code=ERRNO_TIMEOUT, message=ERRMSG_TIMEOUT})]]
end
close = true
end
if response then
ltn12.pump.all(response, sinkout)
end
if cb then
close = cb(client, session, self) or close
end
until close
client:shutdown()
client:close()
end
| apache-2.0 |
mcanthony/bgfx | scripts/example-common.lua | 6 | 1943 | --
-- Copyright 2010-2015 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
project ("example-common")
uuid ("21cc0e26-bf62-11e2-a01e-0291bd4c8125")
kind "StaticLib"
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty"),
}
files {
path.join(BGFX_DIR, "3rdparty/ib-compress/**.cpp"),
path.join(BGFX_DIR, "3rdparty/ib-compress/**.h"),
path.join(BGFX_DIR, "3rdparty/ocornut-imgui/**.cpp"),
path.join(BGFX_DIR, "3rdparty/ocornut-imgui/**.h"),
path.join(BGFX_DIR, "examples/common/**.cpp"),
path.join(BGFX_DIR, "examples/common/**.h"),
}
if _OPTIONS["with-scintilla"] then
defines {
"SCI_NAMESPACE",
"SCI_LEXER",
}
buildoptions {
-- "-Wno-missing-field-initializers",
}
includedirs {
path.join(BGFX_DIR, "3rdparty/scintilla/include"),
path.join(BGFX_DIR, "3rdparty/scintilla/lexlib"),
}
files {
path.join(BGFX_DIR, "3rdparty/scintilla/src/**.cxx"),
path.join(BGFX_DIR, "3rdparty/scintilla/src/**.h"),
path.join(BGFX_DIR, "3rdparty/scintilla/lexlib/**.cxx"),
path.join(BGFX_DIR, "3rdparty/scintilla/lexlib/**.h"),
path.join(BGFX_DIR, "3rdparty/scintilla/lexers/**.cxx"),
}
end
if _OPTIONS["with-sdl"] then
defines {
"ENTRY_CONFIG_USE_SDL=1",
}
includedirs {
"$(SDL2_DIR)/include",
}
end
if _OPTIONS["with-glfw"] then
defines {
"ENTRY_CONFIG_USE_GLFW=1",
}
end
configuration { "osx or ios*" }
files {
path.join(BGFX_DIR, "examples/common/**.mm"),
}
configuration { "winphone8* or winstore8*"}
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
premake.vstudio.splashpath = "../../../examples/runtime/images/SplashScreen.png"
| bsd-2-clause |
xponen/Zero-K | effects/debris.lua | 25 | 2772 | -- debris1
return {
["debris1"] = {
dirt = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
colormap = [[0.72 0.61 0.41 1 0 0 0 0.01]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.5, 0]],
numparticles = 20,
particlelife = 70,
particlelifespread = 10,
particlesize = 10,
particlesizespread = 10,
particlespeed = 15,
particlespeedspread = 5,
pos = [[0, 2, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[randdots]],
},
},
rocks = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
water = true,
properties = {
airdrag = 0.97,
colormap = [[0.72 0.61 0.41 1 0.72 0.61 0.41 1]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.5, 0]],
numparticles = 1,
particlelife = 70,
particlelifespread = 0,
particlesize = 5,
particlesizespread = 10,
particlespeed = 10,
particlespeedspread = 10,
pos = [[0, 1, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[debris]],
},
},
smallrocks = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
water = true,
properties = {
airdrag = 0.97,
colormap = [[0.72 0.61 0.41 1 0.72 0.61 0.41 1]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.5, 0]],
numparticles = 1,
particlelife = 70,
particlelifespread = 0,
particlesize = 5,
particlesizespread = 10,
particlespeed = 10,
particlespeedspread = 10,
pos = [[0, 1, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[debris2]],
},
},
},
}
| gpl-2.0 |
k-yak/arrow | arrow/archer.lua | 1 | 3196 | CLASS_archer = Core.class(Sprite)
function CLASS_archer:init(world, physics)
self.pack = TexturePack.new("frioArcher.txt", "frioArcher.png")
-- init texture animation loader and read animations...
self.archerLoader = CTNTAnimatorLoader.new()
-- read animation infos from file "frioArcher.tan" use texture pack defined in texturePack and center all sprites...
self.archerLoader:loadAnimations("frioArcher.tan", self.pack, true)
-- box2d
self.body = world:createBody{type = b2.DYNAMIC_BODY, position = {x = application:getContentWidth()/2, y = 0}}
item = "FrioArcher"
self.body.name = item
physics:addFixture(self.body, item)
-- allow to callback on collision
self.body.parent = self
self.anim = CTNTAnimator.new(self.archerLoader)
self.anim:setAnimation("STAND_RIGHT")
self.anim:setSpeed(180)
self.anim:addToParent(self)
self.anim:playAnimation()
self.angle = 0
self.isJumping = false
self.fly = false
self.shooting = false
self:setPosition(self.body:getPosition())
self.nbArrow = 3
end
function CLASS_archer:move(direction, speed)
if math.cos (direction) < 0 then
self.angle = 3.14
else
self.angle = 0
end
if math.deg(direction) < 155 and math.deg(direction) > 105 then
print("down")
end
local xPos, yPos = self.body:getPosition()
xPos = xPos + math.cos (direction) * speed
if self.angle == 0 then
self.anim:setAnimation("WALK_RIGHT")
else
self.anim:setAnimation("WALK_LEFT")
end
self.body:setPosition(xPos, yPos)
end
function CLASS_archer:jump(direction)
if self.isJumping == false and self.fly == false then
self.isJumping = true
end
end
jump = 0
function CLASS_archer:onEnterFrame(Event)
local xPos, yPos = self.body:getPosition()
if self.isJumping == true then
print("jump")
self.body:setLinearVelocity(0,-12)
self.isJumping = false
self.fly = true
jump = 10
elseif jump ~= 0 then
jump = jump - 1
else
self.body:setLinearVelocity(0,9)
end
if xPos > application:getLogicalHeight() then
xPos = 0
elseif xPos < 0 then
xPos = application:getLogicalHeight()
end
if yPos > application:getLogicalWidth() then
yPos = 0
--self.body:setLinearVelocity(0,10)
elseif yPos < 0 then
yPos = application:getLogicalWidth()
end
self.body:setPosition(xPos, yPos)
--self.world:step(1/60, 8, 3)
self:setPosition(xPos, yPos)
--self:setRotation(self.body:getAngle() * 180 / math.pi)
end
function CLASS_archer:stop(direction)
if math.cos (direction) < 0 then
self.anim:setAnimation("STAND_LEFT")
else
self.anim:setAnimation("STAND_RIGHT")
end
end
function CLASS_archer:getClassName()
return "archer"
end
function CLASS_archer:touchFloor()
self.fly = false
end
function CLASS_archer:toucheByArrow()
local xPos, yPos = self:getPosition()
print(yPos)
self.anim:setAnimation("DEAD")
end
function CLASS_archer:shoot(orientation)
self.shooting = true
if orientation == "left" then
self.anim:setAnimation("SHOOT_LEFT")
else
self.anim:setAnimation("SHOOT_RIGHT")
end
end
function CLASS_archer:stopShoot(orientation)
self.shooting = false
if orientation == "left" then
self.anim:setAnimation("STAND_LEFT")
else
self.anim:setAnimation("STAND_RIGHT")
end
end | mit |
mumingv/redis | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
alastair-robertson/awesome | lib/menubar/init.lua | 1 | 14460 | ---------------------------------------------------------------------------
--- Menubar module, which aims to provide a freedesktop menu alternative
--
-- List of menubar keybindings:
-- ---
--
-- * "Left" | "C-j" select an item on the left
-- * "Right" | "C-k" select an item on the right
-- * "Backspace" exit the current category if we are in any
-- * "Escape" exit the current directory or exit menubar
-- * "Home" select the first item
-- * "End" select the last
-- * "Return" execute the entry
-- * "C-Return" execute the command with awful.spawn
-- * "C-M-Return" execute the command in a terminal
--
-- @author Alexander Yakushev <yakushev.alex@gmail.com>
-- @copyright 2011-2012 Alexander Yakushev
-- @release @AWESOME_VERSION@
-- @module menubar
---------------------------------------------------------------------------
-- Grab environment we need
local capi = {
client = client,
mouse = mouse,
screen = screen
}
local awful = require("awful")
local common = require("awful.widget.common")
local theme = require("beautiful")
local wibox = require("wibox")
local function get_screen(s)
return s and capi.screen[s]
end
-- menubar
local menubar = { mt = {}, menu_entries = {} }
menubar.menu_gen = require("menubar.menu_gen")
menubar.utils = require("menubar.utils")
local compute_text_width = menubar.utils.compute_text_width
-- Options section
--- When true the .desktop files will be reparsed only when the
-- extension is initialized. Use this if menubar takes much time to
-- open.
menubar.cache_entries = true
--- When true the categories will be shown alongside application
-- entries.
menubar.show_categories = true
--- Specifies the geometry of the menubar. This is a table with the keys
-- x, y, width and height. Missing values are replaced via the screen's
-- geometry. However, missing height is replaced by the font size.
menubar.geometry = { width = nil,
height = nil,
x = nil,
y = nil }
--- Width of blank space left in the right side.
menubar.right_margin = theme.xresources.apply_dpi(8)
--- Label used for "Next page", default "▶▶".
menubar.right_label = "▶▶"
--- Label used for "Previous page", default "◀◀".
menubar.left_label = "◀◀"
-- awful.widget.common.list_update adds three times a margin of dpi(4)
-- for each item:
local list_interspace = theme.xresources.apply_dpi(4) * 3
--- Allows user to specify custom parameters for prompt.run function
-- (like colors).
menubar.prompt_args = {}
-- Private section
local current_item = 1
local previous_item = nil
local current_category = nil
local shownitems = nil
local instance = { prompt = nil,
widget = nil,
wibox = nil }
local common_args = { w = wibox.layout.fixed.horizontal(),
data = setmetatable({}, { __mode = 'kv' }) }
--- Wrap the text with the color span tag.
-- @param s The text.
-- @param c The desired text color.
-- @return the text wrapped in a span tag.
local function colortext(s, c)
return "<span color='" .. awful.util.ensure_pango_color(c) .. "'>" .. s .. "</span>"
end
--- Get how the menu item should be displayed.
-- @param o The menu item.
-- @return item name, item background color, background image, item icon.
local function label(o)
if o.focused then
return colortext(o.name, (theme.menu_fg_focus or theme.fg_focus)), (theme.menu_bg_focus or theme.bg_focus), nil, o.icon
else
return o.name, (theme.menu_bg_normal or theme.bg_normal), nil, o.icon
end
end
local function load_count_table()
local count_file_name = awful.util.getdir("cache") .. "/menu_count_file"
local count_file = io.open (count_file_name, "r")
local count_table = {}
-- read count file
if count_file then
io.input (count_file)
for line in io.lines() do
local name, count = string.match(line, "([^;]+);([^;]+)")
if name ~= nil and count ~= nil then
count_table[name] = count
end
end
end
return count_table
end
local function write_count_table(count_table)
local count_file_name = awful.util.getdir("cache") .. "/menu_count_file"
local count_file = io.open (count_file_name, "w")
if count_file then
io.output (count_file)
for name,count in pairs(count_table) do
local str = string.format("%s;%d\n", name, count)
io.write(str)
end
io.flush()
end
end
--- Perform an action for the given menu item.
-- @param o The menu item.
-- @return if the function processed the callback, new awful.prompt command, new awful.prompt prompt text.
local function perform_action(o)
if not o then return end
if o.key then
current_category = o.key
local new_prompt = shownitems[current_item].name .. ": "
previous_item = current_item
current_item = 1
return true, "", new_prompt
elseif shownitems[current_item].cmdline then
awful.spawn(shownitems[current_item].cmdline)
-- load count_table from cache file
local count_table = load_count_table()
-- increase count
local curname = shownitems[current_item].name
if count_table[curname] ~= nil then
count_table[curname] = count_table[curname] + 1
else
count_table[curname] = 1
end
-- write updated count table to cache file
write_count_table(count_table)
-- Let awful.prompt execute dummy exec_callback and
-- done_callback to stop the keygrabber properly.
return false
end
end
-- Cut item list to return only current page.
-- @tparam table all_items All items list.
-- @tparam str query Search query.
-- @tparam number|screen scr Screen
-- @return table List of items for current page.
local function get_current_page(all_items, query, scr)
scr = get_screen(scr)
if not instance.prompt.width then
instance.prompt.width = compute_text_width(instance.prompt.prompt, scr)
end
if not menubar.left_label_width then
menubar.left_label_width = compute_text_width(menubar.left_label, scr)
end
if not menubar.right_label_width then
menubar.right_label_width = compute_text_width(menubar.right_label, scr)
end
local available_space = instance.geometry.width - menubar.right_margin -
menubar.right_label_width - menubar.left_label_width -
compute_text_width(query, scr) - instance.prompt.width
local width_sum = 0
local current_page = {}
for i, item in ipairs(all_items) do
item.width = item.width or
compute_text_width(item.name, scr) +
(item.icon and instance.geometry.height or 0) + list_interspace
if width_sum + item.width > available_space then
if current_item < i then
table.insert(current_page, { name = menubar.right_label, icon = nil })
break
end
current_page = { { name = menubar.left_label, icon = nil }, item, }
width_sum = item.width
else
table.insert(current_page, item)
width_sum = width_sum + item.width
end
end
return current_page
end
--- Update the menubar according to the command entered by user.
-- @tparam str query Search query.
-- @tparam number|screen scr Screen
local function menulist_update(query, scr)
query = query or ""
shownitems = {}
local pattern = awful.util.query_to_pattern(query)
local match_inside = {}
-- First we add entries which names match the command from the
-- beginning to the table shownitems, and the ones that contain
-- command in the middle to the table match_inside.
-- Add the categories
if menubar.show_categories then
for _, v in pairs(menubar.menu_gen.all_categories) do
v.focused = false
if not current_category and v.use then
if string.match(v.name, pattern) then
if string.match(v.name, "^" .. pattern) then
table.insert(shownitems, v)
else
table.insert(match_inside, v)
end
end
end
end
end
local count_table = load_count_table()
local command_list = {}
-- Add the applications according to their name and cmdline
for _, v in ipairs(menubar.menu_entries) do
v.focused = false
if not current_category or v.category == current_category then
if string.match(v.name, pattern)
or string.match(v.cmdline, pattern) then
if string.match(v.name, "^" .. pattern)
or string.match(v.cmdline, "^" .. pattern) then
v.count = 0
-- use count from count_table if present
if string.len(pattern) > 0 and count_table[v.name] ~= nil then
v.count = tonumber(count_table[v.name])
end
table.insert (command_list, v)
end
end
end
end
local function compare_counts(a,b)
return a.count > b.count
end
-- sort command_list by count (highest first)
table.sort(command_list, compare_counts)
-- copy into showitems
shownitems = command_list
if #shownitems > 0 then
-- Insert a run item value as the last choice
table.insert(shownitems, { name = "Exec: " .. query, cmdline = query, icon = nil })
if current_item > #shownitems then
current_item = #shownitems
end
shownitems[current_item].focused = true
else
table.insert(shownitems, { name = "", cmdline = query, icon = nil })
end
common.list_update(common_args.w, nil, label,
common_args.data,
get_current_page(shownitems, query, scr))
end
--- Create the menubar wibox and widgets.
-- @tparam[opt] screen scr Screen.
local function initialize(scr)
instance.wibox = wibox({})
instance.widget = menubar.get(scr)
instance.wibox.ontop = true
instance.prompt = awful.widget.prompt()
local layout = wibox.layout.fixed.horizontal()
layout:add(instance.prompt)
layout:add(instance.widget)
instance.wibox:set_widget(layout)
end
--- Refresh menubar's cache by reloading .desktop files.
-- @tparam[opt] screen scr Screen.
function menubar.refresh(scr)
menubar.menu_gen.generate(function(entries)
menubar.menu_entries = entries
menulist_update(nil, scr)
end)
end
--- Awful.prompt keypressed callback to be used when the user presses a key.
-- @param mod Table of key combination modifiers (Control, Shift).
-- @param key The key that was pressed.
-- @param comm The current command in the prompt.
-- @return if the function processed the callback, new awful.prompt command, new awful.prompt prompt text.
local function prompt_keypressed_callback(mod, key, comm)
if key == "Left" or (mod.Control and key == "j") then
current_item = math.max(current_item - 1, 1)
return true
elseif key == "Right" or (mod.Control and key == "k") then
current_item = current_item + 1
return true
elseif key == "BackSpace" then
if comm == "" and current_category then
current_category = nil
current_item = previous_item
return true, nil, "Run: "
end
elseif key == "Escape" then
if current_category then
current_category = nil
current_item = previous_item
return true, nil, "Run: "
end
elseif key == "Home" then
current_item = 1
return true
elseif key == "End" then
current_item = #shownitems
return true
elseif key == "Return" or key == "KP_Enter" then
if mod.Control then
current_item = #shownitems
if mod.Mod1 then
-- add a terminal to the cmdline
shownitems[current_item].cmdline = menubar.utils.terminal
.. " -e " .. shownitems[current_item].cmdline
end
end
return perform_action(shownitems[current_item])
end
return false
end
--- Show the menubar on the given screen.
-- @param scr Screen.
function menubar.show(scr)
if not instance.wibox then
initialize(scr)
elseif instance.wibox.visible then -- Menu already shown, exit
return
elseif not menubar.cache_entries then
menubar.refresh(scr)
end
-- Set position and size
scr = scr or awful.screen.focused() or 1
scr = get_screen(scr)
local scrgeom = capi.screen[scr].workarea
local geometry = menubar.geometry
instance.geometry = {x = geometry.x or scrgeom.x,
y = geometry.y or scrgeom.y,
height = geometry.height or awful.util.round(theme.get_font_height() * 1.5),
width = geometry.width or scrgeom.width}
instance.wibox:geometry(instance.geometry)
current_item = 1
current_category = nil
menulist_update(nil, scr)
local prompt_args = menubar.prompt_args or {}
prompt_args.prompt = "Run: "
awful.prompt.run(prompt_args, instance.prompt.widget,
function() end, -- exe_callback function set to do nothing
awful.completion.shell, -- completion_callback
awful.util.get_cache_dir() .. "/history_menu",
nil,
menubar.hide, function(query) menulist_update(query, scr) end,
prompt_keypressed_callback
)
instance.wibox.visible = true
end
--- Hide the menubar.
function menubar.hide()
instance.wibox.visible = false
end
--- Get a menubar wibox.
-- @tparam[opt] screen scr Screen.
-- @return menubar wibox.
function menubar.get(scr)
menubar.refresh(scr)
-- Add to each category the name of its key in all_categories
for k, v in pairs(menubar.menu_gen.all_categories) do
v.key = k
end
return common_args.w
end
function menubar.mt.__call(_, ...)
return menubar.get(...)
end
return setmetatable(menubar, menubar.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
Vermeille/kong | spec/03-plugins/05-galileo/01-alf_spec.lua | 2 | 23004 | _G.ngx = require "spec.03-plugins.05-galileo.ngx"
-- asserts if an array contains a given table
local function contains(state, args)
local entry, t = unpack(args)
for i = 1, #t do
if pcall(assert.same, entry, t[i]) then
return true
end
end
return false
end
local say = require "say"
local luassert = require "luassert"
say:set("assertion.contains.positive", "Should contain")
say:set("assertion.contains.negative", "Should not contain")
luassert:register("assertion", "contains", contains,
"assertion.contains.positive",
"assertion.contains.negative")
local alf_serializer = require "kong.plugins.galileo.alf"
-- since our module caches ngx's global functions, this is a
-- hacky utility to reload it, allowing us to send different
-- input sets to the serializer.
local function reload_alf_serializer()
package.loaded["kong.plugins.galileo.alf"] = nil
-- FIXME: temporary double-loading of the cjson module
-- for the encoding JSON as empty array tests in the
-- serialize() suite.
-- remove once https://github.com/openresty/lua-cjson/pull/16
-- is included in a formal OpenResty release.
package.loaded["cjson"] = nil
package.loaded["cjson.safe"] = nil
require "cjson.safe"
require "cjson"
alf_serializer = require "kong.plugins.galileo.alf"
end
---------------------------
-- Serialization unit tests
---------------------------
describe("ALF serializer", function()
local _ngx
before_each(function()
_ngx = {
status = 200,
var = {
server_protocol = "HTTP/1.1",
scheme = "https",
host = "mockbin.com",
request_uri = "/request/path",
request_length = 32,
remote_addr = "127.0.0.1"
},
ctx = {
KONG_PROXY_LATENCY = 3,
KONG_WAITING_TIME = 15,
KONG_RECEIVE_TIME = 25
}
}
end)
it("sanity", function()
local alf = alf_serializer.new()
assert.is_nil(alf.log_bodies)
assert.equal(0, #alf.entries)
alf = alf_serializer.new(true)
assert.True(alf.log_bodies)
end)
describe("add_entry()", function()
it("adds an entry", function()
local alf = alf_serializer.new(nil, "10.10.10.10")
local entry = assert(alf:add_entry(_ngx))
assert.matches("%d%d%d%d%-%d%d%-%d%dT%d%d:%d%d:%d%dZ", entry.startedDateTime)
assert.equal("10.10.10.10", entry.serverIPAddress)
assert.equal("127.0.0.1", entry.clientIPAddress)
assert.is_table(entry.request)
assert.is_table(entry.response)
assert.is_table(entry.timings)
assert.is_number(entry.time)
end)
it("appends the entry to the 'entries' table", function()
local alf = alf_serializer.new()
for i = 1, 10 do
assert(alf:add_entry(_ngx))
assert.equal(i, #alf.entries)
end
end)
it("returns the number of entries", function()
local alf = alf_serializer.new()
for i = 1, 10 do
local entry, n = assert(alf:add_entry(_ngx))
assert.equal(i, n)
assert.truthy(entry)
end
end)
describe("request", function()
it("captures info", function()
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.equal("HTTP/1.1", entry.request.httpVersion)
assert.equal("GET", entry.request.method)
assert.equal("https://mockbin.com/request/path", entry.request.url)
assert.is_table(entry.request.headers)
assert.is_table(entry.request.queryString)
--assert.is_table(entry.request.postData) -- none by default
assert.is_number(entry.request.headersSize)
assert.is_boolean(entry.request.bodyCaptured)
assert.is_number(entry.request.bodySize)
end)
it("captures querystring info", function()
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.contains({name = "hello", value = "world"}, entry.request.queryString)
assert.contains({name = "foobar", value = "baz"}, entry.request.queryString)
end)
it("captures headers info", function()
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.contains({name = "accept", value = "application/json"}, entry.request.headers)
assert.contains({name = "host", value = "mockbin.com"}, entry.request.headers)
assert.equal(84, entry.request.headersSize)
end)
it("handles headers with multiple values", function()
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.contains({
name = "accept",
value = "application/json"
}, entry.request.headers)
assert.contains({
name = "accept",
value = "application/x-www-form-urlencoded"
}, entry.request.headers)
assert.contains({
name = "host",
value = "mockbin.com"
}, entry.request.headers)
end)
end)
describe("response", function()
it("captures info", function()
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.equal(200, entry.response.status)
assert.is_string(entry.response.statusText) -- can't get
assert.is_string(entry.response.httpVersion) -- can't get
assert.is_table(entry.response.headers)
--assert.is_table(entry.response.content) -- none by default
assert.is_number(entry.response.headersSize) -- can't get
assert.is_boolean(entry.response.bodyCaptured)
assert.is_number(entry.response.bodySize)
end)
it("captures headers info", function()
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.contains({
name = "connection",
value = "close"
}, entry.response.headers)
assert.contains({
name = "content-type",
value = "application/json"
}, entry.response.headers)
assert.contains({
name = "content-length",
value = "934"
}, entry.response.headers)
assert.equal(0, entry.response.headersSize) -- can't get
end)
it("handles headers with multiple values", function()
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.contains({
name = "content-type",
value = "application/json"
}, entry.response.headers)
assert.contains({
name = "content-type",
value = "application/x-www-form-urlencoded"
}, entry.response.headers)
end)
end)
describe("request body", function()
local get_headers
setup(function()
get_headers = _G.ngx.req.get_headers
end)
teardown(function()
_G.ngx.req.get_headers = get_headers
reload_alf_serializer()
end)
it("captures body info if and only if asked for", function()
local body_str = "hello=world&foo=bar"
_G.ngx.resp.get_headers = function()
return {}
end
reload_alf_serializer()
local alf_with_body = alf_serializer.new(true)
local alf_without_body = alf_serializer.new(false) -- no bodies
local entry1 = assert(alf_with_body:add_entry(_ngx, body_str))
assert.is_table(entry1.request.postData)
assert.same({
text = "base64_hello=world&foo=bar",
encoding = "base64",
mimeType = "application/octet-stream"
}, entry1.request.postData)
local entry2 = assert(alf_without_body:add_entry(_ngx, body_str))
assert.is_nil(entry2.request.postData)
end)
it("captures bodySize from Content-Length if not logging bodies", function()
_G.ngx.req.get_headers = function()
return {["content-length"] = "38"}
end
reload_alf_serializer()
local alf = alf_serializer.new() -- log_bodies disabled
local entry = assert(alf:add_entry(_ngx)) -- no body str
assert.equal(38, entry.request.bodySize)
end)
it("captures bodySize reading the body if logging bodies", function()
local body_str = "hello=world"
_G.ngx.req.get_headers = function()
return {["content-length"] = "3800"}
end
reload_alf_serializer()
local alf = alf_serializer.new(true) -- log_bodies enabled
local entry = assert(alf:add_entry(_ngx, body_str))
assert.equal(#body_str, entry.request.bodySize)
end)
it("zeroes bodySize if no body logging or Content-Length", function()
_G.ngx.req.get_headers = function()
return {}
end
reload_alf_serializer()
local alf = alf_serializer.new() -- log_bodies disabled
local entry = assert(alf:add_entry(_ngx)) -- no body str
assert.equal(0, entry.request.bodySize)
end)
it("ignores nil body string (no postData)", function()
local alf = alf_serializer.new(true)
local entry = assert(alf:add_entry(_ngx, nil))
assert.is_nil(entry.request.postData)
end)
it("captures postData.mimeType", function()
local body_str = [[{"hello": "world"}]]
_G.ngx.req.get_headers = function()
return {["content-type"] = "application/json"}
end
reload_alf_serializer()
local alf = alf_serializer.new(true)
local entry = assert(alf:add_entry(_ngx, body_str))
assert.equal("application/json", entry.request.postData.mimeType)
end)
it("bodyCaptured is always set from the given headers", function()
-- this behavior tries to stay compliant with RFC 2616 by
-- determining if the request has a body from its headers,
-- instead of having to read it, which would defeat the purpose
-- of the 'log_bodies' option flag.
local alf = alf_serializer.new(true) -- log_bodies enabled
local entry = assert(alf:add_entry(_ngx)) -- no body str
assert.False(entry.request.bodyCaptured)
_G.ngx.req.get_headers = function()
return {["content-length"] = "38"}
end
reload_alf_serializer()
alf = alf_serializer.new() -- log_bodies disabled
entry = assert(alf:add_entry(_ngx)) -- no body str
assert.True(entry.request.bodyCaptured)
_G.ngx.req.get_headers = function()
return {["transfer-encoding"] = "chunked"}
end
reload_alf_serializer()
alf = alf_serializer.new(true)
entry = assert(alf:add_entry(_ngx))
assert.True(entry.request.bodyCaptured)
_G.ngx.req.get_headers = function()
return {["content-type"] = "multipart/byteranges"}
end
reload_alf_serializer()
alf = alf_serializer.new(false)
entry = assert(alf:add_entry(_ngx))
assert.True(entry.request.bodyCaptured)
_G.ngx.req.get_headers = function()
return {["content-length"] = 0}
end
reload_alf_serializer()
alf = alf_serializer.new(false)
entry = assert(alf:add_entry(_ngx))
assert.False(entry.request.bodyCaptured)
end)
it("bodyCaptures handles headers with multiple values", function()
-- it uses the last header value
_G.ngx.req.get_headers = function()
return {["content-length"] = {"0", "38"}}
end
reload_alf_serializer()
local alf = alf_serializer.new(true)
local entry = assert(alf:add_entry(_ngx))
assert.True(entry.request.bodyCaptured)
end)
end)
describe("response body", function()
local get_headers
setup(function()
get_headers = _G.ngx.resp.get_headers
end)
teardown(function()
_G.ngx.resp.get_headers = get_headers
reload_alf_serializer()
end)
it("captures body info if and only if asked for", function()
local body_str = "message=hello"
_G.ngx.resp.get_headers = function()
return {}
end
reload_alf_serializer()
local alf_with_body = alf_serializer.new(true)
local alf_without_body = alf_serializer.new(false) -- no bodies
local entry1 = assert(alf_with_body:add_entry(_ngx, nil, body_str))
assert.is_table(entry1.response.content)
assert.same({
text = "base64_message=hello",
encoding = "base64",
mimeType = "application/octet-stream"
}, entry1.response.content)
local entry2 = assert(alf_without_body:add_entry(_ngx, body_str))
assert.is_nil(entry2.response.postData)
end)
it("captures bodySize from Content-Length if not logging bodies", function()
_G.ngx.resp.get_headers = function()
return {["content-length"] = "38"}
end
reload_alf_serializer()
local alf = alf_serializer.new() -- log_bodies disabled
local entry = assert(alf:add_entry(_ngx)) -- no body str
assert.equal(38, entry.response.bodySize)
end)
it("captures bodySize reading the body if logging bodies", function()
local body_str = "hello=world"
_G.ngx.resp.get_headers = function()
return {["content-length"] = "3800"}
end
reload_alf_serializer()
local alf = alf_serializer.new(true) -- log_bodies enabled
local entry = assert(alf:add_entry(_ngx, nil, body_str))
assert.equal(#body_str, entry.response.bodySize)
end)
it("zeroes bodySize if no body logging or Content-Length", function()
_G.ngx.resp.get_headers = function()
return {}
end
reload_alf_serializer()
local alf = alf_serializer.new() -- log_bodies disabled
local entry = assert(alf:add_entry(_ngx)) -- no body str
assert.equal(0, entry.response.bodySize)
end)
it("ignores nil body string (no response.content)", function()
local alf = alf_serializer.new(true)
local entry = assert(alf:add_entry(_ngx, nil, nil))
assert.is_nil(entry.response.content)
end)
it("captures content.mimeType", function()
local body_str = [[{"hello": "world"}]]
_G.ngx.resp.get_headers = function()
return {["content-type"] = "application/json"}
end
reload_alf_serializer()
local alf = alf_serializer.new(true)
local entry = assert(alf:add_entry(_ngx, nil, body_str))
assert.equal("application/json", entry.response.content.mimeType)
end)
it("bodyCaptured is always set from the given headers", function()
-- this behavior tries to stay compliant with RFC 2616 by
-- determining if the request has a body from its headers,
-- instead of having to read it, which would defeat the purpose
-- of the 'log_bodies' option flag.
local alf = alf_serializer.new(true) -- log_bodies enabled
local entry = assert(alf:add_entry(_ngx)) -- no body str
assert.False(entry.request.bodyCaptured)
_G.ngx.resp.get_headers = function()
return {["content-length"] = "38"}
end
reload_alf_serializer()
alf = alf_serializer.new("abcd", "test") -- log_bodies disabled
entry = assert(alf:add_entry(_ngx)) -- no body str
assert.True(entry.response.bodyCaptured)
_G.ngx.resp.get_headers = function()
return {["transfer-encoding"] = "chunked"}
end
reload_alf_serializer()
alf = alf_serializer.new(true)
entry = assert(alf:add_entry(_ngx))
assert.True(entry.response.bodyCaptured)
_G.ngx.resp.get_headers = function()
return {["content-type"] = "multipart/byteranges"}
end
reload_alf_serializer()
alf = alf_serializer.new(false)
entry = assert(alf:add_entry(_ngx))
assert.True(entry.response.bodyCaptured)
_G.ngx.resp.get_headers = function()
return {["content-length"] = "0"}
end
reload_alf_serializer()
alf = alf_serializer.new(false)
entry = assert(alf:add_entry(_ngx))
assert.False(entry.response.bodyCaptured)
end)
it("bodyCaptures handles headers with multiple values", function()
-- it uses the last header value
_G.ngx.resp.get_headers = function()
return {["content-length"] = {"0", "38"}}
end
reload_alf_serializer()
local alf = alf_serializer.new(true)
local entry = assert(alf:add_entry(_ngx))
assert.True(entry.response.bodyCaptured)
end)
end)
describe("timings", function()
it("computes timings", function()
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.equal(43, entry.time)
assert.equal(3, entry.timings.send)
assert.equal(15, entry.timings.wait)
assert.equal(25, entry.timings.receive)
end)
it("handles missing timer", function()
_ngx.ctx.KONG_WAITING_TIME = nil
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.equal(28, entry.time)
assert.equal(3, entry.timings.send)
assert.equal(0, entry.timings.wait)
assert.equal(25, entry.timings.receive)
end)
end)
it("bad self", function()
local entry, err = alf_serializer.add_entry({})
assert.equal("no entries table", err)
assert.is_nil(entry)
end)
it("missing captured _ngx", function()
local alf = alf_serializer.new()
local entry, err = alf_serializer.add_entry(alf)
assert.equal("arg #1 (_ngx) must be given", err)
assert.is_nil(entry)
end)
it("invalid body string", function()
local alf = alf_serializer.new()
local entry, err = alf:add_entry(_ngx, false)
assert.equal("arg #2 (req_body_str) must be a string", err)
assert.is_nil(entry)
end)
it("invalid response body string", function()
local alf = alf_serializer.new()
local entry, err = alf:add_entry(_ngx, nil, false)
assert.equal("arg #3 (resp_body_str) must be a string", err)
assert.is_nil(entry)
end)
it("assert incompatibilities with ALF 1.1.0", function()
local alf = alf_serializer.new()
local entry = assert(alf:add_entry(_ngx))
assert.equal("", entry.response.statusText) -- can't get
assert.equal(0, entry.response.headersSize) -- can't get
end)
end) -- add_entry()
describe("serialize()", function()
-- FIXME: temporary double-loading of the cjson module
-- for the encoding JSON as empty array tests in the
-- serialize() suite.
-- remove once https://github.com/openresty/lua-cjson/pull/16
-- is included in a formal OpenResty release.
reload_alf_serializer()
local cjson = require "cjson.safe"
it("returns a JSON encoded ALF object", function()
local alf = alf_serializer.new()
assert(alf:add_entry(_ngx))
assert(alf:add_entry(_ngx))
assert(alf:add_entry(_ngx))
local json_encoded_alf = assert(alf:serialize("abcd", "test"))
assert.is_string(json_encoded_alf)
local alf_o = assert(cjson.decode(json_encoded_alf))
assert.is_string(alf_o.version)
assert.equal(alf_serializer._ALF_VERSION, alf_o.version)
assert.is_string(alf_o.serviceToken)
assert.equal("abcd", alf_o.serviceToken)
assert.is_string(alf_o.environment)
assert.equal("test", alf_o.environment)
assert.is_table(alf_o.har)
assert.is_table(alf_o.har.log)
assert.is_table(alf_o.har.log.creator)
assert.is_string(alf_o.har.log.creator.name)
assert.equal(alf_serializer._ALF_CREATOR, alf_o.har.log.creator.name)
assert.is_string(alf_o.har.log.creator.version)
assert.equal(alf_serializer._VERSION, alf_o.har.log.creator.version)
assert.is_table(alf_o.har.log.entries)
assert.equal(3, #alf_o.har.log.entries)
end)
it("gives empty arrays and not empty objects", function()
_G.ngx.resp.get_headers = function()
return {}
end
_G.ngx.req.get_uri_args = function()
return {}
end
reload_alf_serializer()
local alf = alf_serializer.new()
assert(alf:add_entry(_ngx))
local json_encoded_alf = assert(alf:serialize("abcd"))
assert.matches('"headers":[]', json_encoded_alf, nil, true)
assert.matches('"queryString":[]', json_encoded_alf, nil, true)
end)
it("handles nil environment", function()
local alf = alf_serializer.new()
local json_encoded_alf = assert(alf:serialize("abcd"))
assert.is_string(json_encoded_alf)
local alf_o = assert(cjson.decode(json_encoded_alf))
assert.is_nil(alf_o.environment)
end)
it("returns an error on invalid token", function()
local alf = alf_serializer.new()
local alf_str, err = alf:serialize()
assert.equal("arg #1 (service_token) must be a string", err)
assert.is_nil(alf_str)
end)
it("returns an error on invalid environment", function()
local alf = alf_serializer.new()
local alf_str, err = alf:serialize("abcd", false)
assert.equal("arg #2 (environment) must be a string", err)
assert.is_nil(alf_str)
end)
it("bad self", function()
local alf = alf_serializer.new()
assert(alf:add_entry(_ngx))
local res, err = alf.serialize({})
assert.equal("no entries table", err)
assert.is_nil(res)
end)
it("limits ALF sizes to 20MB", function()
local alf = alf_serializer.new(true)
local body_12mb = string.rep(".", 21 * 2^20)
assert(alf:add_entry(_ngx, body_12mb))
local json_encoded_alf, err = alf:serialize("abcd")
assert.equal("ALF too large (> 20MB)", err)
assert.is_nil(json_encoded_alf)
end)
it("returns the number of entries in the serialized ALF", function()
local alf = alf_serializer.new()
assert(alf:add_entry(_ngx))
assert(alf:add_entry(_ngx))
assert(alf:add_entry(_ngx))
local _, n_entries = assert(alf:serialize("abcd", "test"))
assert.equal(3, n_entries)
end)
it("removes escaped slashes", function()
local alf = alf_serializer.new()
assert(alf:add_entry(_ngx))
local json_encoded_alf = assert(alf:serialize("abcd", "test"))
assert.matches([["value":"application/json"]], json_encoded_alf, nil, true)
assert.matches([["httpVersion":"HTTP/1.1"]], json_encoded_alf, nil, true)
assert.matches([["url":"https://mockbin.com/request/path"]], json_encoded_alf, nil, true)
end)
end)
describe("reset()", function()
it("empties an ALF", function()
local alf = alf_serializer.new()
assert(alf:add_entry(_ngx))
assert(alf:add_entry(_ngx))
assert.equal(2, #alf.entries)
alf:reset()
assert.equal(0, #alf.entries)
end)
end)
end)
| apache-2.0 |
DreamHacks/dreamdota | Plugins/src/core/constants.lua | 1 | 15372 | -- JASS CONSTANTS ID --
JASS_MAX_ARRAY_SIZE = Handle(8192)
PLAYER_NEUTRAL_PASSIVE = Handle(15)
PLAYER_NEUTRAL_AGGRESSIVE = Handle(12)
PLAYER_COLOR_RED = Handle(0)
PLAYER_COLOR_BLUE = Handle(1)
PLAYER_COLOR_CYAN = Handle(2)
PLAYER_COLOR_PURPLE = Handle(3)
PLAYER_COLOR_YELLOW = Handle(4)
PLAYER_COLOR_ORANGE = Handle(5)
PLAYER_COLOR_GREEN = Handle(6)
PLAYER_COLOR_PINK = Handle(7)
PLAYER_COLOR_LIGHT_GRAY = Handle(8)
PLAYER_COLOR_LIGHT_BLUE = Handle(9)
PLAYER_COLOR_AQUA = Handle(10)
PLAYER_COLOR_BROWN = Handle(11)
RACE_HUMAN = Handle(1)
RACE_ORC = Handle(2)
RACE_UNDEAD = Handle(3)
RACE_NIGHTELF = Handle(4)
RACE_DEMON = Handle(5)
RACE_OTHER = Handle(7)
PLAYER_GAME_RESULT_VICTORY = Handle(0)
PLAYER_GAME_RESULT_DEFEAT = Handle(1)
PLAYER_GAME_RESULT_TIE = Handle(2)
PLAYER_GAME_RESULT_NEUTRAL = Handle(3)
ALLIANCE_PASSIVE = Handle(0)
ALLIANCE_HELP_REQUEST = Handle(1)
ALLIANCE_HELP_RESPONSE = Handle(2)
ALLIANCE_SHARED_XP = Handle(3)
ALLIANCE_SHARED_SPELLS = Handle(4)
ALLIANCE_SHARED_VISION = Handle(5)
ALLIANCE_SHARED_CONTROL = Handle(6)
ALLIANCE_SHARED_ADVANCED_CONTROL= Handle(7)
ALLIANCE_RESCUABLE = Handle(8)
ALLIANCE_SHARED_VISION_FORCED = Handle(9)
VERSION_REIGN_OF_CHAOS = Handle(0)
VERSION_FROZEN_THRONE = Handle(1)
ATTACK_TYPE_NORMAL = Handle(0)
ATTACK_TYPE_MELEE = Handle(1)
ATTACK_TYPE_PIERCE = Handle(2)
ATTACK_TYPE_SIEGE = Handle(3)
ATTACK_TYPE_MAGIC = Handle(4)
ATTACK_TYPE_CHAOS = Handle(5)
ATTACK_TYPE_HERO = Handle(6)
DAMAGE_TYPE_UNKNOWN = Handle(0)
DAMAGE_TYPE_NORMAL = Handle(4)
DAMAGE_TYPE_ENHANCED = Handle(5)
DAMAGE_TYPE_FIRE = Handle(8)
DAMAGE_TYPE_COLD = Handle(9)
DAMAGE_TYPE_LIGHTNING = Handle(10)
DAMAGE_TYPE_POISON = Handle(11)
DAMAGE_TYPE_DISEASE = Handle(12)
DAMAGE_TYPE_DIVINE = Handle(13)
DAMAGE_TYPE_MAGIC = Handle(14)
DAMAGE_TYPE_SONIC = Handle(15)
DAMAGE_TYPE_ACID = Handle(16)
DAMAGE_TYPE_FORCE = Handle(17)
DAMAGE_TYPE_DEATH = Handle(18)
DAMAGE_TYPE_MIND = Handle(19)
DAMAGE_TYPE_PLANT = Handle(20)
DAMAGE_TYPE_DEFENSIVE = Handle(21)
DAMAGE_TYPE_DEMOLITION = Handle(22)
DAMAGE_TYPE_SLOW_POISON = Handle(23)
DAMAGE_TYPE_SPIRIT_LINK = Handle(24)
DAMAGE_TYPE_SHADOW_STRIKE = Handle(25)
DAMAGE_TYPE_UNIVERSAL = Handle(26)
WEAPON_TYPE_WHOKNOWS = Handle(0)
WEAPON_TYPE_METAL_LIGHT_CHOP = Handle(1)
WEAPON_TYPE_METAL_MEDIUM_CHOP = Handle(2)
WEAPON_TYPE_METAL_HEAVY_CHOP = Handle(3)
WEAPON_TYPE_METAL_LIGHT_SLICE = Handle(4)
WEAPON_TYPE_METAL_MEDIUM_SLICE = Handle(5)
WEAPON_TYPE_METAL_HEAVY_SLICE = Handle(6)
WEAPON_TYPE_METAL_MEDIUM_BASH = Handle(7)
WEAPON_TYPE_METAL_HEAVY_BASH = Handle(8)
WEAPON_TYPE_METAL_MEDIUM_STAB = Handle(9)
WEAPON_TYPE_METAL_HEAVY_STAB = Handle(10)
WEAPON_TYPE_WOOD_LIGHT_SLICE = Handle(11)
WEAPON_TYPE_WOOD_MEDIUM_SLICE = Handle(12)
WEAPON_TYPE_WOOD_HEAVY_SLICE = Handle(13)
WEAPON_TYPE_WOOD_LIGHT_BASH = Handle(14)
WEAPON_TYPE_WOOD_MEDIUM_BASH = Handle(15)
WEAPON_TYPE_WOOD_HEAVY_BASH = Handle(16)
WEAPON_TYPE_WOOD_LIGHT_STAB = Handle(17)
WEAPON_TYPE_WOOD_MEDIUM_STAB = Handle(18)
WEAPON_TYPE_CLAW_LIGHT_SLICE = Handle(19)
WEAPON_TYPE_CLAW_MEDIUM_SLICE = Handle(20)
WEAPON_TYPE_CLAW_HEAVY_SLICE = Handle(21)
WEAPON_TYPE_AXE_MEDIUM_CHOP = Handle(22)
WEAPON_TYPE_ROCK_HEAVY_BASH = Handle(23)
PATHING_TYPE_ANY = Handle(0)
PATHING_TYPE_WALKABILITY = Handle(1)
PATHING_TYPE_FLYABILITY = Handle(2)
PATHING_TYPE_BUILDABILITY = Handle(3)
PATHING_TYPE_PEONHARVESTPATHING = Handle(4)
PATHING_TYPE_BLIGHTPATHING = Handle(5)
PATHING_TYPE_FLOATABILITY = Handle(6)
PATHING_TYPE_AMPHIBIOUSPATHING = Handle(7)
RACE_PREF_HUMAN = Handle(1)
RACE_PREF_ORC = Handle(2)
RACE_PREF_NIGHTELF = Handle(4)
RACE_PREF_UNDEAD = Handle(8)
RACE_PREF_DEMON = Handle(16)
RACE_PREF_RANDOM = Handle(32)
RACE_PREF_USER_SELECTABLE = Handle(64)
MAP_CONTROL_USER = Handle(0)
MAP_CONTROL_COMPUTER = Handle(1)
MAP_CONTROL_RESCUABLE = Handle(2)
MAP_CONTROL_NEUTRAL = Handle(3)
MAP_CONTROL_CREEP = Handle(4)
MAP_CONTROL_NONE = Handle(5)
GAME_TYPE_MELEE = Handle(1)
GAME_TYPE_FFA = Handle(2)
GAME_TYPE_USE_MAP_SETTINGS = Handle(4)
GAME_TYPE_BLIZ = Handle(8)
GAME_TYPE_ONE_ON_ONE = Handle(16)
GAME_TYPE_TWO_TEAM_PLAY = Handle(32)
GAME_TYPE_THREE_TEAM_PLAY = Handle(64)
GAME_TYPE_FOUR_TEAM_PLAY = Handle(128)
MAP_FOG_HIDE_TERRAIN = Handle(1)
MAP_FOG_MAP_EXPLORED = Handle(2)
MAP_FOG_ALWAYS_VISIBLE = Handle(4)
MAP_USE_HANDICAPS = Handle(8)
MAP_OBSERVERS = Handle(16)
MAP_OBSERVERS_ON_DEATH = Handle(32)
MAP_FIXED_COLORS = Handle(128)
MAP_LOCK_RESOURCE_TRADING = Handle(256)
MAP_RESOURCE_TRADING_ALLIES_ONLY = Handle(512)
MAP_LOCK_ALLIANCE_CHANGES = Handle(1024)
MAP_ALLIANCE_CHANGES_HIDDEN = Handle(2048)
MAP_CHEATS = Handle(4096)
MAP_CHEATS_HIDDEN = Handle(8192)
MAP_LOCK_SPEED = Handle(8192*2)
MAP_LOCK_RANDOM_SEED = Handle(8192*4)
MAP_SHARED_ADVANCED_CONTROL = Handle(8192*8)
MAP_RANDOM_HERO = Handle(8192*16)
MAP_RANDOM_RACES = Handle(8192*32)
MAP_RELOADED = Handle(8192*64)
MAP_PLACEMENT_RANDOM = 0
MAP_PLACEMENT_FIXED = 1
MAP_PLACEMENT_USE_MAP_SETTINGS = 2
MAP_PLACEMENT_TEAMS_TOGETHER = 3
MAP_LOC_PRIO_LOW = Handle(0)
MAP_LOC_PRIO_HIGH = Handle(1)
MAP_LOC_PRIO_NOT = Handle(2)
MAP_DENSITY_NONE = Handle(0)
MAP_DENSITY_LIGHT = Handle(1)
MAP_DENSITY_MEDIUM = Handle(2)
MAP_DENSITY_HEAVY = Handle(3)
MAP_DIFFICULTY_EASY = Handle(0)
MAP_DIFFICULTY_NORMAL = Handle(1)
MAP_DIFFICULTY_HARD = Handle(2)
MAP_DIFFICULTY_INSANE = Handle(3)
MAP_SPEED_SLOWEST = Handle(0)
MAP_SPEED_SLOW = Handle(1)
MAP_SPEED_NORMAL = Handle(2)
MAP_SPEED_FAST = Handle(3)
MAP_SPEED_FASTEST = Handle(4)
PLAYER_SLOT_STATE_EMPTY = Handle(0)
PLAYER_SLOT_STATE_PLAYING = Handle(1)
PLAYER_SLOT_STATE_LEFT = Handle(2)
SOUND_VOLUMEGROUP_UNITMOVEMENT = Handle(0)
SOUND_VOLUMEGROUP_UNITSOUNDS = Handle(1)
SOUND_VOLUMEGROUP_COMBAT = Handle(2)
SOUND_VOLUMEGROUP_SPELLS = Handle(3)
SOUND_VOLUMEGROUP_UI = Handle(4)
SOUND_VOLUMEGROUP_MUSIC = Handle(5)
SOUND_VOLUMEGROUP_AMBIENTSOUNDS = Handle(6)
SOUND_VOLUMEGROUP_FIRE = Handle(7)
GAME_STATE_DIVINE_INTERVENTION = Handle(0)
GAME_STATE_DISCONNECTED = Handle(1)
GAME_STATE_TIME_OF_DAY = Handle(2)
PLAYER_STATE_GAME_RESULT = Handle(0)
PLAYER_STATE_RESOURCE_GOLD = Handle(1)
PLAYER_STATE_RESOURCE_LUMBER = Handle(2)
PLAYER_STATE_RESOURCE_HERO_TOKENS = Handle(3)
PLAYER_STATE_RESOURCE_FOOD_CAP = Handle(4)
PLAYER_STATE_RESOURCE_FOOD_USED = Handle(5)
PLAYER_STATE_FOOD_CAP_CEILING = Handle(6)
PLAYER_STATE_GIVES_BOUNTY = Handle(7)
PLAYER_STATE_ALLIED_VICTORY = Handle(8)
PLAYER_STATE_PLACED = Handle(9)
PLAYER_STATE_OBSERVER_ON_DEATH = Handle(10)
PLAYER_STATE_OBSERVER = Handle(11)
PLAYER_STATE_UNFOLLOWABLE = Handle(12)
PLAYER_STATE_GOLD_UPKEEP_RATE = Handle(13)
PLAYER_STATE_LUMBER_UPKEEP_RATE = Handle(14)
PLAYER_STATE_GOLD_GATHERED = Handle(15)
PLAYER_STATE_LUMBER_GATHERED = Handle(16)
PLAYER_STATE_NO_CREEP_SLEEP = Handle(25)
UNIT_STATE_LIFE = Handle(0)
UNIT_STATE_MAX_LIFE = Handle(1)
UNIT_STATE_MANA = Handle(2)
UNIT_STATE_MAX_MANA = Handle(3)
AI_DIFFICULTY_NEWBIE = Handle(0)
AI_DIFFICULTY_NORMAL = Handle(1)
AI_DIFFICULTY_INSANE = Handle(2)
PLAYER_SCORE_UNITS_TRAINED = Handle(0)
PLAYER_SCORE_UNITS_KILLED = Handle(1)
PLAYER_SCORE_STRUCT_BUILT = Handle(2)
PLAYER_SCORE_STRUCT_RAZED = Handle(3)
PLAYER_SCORE_TECH_PERCENT = Handle(4)
PLAYER_SCORE_FOOD_MAXPROD = Handle(5)
PLAYER_SCORE_FOOD_MAXUSED = Handle(6)
PLAYER_SCORE_HEROES_KILLED = Handle(7)
PLAYER_SCORE_ITEMS_GAINED = Handle(8)
PLAYER_SCORE_MERCS_HIRED = Handle(9)
PLAYER_SCORE_GOLD_MINED_TOTAL = Handle(10)
PLAYER_SCORE_GOLD_MINED_UPKEEP = Handle(11)
PLAYER_SCORE_GOLD_LOST_UPKEEP = Handle(12)
PLAYER_SCORE_GOLD_LOST_TAX = Handle(13)
PLAYER_SCORE_GOLD_GIVEN = Handle(14)
PLAYER_SCORE_GOLD_RECEIVED = Handle(15)
PLAYER_SCORE_LUMBER_TOTAL = Handle(16)
PLAYER_SCORE_LUMBER_LOST_UPKEEP = Handle(17)
PLAYER_SCORE_LUMBER_LOST_TAX = Handle(18)
PLAYER_SCORE_LUMBER_GIVEN = Handle(19)
PLAYER_SCORE_LUMBER_RECEIVED = Handle(20)
PLAYER_SCORE_UNIT_TOTAL = Handle(21)
PLAYER_SCORE_HERO_TOTAL = Handle(22)
PLAYER_SCORE_RESOURCE_TOTAL = Handle(23)
PLAYER_SCORE_TOTAL = Handle(24)
EVENT_GAME_VICTORY = Handle(0)
EVENT_GAME_END_LEVEL = Handle(1)
EVENT_GAME_VARIABLE_LIMIT = Handle(2)
EVENT_GAME_STATE_LIMIT = Handle(3)
EVENT_GAME_TIMER_EXPIRED = Handle(4)
EVENT_GAME_ENTER_REGION = Handle(5)
EVENT_GAME_LEAVE_REGION = Handle(6)
EVENT_GAME_TRACKABLE_HIT = Handle(7)
EVENT_GAME_TRACKABLE_TRACK = Handle(8)
EVENT_GAME_SHOW_SKILL = Handle(9)
EVENT_GAME_BUILD_SUBMENU = Handle(10)
EVENT_PLAYER_STATE_LIMIT = Handle(11)
EVENT_PLAYER_ALLIANCE_CHANGED = Handle(12)
EVENT_PLAYER_DEFEAT = Handle(13)
EVENT_PLAYER_VICTORY = Handle(14)
EVENT_PLAYER_LEAVE = Handle(15)
EVENT_PLAYER_CHAT = Handle(16)
EVENT_PLAYER_END_CINEMATIC = Handle(17)
EVENT_PLAYER_UNIT_ATTACKED = Handle(18)
EVENT_PLAYER_UNIT_RESCUED = Handle(19)
EVENT_PLAYER_UNIT_DEATH = Handle(20)
EVENT_PLAYER_UNIT_DECAY = Handle(21)
EVENT_PLAYER_UNIT_DETECTED = Handle(22)
EVENT_PLAYER_UNIT_HIDDEN = Handle(23)
EVENT_PLAYER_UNIT_SELECTED = Handle(24)
EVENT_PLAYER_UNIT_DESELECTED = Handle(25)
EVENT_PLAYER_UNIT_CONSTRUCT_START = Handle(26)
EVENT_PLAYER_UNIT_CONSTRUCT_CANCEL = Handle(27)
EVENT_PLAYER_UNIT_CONSTRUCT_FINISH = Handle(28)
EVENT_PLAYER_UNIT_UPGRADE_START = Handle(29)
EVENT_PLAYER_UNIT_UPGRADE_CANCEL = Handle(30)
EVENT_PLAYER_UNIT_UPGRADE_FINISH = Handle(31)
EVENT_PLAYER_UNIT_TRAIN_START = Handle(32)
EVENT_PLAYER_UNIT_TRAIN_CANCEL = Handle(33)
EVENT_PLAYER_UNIT_TRAIN_FINISH = Handle(34)
EVENT_PLAYER_UNIT_RESEARCH_START = Handle(35)
EVENT_PLAYER_UNIT_RESEARCH_CANCEL = Handle(36)
EVENT_PLAYER_UNIT_RESEARCH_FINISH = Handle(37)
EVENT_PLAYER_UNIT_ISSUED_ORDER = Handle(38)
EVENT_PLAYER_UNIT_ISSUED_POINT_ORDER = Handle(39)
EVENT_PLAYER_UNIT_ISSUED_TARGET_ORDER = Handle(40)
EVENT_PLAYER_UNIT_ISSUED_UNIT_ORDER = 40
EVENT_PLAYER_HERO_LEVEL = Handle(41)
EVENT_PLAYER_HERO_SKILL = Handle(42)
EVENT_PLAYER_HERO_REVIVABLE = Handle(43)
EVENT_PLAYER_HERO_REVIVE_START = Handle(44)
EVENT_PLAYER_HERO_REVIVE_CANCEL = Handle(45)
EVENT_PLAYER_HERO_REVIVE_FINISH = Handle(46)
EVENT_PLAYER_UNIT_SUMMON = Handle(47)
EVENT_PLAYER_UNIT_DROP_ITEM = Handle(48)
EVENT_PLAYER_UNIT_PICKUP_ITEM = Handle(49)
EVENT_PLAYER_UNIT_USE_ITEM = Handle(50)
EVENT_PLAYER_UNIT_LOADED = Handle(51)
EVENT_UNIT_DAMAGED = Handle(52)
EVENT_UNIT_DEATH = Handle(53)
EVENT_UNIT_DECAY = Handle(54)
EVENT_UNIT_DETECTED = Handle(55)
EVENT_UNIT_HIDDEN = Handle(56)
EVENT_UNIT_SELECTED = Handle(57)
EVENT_UNIT_DESELECTED = Handle(58)
EVENT_UNIT_STATE_LIMIT = Handle(59)
EVENT_UNIT_ACQUIRED_TARGET = Handle(60)
EVENT_UNIT_TARGET_IN_RANGE = Handle(61)
EVENT_UNIT_ATTACKED = Handle(62)
EVENT_UNIT_RESCUED = Handle(63)
EVENT_UNIT_CONSTRUCT_CANCEL = Handle(64)
EVENT_UNIT_CONSTRUCT_FINISH = Handle(65)
EVENT_UNIT_UPGRADE_START = Handle(66)
EVENT_UNIT_UPGRADE_CANCEL = Handle(67)
EVENT_UNIT_UPGRADE_FINISH = Handle(68)
EVENT_UNIT_TRAIN_START = Handle(69)
EVENT_UNIT_TRAIN_CANCEL = Handle(70)
EVENT_UNIT_TRAIN_FINISH = Handle(71)
EVENT_UNIT_RESEARCH_START = Handle(72)
EVENT_UNIT_RESEARCH_CANCEL = Handle(73)
EVENT_UNIT_RESEARCH_FINISH = Handle(74)
EVENT_UNIT_ISSUED_ORDER = Handle(75)
EVENT_UNIT_ISSUED_POINT_ORDER = Handle(76)
EVENT_UNIT_ISSUED_TARGET_ORDER = Handle(77)
EVENT_UNIT_HERO_LEVEL = Handle(78)
EVENT_UNIT_HERO_SKILL = Handle(79)
EVENT_UNIT_HERO_REVIVABLE = Handle(80)
EVENT_UNIT_HERO_REVIVE_START = Handle(81)
EVENT_UNIT_HERO_REVIVE_CANCEL = Handle(82)
EVENT_UNIT_HERO_REVIVE_FINISH = Handle(83)
EVENT_UNIT_SUMMON = Handle(84)
EVENT_UNIT_DROP_ITEM = Handle(85)
EVENT_UNIT_PICKUP_ITEM = Handle(86)
EVENT_UNIT_USE_ITEM = Handle(87)
EVENT_UNIT_LOADED = Handle(88)
EVENT_WIDGET_DEATH = Handle(89)
EVENT_DIALOG_BUTTON_CLICK = Handle(90)
EVENT_DIALOG_CLICK = Handle(91)
EVENT_GAME_LOADED = Handle(256)
EVENT_GAME_TOURNAMENT_FINISH_SOON = Handle(257)
EVENT_GAME_TOURNAMENT_FINISH_NOW = Handle(258)
EVENT_GAME_SAVE = Handle(259)
EVENT_PLAYER_ARROW_LEFT_DOWN = Handle(261)
EVENT_PLAYER_ARROW_LEFT_UP = Handle(262)
EVENT_PLAYER_ARROW_RIGHT_DOWN = Handle(263)
EVENT_PLAYER_ARROW_RIGHT_UP = Handle(264)
EVENT_PLAYER_ARROW_DOWN_DOWN = Handle(265)
EVENT_PLAYER_ARROW_DOWN_UP = Handle(266)
EVENT_PLAYER_ARROW_UP_DOWN = Handle(267)
EVENT_PLAYER_ARROW_UP_UP = Handle(268)
EVENT_PLAYER_UNIT_SELL = Handle(269)
EVENT_PLAYER_UNIT_CHANGE_OWNER = Handle(270)
EVENT_PLAYER_UNIT_SELL_ITEM = Handle(271)
EVENT_PLAYER_UNIT_SPELL_CHANNEL = Handle(272)
EVENT_PLAYER_UNIT_SPELL_CAST = Handle(273)
EVENT_PLAYER_UNIT_SPELL_EFFECT = Handle(274)
EVENT_PLAYER_UNIT_SPELL_FINISH = Handle(275)
EVENT_PLAYER_UNIT_SPELL_ENDCAST = Handle(276)
EVENT_PLAYER_UNIT_PAWN_ITEM = Handle(277)
EVENT_UNIT_SELL = Handle(286)
EVENT_UNIT_CHANGE_OWNER = Handle(287)
EVENT_UNIT_SELL_ITEM = Handle(288)
EVENT_UNIT_SPELL_CHANNEL = Handle(289)
EVENT_UNIT_SPELL_CAST = Handle(290)
EVENT_UNIT_SPELL_EFFECT = Handle(291)
EVENT_UNIT_SPELL_FINISH = Handle(292)
EVENT_UNIT_SPELL_ENDCAST = Handle(293)
EVENT_UNIT_PAWN_ITEM = Handle(294)
LESS_THAN = Handle(0)
LESS_THAN_OR_EQUAL = Handle(1)
EQUAL = Handle(2)
GREATER_THAN_OR_EQUAL = Handle(3)
GREATER_THAN = Handle(4)
NOT_EQUAL = Handle(5)
UNIT_TYPE_HERO = Handle(0)
UNIT_TYPE_DEAD = Handle(1)
UNIT_TYPE_STRUCTURE = Handle(2)
UNIT_TYPE_FLYING = Handle(3)
UNIT_TYPE_GROUND = Handle(4)
UNIT_TYPE_ATTACKS_FLYING = Handle(5)
UNIT_TYPE_ATTACKS_GROUND = Handle(6)
UNIT_TYPE_MELEE_ATTACKER = Handle(7)
UNIT_TYPE_RANGED_ATTACKER = Handle(8)
UNIT_TYPE_GIANT = Handle(9)
UNIT_TYPE_SUMMONED = Handle(10)
UNIT_TYPE_STUNNED = Handle(11)
UNIT_TYPE_PLAGUED = Handle(12)
UNIT_TYPE_SNARED = Handle(13)
UNIT_TYPE_UNDEAD = Handle(14)
UNIT_TYPE_MECHANICAL = Handle(15)
UNIT_TYPE_PEON = Handle(16)
UNIT_TYPE_SAPPER = Handle(17)
UNIT_TYPE_TOWNHALL = Handle(18)
UNIT_TYPE_ANCIENT = Handle(19)
UNIT_TYPE_TAUREN = Handle(20)
UNIT_TYPE_POISONED = Handle(21)
UNIT_TYPE_POLYMORPHED = Handle(22)
UNIT_TYPE_SLEEPING = Handle(23)
UNIT_TYPE_RESISTANT = Handle(24)
UNIT_TYPE_ETHEREAL = Handle(25)
UNIT_TYPE_MAGIC_IMMUNE = Handle(26)
ITEM_TYPE_PERMANENT = Handle(0)
ITEM_TYPE_CHARGED = Handle(1)
ITEM_TYPE_POWERUP = Handle(2)
ITEM_TYPE_ARTIFACT = Handle(3)
ITEM_TYPE_PURCHASABLE = Handle(4)
ITEM_TYPE_CAMPAIGN = Handle(5)
ITEM_TYPE_MISCELLANEOUS = Handle(6)
ITEM_TYPE_UNKNOWN = Handle(7)
ITEM_TYPE_ANY = Handle(8)
ITEM_TYPE_TOME = Handle(2)
CAMERA_FIELD_TARGET_DISTANCE = Handle(0)
CAMERA_FIELD_FARZ = Handle(1)
CAMERA_FIELD_ANGLE_OF_ATTACK = Handle(2)
CAMERA_FIELD_FIELD_OF_VIEW = Handle(3)
CAMERA_FIELD_ROLL = Handle(4)
CAMERA_FIELD_ROTATION = Handle(5)
CAMERA_FIELD_ZOFFSET = Handle(6)
BLEND_MODE_NONE = Handle(0)
BLEND_MODE_DONT_CARE = Handle(0)
BLEND_MODE_KEYALPHA = Handle(1)
BLEND_MODE_BLEND = Handle(2)
BLEND_MODE_ADDITIVE = Handle(3)
BLEND_MODE_MODULATE = Handle(4)
BLEND_MODE_MODULATE_2X = Handle(5)
RARITY_FREQUENT = Handle(0)
RARITY_RARE = Handle(1)
TEXMAP_FLAG_NONE = Handle(0)
TEXMAP_FLAG_WRAP_U = Handle(1)
TEXMAP_FLAG_WRAP_V = Handle(2)
TEXMAP_FLAG_WRAP_UV = Handle(3)
FOG_OF_WAR_MASKED = Handle(1)
FOG_OF_WAR_FOGGED = Handle(2)
FOG_OF_WAR_VISIBLE = Handle(4)
CAMERA_MARGIN_LEFT = Handle(0)
CAMERA_MARGIN_RIGHT = Handle(1)
CAMERA_MARGIN_TOP = Handle(2)
CAMERA_MARGIN_BOTTOM = Handle(3)
EFFECT_TYPE_EFFECT = Handle(0)
EFFECT_TYPE_TARGET = Handle(1)
EFFECT_TYPE_CASTER = Handle(2)
EFFECT_TYPE_SPECIAL = Handle(3)
EFFECT_TYPE_AREA_EFFECT = Handle(4)
EFFECT_TYPE_MISSILE = Handle(5)
EFFECT_TYPE_LIGHTNING = Handle(6)
SOUND_TYPE_EFFECT = Handle(0)
SOUND_TYPE_EFFECT_LOOPED = Handle(1)
-- CUSTOM EVENT ID --
EVENT_GAME_START = Handle(1000)
EVENT_GAME_END = Handle(1001)
EVENT_PLAYER_KEY_UP = Handle(1002)
EVENT_PLAYER_KEY_DOWN = Handle(1003)
EVENT_PACKET = Handle(1004)
EVENT_UNIT_ATTACK_MISS = Handle(1005)
| mit |
nightrune/wireshark | test/lua/nstime.lua | 32 | 5569 | -- test script for various Lua functions
-- use with dhcp.pcap in test/captures directory
------------- general test helper funcs ------------
local FRAME = "frame"
local OTHER = "other"
local packet_counts = {}
local function incPktCount(name)
if not packet_counts[name] then
packet_counts[name] = 1
else
packet_counts[name] = packet_counts[name] + 1
end
end
local function getPktCount(name)
return packet_counts[name] or 0
end
local passed = {}
local function setPassed(name)
if not passed[name] then
passed[name] = 1
else
passed[name] = passed[name] + 1
end
end
-- expected number of runs per type
-- note ip only runs 3 times because it gets removed
-- and bootp only runs twice because the filter makes it run
-- once and then it gets replaced with a different one for the second time
local taptests = { [FRAME]=4, [OTHER]=37 }
local function getResults()
print("\n-----------------------------\n")
for k,v in pairs(taptests) do
if passed[k] ~= v then
print("Something didn't run or ran too much... tests failed!")
print("Listener type "..k.." expected: "..v..", but got: "..tostring(passed[k]))
return false
end
end
print("All tests passed!\n\n")
return true
end
local function testing(type,...)
print("---- Testing "..type.." ---- "..tostring(...).." for packet # "..getPktCount(type).."----")
end
local function test(type,name, ...)
io.stdout:write("test "..type.."-->"..name.."-"..getPktCount(type).."...")
if (...) == true then
io.stdout:write("passed\n")
return true
else
io.stdout:write("failed!\n")
error(name.." test failed!")
end
end
---------
-- the following are so we can use pcall (which needs a function to call)
local function makeNSTime(...)
local foo = NSTime(...)
end
local function setNSTime(nst,name,value)
nst[name] = value
end
local function getNSTime(nst,name)
local foo = nst[name]
end
------------- test script ------------
testing(OTHER,"negative tests")
local orig_test = test
test = function (...)
if orig_test(OTHER,...) then
setPassed(OTHER)
end
end
test("NSTime.new-1",not pcall(makeNSTime,"FooBARhowdy"))
test("NSTime.new-2",not pcall(makeNSTime,"ip","FooBARhowdy"))
local tmptime = NSTime()
test("NSTime.set-3",pcall(setNSTime,tmptime,"secs",10))
test("NSTime.set-4",not pcall(setNSTime,tmptime,"foobar",1000))
test("NSTime.set-5",pcall(setNSTime,tmptime,"nsecs",123))
test("NSTime.set-6",not pcall(setNSTime,NSTime,"secs",0))
test("NSTime.set-7",not pcall(setNSTime,tmptime,"secs","foobar"))
test("NSTime.set-8",not pcall(setNSTime,NSTime,"nsecs",0))
test("NSTime.set-9",not pcall(setNSTime,tmptime,"nsecs","foobar"))
test("NSTime.get-10",pcall(getNSTime,tmptime,"secs"))
test("NSTime.get-11",pcall(getNSTime,tmptime,"nsecs"))
test("NSTime.get-12",not pcall(getNSTime,NSTime,"secs"))
test("NSTime.get-13",not pcall(getNSTime,NSTime,"nsecs"))
testing(OTHER,"basic tests")
local first = NSTime()
local second = NSTime(100,100)
local third = NSTime(0,100)
test("NSTime.secs-14", first.secs == 0)
test("NSTime.secs-15", second.secs == 100)
test("NSTime.secs-16", third.secs == 0)
test("NSTime.nsecs-17", first.nsecs == 0)
test("NSTime.nsecs-18", second.nsecs == 100)
test("NSTime.nsecs-19", third.nsecs == 100)
test("NSTime.eq-20", first == NSTime())
test("NSTime.neq-21", second ~= third)
test("NSTime.add-22", first + second == second)
test("NSTime.add-23", third + NSTime(100,0) == second)
test("NSTime.add-24", NSTime(100) + NSTime(nil,100) == second)
test("NSTime.lt-25", third < second)
test("NSTime.gt-26", third > first)
test("NSTime.le-27", second <= NSTime(100,100))
test("NSTime.unm-28", -first == first)
test("NSTime.unm-29", -(-second) == second)
test("NSTime.unm-30", -second == NSTime(-100,-100))
test("NSTime.unm-31", -third == NSTime(0,-100))
test("NSTime.tostring-32", tostring(first) == "0.000000000")
test("NSTime.tostring-33", tostring(second) == "100.000000100")
test("NSTime.tostring-34", tostring(third) == "0.000000100")
testing(OTHER,"setters/getters")
first.secs = 123
first.nsecs = 100
test("NSTime.set-35", first == NSTime(123,100))
test("NSTime.get-36", first.secs == 123)
test("NSTime.get-37", first.nsecs == 100)
----------------------------------
-- revert to original test function, kinda sorta
test = function (...)
return orig_test(FRAME,...)
end
-- declare some field extractors
local f_frame_time = Field.new("frame.time")
local f_frame_time_rel = Field.new("frame.time_relative")
local f_frame_time_delta = Field.new("frame.time_delta")
local tap = Listener.new()
local begin = NSTime()
local now, previous
function tap.packet(pinfo,tvb,frame)
incPktCount(FRAME)
testing(FRAME,"NSTime in Frame")
local fi_now = f_frame_time()
local fi_rel = f_frame_time_rel()
local fi_delta = f_frame_time_delta()
test("typeof-1", typeof(begin) == "NSTime")
test("typeof-2", typeof(fi_now()) == "NSTime")
now = fi_now()
if getPktCount(FRAME) == 1 then
test("__eq-1", begin == fi_delta())
test("NSTime.secs-1", fi_delta().secs == 0)
test("NSTime.nsecs-1", fi_delta().nsecs == 0)
begin = fi_now()
else
test("__sub__eq-1", now - previous == fi_delta())
test("__sub__eq-2", now - begin == fi_rel())
test("__add-1", (previous - begin) + (now - previous) == fi_rel())
end
previous = now
setPassed(FRAME)
end
function tap.draw()
getResults()
end
| gpl-2.0 |
SirNate0/Urho3D | bin/Data/LuaScripts/04_StaticScene.lua | 24 | 7000 | -- Static 3D scene example.
-- This sample demonstrates:
-- - Creating a 3D scene with static content
-- - Displaying the scene using the Renderer subsystem
-- - Handling keyboard and mouse input to move a freelook camera
require "LuaScripts/Utilities/Sample"
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateInstructions()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE)
-- Hook up to the frame update events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
-- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it
-- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
-- optimizing manner
scene_:CreateComponent("Octree")
-- Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
-- plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
-- (100 x 100 world units)
local planeNode = scene_:CreateChild("Plane")
planeNode.scale = Vector3(100.0, 1.0, 100.0)
local planeObject = planeNode:CreateComponent("StaticModel")
planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
-- Create a directional light to the world so that we can see something. The light scene node's orientation controls the
-- light direction we will use the SetDirection() function which calculates the orientation from a forward direction vector.
-- The light will use default settings (white light, no shadows)
local lightNode = scene_:CreateChild("DirectionalLight")
lightNode.direction = Vector3(0.6, -1.0, 0.8) -- The direction vector does not need to be normalized
local light = lightNode:CreateComponent("Light")
light.lightType = LIGHT_DIRECTIONAL
-- Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
-- quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
-- LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
-- see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
-- same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
-- scene.
local NUM_OBJECTS = 200
for i = 1, NUM_OBJECTS do
local mushroomNode = scene_:CreateChild("Mushroom")
mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)
mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
mushroomNode:SetScale(0.5 + Random(2.0))
local mushroomObject = mushroomNode:CreateComponent("StaticModel")
mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
end
-- Create a scene node for the camera, which we will move around
-- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode = scene_:CreateChild("Camera")
cameraNode:CreateComponent("Camera")
-- Set an initial position for the camera scene node above the plane
cameraNode.position = Vector3(0.0, 5.0, 0.0)
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText:SetText("Use WASD keys and mouse to move")
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
-- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
-- use, but now we just use full screen and default render path configured in the engine command line options
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function MoveCamera(timeStep)
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 20.0
-- Mouse sensitivity as degrees per pixel
local MOUSE_SENSITIVITY = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
local mouseMove = input.mouseMove
yaw = yaw +MOUSE_SENSITIVITY * mouseMove.x
pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
pitch = Clamp(pitch, -90.0, 90.0)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
-- Use the Translate() function (default local space) to move relative to the node's orientation.
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
end
| mit |
DavidIngraham/ardupilot | Tools/CHDK-Scripts/Cannon SX260/3DR_EAI_SX260.lua | 96 | 29666 |
--[[
KAP UAV Exposure Control Script v3.1
-- Released under GPL by waterwingz and wayback/peabody
http://chdk.wikia.com/wiki/KAP_%26_UAV_Exposure_Control_Script
3DR EAI 1.0 is a fork of KAP 3.1 with settings specific to Canon cameras triggered off the Pixhawk autopilot.
Changelog:
-Modified Tv, Av, and ISO settings for the Canon SX260
-Added an option to turn the GPS on and off
-Added control of GPS settings in Main Loop
-Changed USB OneShot mode to listen for 100ms command pulse from Pixhawk
@title 3DR EAI 1.0 - Lets Map!
@param i Shot Interval (sec)
@default i 2
@range i 2 120
@param s Total Shots (0=infinite)
@default s 0
@range s 0 10000
@param j Power off when done?
@default j 0
@range j 0 1
@param e Exposure Comp (stops)
@default e 6
@values e -2.0 -1.66 -1.33 -1.0 -0.66 -0.33 0.0 0.33 0.66 1.00 1.33 1.66 2.00
@param d Start Delay Time (sec)
@default d 0
@range d 0 10000
@param y Tv Min (sec)
@default y 5
@values y None 1/60 1/100 1/200 1/400 1/640
@param t Target Tv (sec)
@default t 7
@values t 1/100 1/200 1/400 1/640 1/800 1/1000 1/1250 1/1600 1/2000
@param x Tv Max (sec)
@default x 4
@values x 1/1000 1/1250 1/1600 1/2000 1/3200 1/5000 1/10000
@param f Av Low(f-stop)
@default f 6
@values f 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param a Av Target (f-stop)
@default a 7
@values a 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param m Av Max (f-stop)
@default m 13
@values m 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param p ISO Min
@default p 0
@values p 80 100 200 400 800 1250 1600
@param q ISO Max1
@default q 1
@values q 100 200 400 800 1250 1600
@param r ISO Max2
@default r 3
@values r 100 200 400 800 1250 1600
@param n Allow use of ND filter?
@default n 0
@values n No Yes
@param z Zoom position
@default z 0
@values z Off 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
@param c Focus @ Infinity Mode
@default c 3
@values c None @Shot AFL MF
@param v Video Interleave (shots)
@default v 0
@values v Off 1 5 10 25 50 100
@param w Video Duration (sec)
@default w 10
@range w 5 300
@param u Trigger Type
@default u 2
@values u Interval Cont. USB PWM
@param g GPS On
@default g 1
@range g 0 1
@param b Backlight Off?
@default b 1
@range b 0 1
@param l Logging
@default l 3
@values l Off Screen SDCard Both
--]]
props=require("propcase")
capmode=require("capmode")
-- convert user parameter to usable variable names and values
tv_table = { -320, 576, 640, 736, 832, 896, 928, 960, 992, 1024, 1056, 1113, 1180, 1276}
tv96target = tv_table[t+3]
tv96max = tv_table[x+8]
tv96min = tv_table[y+1]
sv_table = { 381, 411, 507, 603, 699, 761, 795 }
sv96min = sv_table[p+1]
sv96max1 = sv_table[q+2]
sv96max2 = sv_table[r+2]
av_table = { 171, 192, 218, 265, 285, 322, 347, 384, 417, 446, 477, 510, 543, 576 }
av96target = av_table[a+1]
av96minimum = av_table[f+1]
av96max = av_table[m+1]
ec96adjust = (e - 6)*32
video_table = { 0, 1, 5, 10, 25, 50, 100 }
video_mode = video_table[v+1]
video_duration = w
interval = i*1000
max_shots = s
poff_if_done = j
start_delay = d
backlight = b
log_mode= l
focus_mode = c
usb_mode = u
gps = g
if ( z==0 ) then zoom_setpoint = nil else zoom_setpoint = (z-1)*10 end
-- initial configuration values
nd96offset=3*96 -- ND filter's number of equivalent f-stops (f * 96)
infx = 50000 -- focus lock distance in mm (approximately 55 yards)
shot_count = 0 -- shot counter
blite_timer = 300 -- backlight off delay in 100mSec increments
old_console_timeout = get_config_value( 297 )
shot_request = false -- pwm mode flag to request a shot be taken
-- check camera Av configuration ( variable aperture and/or ND filter )
if n==0 then -- use of nd filter allowed?
if get_nd_present()==1 then -- check for ND filter only
Av_mode = 0 -- 0 = ND disabled and no iris available
else
Av_mode = 1 -- 1 = ND disabled and iris available
end
else
Av_mode = get_nd_present()+1 -- 1 = iris only , 2=ND filter only, 3= both ND & iris
end
function printf(...)
if ( log_mode == 0) then return end
local str=string.format(...)
if (( log_mode == 1) or (log_mode == 3)) then print(str) end
if ( log_mode > 1 ) then
local logname="A/3DR_EAI_log.log"
log=io.open(logname,"a")
log:write(os.date("%Y%b%d %X ")..string.format(...),"\n")
log:close()
end
end
tv_ref = { -- note : tv_ref values set 1/2 way between shutter speed values
-608, -560, -528, -496, -464, -432, -400, -368, -336, -304,
-272, -240, -208, -176, -144, -112, -80, -48, -16, 16,
48, 80, 112, 144, 176, 208, 240, 272, 304, 336,
368, 400, 432, 464, 496, 528, 560, 592, 624, 656,
688, 720, 752, 784, 816, 848, 880, 912, 944, 976,
1008, 1040, 1072, 1096, 1129, 1169, 1192, 1225, 1265, 1376 }
tv_str = {
">64",
"64", "50", "40", "32", "25", "20", "16", "12", "10", "8.0",
"6.0", "5.0", "4.0", "3.2", "2.5", "2.0", "1.6", "1.3", "1.0", "0.8",
"0.6", "0.5", "0.4", "0.3", "1/4", "1/5", "1/6", "1/8", "1/10", "1/13",
"1/15", "1/20", "1/25", "1/30", "1/40", "1/50", "1/60", "1/80", "1/100", "1/125",
"1/160", "1/200", "1/250", "1/320", "1/400", "1/500", "1/640", "1/800", "1/1000","1/1250",
"1/1600","1/2000","1/2500","1/3200","1/4000","1/5000","1/6400","1/8000","1/10000","hi" }
function print_tv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #tv_ref) and (val > tv_ref[i]) do i=i+1 end
return tv_str[i]
end
av_ref = { 160, 176, 208, 243, 275, 304, 336, 368, 400, 432, 464, 480, 496, 512, 544, 592, 624, 656, 688, 720, 752, 784 }
av_str = {"n/a","1.8", "2.0","2.2","2.6","2.8","3.2","3.5","4.0","4.5","5.0","5.6","5.9","6.3","7.1","8.0","9.0","10.0","11.0","13.0","14.0","16.0","hi"}
function print_av(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #av_ref) and (val > av_ref[i]) do i=i+1 end
return av_str[i]
end
sv_ref = { 370, 397, 424, 456, 492, 523, 555, 588, 619, 651, 684, 731, 779, 843, 907 }
sv_str = {"n/a","80","100","120","160","200","250","320","400","500","640","800","1250","1600","3200","hi"}
function print_sv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #sv_ref) and (val > sv_ref[i]) do i=i+1 end
return sv_str[i]
end
function pline(message, line) -- print line function
fg = 258 bg=259
end
-- switch between shooting and playback modes
function switch_mode( m )
if ( m == 1 ) then
if ( get_mode() == false ) then
set_record(1) -- switch to shooting mode
while ( get_mode() == false ) do
sleep(100)
end
sleep(1000)
end
else
if ( get_mode() == true ) then
set_record(0) -- switch to playback mode
while ( get_mode() == true ) do
sleep(100)
end
sleep(1000)
end
end
end
-- focus lock and unlock
function lock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if ( focus_mode == 2 ) then -- method 1 : set_aflock() command enables MF
if (chdk_version==120) then
set_aflock(1)
set_prop(props.AF_LOCK,1)
else
set_aflock(1)
end
if (get_prop(props.AF_LOCK) == 1) then printf(" AFL enabled") else printf(" AFL failed ***") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOn") == -1 then
call_event_proc("PT_MFOn")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOn") == -1 then
call_event_proc("MFOn")
end
end
if (get_prop(props.FOCUS_MODE) == 0 ) then -- MF not set - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(1) == 0 ) then set_aflock(1) end -- as a fall back, try setting AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 1) then printf(" MF enabled") else printf(" MF enable failed ***") end
end
sleep(1000)
set_focus(infx)
sleep(1000)
end
end
function unlock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if (focus_mode == 2 ) then -- method 1 : AFL
if (chdk_version==120) then
set_aflock(0)
set_prop(props.AF_LOCK,0)
else
set_aflock(0)
end
if (get_prop(props.AF_LOCK) == 0) then printf(" AFL unlocked") else printf(" AFL unlock failed") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOff") == -1 then
call_event_proc("PT_MFOff")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOff") == -1 then
call_event_proc("MFOff")
end
end
if (get_prop(props.FOCUS_MODE) == 1 ) then -- MF not reset - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(0) == 0 ) then set_aflock(0) end -- fall back so reset AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 0) then printf(" MF disabled") else printf(" MF disable failed") end
end
sleep(100)
end
end
-- zoom position
function update_zoom(zpos)
local count = 0
if(zpos ~= nil) then
zstep=((get_zoom_steps()-1)*zpos)/100
printf("setting zoom to "..zpos.." percent step="..zstep)
sleep(200)
set_zoom(zstep)
sleep(2000)
press("shoot_half")
repeat
sleep(100)
count = count + 1
until (get_shooting() == true ) or (count > 40 )
release("shoot_half")
end
end
-- restore camera settings on shutdown
function restore()
set_config_value(121,0) -- USB remote disable
set_config_value(297,old_console_timeout) -- restore console timeout value
if (backlight==1) then set_lcd_display(1) end -- display on
unlock_focus()
if( zoom_setpoint ~= nil ) then update_zoom(0) end
if( shot_count >= max_shots) and ( max_shots > 1) then
if ( poff_if_done == 1 ) then -- did script ending because # of shots done ?
printf("power off - shot count at limit") -- complete power down
sleep(2000)
post_levent_to_ui('PressPowerButton')
else
set_record(0) end -- just retract lens
end
end
-- Video mode
function check_video(shot)
local capture_mode
if ((video_mode>0) and(shot>0) and (shot%video_mode == 0)) then
unlock_focus()
printf("Video mode started. Button:"..tostring(video_button))
if( video_button ) then
click "video"
else
capture_mode=capmode.get()
capmode.set('VIDEO_STD')
press("shoot_full")
sleep(300)
release("shoot_full")
end
local end_second = get_day_seconds() + video_duration
repeat
wait_click(500)
until (is_key("menu")) or (get_day_seconds() > end_second)
if( video_button ) then
click "video"
else
press("shoot_full")
sleep(300)
release("shoot_full")
capmode.set(capture_mode)
end
printf("Video mode finished.")
sleep(1000)
lock_focus()
return(true)
else
return(false)
end
end
-- PWM USB pulse functions
function ch1up()
printf(" * usb pulse = ch1up")
shot_request = true
end
function ch1mid()
printf(" * usb pulse = ch1mid")
if ( get_mode() == false ) then
switch_mode(1)
lock_focus()
end
end
function ch1down()
printf(" * usb pulse = ch1down")
switch_mode(0)
end
function ch2up()
printf(" * usb pulse = ch2up")
update_zoom(100)
end
function ch2mid()
printf(" * usb pulse = ch2mid")
if ( zoom_setpoint ~= nil ) then update_zoom(zoom_setpoint) else update_zoom(50) end
end
function ch2down()
printf(" * usb pulse = ch2down")
update_zoom(0)
end
function pwm_mode(pulse_width)
if pulse_width > 0 then
if pulse_width < 5 then ch1up()
elseif pulse_width < 8 then ch1mid()
elseif pulse_width < 11 then ch1down()
elseif pulse_width < 14 then ch2up()
elseif pulse_width < 17 then ch2mid()
elseif pulse_width < 20 then ch2down()
else printf(" * usb pulse width error") end
end
end
-- Basic exposure calculation using shutter speed and ISO only
-- called for Tv-only and ND-only cameras (cameras without an iris)
function basic_tv_calc()
tv96setpoint = tv96target
av96setpoint = nil
local min_av = get_prop(props.MIN_AV)
-- calculate required ISO setting
sv96setpoint = tv96setpoint + min_av - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max2 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max2 -- clamp at max2 ISO if so
tv96setpoint = math.max(bv96meter+sv96setpoint-min_av,tv96min) -- recalculate required shutter speed down to Tv min
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - min_av -- recalculate required shutter speed and hope for the best
end
end
-- Basic exposure calculation using shutter speed, iris and ISO
-- called for iris-only and "both" cameras (cameras with an iris & ND filter)
function basic_iris_calc()
tv96setpoint = tv96target
av96setpoint = av96target
-- calculate required ISO setting
sv96setpoint = tv96setpoint + av96setpoint - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max1 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max1 -- clamp at first ISO limit
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint < av96min ) then -- check if new setting is goes below lowest f-stop
av96setpoint = av96min -- clamp at lowest f-stop
sv96setpoint = tv96setpoint + av96setpoint - bv96meter -- recalculate ISO setting
if (sv96setpoint > sv96max2 ) then -- check if the result is above max2 ISO
sv96setpoint = sv96max2 -- clamp at highest ISO setting if so
tv96setpoint = math.max(bv96meter+sv96setpoint-av96setpoint,tv96min) -- recalculate required shutter speed down to tv minimum
end
end
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate required shutter speed
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
tv96setpoint = tv96max -- clamp at maximum shutter speed if so
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint > av96max ) then -- check if new setting is goes above highest f-stop
av96setpoint = av96max -- clamp at highest f-stop
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate shutter speed needed and hope for the best
end
end
end
end
-- calculate exposure for cams without adjustable iris or ND filter
function exposure_Tv_only()
insert_ND_filter = nil
basic_tv_calc()
end
-- calculate exposure for cams with ND filter only
function exposure_NDfilter()
insert_ND_filter = false
basic_tv_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_tv_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- calculate exposure for cams with adjustable iris only
function exposure_iris()
insert_ND_filter = nil
basic_iris_calc()
end
-- calculate exposure for cams with both adjustable iris and ND filter
function exposure_both()
insert_ND_filter = false -- NOTE : assume ND filter never used automatically by Canon firmware
basic_iris_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_iris_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- ========================== Main Program =================================
set_console_layout(1 ,1, 45, 14 )
--printf("KAP 3.1 started - press MENU to exit")
printf("3DR EAI 1.0 Canon SX260 - Lets Map!")
printf("Based On KAP 3.1")
printf("Press the shutter button to pause")
bi=get_buildinfo()
printf("%s %s-%s %s %s %s", bi.version, bi.build_number, bi.build_revision, bi.platform, bi.platsub, bi.build_date)
chdk_version= tonumber(string.sub(bi.build_number,1,1))*100 + tonumber(string.sub(bi.build_number,3,3))*10 + tonumber(string.sub(bi.build_number,5,5))
if ( tonumber(bi.build_revision) > 0 ) then
build = tonumber(bi.build_revision)
else
build = tonumber(string.match(bi.build_number,'-(%d+)$'))
end
if ((chdk_version<120) or ((chdk_version==120)and(build<3276)) or ((chdk_version==130)and(build<3383))) then
printf("CHDK 1.2.0 build 3276 or higher required")
else
if( props.CONTINUOUS_AF == nil ) then caf=-999 else caf = get_prop(props.CONTINUOUS_AF) end
if( props.SERVO_AF == nil ) then saf=-999 else saf = get_prop(props.SERVO_AF) end
cmode = capmode.get_name()
printf("Mode:%s,Continuous_AF:%d,Servo_AF:%d", cmode,caf,saf)
printf(" Tv:"..print_tv(tv96target).." max:"..print_tv(tv96max).." min:"..print_tv(tv96min).." ecomp:"..(ec96adjust/96).."."..(math.abs(ec96adjust*10/96)%10) )
printf(" Av:"..print_av(av96target).." minAv:"..print_av(av96minimum).." maxAv:"..print_av(av96max) )
printf(" ISOmin:"..print_sv(sv96min).." ISO1:"..print_sv(sv96max1).." ISO2:"..print_sv(sv96max2) )
printf(" MF mode:"..focus_mode.." Video:"..video_mode.." USB:"..usb_mode)
printf(" AvM:"..Av_mode.." int:"..(interval/1000).." Shts:"..max_shots.." Dly:"..start_delay.." B/L:"..backlight)
sleep(500)
if (start_delay > 0 ) then
printf("entering start delay of ".. start_delay.." seconds")
sleep( start_delay*1000 )
end
-- CAMERA CONFIGURATION -
-- FIND config table here http://subversion.assembla.com/svn/chdk/trunk/core/conf.c
set_config_value(2,0) --Save raw: off
if (gps==1) then
set_config_value(282,1) --turn GPS on
--set_config_value(278,1) --show GPS symbol
set_config_value(261,1) --wait for signal time
set_config_value(266,5) --battery shutdown percentage
end
-- enable USB remote in USB remote moded
if (usb_mode > 0 ) then
set_config_value(121,1) -- make sure USB remote is enabled
if (get_usb_power(1) == 0) then -- can we start ?
printf("waiting on USB signal")
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
--changed sleep from 1000 to 500
else sleep(500) end
printf("USB signal received")
end
-- switch to shooting mode
switch_mode(1)
-- set zoom position
update_zoom(zoom_setpoint)
-- lock focus at infinity
lock_focus()
-- disable flash and AF assist lamp
set_prop(props.FLASH_MODE, 2) -- flash off
set_prop(props.AF_ASSIST_BEAM,0) -- AF assist off if supported for this camera
set_config_value( 297, 60) -- set console timeout to 60 seconds
if (usb_mode > 2 ) then repeat until (get_usb_power(2) == 0 ) end -- flush pulse buffer
next_shot_time = get_tick_count()
script_exit = false
if( get_video_button() == 1) then video_button = true else video_button = false end
set_console_layout(2 ,0, 45, 4 )
repeat
--BB: Set get_usb_power(2) > 7 for a 70/100s pulse
--BB: Could consider a max threshold to prevent erroneous trigger events
--eg. get_usb_power(2) > 7 && get_usb_power(2) < 13
if( ( (usb_mode < 2 ) and ( next_shot_time <= get_tick_count() ) )
or ( (usb_mode == 2 ) and (get_usb_power(2) > 7 ) )
or ( (usb_mode == 3 ) and (shot_request == true ) ) ) then
-- time to insert a video sequence ?
if( check_video(shot_count) == true) then next_shot_time = get_tick_count() end
-- intervalometer timing
next_shot_time = next_shot_time + interval
-- set focus at infinity ? (maybe redundant for AFL & MF mode but makes sure it's set right)
if (focus_mode > 0) then
set_focus(infx)
sleep(100)
end
-- check exposure
local count = 0
local timeout = false
press("shoot_half")
repeat
sleep(50)
count = count + 1
if (count > 40 ) then timeout = true end
until (get_shooting() == true ) or (timeout == true)
-- shoot in auto mode if meter reading invalid, else calculate new desired exposure
if ( timeout == true ) then
release("shoot_half")
repeat sleep(50) until get_shooting() == false
shoot() -- shoot in Canon auto mode if we don't have a valid meter reading
shot_count = shot_count + 1
printf(string.format('IMG_%04d.JPG',get_exp_count()).." : shot in auto mode, meter reading invalid")
else
-- get meter reading values (and add in exposure compensation)
bv96raw=get_bv96()
bv96meter=bv96raw-ec96adjust
tv96meter=get_tv96()
av96meter=get_av96()
sv96meter=get_sv96()
-- set minimum Av to larger of user input or current min for zoom setting
av96min= math.max(av96minimum,get_prop(props.MIN_AV))
if (av96target < av96min) then av96target = av96min end
-- calculate required setting for current ambient light conditions
if (Av_mode == 1) then exposure_iris()
elseif (Av_mode == 2) then exposure_NDfilter()
elseif (Av_mode == 3) then exposure_both()
else exposure_Tv_only()
end
-- set up all exposure overrides
set_tv96_direct(tv96setpoint)
set_sv96(sv96setpoint)
if( av96setpoint ~= nil) then set_av96_direct(av96setpoint) end
if(Av_mode > 1) and (insert_ND_filter == true) then -- ND filter available and needed?
set_nd_filter(1) -- activate the ND filter
nd_string="NDin"
else
set_nd_filter(2) -- make sure the ND filter does not activate
nd_string="NDout"
end
-- and finally shoot the image
press("shoot_full_only")
sleep(100)
release("shoot_full")
repeat sleep(50) until get_shooting() == false
shot_count = shot_count + 1
-- update shooting statistic and log as required
shot_focus=get_focus()
if(shot_focus ~= -1) and (shot_focus < 20000) then
focus_string=" foc:"..(shot_focus/1000).."."..(((shot_focus%1000)+50)/100).."m"
if(focus_mode>0) then
error_string=" **WARNING : focus not at infinity**"
end
else
focus_string=" foc:infinity"
error_string=nil
end
printf(string.format('%d) IMG_%04d.JPG',shot_count,get_exp_count()))
printf(" meter : Tv:".. print_tv(tv96meter) .." Av:".. print_av(av96meter) .." Sv:"..print_sv(sv96meter).." "..bv96raw ..":"..bv96meter)
printf(" actual: Tv:".. print_tv(tv96setpoint).." Av:".. print_av(av96setpoint).." Sv:"..print_sv(sv96setpoint))
printf(" AvMin:".. print_av(av96min).." NDF:"..nd_string..focus_string )
if ((max_shots>0) and (shot_count >= max_shots)) then script_exit = true end
shot_request = false -- reset shot request flag
end
collectgarbage()
end
-- check if USB remote enabled in intervalometer mode and USB power is off -> pause if so
if ((usb_mode == 1 ) and (get_usb_power(1) == 0)) then
printf("waiting on USB signal")
unlock_focus()
switch_mode(0)
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
switch_mode(1)
lock_focus()
if ( is_key("menu")) then script_exit = true end
printf("USB wait finished")
sleep(100)
end
if (usb_mode == 3 ) then pwm_mode(get_usb_power(2)) end
if (blite_timer > 0) then
blite_timer = blite_timer-1
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(0) end
end
if( error_string ~= nil) then
draw_string( 16, 144, string.sub(error_string.." ",0,42), 258, 259)
end
wait_click(100)
if( not( is_key("no_key"))) then
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(1) end
blite_timer=300
if ( is_key("menu") ) then script_exit = true end
end
until (script_exit==true)
printf("script halt requested")
restore()
end
--[[ end of file ]]--
| gpl-3.0 |
Vermeille/kong | kong/plugins/http-log/handler.lua | 4 | 3188 | local basic_serializer = require "kong.plugins.log-serializers.basic"
local BasePlugin = require "kong.plugins.base_plugin"
local cjson = require "cjson"
local url = require "socket.url"
local HttpLogHandler = BasePlugin:extend()
HttpLogHandler.PRIORITY = 1
local HTTPS = "https"
-- Generates http payload .
-- @param `method` http method to be used to send data
-- @param `parsed_url` contains the host details
-- @param `message` Message to be logged
-- @return `body` http payload
local function generate_post_payload(method, parsed_url, body)
return string.format(
"%s %s HTTP/1.1\r\nHost: %s\r\nConnection: Keep-Alive\r\nContent-Type: application/json\r\nContent-Length: %s\r\n\r\n%s",
method:upper(), parsed_url.path, parsed_url.host, string.len(body), body)
end
-- Parse host url
-- @param `url` host url
-- @return `parsed_url` a table with host details like domain name, port, path etc
local function parse_url(host_url)
local parsed_url = url.parse(host_url)
if not parsed_url.port then
if parsed_url.scheme == "http" then
parsed_url.port = 80
elseif parsed_url.scheme == HTTPS then
parsed_url.port = 443
end
end
if not parsed_url.path then
parsed_url.path = "/"
end
return parsed_url
end
-- Log to a Http end point.
-- @param `premature`
-- @param `conf` Configuration table, holds http endpoint details
-- @param `message` Message to be logged
local function log(premature, conf, body, name)
if premature then return end
name = "["..name.."] "
local ok, err
local parsed_url = parse_url(conf.http_endpoint)
local host = parsed_url.host
local port = tonumber(parsed_url.port)
local sock = ngx.socket.tcp()
sock:settimeout(conf.timeout)
ok, err = sock:connect(host, port)
if not ok then
ngx.log(ngx.ERR, name.."failed to connect to "..host..":"..tostring(port)..": ", err)
return
end
if parsed_url.scheme == HTTPS then
local _, err = sock:sslhandshake(true, host, false)
if err then
ngx.log(ngx.ERR, name.."failed to do SSL handshake with "..host..":"..tostring(port)..": ", err)
end
end
ok, err = sock:send(generate_post_payload(conf.method, parsed_url, body))
if not ok then
ngx.log(ngx.ERR, name.."failed to send data to "..host..":"..tostring(port)..": ", err)
end
ok, err = sock:setkeepalive(conf.keepalive)
if not ok then
ngx.log(ngx.ERR, name.."failed to keepalive to "..host..":"..tostring(port)..": ", err)
return
end
end
-- Only provide `name` when deriving from this class. Not when initializing an instance.
function HttpLogHandler:new(name)
HttpLogHandler.super.new(self, name or "http-log")
end
-- serializes context data into an html message body
-- @param `ngx` The context table for the request being logged
-- @return html body as string
function HttpLogHandler:serialize(ngx)
return cjson.encode(basic_serializer.serialize(ngx))
end
function HttpLogHandler:log(conf)
HttpLogHandler.super.log(self)
local ok, err = ngx.timer.at(0, log, conf, self:serialize(ngx), self._name)
if not ok then
ngx.log(ngx.ERR, "["..self._name.."] failed to create timer: ", err)
end
end
return HttpLogHandler
| apache-2.0 |
pokorj18/vlc | share/lua/intf/http.lua | 9 | 10566 | --[==========================================================================[
http.lua: HTTP interface module for VLC
--[==========================================================================[
Copyright (C) 2007-2009 the VideoLAN team
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
--[==========================================================================[
Configuration options:
* dir: Directory to use as the http interface's root.
* no_error_detail: If set, do not print the Lua error message when generating
a page fails.
* no_index: If set, don't build directory indexes
--]==========================================================================]
require "common"
vlc.msg.info("Lua HTTP interface")
open_tag = "<?vlc"
close_tag = "?>"
-- TODO: use internal VLC mime lookup function for mimes not included here
local mimes = {
txt = "text/plain",
json = "text/plain",
html = "text/html",
xml = "text/xml",
js = "text/javascript",
css = "text/css",
png = "image/png",
jpg = "image/jpeg",
jpeg = "image/jpeg",
ico = "image/x-icon",
}
function escape(s)
return (string.gsub(s,"([%^%$%%%.%[%]%*%+%-%?])","%%%1"))
end
function process_raw(filename)
local input = io.open(filename):read("*a")
-- find the longest [===[ or ]=====] type sequence and make sure that
-- we use one that's longer.
local str="X"
for str2 in string.gmatch(input,"[%[%]]=*[%[%]]") do
if #str < #str2 then str = str2 end
end
str=string.rep("=",#str-1)
--[[ FIXME:
<?xml version="1.0" encoding="charset" standalone="yes" ?> is still a problem. The closing '?>' needs to be printed using '?<?vlc print ">" ?>' to prevent a parse error.
--]]
local code0 = string.gsub(input,escape(close_tag)," print(["..str.."[")
local code1 = string.gsub(code0,escape(open_tag),"]"..str.."]) ")
local code = "print(["..str.."["..code1.."]"..str.."])"
--[[ Uncomment to debug
if string.match(filename,"vlm_cmd.xml$") then
io.write(code)
io.write("\n")
end
--]]
return assert(loadstring(code,filename))
end
function process(filename)
local mtime = 0 -- vlc.net.stat(filename).modification_time
local func = false -- process_raw(filename)
return function(...)
local new_mtime = vlc.net.stat(filename).modification_time
if new_mtime ~= mtime then
-- Re-read the file if it changed
if mtime == 0 then
vlc.msg.dbg("Loading `"..filename.."'")
else
vlc.msg.dbg("Reloading `"..filename.."'")
end
func = process_raw(filename)
mtime = new_mtime
end
return func(...)
end
end
function callback_error(path,url,msg)
local url = url or "<page unknown>"
return [[<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Error loading ]]..url..[[</title>
</head>
<body>
<h1>Error loading ]]..url..[[</h1><pre>]]..(config.no_error_detail and "Remove configuration option `no_error_detail' on the server to get more information." or tostring(msg))..[[</pre>
<p>
<a href="http://www.videolan.org/">VideoLAN</a><br/>
<a href="http://www.lua.org/manual/5.1/">Lua 5.1 Reference Manual</a>
</p>
</body>
</html>]]
end
function dirlisting(url,listing,acl_)
local list = {}
for _,f in ipairs(listing) do
if not string.match(f,"^%.") then
table.insert(list,"<li><a href='"..f.."'>"..f.."</a></li>")
end
end
list = table.concat(list)
local function callback()
return [[<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Directory listing ]]..url..[[</title>
</head>
<body>
<h1>Directory listing ]]..url..[[</h1><ul>]]..list..[[</ul>
</body>
</html>]]
end
return h:file(url,"text/html",nil,nil,acl_,callback,nil)
end
-- FIXME: Experimental art support. Needs some cleaning up.
function callback_art(data, request, args)
local art = function(data, request)
local num = nil
if args ~= nil then
num = string.gmatch(args, "item=(.*)")
if num ~= nil then
num = num()
end
end
local item
if num == nil then
item = vlc.input.item()
else
item = vlc.playlist.get(num).item
end
local metas = item:metas()
local filename = vlc.strings.decode_uri(string.gsub(metas["artwork_url"],"file://",""))
local size = vlc.net.stat(filename).size
local ext = string.match(filename,"%.([^%.]-)$")
local raw = io.open(filename):read("*a")
local content = [[Content-Type: ]]..mimes[ext]..[[
Content-Length: ]]..size..[[
]]..raw..[[
]]
return content
end
local ok, content = pcall(art, data, request)
if not ok then
return [[Status: 404
Content-Type: text/plain
Content-Length: 5
Error
]]
end
return content
end
function file(h,path,url,acl_,mime)
local generate_page = process(path)
local callback = function(data,request)
-- FIXME: I'm sure that we could define a real sandbox
-- redefine print
local page = {}
local function pageprint(...)
for i=1,select("#",...) do
if i== 1 then
table.insert(page,tostring(select(i,...)))
else
table.insert(page," "..tostring(select(i,...)))
end
end
end
_G._GET = parse_url_request(request)
local oldprint = print
print = pageprint
local ok, msg = pcall(generate_page)
-- reset
print = oldprint
if not ok then
return callback_error(path,url,msg)
end
return table.concat(page)
end
return h:file(url or path,mime,nil,nil,acl_,callback,nil)
end
function rawfile(h,path,url,acl_)
local filename = path
local mtime = 0 -- vlc.net.stat(filename).modification_time
local page = false -- io.open(filename):read("*a")
local callback = function(data,request)
local new_mtime = vlc.net.stat(filename).modification_time
if mtime ~= new_mtime then
-- Re-read the file if it changed
if mtime == 0 then
vlc.msg.dbg("Loading `"..filename.."'")
else
vlc.msg.dbg("Reloading `"..filename.."'")
end
page = io.open(filename,"rb"):read("*a")
mtime = new_mtime
end
return page
end
return h:file(url or path,nil,nil,nil,acl_,callback,nil)
end
function parse_url_request(request)
if not request then return {} end
local t = {}
for k,v in string.gmatch(request,"([^=&]+)=?([^=&]*)") do
local k_ = vlc.strings.decode_uri(k)
local v_ = vlc.strings.decode_uri(v)
if t[k_] ~= nil then
local t2
if type(t[k_]) ~= "table" then
t2 = {}
table.insert(t2,t[k_])
t[k_] = t2
else
t2 = t[k_]
end
table.insert(t2,v_)
else
t[k_] = v_
end
end
return t
end
local function find_datadir(name)
local list = vlc.config.datadir_list(name)
for _, l in ipairs(list) do
local s = vlc.net.stat(l)
if s then
return l
end
end
error("Unable to find the `"..name.."' directory.")
end
http_dir = config.dir or find_datadir("http")
do
local oldpath = package.path
package.path = http_dir.."/?.lua"
local ok, err = pcall(require,"custom")
if not ok then
vlc.msg.warn("Couldn't load "..http_dir.."/custom.lua",err)
else
vlc.msg.dbg("Loaded "..http_dir.."/custom.lua")
end
package.path = oldpath
end
local files = {}
local function load_dir(dir,root,parent_acl)
local root = root or "/"
local has_index = false
local my_acl = parent_acl
do
local af = dir.."/.hosts"
local s = vlc.net.stat(af)
if s and s.type == "file" then
-- We found an acl
my_acl = vlc.acl(false)
my_acl:load_file(af)
end
end
local d = vlc.net.opendir(dir)
for _,f in ipairs(d) do
if not string.match(f,"^%.") then
local s = vlc.net.stat(dir.."/"..f)
if s.type == "file" then
local url
if f == "index.html" then
url = root
has_index = true
else
url = root..f
end
local ext = string.match(f,"%.([^%.]-)$")
local mime = mimes[ext]
-- print(url,mime)
if mime and string.match(mime,"^text/") then
table.insert(files,file(h,dir.."/"..f,url,my_acl,mime))
else
table.insert(files,rawfile(h,dir.."/"..f,url,my_acl))
end
elseif s.type == "dir" then
load_dir(dir.."/"..f,root..f.."/",my_acl)
end
end
end
if not has_index and not config.no_index then
-- print("Adding index for", root)
table.insert(files,dirlisting(root,d,my_acl))
end
return my_acl
end
if config.host then
vlc.msg.err("\""..config.host.."\" HTTP host ignored")
local port = string.match(config.host, ":(%d+)[^]]*$")
vlc.msg.info("Pass --http-host=IP "..(port and "and --http-port="..port.." " or "").."on the command line instead.")
end
h = vlc.httpd()
local root_acl = load_dir( http_dir )
local a = h:handler("/art",nil,nil,root_acl,callback_art,nil)
while not vlc.misc.lock_and_wait() do end -- everything happens in callbacks
| gpl-2.0 |
pablo93/TrinityCore | Data/Interface/FrameXML/RestrictedExecution.lua | 1 | 25213 | -- RestrictedExecution.lua (Part of the new Secure Headers implementation)
--
-- This contains the necessary (and sufficient) code to support
-- 'restricted execution' for code provided via attributes, intended
-- for use in the secure header implementations. It provides a fairly
-- isolated execution environment and is constructed to maintain local
-- control over the important elements of the execution environment.
--
-- Daniel Stephens (iriel@vigilance-committee.org)
-- Nevin Flanagan (alestane@comcast.net)
---------------------------------------------------------------------------
-- Localizes for functions that are frequently called or need to be
-- assuredly un-replaceable or unhookable.
local type = type;
local error = error;
local scrub = scrub;
local issecure = issecure;
local rawset = rawset;
local setfenv = setfenv;
local loadstring = loadstring;
local setmetatable = setmetatable;
local getmetatable = getmetatable;
local pcall = pcall;
local tostring = tostring;
local next = next;
local unpack = unpack;
local newproxy = newproxy;
local select = select;
local wipe = wipe;
local tonumber = tonumber;
local t_insert = table.insert;
local t_maxn = table.maxn;
local t_concat = table.concat;
local t_sort = table.sort;
local t_remove = table.remove;
local IsFrameHandle = IsFrameHandle;
---------------------------------------------------------------------------
-- RESTRICTED CLOSURES
local function SelfScrub(self)
if (self ~= nil and IsFrameHandle(self)) then
return self;
end
return nil;
end
-- closure, err = BuildRestrictedClosure(body, env, signature)
--
-- body -- The function body (defaults to "")
-- env -- The execution environment (defaults to {})
-- signature -- The function signature (defaults to "self,...")
--
-- Returns the constructed closure, or nil and an error
local function BuildRestrictedClosure(body, env, signature)
body = tostring(body) or "";
signature = tostring(signature) or "self,...";
if (type(env) ~= "table") then
env = {};
end
if (body:match("function")) then
-- NOTE - This is overzealous but it keeps it simple
return nil, "The function keyword is not permitted";
end
if (body:match("[{}]")) then
-- NOTE - This is overzealous but it keeps it simple
return nil, "Direct table creation is not permitted";
end
if (signature:match("function")) then
-- NOTE - This is overzealous but it keeps it simple
return nil, "The function keyword is not permitted";
end
if (not signature:match("^[a-zA-Z_0-9, ]*[.]*$")) then
-- NOTE - This is overzealous but it keeps it simple
return nil, "Signature contains invalid characters (" .. signature .. ")";
end
-- Include a \n before end to stop shenanigans with comments
local def, err =
loadstring("return function (" .. signature .. ") " .. body .. "\nend", body);
if (def == nil) then
return nil, err;
end
-- Use a completely empty environment here to be absolutely
-- sure to avoid tampering during function definition.
setfenv(def, {});
def = def();
-- Double check that the definition did infact return a function
if (type(def) ~= "function") then
return nil, "Invalid body";
end
-- Set the desired environment on the resulting closure.
setfenv(def, env);
-- And then return a 'safe' wrapped invocation for the closure.
return function(self, ...) return def(SelfScrub(self), scrub(...)) end;
end
-- factory = CreateClosureFactory(env, signature)
--
-- env -- The desired environment table for the closures
-- signature -- The function signature for the closures
--
-- Returns a 'factory table' which is keyed by function bodies, and
-- has restricted closure values. It's weak-keyed and uses an __index
-- metamethod that automatically creates necessary closures on demand.
local function CreateClosureFactory(env, signature)
local function metaIndex(t, k)
if (type(k) == "string") then
local closure, err = BuildRestrictedClosure(k, env, signature);
if (not closure) then
-- Put the error into a closure to avoid constantly
-- re-parsing it
err = tostring(err or "Closure creation failed");
closure = function() error(err) end;
end
if (issecure()) then
t[k] = closure;
end
return closure;
end
error("Invalid closure body type (" .. type(k) .. ")");
return nil;
end
local ret = {};
setmetatable(ret, { __index = metaIndex, __mode = "k" });
return ret;
end
---------------------------------------------------------------------------
-- RESTRICTED TABLES
--
-- Provides fully proxied tables with restrictions on their contents.
--
-- Mapping table from restricted table 'proxy' to the 'real' storage
local LOCAL_Restricted_Tables = {};
setmetatable(LOCAL_Restricted_Tables, { __mode="k" });
-- Metatable common to all restricted tables (This introduces one
-- level of indirection in every use as a means to share the same
-- metatable between all instances)
local LOCAL_Restricted_Table_Meta = {
__index = function(t, k)
local real = LOCAL_Restricted_Tables[t];
return real[k];
end,
__newindex = function(t, k, v)
local real = LOCAL_Restricted_Tables[t];
if (not issecure()) then
error("Cannot insecurely modify restricted table");
return;
end
local tv = type(v);
if ((tv ~= "string") and (tv ~= "number")
and (tv ~= "boolean") and (tv ~= "nil")
and ((tv ~= "userdata")
or not (LOCAL_Restricted_Tables[v]
or IsFrameHandle(v)))) then
error("Invalid value type '" .. tv .. "'");
return;
end
local tk = type(k);
if ((tk ~= "string") and (tk ~= "number")
and (tk ~= "boolean")
and ((tv ~= "userdata")
or not (IsFrameHandle(v)))) then
error("Invalid key type '" .. tk .. "'");
return;
end
real[k] = v;
end,
__len = function(t)
local real = LOCAL_Restricted_Tables[t];
return #real;
end,
__metatable = false, -- False means read-write proxy
}
local LOCAL_Readonly_Restricted_Tables = {};
setmetatable(LOCAL_Readonly_Restricted_Tables, { __mode="k" });
local function CheckReadonlyValue(ret)
if (type(ret) == "userdata") then
if (LOCAL_Restricted_Tables[ret]) then
if (getmetatable(ret)) then
return ret;
end
return LOCAL_Readonly_Restricted_Tables[ret];
end
end
return ret;
end
-- Metatable common to all read-only restricted tables (This also introduces
-- indirection so that a single metatable is viable)
local LOCAL_Readonly_Restricted_Table_Meta = {
__index = function(t, k)
local real = LOCAL_Restricted_Tables[t];
return CheckReadonlyValue(real[k]);
end,
__newindex = function(t, k, v)
error("Table is read-only");
end,
__len = function(t)
local real = LOCAL_Restricted_Tables[t];
return #real;
end,
__metatable = true, -- True means read-only proxy
}
local LOCAL_Restricted_Prototype = newproxy(true);
local LOCAL_Readonly_Restricted_Prototype = newproxy(true);
do
local meta = getmetatable(LOCAL_Restricted_Prototype);
for k, v in pairs(LOCAL_Restricted_Table_Meta) do
meta[k] = v;
end
meta = getmetatable(LOCAL_Readonly_Restricted_Prototype);
for k, v in pairs(LOCAL_Readonly_Restricted_Table_Meta) do
meta[k] = v;
end
end
local function RestrictedTable_Readonly_index(t, k)
local real = LOCAL_Restricted_Tables[k];
if (not real) then return; end
if (not issecure()) then
error("Cannot create restricted tables from insecure code");
return;
end
local ret = newproxy(LOCAL_Readonly_Restricted_Prototype);
LOCAL_Restricted_Tables[ret] = real;
t[k] = ret;
return ret;
end
getmetatable(LOCAL_Readonly_Restricted_Tables).__index
= RestrictedTable_Readonly_index;
-- table = RestrictedTable_create(...)
--
-- Create a new, restricted table, populating it from ... if
-- necessary, similar to the way the normal table constructor
-- works.
local function RestrictedTable_create(...)
local ret = newproxy(LOCAL_Restricted_Prototype);
if (not issecure()) then
error("Cannot create restricted tables from insecure code");
return;
end
LOCAL_Restricted_Tables[ret] = {};
-- Use this loop to ensure that the contents of the new
-- table are all allowed
for i = 1, select('#', ...) do
ret[i] = select(i, ...);
end
return ret;
end
-- table = GetReadonlyRestrictedTable(otherTable)
--
-- Given a restricted table, return a read-only proxy to the same
-- table (which will be itself, if it's already read-only)
function GetReadonlyRestrictedTable(ref)
if (LOCAL_Restricted_Tables[ref]) then
if (getmetatable(ref)) then
return ref;
end
return LOCAL_Readonly_Restricted_Tables[ref];
end
error("Invalid restricted table");
end
-- key = RestrictedTable_next(table [,key])
--
-- An implementation of the next function, which is
-- aware of restricted and normal tables and behaves consistently
-- for both.
local function RestrictedTable_next(T, k)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
if (getmetatable(T)) then
local idx, val = next(PT, k);
if (val ~= nil) then
return idx, CheckReadonlyValue(val);
else
return idx, val;
end
else
return next(PT, k);
end
end
return next(T, k);
end
-- iterfunc, table, key = RestrictedTable_pairs(table)
--
-- An implementation of the pairs function, which is aware
-- of and iterates over both restricted and normal tables.
local function RestrictedTable_pairs(T)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
-- v
return RestrictedTable_next, T, nil;
end
return pairs(T);
end
-- key, value = RestrictedTable_ipairsaux(table, prevkey)
--
-- Iterator function for internal use by restricted table ipairs
local function RestrictedTable_ipairsaux(T, i)
i = i + 1;
local v = T[i];
if (v) then
return i, v;
end
end
-- iterfunc, table, key = RestrictedTable_ipairs(table)
--
-- An implementation of the ipairs function, which is aware
-- of and iterates over both restricted and normal tables.
local function RestrictedTable_ipairs(T)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
return RestrictedTable_ipairsaux, T, 0;
end
return ipairs(T);
end
-- Recursive helper to ensure all values from a list are properly converted
-- to read-only proxies
local RestrictedTable_unpack_ro;
function RestrictedTable_unpack_ro(...)
local n = select('#', ...);
if (n == 0) then
return;
end
return CheckReadonlyValue(...), RestrictedTable_unpack_ro(select(2, ...));
end
-- ... = RestrictedTable_unpack(table)
--
-- An implementation of unpack which unpacks both restricted
-- and normal tables.
local function RestrictedTable_unpack(T)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
if (getmetatable(T)) then
return RestrictedTable_unpack_ro(unpack(PT));
end
return unpack(PT)
end
return unpack(T);
end
-- table = RestrictedTable_wipe(table)
--
-- A restricted aware implementation of wipe()
local function RestrictedTable_wipe(T)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
if (getmetatable(T)) then
error("Cannot wipe a read-only table");
return;
end
if (not issecure()) then
error("Cannot insecurely modify restricted table");
return;
end
wipe(PT);
return T;
end
return wipe(T);
end
-- RestrictedTable_maxn(table)
--
-- A restricted aware implementation of table.maxn()
local function RestrictedTable_maxn(T)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
return t_maxn(PT);
end
return t_maxn(T);
end
-- RestrictedTable_concat(table)
--
-- A restricted aware implementation of table.concat()
local function RestrictedTable_concat(T)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
return t_concat(PT);
end
return t_concat(T);
end
-- RestrictedTable_sort(table, func)
--
-- A restricted aware implementation of table.sort()
local function RestrictedTable_sort(T, func)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
if (getmetatable(T)) then
error("Cannot sort a read-only table");
return;
end
if (not issecure()) then
error("Cannot insecurely modify restricted table");
return;
end
t_sort(PT, func);
return;
end
t_sort(T, func);
end
-- RestrictedTable_insert(table [,pos], val)
--
-- A restricted aware implementation of table.insert()
local function RestrictedTable_insert(T, ...)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
if (getmetatable(T)) then
error("Cannot insert into a read-only table");
return;
end
local pos, val;
if (select('#', ...) == 1) then
T[#PT] = val;
return;
end
pos, val = ...;
pos = tonumber(pos);
t_insert(PT, pos, nil);
-- Leverage protections present on regular indexing
T[pos] = val;
return;
end
return t_insert(T, ...);
end
-- val = RestrictedTable_remove(table, pos)
--
-- A restricted aware implementation of table.remove()
local function RestrictedTable_remove(T, pos)
local PT = LOCAL_Restricted_Tables[T];
if (PT) then
if (getmetatable(T)) then
error("Cannot remove from a read-only table");
return;
end
if (not issecure()) then
error("Cannot insecurely modify restricted table");
return;
end
return CheckReadonlyValue(t_remove(PT, pos));
end
return t_remove(T, pos);
end
-- objtype = type(obj)
--
-- A version of type which returns 'table' for restricted tables
local function RestrictedTable_type(obj)
local t = type(obj);
if (t == "userdata") then
if (LOCAL_Restricted_Tables[obj]) then
t = "table";
end
end
return t;
end
-- Export these functions so that addon code can use them if desired
-- and so that the handlers can create these tables
rtable = {
next = RestrictedTable_next;
pairs = RestrictedTable_pairs;
ipairs = RestrictedTable_ipairs;
unpack = RestrictedTable_unpack;
newtable = RestrictedTable_create;
maxn = RestrictedTable_maxn;
insert = RestrictedTable_insert;
remove = RestrictedTable_remove;
sort = RestrictedTable_sort;
concat = RestrictedTable_concat;
wipe = RestrictedTable_wipe;
type = RestrictedTable_type;
};
local LOCAL_Table_Namespace = {
table = {
maxn = RestrictedTable_maxn;
insert = RestrictedTable_insert;
remove = RestrictedTable_remove;
sort = RestrictedTable_sort;
concat = RestrictedTable_concat;
wipe = RestrictedTable_wipe;
new = RestrictedTable_create;
}
};
---------------------------------------------------------------------------
-- RESTRICTED ENVIRONMENT
--
-- environment, manageFunc = CreateRestrictedEnvironment(baseEnvironment)
--
-- baseEnvironment -- The base environment table (containing functions)
--
-- environment -- The new restricted environment table
-- manageFunc -- Management function to set/clear working and proxy
-- environments.
--
-- The management function takes two parameters
-- manageFunc(set, workingTable, controlHandle)
--
-- set is a boolean; If it's true then the working table is set to the
-- specified value (pushing any previous environment onto a stack). If
-- it's false then the working table is unset (and restored from stack).
--
-- The working table should be a restricted table, or an immutable object.
--
-- The controlHandle is an optional object which is made available to
-- the restricted code with the name 'control'.
--
-- The management function monitors calls to get and set in order to prevent
-- re-entrancy (i.e. calls to get and set must be balanced, and one cannot
-- switch working tables in the middle).
local function CreateRestrictedEnvironment(base)
if (type(base) ~= "table") then base = {}; end
local working, control, depth = nil, nil, 0;
local workingStack, controlStack = {}, {};
local result = {};
local meta_index;
local function meta_index(t, k)
local v = base[k] or working[k];
if (v == nil) then
if (k == "control") then return control; end
end
return v;
end;
local function meta_newindex(t, k, v)
working[k] = v;
end
local meta = {
__index = meta_index,
__newindex = meta_newindex,
__metatable = false;
__environment = false;
}
setmetatable(result, meta);
local function manage(set, newWorking, newControl)
if (set) then
if (depth == 0) then
depth = 1;
else
workingStack[depth] = working;
controlStack[depth] = control;
depth = depth + 1;
end
working = newWorking;
control = newControl;
else
if (depth == 0) then
error("Attempted to release unused environment");
return;
end
if (working ~= newWorking) then
error("Working environment mismatch at release");
return;
end
if (control ~= newControl) then
error("Control handle mismatch at release");
return;
end
depth = depth - 1;
if (depth == 0) then
working = nil;
control = nil;
else
working = workingStack[depth];
control = controlStack[depth];
workingStack[depth] = nil;
controlStack[depth] = nil;
end
end
end
return result, manage;
end
---------------------------------------------------------------------------
-- AVAILABLE FUNCTIONS
--
-- The current implementation has a single set of functions (aka a single
-- base environment), this initializes that environment by creating a master
-- base environment table, and then creating a restricted environment
-- around that. If the RESTRICTED_FUNCTIONS_SCOPE table exists when
-- this file is executed then its contents are added to the environment.
--
-- It is expected that any functions that are to be placed into this
-- environment have been carefully written to not return arbtirary tables,
-- functions, or userdata back to the caller.
--
-- One can use function(...) return scrub(realFunction(...)) end to wrap
-- those functions one doesn't trust.
-- A metatable to prevent tampering with the environment tables.
local LOCAL_No_Secure_Update_Meta = {
__newindex = function() end;
__metatable = false;
};
local LOCAL_Restricted_Global_Functions = {
newtable = RestrictedTable_create;
pairs = RestrictedTable_pairs;
ipairs = RestrictedTable_ipairs;
next = RestrictedTable_next;
unpack = RestrictedTable_unpack;
-- Table methods
wipe = RestrictedTable_wipe;
tinsert = RestrictedTable_insert;
tremove = RestrictedTable_remove;
-- Synthetic restricted-table-aware 'type'
type = RestrictedTable_type;
};
-- A helper function to recursively copy and protect scopes
local PopulateGlobalFunctions
function PopulateGlobalFunctions(src, dest)
for k, v in pairs(src) do
if (type(k) == "string") then
local tv = type(v);
if ((tv == "function") or (tv == "number") or (tv == "string") or (tv == "boolean")) then
dest[k] = v;
elseif (tv == "table") then
local subdest = {};
PopulateGlobalFunctions(v, subdest);
setmetatable(subdest, LOCAL_No_Secure_Update_Meta);
local dproxy = newproxy(true);
local dproxy_meta = getmetatable(dproxy);
dproxy_meta.__index = subdest;
dproxy_meta.__metatable = false;
dest[k] = dproxy;
end
end
end
end
-- Import any functions initialized by other/earier files
if (RESTRICTED_FUNCTIONS_SCOPE) then
PopulateGlobalFunctions(RESTRICTED_FUNCTIONS_SCOPE,
LOCAL_Restricted_Global_Functions);
RESTRICTED_FUNCTIONS_SCOPE = nil;
end
PopulateGlobalFunctions(LOCAL_Table_Namespace,
LOCAL_Restricted_Global_Functions);
-- Create the environment
local LOCAL_Function_Environment, LOCAL_Function_Environment_Manager =
CreateRestrictedEnvironment(LOCAL_Restricted_Global_Functions);
-- Protect from injection via the string metatable index
-- Assume for now that 'string' is relatively clean
local strmeta = getmetatable("x");
local newmetaindex = {};
for k, v in pairs(string) do newmetaindex[k] = v; end
setmetatable(newmetaindex, {
__index = function(t,k)
if (not issecure()) then
return string[k];
end
end;
__metatable = false;
});
strmeta.__index = newmetaindex;
strmeta.__metatable = string;
strmeta = nil;
newmetaindex = nil;
---------------------------------------------------------------------------
-- CLOSURE FACTORIES
--
-- An automatically populating table keyed by function signature with
-- values that are closure factories for those signatures.
local LOCAL_Closure_Factories = { };
local function ClosureFactories_index(t, signature)
if (type(signature) ~= "string") then
return;
end
local factory = CreateClosureFactory(LOCAL_Function_Environment, signature);
if (not issecure()) then
error("Cannot declare closure factories from insecure code");
return;
end
t[signature] = factory;
return factory;
end
setmetatable(LOCAL_Closure_Factories, { __index = ClosureFactories_index });
---------------------------------------------------------------------------
-- FUNCTION CALL
-- A helper method to release the restricted environment environment before
-- returning from the function call.
local function ReleaseAndReturn(workingEnv, ctrlHandle, pcallFlag, ...)
-- Tampering at this point will irrevocably taint the protected
-- environment, for now that's a handy protective measure.
LOCAL_Function_Environment_Manager(false, workingEnv, ctrlHandle);
if (pcallFlag) then
return ...;
end
error("Call failed: " .. tostring( (...) ) );
end
-- ? = CallRestrictedClosure(signature, workingEnv, onupdate, body, ...)
--
-- Invoke a managed closure, looking its definition up from a factory
-- and managing its environment during execution.
--
-- signature -- function signature
-- workingEnv -- the working environment, must be a restricted table
-- ctrlHandle -- a control handle
-- body -- function body
-- ... -- any arguments to pass to the executing closure
--
-- Returns whatever the restricted closure returns
function CallRestrictedClosure(signature, workingEnv, ctrlHandle, body, ...)
if (not LOCAL_Restricted_Tables[workingEnv]) then
error("Invalid working environment");
return;
end
signature = tostring(signature);
local factory = LOCAL_Closure_Factories[signature];
if (not factory) then
error("Invalid signature '" .. signature .. "'");
return;
end
local closure = factory[body];
if (not closure) then
-- Expect factory to have thrown an error
return;
end
if (not issecure()) then
error("Cannot call restricted closure from insecure code");
return;
end
if (type(ctrlHandle) ~= "userdata") then
ctrlHandle = nil;
end
LOCAL_Function_Environment_Manager(true, workingEnv, ctrlHandle);
return ReleaseAndReturn(workingEnv, ctrlHandle, pcall( closure, ... ) );
end
| gpl-2.0 |
alexandergall/snabbswitch | src/program/lisper/dev-env-docker/l2tp.lua | 28 | 7462 | #!snabb/src/snabb snsh
io.stdout:setvbuf'no'
io.stderr:setvbuf'no'
--L2TP IP-over-IPv6 tunnelling program for testing.
local function assert(v, ...)
if v then return v, ... end
error(tostring((...)), 2)
end
local ffi = require'ffi'
local S = require'syscall'
local C = ffi.C
local htons = require'syscall.helpers'.htons
local DEBUG = os.getenv'DEBUG'
local function hex(s)
return (s:gsub('(.)(.?)', function(c1, c2)
return c2 and #c2 == 1 and
string.format('%02x%02x ', c1:byte(), c2:byte()) or
string.format('%02x ', c1:byte())
end))
end
local digits = {}
for i=0,9 do digits[string.char(('0'):byte()+i)] = i end
for i=0,5 do digits[string.char(('a'):byte()+i)] = 10+i end
for i=0,5 do digits[string.char(('A'):byte()+i)] = 10+i end
local function parsehex(s)
return (s:gsub('[%s%:%.]*(%x)(%x)[%s%:%.]*', function(hi, lo)
local hi = digits[hi]
local lo = digits[lo]
return string.char(lo + hi * 16)
end))
end
local function open_tap(name)
local fd = assert(S.open('/dev/net/tun', 'rdwr, nonblock'))
local ifr = S.t.ifreq{flags = 'tap, no_pi', name = name}
assert(fd:ioctl('tunsetiff', ifr))
return fd
end
local function open_raw(name)
local fd = assert(S.socket('packet', 'raw, nonblock', htons(S.c.ETH_P.all)))
local ifr = S.t.ifreq{name = name}
assert(S.ioctl(fd, 'siocgifindex', ifr))
assert(S.bind(fd, S.t.sockaddr_ll{
ifindex = ifr.ivalue,
protocol = 'all'}))
return fd
end
local mtu = 1500
local rawbuf = ffi.new('uint8_t[?]', mtu)
local tapbuf = ffi.new('uint8_t[?]', mtu)
local function read_buf(buf, fd)
return buf, assert(S.read(fd, buf, mtu))
end
local function write(fd, s, len)
assert(S.write(fd, s, len))
end
local tapname, ethname, smac, dmac, sip, dip, sid, did = unpack(main.parameters)
if not (tapname and ethname and smac and dmac and sip and dip and sid and did) then
print('Usage: l2tp.lua TAP ETH SMAC DMAC SIP DIP SID DID')
print' TAP: the tunneled interface: will be created if not present.'
print' ETH: the tunneling interface: must have an IPv6 assigned.'
print' SMAC: the MAC address of ETH.'
print' DMAC: the MAC address of the gateway interface.'
print' SIP: the IPv6 of ETH (long form).'
print' DIP: the IPv6 of ETH at the other endpoint (long form).'
print' SID: session ID (hex)'
print' DID: peer session ID (hex)'
os.exit(1)
end
smac = parsehex(smac)
dmac = parsehex(dmac)
sip = parsehex(sip)
dip = parsehex(dip)
sid = parsehex(sid)
did = parsehex(did)
local tap = open_tap(tapname)
local raw = open_raw(ethname)
print('tap ', tapname)
print('raw ', ethname)
print('smac ', hex(smac))
print('dmac ', hex(dmac))
print('sip ', hex(sip))
print('dip ', hex(dip))
print('sid ', hex(sid))
print('did ', hex(did))
local l2tp_ct = ffi.typeof[[
struct {
// ethernet
char dmac[6];
char smac[6];
uint16_t ethertype;
// ipv6
uint32_t flow_id; // version, tc, flow_id
int8_t payload_length_hi;
int8_t payload_length_lo;
int8_t next_header;
uint8_t hop_limit;
char src_ip[16];
char dst_ip[16];
// l2tp
//uint32_t session_id;
char session_id[4];
char cookie[8];
} __attribute__((packed))
]]
local l2tp_ct_size = ffi.sizeof(l2tp_ct)
local l2tp_ctp = ffi.typeof('$*', l2tp_ct)
local function decap_l2tp_buf(buf, len)
if len < l2tp_ct_size then return nil, 'packet too small' end
local p = ffi.cast(l2tp_ctp, buf)
if p.ethertype ~= 0xdd86 then return nil, 'not ipv6' end
if p.next_header ~= 115 then return nil, 'not l2tp' end
local dmac = ffi.string(p.dmac, 6)
local smac = ffi.string(p.smac, 6)
local sip = ffi.string(p.src_ip, 16)
local dip = ffi.string(p.dst_ip, 16)
local sid = ffi.string(p.session_id, 4) --p.session_id
local payload_size = len - l2tp_ct_size
return smac, dmac, sip, dip, sid, l2tp_ct_size, payload_size
end
local function encap_l2tp_buf(smac, dmac, sip, dip, did, payload, payload_size, outbuf)
local p = ffi.cast(l2tp_ctp, outbuf)
ffi.copy(p.dmac, dmac)
ffi.copy(p.smac, smac)
p.ethertype = 0xdd86
p.flow_id = 0x60
local ipsz = payload_size + 12
p.payload_length_hi = bit.rshift(ipsz, 8)
p.payload_length_lo = bit.band(ipsz, 0xff)
p.next_header = 115
p.hop_limit = 64
ffi.copy(p.src_ip, sip)
ffi.copy(p.dst_ip, dip)
ffi.copy(p.session_id, did)
ffi.fill(p.cookie, 8)
ffi.copy(p + 1, payload, payload_size)
return outbuf, l2tp_ct_size + payload_size
end
--fast select ----------------------------------------------------------------
--select() is gruesome.
local band, bor, shl, shr = bit.band, bit.bor, bit.lshift, bit.rshift
local function getbit(b, bits)
return band(bits[shr(b, 3)], shl(1, band(b, 7))) ~= 0
end
local function setbit(b, bits)
bits[shr(b, 3)] = bor(bits[shr(b, 3)], shl(1, band(b, 7)))
end
ffi.cdef[[
typedef struct {
uint8_t bits[128]; // 1024 bits
} xfd_set;
int xselect(int, xfd_set*, xfd_set*, xfd_set*, void*) asm("select");
]]
local function FD_ISSET(d, set) return getbit(d, set.bits) end
local function FD_SET(d, set)
assert(d <= 1024)
setbit(d, set.bits)
end
local fds0 = ffi.new'xfd_set'
local fds = ffi.new'xfd_set'
local fds_size = ffi.sizeof(fds)
local rawfd = raw:getfd()
local tapfd = tap:getfd()
FD_SET(rawfd, fds0)
FD_SET(tapfd, fds0)
local maxfd = math.max(rawfd, tapfd) + 1
local EINTR = 4
local function can_read() --returns true if fd has data, false if timed out
ffi.copy(fds, fds0, fds_size)
::retry::
local ret = C.xselect(maxfd, fds, nil, nil, nil)
if ret == -1 then
if C.errno() == EINTR then goto retry end
error('select errno '..tostring(C.errno()))
end
return FD_ISSET(rawfd, fds), FD_ISSET(tapfd, fds)
end
------------------------------------------------------------------------------
while true do
local can_raw, can_tap = can_read()
if can_raw or can_tap then
if can_raw then
local buf, len = read_buf(rawbuf, raw)
local smac1, dmac1, sip1, dip1, did1, payload_offset, payload_size = decap_l2tp_buf(buf, len)
local accept = smac1
and smac1 == dmac
and dmac1 == smac
and dip1 == sip
and sip1 == dip
and did1 == sid
if DEBUG then
if accept or smac1 then
print('read', accept and 'accepted' or 'rejected')
print(' smac ', hex(smac1))
print(' dmac ', hex(dmac1))
print(' sip ', hex(sip1))
print(' dip ', hex(dip1))
print(' did ', hex(did1))
print(' # ', payload_size)
end
end
if accept then
write(tap, buf + payload_offset, payload_size)
end
end
if can_tap then
local payload, payload_size = read_buf(tapbuf, tap)
local frame, frame_size = encap_l2tp_buf(smac, dmac, sip, dip, did, payload, payload_size, rawbuf)
if DEBUG then
print('write')
print(' smac ', hex(smac))
print(' dmac ', hex(dmac))
print(' sip ', hex(sip))
print(' dip ', hex(dip))
print(' did ', hex(did))
print(' #in ', payload_size)
print(' #out ', frame_size)
end
write(raw, frame, frame_size)
end
end
end
tap:close()
raw:close()
| apache-2.0 |
MRAHS/UBTEST | plugins/Quran.lua | 20 | 1243 | do
umbrella = "http://umbrella.shayan-soft.ir/quran/" -- database
-- get sound of sura
local function read_sura(chat_id, target)
local readq = http.request(umbrella.."Sura"..target..".mp3")
local url = umbrella.."Sura"..target..".mp3"
local file = download_to_file(url)
local cb_extra = {file_path=file}
return send_document("chat#id"..chat_id, file, rmtmp_cb, cb_extra)
end
-- get text of sura
local function view_sura(chat_id, target)
local viewq = http.request(umbrella.."quran ("..target..").txt")
return viewq
end
-- run script
local function run(msg, matches)
local chat_id = msg.to.id
if matches[1] == "read" then
local target = matches[2]
return read_sura(chat_id, target)
elseif matches[1] == "sura" then
local target = matches[2]
return view_sura(chat_id, target)
elseif matches [1] == "quran" then
local qlist = http.request(umbrella.."list.txt") -- list of suras
return qlist
end
end
-- other help and commands
return {
description = "Umbrella Quran Project",
usage = {
"!sura (num) : view arabic sura",
"!read (num) : send sound of sura",
"!quran : sura list of quran",
},
patterns = {
"^[!/](sura) (.+)$",
"^[!/](read) (.+)$",
"^[!/](quran)$",
},
run = run,
}
end
| gpl-2.0 |
Elanis/SciFi-Pack-Addon-Gamemode | gamemodes/scifipack/entities/weapons/gmod_tool/stools/colour.lua | 2 | 2007 |
TOOL.Category = "Construction"
TOOL.Name = "Couleur"
TOOL.Command = nil
TOOL.ConfigName = nil
TOOL.ClientConVar[ "r" ] = 255
TOOL.ClientConVar[ "g" ] = 0
TOOL.ClientConVar[ "b" ] = 255
TOOL.ClientConVar[ "a" ] = 255
TOOL.ClientConVar[ "mode" ] = 0
TOOL.ClientConVar[ "fx" ] = 0
local function SetColour( Player, Entity, Data )
--
-- If we're trying to make them transparent them make the render mode
-- a transparent type. This used to fix in the engine - but made HL:S props invisible(!)
--
if ( Data.Color && Data.Color.a < 255 && Data.RenderMode == 0 ) then
Data.RenderMode = 1
end
if ( Data.Color ) then Entity:SetColor( Color( Data.Color.r, Data.Color.g, Data.Color.b, Data.Color.a ) ) end
if ( Data.RenderMode ) then Entity:SetRenderMode( Data.RenderMode ) end
if ( Data.RenderFX ) then Entity:SetKeyValue( "renderfx", Data.RenderFX ) end
if ( SERVER ) then
duplicator.StoreEntityModifier( Entity, "colour", Data )
end
end
duplicator.RegisterEntityModifier( "colour", SetColour )
function TOOL:LeftClick( trace )
if trace.Entity && -- Hit an entity
trace.Entity:IsValid() && -- And the entity is valid
trace.Entity:EntIndex() != 0 -- And isn't worldspawn
then
if (CLIENT) then
return true
end
local r = self:GetClientNumber( "r", 0 )
local g = self:GetClientNumber( "g", 0 )
local b = self:GetClientNumber( "b", 0 )
local a = self:GetClientNumber( "a", 0 )
local mode = self:GetClientNumber( "mode", 0 )
local fx = self:GetClientNumber( "fx", 0 )
SetColour( self:GetOwner(), trace.Entity, { Color = Color( r, g, b, a ), RenderMode = mode, RenderFX = fx } )
return true
end
end
function TOOL:RightClick( trace )
if trace.Entity && -- Hit an entity
trace.Entity:IsValid() && -- And the entity is valid
trace.Entity:EntIndex() != 0 -- And isn't worldspawn
then
SetColour( self:GetOwner(), trace.Entity, { Color = Color( 255, 255, 255, 255 ), RenderMode = 0, RenderFX = 0 } )
return true
end
end
| gpl-2.0 |
xuejian1354/barrier_breaker | feeds/luci/modules/base/luasrc/i18n.lua | 77 | 3182 | --[[
LuCI - Internationalisation
Description:
A very minimalistic but yet effective internationalisation module
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
--- LuCI translation library.
module("luci.i18n", package.seeall)
require("luci.util")
local tparser = require "luci.template.parser"
table = {}
i18ndir = luci.util.libpath() .. "/i18n/"
loaded = {}
context = luci.util.threadlocal()
default = "en"
--- Clear the translation table.
function clear()
end
--- Load a translation and copy its data into the translation table.
-- @param file Language file
-- @param lang Two-letter language code
-- @param force Force reload even if already loaded (optional)
-- @return Success status
function load(file, lang, force)
end
--- Load a translation file using the default translation language.
-- Alternatively load the translation of the fallback language.
-- @param file Language file
-- @param force Force reload even if already loaded (optional)
function loadc(file, force)
end
--- Set the context default translation language.
-- @param lang Two-letter language code
function setlanguage(lang)
context.lang = lang:gsub("_", "-")
context.parent = (context.lang:match("^([a-z][a-z])_"))
if not tparser.load_catalog(context.lang, i18ndir) then
if context.parent then
tparser.load_catalog(context.parent, i18ndir)
return context.parent
end
end
return context.lang
end
--- Return the translated value for a specific translation key.
-- @param key Default translation text
-- @return Translated string
function translate(key)
return tparser.translate(key) or key
end
--- Return the translated value for a specific translation key and use it as sprintf pattern.
-- @param key Default translation text
-- @param ... Format parameters
-- @return Translated and formatted string
function translatef(key, ...)
return tostring(translate(key)):format(...)
end
--- Return the translated value for a specific translation key
-- and ensure that the returned value is a Lua string value.
-- This is the same as calling <code>tostring(translate(...))</code>
-- @param key Default translation text
-- @return Translated string
function string(key)
return tostring(translate(key))
end
--- Return the translated value for a specific translation key and use it as sprintf pattern.
-- Ensure that the returned value is a Lua string value.
-- This is the same as calling <code>tostring(translatef(...))</code>
-- @param key Default translation text
-- @param ... Format parameters
-- @return Translated and formatted string
function stringf(key, ...)
return tostring(translate(key)):format(...)
end
| gpl-2.0 |
Vermeille/kong | kong/plugins/response-ratelimiting/dao/postgres.lua | 4 | 1591 | local PostgresDB = require "kong.dao.postgres_db"
local timestamp = require "kong.tools.timestamp"
local fmt = string.format
local concat = table.concat
local _M = PostgresDB:extend()
_M.table = "response_ratelimiting_metrics"
_M.schema = require("kong.plugins.response-ratelimiting.schema")
function _M:increment(api_id, identifier, current_timestamp, value, name)
local buf = {}
local periods = timestamp.get_timestamps(current_timestamp)
for period, period_date in pairs(periods) do
buf[#buf + 1] = fmt("SELECT increment_response_rate_limits('%s', '%s', '%s', to_timestamp('%s') at time zone 'UTC', %d)",
api_id, identifier, name.."_"..period, period_date/1000, value)
end
local queries = concat(buf, ";")
local res, err = self:query(queries)
if not res then
return false, err
end
return true
end
function _M:find(api_id, identifier, current_timestamp, period, name)
local periods = timestamp.get_timestamps(current_timestamp)
local q = fmt([[SELECT *, extract(epoch from period_date)*1000 AS period_date FROM response_ratelimiting_metrics WHERE
api_id = '%s' AND
identifier = '%s' AND
period_date = to_timestamp('%s') at time zone 'UTC' AND
period = '%s'
]], api_id, identifier, periods[period]/1000, name.."_"..period)
local res, err = self:query(q)
if not res or err then
return nil, err
end
return res[1]
end
function _M:count()
return _M.super.count(self, _M.table, nil, _M.schema)
end
return {response_ratelimiting_metrics = _M}
| apache-2.0 |
pablo93/TrinityCore | Data/Interface/FrameXML/ArenaRegistrarFrame.lua | 1 | 7296 | MAX_TEAM_EMBLEMS = 102;
MAX_TEAM_BORDERS = 6;
function ArenaRegistrar_OnLoad (self)
self:RegisterEvent("PETITION_VENDOR_SHOW");
self:RegisterEvent("PETITION_VENDOR_CLOSED");
self:RegisterEvent("PETITION_VENDOR_UPDATE");
end
function ArenaRegistrar_OnEvent (self, event, ...)
if ( event == "PETITION_VENDOR_SHOW" ) then
ShowUIPanel(ArenaRegistrarFrame);
if ( not ArenaRegistrarFrame:IsShown() ) then
if ( not PVPBannerFrame:IsShown() ) then
ClosePetitionVendor();
end
end
elseif ( event == "PETITION_VENDOR_CLOSED" ) then
HideUIPanel(ArenaRegistrarFrame);
HideUIPanel(PVPBannerFrame);
elseif ( event == "PETITION_VENDOR_UPDATE" ) then
if ( HasFilledPetition() ) then
ArenaRegistrarButton4:Show();
ArenaRegistrarButton5:Show();
ArenaRegistrarButton6:Show();
RegistrationText:Show();
else
ArenaRegistrarButton4:Hide();
ArenaRegistrarButton5:Hide();
ArenaRegistrarButton6:Hide();
RegistrationText:Hide();
end
--If we clicked a button then show the appropriate purchase frame
if ( ArenaRegistrarPurchaseFrame.waitingForPetitionInfo ) then
ArenaRegistrar_UpdatePrice();
ArenaRegistrarPurchaseFrame.waitingForPetitionInfo = nil;
end
end
end
function ArenaRegistrar_OnShow (self)
self.dontClose = nil;
ArenaRegistrarFrame.bannerDesign = nil;
ArenaRegistrarGreetingFrame:Show();
ArenaRegistrarPurchaseFrame:Hide();
SetPortraitTexture(ArenaRegistrarFramePortrait, "NPC");
ArenaRegistrarFrameNpcNameText:SetText(UnitName("NPC"));
end
function ArenaRegistrar_ShowPurchaseFrame (self, teamSize)
ArenaRegistrarPurchaseFrame.id = self:GetID();
PVPBannerFrame.teamSize = teamSize;
if ( GetPetitionItemInfo(ArenaRegistrarPurchaseFrame.id) ) then
ArenaRegistrar_UpdatePrice();
else
-- Waiting for the callback
ArenaRegistrarPurchaseFrame.waitingForPetitionInfo = 1;
end
end
function ArenaRegistrar_UpdatePrice ()
local name, texture, price = GetPetitionItemInfo(ArenaRegistrarPurchaseFrame.id);
MoneyFrame_Update("ArenaRegistrarMoneyFrame", price);
ArenaRegistrarPurchaseFrame:Show();
ArenaRegistrarGreetingFrame:Hide();
end
function ArenaRegistrar_TurnInPetition (self, teamSize)
ArenaRegistrarFrame.bannerDesign = 1;
ArenaRegistrarFrame.dontClose = 1;
HideUIPanel(self:GetParent());
SetPortraitTexture(PVPBannerFramePortrait,"npc");
PVPBannerFrame.teamSize = teamSize;
ShowUIPanel(PVPBannerFrame);
end
function PVPBannerFrame_SetBannerColor ()
local r,g,b = ColorPickerFrame:GetColorRGB();
PVPBannerFrameStandardBanner.r, PVPBannerFrameStandardBanner.g, PVPBannerFrameStandardBanner.b = r, g, b;
PVPBannerFrameStandardBanner:SetVertexColor(r, g, b);
end
function PVPBannerFrame_SetEmblemColor ()
local r,g,b = ColorPickerFrame:GetColorRGB();
PVPBannerFrameStandardEmblem.r, PVPBannerFrameStandardEmblem.g, PVPBannerFrameStandardEmblem.b = r, g, b;
PVPBannerFrameStandardEmblem:SetVertexColor(r, g, b);
end
function PVPBannerFrame_SetBorderColor ()
local r,g,b = ColorPickerFrame:GetColorRGB();
PVPBannerFrameStandardBorder.r, PVPBannerFrameStandardBorder.g, PVPBannerFrameStandardBorder.b = r, g, b;
PVPBannerFrameStandardBorder:SetVertexColor(r, g, b);
end
function PVPBannerFrame_OnShow (self)
PVPBannerFrameStandardEmblem.id = random(MAX_TEAM_EMBLEMS);
PVPBannerFrameStandardBorder.id = random(MAX_TEAM_BORDERS);
local bannerColor = {r = 0, g = 0, b = 0};
local borderColor = {r = 0, g = 0, b = 0};
local emblemColor = {r = 0, g = 0, b = 0};
local Standard = {Banner = bannerColor, Border = borderColor, Emblem = emblemColor};
for index, value in pairs(Standard) do
for k, v in pairs(value) do
value[k] = random(100) / 100;
end
getglobal("PVPBannerFrameStandard"..index):SetVertexColor(value.r, value.g, value.b);
end
PVPBannerFrameStandardEmblemWatermark:SetAlpha(0.4);
PVPBannerFrameStandardBanner:SetTexture("Interface\\PVPFrame\\PVP-Banner-"..PVPBannerFrame.teamSize);
PVPBannerFrameStandardBorder:SetTexture("Interface\\PVPFrame\\PVP-Banner-"..PVPBannerFrame.teamSize.."-Border-"..PVPBannerFrameStandardBorder.id);
PVPBannerFrameStandardEmblem:SetTexture("Interface\\PVPFrame\\Icons\\PVP-Banner-Emblem-"..PVPBannerFrameStandardEmblem.id);
PVPBannerFrameStandardEmblemWatermark:SetTexture("Interface\\PVPFrame\\Icons\\PVP-Banner-Emblem-"..PVPBannerFrameStandardEmblem.id);
end
function PVPBannerFrame_OpenColorPicker (button, texture)
local r,g,b = texture:GetVertexColor();
if ( texture == PVPBannerFrameStandardEmblem ) then
ColorPickerFrame.func = PVPBannerFrame_SetEmblemColor;
elseif ( texture == PVPBannerFrameStandardBanner ) then
ColorPickerFrame.func = PVPBannerFrame_SetBannerColor;
elseif ( texture == PVPBannerFrameStandardBorder ) then
ColorPickerFrame.func = PVPBannerFrame_SetBorderColor;
end
ColorPickerFrame:SetColorRGB(r, g, b);
ShowUIPanel(ColorPickerFrame);
end
function PVPBannerCustomization_Left (id)
local texture;
if ( id == 1 ) then
texture = PVPBannerFrameStandardEmblem;
if ( texture.id == 1 ) then
texture.id = MAX_TEAM_EMBLEMS;
else
texture.id = texture.id - 1;
end
texture:SetTexture("Interface\\PVPFrame\\Icons\\PVP-Banner-Emblem-"..texture.id);
PVPBannerFrameStandardEmblemWatermark:SetTexture("Interface\\PVPFrame\\Icons\\PVP-Banner-Emblem-"..texture.id);
else
texture = PVPBannerFrameStandardBorder;
if ( texture.id == 1 ) then
texture.id = MAX_TEAM_BORDERS;
else
texture.id = texture.id - 1;
end
texture:SetTexture("Interface\\PVPFrame\\PVP-Banner-"..PVPBannerFrame.teamSize.."-Border-"..texture.id);
end
PlaySound("gsCharacterCreationLook");
end
function PVPBannerCustomization_Right (id)
local texture;
if ( id == 1 ) then
texture = PVPBannerFrameStandardEmblem;
if ( texture.id == MAX_TEAM_EMBLEMS ) then
texture.id = 1;
else
texture.id = texture.id + 1;
end
texture:SetTexture("Interface\\PVPFrame\\Icons\\PVP-Banner-Emblem-"..texture.id);
PVPBannerFrameStandardEmblemWatermark:SetTexture("Interface\\PVPFrame\\Icons\\PVP-Banner-Emblem-"..texture.id);
else
texture = PVPBannerFrameStandardBorder;
if ( texture.id == MAX_TEAM_BORDERS ) then
texture.id = 1;
else
texture.id = texture.id + 1;
end
texture:SetTexture("Interface\\PVPFrame\\PVP-Banner-"..PVPBannerFrame.teamSize.."-Border-"..texture.id);
end
PlaySound("gsCharacterCreationLook");
end
function PVPBannerFrame_SaveBanner (self)
local teamSize, iconStyle, borderStyle;
local bgColor = {r = 0, g = 0, b = 0};
local borderColor = {r = 0, g = 0, b = 0};
local iconColor = {r = 0, g = 0, b = 0};
local color = {bgColor, borderColor, iconColor};
-- Get color values
bgColor.r, bgColor.g, bgColor.b = PVPBannerFrameStandardBanner:GetVertexColor();
borderColor.r, borderColor.g, borderColor.b = PVPBannerFrameStandardBorder:GetVertexColor();
iconColor.r, iconColor.g, iconColor.b = PVPBannerFrameStandardEmblem:GetVertexColor();
-- Get team size
teamSize = PVPBannerFrame.teamSize;
-- Get border style
borderStyle = PVPBannerFrameStandardBorder.id;
-- Get emblem style
iconStyle = PVPBannerFrameStandardEmblem.id;
TurnInArenaPetition(teamSize, bgColor.r, bgColor.g, bgColor.b, iconStyle, iconColor.r, iconColor.g, iconColor.b, borderStyle, borderColor.r, borderColor.g, borderColor.b);
HideUIPanel(self:GetParent());
ClosePetitionVendor();
end | gpl-2.0 |
pavanky/arrayfire-lua | examples/machine_learning/softmax_regression.lua | 4 | 5883 | --[[
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <arrayfire.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <af/util.h>
#include <math.h>
#include "mnist_common.h"
using namespace af;
float accuracy(const array& predicted, const array& target)
{
array val, plabels, tlabels;
max(val, tlabels, target, 1);
max(val, plabels, predicted, 1);
return 100 * count<float>(plabels == tlabels) / tlabels.elements();
}
float abserr(const array& predicted, const array& target)
{
return 100 * sum<float>(abs(predicted - target)) / predicted.elements();
}
array divide(const array &a, const array &b)
{
return a / b;
}
// Predict based on given parameters
array predict(const array &X, const array &Weights)
{
array Z = matmul(X, Weights);
array EZ = exp(Z);
array nrm = sum(EZ, 1);
return batchFunc(EZ, nrm, divide);
}
void cost(array &J, array &dJ, const array &Weights,
const array &X, const array &Y, double lambda = 1.0)
{
// Number of samples
int m = Y.dims(0);
// Make the lambda corresponding to Weights(0) == 0
array lambdat = constant(lambda, Weights.dims());
// No regularization for bias weights
lambdat(0, span) = 0;
// Get the prediction
array H = predict(X, Weights);
// Cost of misprediction
array Jerr = -sum(Y * log(H));
// Regularization cost
array Jreg = 0.5 * sum(lambdat * Weights * Weights);
// Total cost
J = (Jerr + Jreg) / m;
// Find the gradient of cost
array D = (H - Y);
dJ = (matmulTN(X, D) + lambdat * Weights) / m;
}
array train(const array &X, const array &Y,
double alpha = 0.1,
double lambda = 1.0,
double maxerr = 0.01,
int maxiter = 1000,
bool verbose = false)
{
// Initialize parameters to 0
array Weights = constant(0, X.dims(1), Y.dims(1));
array J, dJ;
float err = 0;
for (int i = 0; i < maxiter; i++) {
// Get the cost and gradient
cost(J, dJ, Weights, X, Y, lambda);
err = max<float>(abs(J));
if (err < maxerr) {
printf("Iteration %4d Err: %.4f\n", i + 1, err);
printf("Training converged\n");
return Weights;
}
if (verbose && ((i + 1) % 10 == 0)) {
printf("Iteration %4d Err: %.4f\n", i + 1, err);
}
// Update the parameters via gradient descent
Weights = Weights - alpha * dJ;
}
printf("Training stopped after %d iterations\n", maxiter);
return Weights;
}
void benchmark_softmax_regression(const array &train_feats,
const array &train_targets,
const array test_feats)
{
timer::start();
array Weights = train(train_feats, train_targets, 0.1, 1.0, 0.01, 1000);
af::sync();
printf("Training time: %4.4lf s\n", timer::stop());
timer::start();
const int iter = 100;
for (int i = 0; i < iter; i++) {
array test_outputs = predict(test_feats , Weights);
test_outputs.eval();
}
af::sync();
printf("Prediction time: %4.4lf s\n", timer::stop() / iter);
}
// Demo of one vs all logistic regression
int logit_demo(bool console, int perc)
{
array train_images, train_targets;
array test_images, test_targets;
int num_train, num_test, num_classes;
// Load mnist data
float frac = (float)(perc) / 100.0;
setup_mnist<true>(&num_classes, &num_train, &num_test,
train_images, test_images,
train_targets, test_targets, frac);
// Reshape images into feature vectors
int feature_length = train_images.elements() / num_train;
array train_feats = moddims(train_images, feature_length, num_train).T();
array test_feats = moddims(test_images , feature_length, num_test ).T();
train_targets = train_targets.T();
test_targets = test_targets.T();
// Add a bias that is always 1
train_feats = join(1, constant(1, num_train, 1), train_feats);
test_feats = join(1, constant(1, num_test , 1), test_feats );
// Train logistic regression parameters
array Weights = train(train_feats, train_targets,
0.1, // learning rate (aka alpha)
1.0, // regularization constant (aka weight decay, aka lamdba)
0.01, // maximum error
1000, // maximum iterations
true);// verbose
// Predict the results
array train_outputs = predict(train_feats, Weights);
array test_outputs = predict(test_feats , Weights);
printf("Accuracy on training data: %2.2f\n",
accuracy(train_outputs, train_targets ));
printf("Accuracy on testing data: %2.2f\n",
accuracy(test_outputs , test_targets ));
printf("Maximum error on testing data: %2.2f\n",
abserr(test_outputs , test_targets ));
benchmark_softmax_regression(train_feats, train_targets, test_feats);
if (!console) {
test_outputs = test_outputs.T();
// Get 20 random test images.
display_results<true>(test_images, test_outputs, test_targets.T(), 20);
}
return 0;
}
int main(int argc, char** argv)
{
int device = argc > 1 ? atoi(argv[1]) : 0;
bool console = argc > 2 ? argv[2][0] == '-' : false;
int perc = argc > 3 ? atoi(argv[3]) : 60;
try {
af::setDevice(device);
af::info();
return logit_demo(console, perc);
} catch (af::exception &ae) {
std::cerr << ae.what() << std::endl;
}
}
]] | bsd-3-clause |
nwf/nodemcu-firmware | lua_modules/gossip/gossip.lua | 6 | 7585 | -- Gossip protocol implementation
-- https://github.com/alexandruantochi/
local gossip = {};
local constants = {};
local utils = {};
local network = {};
local state = {};
-- Utils
utils.contains = function(list, element)
for k in pairs(list) do if list[k] == element then return true; end end
return false;
end
utils.debug = function(message)
if gossip.config.debug then
if gossip.config.debugOutput then
gossip.config.debugOutput(message);
else
print(message);
end
end
end
utils.getNetworkState = function() return sjson.encode(gossip.networkState); end
utils.isNodeDataValid = function(nodeData)
return (nodeData and nodeData.revision and nodeData.heartbeat and
nodeData.state) ~= nil;
end
utils.compare = function(first, second)
if first > second then return -1; end
if first < second then return 1; end
return 0;
end
utils.compareNodeData = function(first, second)
local firstDataValid = utils.isNodeDataValid(first);
local secondDataValid = utils.isNodeDataValid(second);
if firstDataValid and secondDataValid then
for index in ipairs(constants.comparisonFields) do
local comparisonField = constants.comparisonFields[index];
local comparisonResult = utils.compare(first[comparisonField],
second[comparisonField]);
if comparisonResult ~= 0 then return comparisonResult; end
end
elseif firstDataValid then
return -1;
elseif secondDataValid then
return 1;
end
return 0;
end
-- computes data1 - data2 based on node compare function
utils.getMinus = function(data1, data2)
local diff = {};
for ip, nodeData1 in pairs(data1) do
if utils.compareNodeData(nodeData1, data2[ip]) == -1 then
diff[ip] = nodeData1;
end
end
return diff;
end
utils.setConfig = function(userConfig)
for k, v in pairs(userConfig) do
if gossip.config[k] ~= nil and type(gossip.config[k]) == type(v) then
gossip.config[k] = v;
end
end
end
-- State
state.setRev = function()
local revision = 0;
if file.exists(constants.revFileName) then
revision = file.getcontents(constants.revFileName) + 1;
end
file.putcontents(constants.revFileName, revision);
utils.debug('Revision set to ' .. revision);
return revision;
end
state.setRevFileValue = function(revNumber)
if revNumber then
file.putcontents(constants.revFileName, revNumber);
utils.debug('Revision overriden to ' .. revNumber);
else
utils.debug('Please provide a revision number.');
end
end
state.start = function()
if gossip.started then
utils.debug('Gossip already started.');
return;
end
gossip.ip = wifi.sta.getip();
if not gossip.ip then
utils.debug('Node not connected to network. Gossip will not start.');
return;
end
gossip.networkState[gossip.ip] = {};
local localState = gossip.networkState[gossip.ip];
localState.revision = state.setRev();
localState.heartbeat = tmr.time();
localState.state = constants.nodeState.UP;
gossip.inboundSocket = net.createUDPSocket();
gossip.inboundSocket:listen(gossip.config.comPort);
gossip.inboundSocket:on('receive', network.receiveData);
gossip.started = true;
gossip.timer = tmr.create();
gossip.timer:register(gossip.config.roundInterval, tmr.ALARM_AUTO,
network.sendSyn);
gossip.timer:start();
utils.debug('Gossip started.');
end
state.tickNodeState = function(ip)
if gossip.networkState[ip] then
local nodeState = gossip.networkState[ip].state;
if nodeState < constants.nodeState.REMOVE then
nodeState = nodeState + constants.nodeState.TICK;
gossip.networkState[ip].state = nodeState;
end
end
end
-- Network
network.pushGossip = function(data, ip)
gossip.networkState[gossip.ip].data = data;
network.sendSyn(nil, ip);
end
network.updateNetworkState = function(updateData)
if gossip.updateCallback then gossip.updateCallback(updateData); end
for ip, data in pairs(updateData) do
if not utils.contains(gossip.config.seedList, ip) then
table.insert(gossip.config.seedList, ip);
end
gossip.networkState[ip] = data;
end
end
-- luacheck: push no unused
network.sendSyn = function(t, ip)
local destination = ip or network.pickRandomNode();
gossip.networkState[gossip.ip].heartbeat = tmr.time();
if destination then
network.sendData(destination, gossip.networkState, constants.updateType.SYN);
state.tickNodeState(destination);
end
end
-- luacheck: pop
network.pickRandomNode = function()
if #gossip.config.seedList > 0 then
local randomListPick = node.random(1, #gossip.config.seedList);
utils.debug('Randomly picked: ' .. gossip.config.seedList[randomListPick]);
return gossip.config.seedList[randomListPick];
end
utils.debug(
'Seedlist is empty. Please provide one or wait for node to be contacted.');
return nil;
end
network.sendData = function(ip, data, sendType)
local outboundSocket = net.createUDPSocket();
data.type = sendType;
local dataToSend = sjson.encode(data);
data.type = nil;
outboundSocket:send(gossip.config.comPort, ip, dataToSend);
outboundSocket:close();
end
network.receiveSyn = function(ip, synData)
utils.debug('Received SYN from ' .. ip);
local update = utils.getMinus(synData, gossip.networkState);
local diff = utils.getMinus(gossip.networkState, synData);
network.updateNetworkState(update);
network.sendAck(ip, diff);
end
network.receiveAck = function(ip, ackData)
utils.debug('Received ACK from ' .. ip);
local update = utils.getMinus(ackData, gossip.networkState);
network.updateNetworkState(update);
end
network.sendAck = function(ip, diff)
local diffIps = '';
for k in pairs(diff) do diffIps = diffIps .. ' ' .. k; end
utils.debug('Sending ACK to ' .. ip .. ' with ' .. diffIps .. ' updates.');
network.sendData(ip, diff, constants.updateType.ACK);
end
-- luacheck: push no unused
network.receiveData = function(socket, data, port, ip)
if gossip.networkState[ip] then
gossip.networkState[ip].state = constants.nodeState.UP;
end
local messageDecoded, updateData = pcall(sjson.decode, data);
if not messageDecoded then
utils.debug('Invalid JSON received from ' .. ip);
return;
end
local updateType = updateData.type;
updateData.type = nil;
if updateType == constants.updateType.SYN then
network.receiveSyn(ip, updateData);
elseif updateType == constants.updateType.ACK then
network.receiveAck(ip, updateData);
else
utils.debug('Invalid data comming from ip ' .. ip ..
'. No valid type specified.');
end
end
-- luacheck: pop
-- Constants
constants.nodeState = {TICK = 1, UP = 0, SUSPECT = 2, DOWN = 3, REMOVE = 4};
constants.defaultConfig = {
seedList = {},
roundInterval = 15000,
comPort = 5000,
debug = false
};
constants.comparisonFields = {'revision', 'heartbeat', 'state'};
constants.updateType = {ACK = 'ACK', SYN = 'SYN'}
constants.revFileName = 'gossip/rev.dat';
-- Return
gossip = {
started = false,
config = constants.defaultConfig,
setConfig = utils.setConfig,
start = state.start,
setRevFileValue = state.setRevFileValue,
networkState = {},
getNetworkState = utils.getNetworkState,
pushGossip = network.pushGossip
};
-- return
if (... == 'test') then
return {
_gossip = gossip,
_constants = constants,
_utils = utils,
_network = network,
_state = state
};
elseif net and file and tmr and wifi then
return gossip;
else
error('Gossip requires these modules to work: net, file, tmr, wifi');
end
| mit |
Elanis/SciFi-Pack-Addon-Gamemode | lua/entities/b5_asimov/cl_init.lua | 1 | 1208 | include('shared.lua')
function ViewPoint( ply, origin, angles, fov )
local jump=LocalPlayer():GetNetworkedEntity("Ship",LocalPlayer())
local dist= -300
if LocalPlayer():GetNetworkedBool("Driving",false) and jump~=LocalPlayer() and jump:IsValid() then
local view = {}
view.origin = jump:GetPos()+Vector( -50, 0, 180 )+ply:GetAimVector():GetNormal()*dist +LocalPlayer():GetAimVector():GetNormal()
view.angles = angles
return view
end
end
hook.Add("CalcView", "ShipView", ViewPoint)
function CalcViewThing( pl, origin, angle, fov )
local ang = pl:GetAimVector();
local pos = self.Entity:GetPos() + Vector( 0, 0, 64 ) - ( ang * 2000 );
local speed = self.Entity:GetVelocity():Length() - 500;
// the direction to face
local face = ( ( self.Entity:GetPos() + Vector( 0, 0, 40 ) ) - pos ):Angle();
// trace to keep it out of the walls
local trace = {
start = self.Entity:GetPos() + Vector( 0, 0, 64 ),
endpos = self.Entity:GetPos() + Vector( 0, 0, 64 ) + face:Forward() * ( 2000 * -1 );
mask = MASK_NPCWORLDSTATIC,
};
local tr = util.TraceLine( trace );
// setup view
local view = {
origin = tr.HitPos + tr.HitNormal,
angles = face,
fov = 90,
};
return view;
end | gpl-2.0 |
phyorat/Pktgen-user-payload | examples/pktgen-v3.1.0/lib/archive/lua-5.3.0/Makefile.lua | 87 | 3273 | # Makefile for installing Lua
# See doc/readme.html for installation and customization instructions.
# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
# Your platform. See PLATS for possible values.
PLAT= none
# Where to install. The installation starts in the src and doc directories,
# so take care if INSTALL_TOP is not an absolute path. See the local target.
# You may want to make INSTALL_LMOD and INSTALL_CMOD consistent with
# LUA_ROOT, LUA_LDIR, and LUA_CDIR in luaconf.h.
INSTALL_TOP= /usr/local
INSTALL_BIN= $(INSTALL_TOP)/bin
INSTALL_INC= $(INSTALL_TOP)/include
INSTALL_LIB= $(INSTALL_TOP)/lib
INSTALL_MAN= $(INSTALL_TOP)/man/man1
INSTALL_LMOD= $(INSTALL_TOP)/share/lua/$V
INSTALL_CMOD= $(INSTALL_TOP)/lib/lua/$V
# How to install. If your install program does not support "-p", then
# you may have to run ranlib on the installed liblua.a.
INSTALL= install -p
INSTALL_EXEC= $(INSTALL) -m 0755
INSTALL_DATA= $(INSTALL) -m 0644
#
# If you don't have "install" you can use "cp" instead.
# INSTALL= cp -p
# INSTALL_EXEC= $(INSTALL)
# INSTALL_DATA= $(INSTALL)
# Other utilities.
MKDIR= mkdir -p
RM= rm -f
# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
# Convenience platforms targets.
PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris
# What to install.
TO_BIN= lua luac
TO_INC= lua.h luaconf.h lualib.h lauxlib.h lua.hpp
TO_LIB= liblua.a
TO_MAN= lua.1 luac.1
# Lua version and release.
V= 5.3
R= $V.0
# Targets start here.
all: $(PLAT)
$(PLATS) clean:
cd src && $(MAKE) $@
test: dummy
src/lua -v
install: dummy
cd src && $(MKDIR) $(INSTALL_BIN) $(INSTALL_INC) $(INSTALL_LIB) $(INSTALL_MAN) $(INSTALL_LMOD) $(INSTALL_CMOD)
cd src && $(INSTALL_EXEC) $(TO_BIN) $(INSTALL_BIN)
cd src && $(INSTALL_DATA) $(TO_INC) $(INSTALL_INC)
cd src && $(INSTALL_DATA) $(TO_LIB) $(INSTALL_LIB)
cd doc && $(INSTALL_DATA) $(TO_MAN) $(INSTALL_MAN)
uninstall:
cd src && cd $(INSTALL_BIN) && $(RM) $(TO_BIN)
cd src && cd $(INSTALL_INC) && $(RM) $(TO_INC)
cd src && cd $(INSTALL_LIB) && $(RM) $(TO_LIB)
cd doc && cd $(INSTALL_MAN) && $(RM) $(TO_MAN)
local:
$(MAKE) install INSTALL_TOP=../install
none:
@echo "Please do 'make PLATFORM' where PLATFORM is one of these:"
@echo " $(PLATS)"
@echo "See doc/readme.html for complete instructions."
# make may get confused with test/ and install/
dummy:
# echo config parameters
echo:
@cd src && $(MAKE) -s echo
@echo "PLAT= $(PLAT)"
@echo "V= $V"
@echo "R= $R"
@echo "TO_BIN= $(TO_BIN)"
@echo "TO_INC= $(TO_INC)"
@echo "TO_LIB= $(TO_LIB)"
@echo "TO_MAN= $(TO_MAN)"
@echo "INSTALL_TOP= $(INSTALL_TOP)"
@echo "INSTALL_BIN= $(INSTALL_BIN)"
@echo "INSTALL_INC= $(INSTALL_INC)"
@echo "INSTALL_LIB= $(INSTALL_LIB)"
@echo "INSTALL_MAN= $(INSTALL_MAN)"
@echo "INSTALL_LMOD= $(INSTALL_LMOD)"
@echo "INSTALL_CMOD= $(INSTALL_CMOD)"
@echo "INSTALL_EXEC= $(INSTALL_EXEC)"
@echo "INSTALL_DATA= $(INSTALL_DATA)"
# echo pkg-config data
pc:
@echo "version=$R"
@echo "prefix=$(INSTALL_TOP)"
@echo "libdir=$(INSTALL_LIB)"
@echo "includedir=$(INSTALL_INC)"
# list targets that do not create files (but not all makes understand .PHONY)
.PHONY: all $(PLATS) clean test install local none dummy echo pecho lecho
# (end of Makefile)
| gpl-2.0 |
ghhgf/hac | plugins/ar-lock-fwd.lua | 2 | 1702 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY SAJJAD HUSSIEN ▀▄ ▄▀
▀▄ ▄▀ BY SAJJADHUSSIEN (@TH3_Evil) ▀▄ ▄▀
▀▄ ▄ JUST WRITED BY SAJJAD HUSSIEN ▀▄ ▄▀
▀▄ ▄▀ ANTI FWD : منع اعاده توجيه ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function pre_process(msg)
--Checking mute
local hash = 'mate:'..msg.to.id
if redis:get(hash) and msg.fwd_from and not is_sudo(msg) and not is_owner(msg) and not is_momod(msg) then
delete_msg(msg.id, ok_cb, true)
return "done"
end
return msg
end
local function run(msg, matches)
chat_id = msg.to.id
if is_momod(msg) and matches[1] == 'قفل اعاده توجيه' then
local hash = 'mate:'..msg.to.id
redis:set(hash, true)
return "تم ☑️ قفل 🔒 اعاده توجيه ✋😽"
elseif is_momod(msg) and matches[1] == 'فتح اعاده توجيه' then
local hash = 'mate:'..msg.to.id
redis:del(hash)
return "تم ☑️ فتح 🔓 اعاده توجيه ✋😽"
end
end
return {
patterns = {
'^(قفل اعاده توجيه)$',
'^(فتح اعاده توجيه)$'
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
alexandergall/snabbswitch | src/program/lwaftr/check/check.lua | 9 | 2207 | module(..., package.seeall)
local lib = require("core.lib")
local setup = require("program.lwaftr.setup")
local util = require("program.lwaftr.check.util")
local engine = require("core.app")
local counters = require("program.lwaftr.counters")
local function show_usage(code)
print(require("program.lwaftr.check.README_inc"))
main.exit(code)
end
local function parse_args (args)
local handlers = {}
local opts = {}
function handlers.h() show_usage(0) end
function handlers.r() opts.r = true end
handlers["on-a-stick"] = function ()
opts["on-a-stick"] = true
end
handlers.D = function(dur)
opts["duration"] = tonumber(dur)
end
args = lib.dogetopt(args, handlers, "hrD:",
{ help="h", regen="r", duration="D", ["on-a-stick"] = 0 })
if #args ~= 5 and #args ~= 6 then show_usage(1) end
if not opts["duration"] then opts["duration"] = 0.10 end
return opts, args
end
local function fix_nondeterminacy()
require('apps.ipv4.fragment').use_deterministic_first_fragment_id()
require('apps.ipv6.fragment').use_deterministic_first_fragment_id()
end
function run(args)
fix_nondeterminacy()
local opts, args = parse_args(args)
local load_check = opts["on-a-stick"] and setup.load_check_on_a_stick
or setup.load_check
local conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap, counters_path =
unpack(args)
local conf = setup.read_config(conf_file)
local c = config.new()
load_check(c, conf, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap)
engine.configure(c)
if counters_path then
local initial_counters = counters.read_counters()
engine.main({duration=opts.duration})
local final_counters = counters.read_counters()
local counters_diff = util.diff_counters(final_counters,
initial_counters)
if opts.r then
util.regen_counters(counters_diff, counters_path)
else
local req_counters = util.load_requested_counters(counters_path)
util.validate_diff(counters_diff, req_counters)
end
else
engine.main({duration=opts.duration})
end
print("done")
end
| apache-2.0 |
xuejian1354/barrier_breaker | feeds/luci/modules/base/luasrc/util.lua | 81 | 21858 | --[[
LuCI - Utility library
Description:
Several common useful Lua functions
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local io = require "io"
local math = require "math"
local table = require "table"
local debug = require "debug"
local ldebug = require "luci.debug"
local string = require "string"
local coroutine = require "coroutine"
local tparser = require "luci.template.parser"
local getmetatable, setmetatable = getmetatable, setmetatable
local rawget, rawset, unpack = rawget, rawset, unpack
local tostring, type, assert = tostring, type, assert
local ipairs, pairs, next, loadstring = ipairs, pairs, next, loadstring
local require, pcall, xpcall = require, pcall, xpcall
local collectgarbage, get_memory_limit = collectgarbage, get_memory_limit
--- LuCI utility functions.
module "luci.util"
--
-- Pythonic string formatting extension
--
getmetatable("").__mod = function(a, b)
if not b then
return a
elseif type(b) == "table" then
for k, _ in pairs(b) do if type(b[k]) == "userdata" then b[k] = tostring(b[k]) end end
return a:format(unpack(b))
else
if type(b) == "userdata" then b = tostring(b) end
return a:format(b)
end
end
--
-- Class helper routines
--
-- Instantiates a class
local function _instantiate(class, ...)
local inst = setmetatable({}, {__index = class})
if inst.__init__ then
inst:__init__(...)
end
return inst
end
--- Create a Class object (Python-style object model).
-- The class object can be instantiated by calling itself.
-- Any class functions or shared parameters can be attached to this object.
-- Attaching a table to the class object makes this table shared between
-- all instances of this class. For object parameters use the __init__ function.
-- Classes can inherit member functions and values from a base class.
-- Class can be instantiated by calling them. All parameters will be passed
-- to the __init__ function of this class - if such a function exists.
-- The __init__ function must be used to set any object parameters that are not shared
-- with other objects of this class. Any return values will be ignored.
-- @param base The base class to inherit from (optional)
-- @return A class object
-- @see instanceof
-- @see clone
function class(base)
return setmetatable({}, {
__call = _instantiate,
__index = base
})
end
--- Test whether the given object is an instance of the given class.
-- @param object Object instance
-- @param class Class object to test against
-- @return Boolean indicating whether the object is an instance
-- @see class
-- @see clone
function instanceof(object, class)
local meta = getmetatable(object)
while meta and meta.__index do
if meta.__index == class then
return true
end
meta = getmetatable(meta.__index)
end
return false
end
--
-- Scope manipulation routines
--
local tl_meta = {
__mode = "k",
__index = function(self, key)
local t = rawget(self, coxpt[coroutine.running()]
or coroutine.running() or 0)
return t and t[key]
end,
__newindex = function(self, key, value)
local c = coxpt[coroutine.running()] or coroutine.running() or 0
if not rawget(self, c) then
rawset(self, c, { [key] = value })
else
rawget(self, c)[key] = value
end
end
}
--- Create a new or get an already existing thread local store associated with
-- the current active coroutine. A thread local store is private a table object
-- whose values can't be accessed from outside of the running coroutine.
-- @return Table value representing the corresponding thread local store
function threadlocal(tbl)
return setmetatable(tbl or {}, tl_meta)
end
--
-- Debugging routines
--
--- Write given object to stderr.
-- @param obj Value to write to stderr
-- @return Boolean indicating whether the write operation was successful
function perror(obj)
return io.stderr:write(tostring(obj) .. "\n")
end
--- Recursively dumps a table to stdout, useful for testing and debugging.
-- @param t Table value to dump
-- @param maxdepth Maximum depth
-- @return Always nil
function dumptable(t, maxdepth, i, seen)
i = i or 0
seen = seen or setmetatable({}, {__mode="k"})
for k,v in pairs(t) do
perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
if type(v) == "table" and (not maxdepth or i < maxdepth) then
if not seen[v] then
seen[v] = true
dumptable(v, maxdepth, i+1, seen)
else
perror(string.rep("\t", i) .. "*** RECURSION ***")
end
end
end
end
--
-- String and data manipulation routines
--
--- Create valid XML PCDATA from given string.
-- @param value String value containing the data to escape
-- @return String value containing the escaped data
function pcdata(value)
return value and tparser.pcdata(tostring(value))
end
--- Strip HTML tags from given string.
-- @param value String containing the HTML text
-- @return String with HTML tags stripped of
function striptags(value)
return value and tparser.striptags(tostring(value))
end
--- Splits given string on a defined separator sequence and return a table
-- containing the resulting substrings. The optional max parameter specifies
-- the number of bytes to process, regardless of the actual length of the given
-- string. The optional last parameter, regex, specifies whether the separator
-- sequence is interpreted as regular expression.
-- @param str String value containing the data to split up
-- @param pat String with separator pattern (optional, defaults to "\n")
-- @param max Maximum times to split (optional)
-- @param regex Boolean indicating whether to interpret the separator
-- pattern as regular expression (optional, default is false)
-- @return Table containing the resulting substrings
function split(str, pat, max, regex)
pat = pat or "\n"
max = max or #str
local t = {}
local c = 1
if #str == 0 then
return {""}
end
if #pat == 0 then
return nil
end
if max == 0 then
return str
end
repeat
local s, e = str:find(pat, c, not regex)
max = max - 1
if s and max < 0 then
t[#t+1] = str:sub(c)
else
t[#t+1] = str:sub(c, s and s - 1)
end
c = e and e + 1 or #str + 1
until not s or max < 0
return t
end
--- Remove leading and trailing whitespace from given string value.
-- @param str String value containing whitespace padded data
-- @return String value with leading and trailing space removed
function trim(str)
return (str:gsub("^%s*(.-)%s*$", "%1"))
end
--- Count the occurences of given substring in given string.
-- @param str String to search in
-- @param pattern String containing pattern to find
-- @return Number of found occurences
function cmatch(str, pat)
local count = 0
for _ in str:gmatch(pat) do count = count + 1 end
return count
end
--- Return a matching iterator for the given value. The iterator will return
-- one token per invocation, the tokens are separated by whitespace. If the
-- input value is a table, it is transformed into a string first. A nil value
-- will result in a valid interator which aborts with the first invocation.
-- @param val The value to scan (table, string or nil)
-- @return Iterator which returns one token per call
function imatch(v)
if type(v) == "table" then
local k = nil
return function()
k = next(v, k)
return v[k]
end
elseif type(v) == "number" or type(v) == "boolean" then
local x = true
return function()
if x then
x = false
return tostring(v)
end
end
elseif type(v) == "userdata" or type(v) == "string" then
return tostring(v):gmatch("%S+")
end
return function() end
end
--- Parse certain units from the given string and return the canonical integer
-- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
-- Recognized units are:
-- o "y" - one year (60*60*24*366)
-- o "m" - one month (60*60*24*31)
-- o "w" - one week (60*60*24*7)
-- o "d" - one day (60*60*24)
-- o "h" - one hour (60*60)
-- o "min" - one minute (60)
-- o "kb" - one kilobyte (1024)
-- o "mb" - one megabyte (1024*1024)
-- o "gb" - one gigabyte (1024*1024*1024)
-- o "kib" - one si kilobyte (1000)
-- o "mib" - one si megabyte (1000*1000)
-- o "gib" - one si gigabyte (1000*1000*1000)
-- @param ustr String containing a numerical value with trailing unit
-- @return Number containing the canonical value
function parse_units(ustr)
local val = 0
-- unit map
local map = {
-- date stuff
y = 60 * 60 * 24 * 366,
m = 60 * 60 * 24 * 31,
w = 60 * 60 * 24 * 7,
d = 60 * 60 * 24,
h = 60 * 60,
min = 60,
-- storage sizes
kb = 1024,
mb = 1024 * 1024,
gb = 1024 * 1024 * 1024,
-- storage sizes (si)
kib = 1000,
mib = 1000 * 1000,
gib = 1000 * 1000 * 1000
}
-- parse input string
for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
local num = spec:gsub("[^0-9%.]+$","")
local spn = spec:gsub("^[0-9%.]+", "")
if map[spn] or map[spn:sub(1,1)] then
val = val + num * ( map[spn] or map[spn:sub(1,1)] )
else
val = val + num
end
end
return val
end
-- also register functions above in the central string class for convenience
string.pcdata = pcdata
string.striptags = striptags
string.split = split
string.trim = trim
string.cmatch = cmatch
string.parse_units = parse_units
--- Appends numerically indexed tables or single objects to a given table.
-- @param src Target table
-- @param ... Objects to insert
-- @return Target table
function append(src, ...)
for i, a in ipairs({...}) do
if type(a) == "table" then
for j, v in ipairs(a) do
src[#src+1] = v
end
else
src[#src+1] = a
end
end
return src
end
--- Combines two or more numerically indexed tables and single objects into one table.
-- @param tbl1 Table value to combine
-- @param tbl2 Table value to combine
-- @param ... More tables to combine
-- @return Table value containing all values of given tables
function combine(...)
return append({}, ...)
end
--- Checks whether the given table contains the given value.
-- @param table Table value
-- @param value Value to search within the given table
-- @return Boolean indicating whether the given value occurs within table
function contains(table, value)
for k, v in pairs(table) do
if value == v then
return k
end
end
return false
end
--- Update values in given table with the values from the second given table.
-- Both table are - in fact - merged together.
-- @param t Table which should be updated
-- @param updates Table containing the values to update
-- @return Always nil
function update(t, updates)
for k, v in pairs(updates) do
t[k] = v
end
end
--- Retrieve all keys of given associative table.
-- @param t Table to extract keys from
-- @return Sorted table containing the keys
function keys(t)
local keys = { }
if t then
for k, _ in kspairs(t) do
keys[#keys+1] = k
end
end
return keys
end
--- Clones the given object and return it's copy.
-- @param object Table value to clone
-- @param deep Boolean indicating whether to do recursive cloning
-- @return Cloned table value
function clone(object, deep)
local copy = {}
for k, v in pairs(object) do
if deep and type(v) == "table" then
v = clone(v, deep)
end
copy[k] = v
end
return setmetatable(copy, getmetatable(object))
end
--- Create a dynamic table which automatically creates subtables.
-- @return Dynamic Table
function dtable()
return setmetatable({}, { __index =
function(tbl, key)
return rawget(tbl, key)
or rawget(rawset(tbl, key, dtable()), key)
end
})
end
-- Serialize the contents of a table value.
function _serialize_table(t, seen)
assert(not seen[t], "Recursion detected.")
seen[t] = true
local data = ""
local idata = ""
local ilen = 0
for k, v in pairs(t) do
if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
k = serialize_data(k, seen)
v = serialize_data(v, seen)
data = data .. ( #data > 0 and ", " or "" ) ..
'[' .. k .. '] = ' .. v
elseif k > ilen then
ilen = k
end
end
for i = 1, ilen do
local v = serialize_data(t[i], seen)
idata = idata .. ( #idata > 0 and ", " or "" ) .. v
end
return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
end
--- Recursively serialize given data to lua code, suitable for restoring
-- with loadstring().
-- @param val Value containing the data to serialize
-- @return String value containing the serialized code
-- @see restore_data
-- @see get_bytecode
function serialize_data(val, seen)
seen = seen or setmetatable({}, {__mode="k"})
if val == nil then
return "nil"
elseif type(val) == "number" then
return val
elseif type(val) == "string" then
return "%q" % val
elseif type(val) == "boolean" then
return val and "true" or "false"
elseif type(val) == "function" then
return "loadstring(%q)" % get_bytecode(val)
elseif type(val) == "table" then
return "{ " .. _serialize_table(val, seen) .. " }"
else
return '"[unhandled data type:' .. type(val) .. ']"'
end
end
--- Restore data previously serialized with serialize_data().
-- @param str String containing the data to restore
-- @return Value containing the restored data structure
-- @see serialize_data
-- @see get_bytecode
function restore_data(str)
return loadstring("return " .. str)()
end
--
-- Byte code manipulation routines
--
--- Return the current runtime bytecode of the given data. The byte code
-- will be stripped before it is returned.
-- @param val Value to return as bytecode
-- @return String value containing the bytecode of the given data
function get_bytecode(val)
local code
if type(val) == "function" then
code = string.dump(val)
else
code = string.dump( loadstring( "return " .. serialize_data(val) ) )
end
return code -- and strip_bytecode(code)
end
--- Strips unnescessary lua bytecode from given string. Information like line
-- numbers and debugging numbers will be discarded. Original version by
-- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
-- @param code String value containing the original lua byte code
-- @return String value containing the stripped lua byte code
function strip_bytecode(code)
local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
local subint
if endian == 1 then
subint = function(code, i, l)
local val = 0
for n = l, 1, -1 do
val = val * 256 + code:byte(i + n - 1)
end
return val, i + l
end
else
subint = function(code, i, l)
local val = 0
for n = 1, l, 1 do
val = val * 256 + code:byte(i + n - 1)
end
return val, i + l
end
end
local function strip_function(code)
local count, offset = subint(code, 1, size)
local stripped = { string.rep("\0", size) }
local dirty = offset + count
offset = offset + count + int * 2 + 4
offset = offset + int + subint(code, offset, int) * ins
count, offset = subint(code, offset, int)
for n = 1, count do
local t
t, offset = subint(code, offset, 1)
if t == 1 then
offset = offset + 1
elseif t == 4 then
offset = offset + size + subint(code, offset, size)
elseif t == 3 then
offset = offset + num
elseif t == 254 or t == 9 then
offset = offset + lnum
end
end
count, offset = subint(code, offset, int)
stripped[#stripped+1] = code:sub(dirty, offset - 1)
for n = 1, count do
local proto, off = strip_function(code:sub(offset, -1))
stripped[#stripped+1] = proto
offset = offset + off - 1
end
offset = offset + subint(code, offset, int) * int + int
count, offset = subint(code, offset, int)
for n = 1, count do
offset = offset + subint(code, offset, size) + size + int * 2
end
count, offset = subint(code, offset, int)
for n = 1, count do
offset = offset + subint(code, offset, size) + size
end
stripped[#stripped+1] = string.rep("\0", int * 3)
return table.concat(stripped), offset
end
return code:sub(1,12) .. strip_function(code:sub(13,-1))
end
--
-- Sorting iterator functions
--
function _sortiter( t, f )
local keys = { }
local k, v
for k, v in pairs(t) do
keys[#keys+1] = k
end
local _pos = 0
table.sort( keys, f )
return function()
_pos = _pos + 1
if _pos <= #keys then
return keys[_pos], t[keys[_pos]], _pos
end
end
end
--- Return a key, value iterator which returns the values sorted according to
-- the provided callback function.
-- @param t The table to iterate
-- @param f A callback function to decide the order of elements
-- @return Function value containing the corresponding iterator
function spairs(t,f)
return _sortiter( t, f )
end
--- Return a key, value iterator for the given table.
-- The table pairs are sorted by key.
-- @param t The table to iterate
-- @return Function value containing the corresponding iterator
function kspairs(t)
return _sortiter( t )
end
--- Return a key, value iterator for the given table.
-- The table pairs are sorted by value.
-- @param t The table to iterate
-- @return Function value containing the corresponding iterator
function vspairs(t)
return _sortiter( t, function (a,b) return t[a] < t[b] end )
end
--
-- System utility functions
--
--- Test whether the current system is operating in big endian mode.
-- @return Boolean value indicating whether system is big endian
function bigendian()
return string.byte(string.dump(function() end), 7) == 0
end
--- Execute given commandline and gather stdout.
-- @param command String containing command to execute
-- @return String containing the command's stdout
function exec(command)
local pp = io.popen(command)
local data = pp:read("*a")
pp:close()
return data
end
--- Return a line-buffered iterator over the output of given command.
-- @param command String containing the command to execute
-- @return Iterator
function execi(command)
local pp = io.popen(command)
return pp and function()
local line = pp:read()
if not line then
pp:close()
end
return line
end
end
-- Deprecated
function execl(command)
local pp = io.popen(command)
local line = ""
local data = {}
while true do
line = pp:read()
if (line == nil) then break end
data[#data+1] = line
end
pp:close()
return data
end
--- Returns the absolute path to LuCI base directory.
-- @return String containing the directory path
function libpath()
return require "nixio.fs".dirname(ldebug.__file__)
end
--
-- Coroutine safe xpcall and pcall versions modified for Luci
-- original version:
-- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
--
-- Copyright © 2005 Kepler Project.
-- 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 performResume, handleReturnValue
local oldpcall, oldxpcall = pcall, xpcall
coxpt = {}
setmetatable(coxpt, {__mode = "kv"})
-- Identity function for copcall
local function copcall_id(trace, ...)
return ...
end
--- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
-- @param f Lua function to be called protected
-- @param err Custom error handler
-- @param ... Parameters passed to the function
-- @return A boolean whether the function call succeeded and the return
-- values of either the function or the error handler
function coxpcall(f, err, ...)
local res, co = oldpcall(coroutine.create, f)
if not res then
local params = {...}
local newf = function() return f(unpack(params)) end
co = coroutine.create(newf)
end
local c = coroutine.running()
coxpt[co] = coxpt[c] or c or 0
return performResume(err, co, ...)
end
--- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
-- @param f Lua function to be called protected
-- @param ... Parameters passed to the function
-- @return A boolean whether the function call succeeded and the returns
-- values of the function or the error object
function copcall(f, ...)
return coxpcall(f, copcall_id, ...)
end
-- Handle return value of protected call
function handleReturnValue(err, co, status, ...)
if not status then
return false, err(debug.traceback(co, (...)), ...)
end
if coroutine.status(co) ~= 'suspended' then
return true, ...
end
return performResume(err, co, coroutine.yield(...))
end
-- Resume execution of protected function call
function performResume(err, co, ...)
return handleReturnValue(err, co, coroutine.resume(co, ...))
end
| gpl-2.0 |
xponen/Zero-K | effects/corpun.lua | 25 | 1956 | -- corpun_shockwave
return {
["corpun_shockwave"] = {
clouds0 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
underwater = 0,
water = false,
properties = {
airdrag = 0.95,
colormap = [[0 0 0 0.001 0.2 0.15 0 0.08 0 0 0 0.001]],
directional = true,
emitrot = 90,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.1, 0]],
numparticles = 3,
particlelife = 140,
particlelifespread = 0,
particlesize = 2,
particlesizespread = 1,
particlespeed = 5,
particlespeedspread = 0,
pos = [[15, 1, 0]],
sizegrowth = 0.3,
sizemod = 1.0,
texture = [[kfoom]],
},
},
clouds1 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
underwater = 0,
water = false,
properties = {
airdrag = 0.95,
colormap = [[0 0 0 0.001 0.04 0.04 0.04 0.2 0 0 0 0.001]],
directional = true,
emitrot = 90,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.1, 0]],
numparticles = 20,
particlelife = 140,
particlelifespread = 0,
particlesize = 4,
particlesizespread = 1,
particlespeed = 5,
particlespeedspread = 0,
pos = [[15, 1, 0]],
sizegrowth = 0.3,
sizemod = 1.0,
texture = [[kfoam]],
},
},
},
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.