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 |
|---|---|---|---|---|---|
n0xus/darkstar | scripts/zones/Northern_San_dOria/npcs/HomePoint#2.lua | 17 | 1262 | -----------------------------------
-- Area: Northern San dOria
-- NPC: HomePoint#2
-- @pos 10 -0.2 95 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Northern_San_dOria/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 4);
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 == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-Core/DBM-Flash.lua | 1 | 1263 | -- globals
DBM.Flash = {}
-- locals
local flashFrame = DBM.Flash
local r, g, b, t, a
local duration
local elapsed = 0
local totalRepeat = 0
--------------------
-- Create Frame --
--------------------
local frame = CreateFrame("Frame", "DBMFlash", UIParent)
frame:Hide()
frame:SetBackdrop({bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",})
frame:SetAllPoints(UIParent)
frame:SetFrameStrata("BACKGROUND")
------------------------
-- OnUpdate Handler --
------------------------
do
frame:SetScript("OnUpdate", function(self, e)
elapsed = elapsed + e
if elapsed >= t then
self:Hide()
self:SetAlpha(0)
if totalRepeat >= 1 then--Keep repeating until totalRepeat = 0
flashFrame:Show(r, g, b, t, a, totalRepeat-1)
end
return
end
-- quadratic fade in/out
self:SetAlpha(-(elapsed / (duration / 2) - 1)^2 + 1)
end)
frame:Hide()
end
function flashFrame:Show(red, green, blue, dur, alpha, repeatFlash)
r, g, b, t, a = red or 1, green or 0, blue or 0, dur or 0.4, alpha or 0.3
duration = dur
elapsed = 0
totalRepeat = repeatFlash or 0
frame:SetAlpha(0)
frame:SetBackdropColor(r, g, b, a)
frame:Show()
end
function flashFrame:IsShown()
return frame and frame:IsShown()
end
function flashFrame:Hide()
frame:Hide()
end
| gpl-2.0 |
Python1320/wire | lua/wire/stools/digitalscreen.lua | 9 | 1091 | WireToolSetup.setCategory( "Visuals/Screens" )
WireToolSetup.open( "digitalscreen", "Digital Screen", "gmod_wire_digitalscreen", nil, "Digital Screens" )
if CLIENT then
language.Add( "tool.wire_digitalscreen.name", "Digital Screen Tool (Wire)" )
language.Add( "tool.wire_digitalscreen.desc", "Spawns a digital screen, which can be used to draw pixel by pixel." )
language.Add( "tool.wire_digitalscreen.0", "Primary: Create/Update screen" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 20 )
if SERVER then
function TOOL:GetConVars()
return self:GetClientInfo("width"), self:GetClientInfo("height")
end
end
TOOL.ClientConVar = {
model = "models/props_lab/monitor01b.mdl",
width = 32,
height = 32,
createflat = 0,
}
function TOOL.BuildCPanel(panel)
WireDermaExts.ModelSelect(panel, "wire_digitalscreen_model", list.Get( "WireScreenModels" ), 5)
panel:NumSlider("Width", "wire_digitalscreen_width", 1, 512, 0)
panel:NumSlider("Height", "wire_digitalscreen_height", 1, 512, 0)
panel:CheckBox("#Create Flat to Surface", "wire_digitalscreen_createflat")
end | apache-2.0 |
mortezamosavy999/monsterm | plugins/inrealm.lua | 850 | 25085 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
lcfx/etet-dev-utils | itemdef.lua | 1 | 5152 | dofile("lib/parser.lua")
function printf(fmt, ...)
io.stdout:write(string.format(fmt, ...))
end
function stringParser(value)
if value == "NULL" then
return ""
end
return value
end
function intParser(value)
if value == "NULL" then
return -1
end
return tonumber(value) or -1
end
-- 一番長いのが13文字なので
-- 16文字目に合わせる (タブ幅 = 4)
function addtab(str, maxlen)
local len = string.len(str)
local diff = maxlen - len
local tabs = math.ceil(diff/4.0)
return str .. string.rep("\t", tabs)
end
itemCount = 1
KEY = 1
VALUE = 2
parseDef = {
-- classname
{name="classname", target=KEY, tb=false, parser=stringParser},
-- pickupSound
{name="pickupSound", target=VALUE, tb=false, parser=stringParser},
-- model
{name="model", target=VALUE, tb=true, parser=stringParser},
-- icon
{name="icon", target=VALUE, tb=false, parser=stringParser},
-- ammoIcon
{name="ammoIcon", target=VALUE, tb=false, parser=stringParser},
-- pickupName
{name="pickupName", target=VALUE, tb=false, parser=stringParser},
-- quantity
{name="quantity", target=VALUE, tb=false, parser=intParser},
-- itemType
{name="itemType", target=VALUE, tb=false, parser=stringParser},
-- itemTag
{name="itemTag", target=VALUE, tb=false, parser=stringParser},
-- itemAmmoIndex
{name="itemAmmoIndex", target=VALUE, tb=false, parser=stringParser},
-- itemClipIndex
{name="itemClipIndex", target=VALUE, tb=false, parser=stringParser},
-- precaches
{name="precaches", target=VALUE, tb=false, parser=stringParser},
-- sounds
{name="sounds", target=VALUE, tb=false, parser=stringParser},
}
local itemlist = {
--[[
["classname"] = {
pickupSound = string,
model = {string, string, string},
icon = string,
ammoIcon = string,
pickupName = string,
quantity = number,
itemType = "<itemType_t>",
itemTag = "<WP_>",
itemAmmoIndex = "<WP_>",
itemClipIndex = "<WP_>",
precaches = string,
sounds = string,
},
--]]
}
-- parse bg_itemlist
function parse()
local fdr = io.open("itemlist.c", "r")
fdr:seek("set")
local buf = fdr:read("*a")
io.close(fdr)
local pa = parser:new(buf, false, nil, printf)
local str = pa:parseExt()
local nest = 0
local count = {0, 0}
local pd
local value
local ilist
local keyname
while str ~= 0 do
if str == "{NULL}" then
break
end
if str == "{" then
nest = nest + 1
if nest == 2 then
count[1] = count[1] + 1
end
elseif str == "}" then
nest = nest - 1
if nest == 0 then
count[1] = 0
count[2] = 0
printf("%d(%d, n=%d): %s\n", pa.pos, pa.line, nest, str)
end
else
count[nest] = count[nest] + 1
printf("%d(%d, n=%d, c=%d): %s\n", pa.pos, pa.line, nest, count[nest], str)
pd = parseDef[count[1]]
if pd then
value = pd.parser(str)
if pd.target == KEY then
itemlist[value] = {}
keyname = value
ilist = itemlist[value]
printf("%d(%d, n=%d, c=%d): key = \"%s\"\n",
pa.pos, pa.line, nest, count[nest], keyname)
if not pd.maxlen then
pd.maxlen = 0
end
if #value > pd.maxlen then
pd.maxlen = #value
end
itemCount = itemCount + 1
else
if pd.tb then
if not ilist[pd.name] then
ilist[pd.name] = {}
end
ilist[pd.name][#ilist[pd.name]+1] = value
printf("%d(%d, n=%d, c=%d): [%s] %s[%d] = \"%s\"\n",
pa.pos, pa.line, nest, count[nest], keyname, pd.name, #ilist[pd.name], tostring(value))
else
ilist[pd.name] = value
printf("%d(%d, n=%d, c=%d): [%s] %s = \"%s\"\n",
pa.pos, pa.line, nest, count[nest], keyname, pd.name, tostring(value))
end
if pd.parser == stringParser then
if not pd.maxlen then
pd.maxlen = 0
end
if #value > pd.maxlen then
pd.maxlen = #value
end
end
end
end
end
str = pa:parseExt()
end
end
function rebuild()
local fdw = io.open("item.def", "w")
local buf
local itembuf = {}
local i = 1
for itemname, ilist in pairs(itemlist) do
itembuf[i] = string.format("\n%s {\n", itemname)
for keyname, v in pairs(ilist) do
-- bad
if type(v) == "table" then
for k=1, 3 do
if v[k] ~= "0" then
itembuf[i] = itembuf[i] .. string.format("\t%s\"%s\"\n", addtab(keyname, 16), v[k])
end
end
else
if v ~= "" and v ~= "0" then
-- bad
if keyname == "quantity" then
itembuf[i] = itembuf[i] .. string.format("\t%s%s\n", addtab(keyname, 16), v)
else
itembuf[i] = itembuf[i] .. string.format("\t%s\"%s\"\n", addtab(keyname, 16), v)
end
end
end
end
itembuf[i] = itembuf[i] .. "}\n"
i = i + 1
end
-- itembuf を昇順ソート
table.sort(itembuf, function(a, b) return a < b end)
-- ソートした itembuf を連結する
buf = table.concat(itembuf)
fdw:seek("set")
fdw:write(buf)
io.close(fdw)
end
-- 各設定値の最大長を出す
function result()
local pd
printf("\n\n")
for i=1, #parseDef do
pd = parseDef[i]
if pd.parser == stringParser then
printf("%s's maxlen = %d\n", pd.name, pd.maxlen)
end
end
printf("itemCount %d\n", itemCount)
end
parse()
rebuild()
result()
| unlicense |
davymai/CN-QulightUI | Interface/AddOns/QulightUI/Addons/Skins/skins/DBM.lua | 1 | 11953 | ----------------------------------------------------------------------------------------
-- DBM skin(by Affli)
----------------------------------------------------------------------------------------
if not Qulight["addonskins"].DBM == true then return end
local forcebosshealthclasscolor = false -- Forces BossHealth to be classcolored. Not recommended.
local croprwicons = true -- Crops blizz shitty borders from icons in RaidWarning messages
local rwiconsize = 12 -- RaidWarning icon size. Works only if croprwicons = true
local backdrop = {
bgFile = Qulight["media"].texture,
insets = {left = 0, right = 0, top = 0, bottom = 0},
}
local DBMSkin = CreateFrame("Frame")
DBMSkin:RegisterEvent("PLAYER_LOGIN")
DBMSkin:SetScript("OnEvent", function(self, event, addon)
if IsAddOnLoaded("DBM-Core") then
local function SkinBars(self)
for bar in self:GetBarIterator() do
if not bar.injected then
bar.ApplyStyle = function()
local frame = bar.frame
local tbar = _G[frame:GetName().."Bar"]
local spark = _G[frame:GetName().."BarSpark"]
local texture = _G[frame:GetName().."BarTexture"]
local icon1 = _G[frame:GetName().."BarIcon1"]
local icon2 = _G[frame:GetName().."BarIcon2"]
local name = _G[frame:GetName().."BarName"]
local timer = _G[frame:GetName().."BarTimer"]
if (icon1.overlay) then
icon1.overlay = _G[icon1.overlay:GetName()]
else
icon1.overlay = CreateFrame("Frame", "$parentIcon1Overlay", tbar)
icon1.overlay:SetWidth(23)
icon1.overlay:SetHeight(23)
icon1.overlay:SetFrameStrata("BACKGROUND")
icon1.overlay:SetPoint("BOTTOMRIGHT", tbar, "BOTTOMLEFT", -2, -2)
CreateStyle(icon1.overlay, 2)
end
if (icon2.overlay) then
icon2.overlay = _G[icon2.overlay:GetName()]
else
icon2.overlay = CreateFrame("Frame", "$parentIcon2Overlay", tbar)
icon2.overlay:SetWidth(23)
icon2.overlay:SetHeight(23)
icon2.overlay:SetFrameStrata("BACKGROUND")
icon2.overlay:SetPoint("BOTTOMLEFT", tbar, "BOTTOMRIGHT", 5, -2)
CreateStyle(icon2.overlay, 2)
end
if bar.color then
tbar:SetStatusBarColor(0.1, 0.1, 0.1)
tbar:SetBackdrop(backdrop)
tbar:SetBackdropColor(0.1, 0.1, 0.1, 0.15)
else
tbar:SetStatusBarColor(0.1, 0.1, 0.1)
tbar:SetBackdrop(backdrop)
tbar:SetBackdropColor(0.1, 0.1, 0.1, 0.15)
end
if bar.enlarged then frame:SetWidth(bar.owner.options.HugeWidth) else frame:SetWidth(bar.owner.options.Width) end
if bar.enlarged then tbar:SetWidth(bar.owner.options.HugeWidth) else tbar:SetWidth(bar.owner.options.Width) end
frame:SetScale(1)
if not frame.styled then
frame:SetHeight(23)
CreateStyle(frame, 2)
frame.styled = true
end
if not spark.killed then
spark:SetAlpha(0)
spark:SetTexture(nil)
spark.killed = true
end
if not icon1.styled then
icon1:SetTexCoord(0.1, 0.9, 0.1, 0.9)
icon1:ClearAllPoints()
icon1:SetPoint("TOPLEFT", icon1.overlay, 2, -2)
icon1:SetPoint("BOTTOMRIGHT", icon1.overlay, -2, 2)
icon1.styled = true
end
if not icon2.styled then
icon2:SetTexCoord(0.1, 0.9, 0.1, 0.9)
icon2:ClearAllPoints()
icon2:SetPoint("TOPLEFT", icon2.overlay, 2, -2)
icon2:SetPoint("BOTTOMRIGHT", icon2.overlay, -2, 2)
icon2.styled = true
end
if not texture.styled then
texture:SetTexture(Qulight["media"].texture)
texture.styled = true
end
if not tbar.styled then
tbar:SetPoint("TOPLEFT", frame, "TOPLEFT", 2, -2)
tbar:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -2, 2)
tbar.styled = true
end
if not name.styled then
name:ClearAllPoints()
name:SetPoint("LEFT", frame, "LEFT", 4, 0)
name:SetWidth(180)
name:SetHeight(8)
name:SetFont(Qulight["media"].font, 10, "OUTLINE")
name:SetShadowOffset(0, 0, 0, 0)
name:SetJustifyH("LEFT")
name.SetFont = dummy
name.styled = true
end
if not timer.styled then
timer:ClearAllPoints()
timer:SetPoint("RIGHT", frame, "RIGHT", -5, 0)
timer:SetFont(Qulight["media"].font, 10, "OUTLINE")
timer:SetShadowOffset(0, 0, 0, 0)
timer:SetJustifyH("RIGHT")
timer.SetFont = dummy
timer.styled = true
end
if bar.owner.options.IconLeft then icon1:Show() icon1.overlay:Show() else icon1:Hide() icon1.overlay:Hide() end
if bar.owner.options.IconRight then icon2:Show() icon2.overlay:Show() else icon2:Hide() icon2.overlay:Hide() end
tbar:SetAlpha(1)
frame:SetAlpha(1)
texture:SetAlpha(1)
frame:Show()
bar:Update(0)
bar.injected = true
end
bar:ApplyStyle()
end
end
end
local SkinBossTitle = function()
local anchor = DBMBossHealthDropdown:GetParent()
if not anchor.styled then
local header = {anchor:GetRegions()}
if header[1]:IsObjectType("FontString") then
header[1]:SetFont(Qulight["media"].font, 10, "OUTLINE")
header[1]:SetShadowOffset(0, 0, 0, 0)
header[1]:SetTextColor(1, 1, 1, 1)
anchor.styled = true
end
header = nil
end
anchor = nil
end
local SkinBoss = function()
local count = 1
while (_G[format("DBM_BossHealth_Bar_%d", count)]) do
local bar = _G[format("DBM_BossHealth_Bar_%d", count)]
local background = _G[bar:GetName().."BarBorder"]
local progress = _G[bar:GetName().."Bar"]
local name = _G[bar:GetName().."BarName"]
local timer = _G[bar:GetName().."BarTimer"]
local prev = _G[format("DBM_BossHealth_Bar_%d", count-1)]
if (count == 1) then
local _, anch, _ , _, _ = bar:GetPoint()
bar:ClearAllPoints()
if DBM_SavedOptions.HealthFrameGrowUp then
bar:SetPoint("BOTTOM", anch, "TOP", 0, 3)
else
bar:SetPoint("TOP", anch, "BOTTOM", 0, -3)
end
else
bar:ClearAllPoints()
if DBM_SavedOptions.HealthFrameGrowUp then
bar:SetPoint("BOTTOMLEFT", prev, "TOPLEFT", 0, 3)
else
bar:SetPoint("TOPLEFT", prev, "BOTTOMLEFT", 0, -3)
end
end
if not bar.styled then
bar:SetScale(1)
bar:SetHeight(19)
CreateStyle(bar, 2)
background:SetNormalTexture(nil)
bar.styled = true
end
if not progress.styled then
progress:SetStatusBarTexture(Qulight["media"].texture)
progress:SetBackdrop(backdrop)
progress:SetBackdropColor(r,g,b,1)
if forcebosshealthclasscolor then
local tslu = 0
progress:SetStatusBarColor(r,g,b,1)
progress:HookScript("OnUpdate", function(self, elapsed)
tslu = tslu+ elapsed
if tslu > 0.025 then
self:SetStatusBarColor(r,g,b,1)
tslu = 0
end
end)
end
progress.styled = true
end
progress:ClearAllPoints()
progress:SetPoint("TOPLEFT", bar, "TOPLEFT", 2, -2)
progress:SetPoint("BOTTOMRIGHT", bar, "BOTTOMRIGHT", -2, 2)
if not name.styled then
name:ClearAllPoints()
name:SetPoint("LEFT", bar, "LEFT", 4, 0)
name:SetFont(Qulight["media"].font, 10, "OUTLINE")
name:SetShadowOffset(0, 0, 0, 0)
name:SetJustifyH("LEFT")
name.styled = true
end
if not timer.styled then
timer:ClearAllPoints()
timer:SetPoint("RIGHT", bar, "RIGHT", -5, 0)
timer:SetFont(Qulight["media"].font, 10, "OUTLINE")
timer:SetShadowOffset(0, 0, 0, 0)
timer:SetJustifyH("RIGHT")
timer.styled = true
end
count = count + 1
end
end
hooksecurefunc(DBT, "CreateBar", SkinBars)
hooksecurefunc(DBM.BossHealth, "Show", SkinBossTitle)
hooksecurefunc(DBM.BossHealth, "AddBoss", SkinBoss)
hooksecurefunc(DBM.BossHealth, "UpdateSettings", SkinBoss)
local firstRange = true
hooksecurefunc(DBM.RangeCheck, "Show", function()
if firstRange then
DBMRangeCheck:SetBackdrop(nil)
local bd = CreateFrame("Frame", nil, DBMRangeCheckRadar)
bd:SetPoint("TOPLEFT")
bd:SetPoint("BOTTOMRIGHT")
bd:SetFrameLevel(0)
bd:SetFrameStrata(DBMRangeCheckRadar:GetFrameStrata())
bd:SetBackdropColor(.05,.05,.05, .9)
bd:SetBackdrop(backdrop)
bd:SetBackdropColor(.08,.08,.08, .9)
firstRange = false
end
end)
if croprwicons then
local replace = string.gsub
local old = RaidNotice_AddMessage
RaidNotice_AddMessage = function(noticeFrame, textString, colorInfo)
if textString:find(" |T") then
textString=replace(textString,"(:12:12)",":"..rwiconsize..":"..rwiconsize..":0:0:64:64:5:59:5:59")
end
return old(noticeFrame, textString, colorInfo)
end
end
end
end)
--[[]]
local UploadDBM = function()
if IsAddOnLoaded("DBM-Core") then
DBM_AllSavedOptions.Enabled=true
DBM_AllSavedOptions.WarningIconLeft=false
DBM_AllSavedOptions.WarningIconRight=false
DBM_AllSavedOptions.ShowSpecialWarnings = true
DBM_AllSavedOptions.ShowMinimapButton = false
DBT_AllPersistentOptions["Default"]["DBM"].Scale = 1
DBT_AllPersistentOptions["Default"]["DBM"].HugeScale = 1
DBT_AllPersistentOptions["Default"]["DBM"].BarXOffset = 0
DBT_AllPersistentOptions["Default"]["DBM"].FillUpBars = true
DBT_AllPersistentOptions["Default"]["DBM"].IconLeft = true
DBT_AllPersistentOptions["Default"]["DBM"].ExpandUpwards = true
DBT_AllPersistentOptions["Default"]["DBM"].IconRight = false
DBT_AllPersistentOptions["Default"]["DBM"].IconLeft = true
DBT_AllPersistentOptions["Default"]["DBM"].HugeBarsEnabled = true
DBT_AllPersistentOptions["Default"]["DBM"].HugeBarXOffset = 0
DBT_AllPersistentOptions["Default"]["DBM"].HugeBarXOffset = 0
DBT_AllPersistentOptions["Default"]["DBM"].HugeTimerX = 7
DBT_AllPersistentOptions["Default"]["DBM"].HugeBarYOffset = 7
DBT_AllPersistentOptions["Default"]["DBM"].BarYOffset = 5
DBT_AllPersistentOptions["Default"]["DBM"].Texture = Qulight["media"].texture
DBT_AllPersistentOptions["Default"]["DBM"].EndColorG = 1
DBT_AllPersistentOptions["Default"]["DBM"].HugeTimerY = 91.11986689654809
DBT_AllPersistentOptions["Default"]["DBM"].HugeBarXOffset = 0
DBT_AllPersistentOptions["Default"]["DBM"].Scale = 1
DBT_AllPersistentOptions["Default"]["DBM"].IconLeft = true
DBT_AllPersistentOptions["Default"]["DBM"].EnlargeBarsPercent = 0.125
DBT_AllPersistentOptions["Default"]["DBM"].TimerY = 172.348816227143
DBT_AllPersistentOptions["Default"]["DBM"].StartColorR = 0.08627450980392157
DBT_AllPersistentOptions["Default"]["DBM"].HugeScale = 1
DBT_AllPersistentOptions["Default"]["DBM"].TimerX = 432.5000026329087
DBT_AllPersistentOptions["Default"]["DBM"].HugeBarsEnabled = true
DBT_AllPersistentOptions["Default"]["DBM"].BarYOffset = 5
DBT_AllPersistentOptions["Default"]["DBM"].HugeTimerX = -306.0003201890552
DBT_AllPersistentOptions["Default"]["DBM"].HugeBarYOffset = 7
DBT_AllPersistentOptions["Default"]["DBM"].ExpandUpwards = true
DBT_AllPersistentOptions["Default"]["DBM"].TimerPoint = "CENTER"
DBT_AllPersistentOptions["Default"]["DBM"].StartColorG = 1
DBT_AllPersistentOptions["Default"]["DBM"].IconRight = false
DBT_AllPersistentOptions["Default"]["DBM"].StartColorB = 0.1333333333333333
DBT_AllPersistentOptions["Default"]["DBM"].EndColorR = 0.2196078431372549
DBT_AllPersistentOptions["Default"]["DBM"].Width = 189
DBT_AllPersistentOptions["Default"]["DBM"].HugeTimerPoint = "CENTER"
DBT_AllPersistentOptions["Default"]["DBM"].FontSize = 10
DBT_AllPersistentOptions["Default"]["DBM"].HugeWidth = 189
DBT_AllPersistentOptions["Default"]["DBM"].EnlargeBarsTime = 8
DBT_AllPersistentOptions["Default"]["DBM"].Height = 20
DBT_AllPersistentOptions["Default"]["DBM"].FillUpBars = true
DBT_AllPersistentOptions["Default"]["DBM"].BarXOffset = 0
DBT_AllPersistentOptions["Default"]["DBM"].EndColorB = 0.3490196078431372
end
end
local loadOptions = CreateFrame("Frame")
loadOptions:RegisterEvent("PLAYER_LOGIN")
loadOptions:SetScript("OnEvent", UploadDBM) | gpl-2.0 |
n0xus/darkstar | scripts/zones/Meriphataud_Mountains/Zone.lua | 17 | 4713 | -----------------------------------
--
-- Zone: Meriphataud_Mountains (119)
--
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
package.loaded["scripts/globals/chocobo_digging"] = nil;
-----------------------------------
require("scripts/zones/Meriphataud_Mountains/TextIDs");
require("scripts/globals/icanheararainbow");
require("scripts/globals/zone");
require("scripts/globals/conquest");
require("scripts/globals/chocobo_digging");
-----------------------------------
-- Chocobo Digging vars
-----------------------------------
local itemMap = {
-- itemid, abundance, requirement
{ 646, 4, DIGREQ_NONE },
{ 845, 12, DIGREQ_NONE },
{ 640, 112, DIGREQ_NONE },
{ 768, 237, DIGREQ_NONE },
{ 893, 41, DIGREQ_NONE },
{ 748, 33, DIGREQ_NONE },
{ 846, 145, DIGREQ_NONE },
{ 869, 100, DIGREQ_NONE },
{ 17296, 162, DIGREQ_NONE },
{ 771, 21, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 678, 5, DIGREQ_BURROW },
{ 645, 9, DIGREQ_BURROW },
{ 737, 5, DIGREQ_BURROW },
{ 643, 69, DIGREQ_BURROW },
{ 1650, 62, DIGREQ_BURROW },
{ 644, 31, DIGREQ_BURROW },
{ 736, 62, DIGREQ_BURROW },
{ 739, 5, DIGREQ_BURROW },
{ 678, 5, DIGREQ_BORE },
{ 645, 9, DIGREQ_BORE },
{ 737, 5, DIGREQ_BORE },
{ 738, 8, DIGREQ_BORE },
{ 4570, 10, DIGREQ_MODIFIER },
{ 4487, 11, DIGREQ_MODIFIER },
{ 4409, 12, DIGREQ_MODIFIER },
{ 1188, 10, DIGREQ_MODIFIER },
{ 4532, 12, DIGREQ_MODIFIER },
};
local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED };
-----------------------------------
-- onChocoboDig
-----------------------------------
function onChocoboDig(player, precheck)
return chocoboDig(player, itemMap, precheck, messageArray);
end;
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17265291,17265292,17265293};
SetFieldManual(manuals);
-- Waraxe Beak
SetRespawnTime(17264828, 900, 10800);
-- Coo Keja the Unseen
SetRespawnTime(17264946, 900, 10800);
SetRegionalConquestOverseers(zone:getRegionID())
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( 752.632, -33.761, -40.035, 129);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 0x001f;
elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then
cs = 0x0022; -- no update for castle oztroja (north)
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter( player, region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x001f) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
elseif (csid == 0x0022) then
if (player:getPreviousZone() == 120) then
player:updateEvent(0,0,0,0,0,2);
elseif (player:getPreviousZone() == 117) then
player:updateEvent(0,0,0,0,0,1);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x001f) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end; | gpl-3.0 |
adamjedlicka/ForgeUI | ForgeUI_InterfaceMenuList/ForgeUI_InterfaceMenuList.lua | 1 | 16603 | -----------------------------------------------------------------------------------------------
-- Client Lua Script for ForgeUI_InterfaceMenuList
-- Copyright (c) NCsoft. All rights reserved
-----------------------------------------------------------------------------------------------
require "Window"
require "GameLib"
require "Apollo"
local ForgeUI
local ForgeUI_InterfaceMenuList = {}
function ForgeUI_InterfaceMenuList:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
-- mandatory
self.api_version = 1
self.version = "0.1.0"
self.author = "WintyBadass"
self.strAddonName = "ForgeUI_InterfaceMenuList"
self.strDisplayName = "Interface menu list"
self.wndContainers = {}
-- optional
self.tSettings = {
tPinnedAddons = {}
}
return o
end
function ForgeUI_InterfaceMenuList:Init()
local bHasConfigureFunction = false
local strConfigureButtonText = ""
local tDependencies = {
"ForgeUI"
}
Apollo.RegisterAddon(self, bHasConfigureFunction, strConfigureButtonText, tDependencies)
end
function ForgeUI_InterfaceMenuList:OnLoad()
self.xmlDoc = XmlDoc.CreateFromFile("ForgeUI_InterfaceMenuList.xml")
self.xmlDoc:RegisterCallback("OnDocumentReady", self)
end
function ForgeUI_InterfaceMenuList:OnDocumentReady()
if self.xmlDoc == nil and not self.xmlDoc:IsLoaded() then return end
if ForgeUI == nil then -- forgeui loaded
ForgeUI = Apollo.GetAddon("ForgeUI")
end
ForgeUI.RegisterAddon(self)
end
function ForgeUI_InterfaceMenuList:ForgeAPI_AfterRegistration()
Apollo.RegisterEventHandler("VarChange_FrameCount", "OnNextFrame", self)
Apollo.RegisterEventHandler("InterfaceMenuList_NewAddOn", "OnNewAddonListed", self)
Apollo.RegisterEventHandler("InterfaceMenuList_AlertAddOn", "OnDrawAlert", self)
Apollo.RegisterEventHandler("CharacterCreated", "OnCharacterCreated", self)
Apollo.RegisterEventHandler("Tutorial_RequestUIAnchor", "OnTutorial_RequestUIAnchor", self)
Apollo.RegisterTimerHandler("TimeUpdateTimer", "OnUpdateTimer", self)
Apollo.RegisterTimerHandler("QueueRedrawTimer", "OnQueuedRedraw", self)
Apollo.RegisterEventHandler("ApplicationWindowSizeChanged", "ButtonListRedraw", self)
Apollo.RegisterEventHandler("OptionsUpdated_HUDPreferences", "OnUpdateTimer", self)
self.wndMain = Apollo.LoadForm(self.xmlDoc , "ForgeUI_InterfaceMenuListForm", "FixedHudStratumHigh", self)
self.wndList = Apollo.LoadForm(self.xmlDoc , "FullListFrame", nil, self)
self.wndMain:FindChild("OpenFullListBtn"):AttachWindow(self.wndList)
self.wndMain:FindChild("OpenFullListBtn"):Enable(false)
Apollo.CreateTimer("QueueRedrawTimer", 0.3, false)
self.tMenuData = {
[Apollo.GetString("InterfaceMenu_SystemMenu")] = { "", "Escape", "Icon_Windows32_UI_CRB_InterfaceMenu_EscMenu" }, --
}
self.tMenuTooltips = {}
self.tMenuAlerts = {}
if GameLib.GetPlayerUnit() then
self:OnCharacterCreated()
end
end
function ForgeUI_InterfaceMenuList:ForgeAPI_AfterRestore()
if #self.tSettings.tPinnedAddons == 0 then
self.tSettings.tPinnedAddons = {
Apollo.GetString("InterfaceMenu_AccountInventory"),
Apollo.GetString("InterfaceMenu_Character"),
Apollo.GetString("InterfaceMenu_AbilityBuilder"),
Apollo.GetString("InterfaceMenu_QuestLog"),
Apollo.GetString("InterfaceMenu_GroupFinder"),
Apollo.GetString("InterfaceMenu_Social"),
Apollo.GetString("InterfaceMenu_Mail"),
Apollo.GetString("InterfaceMenu_Lore")
}
end
self:ButtonListRedraw()
end
function ForgeUI_InterfaceMenuList:OnListShow()
self.wndList:ToFront()
end
function ForgeUI_InterfaceMenuList:OnCharacterCreated()
Apollo.CreateTimer("TimeUpdateTimer", 1.0, true)
end
function ForgeUI_InterfaceMenuList:OnUpdateTimer()
if not self.bHasLoaded then
Event_FireGenericEvent("InterfaceMenuListHasLoaded")
self.wndMain:FindChild("OpenFullListBtn"):Enable(true)
self.bHasLoaded = true
end
--Toggle Visibility based on ui preference
local nVisibility = Apollo.GetConsoleVariable("hud.TimeDisplay")
local tLocalTime = GameLib.GetLocalTime()
local tServerTime = GameLib.GetServerTime()
local b24Hour = true
local nLocalHour = tLocalTime.nHour > 12 and tLocalTime.nHour - 12 or tLocalTime.nHour == 0 and 12 or tLocalTime.nHour
local nServerHour = tServerTime.nHour > 12 and tServerTime.nHour - 12 or tServerTime.nHour == 0 and 12 or tServerTime.nHour
self.wndMain:FindChild("Time"):SetText(string.format("%02d:%02d", tostring(tLocalTime.nHour), tostring(tLocalTime.nMinute)))
if nVisibility == 2 then --Local 12hr am/pm
self.wndMain:FindChild("Time"):SetText(string.format("%02d:%02d", tostring(nLocalHour), tostring(tLocalTime.nMinute)))
b24Hour = false
elseif nVisibility == 3 then --Server 24hr
self.wndMain:FindChild("Time"):SetText(string.format("%02d:%02d", tostring(tServerTime.nHour), tostring(tServerTime.nMinute)))
elseif nVisibility == 4 then --Server 12hr am/pm
self.wndMain:FindChild("Time"):SetText(string.format("%02d:%02d", tostring(nServerHour), tostring(tServerTime.nMinute)))
b24Hour = false
end
nLocalHour = b24Hour and tLocalTime.nHour or nLocalHour
nServerHour = b24Hour and tServerTime.nHour or nServerHour
self.wndMain:FindChild("Time"):SetTooltip(
string.format("%s%02d:%02d\n%s%02d:%02d",
Apollo.GetString("OptionsHUD_Local"), tostring(nLocalHour), tostring(tLocalTime.nMinute),
Apollo.GetString("OptionsHUD_Server"), tostring(nServerHour), tostring(tServerTime.nMinute)
)
)
end
function ForgeUI_InterfaceMenuList:OnNewAddonListed(strKey, tParams)
strKey = string.gsub(strKey, ":", "|") -- ":'s don't work for window names, sorry!"
self.tMenuData[strKey] = tParams
self:FullListRedraw()
self:ButtonListRedraw()
end
function ForgeUI_InterfaceMenuList:IsPinned(strText)
for idx, strWindowText in pairs(self.tSettings.tPinnedAddons) do
if (strText == strWindowText) then
return true
end
end
return false
end
function ForgeUI_InterfaceMenuList:FullListRedraw()
local strUnbound = Apollo.GetString("Keybinding_Unbound")
local wndParent = self.wndList:FindChild("FullListScroll")
local strQuery = Apollo.StringToLower(tostring(self.wndList:FindChild("SearchEditBox"):GetText()) or "")
if strQuery == nil or strQuery == "" or not strQuery:match("[%w%s]+") then
strQuery = ""
end
for strWindowText, tData in pairs(self.tMenuData) do
local bSearchResultMatch = string.find(Apollo.StringToLower(strWindowText), strQuery) ~= nil
if strQuery == "" or bSearchResultMatch then
local wndMenuItem = self:LoadByName("MenuListItem", wndParent, strWindowText)
local wndMenuButton = self:LoadByName("InterfaceMenuButton", wndMenuItem:FindChild("Icon"), strWindowText)
local strTooltip = strWindowText
if string.len(tData[2]) > 0 then
local strKeyBindLetter = GameLib.GetKeyBinding(tData[2])
strKeyBindLetter = strKeyBindLetter == strUnbound and "" or string.format(" (%s)", strKeyBindLetter) -- LOCALIZE
strTooltip = strKeyBindLetter ~= "" and strTooltip .. strKeyBindLetter or strTooltip
end
if tData[3] ~= "" then
wndMenuButton:FindChild("Icon"):SetSprite(tData[3])
else
wndMenuButton:FindChild("Icon"):SetText(string.sub(strTooltip, 1, 1))
end
wndMenuButton:FindChild("ShortcutBtn"):SetData(strWindowText)
wndMenuButton:FindChild("Icon"):SetTooltip(strTooltip)
self.tMenuTooltips[strWindowText] = strTooltip
wndMenuItem:FindChild("MenuListItemBtn"):SetText(strWindowText)
wndMenuItem:FindChild("MenuListItemBtn"):SetData(tData[1])
wndMenuItem:FindChild("PinBtn"):SetCheck(self:IsPinned(strWindowText))
wndMenuItem:FindChild("PinBtn"):SetData(strWindowText)
if string.len(tData[2]) > 0 then
local strKeyBindLetter = GameLib.GetKeyBinding(tData[2])
wndMenuItem:FindChild("MenuListItemBtn"):FindChild("MenuListItemKeybind"):SetText(strKeyBindLetter == strUnbound and "" or string.format("(%s)", strKeyBindLetter)) -- LOCALIZE
end
elseif not bSearchResultMatch and wndParent:FindChild(strWindowText) then
wndParent:FindChild(strWindowText):Destroy()
end
end
wndParent:ArrangeChildrenVert(0, function (a,b) return a:GetName() < b:GetName() end)
end
function ForgeUI_InterfaceMenuList:ButtonListRedraw()
Apollo.StopTimer("QueueRedrawTimer")
Apollo.StartTimer("QueueRedrawTimer")
end
function ForgeUI_InterfaceMenuList:OnQueuedRedraw()
local strUnbound = Apollo.GetString("Keybinding_Unbound")
local wndParent = self.wndMain:FindChild("ButtonList")
wndParent:DestroyChildren()
local nParentWidth = wndParent:GetWidth()
local nLastButtonWidth = 0
local nTotalWidth = 0
for idx, strWindowText in pairs(self.tSettings.tPinnedAddons) do
tData = self.tMenuData[strWindowText]
--Magic number below is allowing the 1 pixel gutter on the right
if tData and nTotalWidth + nLastButtonWidth <= nParentWidth + 1 then
local wndMenuItem = self:LoadByName("InterfaceMenuButton", wndParent, strWindowText)
local strTooltip = strWindowText
nLastButtonWidth = wndMenuItem:GetWidth()
nTotalWidth = nTotalWidth + nLastButtonWidth
if string.len(tData[2]) > 0 then
local strKeyBindLetter = GameLib.GetKeyBinding(tData[2])
strKeyBindLetter = strKeyBindLetter == strUnbound and "" or string.format(" (%s)", strKeyBindLetter) -- LOCALIZE
strTooltip = strKeyBindLetter ~= "" and strTooltip .. strKeyBindLetter or strTooltip
end
if tData[3] ~= "" then
wndMenuItem:FindChild("Icon"):SetSprite(tData[3])
else
wndMenuItem:FindChild("Icon"):SetText(string.sub(strTooltip, 1, 1))
end
wndMenuItem:FindChild("ShortcutBtn"):SetData(strWindowText)
wndMenuItem:FindChild("Icon"):SetTooltip(strTooltip)
end
if self.tMenuAlerts[strWindowText] then
self:OnDrawAlert(strWindowText, self.tMenuAlerts[strWindowText])
end
end
wndParent:ArrangeChildrenHorz(0)
end
-----------------------------------------------------------------------------------------------
-- Search
-----------------------------------------------------------------------------------------------
function ForgeUI_InterfaceMenuList:OnSearchEditBoxChanged(wndHandler, wndControl)
self.wndList:FindChild("SearchClearBtn"):Show(string.len(wndHandler:GetText() or "") > 0)
self:FullListRedraw()
end
function ForgeUI_InterfaceMenuList:OnSearchClearBtn(wndHandler, wndControl)
self.wndList:FindChild("SearchFlash"):SetSprite("CRB_WindowAnimationSprites:sprWinAnim_BirthSmallTemp")
self.wndList:FindChild("SearchFlash"):SetFocus()
self.wndList:FindChild("SearchClearBtn"):Show(false)
self.wndList:FindChild("SearchEditBox"):SetText("")
self:FullListRedraw()
end
function ForgeUI_InterfaceMenuList:OnSearchCommitBtn(wndHandler, wndControl)
self.wndList:FindChild("SearchFlash"):SetSprite("CRB_WindowAnimationSprites:sprWinAnim_BirthSmallTemp")
self.wndList:FindChild("SearchFlash"):SetFocus()
self:FullListRedraw()
end
-----------------------------------------------------------------------------------------------
-- Alerts
-----------------------------------------------------------------------------------------------
function ForgeUI_InterfaceMenuList:OnDrawAlert(strWindowName, tParams)
self.tMenuAlerts[strWindowName] = tParams
for idx, wndTarget in pairs(self.wndMain:FindChild("ButtonList"):GetChildren()) do
if wndTarget and tParams then
local wndButton = wndTarget:FindChild("ShortcutBtn")
if wndButton then
local wndIcon = wndButton:FindChild("Icon")
if wndButton:GetData() == strWindowName then
if tParams[1] then
local wndIndicator = self:LoadByName("AlertIndicator", wndButton:FindChild("Alert"), "AlertIndicator")
elseif wndButton:FindChild("AlertIndicator") ~= nil then
wndButton:FindChild("AlertIndicator"):Destroy()
end
if tParams[2] then
wndIcon:SetTooltip(string.format("%s\n\n%s", self.tMenuTooltips[strWindowName], tParams[2]))
end
if tParams[3] and tParams[3] > 0 then
local strColor = tParams[1] and "UI_WindowTextOrange" or "UI_TextHoloTitle"
wndButton:FindChild("Number"):Show(true)
wndButton:FindChild("Number"):SetText(tParams[3])
wndButton:FindChild("Number"):SetTextColor(ApolloColor.new(strColor))
else
wndButton:FindChild("Number"):Show(false)
wndButton:FindChild("Number"):SetText("")
wndButton:FindChild("Number"):SetTextColor(ApolloColor.new("UI_TextHoloTitle"))
end
end
end
end
end
local wndParent = self.wndList:FindChild("FullListScroll")
for idx, wndTarget in pairs(wndParent:GetChildren()) do
local wndButton = wndTarget:FindChild("ShortcutBtn")
local wndIcon = wndButton:FindChild("Icon")
if wndButton:GetData() == strWindowName then
if tParams[1] then
local wndIndicator = self:LoadByName("AlertIndicator", wndButton:FindChild("Alert"), "AlertIndicator")
elseif wndButton:FindChild("AlertIndicator") ~= nil then
wndButton:FindChild("AlertIndicator"):Destroy()
end
if tParams[2] then
wndIcon:SetTooltip(string.format("%s\n\n%s", self.tMenuTooltips[strWindowName], tParams[2]))
end
if tParams[3] and tParams[3] > 0 then
local strColor = tParams[1] and "UI_WindowTextOrange" or "UI_TextHoloTitle"
wndButton:FindChild("Number"):Show(true)
wndButton:FindChild("Number"):SetText(tParams[3])
wndButton:FindChild("Number"):SetTextColor(ApolloColor.new(strColor))
else
wndButton:FindChild("Number"):Show(false)
end
end
end
end
-----------------------------------------------------------------------------------------------
-- Helpers and Errata
-----------------------------------------------------------------------------------------------
function ForgeUI_InterfaceMenuList:OnMenuListItemClick(wndHandler, wndControl)
if wndHandler ~= wndControl then return end
if string.len(wndControl:GetData()) > 0 then
Event_FireGenericEvent(wndControl:GetData())
else
InvokeOptionsScreen()
end
self.wndList:Show(false)
end
function ForgeUI_InterfaceMenuList:OnPinBtnChecked(wndHandler, wndControl)
if wndHandler ~= wndControl then return end
local wndParent = wndControl:GetParent():GetParent()
self.tSettings.tPinnedAddons = {}
for idx, wndMenuItem in pairs(wndParent:GetChildren()) do
if wndMenuItem:FindChild("PinBtn"):IsChecked() then
table.insert(self.tSettings.tPinnedAddons, wndMenuItem:FindChild("PinBtn"):GetData())
end
end
self:ButtonListRedraw()
end
function ForgeUI_InterfaceMenuList:OnListBtnClick(wndHandler, wndControl) -- These are the five always on icons on the top
if wndHandler ~= wndControl then return end
local strMappingResult = self.tMenuData[wndHandler:GetData()][1] or ""
if string.len(strMappingResult) > 0 then
Event_FireGenericEvent(strMappingResult)
else
InvokeOptionsScreen()
end
end
function ForgeUI_InterfaceMenuList:OnListBtnMouseEnter(wndHandler, wndControl)
wndHandler:SetBGColor("ffffffff")
if wndHandler ~= wndControl or self.wndList:IsVisible() then
return
end
end
function ForgeUI_InterfaceMenuList:OnListBtnMouseExit(wndHandler, wndControl) -- Also self.wndMain MouseExit and ButtonList MouseExit
wndHandler:SetBGColor("9dffffff")
end
function ForgeUI_InterfaceMenuList:OnOpenFullListCheck(wndHandler, wndControl)
self.wndList:FindChild("SearchEditBox"):SetFocus()
self:FullListRedraw()
end
function ForgeUI_InterfaceMenuList:LoadByName(strForm, wndParent, strCustomName)
local wndNew = wndParent:FindChild(strCustomName)
if not wndNew then
wndNew = Apollo.LoadForm(self.xmlDoc , strForm, wndParent, self)
wndNew:SetName(strCustomName)
end
return wndNew
end
function ForgeUI_InterfaceMenuList:OnTutorial_RequestUIAnchor(eAnchor, idTutorial, strPopupText)
local arTutorialAnchorMapping =
{
--[GameLib.CodeEnumTutorialAnchor.Abilities] = "LASBtn",
--[GameLib.CodeEnumTutorialAnchor.Character] = "CharacterBtn",
--[GameLib.CodeEnumTutorialAnchor.Mail] = "MailBtn",
--[GameLib.CodeEnumTutorialAnchor.GalacticArchive] = "LoreBtn",
--[GameLib.CodeEnumTutorialAnchor.Social] = "SocialBtn",
--[GameLib.CodeEnumTutorialAnchor.GroupFinder] = "GroupFinderBtn",
}
local strWindowName = "ButtonList" or false
if not strWindowName then
return
end
local tRect = {}
tRect.l, tRect.t, tRect.r, tRect.b = self.wndMain:FindChild(strWindowName):GetRect()
tRect.r = tRect.r - 26
if arTutorialAnchorMapping[eAnchor] then
Event_FireGenericEvent("Tutorial_RequestUIAnchorResponse", eAnchor, idTutorial, strPopupText, tRect)
end
end
local ForgeUI_InterfaceMenuListInst = ForgeUI_InterfaceMenuList:new()
ForgeUI_InterfaceMenuListInst:Init() | mit |
Python1320/wire | lua/wire/gates/memory.lua | 17 | 11088 | --[[
Memory Gates
]]
GateActions("Memory")
GateActions["latch"] = {
name = "Latch (Edge triggered)",
inputs = { "Data", "Clk" },
output = function(gate, Data, Clk)
local clk = (Clk > 0)
if (gate.PrevValue ~= clk) then
gate.PrevValue = clk
if (clk) then
gate.LatchStore = Data
end
end
return gate.LatchStore or 0
end,
reset = function(gate)
gate.LatchStore = 0
gate.PrevValue = nil
end,
label = function(Out, Data, Clk)
return "Latch Data:"..Data.." Clock:"..Clk.." = "..Out
end
}
GateActions["dlatch"] = {
name = "D-Latch",
inputs = { "Data", "Clk" },
output = function(gate, Data, Clk)
if (Clk > 0) then
gate.LatchStore = Data
end
return gate.LatchStore or 0
end,
reset = function(gate)
gate.LatchStore = 0
end,
label = function(Out, Data, Clk)
return "D-Latch Data:"..Data.." Clock:"..Clk.." = "..Out
end
}
GateActions["srlatch"] = {
name = "SR-Latch",
inputs = { "S", "R" },
output = function(gate, S, R)
if (S > 0) and (R <= 0) then
gate.LatchStore = 1
elseif (S <= 0) and (R > 0) then
gate.LatchStore = 0
end
return gate.LatchStore
end,
reset = function(gate)
gate.LatchStore = 0
end,
label = function(Out, S, R)
return "S:"..S.." R:"..R.." == "..Out
end
}
GateActions["rslatch"] = {
name = "RS-Latch",
inputs = { "S", "R" },
output = function(gate, S, R)
if (S > 0) and (R < 1) then
gate.LatchStore = 1
elseif (R > 0) then
gate.LatchStore = 0
end
return gate.LatchStore
end,
reset = function(gate)
gate.LatchStore = 0
end,
label = function(Out, S, R)
return "S:"..S.." R:"..R.." == "..Out
end
}
GateActions["toggle"] = {
name = "Toggle (Edge triggered)",
inputs = { "Clk", "OnValue", "OffValue" },
output = function(gate, Clk, OnValue, OffValue)
local clk = (Clk > 0)
if (gate.PrevValue ~= clk) then
gate.PrevValue = clk
if (clk) then
gate.LatchStore = (not gate.LatchStore)
end
end
if (gate.LatchStore) then return OnValue end
return OffValue
end,
reset = function(gate)
gate.LatchStore = false
gate.PrevValue = nil
end,
label = function(Out, Clk, OnValue, OffValue)
return "Off:"..OffValue.." On:"..OnValue.." Clock:"..Clk.." = "..Out
end
}
GateActions["wom4"] = {
name = "Write Only Memory(4 store)",
inputs = { "Clk", "AddrWrite", "Data" },
output = function( gate, Clk, AddrWrite, Data )
AddrWrite = math.floor(tonumber(AddrWrite))
if ( Clk > 0 ) then
if ( AddrWrite >= 0 ) and ( AddrWrite < 4 ) then
gate.LatchStore[AddrWrite] = Data
end
end
return 0
end,
reset = function( gate )
gate.LatchStore = {}
for i = 0, 3 do
gate.LatchStore[i] = 0
end
end,
label = function()
return "Write Only Memory - 4 store"
end
}
GateActions["ram8"] = {
name = "RAM(8 store)",
inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" },
output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset )
if (Reset > 0) then
gate.LatchStore = {}
end
AddrRead = math.floor(tonumber(AddrRead))
AddrWrite = math.floor(tonumber(AddrWrite))
if (Clk > 0) then
if (AddrWrite >= 0) and (AddrWrite < 8) then
gate.LatchStore[AddrWrite] = Data
end
end
if (AddrRead < 0) or (AddrRead >= 8) then return 0 end
return gate.LatchStore[AddrRead] or 0
end,
reset = function(gate)
gate.LatchStore = {}
end,
label = function(Out, Clk, AddrRead, AddrWrite, Data, Reset)
return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset..
"\nReadAddr:"..AddrRead.." = "..Out
end,
ReadCell = function(dummy,gate,Address)
if (Address < 0) || (Address >= 8) then
return 0
else
return gate.LatchStore[Address] or 0
end
end,
WriteCell = function(dummy,gate,Address,value)
if (Address < 0) || (Address >= 8) then
return false
else
gate.LatchStore[Address] = value
return true
end
end
}
GateActions["ram64"] = {
name = "RAM(64 store)",
inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" },
output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset )
if (Reset > 0) then
gate.LatchStore = {}
end
AddrRead = math.floor(tonumber(AddrRead))
AddrWrite = math.floor(tonumber(AddrWrite))
if (Clk > 0) then
if (AddrWrite < 64) then
gate.LatchStore[AddrWrite] = Data
end
end
return gate.LatchStore[AddrRead] or 0
end,
reset = function(gate)
gate.LatchStore = {}
end,
label = function(Out, Clk, AddrRead, AddrWrite, Data, Reset)
return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset..
"\nReadAddr:"..AddrRead.." = "..Out
end,
ReadCell = function(dummy,gate,Address)
if (Address < 0) || (Address >= 64) then
return 0
else
return gate.LatchStore[Address] or 0
end
end,
WriteCell = function(dummy,gate,Address,value)
if (Address < 0) || (Address >= 64) then
return false
else
gate.LatchStore[Address] = value
return true
end
end
}
GateActions["ram1k"] = {
name = "RAM(1kb)",
inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" },
output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset )
if (Reset > 0) then
gate.LatchStore = {}
end
AddrRead = math.floor(tonumber(AddrRead))
AddrWrite = math.floor(tonumber(AddrWrite))
if (Clk > 0) then
if (AddrWrite < 1024) then
gate.LatchStore[AddrWrite] = Data
end
end
return gate.LatchStore[AddrRead] or 0
end,
reset = function(gate)
gate.LatchStore = {}
end,
label = function(Out, Clk, AddrRead, AddrWrite, Data, Reset )
return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset..
"\nReadAddr:"..AddrRead.." = "..Out
end,
ReadCell = function(dummy,gate,Address)
if (Address < 0) || (Address >= 1024) then
return 0
else
return gate.LatchStore[Address] or 0
end
end,
WriteCell = function(dummy,gate,Address,value)
if (Address < 0) || (Address >= 1024) then
return false
else
gate.LatchStore[Address] = value
return true
end
end
}
GateActions["ram32k"] = {
name = "RAM(32kb)",
inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" },
output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset )
if (Reset > 0) then
gate.LatchStore = {}
end
AddrRead = math.floor(tonumber(AddrRead))
AddrWrite = math.floor(tonumber(AddrWrite))
if (Clk > 0) then
if (AddrWrite < 32768) then
gate.LatchStore[AddrWrite] = Data
end
end
return gate.LatchStore[AddrRead] or 0
end,
reset = function(gate)
gate.LatchStore = {}
end,
label = function(Out, Clk, AddrRead, AddrWrite, Data, Reset )
return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset..
"\nReadAddr:"..AddrRead.." = "..Out
end,
ReadCell = function(dummy,gate,Address)
if (Address < 0) || (Address >= 32768) then
return 0
else
return gate.LatchStore[Address] or 0
end
end,
WriteCell = function(dummy,gate,Address,value)
if (Address < 0) || (Address >= 32768) then
return false
else
gate.LatchStore[Address] = value
return true
end
end
}
GateActions["ram128k"] = {
name = "RAM(128kb)",
inputs = { "Clk", "AddrRead", "AddrWrite", "Data", "Reset" },
output = function(gate, Clk, AddrRead, AddrWrite, Data, Reset )
if (Reset > 0) then
gate.LatchStore = {}
end
AddrRead = math.floor(tonumber(AddrRead))
AddrWrite = math.floor(tonumber(AddrWrite))
if (Clk > 0) then
if (AddrWrite < 131072) then
gate.LatchStore[AddrWrite] = Data
end
end
return gate.LatchStore[AddrRead] or 0
end,
reset = function(gate)
gate.LatchStore = {}
end,
label = function(Out, Clk, AddrRead, AddrWrite, Data)
return "WriteAddr:"..AddrWrite.." Data:"..Data.." Clock:"..Clk..
"\nReadAddr:"..AddrRead.." = "..Out
end,
ReadCell = function(dummy,gate,Address)
if (Address < 0) || (Address >= 131072) then
return 0
else
return gate.LatchStore[Address] or 0
end
end,
WriteCell = function(dummy,gate,Address,value)
if (Address < 0) || (Address >= 131072) then
return false
else
gate.LatchStore[Address] = value
return true
end
end
}
GateActions["ram64x64"] = {
name = "RAM(64x64 store)",
inputs = { "Clk", "AddrReadX", "AddrReadY", "AddrWriteX", "AddrWriteY", "Data", "Reset" },
output = function(gate, Clk, AddrReadX, AddrReadY, AddrWriteX, AddrWriteY, Data, Reset )
if (Reset > 0) then
gate.LatchStore = {}
end
AddrReadX = math.floor(tonumber(AddrReadX))
AddrReadY = math.floor(tonumber(AddrReadY))
AddrWriteX = math.floor(tonumber(AddrWriteX))
AddrWriteY = math.floor(tonumber(AddrWriteY))
if (Clk > 0) then
if (AddrWriteX >= 0) and (AddrWriteX < 64) or (AddrWriteY >= 0) and (AddrWriteY < 64) then
gate.LatchStore[AddrWriteX + AddrWriteY*64] = Data
end
end
if (AddrReadX < 0) or (AddrReadX >= 64) or (AddrReadY < 0) or (AddrReadY >= 64) then
return 0
end
return gate.LatchStore[AddrReadX + AddrReadY*64] or 0
end,
reset = function(gate)
gate.LatchStore = {}
end,
label = function(Out, Clk, AddrReadX, AddrReadY, AddrWriteX, AddrWriteY, Data, Reset)
return "WriteAddr:"..AddrWriteX..", "..AddrWriteY.." Data:"..Data.." Clock:"..Clk.." Reset:"..Reset..
"\nReadAddr:"..AddrReadX..", "..AddrReadY.." = "..Out
end,
ReadCell = function(dummy,gate,Address)
if (Address < 0) || (Address >= 4096) then
return 0
else
return gate.LatchStore[Address] or 0
end
end,
WriteCell = function(dummy,gate,Address,value)
if (Address < 0) || (Address >= 4096) then
return false
else
gate.LatchStore[Address] = value
return true
end
end
}
GateActions["udcounter"] = {
name = "Up/Down Counter",
inputs = { "Increment", "Decrement", "Clk", "Reset"},
output = function(gate, Inc, Dec, Clk, Reset)
local lInc = (Inc > 0)
local lDec = (Dec > 0)
local lClk = (Clk > 0)
local lReset = (Reset > 0)
if ((gate.PrevInc ~= lInc || gate.PrevDec ~= lDec || gate.PrevClk ~= lClk) && lClk) then
if (lInc) and (!lDec) and (!lReset) then
gate.countStore = (gate.countStore or 0) + 1
elseif (!lInc) and (lDec) and (!lReset) then
gate.countStore = (gate.countStore or 0) - 1
end
gate.PrevInc = lInc
gate.PrevDec = lDec
gate.PrevClk = lClk
end
if (lReset) then
gate.countStore = 0
end
return gate.countStore
end,
label = function(Out, Inc, Dec, Clk, Reset)
return "Increment:"..Inc.." Decrement:"..Dec.." Clk:"..Clk.." Reset:"..Reset.." = "..Out
end
}
GateActions["togglewhile"] = {
name = "Toggle While(Edge triggered)",
inputs = { "Clk", "OnValue", "OffValue", "While" },
output = function(gate, Clk, OnValue, OffValue, While)
local clk = (Clk > 0)
if (While <= 0) then
clk = false
gate.LatchStore = false
end
if (gate.PrevValue ~= clk) then
gate.PrevValue = clk
if (clk) then
gate.LatchStore = (not gate.LatchStore)
end
end
if (gate.LatchStore) then return OnValue end
return OffValue
end,
reset = function(gate)
gate.LatchStore = 0
gate.PrevValue = nil
end,
label = function(Out, Clk, OnValue, OffValue, While)
return "Off:"..OffValue.." On:"..OnValue.." Clock:"..Clk.." While:"..While.." = "..Out
end
}
GateActions()
| apache-2.0 |
n0xus/darkstar | scripts/zones/Giddeus/npcs/Harvesting_Point.lua | 29 | 1095 | -----------------------------------
-- Area: Giddeus
-- NPC: Harvesting Point
-----------------------------------
package.loaded["scripts/zones/Giddeus/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/harvesting");
require("scripts/zones/Giddeus/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startHarvesting(player,player:getZoneID(),npc,trade,0x0046);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020);
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 |
realglobe-Inc/edo-auth | lib/table.lua | 1 | 2281 | -- Copyright 2015 realglobe, Inc.
--
-- 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 cjson = require("cjson.safe")
-- テーブルの比較。
local function equal(t1, t2)
if t1 == t2 then
return true
elseif (not t1) or (not t2) then
return false
end
for k, v1 in pairs(t1) do
local v2 = t2[k]
if v1 ~= v2 then
-- 両方テーブルかつ等しい場合のみ許してやる。
if type(v1) ~= "table" then
return false
elseif type(v2) ~= "table" then
return false
elseif not equal(v1, v2) then
return false
end
end
end
-- t1 は t2 に含まれる。
for k, _ in pairs(t2) do
if not t1[k] then
return false
end
end
-- t2 は t1 より大きくない。
return true
end
-- テーブルを文字列にする。
local to_string = function(t)
local buff, _ = cjson.encode(t)
if not buff then
return ""
end
return buff
end
-- キーの配列をつくる。
local keys = function(t)
if not t then
return nil
end
local ks = {}
local i = 1
for k, _ in pairs(t) do
ks[i] = k
i = i + 1
end
return ks
end
-- 値の配列をつくる。
local values = function(t)
if not t then
return nil
end
local vs = {}
local i = 1
for _, v in pairs(t) do
vs[i] = v
i = i + 1
end
return vs
end
-- 配列を集合形式にする。
local array_to_set = function(t)
if not t then
return nil
end
local set = {}
for _, v in pairs(t) do
set[v] = true
end
return set
end
return {
equal = equal,
to_string = to_string,
keys = keys,
values = values,
array_to_set = array_to_set,
}
| apache-2.0 |
RockySeven3161/Unknown.. | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
ArmanIr/ProFbOt | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
Azurithenkel/dotfiles | .config/awesome/rc.lua | 1 | 19931 | -- Standard awesome library
local gears = require("gears")
local awful = require("awful")
awful.rules = require("awful.rules")
require("awful.autofocus")
-- Widget and layout library
local wibox = require("wibox")
-- Theme handling library
local beautiful = require("beautiful")
-- Notification library
local naughty = require("naughty")
local menubar = require("menubar")
local hotkeys_popup = require("awful.hotkeys_popup")
-- Enable hotkeys help widget for VIM and other apps
-- when client with a matching name is opened:
require("awful.hotkeys_popup.keys")
-- Transparency
naughty.config.presets.normal.opacity = 0.5
naughty.config.presets.low.opacity = 0.5
naughty.config.presets.critical.opacity = 0.5
awful.util.spawn_with_shell("xcompmgr -F &")
-- {{{ 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.connect_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
-- }}}
-- {{{ Variable definitions
-- Themes define colours, icons, font and wallpapers.
beautiful.init("~/.config/awesome/themes/bio/theme.lua")
-- This is used later as the default terminal and editor to run.
terminal = "xterm"
editor = os.getenv("EDITOR") or "vi"
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.
local 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
}
-- }}}
-- {{{ Wallpaper
if beautiful.wallpaper then
gears.wallpaper.maximized(beautiful.wallpaper, 1, true)
end
if beautiful.wallpaper2 then
gears.wallpaper.maximized(beautiful.wallpaper2, 2, true)
end
-- }}}
-- {{{ Tags
-- Define a tag table which hold all screen tags.
tags = {
names = {"☿","♀","♁","♂","♃","♄","♅","♆"}
}
for s = 1, screen.count() do
-- Each screen has its own tag table.
tags[s] = awful.tag(tags.names, 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 },
{ "open terminal", terminal }
}
})
mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon,
menu = mymainmenu })
-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- }}}
-- {{{ Wibox
-- Create a textclock widget
mytextclock = awful.widget.textclock()
-- 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, function(t) awful.tag.viewnext(awful.tag.getscreen(t)) end),
awful.button({ }, 5, function(t) awful.tag.viewprev(awful.tag.getscreen(t)) end)
)
mytasklist = {}
mytasklist.buttons = awful.util.table.join(
awful.button({ }, 1, function (c)
if c == client.focus then
c.minimized = true
else
-- Without this, the following
-- :isvisible() makes no sense
c.minimized = false
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({
theme = { 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()
-- 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.filter.all, mytaglist.buttons)
-- Create a tasklist widget
mytasklist[s] = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, mytasklist.buttons)
-- Create the wibox
mywibox[s] = awful.wibox({ position = "top", screen = s })
-- Widgets that are aligned to the left
local left_layout = wibox.layout.fixed.horizontal()
left_layout:add(mylauncher)
left_layout:add(mytaglist[s])
left_layout:add(mypromptbox[s])
-- Widgets that are aligned to the right
local right_layout = wibox.layout.fixed.horizontal()
if s == 1 then right_layout:add(wibox.widget.systray()) end
right_layout:add(mytextclock)
right_layout:add(mylayoutbox[s])
-- Now bring it all together (with the tasklist in the middle)
local layout = wibox.layout.align.horizontal()
layout:set_left(left_layout)
layout:set_middle(mytasklist[s])
layout:set_right(right_layout)
mywibox[s]:set_widget(layout)
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, }, "s", hotkeys_popup.show_help,
{description="show help", group="awesome"}),
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() 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),
-- Transparency
awful.key({ modkey, "Shift" }, "p", function () awful.util.spawn("xcompmgr -fF -cC -t-4 -l-6 -r6") end),
awful.key({ modkey, "Shift" }, "o", function () awful.util.spawn("killall xcompmgr") end),
-- Screensaver
awful.key({ modkey, "Shift" }, "i", function () awful.util.spawn("xscreensaver-command -lock") end),
-- Keepass
awful.key({ modkey, "Shift" }, "k", function () awful.util.spawn("keepassx") end),
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.index]:run() end),
awful.key({ modkey }, "x",
function ()
awful.prompt.run({ prompt = "Run Lua code: " },
mypromptbox[mouse.screen.index].widget,
awful.util.eval, nil,
awful.util.getdir("cache") .. "/history_eval")
end),
-- Menubar
awful.key({ modkey }, "p", function() menubar.show() 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, }, "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 = not c.maximized
c:raise()
end ,
{description = "(un)maximize", group = "client"}),
awful.key({ modkey, "Control" }, "m",
function (c)
c.maximized_vertical = not c.maximized_vertical
c:raise()
end ,
{description = "(un)maximize vertically", group = "client"}),
awful.key({ modkey, "Shift" }, "m",
function (c)
c.maximized_horizontal = not c.maximized_horizontal
c:raise()
end ,
{description = "(un)maximize horizontally", group = "client"})
)
-- 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, 9 do
globalkeys = awful.util.table.join(globalkeys,
-- View tag only.
awful.key({ modkey }, "#" .. i + 9,
function ()
local screen = mouse.screen.index
local tag = awful.tag.gettags(screen)[i]
if tag then
awful.tag.viewonly(tag)
end
end),
-- Toggle tag.
awful.key({ modkey, "Control" }, "#" .. i + 9,
function ()
local screen = mouse.screen.index
local tag = awful.tag.gettags(screen)[i]
if tag then
awful.tag.viewtoggle(tag)
end
end),
-- Move client to tag.
awful.key({ modkey, "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = awful.tag.gettags(client.focus.screen)[i]
if tag then
awful.client.movetotag(tag)
end
end
end),
-- Toggle tag.
awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = awful.tag.gettags(client.focus.screen)[i]
if tag then
awful.client.toggletag(tag)
end
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
-- Rules to apply to new clients (through the "manage" signal).
awful.rules.rules = {
-- All clients will match this rule.
{ rule = { },
properties = { border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
screen = awful.screen.focused,
raise = true,
keys = clientkeys,
buttons = clientbuttons } },
{ rule = { class = "xterm" },
properties = { opacity = 0.8 } },
{ rule = { class = "XTerm" },
properties = { opacity = 0.8 } },
{ 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.connect_signal("manage", function (c, startup)
-- Enable sloppy focus
c:connect_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
local titlebars_enabled = false
if titlebars_enabled and (c.type == "normal" or c.type == "dialog") then
-- buttons for the titlebar
local buttons = awful.util.table.join(
awful.button({ }, 1, function()
client.focus = c
c:raise()
awful.mouse.client.move(c)
end),
awful.button({ }, 3, function()
client.focus = c
c:raise()
awful.mouse.client.resize(c)
end)
)
-- Widgets that are aligned to the left
local left_layout = wibox.layout.fixed.horizontal()
left_layout:add(awful.titlebar.widget.iconwidget(c))
left_layout:buttons(buttons)
-- Widgets that are aligned to the right
local right_layout = wibox.layout.fixed.horizontal()
right_layout:add(awful.titlebar.widget.floatingbutton(c))
right_layout:add(awful.titlebar.widget.maximizedbutton(c))
right_layout:add(awful.titlebar.widget.stickybutton(c))
right_layout:add(awful.titlebar.widget.ontopbutton(c))
right_layout:add(awful.titlebar.widget.closebutton(c))
-- The title goes in the middle
local middle_layout = wibox.layout.flex.horizontal()
local title = awful.titlebar.widget.titlewidget(c)
title:set_align("center")
middle_layout:add(title)
middle_layout:buttons(buttons)
-- Now bring it all together
local layout = wibox.layout.align.horizontal()
layout:set_left(left_layout)
layout:set_right(right_layout)
layout:set_middle(middle_layout)
awful.titlebar(c):set_widget(layout)
end
end)
client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- }}}
| gpl-2.0 |
feiying1460/witi-openwrt | package/ramips/ui/luci-mtk/src/libs/nixio/docsrc/nixio.File.lua | 173 | 4457 | --- Large File Object.
-- Large file operations are supported up to 52 bits if the Lua number type is
-- double (default).
-- @cstyle instance
module "nixio.File"
--- Write to the file descriptor.
-- @class function
-- @name File.write
-- @usage <strong>Warning:</strong> It is not guaranteed that all data
-- in the buffer is written at once especially when dealing with pipes.
-- You have to check the return value - the number of bytes actually written -
-- or use the safe IO functions in the high-level IO utility module.
-- @usage Unlike standard Lua indexing the lowest offset and default is 0.
-- @param buffer Buffer holding the data to be written.
-- @param offset Offset to start reading the buffer from. (optional)
-- @param length Length of chunk to read from the buffer. (optional)
-- @return number of bytes written
--- Read from a file descriptor.
-- @class function
-- @name File.read
-- @usage <strong>Warning:</strong> It is not guaranteed that all requested data
-- is read at once especially when dealing with pipes.
-- You have to check the return value - the length of the buffer actually read -
-- or use the safe IO functions in the high-level IO utility module.
-- @usage The length of the return buffer is limited by the (compile time)
-- nixio buffersize which is <em>nixio.const.buffersize</em> (8192 by default).
-- Any read request greater than that will be safely truncated to this value.
-- @param length Amount of data to read (in Bytes).
-- @return buffer containing data successfully read
--- Reposition read / write offset of the file descriptor.
-- The seek will be done either from the beginning of the file or relative
-- to the current position or relative to the end.
-- @class function
-- @name File.seek
-- @usage This function calls lseek().
-- @param offset File Offset
-- @param whence Starting point [<strong>"set"</strong>, "cur", "end"]
-- @return new (absolute) offset position
--- Return the current read / write offset of the file descriptor.
-- @class function
-- @name File.tell
-- @usage This function calls lseek() with offset 0 from the current position.
-- @return offset position
--- Synchronizes the file with the storage device.
-- Returns when the file is successfully written to the disk.
-- @class function
-- @name File.sync
-- @usage This function calls fsync() when data_only equals false
-- otherwise fdatasync(), on Windows _commit() is used instead.
-- @usage fdatasync() is only supported by Linux and Solaris. For other systems
-- the <em>data_only</em> parameter is ignored and fsync() is always called.
-- @param data_only Do not synchronize the metadata. (optional, boolean)
-- @return true
--- Apply or test a lock on the file.
-- @class function
-- @name File.lock
-- @usage This function calls lockf() on POSIX and _locking() on Windows.
-- @usage The "lock" command is blocking, "tlock" is non-blocking,
-- "ulock" unlocks and "test" only tests for the lock.
-- @usage The "test" command is not available on Windows.
-- @usage Locks are by default advisory on POSIX, but mandatory on Windows.
-- @param command Locking Command ["lock", "tlock", "ulock", "test"]
-- @param length Amount of Bytes to lock from current offset (optional)
-- @return true
--- Get file status and attributes.
-- @class function
-- @name File.stat
-- @param field Only return a specific field, not the whole table (optional)
-- @usage This function calls fstat().
-- @return Table containing: <ul>
-- <li>atime = Last access timestamp</li>
-- <li>blksize = Blocksize (POSIX only)</li>
-- <li>blocks = Blocks used (POSIX only)</li>
-- <li>ctime = Creation timestamp</li>
-- <li>dev = Device ID</li>
-- <li>gid = Group ID</li>
-- <li>ino = Inode</li>
-- <li>modedec = Mode converted into a decimal number</li>
-- <li>modestr = Mode as string as returned by `ls -l`</li>
-- <li>mtime = Last modification timestamp</li>
-- <li>nlink = Number of links</li>
-- <li>rdev = Device ID (if special file)</li>
-- <li>size = Size in bytes</li>
-- <li>type = ["reg", "dir", "chr", "blk", "fifo", "lnk", "sock"]</li>
-- <li>uid = User ID</li>
-- </ul>
--- Close the file descriptor.
-- @class function
-- @name File.close
-- @return true
--- Get the number of the filedescriptor.
-- @class function
-- @name File.fileno
-- @return file descriptor number
--- (POSIX) Set the blocking mode of the file descriptor.
-- @class function
-- @name File.setblocking
-- @param blocking (boolean)
-- @return true | gpl-2.0 |
n0xus/darkstar | scripts/globals/abilities/call_beast.lua | 18 | 1073 | -----------------------------------
-- Ability: Call Beast
-- Calls a beast to fight by your side.
-- Obtained: Beastmaster Level 23
-- Recast Time: 5:00
-- Duration: Dependent on jug pet used.
-----------------------------------
require("scripts/globals/common");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getPet() ~= nil) then
return MSGBASIC_ALREADY_HAS_A_PET,0;
elseif (not player:hasValidJugPetItem()) then
return MSGBASIC_NO_JUG_PET_ITEM,0;
elseif (not player:canUsePet()) then
return MSGBASIC_CANT_BE_USED_IN_AREA,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local id = player:getWeaponSubSkillType(SLOT_AMMO);
if (id == 0) then
printf("WARNING: jugpet id is ZERO\n");
end
player:spawnPet(id);
end;
| gpl-3.0 |
n0xus/darkstar | scripts/zones/Kazham/npcs/Ronta-Onta.lua | 19 | 4061 | -----------------------------------
-- Area: Kazham
-- NPC: Ronta-Onta
-- Starts and Finishes Quest: Trial by Fire
-- @pos 100 -15 -97 250
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TrialByFire = player:getQuestStatus(OUTLANDS,TRIAL_BY_FIRE);
WhisperOfFlames = player:hasKeyItem(WHISPER_OF_FLAMES);
realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day
if ((TrialByFire == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 6) or (TrialByFire == QUEST_COMPLETED and realday ~= player:getVar("TrialByFire_date"))) then
player:startEvent(0x010e,0,TUNING_FORK_OF_FIRE); -- Start and restart quest "Trial by Fire"
elseif (TrialByFire == QUEST_ACCEPTED and player:hasKeyItem(TUNING_FORK_OF_FIRE) == false and WhisperOfFlames == false) then
player:startEvent(0x011d,0,TUNING_FORK_OF_FIRE); -- Defeat against Ifrit : Need new Fork
elseif (TrialByFire == QUEST_ACCEPTED and WhisperOfFlames == false) then
player:startEvent(0x010f,0,TUNING_FORK_OF_FIRE,0);
elseif (TrialByFire == QUEST_ACCEPTED and WhisperOfFlames) then
numitem = 0;
if (player:hasItem(17665)) then numitem = numitem + 1; end -- Ifrits Blade
if (player:hasItem(13241)) then numitem = numitem + 2; end -- Fire Belt
if (player:hasItem(13560)) then numitem = numitem + 4; end -- Fire Ring
if (player:hasItem(1203)) then numitem = numitem + 8; end -- Egil's Torch
if (player:hasSpell(298)) then numitem = numitem + 32; end -- Ability to summon Ifrit
player:startEvent(0x0111,0,TUNING_FORK_OF_FIRE,0,0,numitem);
else
player:startEvent(0x0112); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x010e and option == 1) then
if (player:getQuestStatus(OUTLANDS,TRIAL_BY_FIRE) == QUEST_COMPLETED) then
player:delQuest(OUTLANDS,TRIAL_BY_FIRE);
end
player:addQuest(OUTLANDS,TRIAL_BY_FIRE);
player:setVar("TrialByFire_date", 0);
player:addKeyItem(TUNING_FORK_OF_FIRE);
player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_FIRE);
elseif (csid == 0x011d) then
player:addKeyItem(TUNING_FORK_OF_FIRE);
player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_FIRE);
elseif (csid == 0x0111) then
item = 0;
if (option == 1) then item = 17665; -- Ifrits Blade
elseif (option == 2) then item = 13241; -- Fire Belt
elseif (option == 3) then item = 13560; -- Fire Ring
elseif (option == 4) then item = 1203; -- Egil's Torch
end
if (player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item);
else
if (option == 5) then
player:addGil(GIL_RATE*10000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil
elseif (option == 6) then
player:addSpell(298); -- Ifrit Spell
player:messageSpecial(IFRIT_UNLOCKED,0,0,0);
else
player:addItem(item);
player:messageSpecial(ITEM_OBTAINED,item); -- Item
end
player:addTitle(HEIR_OF_THE_GREAT_FIRE);
player:delKeyItem(WHISPER_OF_FLAMES);
player:setVar("TrialByFire_date", os.date("%j")); -- %M for next minute, %j for next day
player:addFame(KAZHAM,WIN_FAME*30);
player:completeQuest(OUTLANDS,TRIAL_BY_FIRE);
end
end
end; | gpl-3.0 |
TheDialord/plugin-httpcheck | init.lua | 2 | 1508 |
cal framework = require('./modules/framework.lua')
local Plugin = framework.Plugin
local DataSourcePoller = framework.DataSourcePoller
local WebRequestDataSource = framework.WebRequestDataSource
local PollerCollection = framework.PollerCollection
local url = require('url')
local auth = framework.util.auth
local params = framework.params
params.name = 'Boundary Http Check Plugin'
params.version = '1.2'
params.tags = 'http'
local function createPollers(params)
local pollers = PollerCollection:new()
for _,item in pairs(params.items) do
local options = url.parse(item.url)
options.protocol = options.protocol or item.protocol or 'http'
options.auth = options.auth or auth(item.username, item.password)
options.method = item.method
options.meta = item.source
options.data = item.postdata
options.wait_for_end = false
local data_source = WebRequestDataSource:new(options)
local time_interval = tonumber((item.pollInterval or params.pollInterval)) * 1000
local poller = DataSourcePoller:new(time_interval, data_source)
pollers:add(poller)
end
return pollers
end
local pollers = createPollers(params)
local plugin = Plugin:new(params, pollers)
function plugin:onParseValues(_, extra)
local result = {}
local value = tonumber(extra.response_time)
if extra.status_code < 200 or extra.status_code >= 300 then
value = -1
end
result['HTTP_RESPONSETIME'] = {value = value, source = extra.info}
return result
end
plugin:run()
| apache-2.0 |
feiying1460/witi-openwrt | package/ramips/ui/luci-mtk/src/applications/luci-pbx/luasrc/model/cbi/pbx.lua | 146 | 4360 | --[[
Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com>
This file is part of luci-pbx.
luci-pbx is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>.
]]--
modulename = "pbx"
if nixio.fs.access("/etc/init.d/asterisk") then
server = "asterisk"
elseif nixio.fs.access("/etc/init.d/freeswitch") then
server = "freeswitch"
else
server = ""
end
-- Returns formatted output of string containing only the words at the indices
-- specified in the table "indices".
function format_indices(string, indices)
if indices == nil then
return "Error: No indices to format specified.\n"
end
-- Split input into separate lines.
lines = luci.util.split(luci.util.trim(string), "\n")
-- Split lines into separate words.
splitlines = {}
for lpos,line in ipairs(lines) do
splitlines[lpos] = luci.util.split(luci.util.trim(line), "%s+", nil, true)
end
-- For each split line, if the word at all indices specified
-- to be formatted are not null, add the formatted line to the
-- gathered output.
output = ""
for lpos,splitline in ipairs(splitlines) do
loutput = ""
for ipos,index in ipairs(indices) do
if splitline[index] ~= nil then
loutput = loutput .. string.format("%-40s", splitline[index])
else
loutput = nil
break
end
end
if loutput ~= nil then
output = output .. loutput .. "\n"
end
end
return output
end
m = Map (modulename, translate("PBX Main Page"),
translate("This configuration page allows you to configure a phone system (PBX) service which \
permits making phone calls through multiple Google and SIP (like Sipgate, \
SipSorcery, and Betamax) accounts and sharing them among many SIP devices. \
Note that Google accounts, SIP accounts, and local user accounts are configured in the \
\"Google Accounts\", \"SIP Accounts\", and \"User Accounts\" sub-sections. \
You must add at least one User Account to this PBX, and then configure a SIP device or \
softphone to use the account, in order to make and receive calls with your Google/SIP \
accounts. Configuring multiple users will allow you to make free calls between all users, \
and share the configured Google and SIP accounts. If you have more than one Google and SIP \
accounts set up, you should probably configure how calls to and from them are routed in \
the \"Call Routing\" page. If you're interested in using your own PBX from anywhere in the \
world, then visit the \"Remote Usage\" section in the \"Advanced Settings\" page."))
-----------------------------------------------------------------------------------------
s = m:section(NamedSection, "connection_status", "main",
translate("PBX Service Status"))
s.anonymous = true
s:option (DummyValue, "status", translate("Service Status"))
sts = s:option(DummyValue, "_sts")
sts.template = "cbi/tvalue"
sts.rows = 20
function sts.cfgvalue(self, section)
if server == "asterisk" then
regs = luci.sys.exec("asterisk -rx 'sip show registry' | sed 's/peer-//'")
jabs = luci.sys.exec("asterisk -rx 'jabber show connections' | grep onnected")
usrs = luci.sys.exec("asterisk -rx 'sip show users'")
chan = luci.sys.exec("asterisk -rx 'core show channels'")
return format_indices(regs, {1, 5}) ..
format_indices(jabs, {2, 4}) .. "\n" ..
format_indices(usrs, {1} ) .. "\n" .. chan
elseif server == "freeswitch" then
return "Freeswitch is not supported yet.\n"
else
return "Neither Asterisk nor FreeSwitch discovered, please install Asterisk, as Freeswitch is not supported yet.\n"
end
end
return m
| gpl-2.0 |
chengyi818/openwrt | customer/packages/luci/protocols/ppp/luasrc/model/cbi/admin_network/proto_pptp.lua | 59 | 3379 | --[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local server, username, password
local defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand, mtu
server = section:taboption("general", Value, "server", translate("VPN Server"))
server.datatype = "host"
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
function keepalive_failure.write() end
function keepalive_failure.remove() end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Crawlers_Nest/npcs/Treasure_Chest.lua | 17 | 3197 | -----------------------------------
-- Area: Crawler Nest
-- NPC: Treasure Chest
-- Involved In Quest: Enveloped in Darkness
-- @pos 41 0.1 -314 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/zones/Crawlers_Nest/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 43;
local TreasureMinLvL = 33;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1040,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1040,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
-- IMPORTANT ITEM: AF2 RDM QUEST -----------
if (player:getVar("needs_crawler_blood") == 1) then
questItemNeeded = 1;
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 1) then
player:addKeyItem(CRAWLER_BLOOD);
player:messageSpecial(KEYITEM_OBTAINED,CRAWLER_BLOOD); -- Crawler Blood (KI)
player:setVar("needs_crawler_blood",0);
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = chestLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1040);
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 |
n0xus/darkstar | scripts/zones/Cloister_of_Flames/Zone.lua | 32 | 1663 | -----------------------------------
--
-- Zone: Cloister_of_Flames (207)
--
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Cloister_of_Flames/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-698.729,-1.045,-646.659,184);
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 |
n0xus/darkstar | scripts/zones/La_Theine_Plateau/npcs/Shattered_Telepoint.lua | 19 | 2214 | -----------------------------------
-- Area: La_Theine Plateau
-- NPC: Shattered Telepoint
-- @pos 334 19 -60 102
-----------------------------------
package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/La_Theine_Plateau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x0ca,0,0,1); -- first time in promy -> have you made your preparations cs
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and (player:hasKeyItem(LIGHT_OF_MEA) or player:hasKeyItem(LIGHT_OF_DEM))) then
if (player:getVar("cspromy2") == 1) then
player:startEvent(0x0c9); -- cs you get nearing second promyvion
else
player:startEvent(0x0ca)
end
elseif (player:getCurrentMission(COP) > THE_MOTHERCRYSTALS or player:hasCompletedMission(COP,THE_LAST_VERSE) or (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") > 1)) then
player:startEvent(0x0ca); -- normal cs (third promyvion and each entrance after having that promyvion visited or mission completed)
else
player:messageSpecial(TELEPOINT_HAS_BEEN_SHATTERED);
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 == 0x00C9) then
player:setVar("cspromy2",0);
player:setVar("cs2ndpromy",1);
player:setPos(-266.76, -0.635, 280.058, 0, 14); -- To Hall of Transference {R}
elseif (csid == 0x00CA and option == 0) then
player:setPos(-266.76, -0.635, 280.058, 0, 14); -- To Hall of Transference {R}
end
end;
| gpl-3.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-Party-WoD/IronDocks/Nokgar.lua | 1 | 2853 | local mod = DBM:NewMod(1235, "DBM-Party-WoD", 4, 558)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 12458 $"):sub(12, -3))
mod:SetCreatureID(81297, 81305)
mod:SetEncounterID(1749)
mod:SetZone()
mod:SetBossHPInfoToHighest(false)
mod:RegisterCombat("combat")
mod:SetBossHealthInfo(81297)
mod:RegisterEventsInCombat(
"SPELL_AURA_APPLIED 164426 164835 164632",
"SPELL_AURA_REMOVED 164426",
"UNIT_SPELLCAST_SUCCEEDED boss1",
"UNIT_TARGETABLE_CHANGED",
"UNIT_DIED"
)
local warnNokgar = mod:NewSpellAnnounce("ej10433", 3, "Interface\\ICONS\\INV_Misc_Head_Orc_01.blp")
local warnBurningArrows = mod:NewSpellAnnounce(164635, 3)
local warnRecklessProvocation = mod:NewTargetAnnounce(164426, 3)
local warnEnrage = mod:NewSpellAnnounce(164835, 3, nil, "RemoveEnrage|Tank")
local specWarnBurningArrows = mod:NewSpecialWarningSpell(164635, nil, nil, nil, true)
local specWarnBurningArrowsMove = mod:NewSpecialWarningMove(164635)
local specWarnRecklessProvocation = mod:NewSpecialWarningReflect(164426)
local specWarnRecklessProvocationEnd = mod:NewSpecialWarningEnd(164426)
local specWarnEnrage = mod:NewSpecialWarningDispel(164835, "RemoveEnrage")
local timerRecklessProvocation = mod:NewBuffActiveTimer(5, 164426)
--local timerBurningArrowsCD = mod:NewNextTimer(25, 164635)--25~42 variable (patterned?)
local voiceRecklessProvocation = mod:NewVoice(164426)
local voiceEnrage = mod:NewVoice(164835, "RemoveEnrage")
local voiceBurningArrows = mod:NewVoice(164632)
function mod:SPELL_AURA_APPLIED(args)
if args.spellId == 164426 then
warnRecklessProvocation:Show(args.destName)
specWarnRecklessProvocation:Show(args.destName)
timerRecklessProvocation:Start()
voiceRecklessProvocation:Play("stopattack")
elseif args.spellId == 164835 and self:AntiSpam(2, 1) then
warnEnrage:Show()
specWarnEnrage:Show(args.destName)
voiceEnrage:Play("trannow") --multi sound
elseif args.spellId == 164632 and args:IsPlayer() and self:AntiSpam(2, 2) then
specWarnBurningArrowsMove:Show()
end
end
function mod:SPELL_AURA_REMOVED(args)
if args.spellId == 164426 then
specWarnRecklessProvocationEnd:Show()
voiceBurningArrows:Play("runaway")
end
end
--Not detectable in phase 1. Seems only cleanly detectable in phase 2, in phase 1 boss has no "boss" unitid so cast hidden.
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellId)
if spellId == 164635 then
warnBurningArrows:Show()
specWarnBurningArrows:Show()
--timerBurningArrowsCD:Start()
end
end
function mod:UNIT_TARGETABLE_CHANGED()
warnNokgar:Show()
if DBM.BossHealth:IsShown() then
DBM.BossHealth:AddBoss(81305)
end
end
function mod:UNIT_DIED(args)
if not DBM.BossHealth:IsShown() then return end
local cid = self:GetCIDFromGUID(args.destGUID)
if cid == 81297 then
DBM.BossHealth:RemoveBoss(81297)
end
end
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Bastok_Mines/npcs/Conrad.lua | 17 | 1874 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Conrad
-- Outpost Teleporter NPC
-- @pos 94.457 -0.375 -66.161 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Bastok_Mines/TextIDs");
guardnation = BASTOK;
csid = 0x0245;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (guardnation == player:getNation()) then
player:startEvent(csid,0,0,0,0,0,0,player:getMainLvl(),1073741823 - player:getNationTeleport(guardnation));
else
player:startEvent(csid,0,0,0,0,0,256,0,0);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
loca = option - 1073741829;
player:updateEvent(player:getGil(),OP_TeleFee(player,loca),player:getCP(),OP_TeleFee(player,loca),player:getCP());
end;
-----------------------------------
--onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (option >= 5 and option <= 23) then
if (player:delGil(OP_TeleFee(player,option-5))) then
toOutpost(player,option);
end
elseif (option >= 1029 and option <= 1047) then
local cpCost = OP_TeleFee(player,option-1029);
--printf("CP Cost: %u",cpCost);
if (player:getCP()>=cpCost) then
player:delCP(cpCost);
toOutpost(player,option-1024);
end
end
end; | gpl-3.0 |
n0xus/darkstar | scripts/globals/effects/fan_dance.lua | 18 | 1201 | -----------------------------------
--
-- EFFECT_FAN_DANCE
--
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
local fanDanceMerits = target:getMerit(MERIT_FAN_DANCE);
if (fanDanceMerits >5) then
target:addMod(MOD_WALTZ_RECAST, (fanDanceMerits-5));
end
target:delStatusEffect(EFFECT_HASTE_SAMBA);
target:delStatusEffect(EFFECT_ASPIR_SAMBA);
target:delStatusEffect(EFFECT_DRAIN_SAMBA);
target:delStatusEffect(EFFECT_SABER_DANCE);
target:addMod(MOD_ENMITY, 15);
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local fanDanceMerits = target:getMerit(MERIT_FAN_DANCE);
if (fanDanceMerits >5) then
target:delMod(MOD_WALTZ_RECAST, (fanDanceMerits-5));
end
target:delMod(MOD_ENMITY, 15);
end; | gpl-3.0 |
ppriest/mame | 3rdparty/genie/src/base/table.lua | 4 | 3340 | --
-- table.lua
-- Additions to Lua's built-in table functions.
-- Copyright (c) 2002-2008 Jason Perkins and the Premake project
--
--
-- Returns true if the table contains the specified value.
--
function table.contains(t, value)
for _, v in pairs(t) do
if v == value then return true end
end
return false
end
function table.icontains(t, value)
for _, v in ipairs(t) do
if v == value then return true end
end
return false
end
--
-- Enumerates an array of objects and returns a new table containing
-- only the value of one particular field.
--
function table.extract(arr, fname)
local result = { }
for _,v in ipairs(arr) do
table.insert(result, v[fname])
end
return result
end
--
-- Flattens a hierarchy of tables into a single array containing all
-- of the values.
--
function table.flatten(arr)
local result = { }
local function flatten(arr)
for _, v in ipairs(arr) do
if type(v) == "table" then
flatten(v)
else
table.insert(result, v)
end
end
end
flatten(arr)
return result
end
--
-- Merges an array of items into a string.
--
function table.implode(arr, before, after, between)
local result = ""
for _,v in ipairs(arr) do
if (result ~= "" and between) then
result = result .. between
end
result = result .. before .. v .. after
end
return result
end
--
-- Inserts a value of array of values into a table. If the value is
-- itself a table, its contents are enumerated and added instead. So
-- these inputs give these outputs:
--
-- "x" -> { "x" }
-- { "x", "y" } -> { "x", "y" }
-- { "x", { "y" }} -> { "x", "y" }
--
function table.insertflat(tbl, values)
if type(values) == "table" then
for _, value in ipairs(values) do
table.insertflat(tbl, value)
end
else
table.insert(tbl, values)
end
end
--
-- Returns true if the table is empty, and contains no indexed or keyed values.
--
function table.isempty(t)
return next(t) == nil
end
--
-- Adds the values from one array to the end of another and
-- returns the result.
--
function table.join(...)
local arg={...}
local result = { }
for _,t in ipairs(arg) do
if type(t) == "table" then
for _,v in ipairs(t) do
table.insert(result, v)
end
else
table.insert(result, t)
end
end
return result
end
--
-- Return a list of all keys used in a table.
--
function table.keys(tbl)
local keys = {}
for k, _ in pairs(tbl) do
table.insert(keys, k)
end
return keys
end
--
-- Adds the key-value associations from one table into another
-- and returns the resulting merged table.
--
function table.merge(...)
local arg={...}
local result = { }
for _,t in ipairs(arg) do
if type(t) == "table" then
for k,v in pairs(t) do
result[k] = v
end
else
error("invalid value")
end
end
return result
end
--
-- Translates the values contained in array, using the specified
-- translation table, and returns the results in a new array.
--
function table.translate(arr, translation)
local result = { }
for _, value in ipairs(arr) do
local tvalue
if type(translation) == "function" then
tvalue = translation(value)
else
tvalue = translation[value]
end
if (tvalue) then
table.insert(result, tvalue)
end
end
return result
end
| gpl-2.0 |
n0xus/darkstar | scripts/globals/items/apple_pie_+1.lua | 35 | 1305 | -----------------------------------------
-- ID: 4320
-- Item: Apple Pie +1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Magic 30
-- Intelligence 4
-- Magic Regen While Healing 2
-----------------------------------------
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,3600,4320);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 30);
target:addMod(MOD_INT, 4);
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 30);
target:delMod(MOD_INT, 4);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
n0xus/darkstar | scripts/zones/Nashmau/npcs/Neneroon.lua | 38 | 1033 | ----------------------------------
-- Area: Nashmau
-- NPC: Neneroon
-- Type: Item Deliverer
-- @pos -0.866 -5.999 36.942 53
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, NENE_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 |
LuaDist2/lua-cassandra | spec/01-unit/02-buffer_spec.lua | 2 | 2293 | local Buffer = require("cassandra.cql").buffer
describe("Buffer", function()
-- protocol types (different than CQL types)
local fixtures = {
byte = {1, 2, 3},
int = {0, 4200, -42},
short = {0, 1, -1, 12, 13},
string = {"hello world"},
long_string = {string.rep("blob", 1000), ""},
uuid = {"1144bada-852c-11e3-89fb-e0b9a54a6d11"},
inet = {
"127.0.0.1", "0.0.0.1", "8.8.8.8",
"2001:0db8:85a3:0042:1000:8a2e:0370:7334",
"2001:0db8:0000:0000:0000:0000:0000:0001"
},
string_map = {
{hello = "world"},
{cql_version = "3.0.0", foo = "bar"}
},
}
for fixture_type, fixture_values in pairs(fixtures) do
it("["..fixture_type.."] buffering", function()
for _, fixture in ipairs(fixture_values) do
local writer = Buffer.new(3)
writer["write_"..fixture_type](writer, fixture)
local bytes = writer:get()
local reader = Buffer.new(3, bytes) -- protocol v3
local decoded = reader["read_"..fixture_type](reader)
if type(fixture) == "table" then
assert.same(fixture, decoded)
else
assert.equal(fixture, decoded)
end
end
end)
end
it("accumulates values", function()
local buf = Buffer.new(3) -- protocol v3
buf:write_byte(2)
buf:write_int(128)
buf:write_string("hello world")
buf.pos = 1 -- reset
assert.equal(2, buf:read_byte())
assert.equal(128, buf:read_int())
assert.equal("hello world", buf:read_string())
end)
describe("inet", function()
local fixtures = {
["2001:0db8:85a3:0042:1000:8a2e:0370:7334"] = "2001:0db8:85a3:0042:1000:8a2e:0370:7334",
["2001:0db8:0000:0000:0000:0000:0000:0001"] = "2001:db8::1",
["2001:0db8:85a3:0000:0000:0000:0000:0010"] = "2001:db8:85a3::10",
["2001:0db8:85a3:0000:0000:0000:0000:0100"] = "2001:db8:85a3::100",
["0000:0000:0000:0000:0000:0000:0000:0001"] = "::1",
["0000:0000:0000:0000:0000:0000:0000:0000"] = "::"
}
it("shortens ipv6 addresses", function()
for expected_ip, fixture_ip in pairs(fixtures) do
local buffer = Buffer.new(3)
buffer:write_inet(fixture_ip)
buffer.pos = 1
assert.equal(expected_ip, buffer:read_inet())
end
end)
end)
end)
| mit |
crscardellino/torch-ml-tools | SparseDataset.lua | 1 | 3946 | --[[
Copyright (c) 2016, Cristian Cardellino.
This work is licensed under the "New BSD License".
See LICENSE for more information.
]]--
local SparseDataset = torch.class('mltools.SparseDataset')
function SparseDataset:__init(fname_or_indices, zero_based_or_values, target, shape)
if type(fname_or_indices) == 'string' then
if zero_based_or_values == nil then zero_based_or_values = false end
if type(zero_based_or_values) ~= 'boolean' then error('Wrong second argument. Should be of type boolean.') end
-- If the indices starts with 0 or 1 (default)
self:readFromFile(fname_or_indices, zero_based_or_values)
elseif type(fname_or_indices) == 'table' then
if type(zero_based_or_values) ~= 'table' or not target or type(shape) ~= 'table' then
error('Wrong argument type')
end
self.indices = fname_or_indices -- Table of Tensors
self.values = zero_based_or_values -- Table of Tensors
self.target = target:type('torch.IntTensor') -- One dimensional Tensor
self.shape = shape -- Tuple with 2 values: rows and cols
end
end
function SparseDataset:getDenseDataset()
local dataset = torch.FloatTensor(self.shape.rows, self.shape.cols):zero()
for i = 1, #self.indices do
dataset[{i, {}}]:indexAdd(1,
self.indices[i]:type('torch.LongTensor'),
self.values[i]:type('torch.FloatTensor')
)
end
return dataset
end
function SparseDataset:readFromFile(fname, zero_based)
if zero_based == nil then zero_based = false end
print('Reading ' .. fname)
local function readline(line)
local label = tonumber(string.match(line, '^([%+%-]?%s?%d+)'))
if not label then
error('could not read label')
end
local vals = {}
local inds = {}
local indcntr = 0
for ind, val in string.gmatch(line, '(%d+):([%+%-]?%d?%.?%d+)') do
indcntr = indcntr + 1
ind = tonumber(ind)
val = tonumber(val)
if not ind or not val then
error('reading failed')
end
if zero_based then ind = ind + 1 end -- We transform the zero based in one-based
if ind < indcntr then
error('indices are not in increasing order')
end
inds[#inds+1] = ind
vals[#vals+1] = val
end
return torch.LongTensor(inds), torch.FloatTensor(vals), label
end
local indices = {}
local values = {}
local target = {}
local shape = {rows = 0, cols = 0}
local labels = {}
setmetatable(labels, { __index = function() return 0 end })
for line in io.lines(fname) do
local inds, vals, tgt = readline(line)
indices[#indices+1] = inds
values[#values+1] = vals
target[#target+1] = tgt
shape.rows = shape.rows + 1
shape.cols = math.max(shape.cols, inds[-1])
labels[tgt] = labels[tgt] + 1
end
for l, c in pairs(labels) do
io.write(string.format("# of samples of label %d = %d\n", l, c))
end
io.write(string.format("# of total samples = %d\n", shape.rows))
io.write(string.format("# of features = %d\n", shape.cols))
self.indices = indices
self.values = values
self.target = torch.IntTensor(target)
self.shape = shape
end
function SparseDataset:writeToFile(fname)
print('Writing ' .. fname)
local function vectostr(i, x)
local str = {}
local cntr = 1
x:apply(function(v)
table.insert(str, string.format('%d:%g', i[cntr], v))
cntr = cntr + 1
return v
end)
return table.concat(str, ' ')
end
local of = torch.DiskFile(fname, 'w')
for i = 1, #self.indices do
of:writeString(string.format('%g %s\n', self.target[i], vectostr(self.indices[i], self.values[i])))
end
of:close()
end | bsd-3-clause |
gpedro/server | data/scripts/otstd/actions/make_bread.lua | 3 | 2544 | otstd.make_bread = {}
otstd.ovens = {
[1786] = {},
[1788] = {},
[1790] = {},
[1792] = {},
[6356] = {},
[6358] = {},
[6360] = {},
[6362] = {}
}
function otstd.make_bread.use_wheat_on_mill_callback(event)
local player = event.player
local item = event.item
local toPos = event.targetPosition
local tile = toPos and map:getTile(toPos)
if not tile then
return
end
local mill = tile:getTopThing()
if(mill and mill:getItemID() == 1381) then
item:destroy()
local flour = createItem(2692)
player:addItem(flour)
event.retcode = RETURNVALUE_NOERROR
event:skip()
end
end
function otstd.make_bread.use_flour_on_water_callback(event)
local player = event.player
local item = event.item
local toPos = event.targetPosition
local tile = toPos and map:getTile(toPos)
if not tile then
return
end
local toItem = event.targetInventoryItem or tile:getTopThing()
if(toItem) then
local toItemType = Items[toItem:getItemID()]
if(toItemType.isFluidContainer and toItem:getSubtype() == FLUID_WATER:value()) then
local dough = createItem(2693)
player:addItem(dough)
toItem:setSubtype(FLUID_NONE)
item:destroy()
event.retcode = RETURNVALUE_NOERROR
event:skip()
end
end
end
function otstd.make_bread.use_dough_on_oven_callback(event)
local player = event.player
local item = event.item
local toPos = event.targetPosition
local tile = toPos and map:getTile(toPos)
if not tile then
return
end
local oven = tile:getTopThing()
if(oven and otstd.ovens[oven:getItemID()] ~= nil) then
local bread = createItem(2689)
player:addItem(bread)
item:destroy()
event.retcode = RETURNVALUE_NOERROR
event:skip()
end
end
function otstd.make_bread.registerHandlers()
--use wheat on a mill
if(otstd.make_bread.wheat_listener ~= nil) then
stopListener(otstd.make_bread.wheat_listener)
end
otstd.make_bread.wheat_listener =
registerOnUseItemNearby("itemid", 2694, otstd.make_bread.use_wheat_on_mill_callback)
--use flour on a fluid container with water
if(otstd.make_bread.flour_listener ~= nil) then
stopListener(otstd.make_bread.flour_listener)
end
otstd.make_bread.flour_listener =
registerOnUseItemNearby("itemid", 2692, otstd.make_bread.use_flour_on_water_callback)
--use dough on an oven
if(otstd.make_bread.dough_listener ~= nil) then
stopListener(otstd.make_bread.dough_listener)
end
otstd.make_bread.dough_listener =
registerOnUseItemNearby("itemid", 2693, otstd.make_bread.use_dough_on_oven_callback)
end
otstd.make_bread.registerHandlers()
| gpl-2.0 |
Python1320/wire | lua/wire/client/hlzasm/hc_syntax.lua | 8 | 48757 | --------------------------------------------------------------------------------
-- ZASM2 compatible syntax
--------------------------------------------------------------------------------
-- Syntax lookup for vector definitions
local VectorSyntax = {
FLOAT = { {} },
SCALAR = { {} },
VECTOR1F = { {"x"} },
VECTOR2F = { {"x"},{"y"} },
VECTOR3F = { {"x"},{"y"},{"z"} },
VECTOR4F = { {"x"},{"y"},{"z"},{"w"} },
VEC1F = { {"x"} },
VEC2F = { {"x"},{"y"} },
VEC3F = { {"x"},{"y"},{"z"} },
VEC4F = { {"x"},{"y"},{"z"},{"w"} },
UV = { {"x","u"},{"y","v"} },
COLOR = { {"x","r"},{"y","g"},{"z","b"},{"w","a"} },
MATRIX = {},
}
for i=0,15 do VectorSyntax.MATRIX[i+1] = {tostring(i)} end
--------------------------------------------------------------------------------
-- Compile an opcode (called after if self:MatchToken(TOKEN.OPCODE))
function HCOMP:Opcode() local TOKEN = self.TOKEN
local opcodeName = self.TokenData
local opcodeNo = self.OpcodeNumber[self.TokenData]
local operandCount = self.OperandCount[opcodeNo]
-- Check if opcode is obsolete or old
if self.OpcodeObsolete[opcodeName] then
self:Warning("Instruction \""..opcodeName.."\" is obsolete")
end
if self.OpcodeOld[opcodeName] then
self:Warning("Mnemonic \""..opcodeName.."\" is an old mnemonic for this instruction. Please use the newer mnemonic \""..self.OpcodeOld[opcodeName].."\".")
end
-- Create leaf
local opcodeLeaf = self:NewLeaf()
opcodeLeaf.Opcode = opcodeName
opcodeLeaf.ExplictAssign = true
-- Parse operands
for i=1,operandCount do
local segmentOffset,constantValue,expressionLeaf
local isMemoryReference,useSpecialMemorySyntax
-- Check if it's a special memory reference ([<...>])
if self:MatchToken(TOKEN.LSUBSCR) then
isMemoryReference = true
useSpecialMemorySyntax = true
end
-- Check for segment prefix (ES:<...> or ES+<...>)
if ((self:PeekToken() == TOKEN.SEGMENT) or (self:PeekToken() == TOKEN.REGISTER)) and
((self:PeekToken(1) == TOKEN.DCOLON) or
(useSpecialMemorySyntax and (self:PeekToken(1) == TOKEN.PLUS))) then -- next character is : or +
if self:MatchToken(TOKEN.SEGMENT) then
-- 1 to 8: CS .. LS
segmentOffset = self.TokenData
elseif self:MatchToken(TOKEN.REGISTER) then
if self.TokenData >= 96 then -- 17+: extended registers
segmentOffset = 17 + self.TokenData - 96
else -- 9 to 16: EAX .. EBP
segmentOffset = self.TokenData + 8
end
end
if useSpecialMemorySyntax then
if not self:MatchToken(TOKEN.DCOLON) then self:ExpectToken(TOKEN.PLUS) end
else
self:ExpectToken(TOKEN.DCOLON)
end
end
-- Check if it's a memory reference (#<...>)
if not useSpecialMemorySyntax then
if self:MatchToken(TOKEN.HASH) then isMemoryReference = true end
end
-- Parse operand expression (use previous result if previous const wasnt related to seg offset)
local c,v,e = self:ConstantExpression()
if c then -- Constant value
if v
then constantValue = v -- Exact value
else constantValue = e -- Expression to be recalculated later
end
else -- Expression
expressionLeaf = self:Expression()
if expressionLeaf.Opcode then
self:Warning("Using complex expression as operand: might corrupt user register")
end
-- FIXME: warning about using extra registers?
end
-- Check for segment prefix again (reversed syntax <...>:ES)
if self:MatchToken(TOKEN.DCOLON) then
if (not segmentOffset) and
((self:PeekToken() == TOKEN.SEGMENT) or (self:PeekToken() == TOKEN.REGISTER)) then
if self:MatchToken(TOKEN.SEGMENT) then
-- 1 to 8: CS .. LS
segmentOffset = self.TokenData
elseif self:MatchToken(TOKEN.REGISTER) then
if self.TokenData >= 96 then -- 17+: extended registers
segmentOffset = 17 + self.TokenData - 96
else -- 9 to 16: EAX .. EBP
segmentOffset = self.TokenData + 8
end
end
else
self:Error("Invalid segment offset syntax")
end
end
-- Trailing bracket for [...] memory syntax
if useSpecialMemorySyntax then
self:ExpectToken(TOKEN.RSUBSCR)
end
-- Create operand
if isMemoryReference then
if expressionLeaf then
if expressionLeaf.Register then
opcodeLeaf.Operands[i] = { MemoryRegister = expressionLeaf.Register, Segment = segmentOffset }
else
opcodeLeaf.Operands[i] = { MemoryPointer = expressionLeaf, Segment = segmentOffset }
end
else
opcodeLeaf.Operands[i] = { MemoryPointer = constantValue, Segment = segmentOffset }
end
else
if expressionLeaf then
if expressionLeaf.Register then
if (expressionLeaf.Register >= 16) and (expressionLeaf.Register <= 23) and (segmentOffset) then
-- Swap EBX:ES with ES:EBX (because the former one is invalid in ZCPU)
local register = expressionLeaf.Register
local segment = segmentOffset
-- Convert segment register index to register index
if (segment >= 1) and (segment <= 8) then expressionLeaf.Register = segment + 15 end
if (segment >= 9) and (segment <= 16) then expressionLeaf.Register = segment - 8 end
-- Convert register index to segment register index
if (register >= 1) and (register <= 8) then segmentOffset = register + 8 end
if (register >= 16) and (register <= 23) then segmentOffset = register - 15 end
end
opcodeLeaf.Operands[i] = { Register = expressionLeaf.Register, Segment = segmentOffset }
else
if segmentOffset then
opcodeLeaf.Operands[i] = self:NewLeaf()
opcodeLeaf.Operands[i].Opcode = "add"
opcodeLeaf.Operands[i].Operands[1] = { Register = segmentOffset+15 }
opcodeLeaf.Operands[i].Operands[2] = expressionLeaf
else
opcodeLeaf.Operands[i] = expressionLeaf
end
end
else
opcodeLeaf.Operands[i] = { Constant = constantValue, Segment = segmentOffset }
end
end
-- Attach information from expression
if expressionLeaf then
opcodeLeaf.Operands[i].PreviousLeaf = expressionLeaf.PreviousLeaf
end
-- Syntax
if i < operandCount then
self:ExpectToken(TOKEN.COMMA)
else
if self:MatchToken(TOKEN.COMMA) then
self:Error("Invalid operand count")
end
end
end
-- Check if first operand is a non-preserved register
if self.BusyRegisters then
if opcodeLeaf.Operands[1] and opcodeLeaf.Operands[1].Register and
(self.BusyRegisters[opcodeLeaf.Operands[1].Register] == false) and
(self.BlockDepth > 0) then
self:Warning("Warning: using an unpreserved register")
end
if opcodeLeaf.Operands[1] and opcodeLeaf.Operands[1].MemoryRegister and
(self.BusyRegisters[opcodeLeaf.Operands[1].MemoryRegister] == false) and
(self.BlockDepth > 0) then
self:Warning("Warning: using an unpreserved register")
end
end
-- Add opcode to tail
self:AddLeafToTail(opcodeLeaf)
self:MatchToken(TOKEN.COLON)
return true
end
--------------------------------------------------------------------------------
-- Start a new block
function HCOMP:BlockStart(blockType)
if self.BlockDepth == 0 then
-- Create leaf that corresponds to ENTER instruction
self.HeadLeaf = self:NewLeaf()
self.HeadLeaf.Opcode = "enter"
self.HeadLeaf.Operands[1] = { Constant = self.Settings.MagicValue }
self:AddLeafToTail(self.HeadLeaf)
self.LocalLabels = {}
self.StackPointer = 0
if self.GenerateInlineFunction then
self.ParameterPointer = 0 -- Skip EBP
else
self.ParameterPointer = 1 -- Skip EBP and return address
end
self.StringsTable = {}
self.BlockType = {}
self.SpecialLeaf = {}
-- Create busy registers list
self.BusyRegisters = { false,false,false,false,false,false,true,true }
end
-- Create a leaf that corresponds to label for BREAK
local breakLeaf = self:NewLeaf()
breakLeaf.Opcode = "LABEL"
breakLeaf.Label = self:GetTempLabel()
breakLeaf.Label.Type = "Pointer"
breakLeaf.Label.Leaf = breakLeaf
-- Create a leaf that corresponds to label for CONTINUE
local continueLeaf = self:NewLeaf()
continueLeaf.Opcode = "LABEL"
continueLeaf.Label = self:GetTempLabel()
continueLeaf.Label.Type = "Pointer"
continueLeaf.Label.Leaf = continueLeaf
self:AddLeafToTail(continueLeaf)
-- Only FOR loops have step code
if (blockType == "WHILE") or
(blockType == "DO") then
self.CurrentStepLeaf = nil
end
self.SpecialLeaf[#self.SpecialLeaf+1] = {
Break = breakLeaf,
Continue = continueLeaf,
JumpBack = self:NewLeaf(),
Step = self.CurrentStepLeaf,
}
if (blockType == "FOR") or
(blockType == "WHILE") or
(blockType == "DO") then
self.CurrentContinueLeaf = self.SpecialLeaf[#self.SpecialLeaf].Continue
self.CurrentBreakLeaf = self.SpecialLeaf[#self.SpecialLeaf].Break
end
-- Push block type
table.insert(self.BlockType,blockType or "FUNCTION")
self.BlockDepth = self.BlockDepth + 1
end
--------------------------------------------------------------------------------
-- End the block
function HCOMP:BlockEnd()
-- If required, end the previous block
local endPreviousBlock = self.SpecialLeaf[#self.SpecialLeaf].EndPreviousBlock
-- If required, add leaf that jumps back to block start
if self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Opcode ~= "INVALID" then
self.SpecialLeaf[#self.SpecialLeaf].JumpBack.CurrentPosition = self:CurrentSourcePosition()
self:AddLeafToTail(self.SpecialLeaf[#self.SpecialLeaf].JumpBack)
end
-- Add leaf that corresponds to break label
self.SpecialLeaf[#self.SpecialLeaf].Break.CurrentPosition = self:CurrentSourcePosition()
self:AddLeafToTail(self.SpecialLeaf[#self.SpecialLeaf].Break)
-- Pop current continue leaf if required
if self.CurrentContinueLeaf == self.SpecialLeaf[#self.SpecialLeaf].Continue then
if self.SpecialLeaf[#self.SpecialLeaf-1] then
self.CurrentContinueLeaf = self.SpecialLeaf[#self.SpecialLeaf-1].Continue
self.CurrentBreakLeaf = self.SpecialLeaf[#self.SpecialLeaf-1].Break
self.CurrentStepLeaf = self.SpecialLeaf[#self.SpecialLeaf-1].Step
else
self.CurrentContinueLeaf = nil
self.CurrentBreakLeaf = nil
self.CurrentStepLeaf = nil
end
end
-- Pop unused leaves
self.SpecialLeaf[#self.SpecialLeaf] = nil
-- Pop block type
local blockType = self.BlockType[#self.BlockType]
self.BlockType[#self.BlockType] = nil
self.BlockDepth = self.BlockDepth - 1
if self.BlockDepth == 0 then
-- Update head leaf with new stack data
self.HeadLeaf.Operands[1].Constant = -self.StackPointer
if (self.StackPointer == 0) and
(self.ParameterPointer == 0) and
(not self.Settings.AlwaysEnterLeave) then self.HeadLeaf.Opcode = "DATA" end
-- Create leaf for exiting local scope
local leaveLeaf = self:NewLeaf()
leaveLeaf.Opcode = "leave"
if (self.StackPointer ~= 0) or
(self.ParameterPointer ~= 0) or
(self.Settings.AlwaysEnterLeave) then
self:AddLeafToTail(leaveLeaf)
end
-- Create leaf for returning from call
if blockType == "FUNCTION" then
if not self.GenerateInlineFunction then
local retLeaf = self:NewLeaf()
retLeaf.Opcode = "ret"
self:AddLeafToTail(retLeaf)
end
end
-- Write down strings table
for string,leaf in pairs(self.StringsTable) do
self:AddLeafToTail(leaf)
end
self.StringsTable = nil
-- Add local labels to lookup list
for labelName,labelData in pairs(self.LocalLabels) do
self.DebugInfo.Labels["local."..labelName] = { StackOffset = labelData.StackOffset }
end
self.LocalLabels = nil
self.StackPointer = nil
self.ParameterPointer = nil
self.BlockType = nil
self.SpecialLeaf = nil
-- Zap all registers preserved inside the function
self.BusyRegisters = nil
-- Disable inlining
if self.GenerateInlineFunction then
self.Functions[self.GenerateInlineFunction].InlineCode = self.InlineFunctionCode
self.GenerateInlineFunction = nil
self.InlineFunctionCode = nil
end
-- Disable parent label
self.CurrentParentLabel = nil
end
-- End it, see first line of the function
if endPreviousBlock then
self:BlockEnd()
end
end
--------------------------------------------------------------------------------
-- Parse ELSE clause
function HCOMP:ParseElse(parentBlockExists)
-- Add a jump over the else clause
local jumpLeaf = self:NewLeaf()
jumpLeaf.Opcode = "jmp"
self:AddLeafToTail(jumpLeaf)
-- Alter the conditional jump so it goes to else clause
local jumpOverLabelLeaf = self:NewLeaf()
local jumpOverLabel = self:GetTempLabel()
jumpOverLabelLeaf.Opcode = "LABEL"
jumpOverLabel.Type = "Pointer"
jumpOverLabel.Leaf = jumpOverLabelLeaf
jumpOverLabelLeaf.Label = jumpOverLabel
self:AddLeafToTail(jumpOverLabelLeaf)
if parentBlockExists and self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak then
self:AddLeafToTail(self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak)
end
-- Enter the ELSE block
local needBlock = self:MatchToken(self.TOKEN.LBRACKET)
self:BlockStart("ELSE")
-- Update properly the jump leaf
jumpLeaf.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Break.Label }
if needBlock then
-- Special marker that means that ending this block ends previous one too
self.SpecialLeaf[#self.SpecialLeaf].EndPreviousBlock = parentBlockExists
else
-- Parse next statement if dont need a block
local previousBlockDepth = #self.BlockType
self:Statement()
-- If did not enter any new blocks, it was a plain statement. Pop ELSE block
if #self.BlockType == previousBlockDepth then
-- End the ELSE block
self:BlockEnd()
-- End the IF block, if required
if parentBlockExists then self:BlockEnd() end
else
-- Special marker that means that ending this block ends ELSE block early too
self.SpecialLeaf[#self.SpecialLeaf].EndPreviousBlock = true
-- Special marker that means that ending ELSE block ends previous one too
self.SpecialLeaf[#self.SpecialLeaf-1].EndPreviousBlock = parentBlockExists
end
end
end
--------------------------------------------------------------------------------
function HCOMP:DeclareRegisterVariable()
if self.BlockDepth > 0 then
for reg=1,6 do
if not self.BusyRegisters[reg] then
self.BusyRegisters[reg] = true
return reg
end
end
self:Error("Out of free registers for declaring local variables")
else
self:Error("Unable to declare a register variable")
end
end
--------------------------------------------------------------------------------
-- Compile a variable/function. Returns corresponding labels
function HCOMP:DefineVariable(isFunctionParam,isForwardDecl,isRegisterDecl,isStructMember) local TOKEN = self.TOKEN
local varType,varSize,isStruct
if self:MatchToken(TOKEN.IDENT) then -- Define structure
local structData = self.Structs[structName]
varType = self.TokenData
varSize = 0 -- Depends on pointer level
isStruct = true
else -- Define variable
self:ExpectToken(TOKEN.TYPE)
varType = self.TokenData
varSize = 1
if varType == 5 then varSize = 4 end
end
-- Variable labels list
local labelsList = {}
-- Parse all variables to define
while true do
-- Get pointer level (0, *, **, ***, etc)
local pointerLevel = 0
while self:MatchToken(TOKEN.TIMES) do pointerLevel = pointerLevel + 1 end
-- Fix structure size
if isStruct then
if pointerLevel > 0
then varSize = 1
else varSize = self.StructSize[varType]
end
end
-- Get variable name
self:ExpectToken(TOKEN.IDENT)
local varName = self.TokenData
-- Try to read information about array size, stuff
local arraySize
while self:MatchToken(TOKEN.LSUBSCR) do -- varname[<arr size>]
if self:MatchToken(TOKEN.RSUBSCR) then -- varname[]
if isFunctionParam then -- just a pointer to an array
pointerLevel = 1
end
else
local c,v = self:ConstantExpression(true) -- need precise value here, no ptrs allowed
if c then
if not arraySize then arraySize = {} end
arraySize[#arraySize+1] = v
else
self:Error("Array size must be constant")
end
self:ExpectToken(TOKEN.RSUBSCR)
end
end
-- Calculate size of array
local bytesArraySize
if arraySize then
for k,v in pairs(arraySize) do
bytesArraySize = (bytesArraySize or 0) + v*varSize
end
end
-- Add to global list
table.insert(labelsList,{ Name = varName, Type = varType, PtrLevel = pointerLevel, Size = bytesArraySize or varSize })
if not isStructMember then -- Do not define struct members
if self:MatchToken(TOKEN.LPAREN) then -- Define function
-- Create function entrypoint
local label
label = self:DefineLabel(varName)
label.Type = "Pointer"
label.Defined = true
-- Make all further leaves parented to this label
self.CurrentParentLabel = label
-- Create label leaf
label.Leaf = self:NewLeaf()
label.Leaf.Opcode = "LABEL"
label.Leaf.Label = label
self:AddLeafToTail(label.Leaf) --isInlined
-- Define a function
local _,functionVariables = nil,{}
self:BlockStart()
if not self:MatchToken(TOKEN.RPAREN) then
_,functionVariables = self:DefineVariable(true)
self:ExpectToken(TOKEN.RPAREN)
-- Add comments about function into assembly listing
if self.Settings.GenerateComments then
for i=1,#functionVariables do
label.Leaf.Comment = (label.Leaf.Comment or "")..(functionVariables[i].Name)
if i < #functionVariables then label.Leaf.Comment = label.Leaf.Comment.."," end
end
end
end
-- Forward declaration, mess up label name
if isForwardDecl then
local newName = label.Name.."@"
for i=1,#functionVariables do
newName = newName..functionVariables[i].Name..functionVariables[i].Type
if i < #functionVariables then
newName = newName.."_"
end
end
self:RedefineLabel(label.Name,newName)
end
-- Generate comment if required
if self.Settings.GenerateComments then label.Leaf.Comment = varName.."("..(label.Leaf.Comment or "")..")" end
self:ExpectToken(TOKEN.LBRACKET)
return true,functionVariables,varName,varType,pointerLevel
else -- Define variable
-- Check if there's an initializer
local initializerLeaves,initializerValues
if self:MatchToken(TOKEN.EQUAL) then
if not self.LocalLabels then -- Check rules for global init
if self:MatchToken(TOKEN.LBRACKET) then -- Array initializer
if not bytesArraySize then self:Error("Cannot initialize value: not an array") end
initializerValues = {}
while not self:MatchToken(TOKEN.RBRACKET) do
local c,v = self:ConstantExpression(true)
if not c
then self:Error("Cannot have expressions in global initializers")
else table.insert(initializerValues,v)
end
self:MatchToken(TOKEN.COMMA)
end
else -- Single initializer
if bytesArraySize then self:Error("Cannot initialize value: is an array") end
local c,v = self:ConstantExpression(true)
if not c then
-- initializerLeaves = { self:Expression() }
self:Error("Cannot have expressions in global initializers")
else
initializerValues = { v }
end
end
else -- Local init always an expression
if self:MatchToken(TOKEN.LBRACKET) then -- Array initializer
if not bytesArraySize then self:Error("Cannot initialize value: not an array") end
initializerLeaves = {}
while not self:MatchToken(TOKEN.RBRACKET) do
table.insert(initializerLeaves,self:Expression())
self:MatchToken(TOKEN.COMMA)
end
if #initializerLeaves > 256 then
self:Error("Too much local variable initializers")
end
else
if bytesArraySize then self:Error("Cannot initialize value: is an array") end
initializerLeaves = { self:Expression() }
end
end
end
-- Define a variable
if self.LocalLabels then -- check if var is local
local label = self:DefineLabel(varName,true)
if isRegisterDecl then
label.Type = "Register"
label.Value = self:DeclareRegisterVariable()
if isStruct then self:Error("Cannot hold structure variables in registers - yet") end
else
label.Type = "Stack"
if isStruct and (pointerLevel > 0) then label.PointerToStruct = true end
end
label.Defined = true
if varType == 5 then label.ForceType = "vector" end
if isStruct then label.Struct = varType end
-- If label has associated array size, mark it as an array
if bytesArraySize then label.Array = bytesArraySize end
if not isRegisterDecl then
if not isFunctionParam then
-- Add a new local variable (stack pointer increments)
self.StackPointer = self.StackPointer - (bytesArraySize or varSize)
label.StackOffset = self.StackPointer
else
-- Add a new function variable
self.ParameterPointer = self.ParameterPointer + (bytesArraySize or varSize)
label.StackOffset = self.ParameterPointer
end
end
-- Initialize local variable
if isRegisterDecl then
if initializerLeaves then
local movLeaf = self:NewLeaf()
movLeaf.Opcode = "mov"
movLeaf.Operands[1] = { Register = label.Value }
movLeaf.Operands[2] = initializerLeaves[1]
movLeaf.ExplictAssign = true
self:AddLeafToTail(movLeaf)
end
else
if initializerLeaves then
for i=1,#initializerLeaves do -- FIXME: find a nicer way to initialize
local movLeaf = self:NewLeaf()
movLeaf.Opcode = "mov"
movLeaf.Operands[1] = { Stack = label.StackOffset+i-1 }
movLeaf.Operands[2] = initializerLeaves[i]
movLeaf.ExplictAssign = true
self:AddLeafToTail(movLeaf)
end
for i=#initializerLeaves+1,bytesArraySize or 1 do
local movLeaf = self:NewLeaf()
movLeaf.Opcode = "mov"
movLeaf.Operands[1] = { Stack = label.StackOffset+i-1 }
movLeaf.Operands[2] = { Constant = 0 }
movLeaf.ExplictAssign = true
self:AddLeafToTail(movLeaf)
end
end
end
else
-- Define a new global variable
local label = self:DefineLabel(varName)
if isRegisterDecl then
label.Type = "Register"
label.Value = self:DeclareRegisterVariable()
else
label.Type = "Variable"
if isStruct and (pointerLevel > 0) then label.PointerToStruct = true end
end
label.Defined = true
if varType == 5 then label.ForceType = "vector" end
if isStruct then label.Struct = varType end
-- If label has associated array size, mark it as an array
if bytesArraySize then label.Array = bytesArraySize end
-- Create initialization leaf
label.Leaf = self:NewLeaf()
label.Leaf.ParentLabel = self.CurrentParentLabel or label
label.Leaf.Opcode = "DATA"
if initializerValues then
label.Leaf.Data = initializerValues
label.Leaf.ZeroPadding = (bytesArraySize or varSize) - #initializerValues
else
label.Leaf.ZeroPadding = bytesArraySize or varSize
end
label.Leaf.Label = label
self:AddLeafToTail(label.Leaf)
end
end
else -- Struct member
-- Do nothing right now
end
if not self:MatchToken(TOKEN.COMMA) then
return true,labelsList
else --int x, char y, float z
local nextToken,structName = self:PeekToken(0,true)
if (nextToken == TOKEN.IDENT) and (self.Structs[structName]) then
self:MatchToken(TOKEN.IDENT)
local structData = self.Structs[structName]
varType = self.TokenData
varSize = 0
isStruct = true
elseif self:MatchToken(TOKEN.TYPE) then
varType = self.TokenData
varSize = 1
if varType == 5 then varSize = 4 end
isStruct = false
end
end
end
end
--------------------------------------------------------------------------------
-- Compile a single statement
function HCOMP:Statement() local TOKEN = self.TOKEN
-- Parse end of line colon
if self:MatchToken(TOKEN.COLON) then return true end
-- Check for EOF
if self:MatchToken(TOKEN.EOF) then return false end
-- Parse variable/function definition
local exportSymbol = self:MatchToken(TOKEN.EXPORT)
local inlineFunction = self:MatchToken(TOKEN.INLINE)
local forwardFunction = self:MatchToken(TOKEN.FORWARD)
local registerValue = self:MatchToken(TOKEN.LREGISTER)
if self:PeekToken() == TOKEN.TYPE then
if inlineFunction then
self.GenerateInlineFunction = true
self.InlineFunctionCode = {}
end
local isDefined,variableList,functionName,returnType,returnPtrLevel = self:DefineVariable(false,forwardFunction,registerValue)
if isDefined then
if functionName then
self.Functions[functionName] = {
FunctionName = functionName,
Parameters = variableList,
ReturnType = returnType,
ReturnPtrLevel = returnPtrLevel,
}
if exportSymbol then
self.ExportedSymbols[functionName] = self.Functions[functionName]
end
if inlineFunction then
self.GenerateInlineFunction = functionName
end
else
if exportSymbol then
self:Error("Exporting variables not supported right now by the compiler")
end
end
end
if inlineFunction and (not functionName) then
self:Error("Can only inline functions")
end
if forwardFunction and (not functionName) then
self:Error("Can only forward-declare functions")
end
return isDefined
end
-- Peek structure definition
local nextToken,structName = self:PeekToken(0,true)
if (nextToken == TOKEN.IDENT) and (self.Structs[structName]) then
self:DefineVariable()
return true
end
if inlineFunction or exportSymbol or forwardFunction or registerValue then
self:Error("Function definition or symbol definition expected")
end
-- Parse preserve/zap
if self:MatchToken(TOKEN.PRESERVE) or self:MatchToken(TOKEN.ZAP) then
local tokenType = self.TokenType
if self.BlockDepth > 0 then
while self:MatchToken(TOKEN.REGISTER) do
self.BusyRegisters[self.TokenData] = tokenType == TOKEN.PRESERVE
self:MatchToken(TOKEN.COMMA)
end
self:MatchToken(TOKEN.COLON)
return true
else
self:Error("Can only zap/preserve registers inside functions/local blocks")
end
end
-- Parse assembly instruction
if self:MatchToken(TOKEN.OPCODE) then return self:Opcode() end
-- Parse STRUCT macro
if self:MatchToken(TOKEN.STRUCT) then
self:ExpectToken(TOKEN.IDENT)
local structName = self.TokenData
-- Create structure
self.Structs[structName] = {}
self.StructSize[structName] = 0
-- Populate structure
self:ExpectToken(TOKEN.LBRACKET)
while (not self:MatchToken(TOKEN.RBRACKET)) and (not self:MatchToken(TOKEN.EOF)) do
local _,variableList = self:DefineVariable(false,false,false,true)
for _,variableData in ipairs(variableList) do
variableData.Offset = self.StructSize[structName]
self.Structs[structName][variableData.Name] = variableData
self.StructSize[structName] = self.StructSize[structName] + variableData.Size
end
self:ExpectToken(TOKEN.COLON)
end
return true
end
-- Parse VECTOR macro
if self:MatchToken(TOKEN.VECTOR) then
if self.BlockDepth > 0 then
self:Warning("Defining a vector inside a function block might cause issues")
end
-- Vector type (VEC2F, etc)
local vectorType = self.TokenData
-- Vector name
self:ExpectToken(TOKEN.IDENT)
local vectorName = self.TokenData
-- Create leaf and label for vector name
local vectorNameLabelLeaf = self:NewLeaf()
vectorNameLabelLeaf.Opcode = "LABEL"
local vectorNameLabel = self:DefineLabel(vectorName)
vectorNameLabel.Type = "Pointer"
vectorNameLabel.Defined = true
vectorNameLabel.Leaf = vectorNameLabelLeaf
vectorNameLabel.DebugAsVector = #VectorSyntax[vectorType]
vectorNameLabelLeaf.Label = vectorNameLabel
self:AddLeafToTail(vectorNameLabelLeaf)
-- Create leaves for all vector labels and their data
local vectorLeaves = {}
for index,labelNames in pairs(VectorSyntax[vectorType]) do
-- Create leaves for labels
for labelIndex,labelName in pairs(labelNames) do
local vectorLabelLeaf = self:NewLeaf()
vectorLabelLeaf.Opcode = "LABEL"
local vectorLabel = self:GetLabel(vectorName.."."..labelName)
vectorLabel.Type = "Pointer"
vectorLabel.Defined = true
vectorLabel.Leaf = vectorLabelLeaf
vectorLabelLeaf.Label = vectorLabel
self:AddLeafToTail(vectorLabelLeaf)
end
-- Create leaf for data
vectorLeaves[index] = self:NewLeaf()
vectorLeaves[index].Opcode = "DATA"
vectorLeaves[index].Data = { 0 }
self:AddLeafToTail(vectorLeaves[index])
if vectorType == "COLOR" then
vectorLeaves[index].Data = { 255 }
end
end
-- Parse initialization
self.MostLikelyConstantExpression = true
if self:MatchToken(TOKEN.COMMA) then
for index,labelNames in pairs(VectorSyntax[vectorType]) do
local c,v,e = self:ConstantExpression(false)
if c then
vectorLeaves[index].Data[1] = v or e
else
self:Error("Vector initialization must be constant")
end
if (index == #VectorSyntax[vectorType]) and self:MatchToken(TOKEN.COMMA) then
self:Error("Too much values for intialization")
end
if (index < #VectorSyntax[vectorType]) and (not self:MatchToken(TOKEN.COMMA)) then
return true
end
end
end
self.MostLikelyConstantExpression = false
return true
end
-- Parse DATA macro
if self:MatchToken(TOKEN.DATA) then
local jmpLeaf = self:NewLeaf()
jmpLeaf.Opcode = "jmp"
jmpLeaf.Operands[1] = {
Constant = {{ Type = TOKEN.IDENT, Data = "_code", Position = self:CurrentSourcePosition() }}
}
self:AddLeafToTail(jmpLeaf)
return true
end
-- Parse CODE macro
if self:MatchToken(TOKEN.CODE) then
local label = self:DefineLabel("_code")
label.Type = "Pointer"
label.Leaf = self:NewLeaf()
label.Leaf.Opcode = "LABEL"
label.Leaf.Label = label
self:AddLeafToTail(label.Leaf)
return true
end
-- Parse ORG macro
if self:MatchToken(TOKEN.ORG) then
-- org x
local markerLeaf = self:NewLeaf()
markerLeaf.Opcode = "MARKER"
local c,v = self:ConstantExpression(true)
if c then markerLeaf.SetWritePointer = v
else self:Error("ORG offset must be constant") end
self:AddLeafToTail(markerLeaf)
return true
end
-- Parse OFFSET macro
if self:MatchToken(TOKEN.OFFSET) then
-- offset x
local markerLeaf = self:NewLeaf()
markerLeaf.Opcode = "MARKER"
local c,v = self:ConstantExpression(true)
if c then markerLeaf.SetPointerOffset = v
else self:Error("OFFSET offset must be constant") end
self:AddLeafToTail(markerLeaf)
return true
end
-- Parse DB macro
if self:MatchToken(TOKEN.DB) then
-- db 1,...
self.IgnoreStringInExpression = true
self.MostLikelyConstantExpression = true
local dbLeaf = self:NewLeaf()
dbLeaf.Opcode = "DATA"
dbLeaf.Data = {}
local c,v,e = self:ConstantExpression(false)
while c or (self:PeekToken() == TOKEN.STRING) do
-- Insert data into leaf
if self:MatchToken(TOKEN.STRING) then
table.insert(dbLeaf.Data,self.TokenData)
else
table.insert(dbLeaf.Data,v or e)
end
-- Only keep parsing if next token is comma
if self:MatchToken(TOKEN.COMMA) then
c,v,e = self:ConstantExpression(false)
else
c = false
end
end
self.IgnoreStringInExpression = false
self.MostLikelyConstantExpression = false
self:AddLeafToTail(dbLeaf)
return true
end
-- Parse STRING macro
if self:MatchToken(TOKEN.STRALLOC) then
-- string name,1,...
self:ExpectToken(TOKEN.IDENT)
-- Create leaf and label for vector name
local stringNameLabelLeaf = self:NewLeaf()
stringNameLabelLeaf.Opcode = "LABEL"
local stringNameLabel = self:DefineLabel(self.TokenData)
stringNameLabel.Type = "Pointer"
stringNameLabel.Defined = true
stringNameLabel.Leaf = stringNameLabelLeaf
stringNameLabelLeaf.Label = stringNameLabel
self:AddLeafToTail(stringNameLabelLeaf)
self:ExpectToken(TOKEN.COMMA)
self.IgnoreStringInExpression = true
self.MostLikelyConstantExpression = true
local stringLeaf = self:NewLeaf()
stringLeaf.Opcode = "DATA"
stringLeaf.Data = {}
local c,v,e = self:ConstantExpression(false)
while c or (self:PeekToken() == TOKEN.STRING) do
-- Insert data into leaf
if self:MatchToken(TOKEN.STRING) then
table.insert(stringLeaf.Data,self.TokenData)
else
table.insert(stringLeaf.Data,v or e)
end
-- Only keep parsing if next token is comma
if self:MatchToken(TOKEN.COMMA) then
c,v,e = self:ConstantExpression(false)
else
c = false
end
end
table.insert(stringLeaf.Data,0)
self.IgnoreStringInExpression = false
self.MostLikelyConstantExpression = false
self:AddLeafToTail(stringLeaf)
return true
end
-- Parse DEFINE macro
if self:MatchToken(TOKEN.DEFINE) then
-- define label,value
self:ExpectToken(TOKEN.IDENT)
local defineLabel = self:DefineLabel(self.TokenData)
defineLabel.Type = "Pointer"
defineLabel.Defined = true
self:ExpectToken(TOKEN.COMMA)
self.MostLikelyConstantExpression = true
local c,v,e = self:ConstantExpression(false)
if c then
if v then
defineLabel.Value = v
else
defineLabel.Expression = e
end
else
self:Error("Define value must be constant")
end
self.MostLikelyConstantExpression = false
return true
end
-- Parse ALLOC macro
if self:MatchToken(TOKEN.ALLOC) then
-- alloc label,size,value
-- alloc label,value
-- alloc label
-- alloc size
local allocLeaf = self:NewLeaf()
local allocLabel,allocSize,allocValue = nil,1,0
local expectSize = false
allocLeaf.Opcode = "DATA"
-- Add a label to this alloc
if self:MatchToken(TOKEN.IDENT) then
allocLabel = self:DefineLabel(self.TokenData)
allocLabel.Type = "Pointer"
allocLabel.Defined = true
allocLabel.DebugAsVariable = true
allocLabel.Leaf = allocLeaf
allocLeaf.Label = allocLabel
if self:MatchToken(TOKEN.COMMA) then expectSize = true end
end
-- Read size
self.MostLikelyConstantExpression = true
if (not allocLabel) or (expectSize) then
local c,v = self:ConstantExpression(true) -- need precise value here, no ptrs allowed
if c then allocSize = v
else self:Error("Alloc size must be constant") end
end
if allocLabel and expectSize then
if self:MatchToken(TOKEN.COMMA) then
local c,v = self:ConstantExpression(true) -- need precise value here, no ptrs allowed
if c then allocValue = v
else self:Error("Alloc value must be constant") end
else
allocValue = allocSize
allocSize = 1
end
end
self.MostLikelyConstantExpression = false
-- Initialize alloc
allocLeaf.ZeroPadding = allocSize
self:AddLeafToTail(allocLeaf)
return true
end
-- Parse RETURN
if self:MatchToken(TOKEN.RETURN) and self.HeadLeaf then
if not self:MatchToken(TOKEN.COLON) then
local returnExpression = self:Expression()
local returnLeaf = self:NewLeaf()
returnLeaf.Opcode = "mov"
returnLeaf.Operands[1] = { Register = 1 }
returnLeaf.Operands[2] = returnExpression
returnLeaf.ExplictAssign = true
self:AddLeafToTail(returnLeaf)
end
self:MatchToken(TOKEN.COLON)
-- Check if this is the last return in the function
-- if self:MatchToken(TOKEN.RBRACKET) then
-- if self.BlockDepth > 0 then
-- self:BlockEnd()
-- return true
-- else
-- self:Error("Unexpected bracket")
-- end
-- end
if not self.GenerateInlineFunction then
-- Create leaf for exiting local scope
local leaveLeaf = self:NewLeaf()
leaveLeaf.Opcode = "leave"
if (self.StackPointer ~= 0) or
(self.ParameterPointer ~= 0) or
(self.Settings.AlwaysEnterLeave) then
self:AddLeafToTail(leaveLeaf)
end
-- Create leaf for returning from call
local retLeaf = self:NewLeaf()
retLeaf.Opcode = "ret"
self:AddLeafToTail(retLeaf)
end
return true
end
-- Parse IF syntax
if self:MatchToken(TOKEN.IF) then
-- Parse condition
self:ExpectToken(TOKEN.LPAREN)
local firstToken = self.CurrentToken
self:SaveParserState()
local conditionLeaf = self:Expression()
local conditionText = "if ("..self:PrintTokens(self:GetSavedTokens(firstToken))..")"
self:ExpectToken(TOKEN.RPAREN)
-- Enter the IF block
local needBlock = self:MatchToken(TOKEN.LBRACKET)
self:BlockStart("IF")
-- Calculate condition
local cmpLeaf = self:NewLeaf()
cmpLeaf.Opcode = "cmp"
cmpLeaf.Operands[1] = { Constant = 0 }
cmpLeaf.Operands[2] = conditionLeaf
cmpLeaf.Comment = conditionText
self:AddLeafToTail(cmpLeaf)
-- Create label for conditional break (if condition is false)
local conditionalBreakLeaf = self:NewLeaf()
local conditionalBreak = self:GetTempLabel()
conditionalBreakLeaf.Opcode = "LABEL"
conditionalBreak.Type = "Pointer"
conditionalBreak.Leaf = conditionalBreakLeaf
conditionalBreakLeaf.Label = conditionalBreak
self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak = conditionalBreakLeaf
-- self:AddLeafToTail(conditionalBreakLeaf)
-- Generate conditional jump over the block
local jumpLeaf = self:NewLeaf()
jumpLeaf.Opcode = "jge"
jumpLeaf.Operands[1] = { PointerToLabel = conditionalBreakLeaf.Label }
self:AddLeafToTail(jumpLeaf)
if not needBlock then
-- Parse next statement if dont need a block
self:Statement()
-- End the IF block early
self:BlockEnd()
-- Add exit label
self:AddLeafToTail(conditionalBreakLeaf)
-- Check for out-of-block ELSE
if self:MatchToken(TOKEN.ELSE) then
self:ParseElse(false)
end
-- else
-- self:AddLeafToTail(conditionalBreak)
-- self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak = jumpLeaf
end
return true
end
-- Parse WHILE syntax
if self:MatchToken(TOKEN.WHILE) then
local returnLabel
-- Parse condition
self:ExpectToken(TOKEN.LPAREN)
local firstToken = self.CurrentToken
self:SaveParserState()
local conditionLeaf = self:Expression()
local conditionText = "if ("..self:PrintTokens(self:GetSavedTokens(firstToken))
self:ExpectToken(TOKEN.RPAREN)
-- Enter the WHILE block
local needBlock = self:MatchToken(TOKEN.LBRACKET)
if needBlock then
self:BlockStart("WHILE")
end
if not needBlock then
-- Generate return label
local returnLabelLeaf = self:NewLeaf()
returnLabel = self:GetTempLabel()
returnLabelLeaf.Opcode = "LABEL"
returnLabel.Type = "Pointer"
returnLabel.Leaf = returnLabelLeaf
returnLabelLeaf.Label = returnLabel
self:AddLeafToTail(returnLabelLeaf)
end
-- Calculate condition
local cmpLeaf = self:NewLeaf()
cmpLeaf.Opcode = "cmp"
cmpLeaf.Operands[1] = { Constant = 0 }
cmpLeaf.Operands[2] = conditionLeaf
cmpLeaf.Comment = conditionText
self:AddLeafToTail(cmpLeaf)
if not needBlock then
-- Generate conditional jump over the block
local jumpOverLabelLeaf = self:NewLeaf()
local jumpOverLabel = self:GetTempLabel()
jumpOverLabelLeaf.Opcode = "LABEL"
jumpOverLabel.Type = "Pointer"
jumpOverLabel.Leaf = jumpOverLabelLeaf
jumpOverLabelLeaf.Label = jumpOverLabel
local jumpOverLeaf = self:NewLeaf()
jumpOverLeaf.Opcode = "jz"
jumpOverLeaf.Operands[1] = { PointerToLabel = jumpOverLabel }
self:AddLeafToTail(jumpOverLeaf)
-- Parse next statement if dont need a block
self:Statement()
-- Generate the jump back leaf
local jumpBackLeaf = self:NewLeaf()
jumpBackLeaf.Opcode = "jmp"
jumpBackLeaf.Operands[1] = { PointerToLabel = returnLabel }
self:AddLeafToTail(jumpBackLeaf)
-- Add exit label
self:AddLeafToTail(jumpOverLabelLeaf)
else
-- Generate conditional jump over the block
local jumpOverLeaf = self:NewLeaf()
jumpOverLeaf.Opcode = "jz"
jumpOverLeaf.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Break.Label }
self:AddLeafToTail(jumpOverLeaf)
-- Set the jump back leaf
self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Opcode = "jmp"
self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Continue.Label }
end
return true
end
-- Parse FOR syntax
if self:MatchToken(TOKEN.FOR) then
local returnLabel
-- Parse syntax
self:ExpectToken(TOKEN.LPAREN)
local initLeaf = self:Expression()
initLeaf.Comment = "init loop"
self:ExpectToken(TOKEN.COLON)
local conditionLeaf = self:Expression()
conditionLeaf.Comment = "condition"
self:ExpectToken(TOKEN.COLON)
local stepLeaf = self:Expression()
stepLeaf.Comment = "loop step"
self:ExpectToken(TOKEN.RPAREN)
self:AddLeafToTail(initLeaf)
-- Save stepLeaf for inlining continue
self.CurrentStepLeaf = stepLeaf
-- Enter the FOR block
local needBlock = self:MatchToken(TOKEN.LBRACKET)
if needBlock then
self:BlockStart("FOR")
end
if not needBlock then
-- Generate return label
local returnLabelLeaf = self:NewLeaf()
returnLabel = self:GetTempLabel()
returnLabelLeaf.Opcode = "LABEL"
returnLabel.Type = "Pointer"
returnLabel.Leaf = returnLabelLeaf
returnLabelLeaf.Label = returnLabel
self:AddLeafToTail(returnLabelLeaf)
end
-- Calculate condition
local cmpLeaf = self:NewLeaf()
cmpLeaf.Opcode = "cmp"
cmpLeaf.Operands[1] = { Constant = 0 }
cmpLeaf.Operands[2] = conditionLeaf
self:AddLeafToTail(cmpLeaf)
if not needBlock then
-- Generate conditional jump over the block
local jumpOverLabelLeaf = self:NewLeaf()
local jumpOverLabel = self:GetTempLabel()
jumpOverLabelLeaf.Opcode = "LABEL"
jumpOverLabel.Type = "Pointer"
jumpOverLabel.Leaf = jumpOverLabelLeaf
jumpOverLabelLeaf.Label = jumpOverLabel
local jumpOverLeaf = self:NewLeaf()
jumpOverLeaf.Opcode = "jz"
jumpOverLeaf.Operands[1] = { PointerToLabel = jumpOverLabel }
self:AddLeafToTail(jumpOverLeaf)
-- Parse next statement if dont need a block
self:Statement()
-- Generate the jump back leaf
local jumpBackLeaf = self:NewLeaf()
jumpBackLeaf.Opcode = "jmp"
jumpBackLeaf.Operands[1] = { PointerToLabel = returnLabel }
self:AddLeafToTail(stepLeaf)
self:AddLeafToTail(jumpBackLeaf)
-- Add exit label
self:AddLeafToTail(jumpOverLabelLeaf)
else
-- Generate conditional jump over the block
local jumpOverLeaf = self:NewLeaf()
jumpOverLeaf.Opcode = "jz"
jumpOverLeaf.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Break.Label }
self:AddLeafToTail(jumpOverLeaf)
-- Set the jump back leaf
self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Opcode = "jmp"
self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Continue.Label }
self.SpecialLeaf[#self.SpecialLeaf].JumpBack.PreviousLeaf = stepLeaf
end
return true
end
-- Parse CONTINUE
if self:MatchToken(TOKEN.CONTINUE) then
if (self.BlockDepth > 0) and (self.CurrentContinueLeaf) then
local jumpBackLeaf = self:NewLeaf()
jumpBackLeaf.Opcode = "jmp"
jumpBackLeaf.Operands[1] = { PointerToLabel = self.CurrentContinueLeaf.Label }
if (self.CurrentStepLeaf) then
self:AddLeafToTail(self.CurrentStepLeaf)
end
self:AddLeafToTail(jumpBackLeaf)
return true
else
self:Error("Nowhere to continue here")
end
end
-- Parse BREAK
if self:MatchToken(TOKEN.BREAK) then
if (self.BlockDepth > 0) and (self.CurrentBreakLeaf) then
local jumpLeaf = self:NewLeaf()
jumpLeaf.Opcode = "jmp"
jumpLeaf.Operands[1] = { PointerToLabel = self.CurrentBreakLeaf.Label }
self:AddLeafToTail(jumpLeaf)
return true
else
self:Error("Nowhere to break from here")
end
end
-- Parse GOTO
if self:MatchToken(TOKEN.GOTO) then
local gotoExpression = self:Expression()
local jumpLeaf = self:NewLeaf()
jumpLeaf.Opcode = "jmp"
jumpLeaf.Operands[1] = gotoExpression
self:AddLeafToTail(jumpLeaf)
return true
end
-- Parse block open bracket
if self:MatchToken(TOKEN.LBRACKET) then
self:BlockStart("LBLOCK")
return true
end
-- Parse block close bracket
if self:MatchToken(TOKEN.RBRACKET) then
if self.BlockDepth > 0 then
local blockType = self.BlockType[#self.BlockType]
if (blockType == "IF") and self:MatchToken(TOKEN.ELSE) then -- Add ELSE block, IF remains in stack
self:ParseElse(true)
else
if blockType == "IF" then -- FIXME: It kind of is redundant
self:AddLeafToTail(self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak)
end
self:BlockEnd()
end
return true
else
self:Error("Unexpected bracket")
end
end
-- Parse possible label definition
local firstToken = self.CurrentToken
self:SaveParserState()
if self:MatchToken(TOKEN.IDENT) then
if (self:PeekToken() == TOKEN.COMMA) or (self:PeekToken() == TOKEN.DCOLON) then
-- Label definition for sure
while true do
local label = self:DefineLabel(self.TokenData)
label.Type = "Pointer"
label.Defined = true
label.Leaf = self:NewLeaf()
label.Leaf.Opcode = "LABEL"
label.Leaf.Label = label
self:AddLeafToTail(label.Leaf)
self:MatchToken(TOKEN.COMMA)
if not self:MatchToken(TOKEN.IDENT) then break end
end
self:ExpectToken(TOKEN.DCOLON)
self:MatchToken(TOKEN.COLON)
return true
else
self:RestoreParserState()
end
end
-- If nothing else, must be some kind of an expression
local expressionLeaf = self:Expression()
self:AddLeafToTail(expressionLeaf)
-- Add expression to leaf comment
if self.Settings.GenerateComments then
expressionLeaf.Comment = self:PrintTokens(self:GetSavedTokens(firstToken))
end
-- Skip a colon
self:MatchToken(TOKEN.COLON)
return true
end
| apache-2.0 |
n0xus/darkstar | scripts/globals/spells/yurin_ichi.lua | 18 | 1597 | -----------------------------------------
-- Spell: Yurin: Ichi
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effect = EFFECT_INHIBIT_TP;
-- Base Stats
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
--Duration Calculation
local resist = applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0);
--Base power is 10 and is not affected by resistaces.
local power = 10;
--Calculates Resist Chance
if (resist >= 0.125) then
local duration = 180 * resist;
if (duration >= 50) then
-- Erases a weaker inhibit tp and applies the stronger one
local inhibit_tp = target:getStatusEffect(effect);
if (inhibit_tp ~= nil) then
if (inhibit_tp:getPower() < power) then
target:delStatusEffect(effect);
target:addStatusEffect(effect,power,0,duration);
spell:setMsg(237);
else
-- no effect
spell:setMsg(75);
end
else
target:addStatusEffect(effect,power,0,duration);
spell:setMsg(237);
end
else
spell:setMsg(85);
end
else
spell:setMsg(284);
end
return effect;
end; | gpl-3.0 |
xubigshu/skynet | service/multicastd.lua | 47 | 5408 | local skynet = require "skynet"
local mc = require "multicast.core"
local datacenter = require "datacenter"
local harbor_id = skynet.harbor(skynet.self())
local command = {}
local channel = {}
local channel_n = {}
local channel_remote = {}
local channel_id = harbor_id
local NORET = {}
local function get_address(t, id)
local v = assert(datacenter.get("multicast", id))
t[id] = v
return v
end
local node_address = setmetatable({}, { __index = get_address })
-- new LOCAL channel , The low 8bit is the same with harbor_id
function command.NEW()
while channel[channel_id] do
channel_id = mc.nextid(channel_id)
end
channel[channel_id] = {}
channel_n[channel_id] = 0
local ret = channel_id
channel_id = mc.nextid(channel_id)
return ret
end
-- MUST call by the owner node of channel, delete a remote channel
function command.DELR(source, c)
channel[c] = nil
channel_n[c] = nil
return NORET
end
-- delete a channel, if the channel is remote, forward the command to the owner node
-- otherwise, delete the channel, and call all the remote node, DELR
function command.DEL(source, c)
local node = c % 256
if node ~= harbor_id then
skynet.send(node_address[node], "lua", "DEL", c)
return NORET
end
local remote = channel_remote[c]
channel[c] = nil
channel_n[c] = nil
channel_remote[c] = nil
if remote then
for node in pairs(remote) do
skynet.send(node_address[node], "lua", "DELR", c)
end
end
return NORET
end
-- forward multicast message to a node (channel id use the session field)
local function remote_publish(node, channel, source, ...)
skynet.redirect(node_address[node], source, "multicast", channel, ...)
end
-- publish a message, for local node, use the message pointer (call mc.bind to add the reference)
-- for remote node, call remote_publish. (call mc.unpack and skynet.tostring to convert message pointer to string)
local function publish(c , source, pack, size)
local group = channel[c]
if group == nil then
-- dead channel, delete the pack. mc.bind returns the pointer in pack
local pack = mc.bind(pack, 1)
mc.close(pack)
return
end
mc.bind(pack, channel_n[c])
local msg = skynet.tostring(pack, size)
for k in pairs(group) do
-- the msg is a pointer to the real message, publish pointer in local is ok.
skynet.redirect(k, source, "multicast", c , msg)
end
local remote = channel_remote[c]
if remote then
-- remote publish should unpack the pack, because we should not publish the pointer out.
local _, msg, sz = mc.unpack(pack, size)
local msg = skynet.tostring(msg,sz)
for node in pairs(remote) do
remote_publish(node, c, source, msg)
end
end
end
skynet.register_protocol {
name = "multicast",
id = skynet.PTYPE_MULTICAST,
unpack = function(msg, sz)
return mc.packremote(msg, sz)
end,
dispatch = publish,
}
-- publish a message, if the caller is remote, forward the message to the owner node (by remote_publish)
-- If the caller is local, call publish
function command.PUB(source, c, pack, size)
assert(skynet.harbor(source) == harbor_id)
local node = c % 256
if node ~= harbor_id then
-- remote publish
remote_publish(node, c, source, mc.remote(pack))
else
publish(c, source, pack,size)
end
end
-- the node (source) subscribe a channel
-- MUST call by channel owner node (assert source is not local and channel is create by self)
-- If channel is not exist, return true
-- Else set channel_remote[channel] true
function command.SUBR(source, c)
local node = skynet.harbor(source)
if not channel[c] then
-- channel none exist
return true
end
assert(node ~= harbor_id and c % 256 == harbor_id)
local group = channel_remote[c]
if group == nil then
group = {}
channel_remote[c] = group
end
group[node] = true
end
-- the service (source) subscribe a channel
-- If the channel is remote, node subscribe it by send a SUBR to the owner .
function command.SUB(source, c)
local node = c % 256
if node ~= harbor_id then
-- remote group
if channel[c] == nil then
if skynet.call(node_address[node], "lua", "SUBR", c) then
return
end
if channel[c] == nil then
-- double check, because skynet.call whould yield, other SUB may occur.
channel[c] = {}
channel_n[c] = 0
end
end
end
local group = channel[c]
if group and not group[source] then
channel_n[c] = channel_n[c] + 1
group[source] = true
end
end
-- MUST call by a node, unsubscribe a channel
function command.USUBR(source, c)
local node = skynet.harbor(source)
assert(node ~= harbor_id)
local group = assert(channel_remote[c])
group[node] = nil
return NORET
end
-- Unsubscribe a channel, if the subscriber is empty and the channel is remote, send USUBR to the channel owner
function command.USUB(source, c)
local group = assert(channel[c])
if group[source] then
group[source] = nil
channel_n[c] = channel_n[c] - 1
if channel_n[c] == 0 then
local node = c % 256
if node ~= harbor_id then
-- remote group
channel[c] = nil
channel_n[c] = nil
skynet.send(node_address[node], "lua", "USUBR", c)
end
end
end
return NORET
end
skynet.start(function()
skynet.dispatch("lua", function(_,source, cmd, ...)
local f = assert(command[cmd])
local result = f(source, ...)
if result ~= NORET then
skynet.ret(skynet.pack(result))
end
end)
local self = skynet.self()
local id = skynet.harbor(self)
assert(datacenter.set("multicast", id, self) == nil)
end)
| mit |
MHPG/MHP | plugins/Boobs.lua | 150 | 1613 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. ًں”",
"!butts: Get a butts NSFW image. ًں”"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
davymai/CN-QulightUI | Interface/AddOns/QulightUI/Addons/UF/Raid/elements/RaidDebuffs.lua | 1 | 6546 |
----------------------------------------------------------------------------------------
-- Based on oUF_RaidDebuffs(by Yleaf)
----------------------------------------------------------------------------------------
local _, ns = ...
local oUF = ns.oUF
local CleanseName = GetSpellInfo(4987)
local bossDebuffPrio = 9999999
local invalidPrio = -1
local auraFilters = {
["HARMFUL"] = true,
}
local DispellColor = {
["Magic"] = {0.2, 0.6, 1},
["Curse"] = {0.6, 0, 1},
["Disease"] = {0.6, 0.4, 0},
["Poison"] = {0, 0.6, 0},
["none"] = {0.4,0.4,0.4},
}
if Qulight.raidframes.debuff_color_type == true then
DispellColor.none = {1, 0, 0}
end
local DispellPriority = {
["Magic"] = 4,
["Curse"] = 3,
["Disease"] = 2,
["Poison"] = 1,
}
local DispellFilter
do
local dispellClasses = {
["DRUID"] = {
["Magic"] = false,
["Curse"] = true,
["Poison"] = true,
},
["MAGE"] = {
["Curse"] = true,
},
["MONK"] = {
["Magic"] = true,
["Poison"] = true,
["Disease"] = true,
},
["PALADIN"] = {
["Magic"] = false,
["Poison"] = true,
["Disease"] = true,
},
["PRIEST"] = {
["Magic"] = false,
["Disease"] = false,
},
["SHAMAN"] = {
["Magic"] = false,
["Curse"] = true,
},
}
DispellFilter = dispellClasses[class] or {}
end
CheckSpec = function(tree)
local activeGroup = GetActiveSpecGroup()
if activeGroup and GetSpecialization(false, false, activeGroup) then
return tree == GetSpecialization(false, false, activeGroup)
end
end
local function CheckSpec()
if class == "DRUID" then
if CheckSpec(4) then
DispellFilter.Magic = true
else
DispellFilter.Magic = false
end
elseif class == "MONK" then
if CheckSpec(2) then
DispellFilter.Magic = true
else
DispellFilter.Magic = false
end
elseif class == "PALADIN" then
if CheckSpec(1)then
DispellFilter.Magic = true
else
DispellFilter.Magic = false
end
elseif class == "PRIEST" then
if CheckSpec(3) then
DispellFilter.Magic = false
DispellFilter.Disease = false
else
DispellFilter.Magic = true
DispellFilter.Disease = true
end
elseif class == "SHAMAN" then
if CheckSpec(3) then
DispellFilter.Magic = true
else
DispellFilter.Magic = false
end
end
end
local function CheckSymbiosis()
if GetSpellInfo(SymbiosisName) == CleanseName then
DispellFilter.Disease = true
else
DispellFilter.Disease = false
end
end
local function formatTime(s)
if s > 60 then
return format("%dm", s / 60), s % 60
else
return format("%d", s), s - floor(s)
end
end
local abs = math.abs
local function OnUpdate(self, elapsed)
self.elapsed = (self.elapsed or 0) + elapsed
if self.elapsed >= 0.1 then
local timeLeft = self.expirationTime - GetTime()
if self.reverse then timeLeft = abs((self.expirationTime - GetTime()) - self.duration) end
if timeLeft > 0 then
local text = formatTime(timeLeft)
self.time:SetText(text)
else
self:SetScript("OnUpdate", nil)
self.time:Hide()
end
self.elapsed = 0
end
end
local UpdateDebuffFrame = function(rd)
if rd.index and rd.type and rd.filter then
local name, rank, icon, count, debuffType, duration, expirationTime, _, _, _, spellId, _, isBossDebuff = UnitAura(rd.__owner.unit, rd.index, rd.filter)
if rd.icon then
rd.icon:SetTexture(icon)
rd.icon:Show()
end
if rd.count then
if count and (count > 1) then
rd.count:SetText(count)
rd.count:Show()
else
rd.count:Hide()
end
end
if spellId and RaidDebuffsReverse[spellId] then
rd.reverse = true
else
rd.reverse = nil
end
if rd.time then
rd.duration = duration
if duration and (duration > 0) then
rd.expirationTime = expirationTime
rd.nextUpdate = 0
rd:SetScript("OnUpdate", OnUpdate)
rd.time:Show()
else
rd:SetScript("OnUpdate", nil)
rd.time:Hide()
end
end
if rd.cd then
if duration and (duration > 0) then
rd.cd:SetCooldown(expirationTime - duration, duration)
rd.cd:Show()
else
rd.cd:Hide()
end
end
local c = DispellColor[debuffType] or DispellColor.none
if Qulight.raidframes.debuff_color_type == true then
rd:SetBackdropBorderColor(c[1], c[2], c[3])
end
if not rd:IsShown() then
rd:Show()
end
else
if rd:IsShown() then
rd:Hide()
end
end
end
local Update = function(self, event, unit)
if unit ~= self.unit then return end
local rd = self.RaidDebuffs
rd.priority = invalidPrio
for filter in next, (rd.Filters or auraFilters) do
local i = 0
while(true) do
i = i + 1
local name, rank, icon, count, debuffType, duration, expirationTime, _, _, _, spellId, _, isBossDebuff = UnitAura(unit, i, filter)
if not name then break end
if rd.ShowBossDebuff and isBossDebuff then
local prio = rd.BossDebuffPriority or bossDebuffPrio
if prio and prio > rd.priority then
rd.priority = prio
rd.index = i
rd.type = "Boss"
rd.filter = filter
end
end
if rd.ShowDispellableDebuff and debuffType then
local disPrio = rd.DispellPriority or DispellPriority
local disFilter = rd.DispellFilter or DispellFilter
local prio
if rd.FilterDispellableDebuff and disFilter then
prio = disFilter[debuffType] and disPrio[debuffType]
else
prio = disPrio[debuffType]
end
if prio and (prio > rd.priority) then
rd.priority = prio
rd.index = i
rd.type = "Dispel"
rd.filter = filter
end
end
local prio = rd.Debuffs and rd.Debuffs[rd.MatchBySpellName and name or spellId]
if not RaidDebuffsIgnore[spellId] and prio and (prio > rd.priority) then
rd.priority = prio
rd.index = i
rd.type = "Custom"
rd.filter = filter
end
end
end
if rd.priority == invalidPrio then
rd.index = nil
rd.filter = nil
rd.type = nil
end
return UpdateDebuffFrame(rd)
end
local Path = function(self, ...)
return (self.RaidDebuffs.Override or Update) (self, ...)
end
local ForceUpdate = function(element)
return Path(element.__owner, "ForceUpdate", element.__owner.unit)
end
local Enable = function(self)
local rd = self.RaidDebuffs
if rd then
self:RegisterEvent("UNIT_AURA", Path)
rd.ForceUpdate = ForceUpdate
rd.__owner = self
return true
end
self:RegisterEvent("PLAYER_TALENT_UPDATE", CheckSpec)
CheckSpec()
end
local Disable = function(self)
if self.RaidDebuffs then
self:UnregisterEvent("UNIT_AURA", Path)
self.RaidDebuffs:Hide()
self.RaidDebuffs.__owner = nil
end
self:UnregisterEvent("PLAYER_TALENT_UPDATE", CheckSpec)
CheckSpec()
end
oUF:AddElement("RaidDebuffs", Update, Enable, Disable) | gpl-2.0 |
Python1320/wire | lua/wire/stools/simple_explosive.lua | 9 | 1897 | WireToolSetup.setCategory( "Physics" )
WireToolSetup.open( "simple_explosive", "Explosives (Simple)", "gmod_wire_simple_explosive", nil, "Simple Explosives" )
if CLIENT then
language.Add( "tool.wire_simple_explosive.name", "Simple Wired Explosives Tool" )
language.Add( "tool.wire_simple_explosive.desc", "Creates a simple explosives for wire system." )
language.Add( "tool.wire_simple_explosive.0", "Left click: Spawn bomb, Reload: Copy model" )
language.Add( "Tool.simple_explosive.model", "Model:" )
language.Add( "Tool.simple_explosive.trigger", "Trigger value:" )
language.Add( "Tool.simple_explosive.damage", "Damage:" )
language.Add( "Tool.simple_explosive.removeafter", "Remove on explosion" )
language.Add( "Tool.simple_explosive.radius", "Blast radius:" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 20 )
if SERVER then
function TOOL:GetConVars()
return self:GetClientNumber( "trigger" ), self:GetClientNumber( "damage" ), self:GetClientNumber( "removeafter" )==1,
self:GetClientNumber( "radius" )
end
end
TOOL.ClientConVar = {
model = "models/props_c17/oildrum001_explosive.mdl",
modelman = "",
trigger = 1, -- Wire input value to cause the explosion
damage = 200, -- Damage to inflict
radius = 300,
removeafter = 0,
}
TOOL.ReloadSetsModel = true
function TOOL.BuildCPanel(panel)
ModelPlug_AddToCPanel(panel, "Explosive", "wire_simple_explosive")
panel:Help("This tool is deprecated as its functionality is contained within Wire Explosive, and will be removed soon.")
panel:NumSlider("#Tool.simple_explosive.trigger", "wire_simple_explosive_trigger", -10, 10, 0 )
panel:NumSlider("#Tool.simple_explosive.damage", "wire_simple_explosive_damage", 0, 500, 0 )
panel:NumSlider("#Tool.simple_explosive.radius", "wire_simple_explosive_radius", 1, 1500, 0 )
panel:CheckBox("#Tool.simple_explosive.removeafter","wire_simple_explosive_removeafter")
end | apache-2.0 |
n0xus/darkstar | scripts/zones/The_Eldieme_Necropolis/TextIDs.lua | 9 | 2300 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6543; -- Obtained: <item>
GIL_OBTAINED = 6544; -- Obtained <number> gil
KEYITEM_OBTAINED = 6546; -- Obtained key item: <keyitem>
SOLID_STONE = 7368; -- This door is made of solid stone.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7387; -- You unlock the chest!
CHEST_FAIL = 7388; -- Fails to open the chest.
CHEST_TRAP = 7389; -- The chest was trapped!
CHEST_WEAK = 7390; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7391; -- The chest was a mimic!
CHEST_MOOGLE = 7392; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7393; -- The chest was but an illusion...
CHEST_LOCKED = 7394; -- The chest appears to be locked.
-- Quests
NOTHING_OUT_OF_ORDINARY = 6557; -- There is nothing out of the ordinary here.
SENSE_OF_FOREBODING = 6558; -- You are suddenly overcome with a sense of foreboding...
NOTHING_HAPPENED = 7328; -- Nothing happened...
RETURN_RIBBON_TO_HER = 7341; -- You can hear a voice from somewhere. (...return...ribbon to...her...)
THE_BRAZIER_IS_LIT = 7355; -- The brazier is lit.
REFUSE_TO_LIGHT = 7356; -- Unexpectedly, therefuses to light.
LANTERN_GOES_OUT = 7357; -- For some strange reason, the light of thegoes out...
THE_LIGHT_DIMLY = 7358; -- lights dimly. It doesn't look like this will be effective yet.?Prompt?
THE_LIGHT_HAS_INTENSIFIED = 7359; -- The light of thehas intensified.
THE_LIGHT_IS_FULLY_LIT = 7360; -- is fully lit!
SPIRIT_INCENSE_EMITS_PUTRID_ODOR = 7397; -- emits a putrid odor and burns up. Your attempt this time has failed...?Prompt?
SARCOPHAGUS_CANNOT_BE_OPENED = 7414; -- It is a stone sarcophagus with the lid sealed tight. It cannot be opened.
-- conquest Base
CONQUEST_BASE = 0;
-- Strange Apparatus
DEVICE_NOT_WORKING = 7304; -- The device is not working.
SYS_OVERLOAD = 7313; -- arning! Sys...verload! Enterin...fety mode. ID eras...d
YOU_LOST_THE = 7318; -- You lost the #.
| gpl-3.0 |
davymai/CN-QulightUI | Interface/AddOns/QulightUI/Addons/UF/Raid/elements/range.lua | 1 | 4933 | local parent, ns = ...
local oUF = ns.oUF or oUF
-- oUF range element with code sniplets from TomTom
local _FRAMES = {}
local OnRangeFrame
local update = .20
local UnitInRange, UnitIsConnected = UnitInRange, UnitIsConnected
local SetMapToCurrentZone, WorldMapFrame = SetMapToCurrentZone, WorldMapFrame
local GetPlayerMapPosition, GetPlayerFacing = GetPlayerMapPosition, GetPlayerFacing
local select, next = select, next
local pi = math.pi
local twopi = pi * 2
local atan2 = math.atan2
local modf = math.modf
local abs = math.abs
local floor = floor
local function ColorGradient(perc, ...)
local num = select("#", ...)
local hexes = type(select(1, ...)) == "string"
if perc == 1 then
return select(num-2, ...), select(num-1, ...), select(num, ...)
end
num = num / 3
local segment, relperc = modf(perc*(num-1))
local r1, g1, b1, r2, g2, b2
r1, g1, b1 = select((segment*3)+1, ...), select((segment*3)+2, ...), select((segment*3)+3, ...)
r2, g2, b2 = select((segment*3)+4, ...), select((segment*3)+5, ...), select((segment*3)+6, ...)
if not r2 or not g2 or not b2 then
return r1, g1, b1
else
return r1 + (r2-r1)*relperc,
g1 + (g2-g1)*relperc,
b1 + (b2-b1)*relperc
end
end
local function ColorTexture(texture, angle)
local perc = abs((pi - abs(angle)) / pi)
local gr,gg,gb = 0, 1, 0
local mr,mg,mb = 1, 1, 0
local br,bg,bb = 1, 0, 0
local r,g,b = ColorGradient(perc, br, bg, bb, mr, mg, mb, gr, gg, gb)
texture:SetVertexColor(r,g,b)
end
local function RotateTexture(frame, angle)
if not frame:IsShown() then
frame:Show()
end
angle = angle - GetPlayerFacing()
local cell = floor(angle / twopi * 108 + 0.5) % 108
if cell == frame.cell then return end
frame.cell = cell
local column = cell % 9
local row = floor(cell / 9)
ColorTexture(frame.arrow, angle)
local xstart = (column * 56) / 512
local ystart = (row * 42) / 512
local xend = ((column + 1) * 56) / 512
local yend = ((row + 1) * 42) / 512
frame.arrow:SetTexCoord(xstart,xend,ystart,yend)
end
local px, py, tx, ty
local function GetBearing(unit)
if unit == 'player' then return end
px, py = GetPlayerMapPosition("player")
if((px or 0)+(py or 0) <= 0) then
if WorldMapFrame:IsVisible() then return end
SetMapToCurrentZone()
px, py = GetPlayerMapPosition("player")
if((px or 0)+(py or 0) <= 0) then return end
end
tx, ty = GetPlayerMapPosition(unit)
if((tx or 0)+(ty or 0) <= 0) then return end
return pi - atan2(px-tx,ty-py)
end
function ns:arrow(object, unit)
if(not object.OoR and not Qulight["raidframes"].arrowmouseoveralways) or not UnitIsConnected(unit) then return end
local bearing = GetBearing(unit)
if bearing then
RotateTexture(object.freebarrow, bearing)
end
end
local timer = 0
local OnRangeUpdate = function(self, elapsed)
timer = timer + elapsed
if(timer >= update) then
for _, object in next, _FRAMES do
if(object:IsShown()) then
local range = object.freebRange
if(UnitIsConnected(object.unit) and not UnitInRange(object.unit)) then
if(object:GetAlpha() == range.insideAlpha) then
object:SetAlpha(range.outsideAlpha)
end
object.OoR = true
elseif(object:GetAlpha() ~= range.insideAlpha) then
object:SetAlpha(range.insideAlpha)
else
object.OoR = false
end
else
end
end
timer = 0
end
end
local Enable = function(self)
local range = self.freebRange
if(range and range.insideAlpha and range.outsideAlpha) then
table.insert(_FRAMES, self)
if(not OnRangeFrame) then
OnRangeFrame = CreateFrame"Frame"
OnRangeFrame:SetScript("OnUpdate", OnRangeUpdate)
end
OnRangeFrame:Show()
local frame = CreateFrame("Frame", nil, UIParent)
frame:SetAllPoints(self)
frame:SetFrameStrata("HIGH")
frame.arrow = frame:CreateTexture(nil, "OVERLAY")
frame.arrow:SetTexture"Interface\\Addons\\oUF_Freebgrid\\Media\\Arrow"
frame.arrow:SetPoint("TOPRIGHT", frame, "TOPRIGHT")
frame.arrow:SetSize(24, 24)
self.freebarrow = frame
self.freebarrow:Hide()
end
end
local Disable = function(self)
local range = self.freebRange
if(range) then
for k, frame in next, _FRAMES do
if(frame == self) then
table.remove(_FRAMES, k)
break
end
end
if(#_FRAMES == 0) then
OnRangeFrame:Hide()
end
end
end
oUF:AddElement('freebRange', nil, Enable, Disable)
| gpl-2.0 |
rekotc/game-engine-demo | Source/GCC4/3rdParty/luaplus51-all/Src/Modules/wxLua/samples/scribble.wx.lua | 4 | 28449 | -------------------------------------------------------------------------=---
-- Name: scribble.wx.lua
-- Purpose: 'Scribble' wxLua sample
-- Author: J Winwood, John Labenski
-- Modified by: Thanks to Peter Prade and Nick Trout for fixing
-- the bug in the for loop in DrawPoints()
-- Created: 16/11/2001
-- RCS-ID: $Id: scribble.wx.lua,v 1.27 2009/05/14 05:06:21 jrl1 Exp $
-- Copyright: (c) 2001 J Winwood. All rights reserved.
-- Licence: wxWidgets licence
-------------------------------------------------------------------------=---
-- Load the wxLua module, does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit
package.cpath = package.cpath..";./?.dll;./?.so;../lib/?.so;../lib/vc_dll/?.dll;../lib/bcc_dll/?.dll;../lib/mingw_dll/?.dll;"
require("wx")
frame = nil -- the main wxFrame
scrollwin = nil -- the child of the frame
panel = nil -- the child wxPanel of the wxScrolledWindow to draw on
mouseDown = false -- left mouse button is down
pointsList = {} -- list of the points added to the drawing
-- pointsList[segment] =
-- { pen = {colour = {r, g, b}, width = 1, style = N},
-- [n] = {x = x_pos, y = x_pos} }
isModified = false -- has the drawing been modified
redrawRequired = true -- redraw the image
lastDrawn = 0 -- last segment that was drawn or 0 to redraw all
fileName = "" -- filename to save to
ID_SAVEBITMAP = wx.wxID_HIGHEST + 1
ID_IMAGESIZE = wx.wxID_HIGHEST + 2
ID_PENCOLOUR = wx.wxID_HIGHEST + 3
ID_PENWIDTH = wx.wxID_HIGHEST + 4
ID_PENSTYLE = wx.wxID_HIGHEST + 5
ID_PENWIDTH_SPINCTRL = wx.wxID_HIGHEST + 6
currentPen = wx.wxPen(wx.wxRED_PEN); currentPen:SetWidth(3)
penStyles = { wx.wxSOLID, wx.wxDOT, wx.wxLONG_DASH, wx.wxSHORT_DASH,
wx.wxDOT_DASH, wx.wxBDIAGONAL_HATCH, wx.wxCROSSDIAG_HATCH,
wx.wxFDIAGONAL_HATCH, wx.wxCROSS_HATCH, wx.wxHORIZONTAL_HATCH,
wx.wxVERTICAL_HATCH }
penStyleNames = { "Solid style", "Dotted style", "Long dashed style", "Short dashed style",
"Dot and dash style", "Backward diagonal hatch", "Cross-diagonal hatch",
"Forward diagonal hatch", "Cross hatch", "Horizontal hatch",
"Vertical hatch" }
screenWidth, screenHeight = wx.wxDisplaySize()
bitmap = wx.wxBitmap(screenWidth, screenHeight)
-- ---------------------------------------------------------------------------
-- Pen to table and back functions
-- ---------------------------------------------------------------------------
function PenToTable(pen)
local c = pen:GetColour()
local t = { colour = { c:Red(), c:Green(), c:Blue() }, width = pen:GetWidth(), style = pen:GetStyle() }
c:delete()
return t
end
function TableToPen(penTable)
local c = wx.wxColour(unpack(penTable.colour))
local pen = wx.wxPen(c, penTable.width, penTable.style)
c:delete()
return pen
end
-- ---------------------------------------------------------------------------
-- Drawing functions
-- ---------------------------------------------------------------------------
function DrawPoints(drawDC)
if lastDrawn == 0 then
drawDC:Clear()
end
local start_index = 1
if lastDrawn > 1 then start_index = lastDrawn end
for list_index = start_index, #pointsList do
local listValue = pointsList[list_index]
local pen = TableToPen(listValue.pen)
drawDC:SetPen(pen)
pen:delete()
local point = listValue[1]
local last_point = point
for point_index = 2, #listValue do
point = listValue[point_index]
drawDC:DrawLine(last_point.x, last_point.y, point.x, point.y)
last_point = point
end
end
lastDrawn = #pointsList
drawDC:SetPen(wx.wxNullPen)
end
function DrawLastPoint(drawDC)
if #pointsList >= 1 then
local listValue = pointsList[#pointsList]
local count = #listValue
if count > 1 then
local pen = TableToPen(listValue.pen)
drawDC:SetPen(pen)
pen:delete()
local pt1 = listValue[count-1]
local pt2 = listValue[count]
drawDC:DrawLine(pt1.x, pt1.y, pt2.x, pt2.y)
end
end
end
function DrawBitmap(bmp)
local memDC = wx.wxMemoryDC() -- create off screen dc to draw on
memDC:SelectObject(bmp) -- select our bitmap to draw into
DrawPoints(memDC)
memDC:SelectObject(wx.wxNullBitmap) -- always release bitmap
memDC:delete() -- ALWAYS delete() any wxDCs created when done
end
function OnPaint(event)
-- ALWAYS create wxPaintDC in wxEVT_PAINT handler, even if unused
local dc = wx.wxPaintDC(panel)
if bitmap and bitmap:Ok() then
if redrawRequired then
DrawBitmap(bitmap)
redrawRequired = false
end
dc:DrawBitmap(bitmap, 0, 0, false)
end
dc:delete() -- ALWAYS delete() any wxDCs created when done
end
function GetBitmap()
local w, h = panel:GetClientSizeWH()
local bmp = wx.wxBitmap(w, h)
lastDrawn = 0 -- force redrawing all points
DrawBitmap(bmp)
lastDrawn = 0 -- force redrawing all points
return bmp
end
-- ---------------------------------------------------------------------------
-- Mouse functions
-- ---------------------------------------------------------------------------
function OnLeftDown(event)
local pointItem = {pen = PenToTable(currentPen), {x = event:GetX(), y = event:GetY()}}
table.insert(pointsList, pointItem)
if (not panel:HasCapture()) then panel:CaptureMouse() end
mouseDown = true
isModified = true
end
function OnLeftUp(event)
if mouseDown then
-- only add point if the mouse moved since DrawLine(1,2,1,2) won't draw anyway
if (#pointsList[#pointsList] > 1) then
local point = { x = event:GetX(), y = event:GetY() }
table.insert(pointsList[#pointsList], point)
else
pointsList[#pointsList] = nil
end
if panel:HasCapture() then panel:ReleaseMouse() end
mouseDown = false
redrawRequired = true
panel:Refresh()
end
end
function OnMotion(event)
frame:SetStatusText(string.format("%d, %d", event:GetX(), event:GetY()), 1)
if event:LeftIsDown() then
local point = { x = event:GetX(), y = event:GetY() }
table.insert(pointsList[#pointsList], point)
mouseDown = true
-- draw directly on the panel, we'll draw on the bitmap in OnLeftUp
local drawDC = wx.wxClientDC(panel)
DrawLastPoint(drawDC)
drawDC:delete()
elseif panel:HasCapture() then -- just in case we lost focus somehow
panel:ReleaseMouse()
mouseDown = false
end
end
-- ---------------------------------------------------------------------------
-- File functions
-- ---------------------------------------------------------------------------
function QuerySaveChanges()
local dialog = wx.wxMessageDialog( frame,
"Document has changed. Do you wish to save the changes?",
"wxLua Scribble Save Changes?",
wx.wxYES_NO + wx.wxCANCEL + wx.wxCENTRE + wx.wxICON_QUESTION )
local result = dialog:ShowModal()
dialog:Destroy()
if result == wx.wxID_YES then
if not SaveChanges() then return wx.wxID_CANCEL end
end
return result
end
function LoadScribbles(fileName)
pointsList = {}
lastDrawn = 0
return ((pcall(dofile, fileName)) ~= nil)
end
-- modified from the lua sample save.lua
function savevar(fh, n, v)
if v ~= nil then
fh:write(n, "=")
if type(v) == "string" then
fh:write(format("%q", v))
elseif type(v) == "table" then
fh:write("{}\n")
for r,f in pairs(v) do
if type(r) == 'string' then
savevar(fh, n.."."..r, f)
else
savevar(fh, n.."["..r.."]", f)
end
end
else
fh:write(tostring(v))
end
fh:write("\n")
end
end
function SaveScribbles()
local fh, msg = io.open(fileName, "w+")
if fh then
savevar(fh, "pointsList", pointsList)
fh:close()
return true
else
wx.wxMessageBox("Unable to save file:'"..fileName.."'.\n"..msg,
"wxLua Scribble Save error",
wx.wxOK + wx.wxICON_ERROR,
frame)
return false
end
end
function Open()
local fileDialog = wx.wxFileDialog(frame,
"Open wxLua scribble file",
"",
"",
"Scribble files(*.scribble)|*.scribble|All files(*)|*",
wx.wxOPEN + wx.wxFILE_MUST_EXIST)
local result = false
if fileDialog:ShowModal() == wx.wxID_OK then
fileName = fileDialog:GetPath()
result = LoadScribbles(fileName)
if result then
frame:SetTitle("wxLua Scribble - " .. fileName)
end
end
fileDialog:Destroy()
return result
end
function SaveAs()
local fileDialog = wx.wxFileDialog(frame,
"Save wxLua scribble file",
"",
"",
"Scribble files(*.scribble)|*.scribble|All files(*)|*",
wx.wxSAVE + wx.wxOVERWRITE_PROMPT)
local result = false
if fileDialog:ShowModal() == wx.wxID_OK then
fileName = fileDialog:GetPath()
result = SaveScribbles()
if result then
frame:SetTitle("wxLua Scribble - " .. fileName)
end
end
fileDialog:Destroy()
return result
end
function SaveChanges()
local saved = false
if fileName == "" then
saved = SaveAs()
else
saved = SaveScribbles()
end
return saved
end
function SetBitmapSize()
local w, h = bitmap:GetWidth(), bitmap:GetHeight()
local ok = true
repeat
local s = wx.wxGetTextFromUser("Enter the image size to use as 'width height'", "Set new image size",
string.format("%d %d", bitmap:GetWidth(), bitmap:GetHeight()), frame)
if (#s == 0) then
return false -- they canceled the dialog
end
w, h = string.match(s, "(%d+) (%d+)")
w = tonumber(w)
h = tonumber(h)
if (w == nil) or (h == nil) or (w < 2) or (h < 2) or (w > 10000) or (h > 10000) then
wx.wxMessageBox("Please enter two positive numbers < 10000 for the width and height separated by a space",
"Invalid image width or height", wx.wxOK + wx.wxCENTRE + wx.wxICON_ERROR, frame)
ok = false
end
until ok
-- resize all the drawing objects
bitmap:delete()
bitmap = wx.wxBitmap(w, h)
panel:SetSize(w, h)
scrollwin:SetScrollbars(1, 1, w, h)
return true
end
-- ---------------------------------------------------------------------------
-- The main program
-- ---------------------------------------------------------------------------
function main()
frame = wx.wxFrame( wx.NULL, wx.wxID_ANY, "wxLua Scribble",
wx.wxDefaultPosition, wx.wxSize(450, 450),
wx.wxDEFAULT_FRAME_STYLE )
-- -----------------------------------------------------------------------
-- Create the menubar
local fileMenu = wx.wxMenu()
fileMenu:Append(wx.wxID_NEW, "&New...\tCtrl+N", "Begin a new drawing")
fileMenu:Append(wx.wxID_OPEN, "&Open...\tCtrl+O", "Open an existing drawing")
fileMenu:AppendSeparator()
fileMenu:Append(wx.wxID_SAVE, "&Save\tCtrl+S", "Save the drawing lines")
fileMenu:Append(wx.wxID_SAVEAS, "Save &as...\tAlt+S", "Save the drawing lines to a new file")
fileMenu:Append(ID_SAVEBITMAP, "Save &bitmap...", "Save the drawing as a bitmap file")
fileMenu:AppendSeparator()
fileMenu:Append(wx.wxID_EXIT, "E&xit\tCtrl+Q", "Quit the program")
local editMenu = wx.wxMenu()
editMenu:Append(ID_IMAGESIZE, "Set image size...", "Set the size of the image to draw on")
editMenu:Append(ID_PENCOLOUR, "Set pen &color...\tCtrl+R", "Set the color of the pen to draw with")
editMenu:Append(ID_PENWIDTH, "Set pen &width...\tCtrl+T", "Set width of the pen to draw with")
-- Pen styles really only work for long lines, when you change direction the styles
-- blur into each other and just look like a solid line.
--editMenu:Append(ID_PENSTYLE, "Set &Style\tCtrl+Y", "Set style of the pen to draw with")
editMenu:AppendSeparator()
editMenu:Append(wx.wxID_COPY, "Copy to clipboard\tCtrl-C", "Copy current image to the clipboard")
editMenu:AppendSeparator()
editMenu:Append(wx.wxID_UNDO, "&Undo\tCtrl-Z", "Undo last drawn segment")
local helpMenu = wx.wxMenu()
helpMenu:Append(wx.wxID_ABOUT, "&About...", "About the wxLua Scribble Application")
local menuBar = wx.wxMenuBar()
menuBar:Append(fileMenu, "&File")
menuBar:Append(editMenu, "&Edit")
menuBar:Append(helpMenu, "&Help")
frame:SetMenuBar(menuBar)
-- -----------------------------------------------------------------------
-- Create the toolbar
toolBar = frame:CreateToolBar(wx.wxNO_BORDER + wx.wxTB_FLAT + wx.wxTB_DOCKABLE)
-- Note: Ususally the bmp size isn't necessary, but the HELP icon is not the right size in MSW
local toolBmpSize = toolBar:GetToolBitmapSize()
-- Note: Each temp bitmap returned by the wxArtProvider needs to be garbage collected
-- and there is no way to call delete() on them. See collectgarbage("collect")
-- at the end of this function.
toolBar:AddTool(wx.wxID_NEW, "New", wx.wxArtProvider.GetBitmap(wx.wxART_NORMAL_FILE, wx.wxART_MENU, toolBmpSize), "Create an empty scribble")
toolBar:AddTool(wx.wxID_OPEN, "Open", wx.wxArtProvider.GetBitmap(wx.wxART_FILE_OPEN, wx.wxART_MENU, toolBmpSize), "Open an existing scribble")
toolBar:AddTool(wx.wxID_SAVE, "Save", wx.wxArtProvider.GetBitmap(wx.wxART_FILE_SAVE, wx.wxART_MENU, toolBmpSize), "Save the current scribble")
toolBar:AddTool(wx.wxID_SAVEAS, "Save as", wx.wxArtProvider.GetBitmap(wx.wxART_NEW_DIR, wx.wxART_MENU, toolBmpSize), "Save the current scribble to a new file")
toolBar:AddSeparator()
toolBar:AddTool(wx.wxID_COPY, "Copy", wx.wxArtProvider.GetBitmap(wx.wxART_COPY, wx.wxART_MENU, toolBmpSize), "Copy image to clipboard")
toolBar:AddSeparator()
toolBar:AddTool(wx.wxID_UNDO, "Undo", wx.wxArtProvider.GetBitmap(wx.wxART_UNDO, wx.wxART_MENU, toolBmpSize), "Undo last line drawn")
toolBar:AddSeparator()
penWidthSpinCtrl = wx.wxSpinCtrl(toolBar, ID_PENWIDTH_SPINCTRL, tostring(currentPen:GetWidth()),
wx.wxDefaultPosition, wx.wxDefaultSize,
wx.wxSP_ARROW_KEYS, 1, 100, currentPen:GetWidth())
local w, h = penWidthSpinCtrl:GetSizeWH()
penWidthSpinCtrl:SetSize(3*h, -1)
penWidthSpinCtrl:SetToolTip("Set pen width in pixels")
toolBar:AddControl(penWidthSpinCtrl)
toolBar:AddSeparator()
local c = currentPen:GetColour()
colourPicker = wx.wxColourPickerCtrl(toolBar, ID_PENCOLOUR, c,
wx.wxDefaultPosition, toolBmpSize:op_sub(wx.wxSize(2,2)),
wx.wxCLRP_DEFAULT_STYLE)
c:delete()
colourPicker:SetToolTip("Choose pen color")
colourPicker:Connect(wx.wxEVT_COMMAND_COLOURPICKER_CHANGED,
function(event)
local c = event:GetColour()
currentPen:SetColour(c)
c:delete()
end)
toolBar:AddControl(colourPicker)
toolBar:AddSeparator()
-- Create a custom control to choose some common colours.
local colourWin_height = math.floor(h/2)*2 -- round to be divisible by two
local colourWin = wx.wxControl(toolBar, wx.wxID_ANY,
wx.wxDefaultPosition, wx.wxSize(4*colourWin_height, colourWin_height),
wx.wxBORDER_NONE)
-- Need help in GTK to ensure that it's positioned correctly
colourWin:SetMinSize(wx.wxSize(4*colourWin_height, colourWin_height))
local colourWinColours = {
"black", "grey", "brown", "red", "orange", "green", "blue", "violet",
"white", "light grey", "tan", "pink", "yellow", "turquoise", "sky blue", "maroon"
}
-- Note: this bitmap is local, but is used in the event handlers
local colourWinBmp = wx.wxBitmap(4*colourWin_height, colourWin_height)
do
local memDC = wx.wxMemoryDC()
memDC:SelectObject(colourWinBmp)
memDC:SetPen(wx.wxBLACK_PEN)
local w, h = colourWin:GetClientSizeWH()
local w2 = math.floor(w/8)
local h2 = math.floor(h/2)
for j = 1, 2 do
for i = 1, 8 do
local colour = wx.wxColour(colourWinColours[i + 8*(j-1)])
local brush = wx.wxBrush(colour, wx.wxSOLID)
memDC:SetBrush(brush)
memDC:DrawRectangle(w2*(i-1), h2*(j-1), w2, h2)
brush:delete()
colour:delete()
end
end
memDC:SelectObject(wx.wxNullBitmap)
memDC:delete()
end
colourWin:Connect(wx.wxEVT_ERASE_BACKGROUND,
function(event)
local dc = wx.wxClientDC(colourWin)
dc:DrawBitmap(colourWinBmp, 0, 0, false) -- this is our background
dc:delete()
end)
colourWin:Connect(wx.wxEVT_LEFT_DOWN,
function(event)
local x, y = event:GetPositionXY()
local w, h = colourWin:GetClientSizeWH()
local i = math.floor(8*x/w)+1 + 8*math.floor(2*y/h)
if colourWinColours[i] then
local c = wx.wxColour(colourWinColours[i])
currentPen:SetColour(c)
colourPicker:SetColour(c)
c:delete()
end
end)
colourWin:Connect(wx.wxEVT_MOTION,
function(event)
local x, y = event:GetPositionXY()
local w, h = colourWin:GetClientSizeWH()
local i = math.floor(8*x/w)+1 + 8*math.floor(2*y/h)
if colourWinColours[i] then
local s = "Set pen color : "..colourWinColours[i]
if colourWin:GetToolTip() ~= s then
colourWin:SetToolTip(s)
end
end
end)
toolBar:AddControl(colourWin)
-- once all the tools are added, layout all the tools
toolBar:Realize()
-- -----------------------------------------------------------------------
-- Create the statusbar
local statusBar = frame:CreateStatusBar(2)
local status_width = statusBar:GetTextExtent("88888, 88888")
frame:SetStatusWidths({ -1, status_width })
frame:SetStatusText("Welcome to wxLua Scribble.")
-- Create a wxScrolledWindow to hold drawing window, it will fill the frame
scrollwin = wx.wxScrolledWindow(frame, wx.wxID_ANY)
scrollwin:SetScrollbars(1, 1, bitmap:GetWidth(), bitmap:GetHeight())
-- Create the panel that's the correct size of the bitmap on the scrolled
-- window so we don't have to worry about calculating the scrolled position
-- for drawing and the mouse position.
panel = wx.wxPanel(scrollwin, wx.wxID_ANY, wx.wxDefaultPosition, wx.wxSize(bitmap:GetWidth(), bitmap:GetHeight()))
panel:Connect(wx.wxEVT_PAINT, OnPaint)
panel:Connect(wx.wxEVT_ERASE_BACKGROUND, function(event) end) -- do nothing
panel:Connect(wx.wxEVT_LEFT_DOWN, OnLeftDown )
panel:Connect(wx.wxEVT_LEFT_UP, OnLeftUp )
panel:Connect(wx.wxEVT_MOTION, OnMotion )
-- -----------------------------------------------------------------------
-- File menu events
frame:Connect(wx.wxID_NEW, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
if isModified and (QuerySaveChanges() == wx.wxID_CANCEL) then
return
end
local bmp_changed = SetBitmapSize()
if bmp_changed then
fileName = ""
frame:SetTitle("wxLua Scribble")
pointsList = {}
lastDrawn = 0
redrawRequired = true
isModified = false
panel:Refresh()
end
end )
frame:Connect(wx.wxID_OPEN, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
if isModified and (QuerySaveChanges() == wx.wxID_CANCEL) then
return
end
if Open() then
isModified = false
end
redrawRequired = true
panel:Refresh()
end )
frame:Connect(wx.wxID_SAVE, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local saved = false
if fileName == "" then
saved = SaveAs()
else
saved = SaveScribbles()
end
if saved then
isModified = false
end
end )
frame:Connect(wx.wxID_SAVEAS, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
if SaveAs() then
isModified = false
end
end )
frame:Connect(ID_SAVEBITMAP, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local fileDialog = wx.wxFileDialog(frame,
"Save wxLua scribble file as",
"",
"",
"PNG (*.png)|*.png|PCX (*.pcx)|*.pcx|Bitmap (*.bmp)|*.bmp|Jpeg (*.jpg,*.jpeg)|*.jpg,*.jpeg|Tiff (*.tif,*.tiff)|*.tif,*.tiff",
wx.wxSAVE + wx.wxOVERWRITE_PROMPT)
if fileDialog:ShowModal() == wx.wxID_OK then
local bmp = GetBitmap()
local img = bmp:ConvertToImage()
if not img:SaveFile(fileDialog:GetPath()) then
wx.wxMessageBox("There was a problem saving the image file\n"..fileDialog:GetPath(),
"Error saving image",
wx.wxOK + wx.wxICON_ERROR,
frame )
end
bmp:delete()
img:delete()
end
fileDialog:Destroy()
end )
frame:Connect(wx.wxID_EXIT, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
frame:Close(true)
end )
-- -----------------------------------------------------------------------
-- Edit menu events
frame:Connect(ID_IMAGESIZE, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local bmp_changed = SetBitmapSize()
lastDrawn = 0
redrawRequired = true
panel:Refresh()
end )
frame:Connect(ID_PENCOLOUR, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local oldColour = currentPen:GetColour()
local c = wx.wxGetColourFromUser(frame, oldColour,
"wxLua Scribble")
oldColour:delete()
if c:Ok() then -- returns invalid colour if canceled
currentPen:SetColour(c)
colourPicker:SetColour(c)
end
c:delete()
end )
frame:Connect(ID_PENWIDTH, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local ret = wx.wxGetNumberFromUser("Select pen width in pixels", "Width", "wxLua Scribble",
currentPen:GetWidth(), 1, 100, frame)
if ret > 0 then -- returns -1 if canceled
currentPen:SetWidth(ret)
end
end )
frame:Connect(ID_PENWIDTH_SPINCTRL, wx.wxEVT_COMMAND_SPINCTRL_UPDATED,
function (event)
currentPen:SetWidth(event:GetInt())
end )
frame:Connect(ID_PENSTYLE, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local ret = wx.wxGetSingleChoice("Select pen style", "wxLua Scribble",
penStyleNames,
frame)
for n = 1, #penStyleNames do
if penStyleNames[n] == ret then
currentPen:SetStyle(penStyles[n])
break
end
end
end )
frame:Connect(wx.wxID_COPY, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local clipBoard = wx.wxClipboard.Get()
if clipBoard and clipBoard:Open() then
local bmp = GetBitmap()
clipBoard:SetData(wx.wxBitmapDataObject(bmp))
bmp:delete()
clipBoard:Close()
end
end)
frame:Connect(wx.wxID_UNDO, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
if #pointsList then
pointsList[#pointsList] = nil
lastDrawn = 0
redrawRequired = true
panel:Refresh()
end
if #pointsList == 0 then
isModified = false
end
end )
-- -----------------------------------------------------------------------
-- Help menu events
frame:Connect(wx.wxID_ABOUT, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
wx.wxMessageBox('This is the "About" dialog of the Scribble wxLua Sample.\n'..
wxlua.wxLUA_VERSION_STRING.." built with "..wx.wxVERSION_STRING,
"About wxLua Scribble",
wx.wxOK + wx.wxICON_INFORMATION,
frame )
end )
-- -----------------------------------------------------------------------
frame:Connect(wx.wxEVT_CLOSE_WINDOW,
function (event)
local isOkToClose = true
if isModified then
local dialog = wx.wxMessageDialog( frame,
"Save changes before exiting?",
"Save Changes?",
wx.wxYES_NO + wx.wxCANCEL + wx.wxCENTRE + wx.wxICON_QUESTION )
local result = dialog:ShowModal()
dialog:Destroy()
if result == wx.wxID_CANCEL then
return
elseif result == wx.wxID_YES then
isOkToClose = SaveChanges()
end
end
if isOkToClose then
-- prevent paint events using the memDC during closing
bitmap:delete()
bitmap = nil
-- ensure the event is skipped to allow the frame to close
event:Skip()
end
end )
-- delete all locals vars like the temporary wxArtProvider bitmaps
collectgarbage("collect")
frame:Show(true)
end
main()
-- Call wx.wxGetApp():MainLoop() last to start the wxWidgets event loop,
-- otherwise the wxLua program will exit immediately.
-- Does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit since the
-- MainLoop is already running or will be started by the C++ program.
wx.wxGetApp():MainLoop()
| lgpl-3.0 |
n0xus/darkstar | scripts/zones/Temenos/npcs/Armoury_Crate.lua | 25 | 8574 | -----------------------------------
-- Area: Temenos
-- NPC: Armoury Crate
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Temenos/TextIDs");
require("scripts/globals/limbus");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CofferID = npc:getID();
local CofferType=0;
local lootID=0;
local InstanceRegion=0;
local addtime=0;
local DespawnOtherCoffer=false;
local MimicID=0;
local X = npc:getXPos();
local Y = npc:getYPos();
local Z = npc:getZPos();
for coffer = 1,table.getn (ARMOURY_CRATES_LIST_TEMENOS),2 do
if (ARMOURY_CRATES_LIST_TEMENOS[coffer] == CofferID-16928768) then
CofferType=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][1];
InstanceRegion=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][2];
addtime=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][3];
DespawnOtherCoffer=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][4];
MimicID=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][5];
lootID=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][6];
end
end
printf("CofferID : %u",CofferID-16928768);
printf("Coffertype %u",CofferType);
printf("InstanceRegion: %u",InstanceRegion);
printf("addtime: %u",addtime);
printf("MimicID: %u",MimicID);
printf("lootID: %u",lootID);
local coffer = CofferID-16928768;
if (CofferType == cTIME) then
player:addTimeToSpecialBattlefield(InstanceRegion,addtime);
elseif (CofferType == cITEM) then
if (InstanceRegion == Central_Temenos_4th_Floor and coffer~=79) then
local randmimic = math.random(1,24)
print("randmimic" ..randmimic);
if ( randmimic < 19) then
local MimicList={16928986,16928987,16928988,16928989,16928990,16928991,16928992,16928993,16928994,16928995,16928996,16928997,16928998,16928999,16929000,16929001,16929002,16929003};
GetMobByID(MimicList[randmimic]):setSpawn(X,Y,Z);
SpawnMob(MimicList[randmimic]):setPos(X,Y,Z);
GetMobByID(MimicList[randmimic]):updateClaim(player);
else
player:BCNMSetLoot(lootID,InstanceRegion,CofferID);
player:getBCNMloot();
end
-- despawn les coffer du meme groupe
for coffer = 1, table.getn (ARMOURY_CRATES_LIST_TEMENOS), 2 do
if (ARMOURY_CRATES_LIST_TEMENOS[coffer+1][5] == MimicID) then
GetNPCByID(16928768+ARMOURY_CRATES_LIST_TEMENOS[coffer]):setStatus(STATUS_DISAPPEAR);
end
end
else
player:BCNMSetLoot(lootID, InstanceRegion, CofferID);
player:getBCNMloot();
end
elseif (CofferType == cRESTORE) then
player:RestoreAndHealOnBattlefield(InstanceRegion);
elseif (CofferType == cMIMIC) then
if (coffer == 284) then
GetMobByID(16928844):setSpawn(X,Y,Z);
SpawnMob(16928844):setPos(X,Y,Z)
GetMobByID(16928844):updateClaim(player);
elseif (coffer == 321) then
GetMobByID(16928853):setSpawn(X,Y,Z);
SpawnMob(16928853):setPos(X,Y,Z);
GetMobByID(16928853):updateClaim(player);
elseif (coffer == 348) then
GetMobByID(16928862):setSpawn(X,Y,Z);
SpawnMob(16928862):setPos(X,Y,Z);
GetMobByID(16928862):updateClaim(player);
elseif (coffer == 360) then
GetMobByID(16928871):setSpawn(X,Y,Z);
SpawnMob(16928871):setPos(X,Y,Z);
GetMobByID(16928871):updateClaim(player);
elseif (coffer == 393) then
GetMobByID(16928880):setSpawn(X,Y,Z);
SpawnMob(16928880):setPos(X,Y,Z);
GetMobByID(16928880):updateClaim(player);
elseif (coffer == 127) then
GetMobByID(16928889):setSpawn(X,Y,Z);
SpawnMob(16928889):setPos(X,Y,Z);
GetMobByID(16928889):updateClaim(player);
elseif (coffer == 123) then
GetMobByID(16928894):setSpawn(X,Y,Z);
SpawnMob(16928894):setPos(X,Y,Z);
GetMobByID(16928894):updateClaim(player);
end
end
if (DespawnOtherCoffer == true) then
HideArmouryCrates(InstanceRegion,TEMENOS);
if (InstanceRegion==Temenos_Eastern_Tower) then --despawn mob of the current floor
if (coffer == 173 or coffer == 215 or coffer == 284 or coffer == 40) then
--floor 1
if (GetMobAction(16928840) > 0) then DespawnMob(16928840); end
if (GetMobAction(16928841) > 0) then DespawnMob(16928841); end
if (GetMobAction(16928842) > 0) then DespawnMob(16928842); end
if (GetMobAction(16928843) > 0) then DespawnMob(16928843); end
GetNPCByID(16929228):setStatus(STATUS_NORMAL);
elseif (coffer == 174 or coffer == 216 or coffer == 321 or coffer == 45) then
--floor 2
if (GetMobAction(16928849) > 0) then DespawnMob(16928849); end
if (GetMobAction(16928850) > 0) then DespawnMob(16928850); end
if (GetMobAction(16928851) > 0) then DespawnMob(16928851); end
if (GetMobAction(16928852) > 0) then DespawnMob(16928852); end
GetNPCByID(16929229):setStatus(STATUS_NORMAL);
elseif (coffer == 181 or coffer == 217 or coffer == 348 or coffer == 46) then
--floor 3
if (GetMobAction(16928858) > 0) then DespawnMob(16928858); end
if (GetMobAction(16928859) > 0) then DespawnMob(16928859); end
if (GetMobAction(16928860) > 0) then DespawnMob(16928860); end
if (GetMobAction(16928861) > 0) then DespawnMob(16928861); end
GetNPCByID(16929230):setStatus(STATUS_NORMAL);
elseif (coffer == 182 or coffer == 236 or coffer == 360 or coffer == 47) then
--floor 4
if (GetMobAction(16928867) > 0) then DespawnMob(16928867); end
if (GetMobAction(16928868) > 0) then DespawnMob(16928868); end
if (GetMobAction(16928869) > 0) then DespawnMob(16928869); end
if (GetMobAction(16928870) > 0) then DespawnMob(16928870); end
GetNPCByID(16929231):setStatus(STATUS_NORMAL);
elseif (coffer == 183 or coffer == 261 or coffer == 393 or coffer == 68) then
--floor 5
if (GetMobAction(16928876) > 0) then DespawnMob(16928876); end
if (GetMobAction(16928877) > 0) then DespawnMob(16928877); end
if (GetMobAction(16928878) > 0) then DespawnMob(16928878); end
if (GetMobAction(16928879) > 0) then DespawnMob(16928879); end
GetNPCByID(16929232):setStatus(STATUS_NORMAL);
elseif (coffer == 277 or coffer == 190 or coffer == 127 or coffer == 69) then
--floor 6
if (GetMobAction(16928885) > 0) then DespawnMob(16928885); end
if (GetMobAction(16928886) > 0) then DespawnMob(16928886); end
if (GetMobAction(16928887) > 0) then DespawnMob(16928887); end
if (GetMobAction(16928888) > 0) then DespawnMob(16928888); end
GetNPCByID(16929233):setStatus(STATUS_NORMAL);
elseif (coffer == 70 or coffer == 123) then
--floor 7
if (GetMobAction(16928892) > 0) then DespawnMob(16928892); end
if (GetMobAction(16928893) > 0) then DespawnMob(16928893); end
GetNPCByID(16929234):setStatus(STATUS_NORMAL);
end
end
end
npc:setStatus(STATUS_DISAPPEAR);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
n0xus/darkstar | scripts/zones/Windurst_Walls/npcs/Pakke-Pokke.lua | 38 | 1040 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Pakke-Pokke
-- Type: Standard NPC
-- @zone: 239
-- @pos -3.464 -17.25 125.635
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0059);
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 |
sprinkler/rainmachine-developer-resources | api-lua/log.lua | 1 | 1725 | debugMode = true
_PLUGIN_NAME = "rainmachine-api"
local function dump(t)
if t == nil then return "nil" end
local sep = ""
local str = "{ "
for k,v in pairs(t) do
local val
if type(v) == "table" then
val = dump(v)
elseif type(v) == "function" then
val = "(function)"
elseif type(v) == "string" then
val = string.format("%q", v)
else
val = tostring(v)
end
str = str .. sep .. tostring(k) .. "=" .. val
sep = ", "
end
str = str .. " }"
return str
end
function L(msg, ...)
local str
local level = 50
if type(msg) == "table" then
str = tostring(msg.prefix or _PLUGIN_NAME) .. ": " .. tostring(msg.msg)
level = msg.level or level
else
str = _PLUGIN_NAME .. ": " .. tostring(msg)
end
str = string.gsub(str, "%%(%d+)", function( n )
n = tonumber(n, 10)
if n < 1 or n > #arg then return "nil" end
local val = arg[n]
if type(val) == "table" then
return dump(val)
elseif type(val) == "string" then
return string.format("%q", val)
end
return tostring(val)
end
)
print(str)
-- luup.log(str, level)
end
function D(msg, ...)
if debugMode then
L( { msg=msg,prefix=_PLUGIN_NAME .. "(debug)::" }, ... )
end
end
function print_table(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end | gpl-3.0 |
n0xus/darkstar | scripts/zones/Sauromugue_Champaign/npcs/Cavernous_Maw.lua | 16 | 2985 | -----------------------------------
-- Area: Sauromugue Champaign
-- NPC: Cavernous Maw
-- Teleports Players to Sauromugue_Champaign_S
-- @pos 369 8 -227 120
-----------------------------------
package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/missions");
require("scripts/globals/campaign");
require("scripts/zones/Sauromugue_Champaign/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) == false) then
player:startEvent(500,2);
elseif (ENABLE_WOTG == 1 and hasMawActivated(player,2)) then
if (player:getCurrentMission(WOTG) == BACK_TO_THE_BEGINNING and
(player:getQuestStatus(CRYSTAL_WAR, CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, THE_TIGRESS_STRIKES) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, FIRES_OF_DISCONTENT) == QUEST_COMPLETED)) then
player:startEvent(501);
else
player:startEvent(904);
end
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID:",csid);
-- printf("RESULT:",option);
if (csid == 500) then
local r = math.random(1,3);
player:addKeyItem(PURE_WHITE_FEATHER);
player:messageSpecial(KEYITEM_OBTAINED,PURE_WHITE_FEATHER);
player:completeMission(WOTG,CAVERNOUS_MAWS);
player:addMission(WOTG,BACK_TO_THE_BEGINNING);
if (r == 1) then
player:addNationTeleport(MAW,1);
toMaw(player,1); -- go to Batallia_Downs[S]
elseif (r == 2) then
player:addNationTeleport(MAW,2);
toMaw(player,3); -- go to Rolanberry_Fields_[S]
elseif (r == 3) then
player:addNationTeleport(MAW,4);
toMaw(player,5); -- go to Sauromugue_Champaign_[S]
end;
elseif (csid == 904 and option == 1) then
toMaw(player,5); -- go to Sauromugue_Champaign_[S]
elseif (csid == 501) then
player:completeMission(WOTG, BACK_TO_THE_BEGINNING);
player:addMission(WOTG, CAIT_SITH);
player:addTitle(CAIT_SITHS_ASSISTANT);
toMaw(player,5);
end;
end; | gpl-3.0 |
n0xus/darkstar | scripts/zones/Balgas_Dais/npcs/Burning_Circle.lua | 17 | 2294 | -----------------------------------
-- Area: Balga's Dais
-- NPC: Burning Circle
-- Balga's Dais Burning Circle
-- @pos 299 -123 345 146
-------------------------------------
package.loaded["scripts/zones/Balgas_Dais/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/bcnm");
require("scripts/zones/Balgas_Dais/TextIDs");
---- 0: Rank 2 Final Mission for Bastok "The Emissary" and Sandy "Journey Abroad"
---- 1: Steamed Sprouts (BCNM 40, Star Orb)
---- 2: Divine Punishers (BCNM 60, Moon Orb)
---- 3: Saintly Invitation (Windurst mission 6-2)
---- 4: Treasure and Tribulations (BCNM 50, Comet Orb)
---- 5: Shattering Stars (MNK)
---- 6: Shattering Stars (WHM)
---- 7: Shattering Stars (SMN)
---- 8: Creeping Doom (BCNM 30, Sky Orb)
---- 9: Charming Trio (BCNM 20, Cloudy Orb)
---- 10: Harem Scarem (BCNM 30, Sky Orb)
---- 11: Early Bird Catches the Wyrm (KSNM 99, Themis Orb)
---- 12: Royal Succession (BCNM 40, Star Orb)
---- 13: Rapid Raptors (BCNM 50, Comet Orb)
---- 14: Wild Wild Whiskers (BCNM 60, Moon Orb)
---- 15: Season's Greetings (KSNM 30, Clotho Orb)
---- 16: Royale Ramble (KSNM 30, Lachesis Orb)
---- 17: Moa Constrictors (KSNM 30, Atropos Orb
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
alexandre-mbm/SimTools | RandomWeather/Lua/vstruct/io/f.lua | 4 | 3238 | -- IEEE floating point floats, doubles and quads
local struct = require "vstruct"
local io = require "vstruct.io"
local sizes = {
[4] = {1, 8, 23};
[8] = {1, 11, 52};
[16] = {1, 15, 112};
}
local function reader(data, size_exp, size_fraction)
local fraction, exponent, sign
local endian = io("endianness", "get") == "big" and ">" or "<"
-- Split the unsigned integer into the 3 IEEE fields
local bits = struct.unpack(endian.." m"..#data, data)[1]
local fraction = struct.implode({unpack(bits, 1, size_fraction)}, size_fraction)
local exponent = struct.implode({unpack(bits, size_fraction+1, size_fraction+size_exp)}, size_exp)
local sign = bits[#bits] and -1 or 1
-- special case: exponent is all 1s
if exponent == 2^size_exp-1 then
-- significand is 0? +- infinity
if fraction == 0 then
return sign * math.huge
-- otherwise it's NaN
else
return 0/0
end
end
-- restore the MSB of the significand, unless it's a subnormal number
if exponent ~= 0 then
fraction = fraction + (2 ^ size_fraction)
else
exponent = 1
end
-- remove the exponent bias
exponent = exponent - 2 ^ (size_exp - 1) + 1
-- Decrease the size of the exponent rather than make the fraction (0.5, 1]
exponent = exponent - size_fraction
return sign * math.ldexp(fraction, exponent)
end
local function writer(value, size_exp, size_fraction)
local fraction, exponent, sign
local width = (size_exp + size_fraction + 1)/8
local endian = io("endianness", "get") == "big" and ">" or "<"
local bias = 2^(size_exp-1)-1
if value < 0
or 1/value == -math.huge then -- handle the case of -0
sign = true
value = -value
else
sign = false
end
-- special case: value is infinite
if value == math.huge then
exponent = bias+1
fraction = 0
-- special case: value is NaN
elseif value ~= value then
exponent = bias+1
fraction = 2^(size_fraction-1)
--special case: value is 0
elseif value == 0 then
exponent = -bias
fraction = 0
else
fraction,exponent = math.frexp(value)
-- subnormal number
if exponent+bias <= 1 then
fraction = fraction * 2^(size_fraction+(exponent+bias)-1)
exponent = -bias
else
-- remove the most significant bit from the fraction and adjust exponent
fraction = fraction - 0.5
exponent = exponent - 1
-- turn the fraction into an integer
fraction = fraction * 2^(size_fraction+1)
end
end
-- add the exponent bias
exponent = exponent + bias
local bits = struct.explode(fraction)
local bits_exp = struct.explode(exponent)
for i=1,size_exp do
bits[size_fraction+i] = bits_exp[i]
end
bits[size_fraction+size_exp+1] = sign
return struct.pack(endian.."m"..width, {bits})
end
local f = {}
function f.width(n)
n = tonumber(n)
assert(n == 4 or n == 8 or n == 16
, "format 'f' only supports widths 4 (float), 8 (double) and 16 (quad)")
return n
end
function f.unpack(_, buf, width)
return reader(buf, unpack(sizes[width], 2))
end
function f.pack(_, data, width)
return writer(data, unpack(sizes[width], 2))
end
return f
| mit |
n0xus/darkstar | scripts/globals/items/plate_of_barnacle_paella.lua | 36 | 1576 | -----------------------------------------
-- ID: 5974
-- Item: Plate of Barnacle Paella
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- HP 40
-- Vitality 5
-- Mind -1
-- Charisma -1
-- Defense % 25 Cap 150
-- Undead Killer 5
-----------------------------------------
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,5974);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 40);
target:addMod(MOD_VIT, 5);
target:addMod(MOD_MND, -1);
target:addMod(MOD_CHR, -1);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 150);
target:addMod(MOD_UNDEAD_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 40);
target:delMod(MOD_VIT, 5);
target:delMod(MOD_MND, -1);
target:delMod(MOD_CHR, -1);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 150);
target:delMod(MOD_UNDEAD_KILLER, 5);
end;
| gpl-3.0 |
Python1320/wire | lua/wire/stools/adv_input.lua | 9 | 2315 | WireToolSetup.setCategory( "Input, Output/Keyboard Interaction" )
WireToolSetup.open( "adv_input", "Adv. Input", "gmod_wire_adv_input", nil, "Adv Inputs" )
if CLIENT then
language.Add( "tool.wire_adv_input.name", "Adv. Input Tool (Wire)" )
language.Add( "tool.wire_adv_input.desc", "Spawns a adv. input for use with the wire system." )
language.Add( "tool.wire_adv_input.0", "Primary: Create/Update Adv. Input" )
language.Add( "WireAdvInputTool_keymore", "Increase:" )
language.Add( "WireAdvInputTool_keyless", "Decrease:" )
language.Add( "WireAdvInputTool_toggle", "Toggle" )
language.Add( "WireAdvInputTool_value_min", "Minimum:" )
language.Add( "WireAdvInputTool_value_max", "Maximum:" )
language.Add( "WireAdvInputTool_value_start", "Start at:" )
language.Add( "WireAdvInputTool_speed", "Change per second:" )
end
WireToolSetup.BaseLang("Adv. Inputs")
WireToolSetup.SetupMax( 20 )
if SERVER then
ModelPlug_Register("Numpad")
function TOOL:GetConVars()
return self:GetClientNumber( "keymore" ), self:GetClientNumber( "keyless" ), self:GetClientNumber( "toggle" ),
self:GetClientNumber( "value_min" ), self:GetClientNumber( "value_max" ), self:GetClientNumber( "value_start" ),
self:GetClientNumber( "speed" )
end
-- Uses default WireToolObj:MakeEnt's WireLib.MakeWireEnt function
end
TOOL.ClientConVar = {
model = "models/beer/wiremod/numpad.mdl",
modelsize = "",
keymore = "3",
keyless = "1",
toggle = "0",
value_min = "0",
value_max = "10",
value_start = "5",
speed = "1",
}
function TOOL.BuildCPanel( panel )
WireToolHelpers.MakeModelSizer(panel, "wire_adv_input_modelsize")
ModelPlug_AddToCPanel(panel, "Numpad", "wire_adv_input", true)
panel:AddControl( "Numpad", {Label = "#WireAdvInputTool_keymore", Command = "wire_adv_input_keymore"})
panel:AddControl( "Numpad", {Label = "#WireAdvInputTool_keyless", Command = "wire_adv_input_keyless"})
panel:CheckBox("#WireAdvInputTool_toggle", "wire_adv_input_toggle")
panel:NumSlider("#WireAdvInputTool_value_min", "wire_adv_input_value_min", -50, 50, 0)
panel:NumSlider("#WireAdvInputTool_value_max", "wire_adv_input_value_max", -50, 50, 0)
panel:NumSlider("#WireAdvInputTool_value_start", "wire_adv_input_value_start", -50, 50, 0)
panel:NumSlider("#WireAdvInputTool_speed", "wire_adv_input_speed", 0.1, 50, 1)
end
| apache-2.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-Highmaul/localization.en.lua | 1 | 3110 | local L
---------------
-- Kargath Bladefist --
---------------
L= DBM:GetModLocalization(1128)
L:SetTimerLocalization({
timerSweeperCD = DBM_CORE_AUTO_TIMER_TEXTS.next:format((GetSpellInfo(177776)))
})
L:SetOptionLocalization({
timerSweeperCD = DBM_CORE_AUTO_TIMER_OPTIONS.next:format(177776),
countdownSweeper = DBM_CORE_AUTO_COUNTDOWN_OPTION_TEXT:format(177776)
})
---------------------------
-- The Butcher --
---------------------------
L= DBM:GetModLocalization(971)
---------------------------
-- Tectus, the Living Mountain --
---------------------------
L= DBM:GetModLocalization(1195)
L:SetMiscLocalization({
pillarSpawn = "RISE, MOUNTAINS!"
})
------------------
-- Brackenspore, Walker of the Deep --
------------------
L= DBM:GetModLocalization(1196)
L:SetOptionLocalization({
InterruptCounter = "Reset Decay counter after",
Two = "After two casts",
Three = "After three casts",
Four = "After four casts"
})
--------------
-- Twin Ogron --
--------------
L= DBM:GetModLocalization(1148)
L:SetOptionLocalization({
PhemosSpecial = "Play countdown sound for Phemos' cooldowns",
PolSpecial = "Play countdown sound for Pol's cooldowns",
PhemosSpecialVoice = "Play spoken alerts for Phemos' abilities using selected voice pack",
PolSpecialVoice = "Play spoken alerts for Pol's abilities using selected voice pack"
})
--------------------
--Koragh --
--------------------
L= DBM:GetModLocalization(1153)
L:SetWarningLocalization({
specWarnExpelMagicFelFades = "Fel fading in 5s - move to start"
})
L:SetOptionLocalization({
specWarnExpelMagicFelFades = "Show special warning to move to start position for $spell:172895 expiring"
})
L:SetMiscLocalization({
supressionTarget1 = "I will crush you!",
supressionTarget2 = "Silence!",
supressionTarget3 = "Quiet!",
supressionTarget4 = "I will tear you in half!"
})
--------------------------
-- Imperator Mar'gok --
--------------------------
L= DBM:GetModLocalization(1197)
L:SetTimerLocalization({
timerNightTwistedCD = "Next Night-Twisted Adds"
})
L:SetOptionLocalization({
GazeYellType = "Set yell type for Gaze of the Abyss",
Countdown = "Countdown until expires",
Stacks = "Stacks as they are applied",
timerNightTwistedCD = "Show timer for Next Night-Twisted Faithful",
--Auto generated, don't copy to non english files, not needed.
warnBranded = DBM_CORE_AUTO_ANNOUNCE_OPTIONS.stack:format(156225),
warnResonance = DBM_CORE_AUTO_ANNOUNCE_OPTIONS.spell:format(156467),
warnMarkOfChaos = DBM_CORE_AUTO_ANNOUNCE_OPTIONS.spell:format(158605),
warnForceNova = DBM_CORE_AUTO_ANNOUNCE_OPTIONS.spell:format(157349),
warnAberration = DBM_CORE_AUTO_ANNOUNCE_OPTIONS.spell:format(156471)
--Auto generated, don't copy to non english files, not needed.
})
L:SetMiscLocalization({
BrandedYell = "Branded (%d) %dy",
GazeYell = "Gaze fading in %d",
GazeYell2 = "Gaze (%d) on %s",
PlayerDebuffs = "Closest to Glimpse"
})
-------------
-- Trash --
-------------
L = DBM:GetModLocalization("HighmaulTrash")
L:SetGeneralLocalization({
name = "Highmaul Trash"
})
| gpl-2.0 |
n0xus/darkstar | scripts/globals/items/bowl_of_sopa_de_pez_blanco.lua | 35 | 1549 | -----------------------------------------
-- ID: 4601
-- Item: Bowl of Sopa de Pez Blanco
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 12
-- Dexterity 6
-- Mind -4
-- Accuracy 3
-- Ranged ACC % 7
-- Ranged ACC Cap 10
-----------------------------------------
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,4601);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 12);
target:addMod(MOD_DEX, 6);
target:addMod(MOD_MND, -4);
target:addMod(MOD_ACC, 3);
target:addMod(MOD_FOOD_RACCP, 7);
target:addMod(MOD_FOOD_RACC_CAP, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 12);
target:delMod(MOD_DEX, 6);
target:delMod(MOD_MND, -4);
target:delMod(MOD_ACC, 3);
target:delMod(MOD_FOOD_RACCP, 7);
target:delMod(MOD_FOOD_RACC_CAP, 10);
end;
| gpl-3.0 |
chawan/RepHelper | content.lua | 1 | 128311 | function RPH_InitEnFactionGains(guildName, guildCapBase)
local zone = {}
-- Kalimdor
zone.Mulgore = 7
zone.Darkshore = 62
zone.Thunder_Bluff = 88
zone.The_Exodar = 103
zone.Echo_Isles = 463
zone.Camp_Narache = 462
zone.Silithus = 81
zone.Felwood = 77
zone.Mount_Hyjal = 198
zone.Teldrassil = 57
zone.Moonglade = 80
zone.Azshara = 76
zone.Uldum = 249
zone.Durotar = 1
zone.Kalimdor = 12
zone.Orgrimmar = 85
zone.Desolace = 66
zone.Bloodmyst_Isle = 106
zone.Dustwallow_Marsh = 70
zone.UnGoro_Crater = 78
zone.Winterspring = 83
zone.Northern_Barrens = 10
zone.Valley_of_Trials = 461
zone.Ashenvale = 63
zone.Ammen_Vale = 468
zone.Stonetalon_Mountains = 65
zone.Feralas = 69
zone.Darnassus = 89
zone.Thousand_Needles = 64
zone.Southern_Barrens = 199
zone.AhnQiraj_The_Fallen_Kingdom = 327
zone.Azuremyst_Isle = 97
zone.Molten_Front = 338
zone.Shadowglen = 460
zone.Tanaris = 71
-- The Broken Isles
zone.Broken_Isles = 619
zone.Broken_Shore = 646
zone.Highmountain = 650
zone.Dalaran = 625
zone.Valsharah = 641
zone.Stormheim = 634
zone.Suramar = 680
zone.Azuna = 630
zone.Eye_of_Azshara = 790
-- Eastern Kingdoms
zone.Wetlands = 56
zone.Blasted_Lands = 17
zone.Deathknell = 465
zone.Dun_Morogh = 27
zone.Tol_Barad_Peninsula = 245
zone.Silvermoon_City = 110
zone.Duskwood = 47
zone.Loch_Modan = 48
zone.Shimmering_Expanse = 205
zone.Arathi_Highlands = 14
zone.New_Tinkertown = 469
zone.Hillsbrad_Foothills = 25
zone.Undercity = 90
zone.Ghostlands = 95
zone.Eastern_Plaguelands = 23
zone.Gilneas = 179
zone.Burning_Steppes = 36
zone.The_Scarlet_Enclave = 124
zone.Eversong_Woods = 94
zone.Searing_Gorge = 32
zone.Tirisfal_Glades = 18
zone.Western_Plaguelands = 22
zone.Westfall = 52
zone.Coldridge_Valley = 427
zone.The_Cape_of_Stranglethorn = 210
zone.Vashjir = 203
zone.Kelpthar_Forest = 201
zone.Northshire = 425
zone.Gilneas_City = 202
zone.Eastern_Kingdoms = 13
zone.Twilight_Highlands = 241
zone.Redridge_Mountains = 49
zone.The_Hinterlands = 26
zone.Swamp_of_Sorrows = 51
zone.Silverpine_Forest = 21
zone.Abyssal_Depths = 204
zone.Sunstrider_Isle = 467
zone.Badlands = 15
zone.Ruins_of_Gilneas = 217
zone.Stormwind_City = 84
zone.Northern_Stranglethorn = 50
zone.Elwynn_Forest = 37
zone.Ruins_of_Gilneas_City = 218
zone.Stranglethorn_Vale = 224
zone.Isle_of_QuelDanas = 122
zone.Ironforge = 87
zone.Deadwind_Pass = 42
zone.Tol_Barad = 244
-- Outlands
zone.Zangarmarsh = 102
zone.Netherstorm = 109
zone.Shattrath_City = 111
zone.Hellfire_Peninsula = 100
zone.Terokkar_Forest = 108
zone.Shadowmoon_Valley = 104
zone.Outland = 101
zone.Nagrand = 107
zone.Blades_Edge_Mountains = 105
-- Northrend
zone.Icecrown = 118
zone.Wintergrasp = 123
zone.The_Storm_Peaks = 120
zone.Dalaran = 125
zone.Hrothgars_Landing = 170
zone.Howling_Fjord = 117
zone.Sholazar_Basin = 119
zone.Grizzly_Hills = 116
zone.Northrend = 113
zone.Crystalsong_Forest = 127
zone.Dragonblight = 115
zone.ZulDrak = 121
zone.Borean_Tundra = 114
-- The Maelstrom
zone.Kezan = 194
zone.Deepholm = 207
zone.The_Lost_Isles = 174
zone.The_Maelstrom = 276
-- Pandaria
zone.Pandaria = 424
zone.Kun_Lai_Summit = 379
zone.Valley_of_the_FourvWind = 376
zone.Krasarang_Wilds = 418
zone.Vale_of_Eternal_Blossoms = 390
zone.The_Veiled_Stair = 433
zone.Isle_of_Giants = 507
zone.Townlong_Steppes = 388
zone.The_Jade_Forest = 371
zone.Dread_Wastes = 422
zone.Timeless_Isle = 554
zone.The_Wandering_Isle = 378
zone.Isle_of_Thunder = 504
-- Draenor
zone.Ashran = 588
zone.Lunarfall = 579
zone.Gorgrond = 543
zone.Draenor = 572
zone.Spires_of_Arak = 542
zone.Warspear = 624
zone.Shadowmoon_Valley = 539
zone.Tanaan_Jungle_Assault_on_the_Dark_Portal = 577
zone.Tanaan_Jungle = 534
zone.Talador = 535
zone.Stormshield = 622
zone.Frostwall = 585
zone.Frostfire_Ridge = 525
zone.Nagrand_WoD = 550
-- Battlegrounds
zone.Temple_of_Kotmogu = 417
zone.Alterac_Valley = 91
zone.Eye_of_the_Storm = 112
zone.The_Battle_for_Gilneas = 275
zone.Warsong_Gulch = 92
zone.Twin_Peaks = 206
zone.Silvershard_Mines = 423
zone.Strand_of_the_Ancients = 128
zone.Isle_of_Conquest = 169
zone.Arathi_Basin = 93
zone.Deepwind_Gorge = 519
-- Scenarios
zone.Battle_on_the_High_Seas = 524
zone.Greenstone_Village = 448
zone.Domination_Point_H = 498
zone.Arena_of_Annihilation = 480
zone.Blood_in_the_Snow = 523
zone.Assault_on_Zanvess = 451
zone.A_Little_Patience = 487
zone.Theramores_Fall_A = 483
zone.The_Secrets_of_Ragefire = 522
zone.Crypt_of_Forgotten_Kings = 481
zone.Brewmoon_Festival = 452
zone.A_Brewing_Storm = 447
zone.Celestial_Tournament = 571
zone.Theramores_Fall_H = 416
zone.Unga_Ingoo = 450
zone.Lions_Landing_A = 486
zone.Dark_Heart_of_Pandaria = 520
zone.Dagger_in_the_Dark = 488
-- Classic Dungeons
zone.Blackrock_Spire = 250
zone.The_Deadmines = 291
zone.Stratholme = 317
zone.Maraudon = 280
zone.Wailing_Caverns = 279
zone.Razorfen_Downs = 300
zone.Ragefire_Chasm = 213
zone.The_Temple_of_AtalHakkar = 220
zone.Razorfen_Kraul = 301
zone.ZulFarrak = 219
zone.Blackfathom_Deeps = 221
zone.Dire_Maul = 234
zone.The_Stockade = 225
zone.Uldaman = 230
zone.Blackrock_Depths = 242
zone.Shadowfang_Keep = 310
zone.Gnomeregan = 226
-- Classic Raids
zone.Molten_Core = 232
zone.Blackwing_Lair = 287
zone.Ruins_of_AhnQiraj = 247
zone.Temple_of_AhnQiraj = 319
-- Burning Crusade Dungeons
zone.The_Underbog = 262
zone.The_Steamvault = 263
zone.Sethekk_Halls = 258
zone.The_Botanica = 266
zone.Mana_Tombs = 272
zone.Hellfire_Ramparts = 347
zone.The_Black_Morass = 273
zone.The_Shattered_Halls = 246
zone.Magisters_Terrace = 348
zone.The_Mechanar = 267
zone.The_Blood_Furnace = 261
zone.The_Slave_Pens = 265
zone.Shadow_Labyrinth = 260
zone.Auchenai_Crypts = 256
zone.Old_Hillsbrad_Foothills = 274
zone.The_Arcatraz = 269
-- Burning Crusade Raids
zone.Black_Temple = 339
zone.Serpentshrine_Cavern = 332
zone.Magtheridons_Lair = 331
zone.Karazhan = 350
zone.Gruuls_Lair = 330
zone.The_Eye = 334
zone.Hyjal_Summit = 329
zone.Sunwell_Plateau = 335
-- Wrath Dungeons
zone.Utgarde_Pinnacle = 136
zone.Gundrak = 153
zone.The_Oculus = 142
zone.DrakTharon_Keep = 160
zone.Azjol_Nerub = 157
zone.The_Forge_of_Souls = 183
zone.Ahnkahet_The_Old_Kingdom = 132
zone.The_Violet_Hold = 168
zone.The_Nexus = 129
zone.Trial_of_the_Champion = 171
zone.Pit_of_Saron = 184
zone.Halls_o_Lightning = 138
zone.The_Culling_of_Stratholme = 130
zone.Utgarde_Keep = 133
zone.Halls_of_Stone = 140
zone.Halls_of_Reflection = 185
-- Wrath Raids
zone.The_Eye_of_Eternity = 141
zone.The_Ruby_Sanctum = 200
zone.Icecrown_Citadel = 186
zone.Naxxramas = 162
zone.Ulduar = 147
zone.Onyxias_Lair = 248
zone.Trial_of_the_Crusader = 172
zone.Vault_of_Archavon = 156
zone.The_Obsidian_Sanctum = 155
-- Cataclysm Dungeons
zone.Lost_City_of_thevTolvir = 277
zone.End_Time = 401
zone.The_Vortex_Pinnacle = 325
zone.Halls_of_Origination = 297
zone.Throne_of_the_Tides = 322
zone.ZulGurub = 337
zone.Grim_Batol = 293
zone.ZulAman = 333
zone.The_Stonecore = 324
zone.Well_of_Eternity = 398
zone.Blackrock_Caverns = 283
zone.Hour_of_Twilight = 399
-- Cataclysm Raids
zone.Firelands = 367
zone.Dragon_Soul = 409
zone.Blackwing_Descent = 285
zone.Throne_of_the_Four_Winds = 328
zone.The_Bastion_of_Twilight = 294
zone.Baradin_Hold = 282
-- Pandaria Dungeons
zone.Gate_of_the_Setting_Sun = 437
zone.Shado_pan_Monastery = 443
zone.Scholomance = 476
zone.Stormstout_Brewery = 439
zone.Temple_of_the_Jade_Serpen = 429
zone.MoguShan_Palace = 453
zone.Scarlet_Monastery = 435
zone.Scarlet_Halls = 431
zone.Siege_of_Niuzao_Temple = 457
-- Pandaria Raids
zone.Siege_of_Orgrimmar = 556
zone.Throne_of_Thunder = 508
zone.Terrace_of_Endless_Spring = 456
zone.Mogushan_Vaults = 471
zone.Heart_of_Fear = 474
-- Draenor Dungeons
zone.Upper_Blackrock_Spire = 616
zone.Skyreach = 601
zone.The_Everbloom = 620
zone.Bloodmaul_Slag_Mines = 573
zone.Shadowmoon_Burial_Grounds = 574
zone.Auchindoun = 593
zone.Grimrail_Depot = 606
zone.Iron_Docks = 595
-- Draenor Raids
zone.Blackrock_Foundry = 596
zone.Highmaul = 610
zone.Hellfire_Citadel = 661
-- Legion Dungeons
zone.Vault_of_the_Wardens = 710
zone.The_Arcway = 749
zone.Cathedral_of_Eternal_Night = 845
zone.Darkheart_Thicket = 733
zone.Halls_of_Valor = 703
zone.Eye_of_Azshara = 713
zone.Maw_of_Souls = 706
zone.Violet_Hold = 732
zone.Return_to_Karazhan = 809
zone.Seat_of_The_Triumvirate = 903
zone.Neltharions_Lair = 731
zone.Black_Rook_Hold = 751
zone.Court_of_Stars = 761
-- Legion Raids
zone.The_Emerald_Nightmare = 777
zone.Tomb_of_Sargeras = 850
zone.Trial_of_Valor = 806
zone.Antorus_the_Burning_Throne = 909
zone.The_Nighthold = 764
if (RPH_IsAlliance) then
-- Aliance Cities
-- Darnassus 69
RPH_AddQuest(69, 4, 8, 1, 250, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(69, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(69, 4, 8, 3, 250, "nil", RPH_LIMIT_TYPE_Fish)
RPH_AddQuest(69, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(69, 4, 8, 7386, 18.75, {[17423] = 5})
RPH_AddQuest(69, 4, 8, 6881, 2.5, {[17423] = 1})
RPH_AddQuest(69, 4, 8, 6943, 10, {[17504] = 1})
RPH_AddQuest(69, 4, 8, 6942, 10, {[17502] = 1})
RPH_AddQuest(69, 4, 8, 6941, 10, {[17503] = 1})
RPH_AddQuest(69, 4, 8, 7027, 2.5)
RPH_AddQuest(69, 4, 8, 7026, 2.5, {[17643] = 1})
RPH_AddQuest(69, 4, 8, 6781, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(69, 4, 8, 250, {[45714] = 1})
RPH_AddItems(69, 4, 8, 62.5, {[4] = 1})
RPH_AddSpell(69, 1, 8, 5, 1000)
-- Exodar 930
RPH_AddQuest(930, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(930, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(930, 4, 8, 7386, 18.75, {[17423] = 5})
RPH_AddQuest(930, 4, 8, 6881, 2.5, {[17423] = 1})
RPH_AddQuest(930, 4, 8, 6943, 10, {[17504] = 1})
RPH_AddQuest(930, 4, 8, 6942, 10, {[17502] = 1})
RPH_AddQuest(930, 4, 8, 6941, 10, {[17503] = 1})
RPH_AddQuest(930, 4, 8, 7027, 2.5)
RPH_AddQuest(930, 4, 8, 7026, 2.5, {[17643] = 1})
RPH_AddQuest(930, 4, 8, 6781, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(930, 4, 8, 250, {[45715] = 1})
RPH_AddItems(930, 4, 8, 62.5, {[4] = 1})
RPH_AddSpell(930, 1, 8, 5, 1000)
-- Gnomeregan 54
RPH_AddQuest(54,4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(54,4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(54,4, 8, 7386, 18.75, {[17423] = 5})
RPH_AddQuest(54,4, 8, 6881, 2.5, {[17423] = 1})
RPH_AddQuest(54,4, 8, 6943, 10, {[17504] = 1})
RPH_AddQuest(54,4, 8, 6942, 10, {[17502] = 1})
RPH_AddQuest(54,4, 8, 6941, 10, {[17503] = 1})
RPH_AddQuest(54,4, 8, 7027, 2.5)
RPH_AddQuest(54,4, 8, 7026, 2.5, {[17643] = 1})
RPH_AddQuest(54,4, 8, 6781, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(54,4, 8, 250, {[45716] = 1})
RPH_AddItems(54,4, 8, 62.5, {[4] = 1})
RPH_AddSpell(54,1, 8, 5, 1000)
-- Ironforge 47
RPH_AddQuest(47,4, 8, 1, 250, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(47,4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(47,4, 8, 3, 250, "nil", RPH_LIMIT_TYPE_Fish)
RPH_AddQuest(47,4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(47,4, 8, 7386, 18.75, {[17423] = 5})
RPH_AddQuest(47,4, 8, 6881, 2.5, {[17423] = 1})
RPH_AddQuest(47,4, 8, 6943, 10, {[17504] = 1})
RPH_AddQuest(47,4, 8, 6942, 10, {[17502] = 1})
RPH_AddQuest(47,4, 8, 6941, 10, {[17503] = 1})
RPH_AddQuest(47,4, 8, 7027, 2.5)
RPH_AddQuest(47,4, 8, 7026, 2.5, {[17643] = 1})
RPH_AddQuest(47,4, 8, 6781, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(47,4, 8, 250, {[45717] = 1})
RPH_AddItems(47,4, 8, 62.5, {[4] = 1})
RPH_AddSpell(47,1, 8, 5, 1000)
-- Stormwind 301
RPH_AddQuest(72,4, 8, 1, 250, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(72,4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(72,4, 8, 3, 250, "nil", RPH_LIMIT_TYPE_Fish)
RPH_AddQuest(72,4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(72,4, 8, 7386, 18.75, {[17423] = 5})
RPH_AddQuest(72,4, 8, 6881, 2.5, {[17423] = 1})
RPH_AddQuest(72,4, 8, 6943, 10, {[17504] = 1})
RPH_AddQuest(72,4, 8, 6942, 10, {[17502] = 1})
RPH_AddQuest(72,4, 8, 6941, 10, {[17503] = 1})
RPH_AddQuest(72,4, 8, 7027, 2.5)
RPH_AddQuest(72,4, 8, 7026, 2.5, {[17643] = 1})
RPH_AddQuest(72,4, 8, 6781, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(72,4, 8, 250, {[45718] = 1})
RPH_AddItems(72,4, 8, 62.5, {[4] = 1})
RPH_AddSpell(72,1, 8, 5, 1000)
-- Gilneas 545
RPH_AddQuest(1134,4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(1134,4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
---- spillover from Other
RPH_AddSpell(1134,1, 8, 5, 1000)
-- Tushui Pandaren 1353
RPH_AddQuest(1353, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(1353, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
---- spillover from Other
RPH_AddSpell(1353, 1, 8, 5, 1000)
-- Alliance Forces
-- Silverwing Sentinels 890
RPH_AddGeneral(890, 4, 8, "Warsong Gulch flag capture", 100, "Warsong Gulch flag capture", "Every time your team captures a flag you gain 100 reputation")
RPH_AddGeneral(890, 4, 8, "Warsong Gulch victory", 100, "Warsong Gulch victory", "Every time your team wins you gain 100 reputation")
RPH_AddGeneral(890, 4, 8, "Warsong Gulch loss", 35, "Warsong Gulch loss", "Every time your team lose you gain 35 reputation")
-- Stormpike Guard 730
RPH_AddQuest(730, 4, 8, 7386, 18.75, {[17423] = 5})
RPH_AddQuest(730, 4, 8, 6881, 2.5, {[17423] = 1})
RPH_AddQuest(730, 4, 8, 6941, 10, {[17503] = 1})
RPH_AddQuest(730, 4, 8, 6942, 10, {[17502] = 1})
RPH_AddQuest(730, 4, 8, 6941, 10, {[17503] = 1})
RPH_AddQuest(730, 4, 8, 7027, 2.5)
RPH_AddQuest(730, 4, 8, 7026, 2.5, {[17643] = 1})
RPH_AddQuest(730, 4, 8, 6781, 2.5, {[17422] = 20})
-- The League of Arathor 509
RPH_AddGeneral(509, 4, 8, "Arathi Basin collect 100 Resources", 50, "Collect 100 Resources", "For every 100 resources your team collects you gain 50 reputation")
RPH_AddGeneral(509, 4, 8, "Arathi Basin win (1500 Resources)", 750, "Arathi Basin win (1500 Resources)", "If your team wins with 1500 resources you will earn a total of 750 reputation")
-- Bizmo's Brawlpub 1419
RPH_AddQuest(1419, 1, 8, 5, 1)
-- Outlands (Burning Crusade)
-- Honor Hold 946
RPH_AddInstance(946, 4, 5, zone.Hellfire_Ramparts, 600, false)
RPH_AddInstance(946, 6, 8, zone.Hellfire_Ramparts, 2000, true)
RPH_AddInstance(946, 4, 5, zone.The_Blood_Furnace, 750, false)
RPH_AddInstance(946, 6, 8, zone.The_Blood_Furnace, 2700, true)
--RPH_AddMob(946, 4, 7, 725, 5) This NPC is not in game. http://www.wowhead.com/npc=725
--RPH_AddMob(946, 4, 8, 725, 15) This NPC is not in game. http://www.wowhead.com/npc=725
RPH_AddInstance(946, 4, 8, zone.The_Shattered_Halls, 1600, false)
RPH_AddInstance(946, 4, 8, zone.The_Shattered_Halls, 2900, true)
RPH_AddMob(946, 4, 7, RPH_TXT.Mob.MoshOgg_Spellcrafter, 5, zone.Northern_Stranglethorn) -- Mosh'Ogg Spellcrafter ID=710
RPH_AddMob(946, 4, 8, RPH_TXT.Mob.MoshOgg_Spellcrafter, 15, zone.Northern_Stranglethorn) -- Mosh'Ogg Spellcrafter ID=710
RPH_AddQuest(946, 4, 7, 13410, 150)
-- Timewalking Commendation
RPH_AddItems(946, 1, 8, 500, {[129948] = 1})
-- Kurenai 978
RPH_AddQuest(978, 4, 8, 10476, 500, {[25433] = 10})
RPH_AddQuest(978, 4, 8, 11502, 500)
RPH_AddMob(978, 4, 8, RPH_TXT.Mob.BoulderfistOgre, 10, zone.Nagrand) -- Boulderfist Ogre ID=2562
RPH_AddMob(978, 4, 8, "Kil'sorrow Deathsworn, Cultist & Spellbinder", 10, zone.Nagrand)
RPH_AddMob(978, 4, 8, "Murkblood Scavenger", 2, zone.Nagrand)
RPH_AddMob(978, 4, 8, "Murkblood ", 10, zone.Nagrand)
RPH_AddMob(978, 4, 8, "Warmaul non-elite", 10, zone.Nagrand)
-- Northrend (WotLK)
-- Alliance Vanguard 1037
---- spillover from 1068
RPH_AddQuest(1037, 4, 8, 11391, 62.5)
---- spillover from 1126
RPH_AddQuest(1037, 4, 8, 12869, 62.5)
---- spillover from 1094
RPH_AddQuest(1037, 4, 8, 13757, 62.5, {[44981] = 1})
RPH_AddQuest(1037, 4, 8, 13759, 62.5)
RPH_AddQuest(1037, 4, 8, 13769, 62.5)
RPH_AddQuest(1037, 4, 8, 13857, 62.5)
RPH_AddQuest(1037, 4, 8, 13671, 62.5)
RPH_AddQuest(1037, 4, 8, 13625, 62.5)
RPH_AddQuest(1037, 4, 8, 13772, 62.5)
RPH_AddQuest(1037, 4, 8, 13772, 62.5)
---- spillover from 1050
RPH_AddQuest(1037, 4, 8, 11153, 62.5)
RPH_AddQuest(1037, 4, 8, 13309, 62.5)
RPH_AddQuest(1037, 4, 8, 13284, 62.5)
RPH_AddQuest(1037, 4, 8, 13336, 62.5)
RPH_AddQuest(1037, 4, 8, 13280, 62.5)
RPH_AddQuest(1037, 4, 8, 12444, 62.5)
RPH_AddQuest(1037, 4, 8, 12296, 62.5)
RPH_AddQuest(1037, 4, 8, 12289, 62.5)
RPH_AddQuest(1037, 4, 8, 12268, 62.5)
RPH_AddQuest(1037, 4, 8, 12244, 62.5)
---- spillover from tournament
RPH_AddQuest(1037, 4, 8, 13809, 125)
RPH_AddQuest(1037, 4, 8, 13810, 125)
RPH_AddQuest(1037, 4, 8, 13862, 125)
RPH_AddQuest(1037, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1037, 4, 8, 1, 400, false)
RPH_AddInstance(1037, 4, 8, 1, 800, true)
---- Timewalking Commendation
RPH_AddItems(1037, 1, 8, 500, {[129955] = 1})
-- Explorer's League 1068
RPH_AddQuest(1068, 4, 8, 11391, 125)
---- spillover from 1126
RPH_AddQuest(1068, 4, 8, 12869, 62.5)
---- spillover from 1094
RPH_AddQuest(1068, 4, 8, 13757, 62.5, {[44981] = 1})
RPH_AddQuest(1068, 4, 8, 13759, 62.5)
RPH_AddQuest(1068, 4, 8, 13769, 62.5)
RPH_AddQuest(1068, 4, 8, 13857, 62.5)
RPH_AddQuest(1068, 4, 8, 13671, 62.5)
RPH_AddQuest(1068, 4, 8, 13625, 62.5)
RPH_AddQuest(1068, 4, 8, 13772, 62.5)
RPH_AddQuest(1068, 4, 8, 13772, 62.5)
---- spillover from 1050
RPH_AddQuest(1068, 4, 8, 11153, 62.5)
RPH_AddQuest(1068, 4, 8, 13309, 62.5)
RPH_AddQuest(1068, 4, 8, 13284, 62.5)
RPH_AddQuest(1068, 4, 8, 13336, 62.5)
RPH_AddQuest(1068, 4, 8, 13280, 62.5)
RPH_AddQuest(1068, 4, 8, 12444, 62.5)
RPH_AddQuest(1068, 4, 8, 12296, 62.5)
RPH_AddQuest(1068, 4, 8, 12289, 62.5)
RPH_AddQuest(1068, 4, 8, 12268, 62.5)
RPH_AddQuest(1068, 4, 8, 12244, 62.5)
---- spillover from tournament
RPH_AddQuest(1068, 4, 8, 13809, 125)
RPH_AddQuest(1068, 4, 8, 13810, 125)
RPH_AddQuest(1068, 4, 8, 13862, 125)
RPH_AddQuest(1068, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1068, 4, 8, 1, 400, false)
RPH_AddInstance(1068, 4, 8, 1, 800, true)
-- The Frostborn 1126
RPH_AddQuest(1126, 4, 8, 12869, 125)
---- spillover from 1068
RPH_AddQuest(1126, 4, 8, 11391, 62.5)
---- spillover from 1094
RPH_AddQuest(1126, 4, 8, 13757, 62.5, {[44981] = 1})
RPH_AddQuest(1126, 4, 8, 13759, 62.5)
RPH_AddQuest(1126, 4, 8, 13769, 62.5)
RPH_AddQuest(1126, 4, 8, 13857, 62.5)
RPH_AddQuest(1126, 4, 8, 13671, 62.5)
RPH_AddQuest(1126, 4, 8, 13625, 62.5)
RPH_AddQuest(1126, 4, 8, 13772, 62.5)
RPH_AddQuest(1126, 4, 8, 13772, 62.5)
---- spillover from 1050
RPH_AddQuest(1126, 4, 8, 11153, 62.5)
RPH_AddQuest(1126, 4, 8, 13309, 62.5)
RPH_AddQuest(1126, 4, 8, 13284, 62.5)
RPH_AddQuest(1126, 4, 8, 13336, 62.5)
RPH_AddQuest(1126, 4, 8, 13280, 62.5)
RPH_AddQuest(1126, 4, 8, 12444, 62.5)
RPH_AddQuest(1126, 4, 8, 12296, 62.5)
RPH_AddQuest(1126, 4, 8, 12289, 62.5)
RPH_AddQuest(1126, 4, 8, 12268, 62.5)
RPH_AddQuest(1126, 4, 8, 12244, 62.5)
---- spillover from tournament
RPH_AddQuest(1126, 4, 8, 13809, 125)
RPH_AddQuest(1126, 4, 8, 13810, 125)
RPH_AddQuest(1126, 4, 8, 13862, 125)
RPH_AddQuest(1126, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1126, 4, 8, 1, 400, false)
RPH_AddInstance(1126, 4, 8, 1, 800, true)
-- The Silver Covenant 1094
RPH_AddQuest(1094, 4, 8, 13757, 125, {[44981] = 1})
RPH_AddQuest(1094, 4, 8, 13759, 125)
RPH_AddQuest(1094, 4, 8, 13769, 125)
RPH_AddQuest(1094, 4, 8, 13857, 125)
RPH_AddQuest(1094, 4, 8, 13671, 125)
RPH_AddQuest(1094, 4, 8, 13625, 125)
RPH_AddQuest(1094, 4, 8, 13772, 125)
RPH_AddQuest(1094, 4, 8, 13772, 125)
---- spillover from 1068
RPH_AddQuest(1094, 4, 8, 11391, 62.5)
---- spillover from 1126
RPH_AddQuest(1094, 4, 8, 12869, 62.5)
---- spillover from 1050
RPH_AddQuest(1094, 4, 8, 11153, 62.5)
RPH_AddQuest(1094, 4, 8, 13309, 62.5)
RPH_AddQuest(1094, 4, 8, 13284, 62.5)
RPH_AddQuest(1094, 4, 8, 13336, 62.5)
RPH_AddQuest(1094, 4, 8, 13280, 62.5)
RPH_AddQuest(1094, 4, 8, 12444, 62.5)
RPH_AddQuest(1094, 4, 8, 12296, 62.5)
RPH_AddQuest(1094, 4, 8, 12289, 62.5)
RPH_AddQuest(1094, 4, 8, 12268, 62.5)
RPH_AddQuest(1094, 4, 8, 12244, 62.5)
---- spillover from tournament
RPH_AddQuest(1094, 4, 8, 13809, 125)
RPH_AddQuest(1094, 4, 8, 13810, 125)
RPH_AddQuest(1094, 4, 8, 13862, 125)
RPH_AddQuest(1094, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1094, 4, 8, 1, 400, false)
RPH_AddInstance(1094, 4, 8, 1, 800, true)
-- Valiance Expedition 1050
RPH_AddQuest(1050, 4, 8, 11153, 125)
RPH_AddQuest(1050, 4, 8, 13309, 125)
RPH_AddQuest(1050, 4, 8, 13284, 125)
RPH_AddQuest(1050, 4, 8, 13336, 125)
RPH_AddQuest(1050, 4, 8, 13280, 125)
RPH_AddQuest(1050, 4, 8, 12444, 125)
RPH_AddQuest(1050, 4, 8, 12296, 125)
RPH_AddQuest(1050, 4, 8, 12289, 125)
RPH_AddQuest(1050, 4, 8, 12268, 125)
RPH_AddQuest(1050, 4, 8, 12244, 125)
---- spillover from 1068
RPH_AddQuest(1050, 4, 8, 11391, 62.5)
---- spillover from 1126
RPH_AddQuest(1050, 4, 8, 12869, 62.5)
---- spillover from 1094
RPH_AddQuest(1050, 4, 8, 13757, 62.5, {[44981] = 1})
RPH_AddQuest(1050, 4, 8, 13759, 62.5)
RPH_AddQuest(1050, 4, 8, 13769, 62.5)
RPH_AddQuest(1050, 4, 8, 13857, 62.5)
RPH_AddQuest(1050, 4, 8, 13671, 62.5)
RPH_AddQuest(1050, 4, 8, 13625, 62.5)
RPH_AddQuest(1050, 4, 8, 13772, 62.5)
RPH_AddQuest(1050, 4, 8, 13772, 62.5)
---- spillover from tournament
RPH_AddQuest(1050, 4, 8, 13809, 125)
RPH_AddQuest(1050, 4, 8, 13810, 125)
RPH_AddQuest(1050, 4, 8, 13862, 125)
RPH_AddQuest(1050, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1050, 4, 8, 1, 400, false)
RPH_AddInstance(1050, 4, 8, 1, 800, true)
-- Cataclysm
-- Wildhammer Clan 1174
---- from zone Twilight Highlands
RPH_AddQuest(1174, 4, 8, 28864, 250)
RPH_AddQuest(1174, 4, 8, 28861, 250)
RPH_AddQuest(1174, 4, 8, 28860, 250)
RPH_AddQuest(1174, 4, 8, 28862, 250)
RPH_AddQuest(1174, 4, 8, 28863, 350)
RPH_AddSpell(1174, 1, 8, 5, 1000)
RPH_AddSpell(1174, 1, 8, 5, 1800)
RPH_AddMob(1174, 1, 8, 1, 10, 5)
RPH_AddMob(1174, 1, 8, 1, 15, 6)
RPH_AddMob(1174, 1, 8, 4, 150, 5)
RPH_AddMob(1174, 1, 8, 4, 250, 6)
-- Timewalking Commendation
RPH_AddItems(1174, 1, 8, 500, {[133151] = 1})
-- Baradin's Wardens 1177
---- from zone Tol Barad
------ Tol Barad Peninsula
-------- Sargeant Parker (Base Quests)
RPH_AddQuest(1177, 4, 8, 28122, 250)
RPH_AddQuest(1177, 4, 8, 28658, 250)
RPH_AddQuest(1177, 4, 8, 28659, 250)
-------- 2nd Lieutenant Wansworth (Left Prison)
RPH_AddQuest(1177, 4, 8, 28665, 350)
RPH_AddQuest(1177, 4, 8, 28663, 350)
RPH_AddQuest(1177, 4, 8, 28664, 350)
-------- Commander Stevens (Right Prison)
RPH_AddQuest(1177, 4, 8, 28660, 350)
RPH_AddQuest(1177, 4, 8, 28662, 350)
RPH_AddQuest(1177, 4, 8, 28661, 250)
-------- Marshl Fallows (South Prison)
RPH_AddQuest(1177, 4, 8, 28670, 250)
RPH_AddQuest(1177, 4, 8, 28668, 350)
RPH_AddQuest(1177, 4, 8, 28669, 350)
------ Tol Barad Main
-------- Sergeant Gray
RPH_AddQuest(1177, 4, 8, 28275, 250)
RPH_AddQuest(1177, 4, 8, 28698, 250)
RPH_AddQuest(1177, 4, 8, 28697, 250)
RPH_AddQuest(1177, 4, 8, 28700, 250)
RPH_AddQuest(1177, 4, 8, 28695, 250)
RPH_AddQuest(1177, 4, 8, 28694, 250)
-------- Commander Marcus Johnson
RPH_AddQuest(1177, 4, 8, 28682, 250)
RPH_AddQuest(1177, 4, 8, 28685, 250)
RPH_AddQuest(1177, 4, 8, 28686, 250)
RPH_AddQuest(1177, 4, 8, 28687, 250)
RPH_AddQuest(1177, 4, 8, 28721, 250)
-------- Camp Coordinator Brack
RPH_AddQuest(1177, 4, 8, 28684, 250)
RPH_AddQuest(1177, 4, 8, 28680, 250)
RPH_AddQuest(1177, 4, 8, 28678, 250)
RPH_AddQuest(1177, 4, 8, 28679, 250)
RPH_AddQuest(1177, 4, 8, 28681, 350)
RPH_AddQuest(1177, 4, 8, 28683, 250)
-------- Lieutenant Farnsworth
RPH_AddQuest(1177, 4, 8, 28693, 250)
RPH_AddQuest(1177, 4, 8, 28691, 250)
RPH_AddQuest(1177, 4, 8, 28692, 250)
RPH_AddQuest(1177, 4, 8, 28690, 250)
RPH_AddQuest(1177, 4, 8, 28689, 250)
-- Mist of Pandaria
-- Pearlfin Jinyu 1242
RPH_AddQuest(1242, 1, 8, 5, 1)
-- Operation: Shieldwall 1376
RPH_AddQuest(1376, 1, 8, 32643, 400)
---- Lion's Landing
RPH_AddQuest(1376, 1, 8, 32148, 150)
RPH_AddQuest(1376, 1, 8, 32153, 300)
RPH_AddQuest(1376, 1, 8, 32149, 150)
RPH_AddQuest(1376, 1, 8, 32152, 150)
RPH_AddQuest(1376, 1, 8, 32150, 150)
RPH_AddQuest(1376, 1, 8, 32151, 150)
---- Domination Point
RPH_AddQuest(1376, 1, 8, 32143, 150)
RPH_AddQuest(1376, 1, 8, 32145, 300)
RPH_AddQuest(1376, 1, 8, 32146, 150)
RPH_AddQuest(1376, 1, 8, 32144, 300)
RPH_AddQuest(1376, 1, 8, 32142, 150)
---- Ruins of Ogudei
RPH_AddQuest(1376, 1, 8, 32347, 150)
RPH_AddQuest(1376, 1, 8, 32119, 150)
RPH_AddQuest(1376, 1, 8, 32122, 300)
RPH_AddQuest(1376, 1, 8, 32346, 150)
RPH_AddQuest(1376, 1, 8, 32115, 150)
RPH_AddQuest(1376, 1, 8, 32121, 150)
---- Bilgewater Beach
RPH_AddQuest(1376, 1, 8, 32154, 150)
RPH_AddQuest(1376, 1, 8, 32155, 150)
RPH_AddQuest(1376, 1, 8, 32159, 150)
RPH_AddQuest(1376, 1, 8, 32446, 150)
RPH_AddQuest(1376, 1, 8, 32157, 150)
RPH_AddQuest(1376, 1, 8, 32156, 150)
RPH_AddQuest(1376, 1, 8, 32158, 300)
RPH_AddQuest(1376, 1, 8, 32433, 150)
---- Beastmaster Quests
------ Huntsman Blake
RPH_AddQuest(1376, 1, 8, 32172, 200)
RPH_AddQuest(1376, 1, 8, 32170, 200)
RPH_AddQuest(1376, 1, 8, 32171, 200)
---- Timewalking Commendation
RPH_AddItems(1376, 1, 8, 300, {[143944] = 1})
-- 0
-- Kirin Tor Offensive 1387
RPH_AddQuest(1387, 4, 8, 32571, 150)
RPH_AddQuest(1387, 4, 8, 32558, 150)
RPH_AddQuest(1387, 4, 8, 32578, 200)
RPH_AddQuest(1387, 4, 8, 32525, 150)
RPH_AddQuest(1387, 4, 8, 32485, 150)
RPH_AddQuest(1387, 4, 8, 32634, 150)
RPH_AddQuest(1387, 4, 8, 32636, 150)
RPH_AddQuest(1387, 4, 8, 32555, 150)
RPH_AddQuest(1387, 4, 8, 32627, 150)
RPH_AddQuest(1387, 4, 8, 32576, 200)
RPH_AddQuest(1387, 4, 8, 32551, 150)
RPH_AddQuest(1387, 4, 8, 32543, 150)
RPH_AddQuest(1387, 4, 8, 32539, 150)
RPH_AddQuest(1387, 4, 8, 32537, 150)
RPH_AddQuest(1387, 4, 8, 32639, 150)
RPH_AddQuest(1387, 4, 8, 32554, 150)
RPH_AddQuest(1387, 4, 8, 32553, 150)
RPH_AddQuest(1387, 4, 8, 32585, 200)
RPH_AddQuest(1387, 4, 8, 32573, 150)
RPH_AddQuest(1387, 4, 8, 32635, 150)
RPH_AddQuest(1387, 4, 8, 32559, 150)
RPH_AddQuest(1387, 4, 8, 32607, 400)
RPH_AddQuest(1387, 4, 8, 32724, 200)
RPH_AddQuest(1387, 4, 8, 32570, 150)
RPH_AddQuest(1387, 4, 8, 32527, 150)
RPH_AddQuest(1387, 4, 8, 32540, 150)
RPH_AddQuest(1387, 4, 8, 32538, 150)
RPH_AddQuest(1387, 4, 8, 32631, 200)
RPH_AddQuest(1387, 4, 8, 32581, 200)
RPH_AddQuest(1387, 4, 8, 32528, 150)
RPH_AddQuest(1387, 4, 8, 32546, 150)
RPH_AddQuest(1387, 4, 8, 32560, 150)
RPH_AddQuest(1387, 4, 8, 32548, 150)
RPH_AddQuest(1387, 4, 8, 32552, 150)
RPH_AddQuest(1387, 4, 8, 32632, 150)
RPH_AddQuest(1387, 4, 8, 32638, 150)
RPH_AddQuest(1387, 4, 8, 32536, 150)
RPH_AddQuest(1387, 4, 8, 32586, 150)
RPH_AddQuest(1387, 4, 8, 32301, 150)
RPH_AddQuest(1387, 4, 8, 32588, 150)
RPH_AddQuest(1387, 4, 8, 32557, 150)
RPH_AddQuest(1387, 4, 8, 32637, 150)
RPH_AddQuest(1387, 4, 8, 32541, 150)
RPH_AddQuest(1387, 4, 8, 32544, 150)
RPH_AddQuest(1387, 4, 8, 32701, 1850)
RPH_AddQuest(1387, 4, 8, 32703, 1900)
RPH_AddQuest(1387, 4, 8, 32704, 2150)
RPH_AddQuest(1387, 4, 8, 32700, 1250)
RPH_AddQuest(1387, 4, 8, 32608, 400)
RPH_AddQuest(1387, 4, 8, 32582, 200)
RPH_AddQuest(1387, 4, 8, 32723, 350)
RPH_AddQuest(1387, 4, 8, 32532, 150)
RPH_AddQuest(1387, 4, 8, 32550, 150)
RPH_AddQuest(1387, 4, 8, 32526, 150)
RPH_AddQuest(1387, 4, 8, 32633, 150)
RPH_AddQuest(1387, 4, 8, 32533, 150)
RPH_AddQuest(1387, 4, 8, 32606, 150)
RPH_AddQuest(1387, 4, 8, 32542, 150)
RPH_AddQuest(1387, 4, 8, 32628, 150)
RPH_AddQuest(1387, 4, 8, 32530, 150)
RPH_AddQuest(1387, 4, 8, 32529, 150)
RPH_AddQuest(1387, 4, 8, 32531, 150)
RPH_AddQuest(1387, 4, 8, 32547, 150)
RPH_AddQuest(1387, 4, 8, 32556, 150)
RPH_AddQuest(1387, 4, 8, 32545, 150)
RPH_AddQuest(1387, 4, 8, 32574, 150)
RPH_AddQuest(1387, 4, 8, 32535, 150)
RPH_AddQuest(1387, 4, 8, 32572, 150)
RPH_AddQuest(1387, 4, 8, 32575, 150)
RPH_AddQuest(1387, 4, 8, 32583, 200)
-- Timewalking Commendation
RPH_AddItems(1387, 1, 8, 300, {[143940] = 1})
-- WoD Factions
-- Council of Exarchs 1731
-- Pillars of Fate
RPH_AddItems(1731, 1, 8, 1000, {[128315] = 1})
RPH_AddMob(1731, 1, 8, "Shadowmoon Warrior/Defiler/Voidtwister at Pillars of Fate", 5, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Skeletal Ancestor/Reanimated Bones/Shadowmoon Void Augur at Pillars of Fate", 5, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Void Fragment at Pillars of Fate", 5, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Shadowmoon Deathcaller at Pillars of Fate", 8, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Void Horror at Pillars of Fate", 16, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Voidreaver Urnae (Rare mob) at Pillars of Fate", 50, zone.Shadowmoon_Valley);
--Socrethar's Rise
RPH_AddMob(1731, 1, 8, "Sargerei Binder/Worker/Initiate at Socrethar's Rise", 5, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Sargerei Acolyte/Demonspeaker at Socrethar's Rise", 5, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Shadowglen Thornshooter at Socrethar's Rise", 5, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Sargerei Darkblade at Socrethar's Rise", 8, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Nightshade Consort at Socrethar's Rise", 8, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Sargerei Demonlord at Socrethar's Rise", 16, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Master Sergeant Milgra / Demidos (Rare mobs) at Socrethar's Rise", 50, zone.Shadowmoon_Valley);
-- Darktide Roost
RPH_AddMob(1731, 1, 8, "Darktide Engineer/Rylakinator/Matron at Darktide Roost", 5, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Darktide Pilferer/Guardian at Darktide Roost", 5, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Controlled Darkwing / Darkwing Matron at Darktide Roost", 5, zone.Shadowmoon_Valley);
RPH_AddMob(1731, 1, 8, "Darktide Machinist/Windstalker at Darktide Roost", 8, zone.Shadowmoon_Valley);
-- Wrynn's Vanguard 1682
RPH_AddItems(1682, 1, 8, 1000, {[128315] = 1})
RPH_AddGeneral(1682, 1, 8, "Kill enemy faction leader", 2500, "Kill enemy faction leader", "Kill the enemy faction leader to gain 2500 reputation")
RPH_AddGeneral(1682, 1, 8, "Win a bonus objective", 500, "Win a bonus objective", "Win a bonus objective to gain 500 reputation")
RPH_AddQuest(1682, 1, 8, 35927, 2500, {[112015] = 1})
RPH_AddQuest(1682, 1, 8, 35942, 2500, {[112113] = 1})
RPH_AddQuest(1682, 1, 8, 35941, 2500, {[112120] = 1})
RPH_AddQuest(1682, 1, 8, 35940, 2500, {[112122] = 1})
RPH_AddQuest(1682, 1, 8, 35939, 2500, {[112123] = 1})
RPH_AddQuest(1682, 1, 8, 35938, 2500, {[112125] = 1})
RPH_AddQuest(1682, 1, 8, 35937, 2500, {[112128] = 1})
-- Sha'tari Defense 1710
RPH_AddItems(1710, 1, 8, 1000, {[128315] = 1})
-- Shattrath
RPH_AddMob(1710, 1, 8, "Vicious Felhunter/Observer/Voidwalker in Shattrath", 5, zone.Talador);
RPH_AddMob(1710, 1, 8, "Sargerei Summoner/Huntsman/Felbringer/Soul-Twister/ in Shattrath", 5, zone.Talador);
RPH_AddMob(1710, 1, 8, "Sargerei Fiendmaster in Shattrath", 5, zone.Talador);
RPH_AddMob(1710, 1, 8, "Conniving Shadowblade / Council Soulspeaker in Shattrath", 5, zone.Talador);
RPH_AddMob(1710, 1, 8, "Sargerei Discordant/Ritualist/Soulspewer/Fiendspeaker/ in Shattrath", 8, zone.Talador);
RPH_AddMob(1710, 1, 8, "Sargerei Destructor in Shattrath", 8, zone.Talador);
RPH_AddMob(1710, 1, 8, "Conniving Deathblade / Council Felcaller in Shattrath", 8, zone.Talador);
RPH_AddMob(1710, 1, 8, "Rune Ritualist in Shattrath", 15, zone.Talador);
-- Bladefury Hold
RPH_AddMob(1710, 1, 8, "Grom'kar Blademaster/Bulwark/deadeye/Punisher in Bladefury Hold", 5, zone.Talador);
-- Hand of the Prophet 1847
RPH_AddItems(1847, 1, 8, 1000, {[128315] = 1})
RPH_AddGeneral(1847, 1, 8, "Lion's Watch command table random daily quest", 500, "Lion's Watch command table random daily quest", "Random daily that awards 500 reputation")
RPH_AddQuest(1847, 1, 8, 39574, 250)
RPH_AddGeneral(1847, 1, 8, "Vindicator Krethos random daily quest", 250, "Vindicator Krethos random daily quest", "Random daily that awards 250 reputation")
end
if (RPH_IsHorde) then
-- Hord Cities
-- Darkspear Trolls 530
RPH_AddQuest(530, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(530, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(530, 4, 8, 7385, 18.75, {[17306] = 5})
RPH_AddQuest(530, 4, 8, 6801, 2.5, {[17306] = 1})
RPH_AddQuest(530, 4, 8, 6825, 10, {[17326] = 1})
RPH_AddQuest(530, 4, 8, 6826, 10, {[17327] = 1})
RPH_AddQuest(530, 4, 8, 6827, 10, {[17328] = 1})
RPH_AddQuest(530, 4, 8, 7027, 2.5)
RPH_AddQuest(530, 4, 8, 7002, 2.5, {[17642] = 1})
RPH_AddQuest(530, 4, 8, 6741, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(530, 4, 8, 250, {[45720] = 1})
RPH_AddItems(530, 4, 8, 62.5, {[4] = 1})
RPH_AddSpell(530, 1, 8, 5, 1000)
-- Orgrimmar 76
RPH_AddQuest(76, 4, 8, 1, 250, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(76, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(76, 4, 8, 3, 250, "nil", RPH_LIMIT_TYPE_Fish)
RPH_AddQuest(76, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(76, 4, 8, 7385, 18.75, {[17306] = 5})
RPH_AddQuest(76, 4, 8, 6801, 2.5, {[17306] = 1})
RPH_AddQuest(76, 4, 8, 6825, 10, {[17326] = 1})
RPH_AddQuest(76, 4, 8, 6826, 10, {[17327] = 1})
RPH_AddQuest(76, 4, 8, 6827, 10, {[17328] = 1})
RPH_AddQuest(76, 4, 8, 7027, 2.5)
RPH_AddQuest(76, 4, 8, 7002, 2.5, {[17642] = 1})
RPH_AddQuest(76, 4, 8, 6741, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(76, 4, 8, 250, {[45719] = 1})
RPH_AddItems(76, 4, 8, 62.5, {[4] = 1})
RPH_AddSpell(76, 1, 8, 5, 1000)
-- Silvermoon City 911
RPH_AddQuest(911, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(911, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(911, 4, 8, 7385, 18.75, {[17306] = 5})
RPH_AddQuest(911, 4, 8, 6801, 2.5, {[17306] = 1})
RPH_AddQuest(911, 4, 8, 6825, 10, {[17326] = 1})
RPH_AddQuest(911, 4, 8, 6826, 10, {[17327] = 1})
RPH_AddQuest(911, 4, 8, 6827, 10, {[17328] = 1})
RPH_AddQuest(911, 4, 8, 7027, 2.5)
RPH_AddQuest(911, 4, 8, 7002, 2.5, {[17642] = 1})
RPH_AddQuest(911, 4, 8, 6741, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(911, 4, 8, 250, {[45721] = 1})
RPH_AddItems(911, 4, 8, 62.5, {[4] = 1})
RPH_AddSpell(911, 1, 8, 5, 1000)
-- Thunder Bluff 81
RPH_AddQuest(81, 4, 8, 1, 250, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(81, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(81, 4, 8, 3, 250, "nil", RPH_LIMIT_TYPE_Fish)
RPH_AddQuest(81, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(81, 4, 8, 7385, 18.75, {[17306] = 5})
RPH_AddQuest(81, 4, 8, 6801, 2.5, {[17306] = 1})
RPH_AddQuest(81, 4, 8, 6825, 10, {[17326] = 1})
RPH_AddQuest(81, 4, 8, 6826, 10, {[17327] = 1})
RPH_AddQuest(81, 4, 8, 6827, 10, {[17328] = 1})
RPH_AddQuest(81, 4, 8, 7027, 2.5)
RPH_AddQuest(81, 4, 8, 7002, 2.5, {[17642] = 1})
RPH_AddQuest(81, 4, 8, 6741, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(81, 4, 8, 250, {[45722] = 1})
RPH_AddItems(81, 4, 8, 62.5, {[4] = 1})
RPH_AddSpell(81, 1, 8, 5, 1000)
-- Undercity 68
RPH_AddQuest(68, 4, 8, 1, 250, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(68, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(68, 4, 8, 3, 250, "nil", RPH_LIMIT_TYPE_Fish)
RPH_AddQuest(68, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
RPH_AddQuest(68, 4, 8, 7385, 18.75, {[17306] = 5})
RPH_AddQuest(68, 4, 8, 6801, 2.5, {[17306] = 1})
RPH_AddQuest(68, 4, 8, 6825, 10, {[17326] = 1})
RPH_AddQuest(68, 4, 8, 6826, 10, {[17327] = 1})
RPH_AddQuest(68, 4, 8, 6827, 10, {[17328] = 1})
RPH_AddQuest(68, 4, 8, 7027, 2.5)
RPH_AddQuest(68, 4, 8, 7002, 2.5, {[17642] = 1})
RPH_AddQuest(68, 4, 8, 6741, 2.5, {[17422] = 20})
---- spillover from Other
RPH_AddItems(68, 4, 8, 250, {[45723] = 1})
RPH_AddItems(68, 4, 8, 62.5, {[4] = 1})
RPH_AddSpell(68, 1, 8, 5, 1000)
-- Bilgewater Cartel 1133
RPH_AddQuest(1133, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(1133, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
---- spillover from Other
RPH_AddSpell(1133, 1, 8, 5, 1000)
-- Huojin Pandaren 1352
RPH_AddQuest(1352, 4, 8, 2, 65, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(1352, 4, 8, 4, 65, "nil", RPH_LIMIT_TYPE_Fish)
---- spillover from Alterac Valley
---- spillover from Other
RPH_AddSpell(1352, 1, 8, 5, 1000)
-- Horde Forces
-- The Defilers 510
RPH_AddGeneral(510, 4, 8, "Arathi Basin collect 100 Resources", 50, "Collect 100 Resources", "For every 100 resources your team collects you gain 50 reputation")
RPH_AddGeneral(510, 4, 8, "Arathi Basin win (1500 Resources)", 750, "Arathi Basin win (1500 Resources)", "If your team wins with 1500 resources you will earn a total of 750 reputation")
-- Frostwolf Clan 729
RPH_AddQuest(729, 4, 8, 7385, 18.75, {[17306] = 5})
RPH_AddQuest(729, 4, 8, 6801, 2.5, {[17306] = 1})
RPH_AddQuest(729, 4, 8, 6825, 10, {[17326] = 1})
RPH_AddQuest(729, 4, 8, 6826, 10, {[17327] = 1})
RPH_AddQuest(729, 4, 8, 6827, 10, {[17328] = 1})
RPH_AddQuest(729, 4, 8, 7027, 2.5)
RPH_AddQuest(729, 4, 8, 7002, 2.5, {[17642] = 1})
RPH_AddQuest(729, 4, 8, 6741, 2.5, {[17422] = 20})
-- Warsong Outriders 889
RPH_AddGeneral(889, 4, 8, "Warsong Gulch flag capture", 100, "Warsong Gulch flag capture", "Every time your team captures a flag you gain 100 reputation")
RPH_AddGeneral(889, 4, 8, "Warsong Gulch victory", 100, "Warsong Gulch victory", "Every time your team wins you gain 100 reputation")
RPH_AddGeneral(889, 4, 8, "Warsong Gulch loss", 35, "Warsong Gulch loss", "Every time your team lose you gain 35 reputation")
-- Brawl'gar Arena 1374
RPH_AddQuest(1374, 1, 8, 5, 1)
-- 0 Outlands (Burning Crusade)
-- Thrallmar 947
RPH_AddInstance(947, 4, 5, zone.Hellfire_Ramparts, 600, false)
RPH_AddInstance(947, 6, 8, zone.Hellfire_Ramparts, 2000, true)
RPH_AddInstance(947, 4, 5, zone.The_Blood_Furnace, 750, false)
RPH_AddInstance(947, 6, 8, zone.The_Blood_Furnace, 2700, true)
RPH_AddMob(947, 4, 7, 725, 5)
RPH_AddMob(947, 4, 8, 725, 15)
RPH_AddInstance(947, 4, 8, zone.The_Shattered_Halls, 1600, false)
RPH_AddInstance(947, 4, 8, zone.The_Shattered_Halls, 2900, true)
RPH_AddMob(947, 4, 7, 710, 5)
RPH_AddMob(947, 4, 8, 710, 15)
RPH_AddQuest(947, 4, 7, 13410, 150)
-- Timewalking Commendation
RPH_AddItems(947, 1, 8, 500, {[129947] = 1})
-- The Mag'har 941
RPH_AddQuest(941, 4, 8, 10479, 500, {[25433] = 10})
RPH_AddQuest(941, 4, 8, 11503, 500)
RPH_AddMob(941, 4, 8, "Boulderfist ogres", 10, zone.Nagrand)
RPH_AddMob(941, 4, 8, "Kil'sorrow Deathsworn, Cultist & Spellbinder", 10, zone.Nagrand)
RPH_AddMob(941, 4, 8, "Murkblood Scavenger", 2, zone.Nagrand)
RPH_AddMob(941, 4, 8, "Murkblood ", 10, zone.Nagrand)
RPH_AddMob(941, 4, 8, "Warmaul non-elite", 10, zone.Nagrand)
-- Tranquillien 922
RPH_AddQuest(922, 4, 8, 9217, 500, {[22641] = 10})
RPH_AddQuest(922, 4, 8, 9219, 500, {[22642] = 10})
-- Northrend (WotLK)
-- Horde Expedition 1052
RPH_AddQuest(1052, 4, 8, 12170, 125)
---- spillover from 1124
RPH_AddQuest(1052, 4, 8, 13757, 62.5, {[44981] = 1})
RPH_AddQuest(1052, 4, 8, 13625, 62.5)
RPH_AddQuest(1052, 4, 8, 13769, 62.5)
RPH_AddQuest(1052, 4, 8, 13772, 62.5)
RPH_AddQuest(1052, 4, 8, 13671, 62.5)
RPH_AddQuest(1052, 4, 8, 13759, 62.5)
RPH_AddQuest(1052, 4, 8, 13772, 62.5)
---- spillover from 1085
RPH_AddQuest(1052, 4, 8, 12284, 62.5)
RPH_AddQuest(1052, 4, 8, 12280, 62.5)
RPH_AddQuest(1052, 4, 8, 12288, 62.5)
RPH_AddQuest(1052, 4, 8, 12270, 62.5)
RPH_AddQuest(1052, 4, 8, 13309, 62.5)
RPH_AddQuest(1052, 4, 8, 13284, 62.5)
RPH_AddQuest(1052, 4, 8, 13336, 62.5)
RPH_AddQuest(1052, 4, 8, 13280, 62.5)
---- spillover from tournament
RPH_AddQuest(1052, 4, 8, 13809, 125)
RPH_AddQuest(1052, 4, 8, 13810, 125)
RPH_AddQuest(1052, 4, 8, 13862, 125)
RPH_AddQuest(1052, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1052, 4, 8, 1, 400, false)
RPH_AddInstance(1052, 4, 8, 1, 800, true)
---- Timewalking Commendation
RPH_AddItems(1052, 1, 8, 500, {[129954] = 1})
-- The Hand of Vengeance 1067
---- spillover from 1052
RPH_AddQuest(1067, 4, 8, 12170, 62.5)
---- spillover from 1124
RPH_AddQuest(1067, 4, 8, 13757, 62.5, {[44981] = 1})
RPH_AddQuest(1067, 4, 8, 13625, 62.5)
RPH_AddQuest(1067, 4, 8, 13769, 62.5)
RPH_AddQuest(1067, 4, 8, 13772, 62.5)
RPH_AddQuest(1067, 4, 8, 13671, 62.5)
RPH_AddQuest(1067, 4, 8, 13759, 62.5)
RPH_AddQuest(1067, 4, 8, 13772, 62.5)
---- spillover from 1085
RPH_AddQuest(1067, 4, 8, 12284, 62.5)
RPH_AddQuest(1067, 4, 8, 12280, 62.5)
RPH_AddQuest(1067, 4, 8, 12288, 62.5)
RPH_AddQuest(1067, 4, 8, 12270, 62.5)
RPH_AddQuest(1067, 4, 8, 13309, 62.5)
RPH_AddQuest(1067, 4, 8, 13284, 62.5)
RPH_AddQuest(1067, 4, 8, 13336, 62.5)
RPH_AddQuest(1067, 4, 8, 13280, 62.5)
---- spillover from tournament
RPH_AddQuest(1067, 4, 8, 13809, 125)
RPH_AddQuest(1067, 4, 8, 13810, 125)
RPH_AddQuest(1067, 4, 8, 13862, 125)
RPH_AddQuest(1067, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1067, 4, 8, 1, 400, false)
RPH_AddInstance(1067, 4, 8, 1, 800, true)
-- The Sunreavers 1124
RPH_AddQuest(1124, 4, 8, 13757, 125, {[44981] = 1})
RPH_AddQuest(1124, 4, 8, 13625, 125)
RPH_AddQuest(1124, 4, 8, 13769, 125)
RPH_AddQuest(1124, 4, 8, 13772, 125)
RPH_AddQuest(1124, 4, 8, 13671, 125)
RPH_AddQuest(1124, 4, 8, 13759, 125)
RPH_AddQuest(1124, 4, 8, 13772, 125)
---- spillover from 1052
RPH_AddQuest(1124, 4, 8, 12170, 62.5)
---- spillover from 1085
RPH_AddQuest(1124, 4, 8, 12284, 62.5)
RPH_AddQuest(1124, 4, 8, 12280, 62.5)
RPH_AddQuest(1124, 4, 8, 12288, 62.5)
RPH_AddQuest(1124, 4, 8, 12270, 62.5)
RPH_AddQuest(1124, 4, 8, 13309, 62.5)
RPH_AddQuest(1124, 4, 8, 13284, 62.5)
RPH_AddQuest(1124, 4, 8, 13336, 62.5)
RPH_AddQuest(1124, 4, 8, 13280, 62.5)
---- spillover from tournament
RPH_AddQuest(1124, 4, 8, 13809, 125)
RPH_AddQuest(1124, 4, 8, 13810, 125)
RPH_AddQuest(1124, 4, 8, 13862, 125)
RPH_AddQuest(1124, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1124, 4, 8, 1, 400, false)
RPH_AddInstance(1124, 4, 8, 1, 800, true)
-- Warsong Offensive 1085
RPH_AddQuest(1085, 4, 8, 12284, 125)
RPH_AddQuest(1085, 4, 8, 12280, 125)
RPH_AddQuest(1085, 4, 8, 12288, 125)
RPH_AddQuest(1085, 4, 8, 12270, 125)
RPH_AddQuest(1085, 4, 8, 13309, 125)
RPH_AddQuest(1085, 4, 8, 13284, 125)
RPH_AddQuest(1085, 4, 8, 13336, 125)
RPH_AddQuest(1085, 4, 8, 13280, 125)
---- spillover from 1052
RPH_AddQuest(1085, 4, 8, 12170, 62.5)
---- spillover from 1124
RPH_AddQuest(1085, 4, 8, 13757, 62.5, {[44981] = 1})
RPH_AddQuest(1085, 4, 8, 13625, 62.5)
RPH_AddQuest(1085, 4, 8, 13769, 62.5)
RPH_AddQuest(1085, 4, 8, 13772, 62.5)
RPH_AddQuest(1085, 4, 8, 13671, 62.5)
RPH_AddQuest(1085, 4, 8, 13759, 62.5)
RPH_AddQuest(1085, 4, 8, 13772, 62.5)
---- spillover from tournament
RPH_AddQuest(1085, 4, 8, 13809, 125)
RPH_AddQuest(1085, 4, 8, 13810, 125)
RPH_AddQuest(1085, 4, 8, 13862, 125)
RPH_AddQuest(1085, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1085, 4, 8, 1, 400, false)
RPH_AddInstance(1085, 4, 8, 1, 800, true)
-- The Taunka 1064
---- spillover from 1052
RPH_AddQuest(1064, 4, 8, 12170, 62.5)
---- spillover from 1124
RPH_AddQuest(1064, 4, 8, 13757, 62.5, {[44981] = 1})
RPH_AddQuest(1064, 4, 8, 13625, 62.5)
RPH_AddQuest(1064, 4, 8, 13769, 62.5)
RPH_AddQuest(1064, 4, 8, 13772, 62.5)
RPH_AddQuest(1064, 4, 8, 13671, 62.5)
RPH_AddQuest(1064, 4, 8, 13759, 62.5)
RPH_AddQuest(1064, 4, 8, 13772, 62.5)
---- spillover from 1085
RPH_AddQuest(1064, 4, 8, 12284, 62.5)
RPH_AddQuest(1064, 4, 8, 12280, 62.5)
RPH_AddQuest(1064, 4, 8, 12288, 62.5)
RPH_AddQuest(1064, 4, 8, 12270, 62.5)
RPH_AddQuest(1064, 4, 8, 13309, 62.5)
RPH_AddQuest(1064, 4, 8, 13284, 62.5)
RPH_AddQuest(1064, 4, 8, 13336, 62.5)
RPH_AddQuest(1064, 4, 8, 13280, 62.5)
---- spillover from tournament
RPH_AddQuest(1064, 4, 8, 13809, 125)
RPH_AddQuest(1064, 4, 8, 13810, 125)
RPH_AddQuest(1064, 4, 8, 13862, 125)
RPH_AddQuest(1064, 4, 8, 13811, 125)
---- spillover from dungeon
RPH_AddInstance(1064, 4, 8, 1, 400, false)
RPH_AddInstance(1064, 4, 8, 1, 800, true)
-- Cataclysm
-- Dragonmaw Clan 1172
---- from zone Twilight Highlands
RPH_AddQuest(1172, 4, 8, 28873, 250)
RPH_AddQuest(1172, 4, 8, 28875, 350)
RPH_AddQuest(1172, 4, 8, 28871, 250)
RPH_AddQuest(1172, 4, 8, 28874, 250)
RPH_AddQuest(1172, 4, 8, 28872, 250)
RPH_AddSpell(1172, 1, 8, 5, 1000)
RPH_AddSpell(1172, 1, 8, 5, 1800)
RPH_AddMob(1172, 1, 8, 1, 10, 5)
RPH_AddMob(1172, 1, 8, 1, 15, 6)
RPH_AddMob(1172, 1, 8, 4, 150, 5)
RPH_AddMob(1172, 1, 8, 4, 250, 6)
-- Timewalking Commendation
RPH_AddItems(1172, 1, 8, 500, {[133150] = 1})
-- Hellscream's Reach 1178
---- from zone Tol Barad
------ Tol Barad Peninsula
------ Commander Zanoth
RPH_AddQuest(1178, 4, 8, 28122, 250)
RPH_AddQuest(1178, 4, 8, 28658, 250)
RPH_AddQuest(1178, 4, 8, 28659, 250)
------ Drillmaster Razgoth
RPH_AddQuest(1178, 4, 8, 28665, 350)
RPH_AddQuest(1178, 4, 8, 28663, 350)
RPH_AddQuest(1178, 4, 8, 28664, 350)
------ Private Garnoth
RPH_AddQuest(1178, 4, 8, 28660, 350)
RPH_AddQuest(1178, 4, 8, 28662, 350)
RPH_AddQuest(1178, 4, 8, 28661, 250)
------ Staff Sergeant Lazgar
RPH_AddQuest(1178, 4, 8, 28670, 250)
RPH_AddQuest(1178, 4, 8, 28668, 350)
RPH_AddQuest(1178, 4, 8, 28669, 350)
------ Tol Barad Main
---- Private Sarlosk
RPH_AddQuest(1178, 4, 8, 28275, 250)
RPH_AddQuest(1178, 4, 8, 28698, 250)
RPH_AddQuest(1178, 4, 8, 28697, 250)
RPH_AddQuest(1178, 4, 8, 28700, 250)
RPH_AddQuest(1178, 4, 8, 28695, 250)
RPH_AddQuest(1178, 4, 8, 28694, 250)
---- Commander Larmash
RPH_AddQuest(1178, 4, 8, 28682, 250)
RPH_AddQuest(1178, 4, 8, 28685, 250)
RPH_AddQuest(1178, 4, 8, 28686, 250)
RPH_AddQuest(1178, 4, 8, 28687, 250)
RPH_AddQuest(1178, 4, 8, 28721, 250)
---- 3rd Officer Kronkar
RPH_AddQuest(1178, 4, 8, 28684, 250)
RPH_AddQuest(1178, 4, 8, 28680, 250)
RPH_AddQuest(1178, 4, 8, 28678, 250)
RPH_AddQuest(1178, 4, 8, 28679, 250)
RPH_AddQuest(1178, 4, 8, 28681, 350)
RPH_AddQuest(1178, 4, 8, 28683, 250)
---- Captain Prug
RPH_AddQuest(1178, 4, 8, 28693, 250)
RPH_AddQuest(1178, 4, 8, 28691, 250)
RPH_AddQuest(1178, 4, 8, 28692, 250)
RPH_AddQuest(1178, 4, 8, 28690, 250)
RPH_AddQuest(1178, 4, 8, 28689, 250)
-- Mist of Pandaria
-- Forest Hozen 1228
RPH_AddQuest(1228, 1, 8, 5, 1)
-- Dominance Offensive 1375
RPH_AddQuest(1375, 1, 8, 32643, 400)
---- Lion's Landing
RPH_AddQuest(1375, 1, 8, 32148, 150)
RPH_AddQuest(1375, 1, 8, 32153, 150)
RPH_AddQuest(1375, 1, 8, 32152, 150)
RPH_AddQuest(1375, 1, 8, 32150, 150)
RPH_AddQuest(1375, 1, 8, 32151, 150)
RPH_AddQuest(1375, 1, 8, 32132, 150)
---- Domination Point
RPH_AddQuest(1375, 1, 8, 32146, 300)
RPH_AddQuest(1375, 1, 8, 32145, 150)
RPH_AddQuest(1375, 1, 8, 32142, 150)
RPH_AddQuest(1375, 1, 8, 32143, 150)
RPH_AddQuest(1375, 1, 8, 32144, 150)
---- Ruins of Ogudei
RPH_AddQuest(1375, 1, 8, 32122, 300)
RPH_AddQuest(1375, 1, 8, 32121, 150)
RPH_AddQuest(1375, 1, 8, 32119, 150)
RPH_AddQuest(1375, 1, 8, 32347, 150)
RPH_AddQuest(1375, 1, 8, 32115, 150)
RPH_AddQuest(1375, 1, 8, 32346, 150)
---- Bilgewater Beach
------ Set one
RPH_AddQuest(1375, 1, 8, 32199, 150)
RPH_AddQuest(1375, 1, 8, 32149, 150)
RPH_AddQuest(1375, 1, 8, 32157, 150)
RPH_AddQuest(1375, 1, 8, 32446, 150)
RPH_AddQuest(1375, 1, 8, 32158, 300)
------ Set two
RPH_AddQuest(1375, 1, 8, 32214, 150)
RPH_AddQuest(1375, 1, 8, 32433, 300)
RPH_AddQuest(1375, 1, 8, 32197, 150)
RPH_AddQuest(1375, 1, 8, 32155, 150)
RPH_AddQuest(1375, 1, 8, 32137, 150)
------ Xtra Fuel Set
RPH_AddQuest(1375, 1, 8, 32141, 150)
RPH_AddQuest(1375, 1, 8, 32236, 150)
---- Beastmaster Quests
------ Huntsman Blake
RPH_AddQuest(1375, 1, 8, 32172, 200)
RPH_AddQuest(1375, 1, 8, 32170, 200)
RPH_AddQuest(1375, 1, 8, 32171, 200)
-- Timewalking Commendation
RPH_AddItems(1375, 1, 8, 300, {[143943] = 1})
-- Isle of Thunder
-- Sunreaver Onslaught 1388
RPH_AddQuest(1388, 4, 8, 32571, 150)
RPH_AddQuest(1388, 4, 8, 32578, 200)
RPH_AddQuest(1388, 4, 8, 32525, 150)
RPH_AddQuest(1388, 4, 8, 32485, 150)
RPH_AddQuest(1388, 4, 8, 32634, 150)
RPH_AddQuest(1388, 4, 8, 32636, 150)
RPH_AddQuest(1388, 4, 8, 32627, 150)
RPH_AddQuest(1388, 4, 8, 32576, 200)
RPH_AddQuest(1388, 4, 8, 32576, 200)
RPH_AddQuest(1388, 4, 8, 32551, 150)
RPH_AddQuest(1388, 4, 8, 32543, 150)
RPH_AddQuest(1388, 4, 8, 32539, 150)
RPH_AddQuest(1388, 4, 8, 32537, 150)
RPH_AddQuest(1388, 4, 8, 32639, 150)
RPH_AddQuest(1388, 4, 8, 32492, 250)
RPH_AddQuest(1388, 4, 8, 32554, 150)
RPH_AddQuest(1388, 4, 8, 32297, 150)
RPH_AddQuest(1388, 4, 8, 32300, 150)
RPH_AddQuest(1388, 4, 8, 32585, 200)
RPH_AddQuest(1388, 4, 8, 32573, 150)
RPH_AddQuest(1388, 4, 8, 32607, 400)
RPH_AddQuest(1388, 4, 8, 32724, 200)
RPH_AddQuest(1388, 4, 8, 32570, 150)
RPH_AddQuest(1388, 4, 8, 32527, 150)
RPH_AddQuest(1388, 4, 8, 32540, 150)
RPH_AddQuest(1388, 4, 8, 32538, 150)
RPH_AddQuest(1388, 4, 8, 32631, 200)
RPH_AddQuest(1388, 4, 8, 32581, 200)
RPH_AddQuest(1388, 4, 8, 32528, 150)
RPH_AddQuest(1388, 4, 8, 32546, 150)
RPH_AddQuest(1388, 4, 8, 32286, 250)
RPH_AddQuest(1388, 4, 8, 32210, 250)
RPH_AddQuest(1388, 4, 8, 32229, 250)
RPH_AddQuest(1388, 4, 8, 32234, 150)
RPH_AddQuest(1388, 4, 8, 32548, 150)
RPH_AddQuest(1388, 4, 8, 32552, 150)
RPH_AddQuest(1388, 4, 8, 32632, 150)
RPH_AddQuest(1388, 4, 8, 32266, 150)
RPH_AddQuest(1388, 4, 8, 32536, 150)
RPH_AddQuest(1388, 4, 8, 32586, 150)
RPH_AddQuest(1388, 4, 8, 32301, 150)
RPH_AddQuest(1388, 4, 8, 32637, 150)
RPH_AddQuest(1388, 4, 8, 32494, 150)
RPH_AddQuest(1388, 4, 8, 32541, 150)
RPH_AddQuest(1388, 4, 8, 32544, 150)
RPH_AddQuest(1388, 4, 8, 32701, 1850)
RPH_AddQuest(1388, 4, 8, 32703, 1900)
RPH_AddQuest(1388, 4, 8, 32704, 2150)
RPH_AddQuest(1388, 4, 8, 32700, 1250)
RPH_AddQuest(1388, 4, 8, 32608, 400)
RPH_AddQuest(1388, 4, 8, 32582, 200)
RPH_AddQuest(1388, 4, 8, 32532, 150)
RPH_AddQuest(1388, 4, 8, 32550, 150)
RPH_AddQuest(1388, 4, 8, 32209, 150)
RPH_AddQuest(1388, 4, 8, 32526, 150)
RPH_AddQuest(1388, 4, 8, 32633, 150)
RPH_AddQuest(1388, 4, 8, 32533, 150)
RPH_AddQuest(1388, 4, 8, 32606, 150)
RPH_AddQuest(1388, 4, 8, 32275, 150)
RPH_AddQuest(1388, 4, 8, 32628, 150)
RPH_AddQuest(1388, 4, 8, 32482, 250)
RPH_AddQuest(1388, 4, 8, 32530, 150)
RPH_AddQuest(1388, 4, 8, 32529, 150)
RPH_AddQuest(1388, 4, 8, 32531, 150)
RPH_AddQuest(1388, 4, 8, 32547, 150)
RPH_AddQuest(1388, 4, 8, 32545, 150)
RPH_AddQuest(1388, 4, 8, 32574, 150)
RPH_AddQuest(1388, 4, 8, 32535, 150)
RPH_AddQuest(1388, 4, 8, 32572, 150)
RPH_AddQuest(1388, 4, 8, 32575, 150)
RPH_AddQuest(1388, 4, 8, 32493, 150)
RPH_AddQuest(1388, 4, 8, 32206, 150)
RPH_AddQuest(1388, 4, 8, 32233, 150)
RPH_AddQuest(1388, 4, 8, 32232, 150)
RPH_AddQuest(1388, 4, 8, 32583, 200)
-- Timewalking Commendation
RPH_AddItems(1388, 1, 8, 300, {[143939] = 1})
-- WoD Factions
-- Frostwolf Orcs 1445
RPH_AddItems(1445, 1, 8, 1000, {[128315] = 1})
-- Stonefury Cliffs
RPH_AddMob(1445, 1, 8, "Bloodmaul Brute/Dire Boar/Frostbender in Stonefury Cliffs", 5, zone.Frostfire_Ridge);
RPH_AddMob(1445, 1, 8, "Bloodmaul Gladiator in Stonefury Cliffs", 5, zone.Frostfire_Ridge);
RPH_AddMob(1445, 1, 8, "Bloodmaul Geomancer/Magma Shaper/Taskmaster in Stonefury Cliffs", 8, zone.Frostfire_Ridge);
RPH_AddMob(1445, 1, 8, "Bloodmaul Bonecrusher in Stonefury Cliffs", 16, zone.Frostfire_Ridge);
-- Magnarok
RPH_AddMob(1445, 1, 8, "Frostfire Cragstomper in Magnarok", 8, zone.Frostfire_Ridge);
RPH_AddMob(1445, 1, 8, "Vicious Acidmaw in Magnarok", 8, zone.Frostfire_Ridge);
RPH_AddMob(1445, 1, 8, "Icecrag Mountainbreaker in Magnarok", 16, zone.Frostfire_Ridge);
-- Iron Siegeworks
RPH_AddMob(1445, 1, 8, "Grom'kar Deadeye/Enforcer/Footsoldier in Iron Siegeworks", 5, zone.Frostfire_Ridge);
RPH_AddMob(1445, 1, 8, "Grom'kar Shocktrooper/Warforger in Iron Siegeworks", 5, zone.Frostfire_Ridge);
RPH_AddMob(1445, 1, 8, "Grom'kar Crippler/Pulverizer in Iron Siegeworks", 16, zone.Frostfire_Ridge);
RPH_AddMob(1445, 1, 8, "Iron Berserker/Crag-Leaper/Gladiator/Talon in Iron Siegeworks", 5, zone.Frostfire_Ridge);
-- Vol'jin's Spear 1681
RPH_AddItems(1681, 1, 8, 1000, {[128315] = 1})
RPH_AddItems(1681, 1, 8, 1000, {[128315] = 1})
RPH_AddGeneral(1681, 1, 8, "Kill enemy faction leader", 2500, "Kill enemy faction leader", "Kill the enemy faction leader to gain 2500 reputation")
RPH_AddGeneral(1681, 1, 8, "Win a bonus objective", 500, "Win a bonus objective", "Win a bonus objective to gain 500 reputation")
RPH_AddQuest(1681, 1, 8, 36884, 2500, {[112119] = 1})
RPH_AddQuest(1681, 1, 8, 36041, 2500, {[112121] = 1})
RPH_AddQuest(1681, 1, 8, 36033, 2500, {[112124] = 1})
RPH_AddQuest(1681, 1, 8, 36034, 2500, {[112126] = 1})
RPH_AddQuest(1681, 1, 8, 36040, 2500, {[112127] = 1})
RPH_AddQuest(1681, 1, 8, 36042, 2500, {[112131] = 1})
RPH_AddQuest(1681, 1, 8, 36038, 2500, {[112113] = 1})
-- Laughing Skull Orcs 1708
RPH_AddItems(1708, 1, 8, 1000, {[128315] = 1})
-- The Pit
RPH_AddMob(1708, 1, 8, "Iron Laborer in The Pit", 5, zone.Gorgrond);
RPH_AddMob(1708, 1, 8, "Iron Enforcer/Deadshot/Cauterizer in The Pit", 15, zone.Gorgrond);
RPH_AddMob(1708, 1, 8, "Iron Bloodburner/Bulwark/Warden/Reinforcement in The Pit", 15, zone.Gorgrond);
-- Everbloom Wilds
RPH_AddMob(1708, 1, 8, "Everbloom Shaper/Wasp/Waterspeaker in Everbloom Wilds", 5, zone.Gorgrond);
-- Vol'jin's Headhunters 1848
RPH_AddItems(1848, 1, 8, 1000, {[128315] = 1})
RPH_AddGeneral(1848, 1, 8, "Vol'mar command table random daily quest", 500, "Vol'mar command table random daily quest", "Random daily that awards 500 reputation")
RPH_AddQuest(1848, 1, 8, 39526, 250)
RPH_AddGeneral(1848, 1, 8, "Shadow Hunter Denjai random daily quest", 250, "Shadow Hunter Denjai random daily quest", "Random daily that awards 250 reputation")
end
-- Steamwheedle Cartel
-- Booty Bay 21
RPH_AddMob(21, 1, 7, 11, 5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(21, 1, 8, 12, 2.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(21, 1, 8, 13, 2.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(21, 1, 7, 14, 5, zone.Northern_Stranglethorn)
RPH_AddMob(21, 1, 7, 15, 12.5, zone.Northern_Stranglethorn)
RPH_AddMob(21, 1, 8, 15, 7.5, zone.Northern_Stranglethorn)
RPH_AddMob(21, 1, 8, 17, 7.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(21, 1, 7, "Cap'n Garvey & Alicia Cuthbert", 5, "17")
RPH_AddQuest(21, 1, 3, 9259, 500, {[4306] = 1, [2604] = 1})
-- Everlook 577
RPH_AddMob(577, 1, 7, 11, 2.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(577, 1, 7, 12, 2.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(577, 1, 8, 13, 5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(577, 1, 7, 14, 2.5, zone.Northern_Stranglethorn)
RPH_AddMob(577, 1, 8, 15, 7.5, zone.Northern_Stranglethorn)
RPH_AddMob(577, 1, 8, 15, 7.5, zone.Northern_Stranglethorn)
RPH_AddMob(577, 1, 7, 17, 12.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(577, 1, 8, "Cap'n Garvey & Alicia Cuthbert", 12.5, "17")
RPH_AddQuest(577, 1, 3, 9266, 500, {[14047] = 1, [3857] = 1})
-- Gadgetzan 369
RPH_AddMob(369, 1, 8, 11, 2.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(369, 1, 8, 12, 2.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(369, 1, 7, 13, 5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(369, 1, 7, 14, 2.5, zone.Northern_Stranglethorn)
RPH_AddMob(369, 1, 8, 15, 7.5, zone.Northern_Stranglethorn)
RPH_AddMob(369, 1, 7, 15, 12.5, zone.Northern_Stranglethorn)
RPH_AddMob(369, 1, 8, 17, 12.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(369, 1, 7, "Cap'n Garvey & Alicia Cuthbert", 25, "17")
RPH_AddQuest(369, 1, 3, 9268, 500, {[4338] = 1, [3466] = 1})
-- Ratchet 470
RPH_AddMob(470, 1, 8, 11, 2.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(470, 1, 8, 12, 2.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(470, 1, 8, 13, 2.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(470, 1, 7, 14, 2.5, zone.Northern_Stranglethorn)
RPH_AddMob(470, 1, 7, 15, 7.5, zone.Northern_Stranglethorn)
RPH_AddMob(470, 1, 8, 15, 7.5, zone.Northern_Stranglethorn)
RPH_AddMob(470, 1, 7, 17, 12.5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(470, 1, 8, "Cap'n Garvey & Alicia Cuthbert", 12.5, "11")
RPH_AddQuest(470, 1, 3, 9267, 500, {[2589] = 1, [3371] = 1})
-- Bloodsail Buccaneers 87
RPH_AddMob(87, 1, 7, "Booty Bay Bruiser & Elite", 25, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(87, 1, 7, "Some Booty Bay Named", 5, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(87, 1, 7, "Most Booty Bay Named", 1, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(87, 1, 7, "Most Faldir's Cove Named", 5)
RPH_AddMob(87, 1, 7, "Baron Revilgaz, Grizzlowe, &Wharfmaster Lozgil", 25, zone.The_Cape_of_Stranglethorn)
RPH_AddMob(87, 1, 7, "Viznik & Rickle Goldgrubber (bankers)", 25, zone.The_Cape_of_Stranglethorn)
-- Classic world
-- Argent Dawn 529
RPH_AddGeneral(529, 3, 3, "Fiona's Caravan Quests", 24000, "Fiona's Caravan Quests", "Fiona's Caravan Quests until '[42] Argent Call: The Trial of the Crypt will give enough reputation to reach Revered reputation.", nil, 0)
RPH_AddGeneral(529, 4, 4, "Fiona's Caravan Quests", 21000, "Fiona's Caravan Quests", "Fiona's Caravan Quests until '[42] Argent Call: The Trial of the Crypt will give enough reputation to reach Revered reputation.", nil, 0)
RPH_AddGeneral(529, 5, 5, "Fiona's Caravan Quests", 18000, "Fiona's Caravan Quests", "Fiona's Caravan Quests until '[42] Argent Call: The Trial of the Crypt will give enough reputation to reach Revered reputation.", nil, 0)
RPH_AddGeneral(529, 6, 6, "Fiona's Caravan Quests", 12000, "Fiona's Caravan Quests", "Fiona's Caravan Quests until '[42] Argent Call: The Trial of the Crypt will give enough reputation to reach Revered reputation.", nil, 0)
RPH_AddQuest(529, 7, 8, 28756, 1000)
RPH_AddQuest(529, 7, 8, 28755, 1000)
-- Darkmoon Faire 909
RPH_AddQuest(909, 1, 8, 29761, 250)
RPH_AddQuest(909, 1, 8, 29433, 250)
---- Dungons Arch
RPH_AddQuest(909, 1, 8, 29443, 250, {[71635] = 1})
RPH_AddQuest(909, 1, 8, 29446, 250, {[71638] = 1})
RPH_AddQuest(909, 1, 8, 29456, 250, {[71951] = 1})
RPH_AddQuest(909, 1, 8, 29444, 250, {[71636] = 1})
RPH_AddQuest(909, 1, 8, 29445, 250, {[71637] = 1})
RPH_AddQuest(909, 1, 8, 29458, 250, {[71953] = 1})
RPH_AddQuest(909, 1, 8, 29457, 250, {[71952] = 1})
RPH_AddQuest(909, 1, 8, 29451, 250, {[71715] = 1})
RPH_AddQuest(909, 1, 8, 29464, 250, {[71716] = 1})
---- Darkmoon Game Token
------ Base Games
RPH_AddQuest(909, 1, 8, 29463, 250)
RPH_AddQuest(909, 1, 8, 29438, 250)
RPH_AddQuest(909, 1, 8, 29455, 250)
RPH_AddQuest(909, 1, 8, 29436, 250)
RPH_AddQuest(909, 1, 8, 29434, 250)
------ Main profesion
RPH_AddQuest(909, 1, 8, 29514, 250, "nil", RPH_LIMIT_TYPE_Herb)
RPH_AddQuest(909, 1, 8, 29519, 250, "nil", RPH_LIMIT_TYPE_Skin)
RPH_AddQuest(909, 1, 8, 29518, 250, "nil", RPH_LIMIT_TYPE_Mine)
RPH_AddQuest(909, 1, 8, 29511, 250, "nil", RPH_LIMIT_TYPE_Engi)
RPH_AddQuest(909, 1, 8, 29506, 250, "nil", RPH_LIMIT_TYPE_Alch)
RPH_AddQuest(909, 1, 8, 29508, 250, "nil", RPH_LIMIT_TYPE_Blac)
RPH_AddQuest(909, 1, 8, 29520, 250, "nil", RPH_LIMIT_TYPE_Tail)
RPH_AddQuest(909, 1, 8, 29517, 250, "nil", RPH_LIMIT_TYPE_Leat)
RPH_AddQuest(909, 1, 8, 29510, 250, "nil", RPH_LIMIT_TYPE_Ench)
RPH_AddQuest(909, 1, 8, 29516, 250, "nil", RPH_LIMIT_TYPE_Jewe)
RPH_AddQuest(909, 1, 8, 29515, 250, "nil", RPH_LIMIT_TYPE_Incr)
------ Secondary profesion
RPH_AddQuest(909, 1, 8, 29512, 250, "nil", RPH_LIMIT_TYPE_Aid)
RPH_AddQuest(909, 1, 8, 29507, 250, "nil", RPH_LIMIT_TYPE_Arch)
RPH_AddQuest(909, 1, 8, 29509, 250, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(909, 1, 8, 29513, 250, "nil", RPH_LIMIT_TYPE_Fish)
---- Decks
------ Minor
RPH_AddItems(909, 1, 8, 25, {[43039] = 1})
RPH_AddItems(909, 1, 8, 25, {[42922] = 1})
RPH_AddItems(909, 1, 8, 25, {[44184] = 1})
RPH_AddItems(909, 1, 8, 25, {[44185] = 1})
------ Major
RPH_AddItems(909, 1, 8, 350, {[19228] = 1})
RPH_AddItems(909, 1, 8, 350, {[62046] = 1})
RPH_AddItems(909, 1, 8, 350, {[19267] = 1})
RPH_AddItems(909, 1, 8, 350, {[31907] = 1})
RPH_AddItems(909, 1, 8, 350, {[62045] = 1})
RPH_AddItems(909, 1, 8, 350, {[31914] = 1})
RPH_AddItems(909, 1, 8, 350, {[31891] = 1})
RPH_AddItems(909, 1, 8, 350, {[62044] = 1})
RPH_AddItems(909, 1, 8, 350, {[62021] = 1})
RPH_AddItems(909, 1, 8, 350, {[19257] = 1})
RPH_AddItems(909, 1, 8, 350, {[19277] = 1})
RPH_AddItems(909, 1, 8, 350, {[31890] = 1})
RPH_AddItems(909, 1, 8, 350, {[44276] = 1})
RPH_AddItems(909, 1, 8, 350, {[44326] = 1})
RPH_AddItems(909, 1, 8, 350, {[44259] = 1})
RPH_AddItems(909, 1, 8, 350, {[44294] = 1})
-- Ravenholdt 349
RPH_AddQuest(349, 4, 4, 6701, 250, {[17124] = 1})
RPH_AddQuest(349, 4, 8, 8249, 75, {[16885] = 5})
RPH_AddMob(349, 4, 6, "All Syndicate members", 5, zone.Hillsbrad_Foothills)
-- Syndicate 70
RPH_AddMob(70, 1, 4, "Myrokos Silentform", 25, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Winstone Wolfe", 5, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Lord Jorach Ravenholdt", 5, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Fahrad", 5, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Zan Shivsproket", 5, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Smudge Thunderwood", 5, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Simone Cantrell", 5, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Master Kang", 5, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Carlo Aurelius", 5, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Ravenholdt Assassin", 5, zone.Hillsbrad_Foothills)
RPH_AddMob(70, 1, 4, "Ravenholdt Guard", 5, zone.Hillsbrad_Foothills)
-- Thorium Brotherhood 59
RPH_AddQuest(59, 4, 6, 13662, 25, {[18945] = 4})
RPH_AddQuest(59, 4, 6, 7737, 625, {[18945] = 100})
RPH_AddQuest(59, 4, 8, 6642, 300, {[11370] = 10})
RPH_AddQuest(59, 4, 8, 6645, 1400, {[17012] = 2})
RPH_AddQuest(59, 4, 8, 6646, 2000, {[11382] = 1})
RPH_AddQuest(59, 4, 8, 6643, 2000, {[17010] = 1})
RPH_AddQuest(59, 4, 8, 6644, 2000, {[17011] = 1})
-- Timbermaw Hold 576
RPH_AddQuest(576, 2, 8, 28395, 2000, {[21377] = 5})
RPH_AddQuest(576, 2, 8, 28396, 2000, {[21377] = 5})
RPH_AddQuest(576, 2, 8, 28523, 2000, {[21383] = 5})
RPH_AddMob(576, 2, 6, "Deadwood Avenger, Den Watcher, Shaman, Gardener, Pathfinder & Warrior", 20, zone.Felwood)
RPH_AddMob(576, 2, 6, "Winterfell Runner, Den Watcher, Shaman, Pathfinder, Totemic, & Ursa", 20, zone.Winterspring)
RPH_AddMob(576, 2, 8, "Chieftain Bloodmaw", 60, zone.Felwood)
RPH_AddMob(576, 2, 8, "Overlord Ror", 60, zone.Felwood)
RPH_AddMob(576, 2, 8, "Ragepaw (Rare)", 50, zone.Felwood)
RPH_AddMob(576, 2, 8, "Grizzle Snowpaw (Rare)", 50, zone.Winterspring)
RPH_AddMob(576, 2, 8, "High Chief Winterfall", 50, zone.Winterspring)
-- TODO: Fix wintersaber quest
-- Wintersaber Trainers 589
--RPH_AddQuest(589, 4, 8, 29037, 1500)
--RPH_AddQuest(589, 4, 8, 29035, 1500)
--RPH_AddQuest(589, 4, 8, 29038, 1500)
--RPH_AddQuest(589, 4, 8, 29040, 1500)
-- Raid_Factions
-- Ashtongue Deathsworn 1012
RPH_AddInstance(1012, 4, 8, zone.Black_Temple, 8000)
-- Brood of Nozdormu 910
RPH_AddMob(910, 1, 4, "Anubisath Defender", 100, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 4, "Anubisath Sentinel", 100, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 4, "Obsidian Eradicator", 100, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 4, "Qiraj Lasher", 100, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 4, "Vekniss Hive Crawler", 100, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 4, "Vekniss Soldier", 100, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 4, "Vekniss Stinger", 100, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 4, "Vekniss Warrior", 100, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 4, "Vekniss Wasp", 100, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 8, "Most Bosses", 50)
RPH_AddMob(910, 1, 8, "Ossirian", 100, zone.Ruins_of_AhnQiraj)
RPH_AddMob(910, 1, 8, "Twin Emperors", 200, zone.Temple_of_AhnQiraj)
RPH_AddMob(910, 1, 8, "Cthun", 2500, zone.Temple_of_AhnQiraj)
RPH_AddItems(910, 1, 8, 500, {[21229] = 1})
RPH_AddItems(910, 1, 8, 1000, {[21230] = 1})
-- Cenarion Circle 609
RPH_AddQuest(609, 4, 8, 8319, 500, {[20404] = 10})
RPH_AddInstance(609, 4, 8, zone.Ruins_of_AhnQiraj, 1200)
RPH_AddInstance(609, 4, 8, zone.AhnQiraj_The_Fallen_Kingdom, nil)
RPH_AddMob(609, 4, 5, "Any Twilight's Hammer mobs", 10)
RPH_AddItems(609, 1, 8, 500, {[21229] = 1})
-- Hydraxian Waterlords 749
RPH_AddMob(749, 4, 5, "Desert Rumbler, Dust Stormer", 5, zone.Silithus)
RPH_AddMob(749, 4, 5, "Greater Obsidian Elemental", 5, zone.Burning_Steppes)
RPH_AddMob(749, 4, 6, "Lord Incendius", 15, zone.Blackrock_Depths)
RPH_AddMob(749, 4, 6, "Huricanian (Rare)", 25, zone.Silithus)
RPH_AddMob(749, 4, 6, "Pyroguard Emberseer", 50, zone.Blackrock_Spire)
RPH_AddMob(749, 4, 6, "Molten Core Trash", 20, zone.Molten_Core)
RPH_AddMob(749, 4, 6, "Molten Destroyer & Lava Pack", 40, zone.Molten_Core)
RPH_AddInstance(749, 4, 7, zone.Molten_Core, 1050)
RPH_AddInstance(749, 8, 8, zone.Molten_Core, 350)
-- The Scale of the Sands 990
RPH_AddInstance(990, 5, 8, zone.Hyjal_Summit, 7900)
RPH_AddMob(990, 4, 8, 0, 12, zone.Hyjal_Summit)
RPH_AddMob(990, 4, 8, "Frost Wyrm", 60, zone.Hyjal_Summit)
RPH_AddMob(990, 4, 8, 0, 375, zone.Hyjal_Summit)
RPH_AddMob(990, 4, 8, "Archimonde", 1500, zone.Hyjal_Summit)
-- The Violet Eye 967
RPH_AddInstance(967, 4, 8, zone.Old_Hillsbrad_Foothills, 6000, false)
RPH_AddMob(967, 4, 8, 0, 250, zone.Karazhan)
RPH_AddMob(967, 4, 8, 0, 15, zone.Karazhan)
-- Outlands (Burning Crusade)
-- Cenarion Expedition 942
RPH_AddInstance(942, 4, 5, zone.The_Slave_Pens, 650, false)
RPH_AddInstance(942, 6, 8, zone.The_Slave_Pens, 650, true)
RPH_AddInstance(942, 4, 5, zone.The_Underbog, 1000, false)
RPH_AddInstance(942, 6, 8, zone.The_Underbog, 1000, true)
RPH_AddInstance(942, 4, 8, zone.The_Steamvault, 1662, false)
RPH_AddInstance(942, 4, 8, zone.The_Steamvault, 2319, true)
RPH_AddQuest(942, 4, 5, 9802, 250, {[24401] = 10})
RPH_AddQuest(942, 4, 6, 9875, 500)
RPH_AddQuest(942, 4, 8, 11867, 150)
RPH_AddMob(942, 4, 4, "Steam Pump Overseer", 1, zone.Zangarmarsh)
RPH_AddMob(942, 4, 4, "Wrekt Slave", 2.5, zone.Zangarmarsh)
RPH_AddMob(942, 4, 4, "Dreghood Drudge", 2.5, zone.Zangarmarsh)
RPH_AddMob(942, 4, 4, "Bloodscale Overseer", 5, zone.Zangarmarsh)
RPH_AddMob(942, 4, 4, "Bloodscale Wavecaller", 5, zone.Zangarmarsh)
RPH_AddMob(942, 4, 4, "Darkcrest Sorceress", 5, zone.Zangarmarsh)
RPH_AddMob(942, 4, 4, "Darkcrest Slaver", 5, zone.Zangarmarsh)
RPH_AddMob(942, 4, 4, "Terrorclaw", 7, zone.Zangarmarsh)
-- Timewalking Commendation
RPH_AddItems(942, 1, 8, 500, {[129949] = 1})
-- Keepers of Time 989
RPH_AddInstance(989, 4, 8, zone.Old_Hillsbrad_Foothills, 1133, false)
RPH_AddInstance(989, 4, 8, zone.Old_Hillsbrad_Foothills, 2445, true)
RPH_AddInstance(989, 4, 8, zone.The_Black_Morass, 1110, false)
RPH_AddInstance(989, 4, 8, zone.The_Black_Morass, 1725, true)
-- Timewalking Commendation
RPH_AddItems(989, 1, 8, 500, {[129950] = 1})
-- Netherwing 1015
RPH_AddQuest(1015, 4, 8, 11050, 250)
RPH_AddQuest(1015, 4, 8, 11017, 250, "nil", RPH_LIMIT_TYPE_Herb)
RPH_AddQuest(1015, 4, 8, 11018, 250, "nil", RPH_LIMIT_TYPE_Mine)
RPH_AddQuest(1015, 4, 8, 11016, 250, "nil", RPH_LIMIT_TYPE_Skin)
RPH_AddQuest(1015, 4, 8, 11020, 250)
RPH_AddQuest(1015, 4, 8, 11035, 250)
RPH_AddQuest(1015, 4, 8, 11015, 250)
RPH_AddQuest(1015, 5, 8, 11077, 350)
RPH_AddQuest(1015, 5, 8, 11076, 350)
RPH_AddQuest(1015, 5, 8, 11055, 350)
RPH_AddQuest(1015, 6, 8, 11086, 500)
RPH_AddQuest(1015, 7, 8, 11101, 500)
-- Ogri'la 1038
RPH_AddQuest(1038, 4, 8, 11080, 350)
RPH_AddQuest(1038, 4, 8, 11066, 350)
RPH_AddQuest(1038, 4, 8, 11023, 500)
RPH_AddQuest(1038, 6, 8, 11051, 350)
-- Sha'tari Skyguard 1031
RPH_AddQuest(1031, 4, 8, 11004, 150)
RPH_AddQuest(1031, 4, 8, 11008, 350)
RPH_AddQuest(1031, 4, 8, 11085, 150)
RPH_AddQuest(1031, 4, 8, 11066, 350)
RPH_AddQuest(1031, 4, 8, 11023, 500)
RPH_AddMob(1031, 4, 6, "Skettis Kaliri", 2.5, zone.Terokkar_Forest)
RPH_AddMob(1031, 4, 8, "Skettis, Talonpriests, Time-Lost Skettis, Monstrous Kaliri", 10, zone.Terokkar_Forest)
RPH_AddMob(1031, 4, 8, "Talonsworn Forest-Rager", 30, zone.Terokkar_Forest)
RPH_AddMob(1031, 4, 8, "Akkarai, Karrog, Gezzarak, Vakkiz", 100, zone.Terokkar_Forest)
RPH_AddMob(1031, 4, 8, "Terokk", 500, zone.Terokkar_Forest)
-- Sporeggar 970
RPH_AddMob(970, 3, 6, "Bog Lords, Bog Giants", 15)
RPH_AddInstance(970, 3, 7, zone.The_Underbog, 15, false)
RPH_AddInstance(970, 3, 7, zone.The_Underbog, 45, true)
RPH_AddQuest(970, 3, 4, 9739, 750)
RPH_AddQuest(970, 3, 5, 9743, 750)
RPH_AddQuest(970, 3, 5, 9744, 750)
RPH_AddQuest(970, 4, 4, 9808, 750)
RPH_AddQuest(970, 5, 8, 9727, 750)
RPH_AddQuest(970, 4, 8, 9807, 750)
RPH_AddQuest(970, 5, 8, 29692, 750)
-- The Consortium 933
RPH_AddInstance(933, 4, 5, zone.Mana_Tombs, 1200, false)
RPH_AddInstance(933, 6, 8, zone.Mana_Tombs, 2400, true)
RPH_AddQuest(933, 4, 4, 9882, 250)
RPH_AddQuest(933, 4, 4, 9915, 250)
RPH_AddQuest(933, 5, 8, 9892, 250)
RPH_AddQuest(933, 5, 8, 10308, 250)
RPH_AddQuest(933, 6, 8, 10971, 250)
RPH_AddQuest(933, 7, 8, 10973, 500)
RPH_AddQuest(933, 4, 8, 99, 250)
RPH_AddQuest(933, 4, 8, 99, 350)
-- Timewalking Commendation
RPH_AddItems(933, 1, 8, 500, {[129945] = 1})
-- Shattrath City
-- Lower City 1011
RPH_AddInstance(1011, 4, 5, zone.Auchenai_Crypts, 750, false)
RPH_AddInstance(1011, 6, 8, zone.Auchenai_Crypts, 750, true)
RPH_AddInstance(1011, 4, 8, zone.Sethekk_Halls, 1080, false)
RPH_AddInstance(1011, 4, 8, zone.Sethekk_Halls, 1250, true)
RPH_AddInstance(1011, 4, 8, zone.Shadow_Labyrinth, 2000, false)
RPH_AddInstance(1011, 4, 8, zone.Shadow_Labyrinth, 2700, true)
RPH_AddQuest(1011, 4, 5, 10917, 250)
-- Timewalking Commendation
RPH_AddItems(1011, 1, 8, 500, {[129951] = 1})
-- Shattered Sun Offensive 1077
RPH_AddQuest(1077, 4, 8, 11875, 250, "nil", RPH_LIMIT_TYPE_Gather)
RPH_AddQuest(1077, 4, 8, 11877, 250)
RPH_AddQuest(1077, 4, 8, 11880, 150)
RPH_AddQuest(1077, 4, 8, 11515, 250)
RPH_AddQuest(1077, 4, 8, 11516, 250)
RPH_AddQuest(1077, 4, 8, 11523, 150)
RPH_AddQuest(1077, 4, 8, 11525, 150)
RPH_AddQuest(1077, 4, 8, 11514, 250)
RPH_AddQuest(1077, 4, 8, 11547, 250)
RPH_AddQuest(1077, 4, 8, 11537, 250)
RPH_AddQuest(1077, 4, 8, 11533, 150)
RPH_AddQuest(1077, 4, 8, 11544, 350)
RPH_AddQuest(1077, 4, 8, 11536, 250)
RPH_AddQuest(1077, 4, 8, 11541, 250)
RPH_AddQuest(1077, 4, 8, 11543, 250)
RPH_AddQuest(1077, 4, 8, 11540, 250)
RPH_AddQuest(1077, 8, 8, 11549, 500)
RPH_AddQuest(1077, 4, 8, 11548, 150)
RPH_AddQuest(1077, 4, 8, 11521, 350)
RPH_AddQuest(1077, 4, 8, 11546, 250)
RPH_AddInstance(1077, 4, 7, zone.Magisters_Terrace, 1640, false)
RPH_AddInstance(1077, 4, 8, zone.Magisters_Terrace, 2503, true)
-- The Aldor 932
RPH_AddQuest(932, 1, 3, 10017, 250, {[25802] = 8})
RPH_AddQuest(932, 4, 5, 10326, 250, {[29425] = 10})
RPH_AddQuest(932, 4, 5, 10327, 25, {[29425] = 1})
RPH_AddQuest(932, 5, 8, 10654, 250, {[30809] = 10})
RPH_AddQuest(932, 5, 8, 10655, 25, {[30809] = 1})
RPH_AddQuest(932, 5, 8, 10420, 350, {[29740] = 1})
-- The Scryers 934
RPH_AddQuest(934, 1, 3, 10024, 250, {[25744] = 8})
RPH_AddQuest(934, 4, 5, 10415, 250, {[29426] = 10})
RPH_AddQuest(934, 4, 5, 10414, 25, {[29426] = 1})
RPH_AddQuest(934, 5, 8, 10658, 250, {[30810] = 10})
RPH_AddQuest(934, 5, 8, 10659, 25, {[30810] = 1})
RPH_AddQuest(934, 5, 8, 10416, 350, {[29739] = 1})
-- The Sha'tar 935
RPH_AddQuest(935, 4, 5, 10326, 125, {[29425] = 10})
RPH_AddQuest(935, 4, 5, 10327, 12.5, {[29425] = 1})
RPH_AddQuest(935, 4, 5, 10654, 125, {[30809] = 10})
RPH_AddQuest(935, 4, 5, 10655, 12.5, {[30809] = 1})
RPH_AddQuest(935, 4, 5, 10415, 125, {[29426] = 10})
RPH_AddQuest(935, 4, 5, 10414, 12.5, {[29426] = 1})
RPH_AddQuest(935, 4, 5, 10658, 125, {[30810] = 10})
RPH_AddQuest(935, 4, 5, 10659, 12.5, {[30810] = 1})
RPH_AddQuest(935, 4, 5, 10017, 125, {[25802] = 8})
RPH_AddQuest(935, 4, 5, 10024, 125, {[25744] = 8})
RPH_AddQuest(935, 4, 5, 10420, 175, {[29740] = 1})
RPH_AddQuest(935, 4, 5, 10416, 175, {[29739] = 1})
RPH_AddInstance(935, 4, 8, zone.The_Mechanar, 1620, false)
RPH_AddInstance(935, 4, 8, zone.The_Mechanar, 3000, true)
RPH_AddInstance(935, 4, 8, zone.The_Botanica, 2000, false)
RPH_AddInstance(935, 4, 8, zone.The_Botanica, 3000, true)
RPH_AddInstance(935, 4, 8, zone.The_Arcatraz, 1800, false)
RPH_AddInstance(935, 4, 8, zone.The_Arcatraz, 3000, true)
-- Timewalking Commendation
RPH_AddItems(935, 1, 8, 500, {[129946] = 1})
-- Northrend (WotLK)
-- Argent Crusade 1106
RPH_AddQuest(1106, 4, 8, 13302, 325)
RPH_AddQuest(1106, 4, 8, 12587, 455)
RPH_AddQuest(1106, 4, 8, 12604, 650)
RPH_AddItems(1106, 4, 8, 520, {[44711] = 1})
-- Timewalking Commendation
RPH_AddItems(1106, 1, 8, 500, {[129942] = 1})
RPH_AddSpell(1106, 1, 8, 5, 1000)
RPH_AddSpell(1106, 1, 8, 5, 1800)
if (RPH_IsDeathKnight) then
RPH_AddQuest(1106, 4, 8, 13809, 325)
RPH_AddQuest(1106, 4, 8, 13810, 325)
RPH_AddQuest(1106, 4, 8, 13862, 325)
RPH_AddQuest(1106, 4, 8, 13811, 325)
end
-- Kirin Tor 1090
RPH_AddQuest(1090, 4, 8, 99, 250, "nil", RPH_LIMIT_TYPE_Cook)
RPH_AddQuest(1090, 4, 8, 99, 250, "nil", RPH_LIMIT_TYPE_Fish)
RPH_AddQuest(1090, 4, 8, 99, 50, "nil", RPH_LIMIT_TYPE_Jewel)
RPH_AddQuest(1090, 4, 8, 99, 125)
RPH_AddQuest(1090, 4, 8, 14203, 325)
RPH_AddQuest(1090, 4, 8, 13845, 325)
RPH_AddItems(1090, 4, 8, 520, {[43950] = 1})
RPH_AddSpell(1090, 1, 8, 5, 1000)
RPH_AddSpell(1090, 1, 8, 5, 1800)
-- Timewalking Commendation
RPH_AddItems(1090, 1, 8, 500, {[129940] = 1})
-- Knights of the Ebon Blade 1098
RPH_AddQuest(1098, 4, 8, 12813, 325)
RPH_AddQuest(1098, 4, 8, 12838, 325)
RPH_AddQuest(1098, 4, 8, 12995, 325)
RPH_AddQuest(1098, 4, 8, 12815, 325)
RPH_AddQuest(1098, 4, 8, 13071, 325)
RPH_AddQuest(1098, 4, 8, 13069, 325)
RPH_AddQuest(1098, 4, 8, 13093, 10)
RPH_AddItems(1098, 4, 8, 520, {[44713] = 1})
RPH_AddSpell(1098, 1, 8, 5, 1000)
RPH_AddSpell(1098, 1, 8, 5, 1800)
if (RPH_IsDeathKnight) then
RPH_AddQuest(1098, 4, 8, 13809, 325)
RPH_AddQuest(1098, 4, 8, 13810, 325)
RPH_AddQuest(1098, 4, 8, 13862, 325)
RPH_AddQuest(1098, 4, 8, 13811, 325)
end
-- Timewalking Commendation
RPH_AddItems(1098, 1, 8, 500, {[129941] = 1})
-- The Ashen Verdict 1156
RPH_AddInstance(1156, 4, 8, zone.Icecrown_Citadel, 2070, false)
RPH_AddInstance(1156, 4, 8, zone.Icecrown_Citadel, 1005, false)
-- The Kalu'ak 1073
RPH_AddQuest(1073, 4, 8, 11945, 500)
RPH_AddQuest(1073, 4, 8, 11960, 500)
RPH_AddQuest(1073, 4, 8, 11472, 500)
-- The Sons of Hodir 1119
RPH_AddQuest(1119, 1, 4, 4, 1)
RPH_AddQuest(1119, 5, 8, 13559, 325)
RPH_AddQuest(1119, 5, 8, 13421, 455)
RPH_AddQuest(1119, 5, 8, 13006, 455)
RPH_AddQuest(1119, 5, 8, 12981, 455)
RPH_AddQuest(1119, 5, 8, 12977, 455)
RPH_AddQuest(1119, 6, 8, 12994, 455)
RPH_AddQuest(1119, 6, 8, 13003, 650)
RPH_AddQuest(1119, 7, 8, 13046, 455)
RPH_AddItems(1119, 4, 8, 520, {[49702] = 1})
-- Timewalking Commendation
RPH_AddItems(1119, 1, 8, 500, {[129943] = 1})
-- The Wyrmrest Accord 1091
RPH_AddQuest(1091, 4, 8, 11940, 325)
RPH_AddQuest(1091, 4, 8, 12372, 325)
RPH_AddQuest(1091, 4, 8, 13414, 325)
RPH_AddItems(1091, 4, 8, 520, {[44710] = 1})
RPH_AddInstance(1091, 4, 8, 5, 800, false)
RPH_AddInstance(1091, 4, 8, 5, 2000, true)
-- Timewalking Commendation
RPH_AddItems(1091, 1, 8, 500, {[129944] = 1})
-- Frenzyheart Tribe 1104
RPH_AddQuest(1104, 1, 5, 12582, 51000)
RPH_AddQuest(1104, 6, 8, 12703, 500)
RPH_AddQuest(1104, 6, 8, 12759, 500)
RPH_AddQuest(1104, 6, 8, 12760, 500)
RPH_AddQuest(1104, 6, 8, 12758, 500)
RPH_AddQuest(1104, 6, 8, 12702, 500)
RPH_AddQuest(1104, 6, 8, 12734, 500)
RPH_AddQuest(1104, 6, 8, 12741, 500)
RPH_AddQuest(1104, 6, 8, 12732, 500)
-- The Oracles 1105
RPH_AddQuest(1105, 1, 5, 12689, 23239)
RPH_AddQuest(1105, 6, 8, 12761, 500)
RPH_AddQuest(1105, 6, 8, 12705, 500)
RPH_AddQuest(1105, 6, 8, 12762, 500)
RPH_AddQuest(1105, 6, 8, 12704, 500)
RPH_AddQuest(1105, 6, 8, 12735, 500)
RPH_AddQuest(1105, 6, 8, 12737, 500)
RPH_AddQuest(1105, 6, 8, 12736, 500)
RPH_AddQuest(1105, 6, 8, 12726, 500)
-- Cataclysm
-- Avengers of Hyjal 1204
---- For FIRELAND "NORMAL" ""HC UNKNOWN""
------ (courtesy of Henrik H AKA Szereka <Vendredi> At HELLSCREAM-EU)
RPH_AddMob(1204, 4, 6, "Druid of the Flame", 5, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Cinderweb Spider", 5, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Fire Scorpion", 5, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Cinderweb Spinner", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Cinderweb Drone", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Fire Turtle Hatchling", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Beast Handler", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Cauterizer", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Forward Guard", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Hound Master", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Pathfinder", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Sentinel", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Taskmaster", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Trainee", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Giant Fire Scorpion", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Hell Hound", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Molten Surger", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Patriarch Fire Turtle", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Unbound Pyrelord", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Unbound Smoldering Elemental", 15, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Animator", 16, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Flamewalker Centurion", 16, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Harbringer of Flame", 16, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Matriarch Fire Turtle", 16, zone.Firelands)
RPH_AddMob(1204, 4, 6, "Unbound Blazing Elemental", 16, zone.Firelands)
---- stop at friendly
RPH_AddMob(1204, 4, 7, "Ancient Core Hound", 50, zone.Firelands)
RPH_AddMob(1204, 4, 7, "Blazing Monstrosity", 50, zone.Firelands)
RPH_AddMob(1204, 4, 7, "Flame Archon", 50, zone.Firelands)
RPH_AddMob(1204, 4, 7, "Flamewalker Overseer", 50, zone.Firelands)
RPH_AddMob(1204, 4, 7, "Flamewalker Subjugator", 50, zone.Firelands)
RPH_AddMob(1204, 4, 7, "Kar the Everburning", 50, zone.Firelands)
RPH_AddMob(1204, 4, 7, "Molten Erupter", 50, zone.Firelands)
RPH_AddMob(1204, 4, 7, "Molten Flamefather", 50, zone.Firelands)
RPH_AddMob(1204, 4, 7, "Molten Lord", 50, zone.Firelands)
RPH_AddMob(1204, 4, 7, "Unstable Magma", 50, zone.Firelands)
---- Stop at Honored
RPH_AddMob(1204, 4, 8, "Beth'tilac", 250, zone.Firelands)
RPH_AddMob(1204, 4, 8, "Lord Rhyolith", 250, zone.Firelands)
RPH_AddMob(1204, 4, 8, "Shannox", 250, zone.Firelands)
RPH_AddMob(1204, 4, 8, "Majordomo Staghelm", 400, zone.Firelands)
-- Guardians of Hyjal 1158
RPH_AddQuest(1158, 4, 8, 29177, 250, RPH_LIMIT_TYPE_FALSE)
RPH_AddQuest(1158, 4, 8, 29163, 250, RPH_LIMIT_TYPE_TRUE)
RPH_AddQuest(1158, 4, 8, 29122, 250)
RPH_AddQuest(1158, 4, 8, 29162, 250)
RPH_AddQuest(1158, 4, 8, 29246, 250)
RPH_AddQuest(1158, 4, 8, 29148, 250)
RPH_AddQuest(1158, 4, 8, 29247, 250)
RPH_AddQuest(1158, 4, 8, 29165, 250)
RPH_AddQuest(1158, 4, 8, 29126, 250)
RPH_AddQuest(1158, 4, 8, 29248, 250)
RPH_AddQuest(1158, 4, 8, 29128, 350)
RPH_AddQuest(1158, 4, 8, 29138, 250)
RPH_AddQuest(1158, 4, 8, 29179, 250)
RPH_AddQuest(1158, 4, 8, 29141, 250)
RPH_AddQuest(1158, 4, 8, 29139, 250)
RPH_AddQuest(1158, 4, 8, 29304, 250)
RPH_AddQuest(1158, 4, 8, 29137, 250)
RPH_AddQuest(1158, 4, 8, 29143, 250)
RPH_AddQuest(1158, 4, 8, 29142, 250)
RPH_AddQuest(1158, 4, 8, 29101, 150)
RPH_AddQuest(1158, 4, 8, 29161, 150)
RPH_AddQuest(1158, 4, 8, 29147, 150)
RPH_AddQuest(1158, 4, 8, 29164, 150)
RPH_AddQuest(1158, 4, 8, 29125, 150)
RPH_AddInstance(1158, 4, 8, 5, 1000, false)
RPH_AddInstance(1158, 4, 8, 5, 1800, true)
RPH_AddMob(1158, 1, 8, 1, 10, 5)
RPH_AddMob(1158, 1, 8, 1, 15, 6)
RPH_AddMob(1158, 1, 8, 4, 150, 5)
RPH_AddMob(1158, 1, 8, 4, 250, 6)
-- Timewalking Commendation
RPH_AddItems(1158, 1, 8, 500, {[133152] = 1})
-- Ramkahen 1173
RPH_AddSpell(1173, 1, 8, 5, 1000)
RPH_AddSpell(1173, 1, 8, 5, 1800)
RPH_AddMob(1173, 1, 8, 1, 10, 5)
RPH_AddMob(1173, 1, 8, 1, 15, 6)
RPH_AddMob(1173, 1, 8, 4, 150, 5)
RPH_AddMob(1173, 1, 8, 4, 250, 6)
RPH_AddQuest(1173, 4, 8, 28250, 150)
RPH_AddQuest(1173, 4, 8, 28736, 250)
-- Timewalking Commendation
RPH_AddItems(1173, 1, 8, 500, {[133154] = 1})
-- The Earthen Ring 1135
RPH_AddSpell(1135, 1, 8, 5, 1000)
RPH_AddSpell(1135, 1, 8, 5, 1800)
RPH_AddMob(1135, 1, 8, 1, 10, 5)
RPH_AddMob(1135, 1, 8, 1, 15, 6)
RPH_AddMob(1135, 1, 8, 4, 150, 5)
RPH_AddMob(1135, 1, 8, 4, 250, 6)
-- Timewalking Commendation
RPH_AddItems(1135, 1, 8, 500, {[133159] = 1})
-- Therazane 1171
RPH_AddSpell(1171, 1, 8, 5, 1000)
RPH_AddSpell(1171, 1, 8, 5, 1800)
RPH_AddQuest(1171, 4, 8, 28488, 250)
RPH_AddQuest(1171, 4, 8, 27046, 250)
RPH_AddQuest(1171, 4, 8, 26710, 250)
RPH_AddQuest(1171, 4, 8, 27047, 250)
RPH_AddQuest(1171, 4, 8, 27049, 250)
RPH_AddQuest(1171, 4, 8, 27050, 250)
RPH_AddQuest(1171, 4, 8, 27051, 250)
RPH_AddQuest(1171, 4, 8, 27048, 250)
RPH_AddQuest(1171, 5, 8, 28390, 350)
RPH_AddQuest(1171, 5, 8, 28391, 350)
RPH_AddMob(1171, 1, 8, 1, 10, 5)
RPH_AddMob(1171, 1, 8, 1, 15, 6)
RPH_AddMob(1171, 1, 8, 4, 150, 5)
RPH_AddMob(1171, 1, 8, 4, 250, 6)
-- Timewalking Commendation
RPH_AddItems(1171, 1, 8, 500, {[133160] = 1})
-- Mist of Pandaria
-- Golden Lotus 1269
RPH_AddQuest(1269, 1, 8, 30261, 350)
RPH_AddQuest(1269, 1, 8, 30242, 250)
RPH_AddQuest(1269, 1, 8, 30240, 250)
RPH_AddQuest(1269, 1, 8, 30306, 250)
RPH_AddQuest(1269, 1, 8, 30280, 250)
RPH_AddQuest(1269, 1, 8, 30277, 250)
RPH_AddQuest(1269, 1, 8, 30243, 250)
RPH_AddQuest(1269, 1, 8, 30266, 250)
RPH_AddQuest(1269, 1, 8, 32648, 300)
RPH_AddMob(1269, 1, 8, "All normal mobs", 20, zone.Vale_of_Eternal_Blossoms)
RPH_AddMob(1269, 1, 8, "All rare mobs", 400, zone.Vale_of_Eternal_Blossoms)
RPH_AddMob(1269, 1, 8, "Jade Colossus", 100, zone.Vale_of_Eternal_Blossoms)
RPH_AddMob(1269, 1, 8, "Milau", 60, zone.Vale_of_Eternal_Blossoms)
-- Timewalking Commendation
RPH_AddItems(1269, 1, 8, 300, {[143937] = 1})
-- Shado-Pan 1270
RPH_AddQuest(1270, 1, 8, 31198, 250)
RPH_AddQuest(1270, 1, 8, 31114, 250)
RPH_AddQuest(1270, 1, 8, 31113, 250)
RPH_AddQuest(1270, 1, 8, 31047, 250)
RPH_AddQuest(1270, 1, 8, 31044, 250)
RPH_AddQuest(1270, 1, 8, 31120, 250)
RPH_AddQuest(1270, 1, 8, 31043, 250)
RPH_AddQuest(1270, 1, 8, 31199, 250)
RPH_AddQuest(1270, 1, 8, 31041, 250)
RPH_AddQuest(1270, 1, 8, 31201, 250)
RPH_AddQuest(1270, 1, 8, 31200, 250)
RPH_AddQuest(1270, 1, 8, 31048, 250)
RPH_AddQuest(1270, 1, 8, 31045, 250)
RPH_AddQuest(1270, 1, 8, 31049, 250)
RPH_AddQuest(1270, 1, 8, 31046, 250)
RPH_AddQuest(1270, 1, 8, 31042, 250)
RPH_AddQuest(1270, 1, 8, 31061, 250)
RPH_AddQuest(1270, 1, 8, 31116, 250)
RPH_AddQuest(1270, 1, 8, 31040, 250)
RPH_AddQuest(1270, 1, 8, 31196, 250)
RPH_AddQuest(1270, 1, 8, 31204, 250)
RPH_AddQuest(1270, 1, 8, 31203, 250)
RPH_AddQuest(1270, 1, 8, 31197, 250)
RPH_AddQuest(1270, 1, 8, 31119, 250)
RPH_AddQuest(1270, 1, 8, 31039, 250)
RPH_AddQuest(1270, 1, 8, 31117, 250)
RPH_AddQuest(1270, 1, 8, 31062, 250)
RPH_AddQuest(1270, 1, 8, 32650, 300)
-- Timewalking Commendation
RPH_AddItems(1270, 1, 8, 300, {[143936] = 1})
-- The August Celestials 1341
RPH_AddItems(1341, 1, 8, 1000, {[86592] = 1})
RPH_AddQuest(1341, 1, 8, 32657, 1000)
-- Timewalking Commendation
RPH_AddItems(1341, 1, 8, 300, {[143938] = 1})
------ Krasarang Wilds
RPH_AddQuest(1341, 1, 8, 30740, 250)
RPH_AddQuest(1341, 1, 8, 30716, 250)
RPH_AddQuest(1341, 1, 8, 30730, 350)
RPH_AddQuest(1341, 1, 8, 30725, 250)
RPH_AddQuest(1341, 1, 8, 30739, 350)
RPH_AddQuest(1341, 1, 8, 30727, 350)
RPH_AddQuest(1341, 1, 8, 30732, 350)
RPH_AddQuest(1341, 1, 8, 30728, 350)
RPH_AddQuest(1341, 1, 8, 30737, 350)
RPH_AddQuest(1341, 1, 8, 30717, 250)
RPH_AddQuest(1341, 1, 8, 30734, 350)
RPH_AddQuest(1341, 1, 8, 30273, 350)
RPH_AddQuest(1341, 1, 8, 30729, 250)
RPH_AddQuest(1341, 1, 8, 30731, 350)
RPH_AddQuest(1341, 1, 8, 30735, 250)
RPH_AddQuest(1341, 1, 8, 30726, 350)
RPH_AddQuest(1341, 1, 8, 30718, 350)
RPH_AddQuest(1341, 1, 8, 30738, 350)
RPH_AddQuest(1341, 1, 8, 30733, 350)
RPH_AddQuest(1341, 1, 8, 30736, 250)
------ Kun-Lai Summit
RPH_AddQuest(1341, 1, 8, 31517, 250)
RPH_AddQuest(1341, 1, 8, 30879, 250)
RPH_AddQuest(1341, 1, 8, 30880, 250)
RPH_AddQuest(1341, 1, 8, 30881, 250)
RPH_AddQuest(1341, 1, 8, 30882, 250)
RPH_AddQuest(1341, 1, 8, 30885, 250)
RPH_AddQuest(1341, 1, 8, 30883, 250)
RPH_AddQuest(1341, 1, 8, 30902, 250)
RPH_AddQuest(1341, 1, 8, 30907, 250)
------ Townlong Steppes
RPH_AddQuest(1341, 1, 8, 30065, 250)
RPH_AddQuest(1341, 1, 8, 30063, 250)
RPH_AddQuest(1341, 1, 8, 30068, 250)
RPH_AddQuest(1341, 1, 8, 30066, 250)
RPH_AddQuest(1341, 1, 8, 30064, 250)
RPH_AddQuest(1341, 1, 8, 30006, 250)
RPH_AddQuest(1341, 1, 8, 30067, 250)
------ The Jade Forest
RPH_AddQuest(1341, 1, 8, 30954, 250)
RPH_AddQuest(1341, 1, 8, 30953, 250)
RPH_AddQuest(1341, 1, 8, 30958, 250)
RPH_AddQuest(1341, 1, 8, 30925, 250)
RPH_AddQuest(1341, 1, 8, 30955, 250)
RPH_AddQuest(1341, 1, 8, 30959, 250)
RPH_AddQuest(1341, 1, 8, 30957, 250)
RPH_AddQuest(1341, 1, 8, 30956, 350)
RPH_AddQuest(1341, 1, 8, 30952, 300)
-- The Klaxxi 1337
RPH_AddQuest(1337, 1, 8, 31268, 130, {[85885] = 3})
RPH_AddQuest(1337, 4, 8, 31603, 250, {[87903] = 5})
-- Timewalking Commendation
RPH_AddItems(1337, 1, 8, 300, {[143935] = 1})
RPH_AddQuest(1337, 1, 8, 31808, 130)
RPH_AddQuest(1337, 1, 8, 31232, 130)
RPH_AddQuest(1337, 1, 8, 31270, 130)
RPH_AddQuest(1337, 1, 8, 31271, 130)
RPH_AddQuest(1337, 1, 8, 31238, 130)
RPH_AddQuest(1337, 1, 8, 31109, 130)
RPH_AddQuest(1337, 1, 8, 31216, 130)
RPH_AddQuest(1337, 1, 8, 31237, 130)
RPH_AddQuest(1337, 1, 8, 31231, 130)
RPH_AddQuest(1337, 1, 8, 31111, 130)
RPH_AddQuest(1337, 1, 8, 31509, 130)
RPH_AddQuest(1337, 1, 8, 31494, 130)
RPH_AddQuest(1337, 1, 8, 31272, 130)
RPH_AddQuest(1337, 1, 8, 31024, 130)
RPH_AddQuest(1337, 1, 8, 31598, 130)
RPH_AddQuest(1337, 1, 8, 31507, 130)
RPH_AddQuest(1337, 1, 8, 31267, 130)
RPH_AddQuest(1337, 1, 8, 31235, 130)
RPH_AddQuest(1337, 1, 8, 31504, 130)
RPH_AddQuest(1337, 1, 8, 31234, 130)
RPH_AddQuest(1337, 1, 8, 31510, 130)
RPH_AddQuest(1337, 1, 8, 31496, 130)
RPH_AddQuest(1337, 1, 8, 31233, 130)
RPH_AddQuest(1337, 1, 8, 31506, 130)
RPH_AddQuest(1337, 1, 8, 31503, 130)
RPH_AddQuest(1337, 1, 8, 31487, 130)
RPH_AddQuest(1337, 1, 8, 31508, 130)
RPH_AddQuest(1337, 1, 8, 31599, 130)
RPH_AddQuest(1337, 1, 8, 31269, 130)
RPH_AddQuest(1337, 1, 8, 31505, 130)
RPH_AddQuest(1337, 1, 8, 31502, 130)
RPH_AddQuest(1337, 1, 8, 31677, 130)
RPH_AddQuest(1337, 1, 8, 32659, 400)
-- Order of the Cloud Serpent 1271
RPH_AddItems(1271, 1, 8, 1000, {[86592] = 1})
-- Timewalking Commendation
RPH_AddItems(1271, 1, 8, 300, {[143942] = 1})
RPH_AddQuest(1271, 4, 8, 99, 780)
RPH_AddQuest(1271, 4, 8, 99, 780)
RPH_AddQuest(1271, 4, 8, 99, 780)
RPH_AddQuest(1271, 4, 8, 99, 780)
------ Jenova Longeye - Main Quests
RPH_AddQuest(1271, 1, 8, 30149, 125)
RPH_AddQuest(1271, 1, 8, 30147, 125)
RPH_AddQuest(1271, 1, 8, 30148, 125)
RPH_AddQuest(1271, 1, 8, 30146, 125)
------ Instructor Skythorn
RPH_AddQuest(1271, 1, 8, 31707, 450)
RPH_AddQuest(1271, 1, 8, 30158, 450)
RPH_AddQuest(1271, 1, 8, 30155, 450)
RPH_AddQuest(1271, 1, 8, 31698, 450)
RPH_AddQuest(1271, 1, 8, 31706, 450)
------ Your Hatchling
RPH_AddQuest(1271, 1, 8, 30151, 450)
RPH_AddQuest(1271, 1, 8, 30156, 450)
RPH_AddQuest(1271, 1, 8, 31704, 450)
RPH_AddQuest(1271, 1, 8, 31708, 450)
RPH_AddQuest(1271, 1, 8, 30150, 450)
RPH_AddQuest(1271, 1, 8, 30154, 450)
RPH_AddQuest(1271, 1, 8, 31710, 450)
------ Elder Anli <Serpent Master>
RPH_AddQuest(1271, 1, 8, 31701, 600)
RPH_AddQuest(1271, 1, 8, 30157, 450)
RPH_AddQuest(1271, 1, 8, 31709, 450)
RPH_AddQuest(1271, 1, 8, 31703, 600)
RPH_AddQuest(1271, 1, 8, 31712, 450)
RPH_AddQuest(1271, 1, 8, 31705, 600)
RPH_AddQuest(1271, 1, 8, 31702, 600)
RPH_AddQuest(1271, 1, 8, 30159, 450)
RPH_AddQuest(1271, 1, 8, 31714, 450)
RPH_AddQuest(1271, 1, 8, 31194, 600)
RPH_AddQuest(1271, 1, 8, 31699, 450)
RPH_AddQuest(1271, 1, 8, 31713, 450)
RPH_AddQuest(1271, 1, 8, 31715, 600)
RPH_AddQuest(1271, 1, 8, 31711, 600)
RPH_AddQuest(1271, 1, 8, 31700, 450)
RPH_AddQuest(1271, 1, 8, 30152, 600)
RPH_AddQuest(1271, 1, 8, 31718, 450)
-- Shang Xi's Academy 1216
RPH_AddQuest(1216, 1, 8, 5, 1)
-- The Black Prince 1359
RPH_AddQuest(1359, 1, 8, 5, 1)
RPH_AddMob(1359, 1, 7, "Granite Quilen", 10)
RPH_AddMob(1359, 1, 7, "Shao-Tien Marauder", 10)
RPH_AddMob(1359, 1, 7, "Kor'thik Warcaller", 100)
RPH_AddMob(1359, 1, 7, "Rare Mobs", 400, "928")
-- The Lorewalkers 1345
RPH_AddQuest(1345, 1, 8, 5, 1)
-- The Anglers (group)
-- The Anglers 1302
RPH_AddQuest(1302, 1, 8, 30613, 500)
RPH_AddQuest(1302, 1, 8, 30754, 500)
RPH_AddQuest(1302, 1, 8, 30588, 500)
RPH_AddQuest(1302, 1, 8, 31443, 350, {[86542] = 1})
RPH_AddQuest(1302, 1, 8, 30658, 500)
RPH_AddQuest(1302, 1, 8, 30586, 500)
RPH_AddQuest(1302, 1, 8, 30753, 500)
RPH_AddQuest(1302, 1, 8, 30678, 500)
RPH_AddQuest(1302, 1, 8, 31446, 350, {[86545] = 1})
RPH_AddQuest(1302, 1, 8, 30763, 500)
RPH_AddQuest(1302, 1, 8, 30698, 500)
RPH_AddQuest(1302, 1, 8, 30584, 500)
RPH_AddQuest(1302, 1, 8, 30700, 500)
RPH_AddQuest(1302, 1, 8, 31444, 350, {[86544] = 1})
RPH_AddQuest(1302, 1, 8, 30701, 500)
RPH_AddQuest(1302, 1, 8, 30585, 500)
RPH_AddQuest(1302, 1, 8, 30598, 500)
-- Timewalking Commendation
RPH_AddItems(1302, 1, 8, 300, {[143946] = 1})
-- Nat Pagle 1358
RPH_AddQuest(1358, 1, 8, 36804, 350, {[116820] = 1})
RPH_AddQuest(1358, 1, 8, 39283, 350, {[127994] = 1})
RPH_AddQuest(1358, 1, 8, 36800, 350, {[116819] = 1})
RPH_AddQuest(1358, 1, 8, 36802, 350, {[116818] = 1})
RPH_AddQuest(1358, 1, 8, 36805, 350, {[116821] = 1})
RPH_AddQuest(1358, 1, 8, 38406, 350, {[122696] = 1})
RPH_AddQuest(1358, 1, 8, 36803, 350, {[116817] = 1})
RPH_AddQuest(1358, 1, 8, 36806, 350, {[116822] = 1})
RPH_AddQuest(1358, 1, 8, 31443, 600, {[86542] = 1})
RPH_AddQuest(1358, 1, 8, 31444, 600, {[86544] = 1})
RPH_AddQuest(1358, 1, 8, 31446, 600, {[86545] = 1})
-- The Tillers (group)
-- The Tillers 1272
RPH_AddGeneral(1272, 1, 8, "1", 50, "1", "0", nil, 0)
-- Timewalking Commendation
RPH_AddItems(1272, 1, 8, 300, {[143941] = 1})
------ Farmer Yoon
-------- Main
RPH_AddQuest(1272, 1, 8, 30337, 1000)
RPH_AddQuest(1272, 1, 8, 30335, 1000)
RPH_AddQuest(1272, 1, 8, 30334, 1000)
RPH_AddQuest(1272, 1, 8, 30336, 1000)
RPH_AddQuest(1272, 1, 8, 30333, 1000)
-------- Farm
RPH_AddQuest(1272, 1, 8, 31672, 350)
RPH_AddQuest(1272, 1, 8, 31942, 350)
RPH_AddQuest(1272, 1, 8, 31673, 350)
RPH_AddQuest(1272, 1, 8, 31941, 350)
RPH_AddQuest(1272, 1, 8, 31670, 350)
RPH_AddQuest(1272, 1, 8, 31669, 350)
RPH_AddQuest(1272, 1, 8, 31674, 350)
RPH_AddQuest(1272, 1, 8, 31675, 350)
RPH_AddQuest(1272, 1, 8, 31943, 350)
RPH_AddQuest(1272, 1, 8, 31671, 350)
------ Tillers Union:
RPH_AddQuest(1272, 1, 8, 30318, 150)
RPH_AddQuest(1272, 1, 8, 30322, 150)
RPH_AddQuest(1272, 1, 8, 30324, 150)
RPH_AddQuest(1272, 1, 8, 30319, 150)
RPH_AddQuest(1272, 1, 8, 30326, 150)
RPH_AddQuest(1272, 1, 8, 30323, 150)
RPH_AddQuest(1272, 1, 8, 30317, 150)
RPH_AddQuest(1272, 1, 8, 30321, 150)
RPH_AddQuest(1272, 1, 8, 30325, 150)
RPH_AddQuest(1272, 1, 8, 30327, 150)
-------- Tillers Union: Gifts
RPH_AddQuest(1272, 1, 8, 30471, 150)
RPH_AddQuest(1272, 1, 8, 30474, 150)
RPH_AddQuest(1272, 1, 8, 30475, 150)
RPH_AddQuest(1272, 1, 8, 30473, 150)
RPH_AddQuest(1272, 1, 8, 30479, 150)
RPH_AddQuest(1272, 1, 8, 30477, 150)
RPH_AddQuest(1272, 1, 8, 30478, 150)
RPH_AddQuest(1272, 1, 8, 30476, 150)
RPH_AddQuest(1272, 1, 8, 30472, 150)
RPH_AddQuest(1272, 1, 8, 30470, 150)
-- Chee Chee 1277
RPH_AddQuest(1277, 1, 8, 30471, 1400, {[79827] = 1})
RPH_AddQuest(1277, 1, 8, 30402, 1800, {[74647] = 5})
RPH_AddQuest(1277, 1, 8, 30324, 2000)
RPH_AddItems(1277, 1, 8, 900, {[79265] = 1})
RPH_AddItems(1277, 1, 8, 540, {[79264] = 1})
RPH_AddItems(1277, 1, 8, 540, {[79266] = 1})
RPH_AddItems(1277, 1, 8, 540, {[79267] = 1})
RPH_AddItems(1277, 1, 8, 540, {[79268] = 1})
-- Ella 1275
RPH_AddQuest(1275, 1, 8, 30474, 1400, {[79871] = 1})
RPH_AddQuest(1275, 1, 8, 30386, 1800, {[74651] = 5})
RPH_AddQuest(1275, 1, 8, 30327, 2000)
RPH_AddItems(1275, 1, 8, 900, {[79266] = 1})
RPH_AddItems(1275, 1, 8, 540, {[79264] = 1})
RPH_AddItems(1275, 1, 8, 540, {[79265] = 1})
RPH_AddItems(1275, 1, 8, 540, {[79267] = 1})
RPH_AddItems(1275, 1, 8, 540, {[79268] = 1})
-- Farmer Fung 1283
RPH_AddQuest(1283, 1, 8, 30475, 1400, {[80233] = 1})
RPH_AddQuest(1283, 1, 8, 30421, 1800, {[74654] = 5})
RPH_AddQuest(1283, 1, 8, 30317, 2000)
RPH_AddItems(1283, 1, 8, 900, {[79268] = 1})
RPH_AddItems(1283, 1, 8, 540, {[79264] = 1})
RPH_AddItems(1283, 1, 8, 540, {[79265] = 1})
RPH_AddItems(1283, 1, 8, 540, {[79266] = 1})
RPH_AddItems(1283, 1, 8, 540, {[79267] = 1})
-- Fish Fellreed 1282
RPH_AddQuest(1282, 1, 8, 30473, 1400, {[79828] = 1})
RPH_AddQuest(1282, 1, 8, 30427, 1800, {[74655] = 5})
RPH_AddQuest(1282, 1, 8, 30326, 2000)
RPH_AddItems(1282, 1, 8, 900, {[79266] = 1})
RPH_AddItems(1282, 1, 8, 540, {[79264] = 1})
RPH_AddItems(1282, 1, 8, 540, {[79265] = 1})
RPH_AddItems(1282, 1, 8, 540, {[79267] = 1})
RPH_AddItems(1282, 1, 8, 540, {[79268] = 1})
-- Gina Mudclaw 1281
RPH_AddQuest(1281, 1, 8, 30479, 1400, {[80231] = 1})
RPH_AddQuest(1281, 1, 8, 30390, 1800, {[74644] = 5})
RPH_AddQuest(1281, 1, 8, 30322, 2000)
RPH_AddItems(1281, 1, 8, 900, {[79268] = 1})
RPH_AddItems(1281, 1, 8, 540, {[79264] = 1})
RPH_AddItems(1281, 1, 8, 540, {[79265] = 1})
RPH_AddItems(1281, 1, 8, 540, {[79266] = 1})
RPH_AddItems(1281, 1, 8, 540, {[79267] = 1})
-- Haohan Mudclaw 1279
RPH_AddQuest(1279, 1, 8, 30477, 1400, {[80228] = 1})
RPH_AddQuest(1279, 1, 8, 30414, 1800, {[74642] = 5})
RPH_AddQuest(1279, 1, 8, 30319, 2000)
RPH_AddItems(1279, 1, 8, 900, {[79264] = 1})
RPH_AddItems(1279, 1, 8, 540, {[79265] = 1})
RPH_AddItems(1279, 1, 8, 540, {[79266] = 1})
RPH_AddItems(1279, 1, 8, 540, {[79267] = 1})
RPH_AddItems(1279, 1, 8, 540, {[79268] = 1})
-- Jogu the Drunk 1273
RPH_AddQuest(1273, 1, 8, 30478, 1400, {[80236] = 1})
RPH_AddQuest(1273, 1, 8, 30439, 1800, {[74643] = 5})
RPH_AddQuest(1273, 1, 8, 30321, 2000)
RPH_AddItems(1273, 1, 8, 900, {[79267] = 1})
RPH_AddItems(1273, 1, 8, 540, {[79264] = 1})
RPH_AddItems(1273, 1, 8, 540, {[79265] = 1})
RPH_AddItems(1273, 1, 8, 540, {[79266] = 1})
RPH_AddItems(1273, 1, 8, 540, {[79268] = 1})
-- Old Hillpaw 1276
RPH_AddQuest(1276, 1, 8, 30476, 1400, {[80229] = 1})
RPH_AddQuest(1276, 1, 8, 30396, 1800, {[74649] = 5})
RPH_AddQuest(1276, 1, 8, 30318, 2000)
RPH_AddItems(1276, 1, 8, 900, {[79265] = 1})
RPH_AddItems(1276, 1, 8, 540, {[79264] = 1})
RPH_AddItems(1276, 1, 8, 540, {[79266] = 1})
RPH_AddItems(1276, 1, 8, 540, {[79267] = 1})
RPH_AddItems(1276, 1, 8, 540, {[79268] = 1})
-- Sho 1278
RPH_AddQuest(1278, 1, 8, 30472, 1400, {[79870] = 1})
RPH_AddQuest(1278, 1, 8, 30408, 1800, {[74645] = 5})
RPH_AddQuest(1278, 1, 8, 30325, 2000)
RPH_AddItems(1278, 1, 8, 900, {[79267] = 1})
RPH_AddItems(1278, 1, 8, 540, {[79264] = 1})
RPH_AddItems(1278, 1, 8, 540, {[79265] = 1})
RPH_AddItems(1278, 1, 8, 540, {[79266] = 1})
RPH_AddItems(1278, 1, 8, 540, {[79268] = 1})
-- Tina Mudclaw 1280
RPH_AddQuest(1280, 1, 8, 30470, 1400, {[80134] = 1})
RPH_AddQuest(1280, 1, 8, 30433, 1800, {[74652] = 5})
RPH_AddQuest(1280, 1, 8, 30323, 2000)
RPH_AddItems(1280, 1, 8, 900, {[79264] = 1})
RPH_AddItems(1280, 1, 8, 540, {[79265] = 1})
RPH_AddItems(1280, 1, 8, 540, {[79266] = 1})
RPH_AddItems(1280, 1, 8, 540, {[79267] = 1})
RPH_AddItems(1280, 1, 8, 540, {[79268] = 1})
-- Emperor Shaohao 1492
RPH_AddQuest(1492, 1, 8, 33335, 250)
RPH_AddQuest(1492, 1, 8, 33340, 250)
RPH_AddQuest(1492, 1, 8, 33341, 250)
RPH_AddQuest(1492, 1, 8, 33342, 250)
RPH_AddQuest(1492, 1, 8, 33343, 250)
RPH_AddQuest(1492, 1, 8, 33374, 250)
RPH_AddMob(1492, 1, 7, "Archiereus of Flame", 50, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Cinderfall", 40, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Flintlord Gairan", 40, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Urdur the Cauterizer", 40, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Champion of the Black Flame", 30, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "High Priest of Ordos", 25, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Blazebound Chanter", 20, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Eternal Kiln", 20, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Eternal Kilnmaster", 20, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Jakur of Ordan", 20, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Molten Guardian", 20, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Watcher Osu", 20, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Burning Berserker", 15, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Ordon Fire-Watcher", 10, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Ordon Oathguard", 10, zone.Timeless_Isle)
RPH_AddMob(1492, 1, 7, "Ordon Candlekeeper", 5, zone.Timeless_Isle)
-- Timewalking Commendation
RPH_AddItems(1492, 1, 8, 500, {[143947] = 1})
-- Shado-Pan Assault 1435
RPH_AddQuest(1435, 1, 8, 32640, 300, {[94221] = 3})
RPH_AddQuest(1435, 1, 8, 32641, 300, {[94221] = 3})
RPH_AddQuest(1435, 1, 8, 32707, 200, {[94221] = 3})
RPH_AddQuest(1435, 1, 8, 32708, 300)
RPH_AddMob(1435, 1, 5, 1, 30, zone.Throne_of_Thunder)
RPH_AddMob(1435, 1, 8, 3, 30, zone.Throne_of_Thunder)
-- Timewalking Commendation
RPH_AddItems(1435, 1, 8, 300, {[143945] = 1})
-- WoD Factions
-- Arakkoa Outcasts 1515
RPH_AddItems(1515, 1, 8, 1000, {[128315] = 1})
RPH_AddMob(1515, 1, 8, "Amorphic Cognitor at Lost Veil Anzu", 5, ZONE.Spires_of_Arak)
RPH_AddMob(1515, 1, 8, "Befuddled Relic-Seeker at Lost Veil Anzu", 5, ZONE.Spires_of_Arak)
RPH_AddMob(1515, 1, 7, "Highmaul Skullcrusher at Lost Veil Anzu", 5,ZONE.Spires_of_Arak)
RPH_AddMob(1515, 1, 8, "Infected Plunderer at Lost Veil Anzu", 5, ZONE.Spires_of_Arak)
RPH_AddMob(1515, 1, 8, "Darting Swift Feather at Skettis", 1, ZONE.Spires_of_Arak)
RPH_AddMob(1515, 1, 8, "Flighted Storm-Spinner at Skettis", 5, ZONE.Spires_of_Arak)
RPH_AddMob(1515, 1, 8, "Skyreach Dawnbreaker at Skettis", 16, ZONE.Spires_of_Arak)
RPH_AddMob(1515, 1, 8, "Skyreach Dreadtalon at Skettis", 5, ZONE.Spires_of_Arak)
RPH_AddMob(1515, 1, 8, "Skyreach Labormaster at Skettis", 5, ZONE.Spires_of_Arak)
-- Steamwheedle Preservation Society 1711
RPH_AddItems(1711, 1, 8, 1000, {[128315] = 1})
RPH_AddQuest(1711, 1, 8, 35147, 250, {[118099] = 20})
RPH_AddQuest(1711, 1, 8, 35125, 350, {[118100] = 1})
RPH_AddQuest(1711, 1, 8, 37210, 500, {[118654] = 1})
RPH_AddQuest(1711, 1, 8, 37211, 500, {[118655] = 1})
RPH_AddQuest(1711, 1, 8, 37221, 500, {[118656] = 1})
RPH_AddQuest(1711, 1, 8, 37222, 500, {[118657] = 1})
RPH_AddQuest(1711, 1, 8, 37223, 500, {[118658] = 1})
RPH_AddQuest(1711, 1, 8, 37224, 500, {[118659] = 1})
RPH_AddQuest(1711, 1, 8, 37225, 500, {[118660] = 1})
RPH_AddQuest(1711, 1, 8, 37226, 500, {[118661] = 1})
RPH_AddQuest(1711, 1, 8, 37520, 500, {[120172] = 1})
-- Order of the Awakened 1849
RPH_AddItems(1849, 1, 8, 1000, {[128315] = 1})
RPH_AddQuest(1849, 1, 8, 39433, 1500, {[128346] = 10})
-- The Saberstalkers 1850
RPH_AddItems(1850, 1, 8, 1000, {[128315] = 1})
RPH_AddQuest(1850, 1, 8, 39565, 3500)
-- Tooth and Claw quest
if RPH_IsHorde then
RPH_AddQuest(1850, 1, 8, 39529, 1500, {[124099] = 100})
end
if RPH_IsAlliance then
RPH_AddQuest(1850, 1, 8, 39582, 1500, {[124099] = 100})
end
RPH_AddMob(1850, 1, 8, "Blackfang Hunter", 25, ZONE.Tanaan_Jungle)
RPH_AddMob(1850, 1, 8, "Blackfang Prowler", 25, ZONE.Tanaan_Jungle)
RPH_AddMob(1850, 1, 8, "Blackfang Savage", 25, ZONE.Tanaan_Jungle)
RPH_AddMob(1850, 1, 8, "Blackfang Shaman", 25, ZONE.Tanaan_Jungle)
RPH_AddMob(1850, 1, 8, "Soulslicer (Rare elite)", 500, ZONE.Tanaan_Jungle)
RPH_AddMob(1850, 1, 8, "Gloomtalon (Rare elite)", 500, ZONE.Tanaan_Jungle)
RPH_AddMob(1850, 1, 8, "Krell the Serene (Rare elite)", 500, ZONE.Tanaan_Jungle)
RPH_AddMob(1850, 1, 8, "The Blackfang (Rare elite)", 500, ZONE.Tanaan_Jungle)
-- Legion Factions
-- Armies of Legionfall 2045
-- Insignia reputation tokens
RPH_AddItems(2045, 1, 8, 250, {[146949] = 1}, {[146950] = 1})
RPH_AddItems(2045, 1, 8, 750, {[147727] = 1}, {[152464] = 1})
-- Building contributions
RPH_AddQuest(2045, 1, 8, 46277, 150, {[1342] = 100})
RPH_AddQuest(2045, 1, 8, 46736, 150, {[1342] = 100})
RPH_AddQuest(2045, 1, 8, 46735, 150, {[1342] = 100})
-- World Quest
RPH_AddGeneral(2045, 1, 8, "Normal World Quest", 75, "Normal World Quests", "Complete Normal world quests with this faction to gain reputation.")
RPH_AddGeneral(2045, 1, 8, "Rare World Quests", 75, "Rare World Quests", "Complete rare world quests with this faction to gain reputation.")
RPH_AddGeneral(2045, 1, 8, "Rare Elite World Quests", 75, "Rare Elite World Quests", "Complete rare elite world quests with this faction to gain reputation.")
RPH_AddGeneral(2045, 1, 8, "Elite World Quests", 75, "Elite World Quests", "Complete elite world quests with this faction to gain reputation.")
RPH_AddGeneral(2045, 1, 8, "Legionfall Dungeon World Quest", 250, "Legionfall Dungeon World Quest", "Complete dungeon world quests with this faction to gain reputation.")
RPH_AddGeneral(2045, 1, 8, "World Boss World Quest", 500, "World Boss World Quest", "Complete world boss world quests with this faction to gain reputation.")
RPH_AddGeneral(2045, 1, 8, "Raid World Quests", 500, "Epic Elite World Quests", "Complete raid world quests with this faction to gain reputation.")
RPH_AddGeneral(2045, 1, 8, "Armies of Legionfall Emissary", 1500, "Armies of Legionfall Emissary", "Complete 4x Armies of Legionfall world quests while the emissary is available to gain reputation")
-- Court of Farondis 1900
-- Insignia reputation tokens
RPH_AddItems(1900, 1, 8, 250, {[146937] = 1}, {[146943] = 1})
RPH_AddItems(1900, 1, 8, 1500, {[147410] = 1}, {[150927] = 1})
-- World Quest
RPH_AddGeneral(1900, 1, 8, "Normal World Quest", 75, "Normal World Quests", "Complete Normal world quests with this faction to gain reputation.")
RPH_AddGeneral(1900, 1, 8, "PvP World Quest", 75, "PvP World Quests", "Complete PvP world quests with this faction to gain reputation.")
RPH_AddGeneral(1900, 1, 8, "Rare World Quests", 150, "Rare World Quests", "Complete rare world quests with this faction to gain reputation.")
RPH_AddGeneral(1900, 1, 8, "Rare Elite World Quests", 250, "Rare Elite World Quests", "Complete rare elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1900, 1, 8, "Elite World Quests", 250, "Elite World Quests", "Complete elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1900, 1, 8, "Epic Elite World Quests", 250, "Epic Elite World Quests", "Complete epic elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1900, 1, 8, "Dungeon World Quests", 250, "Dungeon World Quests", "Complete dungeon world quests with this faction to gain reputation.")
RPH_AddGeneral(1900, 1, 8, "Work Order World Quests", 250, "Work Order World Quests", "Complete work order world quests with this faction to gain reputation.")
RPH_AddGeneral(1900, 1, 8, "Court of Farondins Emissary", 1500, "Court of Farondins Emissary", "Complete 4x Court of Farondis world quests while the emissary is available to gain reputation")
-- Dreamweavers 1883
-- Insignia reputation tokens
RPH_AddItems(1883, 1, 8, 250, {[146936] = 1}, {[146942] = 1})
RPH_AddItems(1883, 1, 8, 1500, {[147411] = 1}, {[150926] = 1})
-- World Quest
RPH_AddGeneral(1883, 1, 8, "Normal World Quest", 75, "Normal World Quests", "Complete Normal world quests with this faction to gain reputation.")
RPH_AddGeneral(1883, 1, 8, "PvP World Quest", 75, "PvP World Quests", "Complete PvP world quests with this faction to gain reputation.")
RPH_AddGeneral(1883, 1, 8, "Rare World Quests", 150, "Rare World Quests", "Complete rare world quests with this faction to gain reputation.")
RPH_AddGeneral(1883, 1, 8, "Rare Elite World Quests", 250, "Rare Elite World Quests", "Complete rare elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1883, 1, 8, "Epic Elite World Quests", 250, "Epic Elite World Quests", "Complete epic elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1883, 1, 8, "Dungeon World Quests", 250, "Dungeon World Quests", "Complete dungeon world quests with this faction to gain reputation.")
RPH_AddGeneral(1883, 1, 8, "Work Order World Quests", 250, "Work Order World Quests", "Complete work order world quests with this faction to gain reputation.")
RPH_AddGeneral(1883, 1, 8, "Dreamweavers Emissary", 1500, "Dreamweavers Emissary Emissary", "Complete 4x Dreamweavers world quests while the emissary is available to gain reputation")
-- Highmountain Tribe 1828
-- Insignia reputation tokens
RPH_AddItems(1828, 1, 8, 250, {[146938] = 1}, {[146944] = 1})
RPH_AddItems(1828, 1, 8, 1500, {[147412] = 1}, {[150928] = 1})
-- World Quest
RPH_AddGeneral(1828, 1, 8, "Normal World Quest", 75, "Normal World Quests", "Complete Normal world quests with this faction to gain reputation.")
RPH_AddGeneral(1828, 1, 8, "PvP World Quest", 75, "PvP World Quests", "Complete PvP world quests with this faction to gain reputation.")
RPH_AddGeneral(1828, 1, 8, "Epic World Quest", 75, "Epic World Quests", "Complete epic world quests with this faction to gain 75-350 reputation.")
RPH_AddGeneral(1828, 1, 8, "Rare World Quests", 150, "Rare World Quests", "Complete rare world quests with this faction to gain reputation.")
RPH_AddGeneral(1828, 1, 8, "Rare Elite World Quests", 250, "Rare Elite World Quests", "Complete rare elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1828, 1, 8, "Epic Elite World Quests", 250, "Epic Elite World Quests", "Complete epic elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1828, 1, 8, "Dungeon World Quests", 250, "Dungeon World Quests", "Complete dungeon world quests with this faction to gain reputation.")
RPH_AddGeneral(1828, 1, 8, "Work Order World Quests", 250, "Work Order World Quests", "Complete work order world quests with this faction to gain reputation.")
RPH_AddGeneral(1828, 1, 8, "Highmountain Tribe Emissary", 1500, "Highmountain Tribe Emissary", "Complete 4x Highmountain Tribe world quests while the emissary is available to gain reputation")
-- The Nightfallen 1859
-- Insignia reputation tokens
RPH_AddItems(1859, 1, 8, 250, {[146940] = 1}, {[146946] = 1})
RPH_AddItems(1859, 1, 8, 750, {[147413] = 1}, {[150930] = 1})
-- World Quest
RPH_AddGeneral(1859, 1, 8, "Normal World Quest", 75, "Normal World Quests", "Complete Normal world quests with this faction to gain reputation.")
RPH_AddGeneral(1859, 1, 8, "Rare World Quests", 150, "Rare World Quests", "Complete rare world quests with this faction to gain 150-250 reputation.")
RPH_AddGeneral(1859, 1, 8, "Rare Elite World Quests", 250, "Rare Elite World Quests", "Complete rare elite world quests with this faction to gain 250-350 reputation.")
RPH_AddGeneral(1859, 1, 8, "Epic Elite World Quests", 500, "Epic Elite World Quests", "Complete epic elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1859, 1, 8, "Dungeon World Quests", 500, "Dungeon World Quests", "Complete dungeon world quests with this faction to gain reputation.")
RPH_AddGeneral(1859, 1, 8, "Raid World Quests", 500, "Raid World Quests", "Complete Raid world quests with this faction to gain reputation.")
RPH_AddGeneral(1859, 1, 8, "Work Order World Quests", 250, "Work Order World Quests", "Completework order world quests with this faction to gain reputation.")
RPH_AddGeneral(1859, 1, 8, "The Nightfallen Emissary", 1500, "The Nightfallen Emissary", "Complete 4x Nightfallen world quests while the emissary is available to gain reputation")
-- The Wardens 1894
-- Insignia reputation tokens
RPH_AddItems(1894, 1, 8, 250, {[146939] = 1}, {[146945] = 1})
RPH_AddItems(1894, 1, 8, 1500, {[147415] = 1}, {[150929] = 1})
-- World Quest
RPH_AddGeneral(1894, 1, 8, "Normal World Quest", 75, "Normal World Quests", "Complete Normal world quests with this faction to gain reputation.")
RPH_AddGeneral(1894, 1, 8, "Rare World Quests", 150, "Rare World Quests", "Complete rare world quests with this faction to gain reputation.")
RPH_AddGeneral(1894, 1, 8, "Rare Elite World Quests", 250, "Rare Elite World Quests", "Complete rare elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1894, 1, 8, "Epic Elite World Quests", 350, "Epic Elite World Quests", "Complete epic elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1894, 1, 8, "Dungeon World Quests", 250, "Dungeon World Quests", "Complete dungeon world quests with this faction to gain 250-500 reputation.")
RPH_AddGeneral(1894, 1, 8, "Work Order World Quests", 250, "Work Order World Quests", "Complete work order world quests with this faction to gain reputation.")
RPH_AddGeneral(1894, 1, 8, "The Wardens Emissary", 1500, "The Wardens Emissary", "Complete 4x Wardens world quests while the emissary is available to gain reputation")
-- Valarjar 1948
-- Insignia reputation tokens
RPH_AddItems(1948, 1, 8, 250, {[146935] = 1}, {[146941] = 1})
RPH_AddItems(1948, 1, 8, 1500, {[147414] = 1}, {[150925] = 1})
-- World Quest
RPH_AddGeneral(1948, 1, 8, "Normal World Quest", 75, "Normal World Quests", "Complete Normal world quests with this faction to gain reputation.")
RPH_AddGeneral(1948, 1, 8, "PvP World Quest", 75, "PvP World Quests", "Complete PvP world quests with this faction to gain reputation.")
RPH_AddGeneral(1948, 1, 8, "Rare World Quests", 150, "Rare World Quests", "Complete rare world quests with this faction to gain 150-250 reputation.")
RPH_AddGeneral(1948, 1, 8, "Rare Elite World Quests", 250, "Rare Elite World Quests", "Complete rare elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1948, 1, 8, "Epic Elite World Quests", 250, "Epic Elite World Quests", "Complete epic elite world quests with this faction to gain reputation.")
RPH_AddGeneral(1948, 1, 8, "Dungeon World Quests", 250, "Dungeon World Quests", "Complete dungeon world quests with this faction to gain 250-500 reputation.")
RPH_AddGeneral(1948, 1, 8, "Work Order World Quests", 250, "Work Order World Quests", "Complete work order world quests with this faction to gain reputation.")
RPH_AddGeneral(1948, 1, 8, "Valarjar Emissary", 1500, "Valarjar Emissary", "Complete 4x Valarjar world quests while the emissary is available to gain reputation")
-- Conjurer Margoss 1975
RPH_AddItems(1975, 1, 8, 50, {[138777] = 1})
RPH_AddItems(1975, 1, 8, 500, {[138777] = 10})
-- Ilyssia of the Waters 2097
RPH_AddItems(2097, 1, 8, 75, {[146848] = 1})
-- Corbyn 2100
RPH_AddItems(2100, 1, 8, 75, {[146961] = 1})
-- Impus 2102
RPH_AddItems(2102, 1, 8, 75, {[146963] = 1})
-- Sha'leth 2101
RPH_AddItems(2101, 1, 8, 75, {[146962] = 1})
-- Keeper Raynae 2098
RPH_AddItems(2098, 1, 8, 75, {[146959] = 1})
-- Akule Riverhorn 2099
RPH_AddItems(2099, 1, 8, 75, {[146960] = 1})
-- Talons Vengeance 2018
RPH_AddItems(2018, 1, 8, 100, {[142363] = 1})
-- Army of the Light 2165
-- Insignia reputation tokens
RPH_AddItems(2165, 1, 8, 250, {[152958] = 1}, {[152957] = 1})
RPH_AddItems(2165, 1, 8, 750, {[152956] = 1}, {[152955] = 1})
-- World Quest
RPH_AddGeneral(2165, 1, 8, "World Quests", 75, "World Quests", "Complete world quests with this faction to gain reputation.")
RPH_AddGeneral(2165, 1, 8, "Supplies Needed World Quest", 25, "Supplies Needed World Quest", "Complete supplies needed world quests with this faction to gain reputation.")
RPH_AddGeneral(2165, 1, 8, "Supplies Needed: Astral Glory", 10, "Supplies Needed: Astral Glory", "Complete Supplies Needed: Astral Glory to gain reputation.")
RPH_AddGeneral(2165, 1, 8, "Work Order World Quest", 25, "Work Order World Quest", "Complete work order world quests with this faction to gain reputation.")
RPH_AddGeneral(2165, 1, 8, "Work Order: Astral Glory", 10, "Work Order: Astral Glory", "Complete Work Order: Astral Glory to gain reputation.")
RPH_AddGeneral(2165, 1, 8, "Work Order: Tears of the Naaru", 10, "Work Order: Tears of the Naaru", "Complete Supplies Work Order: Tears of the Naaru to gain reputation.")
RPH_AddGeneral(2165, 1, 8, "Work Order: Lightblood Elixirs", 10, "Work Order: Lightblood Elixirs", "Complete Work Order: Lightblood Elixirs to gain reputation.")
RPH_AddGeneral(2165, 1, 8, "Army of the Light Emissary", 1500, "Army of the Light Emissary", "Complete 4x Army of the Light world quests while the emissary is available to gain reputation")
-- Weekly quests
RPH_AddGeneral(2165, 1, 8, "Invasion Onslaught Weekly", 250, "Weekly Quest", "Complete the Invasion Onslaight weekly quest to gain reputation.")
RPH_AddGeneral(2165, 1, 8, "Supplying the Antoran Campaign Weekly", 75, "Weekly Quest", "Complete the Supplying the Antoran Campaign weekly quest to gain reputation.")
-- Argussian Reach 2170
-- Insignia reputation tokens
RPH_AddItems(2170, 1, 8, 250, {[152959] = 1}, {[152960] = 1})
RPH_AddItems(2170, 1, 8, 750, {[152961] = 1}, {[152954] = 1})
-- World Quest
RPH_AddGeneral(2170, 1, 8, "World Quests", 75, "World Quests", "Complete world quests with this faction to gain reputation.")
RPH_AddGeneral(2170, 1, 8, "Supplies Needed World Quest", 25, "Supplies Needed World Quest", "Complete supplies needed world quests with this faction to gain reputation.")
RPH_AddGeneral(2170, 1, 8, "Supplies Needed: Astral Glory", 10, "Supplies Needed: Astral Glory", "Complete Supplies Needed: Astral Glory to gain reputation.")
RPH_AddGeneral(2170, 1, 8, "Work Order World Quest", 25, "Work Order World Quest", "Complete work order world quests with this faction to gain reputation.")
RPH_AddGeneral(2170, 1, 8, "Work Order: Astral Glory", 10, "Work Order: Astral Glory", "Complete Work Order: Astral Glory to gain reputation.")
RPH_AddGeneral(2170, 1, 8, "Work Order: Tears of the Naaru", 10, "Work Order: Tears of the Naaru", "Complete Supplies Work Order: Tears of the Naaru to gain reputation.")
RPH_AddGeneral(2170, 1, 8, "Work Order: Lightblood Elixirs", 10, "Work Order: Lightblood Elixirs", "Complete Work Order: Lightblood Elixirs to gain reputation.")
RPH_AddGeneral(2170, 1, 8, "Argussian Reach Emissary", 1500, "Argussian Reach Emissary", "Complete 4x Argussian Reach world quests while the emissary is available to gain reputation")
-- Weekly quests
RPH_AddGeneral(2170, 1, 8, "Fuel of a Doomed World Weekly", 250, "Weekly Quest", "Complete the Fuel of a Doomed World weekly quest to gain reputation.")
-- Battle for Azeroth
-- Champions of Azeroth
RPH_AddGeneral(2164, 1, 8, "World Quests", 75, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2164, 1, 8, "Champions of Azeroth Emissary", 1500, "Champions of Azeroth Emissary", "Complete 4x Champions of Azeroth world quests while the emissary is available to gain reputation")
-- Tortollan Seekers
RPH_AddGeneral(2163, 1, 8, "Tortollan Seekers", 175, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2163, 1, 8, "Tortollan Seekers Emissary", 1500, "Tortollan Seekers Emissary", "Complete 3x Tortollan Seekers world quests while the emissary is available to gain reputation")
-- Rustbolt Resistance
RPH_AddGeneral(2391, 1, 8, "Daily World Quest", 850, "Daily World Quest", "Complete the daily world quest to gain reputation with this faction")
RPH_AddGeneral(2391, 1, 8, "Daily Pet Battle World Quest", 75, "Daily Pet Battle", "Complete the daily pet battle world quest to gain reputation with this faction")
RPH_AddGeneral(2391, 1, 8, "PVP Daily Quest", 200, "Daily PVP Quest", "Complete a PVP daily quest to gain reputation with this faction")
RPH_AddGeneral(2391, 1, 8, "Daily Quests 75 rep", 75, "Daily Quests", "Daily quests that provide 75 reputation")
RPH_AddGeneral(2391, 1, 8, "Daily Quests 150 rep", 150, "Daily Quests", "Daily quests that provide 150 reputation")
RPH_AddQuest(2045, 1, 8, 46735, 150, {[1342] = 100})
-- Rajanji
RPH_AddQuest(2415, 1, 8, 57008, 500)
RPH_AddQuest(2415, 1, 8, 57728, 500)
RPH_AddQuest(2415, 1, 8, 56064, 1500)
RPH_AddGeneral(2415, 1, 8, "Daily Quests 125 rep", 125, "Daily Quests", "Daily quests that provide 125 reputation")
RPH_AddGeneral(2415, 1, 8, "Threat objectives 50-75 rep", 50, "Threat Objectives", "Completing threat objectives marked by a skull or crossed swords on the minimap provide 50-75 reputation.")
RPH_AddGeneral(2415, 1, 8, "Daily Pet Battle World Quest", 75, "Daily Pet Battle", "Complete the daily pet battle world quest to gain reputation with this faction")
-- Uldum Accord
RPH_AddQuest(2417, 1, 8, 55350, 500)
RPH_AddQuest(2417, 1, 8, 56308, 500)
RPH_AddQuest(2417, 1, 8, 57157, 1500)
RPH_AddGeneral(2417, 1, 8, "Daily Quests 125 rep", 125, "Daily Quests", "Daily quests that provide 125 reputation")
RPH_AddGeneral(2417, 1, 8, "Threat objectives 50-75 rep", 50, "Threat Objectives", "Completing threat objectives marked by a skull or crossed swords on the minimap provide 50-75 reputation.")
RPH_AddGeneral(2417, 1, 8, "Daily Pet Battle World Quest", 75, "Daily Pet Battle", "Complete the daily pet battle world quest to gain reputation with this faction")
if (RPH_IsAlliance) then
-- Proudmoore Admiralty
RPH_AddGeneral(2160, 1, 8, "World Quests", 75, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2160, 1, 8, "Proudmoore Admiralty Emissary", 1500, "Proudmoore Admiralty Emissary", "Complete 4x Proudmoore Admiralty world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2160, 1, 8, "Naga Attack! World Quest", 150, "Naga Attack! World Quest", "Complete the Naga Attack! world quest to gain reputation")
-- Order of Embers
RPH_AddGeneral(2161, 1, 8, "World Quests", 75, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2161, 1, 8, "Order of Embers Emissary", 1500, "Order of Embers Emissary", "Complete 4x Order of Embers world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2161, 1, 8, "Naga Attack! World Quest", 150, "Naga Attack! World Quest", "Complete the Naga Attack! world quest to gain reputation")
-- Storm's Wake
RPH_AddGeneral(2162, 1, 8, "World Quests", 75, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2162, 1, 8, "Storm's Wake Emissary", 1500, "Storm's Wake Emissary", "Complete 4x Storm's Wake world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2162, 1, 8, "Naga Attack! World Quest", 150, "Naga Attack! World Quest", "Complete the Naga Attack! world quest to gain reputation")
-- 7th Legion
RPH_AddGeneral(2159, 1, 8, "World Quests 75 rep", 75, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2159, 1, 8, "World Quests 150 rep", 150, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2159, 1, 8, "7th Legion Emissary", 1500, "7th Legion Emissary", "Completing 4x 7th Legion world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2159, 1, 8, "Warfront Contribution Quests", 150, "Warfront Contribution Quests", "Complete any warfront contribution quest when available to gain reputation")
RPH_AddGeneral(2159, 1, 8, "Island Expeditions Weekly", 1500, "Island Expeditions Weekly", "Complete the Island Expeditions weekly Azerite for the Alliance to gain reputation")
RPH_AddGeneral(2159, 1, 8, "Call to Arms Quest", 75, "Call to Arms Quest", "Complete Call to Arms quest to gain reputation")
RPH_AddGeneral(2159, 1, 8, "Naga Attack! World Quest", 150, "Naga Attack! World Quest", "Complete the Naga Attack! world quest to gain reputation")
-- Waveblade Ankoan
RPH_AddGeneral(2400, 1, 8, "Waveblade Ankoan World Quests", 75, "Waveblade Ankoan Emissary", "Complete Waveblade Ankoan world quests to gain reputation")
RPH_AddGeneral(2400, 1, 8, "Waveblade Ankoan Emissary", 1500, "Waveblade Ankoan Emissary", "Complete 4x Waveblade Ankoan world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2400, 1, 8, "Laboratory of Mardivas Weekly", 500, "Laboratory of Mardivas Weekly", "Complete the Laboratory of Mardivas weekly quest to gain reputation")
RPH_AddGeneral(2400, 1, 8, "Battle for Nazjatar PVP World Quest", 500, "Battle for Nazjatar PVP World Quest", "Complete the Battle for Nazjatar PVP world quest to gain reputation")
RPH_AddGeneral(2400, 1, 8, "Summons from the Depths event", 150, "Summons from the Depths event", "Complete the Summons from the Depths event to have a chance at gaining reputation")
RPH_AddGeneral(2400, 1, 8, "Bounties / Requisition Quests", 50, "Bountes / Requisition Quets", "Complete bounties and requisition quests to gain reputation")
RPH_AddItems(2400, 1, 8, 150, {[170152] = 1})
-- Honeyback Hive
RPH_AddItems(2395, 1, 8, 20, {[168822] = 1}) -- Thin Jelly
RPH_AddItems(2395, 1, 8, 80, {[168825] = 1}) -- Rich Jelly
RPH_AddItems(2395, 1, 8, 160, {[168828] = 1}) -- Royal Jelly
RPH_AddMob(2395, 1, 8, "Honey Smasher (Daily)", 500)
RPH_AddGeneral(2395, 1, 8, "Harvester Event rare mob quest drop (Weekly)", 750, "Harvester Event rare mob quest drop", "Quest items have a chance to drop from a harvester event if the event has a relevant rare.")
end
if (RPH_IsHorde) then
-- Zandalari Empire
RPH_AddGeneral(2103, 1, 8, "World Quests", 75, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2103, 1, 8, "Zandalari Empire Emissary", 1500, "Zandalari Empire Emissary", "Complete 4x Zandalari Empire world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2103, 1, 8, "Naga Attack! World Quest", 150, "Naga Attack! World Quest", "Complete the Naga Attack! world quest to gain reputation")
-- Talanji's Expedition
RPH_AddGeneral(2156, 1, 8, "World Quests", 75, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2156, 1, 8, "Talanji's Expedition Emissary", 1500, "Talanji's Expedition Emissary", "Complete 4x Talanji's Expedition world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2156, 1, 8, "Naga Attack! World Quest", 150, "Naga Attack! World Quest", "Complete the Naga Attack! world quest to gain reputation")
-- Voldunai
RPH_AddGeneral(2158, 1, 8, "World Quests", 75, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2158, 1, 8, "Voldunai Emissary", 1500, "Voldunai Emissary", "Complete 4x Voldunai world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2158, 1, 8, "Naga Attack! World Quest", 150, "Naga Attack! World Quest", "Complete the Naga Attack! world quest to gain reputation")
-- The Honorbound
RPH_AddGeneral(2157, 1, 8, "World Quests 75 rep", 75, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2157, 1, 8, "World Quests 150 rep", 150, "World Quests", "Complete world quests with this faction to gain reputation")
RPH_AddGeneral(2157, 1, 8, "The Honorbound Emissary", 1500, "The Honorbound Emissary", "Complete 4x The Honorbound world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2157, 1, 8, "Warfront Contribution Quests", 150, "Warfront Contribution Quests", "Complete any warfront contribution quest when available to gain reputation")
RPH_AddGeneral(2157, 1, 8, "Island Expeditions Weekly", 1500, "Island Expeditions Weekly", "Complete the Island Expeditions weekly Azerite for the Horde to gain reputation")
RPH_AddGeneral(2157, 1, 8, "Call to Arms Quest", 75, "Call to Arms Quest", "Complete Call to Arms quest to gain reputation")
RPH_AddGeneral(2157, 1, 8, "Naga Attack! World Quest", 150, "Naga Attack! World Quest", "Complete the Naga Attack! world quest to gain reputation")
-- The Unshackled
RPH_AddGeneral(2373, 1, 8, "The Unshackled World Quests", 75, "The Unshackled Emissary", "Complete The Unshackled world quests to gain reputation")
RPH_AddGeneral(2373, 1, 8, "The Unshackled Emissary", 1500, "The Unshackled Emissary", "Complete 4x The Unshackled world quests while the emissary is available to gain reputation")
RPH_AddGeneral(2373, 1, 8, "Laboratory of Mardivas Weekly", 500, "Laboratory of Mardivas Weekly", "Complete the Laboratory of Mardivas weekly quest to gain reputation")
RPH_AddGeneral(2373, 1, 8, "Battle for Nazjatar PVP World Quest", 500, "Battle for Nazjatar PVP World Quest", "Complete the Battle for Nazjatar PVP world quest to gain reputation")
RPH_AddGeneral(2373, 1, 8, "Summons from the Depths event", 150, "Summons from the Depths event", "Complete the Summons from the Depths event to have a chance at gaining reputation")
RPH_AddGeneral(2373, 1, 8, "Bounties / Requisition Quests", 50, "Bountes / Requisition Quets", "Complete bounties and requisition quests to gain reputation")
RPH_AddItems(2373, 1, 8, 150, {[170152] = 1})
end
-- Dead Factions
-- Shen'dralar 809
RPH_AddQuest(809, 1, 8, 6, 1)
-- Gelkis Clan Centaur 92
RPH_AddQuest(92, 1, 8, 6, 1)
-- Magram Clan Centaur 93
RPH_AddQuest(93, 1, 8, 6, 1)
-- Zandalar Tribe 270
RPH_AddQuest(270, 1, 8, 6, 1)
-- The Brewmasters 1351
RPH_AddQuest(1351, 1, 8, 6, 1)
-- 0 guildName
if (guildName and guildCapBase) then
RPH_AddQuest(guildName, 4, 8, 8, 125)
end
--- local preGC = collectgarbage("count")
collectgarbage("collect")
--- print("Collected " .. (preGC-collectgarbage("count")) .. " kB of garbage RPH");
end
| gpl-3.0 |
xennygrimmato/nmt | src/OpenNMT/onmt/utils/Parallel.lua | 8 | 5209 | --[[
This file provides generic parallel class - allowing to run functions
in different threads and on different GPU
]]--
local Parallel = {
_pool = nil,
count = 1,
gradBuffer = torch.Tensor()
}
-- Synchronizes the current stream on dst device with src device. This is only
-- necessary if we are not on the default stream
local function waitForDevice(dst, src)
local stream = cutorch.getStream()
if stream ~= 0 then
cutorch.streamWaitForMultiDevice(dst, stream, { [src] = {stream} })
end
end
function Parallel.getCounter()
return Parallel._tds.AtomicCounter()
end
function Parallel.gmutexId()
return Parallel._gmutex:id()
end
function Parallel.init(opt)
if onmt.utils.Cuda.activated then
Parallel.count = onmt.utils.Cuda.gpuCount()
Parallel.gradBuffer = onmt.utils.Cuda.convert(Parallel.gradBuffer)
Parallel._tds = require('tds')
if Parallel.count > 1 then
local globalLogger = _G.logger
local globalProfiler = _G.profiler
local threads = require('threads')
threads.Threads.serialization('threads.sharedserialize')
Parallel._gmutex = threads.Mutex()
Parallel._pool = threads.Threads(
Parallel.count,
function()
require('cunn')
require('nngraph')
require('onmt.init')
_G.threads = require('threads')
end,
function(threadid)
_G.logger = globalLogger
_G.profiler = globalProfiler
onmt.utils.Cuda.init(opt, threadid)
end
) -- dedicate threads to GPUs
Parallel._pool:specific(true)
end
if Parallel.count > 1 and not opt.no_nccl and not opt.async_parallel then
-- check if we have nccl installed
local ret
ret, Parallel.usenccl = pcall(require, 'nccl')
if not ret then
_G.logger:warning("For improved efficiency with multiple GPUs, consider installing nccl")
Parallel.usenccl = nil
elseif os.getenv('CUDA_LAUNCH_BLOCKING') == '1' then
_G.logger:warning("CUDA_LAUNCH_BLOCKING set - cannot use nccl")
Parallel.usenccl = nil
end
end
end
end
--[[ Launch function in parallel on different threads. ]]
function Parallel.launch(closure, endCallback)
endCallback = endCallback or function() end
for j = 1, Parallel.count do
if Parallel._pool == nil then
endCallback(closure(j))
else
Parallel._pool:addjob(j, function() return closure(j) end, endCallback)
end
end
if Parallel._pool then
Parallel._pool:synchronize()
end
end
--[[ Accumulate the gradient parameters from the different parallel threads. ]]
function Parallel.accGradParams(gradParams, batches)
if Parallel.count > 1 then
for h = 1, #gradParams[1] do
local inputs = { gradParams[1][h] }
for j = 2, #batches do
if not Parallel.usenccl then
-- TODO - this is memory costly since we need to clone full parameters from one GPU to another
-- to avoid out-of-memory, we can copy/add by batch
-- Synchronize before and after copy to ensure that it doesn't overlap
-- with this add or previous adds
waitForDevice(onmt.utils.Cuda.gpuIds[j], onmt.utils.Cuda.gpuIds[1])
local remoteGrads = onmt.utils.Tensor.reuseTensor(Parallel.gradBuffer, gradParams[j][h]:size())
remoteGrads:copy(gradParams[j][h])
waitForDevice(onmt.utils.Cuda.gpuIds[1], onmt.utils.Cuda.gpuIds[j])
gradParams[1][h]:add(remoteGrads)
else
table.insert(inputs, gradParams[j][h])
end
end
if Parallel.usenccl then
Parallel.usenccl.reduce(inputs, nil, true)
end
end
end
end
-- [[ In async mode, sync the parameters from all replica to master replica. ]]
function Parallel.updateAndSync(masterParams, replicaGradParams, replicaParams, gradBuffer, masterGPU, gmutexId)
-- Add a mutex to avoid competition while accessing shared buffer and while updating parameters.
local mutex = _G.threads.Mutex(gmutexId)
mutex:lock()
local device = cutorch.getDevice()
cutorch.setDevice(masterGPU)
for h = 1, #replicaGradParams do
waitForDevice(device, masterGPU)
local remoteGrads = onmt.utils.Tensor.reuseTensor(gradBuffer, replicaGradParams[h]:size())
remoteGrads:copy(replicaGradParams[h])
waitForDevice(masterGPU, device)
masterParams[h]:add(remoteGrads)
end
cutorch.setDevice(device)
for h = 1, #replicaGradParams do
replicaParams[h]:copy(masterParams[h])
waitForDevice(device, masterGPU)
end
mutex:unlock()
end
--[[ Sync parameters from main model to different parallel threads. ]]
function Parallel.syncParams(params)
if Parallel.count > 1 then
if not Parallel.usenccl then
for j = 2, Parallel.count do
for h = 1, #params[1] do
params[j][h]:copy(params[1][h])
end
waitForDevice(onmt.utils.Cuda.gpuIds[j], onmt.utils.Cuda.gpuIds[1])
end
else
for h = 1, #params[1] do
local inputs = { params[1][h] }
for j = 2, Parallel.count do
table.insert(inputs, params[j][h])
end
Parallel.usenccl.bcast(inputs, true, 1)
end
end
end
end
return Parallel
| lgpl-3.0 |
n0xus/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Porter_Moogle.lua | 41 | 1553 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Porter Moogle
-- Type: Storage Moogle
-- @zone 50
-- @pos TODO
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/porter_moogle_util");
local e =
{
TALK_EVENT_ID = 957,
STORE_EVENT_ID = 958,
RETRIEVE_EVENT_ID = 959,
ALREADY_STORED_ID = 960,
MAGIAN_TRIAL_ID = 963
};
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
porterMoogleTrade(player, trade, e);
end
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- No idea what the params are, other than event ID and gil.
player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8);
end
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED);
end
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL);
end | gpl-3.0 |
Azmaedus/GarrisonJukeBox | libs/AceGUI-3.0/widgets/AceGUIContainer-TreeGroup.lua | 7 | 20244 | --[[-----------------------------------------------------------------------------
TreeGroup Container
Container that uses a tree control to switch between groups.
-------------------------------------------------------------------------------]]
local Type, Version = "TreeGroup", 41
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
local WoW80 = select(4, GetBuildInfo()) >= 80000
-- Lua APIs
local next, pairs, ipairs, assert, type = next, pairs, ipairs, assert, type
local math_min, math_max, floor = math.min, math.max, floor
local select, tremove, unpack, tconcat = select, table.remove, unpack, table.concat
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameTooltip, FONT_COLOR_CODE_CLOSE
-- Recycling functions
local new, del
do
local pool = setmetatable({},{__mode='k'})
function new()
local t = next(pool)
if t then
pool[t] = nil
return t
else
return {}
end
end
function del(t)
for k in pairs(t) do
t[k] = nil
end
pool[t] = true
end
end
local DEFAULT_TREE_WIDTH = 175
local DEFAULT_TREE_SIZABLE = true
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function GetButtonUniqueValue(line)
local parent = line.parent
if parent and parent.value then
return GetButtonUniqueValue(parent).."\001"..line.value
else
return line.value
end
end
local function UpdateButton(button, treeline, selected, canExpand, isExpanded)
local self = button.obj
local toggle = button.toggle
local frame = self.frame
local text = treeline.text or ""
local icon = treeline.icon
local iconCoords = treeline.iconCoords
local level = treeline.level
local value = treeline.value
local uniquevalue = treeline.uniquevalue
local disabled = treeline.disabled
button.treeline = treeline
button.value = value
button.uniquevalue = uniquevalue
if selected then
button:LockHighlight()
button.selected = true
else
button:UnlockHighlight()
button.selected = false
end
local normalTexture = button:GetNormalTexture()
local line = button.line
button.level = level
if ( level == 1 ) then
button:SetNormalFontObject("GameFontNormal")
button:SetHighlightFontObject("GameFontHighlight")
button.text:SetPoint("LEFT", (icon and 16 or 0) + 8, 2)
else
button:SetNormalFontObject("GameFontHighlightSmall")
button:SetHighlightFontObject("GameFontHighlightSmall")
button.text:SetPoint("LEFT", (icon and 16 or 0) + 8 * level, 2)
end
if disabled then
button:EnableMouse(false)
button.text:SetText("|cff808080"..text..FONT_COLOR_CODE_CLOSE)
else
button.text:SetText(text)
button:EnableMouse(true)
end
if icon then
button.icon:SetTexture(icon)
button.icon:SetPoint("LEFT", 8 * level, (level == 1) and 0 or 1)
else
button.icon:SetTexture(nil)
end
if iconCoords then
button.icon:SetTexCoord(unpack(iconCoords))
else
button.icon:SetTexCoord(0, 1, 0, 1)
end
if canExpand then
if not isExpanded then
toggle:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-UP")
toggle:SetPushedTexture("Interface\\Buttons\\UI-PlusButton-DOWN")
else
toggle:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-UP")
toggle:SetPushedTexture("Interface\\Buttons\\UI-MinusButton-DOWN")
end
toggle:Show()
else
toggle:Hide()
end
end
local function ShouldDisplayLevel(tree)
local result = false
for k, v in ipairs(tree) do
if v.children == nil and v.visible ~= false then
result = true
elseif v.children then
result = result or ShouldDisplayLevel(v.children)
end
if result then return result end
end
return false
end
local function addLine(self, v, tree, level, parent)
local line = new()
line.value = v.value
line.text = v.text
line.icon = v.icon
line.iconCoords = v.iconCoords
line.disabled = v.disabled
line.tree = tree
line.level = level
line.parent = parent
line.visible = v.visible
line.uniquevalue = GetButtonUniqueValue(line)
if v.children then
line.hasChildren = true
else
line.hasChildren = nil
end
self.lines[#self.lines+1] = line
return line
end
--fire an update after one frame to catch the treeframes height
local function FirstFrameUpdate(frame)
local self = frame.obj
frame:SetScript("OnUpdate", nil)
self:RefreshTree(nil, true)
end
local function BuildUniqueValue(...)
local n = select('#', ...)
if n == 1 then
return ...
else
return (...).."\001"..BuildUniqueValue(select(2,...))
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Expand_OnClick(frame)
local button = frame.button
local self = button.obj
local status = (self.status or self.localstatus).groups
status[button.uniquevalue] = not status[button.uniquevalue]
self:RefreshTree()
end
local function Button_OnClick(frame)
local self = frame.obj
self:Fire("OnClick", frame.uniquevalue, frame.selected)
if not frame.selected then
self:SetSelected(frame.uniquevalue)
frame.selected = true
frame:LockHighlight()
self:RefreshTree()
end
AceGUI:ClearFocus()
end
local function Button_OnDoubleClick(button)
local self = button.obj
local status = self.status or self.localstatus
local status = (self.status or self.localstatus).groups
status[button.uniquevalue] = not status[button.uniquevalue]
self:RefreshTree()
end
local function Button_OnEnter(frame)
local self = frame.obj
self:Fire("OnButtonEnter", frame.uniquevalue, frame)
if self.enabletooltips then
GameTooltip:SetOwner(frame, "ANCHOR_NONE")
GameTooltip:SetPoint("LEFT",frame,"RIGHT")
GameTooltip:SetText(frame.text:GetText() or "", 1, .82, 0, true)
GameTooltip:Show()
end
end
local function Button_OnLeave(frame)
local self = frame.obj
self:Fire("OnButtonLeave", frame.uniquevalue, frame)
if self.enabletooltips then
GameTooltip:Hide()
end
end
local function OnScrollValueChanged(frame, value)
if frame.obj.noupdate then return end
local self = frame.obj
local status = self.status or self.localstatus
status.scrollvalue = floor(value + 0.5)
self:RefreshTree()
AceGUI:ClearFocus()
end
local function Tree_OnSizeChanged(frame)
frame.obj:RefreshTree()
end
local function Tree_OnMouseWheel(frame, delta)
local self = frame.obj
if self.showscroll then
local scrollbar = self.scrollbar
local min, max = scrollbar:GetMinMaxValues()
local value = scrollbar:GetValue()
local newvalue = math_min(max,math_max(min,value - delta))
if value ~= newvalue then
scrollbar:SetValue(newvalue)
end
end
end
local function Dragger_OnLeave(frame)
frame:SetBackdropColor(1, 1, 1, 0)
end
local function Dragger_OnEnter(frame)
frame:SetBackdropColor(1, 1, 1, 0.8)
end
local function Dragger_OnMouseDown(frame)
local treeframe = frame:GetParent()
treeframe:StartSizing("RIGHT")
end
local function Dragger_OnMouseUp(frame)
local treeframe = frame:GetParent()
local self = treeframe.obj
local frame = treeframe:GetParent()
treeframe:StopMovingOrSizing()
--treeframe:SetScript("OnUpdate", nil)
treeframe:SetUserPlaced(false)
--Without this :GetHeight will get stuck on the current height, causing the tree contents to not resize
treeframe:SetHeight(0)
treeframe:SetPoint("TOPLEFT", frame, "TOPLEFT",0,0)
treeframe:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT",0,0)
local status = self.status or self.localstatus
status.treewidth = treeframe:GetWidth()
treeframe.obj:Fire("OnTreeResize",treeframe:GetWidth())
-- recalculate the content width
treeframe.obj:OnWidthSet(status.fullwidth)
-- update the layout of the content
treeframe.obj:DoLayout()
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetTreeWidth(DEFAULT_TREE_WIDTH, DEFAULT_TREE_SIZABLE)
self:EnableButtonTooltips(true)
self.frame:SetScript("OnUpdate", FirstFrameUpdate)
end,
["OnRelease"] = function(self)
self.status = nil
self.tree = nil
self.frame:SetScript("OnUpdate", nil)
for k, v in pairs(self.localstatus) do
if k == "groups" then
for k2 in pairs(v) do
v[k2] = nil
end
else
self.localstatus[k] = nil
end
end
self.localstatus.scrollvalue = 0
self.localstatus.treewidth = DEFAULT_TREE_WIDTH
self.localstatus.treesizable = DEFAULT_TREE_SIZABLE
end,
["EnableButtonTooltips"] = function(self, enable)
self.enabletooltips = enable
end,
["CreateButton"] = function(self)
local num = AceGUI:GetNextWidgetNum("TreeGroupButton")
local button = CreateFrame("Button", ("AceGUI30TreeButton%d"):format(num), self.treeframe, "OptionsListButtonTemplate")
button.obj = self
local icon = button:CreateTexture(nil, "OVERLAY")
icon:SetWidth(14)
icon:SetHeight(14)
button.icon = icon
button:SetScript("OnClick",Button_OnClick)
button:SetScript("OnDoubleClick", Button_OnDoubleClick)
button:SetScript("OnEnter",Button_OnEnter)
button:SetScript("OnLeave",Button_OnLeave)
button.toggle.button = button
button.toggle:SetScript("OnClick",Expand_OnClick)
button.text:SetHeight(14) -- Prevents text wrapping
return button
end,
["SetStatusTable"] = function(self, status)
assert(type(status) == "table")
self.status = status
if not status.groups then
status.groups = {}
end
if not status.scrollvalue then
status.scrollvalue = 0
end
if not status.treewidth then
status.treewidth = DEFAULT_TREE_WIDTH
end
if status.treesizable == nil then
status.treesizable = DEFAULT_TREE_SIZABLE
end
self:SetTreeWidth(status.treewidth,status.treesizable)
self:RefreshTree()
end,
--sets the tree to be displayed
["SetTree"] = function(self, tree, filter)
self.filter = filter
if tree then
assert(type(tree) == "table")
end
self.tree = tree
self:RefreshTree()
end,
["BuildLevel"] = function(self, tree, level, parent)
local groups = (self.status or self.localstatus).groups
local hasChildren = self.hasChildren
for i, v in ipairs(tree) do
if v.children then
if not self.filter or ShouldDisplayLevel(v.children) then
local line = addLine(self, v, tree, level, parent)
if groups[line.uniquevalue] then
self:BuildLevel(v.children, level+1, line)
end
end
elseif v.visible ~= false or not self.filter then
addLine(self, v, tree, level, parent)
end
end
end,
["RefreshTree"] = function(self,scrollToSelection,fromOnUpdate)
local buttons = self.buttons
local lines = self.lines
for i, v in ipairs(buttons) do
v:Hide()
end
while lines[1] do
local t = tremove(lines)
for k in pairs(t) do
t[k] = nil
end
del(t)
end
if not self.tree then return end
--Build the list of visible entries from the tree and status tables
local status = self.status or self.localstatus
local groupstatus = status.groups
local tree = self.tree
local treeframe = self.treeframe
status.scrollToSelection = status.scrollToSelection or scrollToSelection -- needs to be cached in case the control hasn't been drawn yet (code bails out below)
self:BuildLevel(tree, 1)
local numlines = #lines
local maxlines = (floor(((self.treeframe:GetHeight()or 0) - 20 ) / 18))
if maxlines <= 0 then return end
-- workaround for lag spikes on WoW 8.0
if WoW80 and self.frame:GetParent() == UIParent and not fromOnUpdate then
self.frame:SetScript("OnUpdate", FirstFrameUpdate)
return
end
local first, last
scrollToSelection = status.scrollToSelection
status.scrollToSelection = nil
if numlines <= maxlines then
--the whole tree fits in the frame
status.scrollvalue = 0
self:ShowScroll(false)
first, last = 1, numlines
else
self:ShowScroll(true)
--scrolling will be needed
self.noupdate = true
self.scrollbar:SetMinMaxValues(0, numlines - maxlines)
--check if we are scrolled down too far
if numlines - status.scrollvalue < maxlines then
status.scrollvalue = numlines - maxlines
end
self.noupdate = nil
first, last = status.scrollvalue+1, status.scrollvalue + maxlines
--show selection?
if scrollToSelection and status.selected then
local show
for i,line in ipairs(lines) do -- find the line number
if line.uniquevalue==status.selected then
show=i
end
end
if not show then
-- selection was deleted or something?
elseif show>=first and show<=last then
-- all good
else
-- scrolling needed!
if show<first then
status.scrollvalue = show-1
else
status.scrollvalue = show-maxlines
end
first, last = status.scrollvalue+1, status.scrollvalue + maxlines
end
end
if self.scrollbar:GetValue() ~= status.scrollvalue then
self.scrollbar:SetValue(status.scrollvalue)
end
end
local buttonnum = 1
for i = first, last do
local line = lines[i]
local button = buttons[buttonnum]
if not button then
button = self:CreateButton()
buttons[buttonnum] = button
button:SetParent(treeframe)
button:SetFrameLevel(treeframe:GetFrameLevel()+1)
button:ClearAllPoints()
if buttonnum == 1 then
if self.showscroll then
button:SetPoint("TOPRIGHT", -22, -10)
button:SetPoint("TOPLEFT", 0, -10)
else
button:SetPoint("TOPRIGHT", 0, -10)
button:SetPoint("TOPLEFT", 0, -10)
end
else
button:SetPoint("TOPRIGHT", buttons[buttonnum-1], "BOTTOMRIGHT",0,0)
button:SetPoint("TOPLEFT", buttons[buttonnum-1], "BOTTOMLEFT",0,0)
end
end
UpdateButton(button, line, status.selected == line.uniquevalue, line.hasChildren, groupstatus[line.uniquevalue] )
button:Show()
buttonnum = buttonnum + 1
end
end,
["SetSelected"] = function(self, value)
local status = self.status or self.localstatus
if status.selected ~= value then
status.selected = value
self:Fire("OnGroupSelected", value)
end
end,
["Select"] = function(self, uniquevalue, ...)
self.filter = false
local status = self.status or self.localstatus
local groups = status.groups
local path = {...}
for i = 1, #path do
groups[tconcat(path, "\001", 1, i)] = true
end
status.selected = uniquevalue
self:RefreshTree(true)
self:Fire("OnGroupSelected", uniquevalue)
end,
["SelectByPath"] = function(self, ...)
self:Select(BuildUniqueValue(...), ...)
end,
["SelectByValue"] = function(self, uniquevalue)
self:Select(uniquevalue, ("\001"):split(uniquevalue))
end,
["ShowScroll"] = function(self, show)
self.showscroll = show
if show then
self.scrollbar:Show()
if self.buttons[1] then
self.buttons[1]:SetPoint("TOPRIGHT", self.treeframe,"TOPRIGHT",-22,-10)
end
else
self.scrollbar:Hide()
if self.buttons[1] then
self.buttons[1]:SetPoint("TOPRIGHT", self.treeframe,"TOPRIGHT",0,-10)
end
end
end,
["OnWidthSet"] = function(self, width)
local content = self.content
local treeframe = self.treeframe
local status = self.status or self.localstatus
status.fullwidth = width
local contentwidth = width - status.treewidth - 20
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
local maxtreewidth = math_min(400, width - 50)
if maxtreewidth > 100 and status.treewidth > maxtreewidth then
self:SetTreeWidth(maxtreewidth, status.treesizable)
end
treeframe:SetMaxResize(maxtreewidth, 1600)
end,
["OnHeightSet"] = function(self, height)
local content = self.content
local contentheight = height - 20
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end,
["SetTreeWidth"] = function(self, treewidth, resizable)
if not resizable then
if type(treewidth) == 'number' then
resizable = false
elseif type(treewidth) == 'boolean' then
resizable = treewidth
treewidth = DEFAULT_TREE_WIDTH
else
resizable = false
treewidth = DEFAULT_TREE_WIDTH
end
end
self.treeframe:SetWidth(treewidth)
self.dragger:EnableMouse(resizable)
local status = self.status or self.localstatus
status.treewidth = treewidth
status.treesizable = resizable
-- recalculate the content width
if status.fullwidth then
self:OnWidthSet(status.fullwidth)
end
end,
["GetTreeWidth"] = function(self)
local status = self.status or self.localstatus
return status.treewidth or DEFAULT_TREE_WIDTH
end,
["LayoutFinished"] = function(self, width, height)
if self.noAutoHeight then return end
self:SetHeight((height or 0) + 20)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local PaneBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 5, bottom = 3 }
}
local DraggerBackdrop = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = nil,
tile = true, tileSize = 16, edgeSize = 0,
insets = { left = 3, right = 3, top = 7, bottom = 7 }
}
local function Constructor()
local num = AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Frame", nil, UIParent)
local treeframe = CreateFrame("Frame", nil, frame)
treeframe:SetPoint("TOPLEFT")
treeframe:SetPoint("BOTTOMLEFT")
treeframe:SetWidth(DEFAULT_TREE_WIDTH)
treeframe:EnableMouseWheel(true)
treeframe:SetBackdrop(PaneBackdrop)
treeframe:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
treeframe:SetBackdropBorderColor(0.4, 0.4, 0.4)
treeframe:SetResizable(true)
treeframe:SetMinResize(100, 1)
treeframe:SetMaxResize(400, 1600)
treeframe:SetScript("OnUpdate", FirstFrameUpdate)
treeframe:SetScript("OnSizeChanged", Tree_OnSizeChanged)
treeframe:SetScript("OnMouseWheel", Tree_OnMouseWheel)
local dragger = CreateFrame("Frame", nil, treeframe)
dragger:SetWidth(8)
dragger:SetPoint("TOP", treeframe, "TOPRIGHT")
dragger:SetPoint("BOTTOM", treeframe, "BOTTOMRIGHT")
dragger:SetBackdrop(DraggerBackdrop)
dragger:SetBackdropColor(1, 1, 1, 0)
dragger:SetScript("OnEnter", Dragger_OnEnter)
dragger:SetScript("OnLeave", Dragger_OnLeave)
dragger:SetScript("OnMouseDown", Dragger_OnMouseDown)
dragger:SetScript("OnMouseUp", Dragger_OnMouseUp)
local scrollbar = CreateFrame("Slider", ("AceConfigDialogTreeGroup%dScrollBar"):format(num), treeframe, "UIPanelScrollBarTemplate")
scrollbar:SetScript("OnValueChanged", nil)
scrollbar:SetPoint("TOPRIGHT", -10, -26)
scrollbar:SetPoint("BOTTOMRIGHT", -10, 26)
scrollbar:SetMinMaxValues(0,0)
scrollbar:SetValueStep(1)
scrollbar:SetValue(0)
scrollbar:SetWidth(16)
scrollbar:SetScript("OnValueChanged", OnScrollValueChanged)
local scrollbg = scrollbar:CreateTexture(nil, "BACKGROUND")
scrollbg:SetAllPoints(scrollbar)
scrollbg:SetColorTexture(0,0,0,0.4)
local border = CreateFrame("Frame",nil,frame)
border:SetPoint("TOPLEFT", treeframe, "TOPRIGHT")
border:SetPoint("BOTTOMRIGHT")
border:SetBackdrop(PaneBackdrop)
border:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
border:SetBackdropBorderColor(0.4, 0.4, 0.4)
--Container Support
local content = CreateFrame("Frame", nil, border)
content:SetPoint("TOPLEFT", 10, -10)
content:SetPoint("BOTTOMRIGHT", -10, 10)
local widget = {
frame = frame,
lines = {},
levels = {},
buttons = {},
hasChildren = {},
localstatus = { groups = {}, scrollvalue = 0 },
filter = false,
treeframe = treeframe,
dragger = dragger,
scrollbar = scrollbar,
border = border,
content = content,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
treeframe.obj, dragger.obj, scrollbar.obj = widget, widget, widget
return AceGUI:RegisterAsContainer(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| gpl-2.0 |
davymai/CN-QulightUI | Interface/AddOns/Skada/modules/Power.lua | 1 | 3840 |
Skada:AddLoadableModule("Power", function(Skada, L)
if Skada.db.profile.modulesBlocked.Power then return end
local mod = Skada:NewModule(L["Mana gained"])
local playermod = Skada:NewModule(L["Mana gain spell list"])
local function log_gain(set, gain)
-- Get the player from set.
local player = Skada:get_player(set, gain.playerid, gain.playername)
if player then
-- Make sure power type exists.
if not player.power[gain.type] then
player.power[gain.type] = {spells = {}, amount = 0}
end
-- Make sure set power type exists.
if not set.power[gain.type] then
set.power[gain.type] = 0
end
-- Add to player total.
player.power[gain.type].amount = player.power[gain.type].amount + gain.amount
-- Also add to set total gain.
set.power[gain.type] = set.power[gain.type] + gain.amount
-- Create spell if it does not exist.
if not player.power[gain.type].spells[gain.spellid] then
player.power[gain.type].spells[gain.spellid] = 0
end
player.power[gain.type].spells[gain.spellid] = player.power[gain.type].spells[gain.spellid] + gain.amount
end
end
local MANA = 0
local gain = {}
local function SpellEnergize(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
-- Healing
local spellId, spellName, spellSchool, samount, powerType = ...
gain.playerid = srcGUID
gain.playername = srcName
gain.spellid = spellId
gain.spellname = spellName
gain.amount = samount
gain.type = tonumber(powerType)
Skada:FixPets(gain)
log_gain(Skada.current, gain)
log_gain(Skada.total, gain)
end
function mod:Update(win, set)
local nr = 1
local max = 0
for i, player in ipairs(set.players) do
if player.power[MANA] then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.value = player.power[MANA].amount
d.valuetext = Skada:FormatNumber(player.power[MANA].amount)
d.class = player.class
if player.power[MANA].amount > max then
max = player.power[MANA].amount
end
nr = nr + 1
end
end
win.metadata.maxvalue = max
end
function playermod:Enter(win, id, label)
playermod.playerid = id
playermod.title = label
end
-- Detail view of a player.
function playermod:Update(win, set)
-- View spells for this player.
local player = Skada:find_player(set, self.playerid)
local nr = 1
local max = 0
if player then
for spellid, amount in pairs(player.power[MANA].spells) do
local name, rank, icon, cost, isFunnel, powerType, castTime, minRange, maxRange = GetSpellInfo(spellid)
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.label = name
d.value = amount
d.valuetext = Skada:FormatNumber(amount)..(" (%02.1f%%)"):format(amount / player.power[MANA].amount * 100)
d.icon = icon
d.spellid = spellid
if amount > max then
max = amount
end
nr = nr + 1
end
end
win.metadata.hasicon = true
win.metadata.maxvalue = max
end
function mod:OnEnable()
mod.metadata = {showspots = true, click1 = playermod}
playermod.metadata = {}
Skada:RegisterForCL(SpellEnergize, 'SPELL_ENERGIZE', {src_is_interesting = true})
Skada:RegisterForCL(SpellEnergize, 'SPELL_PERIODIC_ENERGIZE', {src_is_interesting = true})
Skada:AddMode(self)
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:AddToTooltip(set, tooltip)
end
function mod:GetSetSummary(set)
return Skada:FormatNumber(set.power[MANA] or 0)
end
-- Called by Skada when a new player is added to a set.
function mod:AddPlayerAttributes(player)
if not player.power then
player.power = {}
end
end
-- Called by Skada when a new set is created.
function mod:AddSetAttributes(set)
if not set.power then
set.power = {}
end
end
end)
| gpl-2.0 |
umbrellaTG/self | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-BlackTemple/ShadeOfAkama.lua | 1 | 1050 | local mod = DBM:NewMod("Akama", "DBM-BlackTemple")
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 501 $"):sub(12, -3))
mod:SetCreatureID(23421, 22841, 23215, 23216)
mod:SetModelID(21357)
mod:SetZone()
mod:RegisterCombat("combat")
mod:SetWipeTime(30)
mod:RegisterEventsInCombat(
"UNIT_DIED"
)
local warnPhase2 = mod:NewPhaseAnnounce(2)
local phase2started = false
function mod:OnCombatStart(delay)
phase2started = false
self:RegisterShortTermEvents(
"SWING_DAMAGE",
"SWING_MISSED"
)
if DBM.BossHealth:IsShown() then
DBM.BossHealth:Clear()
DBM.BossHealth:Show(L.name)
DBM.BossHealth:AddBoss(22841, L.name)
end
end
function mod:OnCombatEnd()
self:UnregisterShortTermEvents()
end
function mod:SWING_DAMAGE(_, sourceName)
if sourceName == L.name and not phase2started then
self:UnregisterShortTermEvents()
phase2started = true
warnPhase2:Show()
end
end
mod.SWING_MISSED = mod.SWING_DAMAGE
function mod:UNIT_DIED(args)
if self:GetCIDFromGUID(args.destGUID) == 22841 then
DBM:EndCombat(self)
end
end
| gpl-2.0 |
lduboeuf/lit | libs/db.lua | 4 | 6459 | --[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
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.
--]]
--[[
Mid Level Storage Commands
=========================
These commands work at a higher level and consume the low-level storage APIs.
db.has(hash) -> bool - check if db has an object
db.load(hash) -> raw - load raw data, nil if not found
db.loadAny(hash) -> kind, value - pre-decode data, error if not found
db.loadAs(kind, hash) -> value - pre-decode and check type or error
db.save(raw) -> hash - save pre-encoded and framed data
db.saveAs(kind, value) -> hash - encode, frame and save to objects/$ha/$sh
db.hashes() -> iter - Iterate over all hashes
db.match(author, name, version)
-> match, hash - Find the best version matching the query.
db.read(author, name, version) -> hash - Read from refs/tags/$author/$tag/v$version
db.write(author, name, version, hash) - Write to refs/tags/$suthor/$tag/v$version
db.authors() -> iter - Iterate over refs/tags/*
db.names(author) -> iter - Iterate nodes in refs/tags/$author/**
db.versions(author, name) -> iter - Iterate leaves in refs/tags/$author/$tag/*
db.readKey(author, fingerprint) -> key - Read from keys/$author/$fingerprint
db.putKey(author, fingerprint, key) - Write to keys/$author/$fingerprint
db.revokeKey(author, fingerprint) - Delete keys/$author/$fingerprint
db.fingerprints(author) -> iter - iter of fingerprints
db.getEtag(author) -> etag - Read keys/$author.etag
db.setEtag(author, etag) - Writes keys/$author.etag
db.owners(org) -> iter - Iterates lines of keys/$org.owners
db.isOwner(org, author) -> bool - Check if a user is an org owner
db.addOwner(org, author) - Add a new owner
db.removeOwner(org, author) - Remove an owner
db.import(fs, path) -> kind, hash - Import a file or tree into database
db.export(hash, path) -> kind - Export a hash to a path
]]
return function (rootPath)
local semver = require('semver')
local normalize = semver.normalize
local fs = require('coro-fs')
local gitMount = require('git').mount
local import = require('import')
local export = require('export')
local db = gitMount(fs.chroot(rootPath))
local storage = db.storage
local function assertHash(hash)
assert(hash and #hash == 40 and hash:match("^%x+$"), "Invalid hash")
end
function db.match(author, name, version)
local match = semver.match(version, db.versions(author, name))
if not match then return end
return match, assert(db.read(author, name, match))
end
function db.read(author, name, version)
version = normalize(version)
local ref = string.format("refs/tags/%s/%s/v%s", author, name, version)
return db.getRef(ref)
end
function db.write(author, name, version, hash)
version = normalize(version)
assertHash(hash)
local ref = string.format("refs/tags/%s/%s/v%s", author, name, version)
storage.write(ref, hash .. "\n")
end
function db.authors()
return db.nodes("refs/tags")
end
function db.names(author)
local prefix = "refs/tags/" .. author .. "/"
local stack = {db.nodes(prefix)}
return function ()
while true do
if #stack == 0 then return end
local name = stack[#stack]()
if name then
local path = stack[#stack - 1]
local newPath = path and path .. "/" .. name or name
stack[#stack + 1] = newPath
stack[#stack + 1] = db.nodes(prefix .. newPath)
return newPath
end
stack[#stack] = nil
stack[#stack] = nil
end
end
end
function db.versions(author, name)
local ref = string.format("refs/tags/%s/%s", author, name)
local iter = db.leaves(ref)
return function ()
local item = iter()
return item and item:sub(2)
end
end
local function keyPath(author, fingerprint)
return string.format("keys/%s/%s", author, fingerprint:gsub(":", "_"))
end
function db.readKey(author, fingerprint)
return storage.read(keyPath(author, fingerprint))
end
function db.putKey(author, fingerprint, key)
return storage.put(keyPath(author, fingerprint), key)
end
function db.revokeKey(author, fingerprint)
return storage.delete(keyPath(author, fingerprint))
end
function db.fingerprints(author)
local iter = storage.leaves("keys/" .. author)
return function ()
local item = iter()
return item and item:gsub("_", ":")
end
end
function db.getEtag(author)
return storage.read("keys/" .. author .. ".etag")
end
function db.setEtag(author, etag)
return storage.write("keys/" .. author .. ".etag", etag)
end
local function ownersPath(org)
return "keys/" .. org .. ".owners"
end
function db.owners(org)
local owners = storage.read(ownersPath(org))
if not owners then return end
return owners:gmatch("[^\n]+")
end
function db.isOwner(org, author)
local iter = db.owners(org)
if not iter then return false end
for owner in iter do
if author == owner then return true end
end
return false
end
function db.addOwner(org, author)
if db.isOwner(org, author) then return end
local path = ownersPath(org)
local owners = storage.read(path)
owners = (owners or "") .. author .. "\n"
storage.write(path, owners)
end
function db.removeOwner(org, author)
local list = {}
for owner in db.owners(org) do
if owner ~= author then
list[#list + 1] = owner
end
end
storage.write(ownersPath(org), table.concat(list, "\n") .. "\n")
end
function db.import(fs, path) --> kind, hash
return import(db, fs, path)
end
function db.export(hash, path) --> kind
return export(db, hash, fs, path)
end
return db
end
| apache-2.0 |
n0xus/darkstar | scripts/zones/Bastok_Mines/npcs/Davyad.lua | 17 | 1205 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Davyad
-- Involved in Mission: Bastok 3-2
-- @zone 234
-- @pos 83 0 30
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(BASTOK) == TO_THE_FORSAKEN_MINES) then
player:startEvent(0x0036);
else
player:startEvent(0x0035);
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 |
davymai/CN-QulightUI | Interface/AddOns/DBM-BlackwingDescent/localization.ru.lua | 1 | 9088 | if GetLocale() ~= "ruRU" then return end
local L
-------------------------------
-- Dark Iron Golem Council --
-------------------------------
L = DBM:GetModLocalization(169)
L:SetWarningLocalization({
SpecWarnActivated = "Смена цели на: %s!",
specWarnGenerator = "Генератор энергии - Двигайтесь %s!"
})
L:SetTimerLocalization({
timerShadowConductorCast = "Проводник тьмы",
timerArcaneLockout = "Волшебный уничтожитель",
timerArcaneBlowbackCast = "Чародейская обратная вспышка",
timerNefAblity = "Восст. баффа" --Ability Buff CD
})
L:SetOptionLocalization({
timerShadowConductorCast = "Отсчет времени применения заклинания $spell:92053",
timerArcaneLockout = "Отсчет времени блокировки $spell:91542",
timerArcaneBlowbackCast = "Отсчет времени применения заклинания $spell:91879",
timerNefAblity = "Отсчет времени восстановления баффа (героический режим)",
SpecWarnActivated = "Спец-предупреждение при активации нового босса",
specWarnGenerator = "Спец-предупреждение, когда босс стоит в $spell:91557",
AcquiringTargetIcon = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(79501),
ConductorIcon = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(79888),
ShadowConductorIcon = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(92053),
SetIconOnActivated = "Устанавливать метку на появившегося босса"
})
L:SetMiscLocalization({
YellTargetLock = "На МНЕ - Обрамляющие тени! Прочь от меня!"
})
--------------
-- Magmaw --
--------------
L = DBM:GetModLocalization(170)
L:SetWarningLocalization({
SpecWarnInferno = "Появляется Пыляющее костяное создание! (~4сек)"
})
L:SetOptionLocalization({
SpecWarnInferno = "Предупреждать заранее о $spell:92190 (~4сек)",
RangeFrame = "Показывать окно проверки дистанции на второй фазе (5м)"
})
L:SetMiscLocalization({
Slump = "%s внезапно падает, выставляя клешки!",
HeadExposed = "%s насаживается на пику, обнажая голову!",
YellPhase2 = "Непостижимо! Вы, кажется, можете уничтожить моего лавового червяка! Пожалуй, я помогу ему."
})
-----------------
-- Atramedes --
-----------------
L = DBM:GetModLocalization(171)
L:SetOptionLocalization({
InfoFrame = "Показывать информационное окно для уровня звуков",
TrackingIcon = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(78092)
})
L:SetMiscLocalization({
NefAdd = "Атрамед, они вон там!",
Airphase = "Да, беги! С каждым шагом твое сердце бьется все быстрее. Эти громкие, оглушительные удары... Тебе некуда бежать!"
})
-----------------
-- Chimaeron --
-----------------
L = DBM:GetModLocalization(172)
L:SetOptionLocalization({
RangeFrame = "Показывать окно проверки дистанции (6м)",
SetIconOnSlime = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(82935),
InfoFrame = "Показывать информационное окно со здоровьем (<10к хп)"
})
L:SetMiscLocalization({
HealthInfo = "Инфо о здоровье"
})
----------------
-- Maloriak --
----------------
L = DBM:GetModLocalization(173)
L:SetWarningLocalization({
WarnPhase = "%s фаза"
})
L:SetTimerLocalization({
TimerPhase = "Следующая фаза"
})
L:SetOptionLocalization({
WarnPhase = "Предупреждать о переходе фаз",
TimerPhase = "Показывать таймер до следующей фазы",
RangeFrame = "В ходе синей фазы, показывать окно проверки дистанции (6м)",
SetTextures = "Автоматически отключить \"Проецирование текстур\" в темной фазе<br/>(включается обратно при выходе из фазы)",
FlashFreezeIcon = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(92979),
BitingChillIcon = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(77760),
ConsumingFlamesIcon = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(77786)
})
L:SetMiscLocalization({
YellRed = "красный|r пузырек в котел!",--Partial matchs, no need for full strings unless you really want em, mod checks for both.
YellBlue = "синий|r пузырек в котел!",
YellGreen = "зеленый|r пузырек в котел!",
YellDark = "магию на котле!"
})
----------------
-- Nefarian --
----------------
L = DBM:GetModLocalization(174)
L:SetWarningLocalization({
OnyTailSwipe = "Удар хвостом (Ониксия)",
NefTailSwipe = "Удар хвостом (Нефариан)",
OnyBreath = "Дыхание темного огня (Ониксия)",
NefBreath = "Дыхание темного огня (Нефариан)",
specWarnShadowblazeSoon = "%s",
warnShadowblazeSoon = "%s"
})
L:SetTimerLocalization({
timerNefLanding = "Приземление Нефариана",
OnySwipeTimer = "Удар хвостом - перезарядка (Ониксия)",
NefSwipeTimer = "Удар хвостом - перезарядка (Нефариан)",
OnyBreathTimer = "Дыхание темного огня (Ониксия)",
NefBreathTimer = "Дыхание темного огня (Нефариан)"
})
L:SetOptionLocalization({
OnyTailSwipe = "Предупреждение для $spell:77827 Ониксии",
NefTailSwipe = "Предупреждение для $spell:77827 Нефариана",
OnyBreath = "Предупреждение для $spell:94124 Ониксии",
NefBreath = "Предупреждение для $spell:94124 Нефариана",
specWarnCinderMove = "Спец-предупреждение за 5 секунд до взрыва $spell:79339",
warnShadowblazeSoon = "Отсчитывать время до $spell:81031 (за 5 секунд до каста)<br/>(Отсчет пойдет только после первой синхронизации с эмоцией босса)",
specWarnShadowblazeSoon = "Предупреждать заранее о $spell:81031<br/>(За 5 секунд до первого каста, за 1 секунду до каждого следующего)",
timerNefLanding = "Отсчет времени до приземления Нефариана",
OnySwipeTimer = "Отсчет времени до восстановления $spell:77827 Ониксии",
NefSwipeTimer = "Отсчет времени до восстановления $spell:77827 Нефариана",
OnyBreathTimer = "Отсчет времени до восстановления $spell:94124 Ониксии",
NefBreathTimer = "Отсчет времени до восстановления $spell:94124 Нефариана",
InfoFrame = "Показывать информационное окно для Электрического заряда Ониксии",
SetWater = "Автоматически отключать настройку Брызги воды<br/>(Включается обратно при выходе из боя)",
TankArrow = "Показывать стрелку для кайтера Оживших костяных воинов<br/>(Работает только для стратегии с одним кайтером)",
SetIconOnCinder = DBM_CORE_AUTO_ICONS_OPTION_TEXT:format(79339),
RangeFrame = "Окно проверки дистанции (10м) для $spell:79339<br/>(Если на вас дебафф - показывает всех, иначе только игроков с метками)"
})
L:SetMiscLocalization({
NefAoe = "В воздухе трещат электрические разряды!",
YellPhase2 = "Дерзкие смертные! Неуважение к чужой собственности нужно пресекать самым жестоким образом!",
YellPhase3 = "Я пытался следовать законам гостеприимства, но вы всё никак не умрете!",
YellShadowBlaze = "И плоть превратится в прах!",
ShadowBlazeExact = "Вспышка пламени тени через %d",
ShadowBlazeEstimate = "Скоро вспышка пламени тени (~5с)"
})
-------------------------------
-- Blackwing Descent Trash --
-------------------------------
L = DBM:GetModLocalization("BWDTrash")
L:SetGeneralLocalization({
name = "Существа Твердыни Крыла Тьмы"
})
| gpl-2.0 |
MOSAVI17/Informationbot | plugins/weater.lua | 1 | 1444 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Yogyakarta'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Yogyakarta is default)",
usage = "/weather (city)",
patterns = {
"^/weather$",
"^/weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
n0xus/darkstar | scripts/globals/items/plate_of_boiled_barnacles_+1.lua | 36 | 1282 | -----------------------------------------
-- ID: 5981
-- Item: Plate of Boiled Barnacles +1
-- Food Effect: 60 Mins, All Races
-----------------------------------------
-- Charisma -2
-- Defense % 26 Cap 135
-----------------------------------------
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,3600,5981);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_CHR, -2);
target:addMod(MOD_FOOD_DEFP, 26);
target:addMod(MOD_FOOD_DEF_CAP, 135);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_CHR, -2);
target:delMod(MOD_FOOD_DEFP, 26);
target:delMod(MOD_FOOD_DEF_CAP, 135);
end;
| gpl-3.0 |
n0xus/darkstar | scripts/zones/Bastok_Markets/npcs/Rabid_Wolf_IM.lua | 28 | 4892 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Rabid Wolf, I.M.
-- X Grant Signet
-- X Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-- X Start Supply Run Missions and offers a list of already-delivered supplies.
-- Start an Expeditionary Force by giving an E.F. region insignia to you.
-------------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Bastok_Markets/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = table.getn(BastInv);
local inventory = BastInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then
player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies."
local region = player:getVar("supplyQuest_region");
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region));
player:setVar("supplyQuest_started",0);
player:setVar("supplyQuest_region",0);
player:setVar("supplyQuest_fresh",0);
else
local Menu1 = getArg1(guardnation,player);
local Menu2 = getExForceAvailable(guardnation,player);
local Menu3 = conquestRanking();
local Menu4 = getSupplyAvailable(guardnation,player);
local Menu5 = player:getNationTeleport(guardnation);
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
local Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ff9,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break;
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end;
end;
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
break;
end;
end;
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end;
end; | gpl-3.0 |
n0xus/darkstar | scripts/globals/weaponskills/black_halo.lua | 30 | 1536 | -----------------------------------
-- Black Halo
-- Club weapon skill
-- Skill level: 230
-- In order to obtain Black Halo, the quest Orastery Woes must be completed.
-- Delivers a two-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Shadow Gorget, Thunder Gorget & Breeze Gorget.
-- Aligned with the Shadow Belt, Thunder Belt & Breeze Belt.
-- Element: None
-- Modifiers: STR:30% ; MND:50%
-- 100%TP 200%TP 300%TP
-- 1.50 2.50 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 2;
params.ftp100 = 1.5; params.ftp200 = 2.5; params.ftp300 = 3;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.5; 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.ftp100 = 3.0; params.ftp200 = 7.25; params.ftp300 = 9.75;
params.mnd_wsc = 0.7;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
misterdustinface/gamelib-common-polyglot | src/param-adjuster/layout-partials/int32-editor.lua | 1 | 17137 | local datastore = require 'datastore'
local constants = require 'constants'
local widgets = require 'widgets'
local style = require 'style'
local fonts = require 'fonts'
local rects = require 'rects'
local icons = require 'icons'
local new_action = require 'touch-action'
local txtfield = require 'layout-partials.txt-field'
local backend = require 'metasys.backend'
local timers = require 'animation-timers'
local text_hint = require 'layout-partials.text-hint'
-- local editorTitle = {
-- font = fonts["OpenSans 14"],
-- text = 'hello world',
-- justification = widgets.JUSTIFICATION.eCenter,
-- horz_align__pct = 0.5,
-- vert_align__pct = 0.5,
-- }
local int32Name = {
family = "OpenSans",
size = 10,
minsize = 8,
-- font = fonts["OpenSans 10"],
text = 'hello world',
justification = widgets.JUSTIFICATION.eCenter,
horz_align__pct = 0.5,
vert_align__pct = 0.05,
}
local int32Value = {
family = "OpenSans",
size = 14,
minsize = 10,
-- font = fonts["OpenSans 14"],
text = 'hello world',
justification = widgets.JUSTIFICATION.eCenter,
horz_align__pct = 0.5,
vert_align__pct = 0.5,
}
local int32Range = {
family = "OpenSans",
size = 10,
minsize = 8,
-- font = fonts["OpenSans 10"],
text = 'hello world',
justification = widgets.JUSTIFICATION.eCenter,
horz_align__pct = 0.5,
vert_align__pct = 0.5,
}
local tab = {}
local close_page_hintId = text_hint.register("Click to Remove Tab")
local reset_value_hintId = text_hint.register("Click to Reset Value")
local accept_value_hintId = text_hint.register("Click to Accept Value")
local progress_bar_hintId = text_hint.register("Drag to Change Value")
local live_accept_value_hintId = text_hint.register("Right Click to Auto-Accept Values Live")
local act_remove_from_editor = new_action {
onPress = function(xIndex, xRelativeTouchx, xRelativeTouchy)
datastore.editor_close_pressed = true
local editor_index = datastore.editor_index
table.remove(datastore.editor_partial_and_index, editor_index)
datastore.params_by_type.int32[xIndex].is_in_edit = false
datastore.selectedTextField = constants.nulltextfield
datastore.editor_index = math.min(#datastore.editor_partial_and_index, datastore.editor_index)
datastore.has_acknowledged_hint[close_page_hintId] = true
end,
onRelease = function(xIndex, xRelativeTouchx, xRelativeTouchy)
datastore.editor_close_pressed = false
end,
onInside = function(xIndex, xRelativeTouchx, xRelativeTouchy)
datastore.editor_close_hover = true
end,
onOutside = function(xIndex)
datastore.editor_close_hover = false
datastore.editor_close_pressed = false
text_hint.reset()
end,
}
local act_reset_value = new_action {
onPress = function(xIndex, xRelativeTouchx, xRelativeTouchy)
datastore.editor_reset_pressed = true
local thing = datastore.params_by_type.int32[xIndex]
thing.ptr.value = thing.initialval
datastore.has_acknowledged_hint[reset_value_hintId] = true
end,
onRelease = function(xIndex, xRelativeTouchx, xRelativeTouchy)
datastore.editor_reset_pressed = false
end,
onInside = function(xIndex, xRelativeTouchx, xRelativeTouchy)
datastore.editor_reset_hover = true
end,
onOutside = function(xIndex)
datastore.editor_reset_hover = false
datastore.editor_reset_pressed = false
text_hint.reset()
end,
}
local act_accept_value = new_action {
onPress = function(xIndex, xRelativeTouchx, xRelativeTouchy)
datastore.editor_accept_pressed = true
local thing = datastore.params_by_type.int32[xIndex]
thing.callback(xIndex, thing.ptr.value)
datastore.has_acknowledged_hint[accept_value_hintId] = true
end,
onRelease = function(xIndex, xRelativeTouchx, xRelativeTouchy)
datastore.editor_accept_pressed = false
end,
onPressAlt = function(xIndex)
datastore.editor_accept_pressed = true
datastore.ACCEPT_ALL_CHANGES_LIVE = not datastore.ACCEPT_ALL_CHANGES_LIVE
if datastore.has_acknowledged_hint[accept_value_hintId] then
datastore.has_acknowledged_hint[live_accept_value_hintId] = true
end
end,
onReleaseAlt = function()
datastore.editor_accept_pressed = false
end,
onInside = function(xIndex, xRelativeTouchx, xRelativeTouchy)
datastore.editor_accept_hover = true
end,
onOutside = function(xIndex)
datastore.editor_accept_hover = false
datastore.editor_accept_pressed = false
text_hint.reset()
end,
}
local act_progress_bar = new_action {
onDrag = function(xIndex, xRelativeTouchx, xRelativeTouchy)
local thing = datastore.params_by_type.int32[xIndex]
local range = datastore.ranges.int32
thing.ptr.value = math.floor(math.max(math.min(((xRelativeTouchx-10) / (rects.int32_editor_progress_bar.w-20)), 1), 0) * (range.maxvalue - range.minvalue)) + range.minvalue
datastore.has_acknowledged_hint[progress_bar_hintId] = true
if datastore.ACCEPT_ALL_CHANGES_LIVE then
thing.callback(xIndex, thing.ptr.value)
end
end,
onInside = function()
datastore.int32_editor_pb_hover = true
end,
onOutside = function()
datastore.int32_editor_pb_hover = false
text_hint.reset()
end
}
local act_set_editor = new_action {
onDragInside = function()
local dragged = datastore.dragged_partial
if dragged.isActive then
local ii = dragged.index
if dragged.type == "int32" then
local thing = datastore.params_by_type.int32[ii]
if not thing.is_in_edit then
table.insert(datastore.editor_partial_and_index, {
partial = require 'layout-partials.int32-editor',
index = xIndex,
})
datastore.editor_index = #datastore.editor_partial_and_index
thing.is_in_edit = true
end
elseif dragged.type == "int64" then
local thing = datastore.params_by_type.int64[ii]
if not thing.is_in_edit then
table.insert(datastore.editor_partial_and_index, {
partial = require 'layout-partials.int64-editor',
index = xIndex,
})
datastore.editor_index = #datastore.editor_partial_and_index
thing.is_in_edit = true
end
elseif dragged.type == "color" then
local thing = datastore.params_by_type.color[ii]
if not thing.is_in_edit then
table.insert(datastore.editor_partial_and_index, {
partial = require 'layout-partials.color-editor',
index = xIndex,
})
datastore.editor_index = #datastore.editor_partial_and_index
thing.is_in_edit = true
end
end
datastore.dragged_partial.isActive = false
end
end,
}
tab.render = function(xTouchmap, index, x, y)
if not index then return end
-- xTouchmap.append(x, y, tab.horizontal_offset(), tab.vertical_offset(), act_set_editor, index)
local thing = datastore.params_by_type.int32[index]
-- if info.isHovering then
-- love.graphics.setColor(unpack(style.highlighted))
-- else
love.graphics.setColor(unpack(style.element))
-- end
if thing.isPressed then
love.graphics.setColor(unpack(style.selected))
end
love.graphics.rectangle('fill', x, y, rects.editor.w, rects.editor.h)
if datastore.paging_bar.isHovering then
love.graphics.setColor(unpack(style.highlighted))
else
love.graphics.setColor(unpack(style.background_separator))
end
love.graphics.rectangle("fill",
rects.editor_paging_bar.x, rects.editor_paging_bar.y,
rects.editor_paging_bar.w, rects.editor_paging_bar.h)
local range = datastore.ranges.int32
widgets.drawProgressBar(
rects.int32_editor_progress_bar.x, rects.int32_editor_progress_bar.y,
rects.int32_editor_progress_bar.w, rects.int32_editor_progress_bar.h,
(thing.ptr.value - range.minvalue) / (range.maxvalue - range.minvalue),
style.progress_bar_background, style.progress_bar_foreground
)
xTouchmap.append(rects.int32_editor_progress_bar.x, rects.int32_editor_progress_bar.y,
rects.int32_editor_progress_bar.w, rects.int32_editor_progress_bar.h,
act_progress_bar, index)
if not datastore.int32_editor_pb_hover then
love.graphics.setColor(style.progress_bar_background)
love.graphics.rectangle("line", rects.int32_editor_progress_bar.x, rects.int32_editor_progress_bar.y,
rects.int32_editor_progress_bar.w, rects.int32_editor_progress_bar.h)
end
love.graphics.setColor(unpack(style.element_text))
int32Name.text = thing.name
widgets.drawTextWithin(int32Name, x, y, rects.editor.w, rects.editor.h)
int32Value.text = thing.ptr.value
widgets.drawTextWithin(int32Value, x, y, rects.editor.w, rects.editor.h)
txtfield.render(xTouchmap, 3,
x + (rects.editor.w - txtfield.horizontal_offset(3)) / 2,
y + (rects.editor.h - txtfield.vertical_offset(3)) / 2 + txtfield.vertical_offset(), int32Value
);
int32Range.text = datastore.ranges.int32.minvalue
datastore.textfields[4].w = rects.int32_editor_progress_bar.w / 8
datastore.textfields[4].h = rects.int32_editor_progress_bar.h
txtfield.render(xTouchmap, 4,
rects.int32_editor_progress_bar.x,
rects.int32_editor_progress_bar.y - (txtfield.vertical_offset(4) + 10),
int32Range,
datastore.textfields[4].w,
datastore.textfields[4].h
);
int32Range.text = datastore.ranges.int32.maxvalue
datastore.textfields[5].w = rects.int32_editor_progress_bar.w / 8
datastore.textfields[5].h = rects.int32_editor_progress_bar.h
txtfield.render(xTouchmap, 5,
rects.int32_editor_progress_bar.x + rects.int32_editor_progress_bar.w - txtfield.horizontal_offset(5),
rects.int32_editor_progress_bar.y - (txtfield.vertical_offset(5) + 10),
int32Range,
datastore.textfields[5].w,
datastore.textfields[5].h
);
if datastore.editor_close_pressed then
love.graphics.setColor(unpack(style.editor_close_button_pressed))
elseif datastore.editor_close_hover then
love.graphics.setColor(unpack(style.editor_close_button_hover))
else
love.graphics.setColor(unpack(style.editor_close_button))
end
love.graphics.rectangle('fill', rects.editor_close_button.x, rects.editor_close_button.y,
rects.editor_close_button.w, rects.editor_close_button.h)
love.graphics.setColor(unpack(style.element_text))
icons.drawX(rects.editor_close_button.x, rects.editor_close_button.y,
rects.editor_close_button.w, rects.editor_close_button.h)
if datastore.editor_reset_pressed then
love.graphics.setColor(unpack(style.editor_reset_button_pressed))
elseif datastore.editor_reset_hover then
love.graphics.setColor(unpack(style.editor_reset_button_hover))
else
love.graphics.setColor(unpack(style.editor_reset_button))
end
love.graphics.rectangle('fill', rects.editor_reset_button.x, rects.editor_reset_button.y,
rects.editor_reset_button.w, rects.editor_reset_button.h)
love.graphics.setColor(unpack(style.element_text))
icons.drawReset(rects.editor_reset_button.x, rects.editor_reset_button.y,
rects.editor_reset_button.w, rects.editor_reset_button.h)
if datastore.editor_accept_pressed then
love.graphics.setColor(unpack(style.editor_accept_button_pressed))
elseif datastore.editor_accept_hover then
love.graphics.setColor(unpack(style.editor_accept_button_hover))
else
love.graphics.setColor(unpack(style.editor_accept_button))
end
love.graphics.rectangle('fill', rects.editor_accept_button.x, rects.editor_accept_button.y,
rects.editor_accept_button.w, rects.editor_accept_button.h)
if datastore.ACCEPT_ALL_CHANGES_LIVE then
love.graphics.setColor(unpack(style.editor_accept_button_hover))
love.graphics.rectangle('line', rects.editor_accept_button.x, rects.editor_accept_button.y,
rects.editor_accept_button.w, rects.editor_accept_button.h)
end
love.graphics.setColor(unpack(style.element_text))
icons.drawCheck(rects.editor_accept_button.x, rects.editor_accept_button.y,
rects.editor_accept_button.w, rects.editor_accept_button.h)
if datastore.editor_close_hover then
text_hint.render_left(xTouchmap, rects.editor_close_button.x, rects.editor_close_button.y, close_page_hintId)
end
if datastore.editor_reset_hover then
text_hint.render_left(xTouchmap, rects.editor_reset_button.x, rects.editor_reset_button.y, reset_value_hintId)
end
if datastore.editor_accept_hover then
if datastore.has_acknowledged_hint[accept_value_hintId] then
text_hint.render_left(xTouchmap, rects.editor_accept_button.x, rects.editor_accept_button.y, live_accept_value_hintId)
else
text_hint.render_left(xTouchmap, rects.editor_accept_button.x, rects.editor_accept_button.y, accept_value_hintId)
end
end
if datastore.int32_editor_pb_hover then
text_hint.render_above(xTouchmap, rects.int32_editor_progress_bar.x, rects.int32_editor_progress_bar.y, progress_bar_hintId)
end
xTouchmap.append(rects.editor_close_button.x, rects.editor_close_button.y,
rects.editor_close_button.w, rects.editor_close_button.h,
act_remove_from_editor, index)
xTouchmap.append(rects.editor_reset_button.x, rects.editor_reset_button.y,
rects.editor_reset_button.w, rects.editor_reset_button.h,
act_reset_value, index)
xTouchmap.append(rects.editor_accept_button.x, rects.editor_accept_button.y,
rects.editor_accept_button.w, rects.editor_accept_button.h,
act_accept_value, index)
end
tab.vertical_offset = function()
return rects.editor.h
end
tab.horizontal_offset = function()
return rects.editor.w
end
local std_txtfield_input = function(index, text)
local txtfield = datastore.textfields[index]
txtfield.insert_pos = math.min(#txtfield.text + 1, txtfield.insert_pos + 1)
table.insert(txtfield.text, txtfield.insert_pos, text)
timers.text_position_indicator = 0
end
local std_txtfield_keypressed = function(index, key, on_return_callback)
local txtfield = datastore.textfields[index]
timers.text_position_indicator = 0
if key == 'right' then
txtfield.insert_pos = math.min(#txtfield.text, txtfield.insert_pos + 1)
end
if key == 'left' then
txtfield.insert_pos = math.max(0, txtfield.insert_pos - 1)
end
if key == "backspace" then
if txtfield.insert_pos > 0 then
table.remove(txtfield.text, txtfield.insert_pos)
txtfield.insert_pos = math.max(0, txtfield.insert_pos - 1)
if #txtfield.text < txtfield.insert_pos then
txtfield.insert_pos = #txtfield.text
end
end
end
if key == "delete" then
if txtfield.insert_pos < #txtfield.text then
table.remove(txtfield.text, txtfield.insert_pos + 1)
if #txtfield.text < txtfield.insert_pos then
txtfield.insert_pos = #txtfield.text
end
end
end
if key == "return" then
local result = '?'
local expression = table.concat(txtfield.text)
local loadable_expression = table.concat({'return', expression}, ' ')
local f, err = loadstring(loadable_expression)
local success, output = pcall(f)
if f and success then
result = output
elseif f then
result = "ERROR: " .. output
else
result = "ERROR: " .. err
end
txtfield.text = {}
table.insert(txtfield.text, tostring(result))
txtfield.insert_pos = 1
on_return_callback(result, index, key)
end
end
-- good stuff --
local int32_on_return_callback = function(result, index, key)
if type(result) == 'number' then
local index = datastore.editor_partial_and_index[datastore.editor_index].index
local thing = datastore.params_by_type.int32[index]
thing.ptr.value = result
if datastore.ACCEPT_ALL_CHANGES_LIVE then
thing.callback(index, thing.ptr.value)
end
end
end
datastore.textfields[3].input = function(index, text)
std_txtfield_input(index, text)
end
datastore.textfields[3].keypressed = function(index, key)
std_txtfield_keypressed(index, key, int32_on_return_callback)
end
local int32_range_min_on_return_callback = function(result, index, key)
if type(result) == 'number' then
local range = datastore.ranges.int32
range.minvalue = result
end
end
-- datastore.textfields[4].text[1] = datastore.ranges.int32.minvalue
datastore.textfields[4].input = function(index, text)
std_txtfield_input(index, text)
end
datastore.textfields[4].keypressed = function(index, key)
std_txtfield_keypressed(index, key, int32_range_min_on_return_callback)
end
local int32_range_max_on_return_callback = function(result, index, key)
if type(result) == 'number' then
local range = datastore.ranges.int32
range.maxvalue = result
end
end
-- datastore.textfields[5].text[1] = datastore.ranges.int32.maxvalue
datastore.textfields[5].input = function(index, text)
std_txtfield_input(index, text)
end
datastore.textfields[5].keypressed = function(index, key)
std_txtfield_keypressed(index, key, int32_range_max_on_return_callback)
end
return tab
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Selbina/npcs/Mendoline.lua | 17 | 1185 | -----------------------------------
-- Area: Selbina
-- NPC: Mendoline
-- Guild Merchant NPC: Fishing Guild
-- @pos -13.603 -7.287 10.916 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(5182,3,18,5)) then
player:showText(npc,FISHING_SHOP_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 |
QVaucher/Gwynt-Lua | lib/suit/imagebutton.lua | 8 | 1338 | -- This file is part of SUIT, copyright (c) 2016 Matthias Richter
local BASE = (...):match('(.-)[^%.]+$')
return function(core, normal, ...)
local opt, x,y = core.getOptionsAndSize(...)
opt.normal = normal or opt.normal or opt[1]
opt.hovered = opt.hovered or opt[2] or opt.normal
opt.active = opt.active or opt[3] or opt.hovered
assert(opt.normal, "Need at least `normal' state image")
opt.id = opt.id or opt.normal
opt.state = core:registerMouseHit(opt.id, x,y, function(u,v)
local id = opt.normal:getData()
assert(id:typeOf("ImageData"), "Can only use uncompressed images")
u, v = math.floor(u+.5), math.floor(v+.5)
if u < 0 or u >= opt.normal:getWidth() or v < 0 or v >= opt.normal:getHeight() then
return false
end
local _,_,_,a = id:getPixel(u,v)
return a > 0
end)
local img = opt.normal
if core:isActive(opt.id) then
img = opt.active
elseif core:isHovered(opt.id) then
img = opt.hovered
end
core:registerDraw(opt.draw or function(img,x,y, r,g,b,a)
love.graphics.setColor(r,g,b,a)
love.graphics.draw(img,x,y)
end, img, x,y, love.graphics.getColor())
return {
id = opt.id,
hit = core:mouseReleasedOn(opt.id),
hovered = core:isHovered(opt.id),
entered = core:isHovered(opt.id) and not core:wasHovered(opt.id),
left = not core:isHovered(opt.id) and core:wasHovered(opt.id)
}
end
| mit |
n0xus/darkstar | scripts/zones/Gustav_Tunnel/npcs/qm2.lua | 19 | 2008 | -----------------------------------
-- Area: Gustav tunnel
-- NPC: qm2 (???)
-- bastok 9-1
-- @zone 212
-- @pos -130 1.256 252.696
-----------------------------------
package.loaded["scripts/zones/Gustav_Tunnel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Gustav_Tunnel/TextIDs");
-----------------------------------
-- onTrade Action
----------------------------------
function onTrade(player,npc,trade)
end;
----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(BASTOK) == THE_SALT_OF_THE_EARTH) then
if (GetMobAction(17645794)==0 and GetMobAction(17645795)==0 and GetMobAction(17645796)== 0 and GetMobAction(17645797)== 0 and GetMobAction(17645798)== 0 and GetMobAction(17645799)== 0 and GetMobAction(17645800)== 0 and GetMobAction(17645801)== 0 and GetMobAction(17645802)== 0 and GetMobAction(17645803)== 0 and GetMobAction(17645804)== 0 and GetMobAction(17645805)== 0 and GetMobAction(17645806)== 0 and GetMobAction(17645807)== 0 and GetMobAction(17645808)== 0) then
if (player:getVar("BASTOK91") == 3) then
if not(player:hasKeyItem(MIRACLESALT)) then
player:addKeyItem(MIRACLESALT);
player:messageSpecial(KEYITEM_OBTAINED,MIRACLESALT);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
elseif (player:getVar("BASTOK91") ==2) then
SpawnMob(17645794);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 |
Python1320/wire | lua/wire/client/texteditor.lua | 3 | 111941 | --
-- Expression 2 Text Editor for Garry's Mod
-- Andreas "Syranide" Svensson, me@syranide.com
--
local string_Explode = string.Explode
local table_concat = table.concat
local string_sub = string.sub
local table_remove = table.remove
local math_floor = math.floor
local math_Clamp = math.Clamp
local math_ceil = math.ceil
local string_match = string.match
local string_gmatch = string.gmatch
local string_gsub = string.gsub
local string_rep = string.rep
local string_byte = string.byte
local string_format = string.format
local string_Trim = string.Trim
local string_reverse = string.reverse
local math_min = math.min
local table_insert = table.insert
local table_sort = table.sort
local surface_SetDrawColor = surface.SetDrawColor
local surface_DrawRect = surface.DrawRect
local surface_SetFont = surface.SetFont
local surface_GetTextSize = surface.GetTextSize
local surface_PlaySound = surface.PlaySound
local surface_SetTextPos = surface.SetTextPos
local surface_SetTextColor = surface.SetTextColor
local surface_DrawText = surface.DrawText
local draw_SimpleText = draw.SimpleText
local draw_WordBox = draw.WordBox
local draw_RoundedBox = draw.RoundedBox
local wire_expression2_autocomplete_controlstyle = CreateClientConVar( "wire_expression2_autocomplete_controlstyle", "0", true, false )
local EDITOR = {}
function EDITOR:Init()
self:SetCursor("beam")
self.Rows = {""}
self.Caret = {1, 1}
self.Start = {1, 1}
self.Scroll = {1, 1}
self.Size = {1, 1}
self.Undo = {}
self.Redo = {}
self.PaintRows = {}
self.LineNumberWidth = 2
self.Blink = RealTime()
self.ScrollBar = vgui.Create("DVScrollBar", self)
self.ScrollBar:SetUp(1, 1)
self.TextEntry = vgui.Create("TextEntry", self)
self.TextEntry:SetMultiline(true)
self.TextEntry:SetSize(0, 0)
self.TextEntry.OnLoseFocus = function (self) self.Parent:_OnLoseFocus() end
self.TextEntry.OnTextChanged = function (self) self.Parent:_OnTextChanged() end
self.TextEntry.OnKeyCodeTyped = function (self, code) self.Parent:_OnKeyCodeTyped(code) end
self.TextEntry.Parent = self
self.LastClick = 0
self.e2fs_functions = {}
end
function EDITOR:GetParent()
return self.parentpanel
end
function EDITOR:RequestFocus()
self.TextEntry:RequestFocus()
end
function EDITOR:OnGetFocus()
self.TextEntry:RequestFocus()
end
function EDITOR:CursorToCaret()
local x, y = self:CursorPos()
x = x - (self.LineNumberWidth + 6)
if x < 0 then x = 0 end
if y < 0 then y = 0 end
local line = math_floor(y / self.FontHeight)
local char = math_floor(x / self.FontWidth+0.5)
line = line + self.Scroll[1]
char = char + self.Scroll[2]
if line > #self.Rows then line = #self.Rows end
local length = #self.Rows[line]
if char > length + 1 then char = length + 1 end
return { line, char }
end
local wire_expression2_editor_highlight_on_double_click = CreateClientConVar( "wire_expression2_editor_highlight_on_double_click", "1", true, false )
function EDITOR:OnMousePressed(code)
if code == MOUSE_LEFT then
local cursor = self:CursorToCaret()
if((CurTime() - self.LastClick) < 1 and self.tmp and cursor[1] == self.Caret[1] and cursor[2] == self.Caret[2]) then
self.Start = self:getWordStart(self.Caret)
self.Caret = self:getWordEnd(self.Caret)
self.tmp = false
if (wire_expression2_editor_highlight_on_double_click:GetBool()) then
self.HighlightedAreasByDoubleClick = {}
local all_finds = self:FindAllWords( self:GetSelection() )
if (all_finds) then
all_finds[0] = {1,1} -- Set [0] so the [i-1]'s don't fail on the first iteration
self.HighlightedAreasByDoubleClick[0] = {{1,1}, {1,1}}
for i=1,#all_finds do
-- Instead of finding the caret by searching from the beginning every time, start searching from the previous caret
local start = all_finds[i][1] - all_finds[i-1][1]
local stop = all_finds[i][2] - all_finds[i-1][2]
local caretstart = self:MovePosition( self.HighlightedAreasByDoubleClick[i-1][1], start )
local caretstop = self:MovePosition( self.HighlightedAreasByDoubleClick[i-1][2], stop )
self.HighlightedAreasByDoubleClick[i] = { caretstart, caretstop }
-- This checks if it's NOT the word the user just highlighted
if (caretstart[1] != self.Start[1] or caretstart[2] != self.Start[2] or
caretstop[1] != self.Caret[1] or caretstop[2] != self.Caret[2]) then
local c = self:GetSyntaxColor("dblclickhighlight")
self:HighlightArea( { caretstart, caretstop }, c.r, c.g, c.b, 100 )
end
end
end
end
return
elseif (self.HighlightedAreasByDoubleClick) then
for i=1,#self.HighlightedAreasByDoubleClick do
self:HighlightArea( self.HighlightedAreasByDoubleClick[i] )
end
self.HighlightedAreasByDoubleClick = nil
end
self.tmp = true
self.LastClick = CurTime()
self:RequestFocus()
self.Blink = RealTime()
self.MouseDown = true
self.Caret = self:CopyPosition( cursor )
if !input.IsKeyDown(KEY_LSHIFT) and !input.IsKeyDown(KEY_RSHIFT) then
self.Start = self:CopyPosition( cursor )
end
self:AC_Check()
elseif code == MOUSE_RIGHT then
self:AC_SetVisible( false )
local menu = DermaMenu()
if self:CanUndo() then
menu:AddOption("Undo", function()
self:DoUndo()
end)
end
if self:CanRedo() then
menu:AddOption("Redo", function()
self:DoRedo()
end)
end
if self:CanUndo() or self:CanRedo() then
menu:AddSpacer()
end
if self:HasSelection() then
menu:AddOption("Cut", function()
if self:HasSelection() then
self.clipboard = self:GetSelection()
self.clipboard = string_gsub(self.clipboard, "\n", "\r\n")
SetClipboardText(self.clipboard)
self:SetSelection()
end
end)
menu:AddOption("Copy", function()
if self:HasSelection() then
self.clipboard = self:GetSelection()
self.clipboard = string_gsub(self.clipboard, "\n", "\r\n")
SetClipboardText(self.clipboard)
end
end)
end
menu:AddOption("Paste", function()
if self.clipboard then
self:SetSelection(self.clipboard)
else
self:SetSelection()
end
end)
if self:HasSelection() then
menu:AddOption("Delete", function()
self:SetSelection()
end)
end
menu:AddSpacer()
menu:AddOption("Select all", function()
self:SelectAll()
end)
menu:AddSpacer()
menu:AddOption("Indent", function()
self:Indent(false)
end)
menu:AddOption("Outdent", function()
self:Indent(true)
end)
if self:HasSelection() then
menu:AddSpacer()
menu:AddOption("Comment Block", function()
self:CommentSelection(false)
end)
menu:AddOption("Uncomment Block", function()
self:CommentSelection(true)
end)
menu:AddOption("Comment Selection",function()
self:BlockCommentSelection( false )
end)
menu:AddOption("Uncomment Selection",function()
self:BlockCommentSelection( true )
end)
end
if self.chosenfile and not self:GetParent().E2 then
menu:AddSpacer()
local caretPos = self:CursorToCaret()
local IsBreakpointSet = CPULib.GetDebugBreakpoint( self.chosenfile, caretPos )
if not IsBreakpointSet then
menu:AddOption( "Add Breakpoint", function()
CPULib.SetDebugBreakpoint( self.chosenfile, caretPos, true )
end)
-- menu:AddOption( "Add Conditional Breakpoint", function()
-- Derma_StringRequestNoBlur( "Add Conditional Breakpoint", "456", "123",
-- function( strTextOut )
-- CPULib.SetDebugBreakpoint( caretPos, strTextOut )
-- end )
-- end)
else
menu:AddOption( "Remove Breakpoint", function()
CPULib.SetDebugBreakpoint( self.chosenfile, caretPos )
end)
end
end
menu:AddSpacer()
menu:AddOption( "Copy with BBCode colors", function()
local str = string_format( "[code][font=%s]", self:GetParent().FontConVar:GetString() )
local prev_colors
local first_loop = true
for i=1,#self.Rows do
local colors = self:SyntaxColorLine(i)
for k,v in pairs( colors ) do
local color = v[2][1]
if (prev_colors and prev_colors == color) or string_Trim(v[1]) == "" then
str = str .. v[1]
else
prev_colors = color
if first_loop then
str = str .. string_format( '[color="#%x%x%x"]', color.r - 50, color.g - 50, color.b - 50 ) .. v[1]
first_loop = false
else
str = str .. string_format( '[/color][color="#%x%x%x"]', color.r - 50, color.g - 50, color.b - 50 ) .. v[1]
end
end
end
str = str .. "\r\n"
end
str = str .. "[/color][/font][/code]"
self.clipboard = str
SetClipboardText( str )
end)
menu:Open()
end
end
function EDITOR:OnMouseReleased(code)
if !self.MouseDown then return end
if code == MOUSE_LEFT then
self.MouseDown = nil
if(!self.tmp) then return end
self.Caret = self:CursorToCaret()
end
end
function EDITOR:SetText(text)
self.Rows = string_Explode("\n", text)
if self.Rows[#self.Rows] != "" then
self.Rows[#self.Rows + 1] = ""
end
self.Caret = {1, 1}
self.Start = {1, 1}
self.Scroll = {1, 1}
self.Undo = {}
self.Redo = {}
self.PaintRows = {}
self:AC_Reset()
self.ScrollBar:SetUp(self.Size[1], #self.Rows - 1)
end
function EDITOR:GetValue()
return string_gsub(table_concat(self.Rows, "\n"), "\r", "")
end
function EDITOR:HighlightLine( line, r, g, b, a )
if (!self.HighlightedLines) then self.HighlightedLines = {} end
if (!r and self.HighlightedLines[line]) then
self.HighlightedLines[line] = nil
return true
elseif (r and g and b and a) then
self.HighlightedLines[line] = { r, g, b, a }
return true
end
return false
end
function EDITOR:ClearHighlightedLines() self.HighlightedLines = nil end
function EDITOR:PaintLine(row)
if row > #self.Rows then return end
if !self.PaintRows[row] then
self.PaintRows[row] = self:SyntaxColorLine(row)
end
local width, height = self.FontWidth, self.FontHeight
if row == self.Caret[1] and self.TextEntry:HasFocus() then
surface_SetDrawColor(48, 48, 48, 255)
surface_DrawRect(self.LineNumberWidth + 5, (row - self.Scroll[1]) * height, self:GetWide() - (self.LineNumberWidth + 5), height)
end
if (self.HighlightedLines and self.HighlightedLines[row]) then
local color = self.HighlightedLines[row]
surface_SetDrawColor( color[1], color[2], color[3], color[4] )
surface_DrawRect(self.LineNumberWidth + 5, (row - self.Scroll[1]) * height, self:GetWide() - (self.LineNumberWidth + 5), height)
end
if self:HasSelection() then
local start, stop = self:MakeSelection(self:Selection())
local line, char = start[1], start[2]
local endline, endchar = stop[1], stop[2]
surface_SetDrawColor(0, 0, 160, 255)
local length = self.Rows[row]:len() - self.Scroll[2] + 1
char = char - self.Scroll[2]
endchar = endchar - self.Scroll[2]
if char < 0 then char = 0 end
if endchar < 0 then endchar = 0 end
if row == line and line == endline then
surface_DrawRect(char * width + self.LineNumberWidth + 6, (row - self.Scroll[1]) * height, width * (endchar - char), height)
elseif row == line then
surface_DrawRect(char * width + self.LineNumberWidth + 6, (row - self.Scroll[1]) * height, width * (length - char + 1), height)
elseif row == endline then
surface_DrawRect(self.LineNumberWidth + 6, (row - self.Scroll[1]) * height, width * endchar, height)
elseif row > line and row < endline then
surface_DrawRect(self.LineNumberWidth + 6, (row - self.Scroll[1]) * height, width * (length + 1), height)
end
end
draw_SimpleText(tostring(row), self.CurrentFont, self.LineNumberWidth + 2, (row - self.Scroll[1]) * height, Color(128, 128, 128, 255), TEXT_ALIGN_RIGHT)
local offset = -self.Scroll[2] + 1
for i,cell in ipairs(self.PaintRows[row]) do
if offset < 0 then
if cell[1]:len() > -offset then
line = cell[1]:sub(1-offset)
offset = line:len()
if cell[2][2] then
draw_SimpleText(line .. " ", self.CurrentFont .. "_Bold", self.LineNumberWidth+ 6, (row - self.Scroll[1]) * height, cell[2][1])
else
draw_SimpleText(line .. " ", self.CurrentFont, self.LineNumberWidth + 6, (row - self.Scroll[1]) * height, cell[2][1])
end
else
offset = offset + cell[1]:len()
end
else
if cell[2][2] then
draw_SimpleText(cell[1] .. " ", self.CurrentFont .. "_Bold", offset * width + self.LineNumberWidth + 6, (row - self.Scroll[1]) * height, cell[2][1])
else
draw_SimpleText(cell[1] .. " ", self.CurrentFont, offset * width + self.LineNumberWidth + 6, (row - self.Scroll[1]) * height, cell[2][1])
end
offset = offset + cell[1]:len()
end
end
end
function EDITOR:PerformLayout()
self.ScrollBar:SetSize(16, self:GetTall())
self.ScrollBar:SetPos(self:GetWide() - 16, 0)
self.Size[1] = math_floor(self:GetTall() / self.FontHeight) - 1
self.Size[2] = math_floor((self:GetWide() - (self.LineNumberWidth + 6) - 16) / self.FontWidth) - 1
self.ScrollBar:SetUp(self.Size[1], #self.Rows - 1)
end
function EDITOR:HighlightArea( area, r,g,b,a )
if (!self.HighlightedAreas) then self.HighlightedAreas = {} end
if (!r) then
local _start, _stop = area[1], area[2]
for k,v in pairs( self.HighlightedAreas ) do
local start = v[1][1]
local stop = v[1][2]
if (start[1] == _start[1] and start[2] == _start[2] and stop[1] == _stop[1] and stop[2] == _stop[2]) then
table.remove( self.HighlightedAreas, k )
break
end
end
return true
elseif (r and g and b and a) then
self.HighlightedAreas[#self.HighlightedAreas+1] = {area, r, g, b, a }
return true
end
return false
end
function EDITOR:ClearHighlightedAreas() self.HighlightedAreas = nil end
function EDITOR:PaintTextOverlay()
if self.TextEntry:HasFocus() and self.Caret[2] - self.Scroll[2] >= 0 then
local width, height = self.FontWidth, self.FontHeight
if (RealTime() - self.Blink) % 0.8 < 0.4 then
surface_SetDrawColor(240, 240, 240, 255)
surface_DrawRect((self.Caret[2] - self.Scroll[2]) * width + self.LineNumberWidth + 6, (self.Caret[1] - self.Scroll[1]) * height, 1, height)
end
-- Area highlighting
if (self.HighlightedAreas) then
local xofs = self.LineNumberWidth + 6
for key, data in pairs( self.HighlightedAreas ) do
local area, r,g,b,a = data[1], data[2], data[3], data[4], data[5]
surface_SetDrawColor( r,g,b,a )
local start, stop = self:MakeSelection( area )
if (start[1] == stop[1]) then -- On the same line
surface_DrawRect( xofs + (start[2]-self.Scroll[2]) * width, (start[1]-self.Scroll[1]) * height, (stop[2]-start[2]) * width, height )
elseif (start[1] < stop[1]) then -- Ends below start
for i=start[1],stop[1] do
if (i == start[1]) then
surface_DrawRect( xofs + (start[2]-self.Scroll[2]) * width, (i-self.Scroll[1]) * height, (#self.Rows[start[1]]-start[2]) * width, height )
elseif (i == stop[1]) then
surface_DrawRect( xofs + (self.Scroll[2]-1) * width, (i-self.Scroll[1]) * height, (#self.Rows[stop[1]]-stop[2]) * width, height )
else
surface_DrawRect( xofs + (self.Scroll[2]-1) * width, (i-self.Scroll[1]) * height, #self.Rows[i] * width, height )
end
end
end
end
end
-- Bracket highlighting by: {Jeremydeath}
local WindowText = self:GetValue()
local LinePos = table_concat(self.Rows, "\n", 1, self.Caret[1]-1):len()
local CaretPos = LinePos+self.Caret[2]+1
local BracketPairs = {
["{"] = "}",
["}"] = "{",
["["] = "]",
["]"] = "[",
["("] = ")",
[")"] = "("
}
local CaretChars = WindowText:sub(CaretPos-1, CaretPos)
local BrackSt, BrackEnd = CaretChars:find("[%(%){}%[%]]")
local Bracket = false
if BrackSt and BrackSt != 0 then
Bracket = CaretChars:sub(BrackSt or 0,BrackEnd or 0)
end
if Bracket and BracketPairs[Bracket] then
local End = 0
local EndX = 1
local EndLine = 1
local StartX = 1
if Bracket == "(" or Bracket == "[" or Bracket == "{" then
BrackSt,End = WindowText:find("%b"..Bracket..BracketPairs[Bracket], CaretPos-1)
if BrackSt and End then
local OffsetSt = 1
local BracketLines = string_Explode("\n",WindowText:sub(BrackSt, End))
EndLine = self.Caret[1]+#BracketLines-1
EndX = End-LinePos-2
if #BracketLines>1 then
EndX = BracketLines[#BracketLines]:len()-1
end
if Bracket == "{" then
OffsetSt = 0
end
if (CaretPos - BrackSt) >= 0 and (CaretPos - BrackSt) <= 1 then
local width, height = self.FontWidth, self.FontHeight
local StartX = BrackSt - LinePos - 2
surface_SetDrawColor(255, 0, 0, 50)
surface_DrawRect((StartX-(self.Scroll[2]-1)) * width + self.LineNumberWidth + self.FontWidth + OffsetSt - 1, (self.Caret[1] - self.Scroll[1]) * height+1, width-2, height-2)
surface_DrawRect((EndX-(self.Scroll[2]-1)) * width + self.LineNumberWidth + 6, (EndLine - self.Scroll[1]) * height+1, width-2, height-2)
end
end
elseif Bracket == ")" or Bracket == "]" or Bracket == "}" then
BrackSt,End = WindowText:reverse():find("%b"..Bracket..BracketPairs[Bracket], -CaretPos)
if BrackSt and End then
local len = WindowText:len()
End = len-End+1
BrackSt = len-BrackSt+1
local BracketLines = string_Explode("\n",WindowText:sub(End, BrackSt))
EndLine = self.Caret[1]-#BracketLines+1
local OffsetSt = -1
EndX = End-LinePos-2
if #BracketLines>1 then
local PrevText = WindowText:sub(1, End):reverse()
EndX = (PrevText:find("\n",1,true) or 2)-2
end
if Bracket != "}" then
OffsetSt = 0
end
if (CaretPos - BrackSt) >= 0 and (CaretPos - BrackSt) <= 1 then
local width, height = self.FontWidth, self.FontHeight
local StartX = BrackSt - LinePos - 2
surface_SetDrawColor(255, 0, 0, 50)
surface_DrawRect((StartX-(self.Scroll[2]-1)) * width + self.LineNumberWidth + self.FontWidth - 2, (self.Caret[1] - self.Scroll[1]) * height+1, width-2, height-2)
surface_DrawRect((EndX-(self.Scroll[2]-1)) * width + self.LineNumberWidth + 8 + OffsetSt, (EndLine - self.Scroll[1]) * height+1, width-2, height-2)
end
end
end
end
end
end
local wire_expression2_editor_display_caret_pos = CreateClientConVar("wire_expression2_editor_display_caret_pos","0",true,false)
function EDITOR:Paint()
self.LineNumberWidth = self.FontWidth * #tostring(self.Scroll[1]+self.Size[1]+1)
if !input.IsMouseDown(MOUSE_LEFT) then
self:OnMouseReleased(MOUSE_LEFT)
end
if !self.PaintRows then
self.PaintRows = {}
end
if self.MouseDown then
self.Caret = self:CursorToCaret()
end
surface_SetDrawColor(0, 0, 0, 255)
surface_DrawRect(0, 0, self.LineNumberWidth + 4, self:GetTall())
surface_SetDrawColor(32, 32, 32, 255)
surface_DrawRect(self.LineNumberWidth + 5, 0, self:GetWide() - (self.LineNumberWidth + 5), self:GetTall())
self.Scroll[1] = math_floor(self.ScrollBar:GetScroll() + 1)
for i=self.Scroll[1],self.Scroll[1]+self.Size[1]+1 do
self:PaintLine(i)
end
-- Paint the overlay of the text (bracket highlighting and carret postition)
self:PaintTextOverlay()
if (wire_expression2_editor_display_caret_pos:GetBool()) then
local str = "Length: " .. #self:GetValue() .. " Lines: " .. #self.Rows .. " Ln: " .. self.Caret[1] .. " Col: " .. self.Caret[2]
if (self:HasSelection()) then
str = str .. " Sel: " .. #self:GetSelection()
end
surface_SetFont( "Default" )
local w,h = surface_GetTextSize( str )
local _w, _h = self:GetSize()
draw_WordBox( 4, _w - w - (self.ScrollBar:IsVisible() and 16 or 0) - 10, _h - h - 10, str, "Default", Color( 0,0,0,100 ), Color( 255,255,255,255 ) )
end
-- Paint CPU debug hints
if self.CurrentVarValue then
local pos = self.CurrentVarValue[1]
local x, y = (pos[2]+2) * self.FontWidth, (pos[1]-1-self.Scroll[1]) * self.FontHeight
local txt = CPULib.GetDebugPopupText(self.CurrentVarValue[2])
if txt then
draw_WordBox(2, x, y, txt, "E2SmallFont", Color(0,0,0,255), Color(255,255,255,255) )
end
end
if not self:GetParent().E2 then
if CPULib.DebuggerAttached then
local debugWindowText = CPULib.GetDebugWindowText()
for k,v in ipairs(debugWindowText) do
if v ~= "" then
local y = (k % 24)
local x = 15*(1 + math_floor(#debugWindowText / 24) - math_floor(k / 24))
draw_WordBox(2, self:GetWide()-self.FontWidth*x, self.FontHeight*(-1+y), v, "E2SmallFont", Color(0,0,0,255), Color(255,255,255,255) )
end
end
end
end
return true
end
function EDITOR:SetCaret(caret)
self.Caret = self:CopyPosition(caret)
self.Start = self:CopyPosition(caret)
self:ScrollCaret()
end
function EDITOR:CopyPosition(caret)
return { caret[1], caret[2] }
end
function EDITOR:MovePosition(caret, offset)
local row, col = caret[1], caret[2]
if offset > 0 then
local numRows = #self.Rows
while true do
local length = #(self.Rows[row]) - col + 2
if offset < length then
col = col + offset
break
elseif row == numRows then
col = col + length - 1
break
else
offset = offset - length
row = row + 1
col = 1
end
end
elseif offset < 0 then
offset = -offset
while true do
if offset < col then
col = col - offset
break
elseif row == 1 then
col = 1
break
else
offset = offset - col
row = row - 1
col = #(self.Rows[row]) + 1
end
end
end
return {row, col}
end
function EDITOR:HasSelection()
return self.Caret[1] != self.Start[1] || self.Caret[2] != self.Start[2]
end
function EDITOR:Selection()
return { { self.Caret[1], self.Caret[2] }, { self.Start[1], self.Start[2] } }
end
function EDITOR:MakeSelection(selection)
local start, stop = selection[1], selection[2]
if start[1] < stop[1] or (start[1] == stop[1] and start[2] < stop[2]) then
return start, stop
else
return stop, start
end
end
function EDITOR:GetArea(selection)
local start, stop = self:MakeSelection(selection)
if start[1] == stop[1] then
return string_sub(self.Rows[start[1]], start[2], stop[2] - 1)
else
local text = string_sub(self.Rows[start[1]], start[2])
for i=start[1]+1,stop[1]-1 do
text = text .. "\n" .. self.Rows[i]
end
return text .. "\n" .. string_sub(self.Rows[stop[1]], 1, stop[2] - 1)
end
end
function EDITOR:SetArea(selection, text, isundo, isredo, before, after)
local start, stop = self:MakeSelection(selection)
local buffer = self:GetArea(selection)
if start[1] != stop[1] or start[2] != stop[2] then
// clear selection
self.Rows[start[1]] = string_sub(self.Rows[start[1]], 1, start[2] - 1) .. string_sub(self.Rows[stop[1]], stop[2])
self.PaintRows[start[1]] = false
for i=start[1]+1,stop[1] do
table_remove(self.Rows, start[1] + 1)
table_remove(self.PaintRows, start[1] + 1)
self.PaintRows = {} // TODO: fix for cache errors
end
// add empty row at end of file (TODO!)
if self.Rows[#self.Rows] != "" then
self.Rows[#self.Rows + 1] = ""
self.PaintRows[#self.Rows + 1] = false
end
end
if !text or text == "" then
self.ScrollBar:SetUp(self.Size[1], #self.Rows - 1)
self.PaintRows = {}
self:OnTextChanged()
if isredo then
self.Undo[#self.Undo + 1] = { { self:CopyPosition(start), self:CopyPosition(start) }, buffer, after, before }
return before
elseif isundo then
self.Redo[#self.Redo + 1] = { { self:CopyPosition(start), self:CopyPosition(start) }, buffer, after, before }
return before
else
self.Redo = {}
self.Undo[#self.Undo + 1] = { { self:CopyPosition(start), self:CopyPosition(start) }, buffer, self:CopyPosition(selection[1]), self:CopyPosition(start) }
return start
end
end
// insert text
local rows = string_Explode("\n", text)
local remainder = string_sub(self.Rows[start[1]], start[2])
self.Rows[start[1]] = string_sub(self.Rows[start[1]], 1, start[2] - 1) .. rows[1]
self.PaintRows[start[1]] = false
for i=2,#rows do
table_insert(self.Rows, start[1] + i - 1, rows[i])
table_insert(self.PaintRows, start[1] + i - 1, false)
self.PaintRows = {} // TODO: fix for cache errors
end
local stop = { start[1] + #rows - 1, #(self.Rows[start[1] + #rows - 1]) + 1 }
self.Rows[stop[1]] = self.Rows[stop[1]] .. remainder
self.PaintRows[stop[1]] = false
// add empty row at end of file (TODO!)
if self.Rows[#self.Rows] != "" then
self.Rows[#self.Rows + 1] = ""
self.PaintRows[#self.Rows + 1] = false
self.PaintRows = {} // TODO: fix for cache errors
end
self.ScrollBar:SetUp(self.Size[1], #self.Rows - 1)
self.PaintRows = {}
self:OnTextChanged()
if isredo then
self.Undo[#self.Undo + 1] = { { self:CopyPosition(start), self:CopyPosition(stop) }, buffer, after, before }
return before
elseif isundo then
self.Redo[#self.Redo + 1] = { { self:CopyPosition(start), self:CopyPosition(stop) }, buffer, after, before }
return before
else
self.Redo = {}
self.Undo[#self.Undo + 1] = { { self:CopyPosition(start), self:CopyPosition(stop) }, buffer, self:CopyPosition(selection[1]), self:CopyPosition(stop) }
return stop
end
end
function EDITOR:GetSelection()
return self:GetArea(self:Selection())
end
function EDITOR:SetSelection(text)
self:SetCaret(self:SetArea(self:Selection(), text))
end
function EDITOR:OnTextChanged()
end
function EDITOR:_OnLoseFocus()
if self.TabFocus then
self:RequestFocus()
self.TabFocus = nil
end
end
-- removes the first 0-4 spaces from a string and returns it
local function unindent(line)
--local i = line:find("%S")
--if i == nil or i > 5 then i = 5 end
--return line:sub(i)
return line:match("^ ? ? ? ?(.*)$")
end
function EDITOR:_OnTextChanged()
local ctrlv = false
local text = self.TextEntry:GetValue()
self.TextEntry:SetText("")
if (input.IsKeyDown(KEY_LCONTROL) or input.IsKeyDown(KEY_RCONTROL)) and not (input.IsKeyDown(KEY_LALT) or input.IsKeyDown(KEY_RALT)) then
-- ctrl+[shift+]key
if input.IsKeyDown(KEY_V) then
-- ctrl+[shift+]V
ctrlv = true
else
-- ctrl+[shift+]key with key ~= V
return
end
end
if text == "" then return end
if not ctrlv then
if text == "\n" or text == "`" then return end
if text == "}" and GetConVarNumber('wire_expression2_autoindent') ~= 0 then
self:SetSelection(text)
local row = self.Rows[self.Caret[1]]
if string_match("{" .. row, "^%b{}.*$") then
local newrow = unindent(row)
self.Rows[self.Caret[1]] = newrow
self.Caret[2] = self.Caret[2] + newrow:len()-row:len()
self.Start[2] = self.Caret[2]
end
return
end
end
self:SetSelection(text)
self:AC_Check()
end
function EDITOR:OnMouseWheeled(delta)
if (self.AC_Panel and self.AC_Panel:IsVisible()) then
local mode = wire_expression2_autocomplete_controlstyle:GetInt()
if (mode == 2 or mode == 3) then
self.AC_Panel.Selected = self.AC_Panel.Selected - delta
if (self.AC_Panel.Selected > #self.AC_Suggestions) then self.AC_Panel.Selected = 1 end
if (self.AC_Panel.Selected < 1) then self.AC_Panel.Selected = #self.AC_Suggestions end
self:AC_FillInfoList( self.AC_Suggestions[self.AC_Panel.Selected] )
self.AC_Panel:RequestFocus()
return
else
self:AC_SetVisible(false)
end
end
self.Scroll[1] = self.Scroll[1] - 4 * delta
if self.Scroll[1] < 1 then self.Scroll[1] = 1 end
if self.Scroll[1] > #self.Rows then self.Scroll[1] = #self.Rows end
self.ScrollBar:SetScroll(self.Scroll[1] - 1)
end
function EDITOR:OnShortcut()
end
function EDITOR:ScrollCaret()
if self.Caret[1] - self.Scroll[1] < 2 then
self.Scroll[1] = self.Caret[1] - 2
if self.Scroll[1] < 1 then self.Scroll[1] = 1 end
end
if self.Caret[1] - self.Scroll[1] > self.Size[1] - 2 then
self.Scroll[1] = self.Caret[1] - self.Size[1] + 2
if self.Scroll[1] < 1 then self.Scroll[1] = 1 end
end
if self.Caret[2] - self.Scroll[2] < 4 then
self.Scroll[2] = self.Caret[2] - 4
if self.Scroll[2] < 1 then self.Scroll[2] = 1 end
end
if self.Caret[2] - 1 - self.Scroll[2] > self.Size[2] - 4 then
self.Scroll[2] = self.Caret[2] - 1 - self.Size[2] + 4
if self.Scroll[2] < 1 then self.Scroll[2] = 1 end
end
self.ScrollBar:SetScroll(self.Scroll[1] - 1)
end
-- Initialize find settings
local wire_expression2_editor_find_use_patterns = CreateClientConVar( "wire_expression2_editor_find_use_patterns", "0", true, false )
local wire_expression2_editor_find_ignore_case = CreateClientConVar( "wire_expression2_editor_find_ignore_case", "0", true, false )
local wire_expression2_editor_find_whole_word_only = CreateClientConVar( "wire_expression2_editor_find_whole_word_only", "0", true, false )
local wire_expression2_editor_find_wrap_around = CreateClientConVar( "wire_expression2_editor_find_wrap_around", "0", true, false )
local wire_expression2_editor_find_dir = CreateClientConVar( "wire_expression2_editor_find_dir", "1", true, false )
function EDITOR:HighlightFoundWord( caretstart, start, stop )
local caretstart = caretstart or self:CopyPosition( self.Start )
if istable( start ) then
self.Start = self:CopyPosition( start )
elseif isnumber( start ) then
self.Start = self:MovePosition( caretstart, start )
end
if istable( stop ) then
self.Caret = { stop[1], stop[2] + 1 }
elseif isnumber( stop ) then
self.Caret = self:MovePosition( caretstart, stop+1 )
end
self:ScrollCaret()
end
function EDITOR:Find( str, looped )
if (looped and looped >= 2) then return end
if (str == "") then return end
local _str = str
local use_patterns = wire_expression2_editor_find_use_patterns:GetBool()
local ignore_case = wire_expression2_editor_find_ignore_case:GetBool()
local whole_word_only = wire_expression2_editor_find_whole_word_only:GetBool()
local wrap_around = wire_expression2_editor_find_wrap_around:GetBool()
local dir = wire_expression2_editor_find_dir:GetBool()
-- Check if the match exists anywhere at all
local temptext = self:GetValue()
if (ignore_case) then
temptext = temptext:lower()
str = str:lower()
end
local _start,_stop = temptext:find( str, 1, !use_patterns )
if (!_start or !_stop) then return false end
if (dir) then -- Down
local line = self.Rows[self.Start[1]]
local text = line:sub(self.Start[2]) .. "\n"
text = text .. table_concat( self.Rows, "\n", self.Start[1]+1 )
if (ignore_case) then text = text:lower() end
local offset = 2
for loop = 1, 100 do
local start, stop = text:find( str, offset, !use_patterns )
if (start and stop) then
if (whole_word_only) then
local caretstart = self:MovePosition( self.Start, start )
caretstart = { caretstart[1], caretstart[2]-1 }
local caretstop = self:MovePosition( self.Start, stop )
caretstop = { caretstop[1], caretstop[2]-1 }
local wstart = self:getWordStart( { caretstart[1], caretstart[2]+1 } )
local wstop = self:getWordEnd( { caretstart[1], caretstart[2]+1 } )
if (caretstart[1] == wstart[1] and caretstop[1] == wstop[1] and
caretstart[2] == wstart[2] and caretstop[2]+1 == wstop[2]) then
self:HighlightFoundWord( nil, caretstart, caretstop )
return true
else
offset = start+1
end
else
self:HighlightFoundWord( nil, start-1, stop-1 )
return true
end
else
break
end
if (loop == 100) then error("\nInfinite loop protection enabled.\nPlease provide a detailed description of what you were doing when you got this error on www.wiremod.com.\n") return end
end
if (wrap_around) then
self:SetCaret( {1,1} )
self:Find( _str, (looped or 0) + 1 )
end
else -- Up
local text = table_concat( self.Rows, "\n", 1, self.Start[1]-1 )
local line = self.Rows[self.Start[1]]
text = text .. "\n" .. line:sub( 1, self.Start[2]-1 )
str = string_reverse( str )
text = string_reverse( text )
if (ignore_case) then text = text:lower() end
local offset = 2
for loop = 1, 100 do
local start, stop = text:find( str, offset, !use_patterns )
if (start and stop) then
if (whole_word_only) then
local caretstart = self:MovePosition( self.Start, -start )
caretstart = { caretstart[1], caretstart[2]-1 }
local caretstop = self:MovePosition( self.Start, -stop )
caretstop = { caretstop[1], caretstop[2]-1 }
local wstart = self:getWordStart( { caretstart[1], caretstart[2]+1 } )
local wstop = self:getWordEnd( { caretstart[1], caretstart[2]+1 } )
if (caretstart[1] == wstart[1] and caretstop[1] == wstop[1] and
caretstart[2] == wstart[2] and caretstop[2]+1 == wstop[2]) then
self:HighlightFoundWord( nil, caretstart, caretstop )
return true
else
offset = start+1
end
else
self:HighlightFoundWord( nil, -(start-1), -(stop+1) )
return true
end
else
break
end
if (loop == 100) then error("\nInfinite loop protection enabled.\nPlease provide a detailed description of what you were doing when you got this error on www.wiremod.com.\n") return end
end
if (wrap_around) then
self:SetCaret( { #self.Rows,#self.Rows[#self.Rows] } )
self:Find( _str, (looped or 0) + 1 )
end
end
return false
end
function EDITOR:Replace( str, replacewith )
if (str == "" or str == replacewith) then return end
local ignore_case = wire_expression2_editor_find_ignore_case:GetBool()
local use_patterns = wire_expression2_editor_find_use_patterns:GetBool()
local selection = self:GetSelection()
local _str = str
if (!use_patterns) then
str = str:gsub( "[%-%^%$%(%)%%%.%[%]%*%+%?]", "%%%1" )
replacewith = replacewith:gsub( "%%", "%%%1" )
end
if (selection:match( str ) != nil) then
self:SetSelection( selection:gsub( str, replacewith ) )
return self:Find( _str )
else
return self:Find( _str )
end
end
function EDITOR:ReplaceAll( str, replacewith )
if (str == "") then return end
local whole_word_only = wire_expression2_editor_find_whole_word_only:GetBool()
local ignore_case = wire_expression2_editor_find_ignore_case:GetBool()
local use_patterns = wire_expression2_editor_find_use_patterns:GetBool()
if (!use_patterns) then
str = str:gsub( "[%-%^%$%(%)%%%.%[%]%*%+%?]", "%%%1" )
replacewith = replacewith:gsub( "%%", "%%%1" )
end
local txt = self:GetValue()
if ignore_case then
local txt2 = txt -- Store original cased copy
str = str:lower() -- Lowercase everything
txt = txt:lower() -- Lowercase everything
local pattern = "()"..str.."()"
if whole_word_only then pattern = "[^a-zA-Z0-9_]()"..str.."()[^a-zA-Z0-9_]" end
local positions = {}
for startpos, endpos in string_gmatch( txt, pattern ) do
positions[#positions+1] = {startpos,endpos}
end
-- Do the replacing backwards, or it won't work
for i=#positions,1,-1 do
local startpos, endpos = positions[i][1], positions[i][2]
txt2 = string_sub(txt2,1,startpos-1) .. replacewith .. string_sub(txt2,endpos)
end
-- Replace everything with the edited copy
self:SelectAll()
self:SetSelection( txt2 )
else
if (whole_word_only) then
local pattern = "([^a-zA-Z0-9_])"..str.."([^a-zA-Z0-9_])"
txt = " " .. txt
txt = string_gsub( txt, pattern, "%1"..replacewith.."%2" )
txt = string_gsub( txt, pattern, "%1"..replacewith.."%2" )
txt = string_sub( txt, 2 )
else
txt = string_gsub( txt, str, replacewith )
end
self:SelectAll()
self:SetSelection( txt )
end
end
function EDITOR:CountFinds( str )
if (str == "") then return 0 end
local whole_word_only = wire_expression2_editor_find_whole_word_only:GetBool()
local ignore_case = wire_expression2_editor_find_ignore_case:GetBool()
local use_patterns = wire_expression2_editor_find_use_patterns:GetBool()
if (!use_patterns) then
str = str:gsub( "[%-%^%$%(%)%%%.%[%]%*%+%?]", "%%%1" )
end
local txt = self:GetValue()
if (ignore_case) then
txt = txt:lower()
str = str:lower()
end
if (whole_word_only) then
local pattern = "([^a-zA-Z0-9_])"..str.."([^a-zA-Z0-9_])"
txt = " " .. txt
local num1, num2 = 0, 0
txt, num1 = txt:gsub( pattern, "%1%2" )
if (txt == "") then return num1 end
txt, num2 = txt:gsub( pattern, "%1%2" )
return num1+num2
else
local num
txt, num = txt:gsub( str, "" )
return num
end
end
function EDITOR:FindAllWords( str )
if str == "" then return end
local txt = self:GetValue()
-- [^a-zA-Z0-9_] ensures we only find whole words, and the gsub escapes any regex command characters that happen to be in str
local pattern = "[^a-zA-Z0-9_]()" .. str:gsub("[%-%^%$%(%)%%%.%[%]%*%+%?]", "%%%1") .. "()[^a-zA-Z0-9_]"
local ret = {}
for start,stop in txt:gmatch( pattern ) do
ret[#ret+1] = { start, stop }
end
return ret
end
function EDITOR:CreateFindWindow()
self.FindWindow = vgui.Create( "DFrame", self )
local pnl = self.FindWindow
pnl:SetSize( 322, 201 )
pnl:ShowCloseButton( true )
pnl:SetDeleteOnClose( false ) -- No need to create a new window every time
pnl:MakePopup() -- Make it separate from the editor itself
pnl:SetVisible( false ) -- but hide it for now
pnl:SetTitle( "Find" )
pnl:SetScreenLock( true )
local old = pnl.Close
function pnl.Close()
self.ForceDrawCursor = false
old( pnl )
end
-- Center it above the editor
local x,y = self:GetParent():GetPos()
local w,h = self:GetSize()
pnl:SetPos( x+w/2-150, y+h/2-100 )
pnl.TabHolder = vgui.Create( "DPropertySheet", pnl )
pnl.TabHolder:StretchToParent( 1, 23, 1, 1 )
-- Options
local common_panel = vgui.Create( "DPanel", pnl )
common_panel:SetSize( 225, 60 )
common_panel:SetPos( 10, 130 )
common_panel.Paint = function()
local w,h = common_panel:GetSize()
draw_RoundedBox( 4, 0, 0, w, h, Color(0,0,0,150) )
end
local use_patterns = vgui.Create( "DCheckBoxLabel", common_panel )
use_patterns:SetText( "Use Patterns" )
use_patterns:SetToolTip( "Use/Don't use Lua patterns in the find." )
use_patterns:SizeToContents()
use_patterns:SetConVar( "wire_expression2_editor_find_use_patterns" )
use_patterns:SetPos( 4, 4 )
local old = use_patterns.Button.SetValue
use_patterns.Button.SetValue = function( pnl, b )
if (wire_expression2_editor_find_whole_word_only:GetBool()) then return end
old( pnl, b )
end
local case_sens = vgui.Create( "DCheckBoxLabel", common_panel )
case_sens:SetText( "Ignore Case" )
case_sens:SetToolTip( "Ignore/Don't ignore case in the find." )
case_sens:SizeToContents()
case_sens:SetConVar( "wire_expression2_editor_find_ignore_case" )
case_sens:SetPos( 4, 24 )
local whole_word = vgui.Create( "DCheckBoxLabel", common_panel )
whole_word:SetText( "Match Whole Word" )
whole_word:SetToolTip( "Match/Don't match the entire word in the find." )
whole_word:SizeToContents()
whole_word:SetConVar( "wire_expression2_editor_find_whole_word_only" )
whole_word:SetPos( 4, 44 )
local old = whole_word.Button.Toggle
whole_word.Button.Toggle = function( pnl )
old( pnl )
if (pnl:GetValue()) then use_patterns:SetValue( false ) end
end
local wrap_around = vgui.Create( "DCheckBoxLabel", common_panel )
wrap_around:SetText( "Wrap Around" )
wrap_around:SetToolTip( "Start/Don't start from the top after reaching the bottom, or the bottom after reaching the top." )
wrap_around:SizeToContents()
wrap_around:SetConVar( "wire_expression2_editor_find_wrap_around" )
wrap_around:SetPos( 130, 4 )
local dir_down = vgui.Create( "DCheckBoxLabel", common_panel )
local dir_up = vgui.Create( "DCheckBoxLabel", common_panel )
dir_up:SetText( "Up" )
dir_up:SizeToContents()
dir_up:SetPos( 130, 24 )
dir_up:SetTooltip( "Note: Most patterns won't work when searching up because the search function reverses the string to search backwards." )
dir_up:SetValue( !wire_expression2_editor_find_dir:GetBool() )
dir_down:SetText( "Down" )
dir_down:SizeToContents()
dir_down:SetPos( 130, 44 )
dir_down:SetValue( wire_expression2_editor_find_dir:GetBool() )
function dir_up.Button:Toggle()
dir_up:SetValue(true)
dir_down:SetValue(false)
RunConsoleCommand( "wire_expression2_editor_find_dir", "0" )
end
function dir_down.Button:Toggle()
dir_down:SetValue(true)
dir_up:SetValue(false)
RunConsoleCommand( "wire_expression2_editor_find_dir", "1" )
end
-- Find tab
local findtab = vgui.Create( "DPanel" )
-- Label
local FindLabel = vgui.Create( "DLabel", findtab )
FindLabel:SetText( "Find:" )
FindLabel:SetPos( 4, 4 )
FindLabel:SetTextColor( Color(0,0,0,255) )
-- Text entry
local FindEntry = vgui.Create( "DTextEntry", findtab )
FindEntry:SetPos(30,4)
FindEntry:SetSize(200,20)
FindEntry:RequestFocus()
FindEntry.OnEnter = function( pnl )
self:Find( pnl:GetValue() )
pnl:RequestFocus()
end
-- Find next button
local FindNext = vgui.Create( "DButton", findtab )
FindNext:SetText("Find Next")
FindNext:SetToolTip( "Find the next match and highlight it." )
FindNext:SetPos(233,4)
FindNext:SetSize(70,20)
FindNext.DoClick = function(pnl)
self:Find( FindEntry:GetValue() )
end
-- Find button
local Find = vgui.Create( "DButton", findtab )
Find:SetText("Find")
Find:SetToolTip( "Find the next match, highlight it, and close the Find window." )
Find:SetPos(233,29)
Find:SetSize(70,20)
Find.DoClick = function(pnl)
self.FindWindow:Close()
self:Find( FindEntry:GetValue() )
end
-- Count button
local Count = vgui.Create( "DButton", findtab )
Count:SetText( "Count" )
Count:SetPos( 233, 95 )
Count:SetSize( 70, 20 )
Count:SetTooltip( "Count the number of matches in the file." )
Count.DoClick = function(pnl)
Derma_Message( self:CountFinds( FindEntry:GetValue() ) .. " matches found.", "", "Ok" )
end
-- Cancel button
local Cancel = vgui.Create( "DButton", findtab )
Cancel:SetText("Cancel")
Cancel:SetPos(233,120)
Cancel:SetSize(70,20)
Cancel.DoClick = function(pnl)
self.FindWindow:Close()
end
pnl.FindTab = pnl.TabHolder:AddSheet( "Find", findtab, "icon16/page_white_find.png", false, false )
pnl.FindTab.Entry = FindEntry
-- Replace tab
local replacetab = vgui.Create( "DPanel" )
-- Label
local FindLabel = vgui.Create( "DLabel", replacetab )
FindLabel:SetText( "Find:" )
FindLabel:SetPos( 4, 4 )
FindLabel:SetTextColor( Color(0,0,0,255) )
-- Text entry
local FindEntry = vgui.Create( "DTextEntry", replacetab )
local ReplaceEntry
FindEntry:SetPos(30,4)
FindEntry:SetSize(200,20)
FindEntry:RequestFocus()
FindEntry.OnEnter = function( pnl )
self:Replace( pnl:GetValue(), ReplaceEntry:GetValue() )
ReplaceEntry:RequestFocus()
end
-- Label
local ReplaceLabel = vgui.Create( "DLabel", replacetab )
ReplaceLabel:SetText( "Replace With:" )
ReplaceLabel:SetPos( 4, 32 )
ReplaceLabel:SizeToContents()
ReplaceLabel:SetTextColor( Color(0,0,0,255) )
-- Replace entry
ReplaceEntry = vgui.Create( "DTextEntry", replacetab )
ReplaceEntry:SetPos(75,29)
ReplaceEntry:SetSize(155,20)
ReplaceEntry:RequestFocus()
ReplaceEntry.OnEnter = function( pnl )
self:Replace( FindEntry:GetValue(), pnl:GetValue() )
pnl:RequestFocus()
end
-- Find next button
local FindNext = vgui.Create( "DButton", replacetab )
FindNext:SetText("Find Next")
FindNext:SetToolTip( "Find the next match and highlight it." )
FindNext:SetPos(233,4)
FindNext:SetSize(70,20)
FindNext.DoClick = function(pnl)
self:Find( FindEntry:GetValue() )
end
-- Replace next button
local ReplaceNext = vgui.Create( "DButton", replacetab )
ReplaceNext:SetText("Replace")
ReplaceNext:SetToolTip( "Replace the current selection if it matches, else find the next match." )
ReplaceNext:SetPos(233,29)
ReplaceNext:SetSize(70,20)
ReplaceNext.DoClick = function(pnl)
self:Replace( FindEntry:GetValue(), ReplaceEntry:GetValue() )
end
-- Replace all button
local ReplaceAll = vgui.Create( "DButton", replacetab )
ReplaceAll:SetText("Replace All")
ReplaceAll:SetToolTip( "Replace all occurences of the match in the entire file, and close the Find window." )
ReplaceAll:SetPos(233,54)
ReplaceAll:SetSize(70,20)
ReplaceAll.DoClick = function(pnl)
self.FindWindow:Close()
self:ReplaceAll( FindEntry:GetValue(), ReplaceEntry:GetValue() )
end
-- Count button
local Count = vgui.Create( "DButton", replacetab )
Count:SetText( "Count" )
Count:SetPos( 233, 95 )
Count:SetSize( 70, 20 )
Count:SetTooltip( "Count the number of matches in the file." )
Count.DoClick = function(pnl)
Derma_Message( self:CountFinds( FindEntry:GetValue() ) .. " matches found.", "", "Ok" )
end
-- Cancel button
local Cancel = vgui.Create( "DButton", replacetab )
Cancel:SetText("Cancel")
Cancel:SetPos(233,120)
Cancel:SetSize(70,20)
Cancel.DoClick = function(pnl)
self.FindWindow:Close()
end
pnl.ReplaceTab = pnl.TabHolder:AddSheet( "Replace", replacetab, "icon16/page_white_wrench.png", false, false )
pnl.ReplaceTab.Entry = FindEntry
-- Go to line tab
local gototab = vgui.Create( "DPanel" )
-- Label
local GotoLabel = vgui.Create( "DLabel", gototab )
GotoLabel:SetText( "Go to Line:" )
GotoLabel:SetPos( 4, 4 )
GotoLabel:SetTextColor( Color(0,0,0,255) )
-- Text entry
local GoToEntry = vgui.Create( "DTextEntry", gototab )
GoToEntry:SetPos(57,4)
GoToEntry:SetSize(173,20)
GoToEntry:SetText("")
GoToEntry:SetNumeric( true )
-- Goto Button
local Goto = vgui.Create( "DButton", gototab )
Goto:SetText("Go to Line")
Goto:SetPos(233,4)
Goto:SetSize(70,20)
-- Action
local function GoToAction(panel)
local val = tonumber(GoToEntry:GetValue())
if (val) then
val = math_Clamp(val, 1, #self.Rows)
self:SetCaret({val, #self.Rows[val] + 1})
end
GoToEntry:SetText(tostring(val))
self.FindWindow:Close()
end
GoToEntry.OnEnter = GoToAction
Goto.DoClick = GoToAction
pnl.GoToLineTab = pnl.TabHolder:AddSheet( "Go to Line", gototab, "icon16/page_white_go.png", false, false )
pnl.GoToLineTab.Entry = GoToEntry
-- Tab buttons
local old = pnl.FindTab.Tab.OnMousePressed
pnl.FindTab.Tab.OnMousePressed = function( ... )
pnl.FindTab.Entry:SetText( pnl.ReplaceTab.Entry:GetValue() or "" )
local active = pnl.TabHolder:GetActiveTab()
if (active == pnl.GoToLineTab.Tab) then
pnl:SetHeight( 200 )
pnl.TabHolder:StretchToParent( 1, 23, 1, 1 )
end
old( ... )
end
local old = pnl.ReplaceTab.Tab.OnMousePressed
pnl.ReplaceTab.Tab.OnMousePressed = function( ... )
pnl.ReplaceTab.Entry:SetText( pnl.FindTab.Entry:GetValue() or "" )
local active = pnl.TabHolder:GetActiveTab()
if (active == pnl.GoToLineTab.Tab) then
pnl:SetHeight( 200 )
pnl.TabHolder:StretchToParent( 1, 23, 1, 1 )
end
old( ... )
end
local old = pnl.GoToLineTab.Tab.OnMousePressed
pnl.GoToLineTab.Tab.OnMousePressed = function( ... )
pnl:SetHeight( 86 )
pnl.TabHolder:StretchToParent( 1, 23, 1, 1 )
old( ... )
end
end
function EDITOR:OpenFindWindow( mode )
if (!self.FindWindow) then self:CreateFindWindow() end
self.FindWindow:SetVisible( true )
self.FindWindow:MakePopup() -- This will move it above the E2 editor if it is behind it.
self.ForceDrawCursor = true
local selection = self:GetSelection():Left(100)
if (mode == "find") then
if (selection and selection != "") then self.FindWindow.FindTab.Entry:SetText( selection ) end
self.FindWindow.TabHolder:SetActiveTab( self.FindWindow.FindTab.Tab )
self.FindWindow.FindTab.Entry:RequestFocus()
self.FindWindow:SetHeight( 201 )
self.FindWindow.TabHolder:StretchToParent( 1, 23, 1, 1 )
elseif (mode == "find and replace") then
if (selection and selection != "") then self.FindWindow.ReplaceTab.Entry:SetText( selection ) end
self.FindWindow.TabHolder:SetActiveTab( self.FindWindow.ReplaceTab.Tab )
self.FindWindow.ReplaceTab.Entry:RequestFocus()
self.FindWindow:SetHeight( 201 )
self.FindWindow.TabHolder:StretchToParent( 1, 23, 1, 1 )
elseif (mode == "go to line") then
self.FindWindow.TabHolder:SetActiveTab( self.FindWindow.GoToLineTab.Tab )
self.FindWindow.GoToLineTab.Entry:RequestFocus()
self.FindWindow:SetHeight( 83 )
self.FindWindow.TabHolder:StretchToParent( 1, 23, 1, 1 )
end
end
function EDITOR:CanUndo()
return #self.Undo > 0
end
function EDITOR:DoUndo()
if #self.Undo > 0 then
local undo = self.Undo[#self.Undo]
self.Undo[#self.Undo] = nil
self:SetCaret(self:SetArea(undo[1], undo[2], true, false, undo[3], undo[4]))
end
end
function EDITOR:CanRedo()
return #self.Redo > 0
end
function EDITOR:DoRedo()
if #self.Redo > 0 then
local redo = self.Redo[#self.Redo]
self.Redo[#self.Redo] = nil
self:SetCaret(self:SetArea(redo[1], redo[2], false, true, redo[3], redo[4]))
end
end
function EDITOR:SelectAll()
self.Caret = {#self.Rows, #(self.Rows[#self.Rows]) + 1}
self.Start = {1, 1}
self:ScrollCaret()
end
function EDITOR:Indent(shift)
-- TAB with a selection --
-- remember scroll position
local tab_scroll = self:CopyPosition(self.Scroll)
-- normalize selection, so it spans whole lines
local tab_start, tab_caret = self:MakeSelection(self:Selection())
tab_start[2] = 1
if (tab_caret[2] ~= 1) then
tab_caret[1] = tab_caret[1] + 1
tab_caret[2] = 1
end
-- remember selection
self.Caret = self:CopyPosition(tab_caret)
self.Start = self:CopyPosition(tab_start)
-- (temporarily) adjust selection, so there is no empty line at its end.
if (self.Caret[2] == 1) then
self.Caret = self:MovePosition(self.Caret, -1)
end
if shift then
-- shift-TAB with a selection --
local tmp = self:GetSelection():gsub("\n ? ? ? ?", "\n")
-- makes sure that the first line is outdented
self:SetSelection(unindent(tmp))
else
-- plain TAB with a selection --
self:SetSelection(" " .. self:GetSelection():gsub("\n", "\n "))
end
-- restore selection
self.Caret = self:CopyPosition(tab_caret)
self.Start = self:CopyPosition(tab_start)
-- restore scroll position
self.Scroll = self:CopyPosition(tab_scroll)
-- trigger scroll bar update (TODO: find a better way)
self:ScrollCaret()
end
-- Comment the currently selected area
function EDITOR:BlockCommentSelection( removecomment )
if (!self:HasSelection()) then return end
local scroll = self:CopyPosition( self.Scroll )
-- Remember selection
local sel_start, sel_caret = self:MakeSelection( self:Selection() )
if (self:GetParent().E2) then
local str = self:GetSelection()
if (removecomment) then
if (str:find( "^#%[" ) and str:find( "%]#$" )) then
self:SetSelection( str:gsub( "^#%[(.+)%]#$", "%1" ) )
if (sel_caret[1] == sel_start[1]) then
sel_caret[2] = sel_caret[2] - 4
else
sel_caret[2] = sel_caret[2] - 2
end
end
else
self:SetSelection( "#[" .. str .."]#" )
if (sel_caret[1] == sel_start[1]) then
sel_caret[2] = sel_caret[2] + 4
else
sel_caret[2] = sel_caret[2] + 2
end
end
else
local str = self:GetSelection()
if (removecomment) then
if (str:find( "^/%*" ) and str:find( "%*/$" )) then
self:SetSelection( str:gsub( "^/%*(.+)%*/$", "%1" ) )
sel_caret[2] = sel_caret[2] - 2
end
else
self:SetSelection( "/*" .. str .. "*/" )
if (sel_caret[1] == sel_start[1]) then
sel_caret[2] = sel_caret[2] + 4
else
sel_caret[2] = sel_caret[2] + 2
end
end
end
-- restore selection
self.Caret = sel_caret
self.Start = sel_start
-- restore scroll position
self.Scroll = scroll
-- trigger scroll bar update (TODO: find a better way)
self:ScrollCaret()
end
-- CommentSelection
-- Idea by Jeremydeath
-- Rewritten by Divran to use block comment
function EDITOR:CommentSelection( removecomment )
if (!self:HasSelection()) then return end
-- Remember scroll position
local scroll = self:CopyPosition( self.Scroll )
-- Normalize selection, so it spans whole lines
local sel_start, sel_caret = self:MakeSelection( self:Selection() )
sel_start[2] = 1
if (sel_caret[2] != 1) then
sel_caret[1] = sel_caret[1] + 1
sel_caret[2] = 1
end
-- Remember selection
self.Caret = self:CopyPosition( sel_caret )
self.Start = self:CopyPosition( sel_start )
-- (temporarily) adjust selection, so there is no empty line at its end.
if (self.Caret[2] == 1) then
self.Caret = self:MovePosition(self.Caret, -1)
end
if (self:GetParent().E2) then -- For Expression 2
local mode = self:GetParent().BlockCommentStyleConVar:GetInt()
if (mode == 0) then -- New (alt 1)
local str = self:GetSelection()
if (removecomment) then
if (str:find( "^#%[\n" ) and str:find( "\n%]#$" )) then
self:SetSelection( str:gsub( "^#%[\n(.+)\n%]#$", "%1" ) )
sel_caret[1] = sel_caret[1] - 2
end
else
self:SetSelection( "#[\n" .. str .. "\n]#" )
sel_caret[1] = sel_caret[1] + 1
sel_caret[2] = 3
end
elseif (mode == 1) then -- New (alt 2)
local str = self:GetSelection()
if (removecomment) then
if (str:find( "^#%[" ) and str:find( "%]#$" )) then
self:SetSelection( str:gsub( "^#%[(.+)%]#$", "%1" ) )
sel_caret[2] = sel_caret[2] - 4
end
else
self:SetSelection( "#[" .. self:GetSelection() .. "]#" )
end
elseif (mode == 2) then -- Old
local comment_char = "#"
if removecomment then
-- shift-TAB with a selection --
local tmp = string_gsub("\n"..self:GetSelection(), "\n"..comment_char, "\n")
-- makes sure that the first line is outdented
self:SetSelection(tmp:sub(2))
else
-- plain TAB with a selection --
self:SetSelection(comment_char .. self:GetSelection():gsub("\n", "\n"..comment_char))
end
else
ErrorNoHalt( "Invalid block comment style" )
end
else -- For CPU/GPU
local comment_char = "//"
if removecomment then
-- shift-TAB with a selection --
local tmp = string_gsub("\n"..self:GetSelection(), "\n"..comment_char, "\n")
-- makes sure that the first line is outdented
self:SetSelection(tmp:sub(2))
else
-- plain TAB with a selection --
self:SetSelection(comment_char .. self:GetSelection():gsub("\n", "\n"..comment_char))
end
end
-- restore selection
self.Caret = sel_caret
self.Start = sel_start
-- restore scroll position
self.Scroll = scroll
-- trigger scroll bar update (TODO: find a better way)
self:ScrollCaret()
end
function EDITOR:ContextHelp()
local word
if self:HasSelection() then
word = self:GetSelection()
else
local row, col = unpack(self.Caret)
local line = self.Rows[row]
if not line:sub(col, col):match("^[a-zA-Z0-9_]$") then
col = col - 1
end
if not line:sub(col, col):match("^[a-zA-Z0-9_]$") then
surface_PlaySound("buttons/button19.wav")
return
end
-- TODO substitute this for getWordStart, if it fits.
local startcol = col
while startcol > 1 and line:sub(startcol-1, startcol-1):match("^[a-zA-Z0-9_]$") do
startcol = startcol - 1
end
-- TODO substitute this for getWordEnd, if it fits.
local _,endcol = line:find("[^a-zA-Z0-9_]", col)
endcol = (endcol or 0) - 1
word = line:sub(startcol, endcol)
end
E2Helper.Show()
if (self:GetParent().E2) then E2Helper.UseE2(self:GetParent().EditorType) else E2Helper.UseCPU(self:GetParent().EditorType) end
E2Helper.Show(word)
end
function EDITOR:_OnKeyCodeTyped(code)
self.Blink = RealTime()
local alt = input.IsKeyDown(KEY_LALT) or input.IsKeyDown(KEY_RALT)
if alt then return end
local shift = input.IsKeyDown(KEY_LSHIFT) or input.IsKeyDown(KEY_RSHIFT)
local control = input.IsKeyDown(KEY_LCONTROL) or input.IsKeyDown(KEY_RCONTROL)
-- allow ctrl-ins and shift-del (shift-ins, like ctrl-v, is handled by vgui)
if not shift and control and code == KEY_INSERT then
shift,control,code = true,false,KEY_C
elseif shift and not control and code == KEY_DELETE then
shift,control,code = false,true,KEY_X
end
if control then
if code == KEY_A then
self:SelectAll()
elseif code == KEY_Z then
self:DoUndo()
elseif code == KEY_Y then
self:DoRedo()
elseif code == KEY_X then
if self:HasSelection() then
self.clipboard = self:GetSelection()
self.clipboard = string_gsub(self.clipboard, "\n", "\r\n")
SetClipboardText(self.clipboard)
self:SetSelection()
end
elseif code == KEY_C then
if self:HasSelection() then
self.clipboard = self:GetSelection()
self.clipboard = string_gsub(self.clipboard, "\n", "\r\n")
SetClipboardText(self.clipboard)
end
-- pasting is now handled by the textbox that is used to capture input
--[[
elseif code == KEY_V then
if self.clipboard then
self:SetSelection(self.clipboard)
end
]]
elseif code == KEY_F then
self:OpenFindWindow( "find" )
elseif code == KEY_H then
self:OpenFindWindow( "find and replace" )
elseif code == KEY_G then
self:OpenFindWindow( "go to line" )
elseif code == KEY_K then
self:CommentSelection(shift)
elseif code == KEY_Q then
self:GetParent():Close()
elseif code == KEY_T then
self:GetParent():NewTab()
elseif code == KEY_W then
self:GetParent():CloseTab()
elseif code == KEY_PAGEUP then
local parent = self:GetParent()
local currentTab = parent:GetActiveTabIndex() - 1
if currentTab < 1 then currentTab = currentTab + parent:GetNumTabs() end
parent:SetActiveTabIndex(currentTab)
elseif code == KEY_PAGEDOWN then
local parent = self:GetParent()
local currentTab = parent:GetActiveTabIndex() + 1
local numTabs = parent:GetNumTabs()
if currentTab > numTabs then currentTab = currentTab - numTabs end
parent:SetActiveTabIndex(currentTab)
elseif code == KEY_UP then
self.Scroll[1] = self.Scroll[1] - 1
if self.Scroll[1] < 1 then self.Scroll[1] = 1 end
elseif code == KEY_DOWN then
self.Scroll[1] = self.Scroll[1] + 1
elseif code == KEY_LEFT then
if self:HasSelection() and not shift then
self.Start = self:CopyPosition(self.Caret)
else
self.Caret = self:wordLeft(self.Caret)
end
self:ScrollCaret()
if not shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_RIGHT then
if self:HasSelection() and !shift then
self.Start = self:CopyPosition(self.Caret)
else
self.Caret = self:wordRight(self.Caret)
end
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
--[[ -- old code that scrolls on ctrl-left/right:
elseif code == KEY_LEFT then
self.Scroll[2] = self.Scroll[2] - 1
if self.Scroll[2] < 1 then self.Scroll[2] = 1 end
elseif code == KEY_RIGHT then
self.Scroll[2] = self.Scroll[2] + 1
]]
elseif code == KEY_HOME then
self.Caret[1] = 1
self.Caret[2] = 1
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_END then
self.Caret[1] = #self.Rows
self.Caret[2] = 1
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_D then
-- Save current selection
local old_start = self:CopyPosition( self.Start )
local old_end = self:CopyPosition( self.Caret )
local old_scroll = self:CopyPosition( self.Scroll )
local str = self:GetSelection()
if (str != "") then -- If you have a selection
self:SetSelection( str:rep(2) ) -- Repeat it
else -- If you don't
-- Select the current line
self.Start = { self.Start[1], 1 }
self.Caret = { self.Start[1], #self.Rows[self.Start[1]]+1 }
-- Get the text
local str = self:GetSelection()
-- Repeat it
self:SetSelection( str .. "\n" .. str )
end
-- Restore selection
self.Caret = old_end
self.Start = old_start
self.Scroll = old_scroll
self:ScrollCaret()
end
else
if code == KEY_ENTER then
local mode = wire_expression2_autocomplete_controlstyle:GetInt()
if (mode == 4 and self.AC_HasSuggestions and self.AC_Suggestions[1] and self.AC_Panel and self.AC_Panel:IsVisible()) then
if (self:AC_Use( self.AC_Suggestions[1] )) then return end
end
local row = self.Rows[self.Caret[1]]:sub(1,self.Caret[2]-1)
local diff = (row:find("%S") or (row:len()+1))-1
local tabs = string_rep(" ", math_floor(diff / 4))
if GetConVarNumber('wire_expression2_autoindent') ~= 0 and (string_match("{" .. row .. "}", "^%b{}.*$") == nil) then tabs = tabs .. " " end
self:SetSelection("\n" .. tabs)
elseif code == KEY_UP then
if (self.AC_Panel and self.AC_Panel:IsVisible()) then
local mode = wire_expression2_autocomplete_controlstyle:GetInt()
if (mode == 1) then
self.AC_Panel:RequestFocus()
return
end
end
if self.Caret[1] > 1 then
self.Caret[1] = self.Caret[1] - 1
local length = #(self.Rows[self.Caret[1]])
if self.Caret[2] > length + 1 then
self.Caret[2] = length + 1
end
end
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_DOWN then
if (self.AC_Panel and self.AC_Panel:IsVisible()) then
local mode = wire_expression2_autocomplete_controlstyle:GetInt()
if (mode == 1) then
self.AC_Panel:RequestFocus()
return
end
end
if self.Caret[1] < #self.Rows then
self.Caret[1] = self.Caret[1] + 1
local length = #(self.Rows[self.Caret[1]])
if self.Caret[2] > length + 1 then
self.Caret[2] = length + 1
end
end
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_LEFT then
if self:HasSelection() and !shift then
self.Start = self:CopyPosition(self.Caret)
else
self.Caret = self:MovePosition(self.Caret, -1)
end
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_RIGHT then
if self:HasSelection() and !shift then
self.Start = self:CopyPosition(self.Caret)
else
self.Caret = self:MovePosition(self.Caret, 1)
end
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_PAGEUP then
self.Caret[1] = self.Caret[1] - math_ceil(self.Size[1] / 2)
self.Scroll[1] = self.Scroll[1] - math_ceil(self.Size[1] / 2)
if self.Caret[1] < 1 then self.Caret[1] = 1 end
local length = #self.Rows[self.Caret[1]]
if self.Caret[2] > length + 1 then self.Caret[2] = length + 1 end
if self.Scroll[1] < 1 then self.Scroll[1] = 1 end
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_PAGEDOWN then
self.Caret[1] = self.Caret[1] + math_ceil(self.Size[1] / 2)
self.Scroll[1] = self.Scroll[1] + math_ceil(self.Size[1] / 2)
if self.Caret[1] > #self.Rows then self.Caret[1] = #self.Rows end
if self.Caret[1] == #self.Rows then self.Caret[2] = 1 end
local length = #self.Rows[self.Caret[1]]
if self.Caret[2] > length + 1 then self.Caret[2] = length + 1 end
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_HOME then
local row = self.Rows[self.Caret[1]]
local first_char = row:find("%S") or row:len()+1
if self.Caret[2] == first_char then
self.Caret[2] = 1
else
self.Caret[2] = first_char
end
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_END then
local length = #(self.Rows[self.Caret[1]])
self.Caret[2] = length + 1
self:ScrollCaret()
if !shift then
self.Start = self:CopyPosition(self.Caret)
end
elseif code == KEY_BACKSPACE then
if self:HasSelection() then
self:SetSelection()
else
local buffer = self:GetArea({self.Caret, {self.Caret[1], 1}})
if self.Caret[2] % 4 == 1 and #(buffer) > 0 and string_rep(" ", #(buffer)) == buffer then
self:SetCaret(self:SetArea({self.Caret, self:MovePosition(self.Caret, -4)}))
else
self:SetCaret(self:SetArea({self.Caret, self:MovePosition(self.Caret, -1)}))
end
end
elseif code == KEY_DELETE then
if self:HasSelection() then
self:SetSelection()
else
local buffer = self:GetArea({{self.Caret[1], self.Caret[2] + 4}, {self.Caret[1], 1}})
if self.Caret[2] % 4 == 1 and string_rep(" ", #(buffer)) == buffer and #(self.Rows[self.Caret[1]]) >= self.Caret[2] + 4 - 1 then
self:SetCaret(self:SetArea({self.Caret, self:MovePosition(self.Caret, 4)}))
else
self:SetCaret(self:SetArea({self.Caret, self:MovePosition(self.Caret, 1)}))
end
end
elseif code == KEY_F1 then
self:ContextHelp()
end
end
if (code == KEY_TAB and self.AC_Panel and self.AC_Panel:IsVisible()) then
local mode = wire_expression2_autocomplete_controlstyle:GetInt()
if (mode == 0 or mode == 4) then
self.AC_Panel:RequestFocus()
if (mode == 4 and self.AC_Panel.Selected == 0) then self.AC_Panel.Selected = 1 end
return
end
end
if code == KEY_TAB or (control and (code == KEY_I or code == KEY_O)) then
if code == KEY_O then shift = not shift end
if code == KEY_TAB and control then shift = not shift end
if self:HasSelection() then
self:Indent(shift)
else
-- TAB without a selection --
if shift then
local newpos = self.Caret[2]-4
if newpos < 1 then newpos = 1 end
self.Start = { self.Caret[1], newpos }
if self:GetSelection():find("%S") then
-- TODO: what to do if shift-tab is pressed within text?
self.Start = self:CopyPosition(self.Caret)
else
self:SetSelection("")
end
else
local count = (self.Caret[2] + 2) % 4 + 1
self:SetSelection(string_rep(" ", count))
end
end
-- signal that we want our focus back after (since TAB normally switches focus)
if code == KEY_TAB then self.TabFocus = true end
end
if control then
self:OnShortcut(code)
end
self:AC_Check()
end
---------------------------------------------------------------------------------------------------------
-- Auto Completion
-- By Divran
---------------------------------------------------------------------------------------------------------
function EDITOR:IsVarLine()
local line = self.Rows[self.Caret[1]]
local word = line:match( "^@(%w+)" )
return (word == "inputs" or word == "outputs" or word == "persist")
end
function EDITOR:IsDirectiveLine()
local line = self.Rows[self.Caret[1]]
return line:match( "^@" ) != nil
end
function EDITOR:getWordStart(caret,getword)
local line = self.Rows[caret[1]]
for startpos, endpos in line:gmatch( "()[a-zA-Z0-9_]+()" ) do -- "()%w+()"
if (startpos <= caret[2] and endpos >= caret[2]) then
return { caret[1], startpos }, getword and line:sub(startpos,endpos-1) or nil
end
end
return {caret[1],1}
end
function EDITOR:getWordEnd(caret,getword)
local line = self.Rows[caret[1]]
for startpos, endpos in line:gmatch( "()[a-zA-Z0-9_]+()" ) do -- "()%w+()"
if (startpos <= caret[2] and endpos >= caret[2]) then
return { caret[1], endpos }, getword and line:sub(startpos,endpos-1) or nil
end
end
return {caret[1],#line+1}
end
-----------------------------------------------------------
-- GetCurrentWord
-- Gets the word the cursor is currently at, and the symbol in front
-----------------------------------------------------------
function EDITOR:AC_GetCurrentWord()
local startpos, word = self:getWordStart( self.Caret, true )
local symbolinfront = self:GetArea( { { startpos[1], startpos[2] - 1}, startpos } )
return word, symbolinfront
end
-- Thank you http://lua-users.org/lists/lua-l/2009-07/msg00461.html
-- Returns the minimum number of character changes required to make one of the words equal the other
-- Used to sort the suggestions in order of relevance
local function CheckDifference( word1, word2 )
local d, sn, tn = {}, #word1, #word2
local byte, min = string_byte, math_min
for i = 0, sn do d[i * tn] = i end
for j = 0, tn do d[j] = j end
for i = 1, sn do
local si = byte(word1, i)
for j = 1, tn do
d[i*tn+j] = min(d[(i-1)*tn+j]+1, d[i*tn+j-1]+1, d[(i-1)*tn+j-1]+(si == byte(word2,j) and 0 or 1))
end
end
return d[#d]
end
-----------------------------------------------------------
-- NewAutoCompletion
-- Sets the autocompletion table
-----------------------------------------------------------
function EDITOR:AC_NewAutoCompletion( tbl )
self.AC_AutoCompletion = tbl
end
local tbl = {}
-----------------------------------------------------------
-- FindConstants
-- Adds all matching constants to the suggestions table
-----------------------------------------------------------
local function GetTableForConstant( str )
return { nice_str = function( t ) return t.data[1] end,
str = function( t ) return t.data[1] end,
replacement = function( t ) return t.data[1] end,
data = { str } }
end
local function FindConstants( self, word )
local len = #word
local wordu = word:upper()
local count = 0
local suggestions = {}
for name,value in pairs( wire_expression2_constants ) do
if (name:sub(1,len) == wordu) then
count = count + 1
suggestions[count] = GetTableForConstant( name )
end
end
return suggestions
end
tbl[1] = function( self )
local word, symbolinfront = self:AC_GetCurrentWord()
if (word and word != "" and word:sub(1,1) == "_") then
return FindConstants( self, word )
end
end
--------------------
-- FindFunctions
-- Adds all matching functions to the suggestions table
--------------------
local function GetTableForFunction()
return { nice_str = function( t ) return t.data[2] end,
str = function( t ) return t.data[1] end,
replacement = function( t, editor )
local caret = editor:CopyPosition( editor.Caret )
caret[2] = caret[2] - 1
local wordend = editor:getWordEnd( caret )
local has_bracket = editor:GetArea( { wordend, { wordend[1], wordend[2] + 1 } } ) == "(" -- If there already is a bracket, we don't want to add more of them.
local ret = t:str()
return ret..(has_bracket and "" or "()"), #ret+1
end,
others = function( t ) return t.data[3] end,
description = function( t )
if (t.data[4] and E2Helper.Descriptions[t.data[4]]) then
return E2Helper.Descriptions[t.data[4]]
end
if (t.data[1] and E2Helper.Descriptions[t.data[1]]) then
return E2Helper.Descriptions[t.data[1]]
end
end,
data = {} }
end
local function FindFunctions( self, has_colon, word )
-- Filter out magic characters
word = word:gsub( "[%-%^%$%(%)%%%.%[%]%*%+%?]", "%%%1" )
local len = #word
local wordl = word:lower()
local count = 0
local suggested = {}
local suggestions = {}
for func_id,_ in pairs( wire_expression2_funcs ) do
if (wordl == func_id:lower():sub(1,len)) then -- Check if the beginning of the word matches
local name, types = func_id:match( "(.+)(%b())" ) -- Get the function name and types
local first_type, colon, other_types = types:match( "%((%w*)(:?)(.*)%)" ) -- Sort the function types
if (((has_colon and colon == ":") or (!has_colon and colon != ":"))) then -- If they both have colons (or not)
first_type = first_type:upper()
other_types = other_types:upper()
if (!suggested[name]) then -- If it hasn't already been suggested
count = count + 1
suggested[name] = count
-- Add to suggestions
if (colon == ":") then
local t = GetTableForFunction()
t.data = { name, first_type .. ":" .. name .. "(" .. other_types .. ")", {}, func_id }
suggestions[count] = t
else
local t = GetTableForFunction()
t.data = { name, name .. "(" .. first_type .. ")", {}, func_id }
suggestions[count] = t
end
else -- If it has already been suggested
-- Get previous data
local others = suggestions[suggested[name]]:others(self)
local i = #others+1
-- Add it to the end of the list
if (colon == ":") then
local t = GetTableForFunction()
t.data = { name, first_type .. ":" .. name .. "(" .. other_types .. ")", nil, func_id }
others[i] = t
else
local t = GetTableForFunction()
t.data = { name, name .. "(" .. first_type .. ")", nil, func_id }
others[i] = t
end
end
end
end
end
return suggestions
end
tbl[2] = function( self )
local word, symbolinfront = self:AC_GetCurrentWord()
if (word and word != "" and word:sub(1,1):upper() != word:sub(1,1)) then
return FindFunctions( self, (symbolinfront == ":"), word )
end
end
-----------------------------------------------------------
-- SaveVariables
-- Saves all variables to a table
-----------------------------------------------------------
function EDITOR:AC_SaveVariables()
local OK, directives,_ = PreProcessor.Execute( self:GetValue() )
if (!OK or !directives) then
return
end
self.AC_Directives = directives
end
-----------------------------------------------------------
-- FindVariables
-- Adds all matching variables to the suggestions table
-----------------------------------------------------------
local function GetTableForVariables( str )
return { nice_str = function( t ) return t.data[1] end,
str = function( t ) return t.data[1] end,
replacement = function( t ) return t.data[1] end,
data = { str } }
end
local function FindVariables( self, word )
local len = #word
local wordl = word:lower()
local count = 0
local suggested = {}
local suggestions = {}
local directives = self.AC_Directives
if (!directives) then self:AC_SaveVariables() end -- If directives is nil, attempt to find
directives = self.AC_Directives
if (!directives) then -- If finding failed, abort
self:AC_SetVisible( false )
return
end
for k,v in pairs( directives["inputs"][1] ) do
if (v:lower():sub(1,len) == wordl) then
if (!suggested[v]) then
suggested[v] = true
count = count + 1
suggestions[count] = GetTableForVariables( v )
end
end
end
for k,v in pairs( directives["outputs"][1] ) do
if (v:lower():sub(1,len) == wordl) then
if (!suggested[v]) then
suggested[v] = true
count = count + 1
suggestions[count] = GetTableForVariables( v )
end
end
end
for k,v in pairs( directives["persist"][1] ) do
if (v:lower():sub(1,len) == wordl) then
if (!suggested[v]) then
suggested[v] = true
count = count + 1
suggestions[count] = GetTableForVariables( v )
end
end
end
return suggestions
end
tbl[3] = function( self )
local word, symbolinfront = self:AC_GetCurrentWord()
if (word and word != "" and word:sub(1,1):upper() == word:sub(1,1)) then
return FindVariables( self, word )
end
end
local wire_expression2_autocomplete = CreateClientConVar( "wire_expression2_autocomplete", "1", true, false )
tbl.RunOnCheck = function( self )
-- Only autocomplete if it's the E2 editor, if it's enabled
if (!self:GetParent().E2 or !wire_expression2_autocomplete:GetBool()) then
self:AC_SetVisible( false )
return false
end
local caret = self:CopyPosition( self.Caret )
caret[2] = caret[2] - 1
local tokenname = self:GetTokenAtPosition( caret )
if (tokenname and (tokenname == "string" or tokenname == "comment")) then
self:AC_SetVisible( false )
return false
end
if (self:IsVarLine() and !self.AC_WasVarLine) then -- If the user IS editing a var line, and they WEREN'T editing a var line before this..
self.AC_WasVarLine = true
elseif (!self:IsVarLine() and self.AC_WasVarLine) then -- If the user ISN'T editing a var line, and they WERE editing a var line before this..
self.AC_WasVarLine = nil
self:AC_SaveVariables()
end
if (self:IsDirectiveLine()) then -- In case you're wondering, DirectiveLine != VarLine (A directive line is any line starting with @, a var line is @inputs, @outputs, and @persists)
self:AC_SetVisible( false )
return false
end
return true
end
-----------------------------------------------------------
-- Check
-- Runs the autocompletion
-----------------------------------------------------------
function EDITOR:AC_Check( notimer )
if (!notimer) then
timer.Create("E2_AC_Check", 0, 1, function()
if self.AC_Check then self:AC_Check(true) end
end)
return
end
if (!self.AC_AutoCompletion) then self:AC_NewAutoCompletion( tbl ) end -- Default to E2 autocompletion
if (!self.AC_Panel) then self:AC_CreatePanel() end
if (self.AC_AutoCompletion.RunOnCheck) then
local ret = self.AC_AutoCompletion.RunOnCheck( self )
if (ret == false) then
return
end
end
self.AC_Suggestions = {}
self.AC_HasSuggestions = false
local suggestions = {}
for i=1,#self.AC_AutoCompletion do
local _suggestions = self.AC_AutoCompletion[i]( self )
if (_suggestions != nil and #_suggestions > 0) then
suggestions = _suggestions
break
end
end
if (#suggestions > 0) then
local word, _ = self:AC_GetCurrentWord()
table_sort( suggestions, function( a, b )
local diff1 = CheckDifference( word, a.str( a ) )
local diff2 = CheckDifference( word, b.str( b ) )
return diff1 < diff2
end)
if (word == suggestions[1].str( suggestions[1] ) and #suggestions == 1) then -- The word matches the first suggestion exactly, and there are no more suggestions. No need to bother displaying
self:AC_SetVisible( false )
return
end
for i=1,10 do
self.AC_Suggestions[i] = suggestions[i]
end
self.AC_HasSuggestions = true
-- Show the panel
local panel = self.AC_Panel
self:AC_SetVisible( true )
-- Calculate its position
local caret = self:CopyPosition( self.Caret )
caret[2] = caret[2] - 1
local wordstart = self:getWordStart( caret )
local x = self.FontWidth * (wordstart[2] - self.Scroll[2] + 1) + 22
local y = self.FontHeight * (wordstart[1] - self.Scroll[1] + 1) + 2
panel:SetPos( x, y )
-- Fill the list
self:AC_FillList()
return
end
self:AC_SetVisible( false )
end
-----------------------------------------------------------
-- Use
-- Replaces the word
-----------------------------------------------------------
local wire_expression2_autocomplete_highlight_after_use = CreateClientConVar("wire_expression2_autocomplete_highlight_after_use","1",true,false)
function EDITOR:AC_Use( suggestion )
if (!suggestion) then return false end
local ret = false
-- Get word position
local wordstart = self:getWordStart( self.Caret )
local wordend = self:getWordEnd( self.Caret )
-- Get replacement
local replacement, caretoffset = suggestion:replacement( self )
-- Check if anything needs changing
local selection = self:GetArea( { wordstart, wordend } )
if (selection == replacement) then -- There's no point in doing anything.
return false
end
-- Overwrite selection
if (replacement and replacement != "") then
self:SetArea( { wordstart, wordend }, replacement )
-- Move caret
if (caretoffset) then
self.Start = { wordstart[1], wordstart[2] + caretoffset }
self.Caret = { wordstart[1], wordstart[2] + caretoffset }
else
if (wire_expression2_autocomplete_highlight_after_use:GetBool()) then
self.Start = wordstart
self.Caret = {wordstart[1],wordstart[2]+#replacement}
else
self.Start = { wordstart[1],wordstart[2]+#replacement }
self.Caret = { wordstart[1],wordstart[2]+#replacement }
end
end
ret = true
end
self:ScrollCaret()
self:RequestFocus()
self.AC_HasSuggestion = false
return ret
end
-----------------------------------------------------------
-- CreatePanel
-----------------------------------------------------------
function EDITOR:AC_CreatePanel()
-- Create the panel
local panel = vgui.Create( "DPanel",self )
panel:SetSize( 100, 202 )
panel.Selected = {}
panel.Paint = function( pnl )
surface_SetDrawColor( 0,0,0,230 )
surface_DrawRect( 0,0,pnl:GetWide(), pnl:GetTall() )
end
-- Override think, to make it listen for key presses
panel.Think = function( pnl, code )
if (!self.AC_HasSuggestions or !self.AC_Panel_Visible) then return end
local mode = wire_expression2_autocomplete_controlstyle:GetInt()
if (mode == 0) then -- Default style - Tab/CTRL+Tab to choose item;\nEnter/Space to use;\nArrow keys to abort.
if (input.IsKeyDown( KEY_ENTER ) or input.IsKeyDown( KEY_SPACE )) then -- Use
self:AC_SetVisible( false )
self:AC_Use( self.AC_Suggestions[pnl.Selected] )
elseif (input.IsKeyDown( KEY_TAB ) and !pnl.AlreadySelected) then -- Select
if (input.IsKeyDown( KEY_LCONTROL )) then -- If control is held down
pnl.Selected = pnl.Selected - 1 -- Scroll up
if (pnl.Selected < 1) then pnl.Selected = #self.AC_Suggestions end
else -- If control isn't held down
pnl.Selected = pnl.Selected + 1 -- Scroll down
if (pnl.Selected > #self.AC_Suggestions) then pnl.Selected = 1 end
end
self:AC_FillInfoList( self.AC_Suggestions[pnl.Selected] ) -- Fill the info list
pnl:RequestFocus()
pnl.AlreadySelected = true -- To keep it from scrolling a thousand times a second
elseif (pnl.AlreadySelected and !input.IsKeyDown( KEY_TAB )) then
pnl.AlreadySelected = nil
elseif (input.IsKeyDown( KEY_UP ) or input.IsKeyDown( KEY_DOWN ) or input.IsKeyDown( KEY_LEFT ) or input.IsKeyDown( KEY_RIGHT )) then
self:AC_SetVisible( false )
end
elseif (mode == 1) then -- Visual C# Style - Ctrl+Space to use the top match;\nArrow keys to choose item;\nTab/Enter/Space to use;\nCode validation hotkey (ctrl+space) moved to ctrl+b.
if (input.IsKeyDown( KEY_TAB ) or input.IsKeyDown( KEY_ENTER ) or input.IsKeyDown( KEY_SPACE )) then -- Use
self:AC_SetVisible( false )
self:AC_Use( self.AC_Suggestions[pnl.Selected] )
elseif (input.IsKeyDown( KEY_DOWN ) and !pnl.AlreadySelected) then -- Select
pnl.Selected = pnl.Selected + 1 -- Scroll down
if (pnl.Selected > #self.AC_Suggestions) then pnl.Selected = 1 end
self:AC_FillInfoList( self.AC_Suggestions[pnl.Selected] ) -- Fill the info list
pnl.AlreadySelected = true -- To keep it from scrolling a thousand times a second
elseif (input.IsKeyDown( KEY_UP ) and !pnl.AlreadySelected) then -- Select
pnl.Selected = pnl.Selected - 1 -- Scroll up
if (pnl.Selected < 1) then pnl.Selected = #self.AC_Suggestions end
self:AC_FillInfoList( self.AC_Suggestions[pnl.Selected] ) -- Fill the info list
pnl.AlreadySelected = true -- To keep it from scrolling a thousand times a second
elseif (pnl.AlreadySelected and !input.IsKeyDown( KEY_UP ) and !input.IsKeyDown( KEY_DOWN )) then
pnl.AlreadySelected = nil
end
elseif (mode == 2) then -- Scroller style - Mouse scroller to choose item;\nMiddle mouse to use.
if (input.IsMouseDown( MOUSE_MIDDLE )) then
self:AC_SetVisible( false )
self:AC_Use( self.AC_Suggestions[pnl.Selected] )
end
elseif (mode == 3) then -- Scroller Style w/ Enter - Mouse scroller to choose item;\nEnter to use.
if (input.IsKeyDown( KEY_ENTER )) then
self:AC_SetVisible( false )
self:AC_Use( self.AC_Suggestions[pnl.Selected] )
end
elseif (mode == 4) then -- Eclipse Style - Enter to use top match;\nTab to enter auto completion menu;\nArrow keys to choose item;\nEnter to use;\nSpace to abort.
if (input.IsKeyDown( KEY_ENTER )) then -- Use
self:AC_SetVisible( false )
self:AC_Use( self.AC_Suggestions[pnl.Selected] )
elseif (input.IsKeyDown( KEY_SPACE )) then
self:AC_SetVisible( false )
elseif (input.IsKeyDown( KEY_DOWN ) and !pnl.AlreadySelected) then -- Select
pnl.Selected = pnl.Selected + 1 -- Scroll down
if (pnl.Selected > #self.AC_Suggestions) then pnl.Selected = 1 end
self:AC_FillInfoList( self.AC_Suggestions[pnl.Selected] ) -- Fill the info list
pnl.AlreadySelected = true -- To keep it from scrolling a thousand times a second
elseif (input.IsKeyDown( KEY_UP ) and !pnl.AlreadySelected) then -- Select
pnl.Selected = pnl.Selected - 1 -- Scroll up
if (pnl.Selected < 1) then pnl.Selected = #self.AC_Suggestions end
self:AC_FillInfoList( self.AC_Suggestions[pnl.Selected] ) -- Fill the info list
pnl.AlreadySelected = true -- To keep it from scrolling a thousand times a second
elseif (pnl.AlreadySelected and !input.IsKeyDown( KEY_UP ) and !input.IsKeyDown( KEY_DOWN )) then
pnl.AlreadySelected = nil
end
end
end
-- Create list
local list = vgui.Create( "DPanelList", panel )
list:StretchToParent( 1,1,1,1 )
list.Paint = function() end
-- Create info list
local infolist = vgui.Create( "DPanelList", panel )
infolist:SetPos( 1000, 1000 )
infolist:SetSize( 100, 200 )
infolist:EnableVerticalScrollbar( true )
infolist.Paint = function() end
self.AC_Panel = panel
panel.list = list
panel.infolist = infolist
self:AC_SetVisible( false )
end
-----------------------------------------------------------
-- FillInfoList
-- Fills the "additional information" box
-----------------------------------------------------------
local wire_expression2_autocomplete_moreinfo = CreateClientConVar( "wire_expression2_autocomplete_moreinfo", "1", true, false )
local function SimpleWrap( txt, width )
local ret = ""
local prev_end, prev_newline = 0, 0
for cur_end in txt:gmatch( "[^ \n]+()" ) do
local w, _ = surface_GetTextSize( txt:sub( prev_newline, cur_end ) )
if (w > width) then
ret = ret .. txt:sub( prev_newline, prev_end ) .. "\n"
prev_newline = prev_end + 1
end
prev_end = cur_end
end
ret = ret .. txt:sub( prev_newline )
return ret
end
function EDITOR:AC_FillInfoList( suggestion )
local panel = self.AC_Panel
if (!suggestion or !suggestion.description or !wire_expression2_autocomplete_moreinfo:GetBool()) then -- If the suggestion is invalid, the suggestion does not need additional information, or if the user has disabled additional information, abort
panel:SetSize( panel.curw, panel.curh )
panel.infolist:SetPos( 1000, 1000 )
return
end
local infolist = panel.infolist
infolist:Clear()
local desc_label = vgui.Create("DLabel")
infolist:AddItem( desc_label )
local desc = suggestion:description( self )
local maxw = 164
local maxh = 0
local others
if (suggestion.others) then others = suggestion:others( self ) end
if (desc and desc != "") then
desc = "Description:\n" .. desc
end
if (#others > 0) then -- If there are other functions with the same name...
desc = (desc or "") .. ((desc and desc != "") and "\n" or "") .. "Others with the same name:"
-- Loop through the "others" table to add all of them
surface_SetFont( "E2SmallFont" )
for k,v in pairs( others ) do
local nice_name = v:nice_str( self )
local namew, nameh = surface_GetTextSize( nice_name )
local label = vgui.Create("DLabel")
label:SetText( "" )
label.Paint = function( pnl )
local w,h = pnl:GetSize()
draw_RoundedBox( 1,1,1, w-2,h-2, Color( 65,105,225,255 ) )
surface_SetFont( "E2SmallFont" )
surface_SetTextPos( 6, h/2-nameh/2 )
surface_SetTextColor( 255,255,255,255 )
surface_DrawText( nice_name )
end
infolist:AddItem( label )
if (namew + 15 > maxw) then maxw = namew + 15 end
maxh = maxh + 20
end
end
if (!desc or desc == "") then
panel:SetSize( panel.curw, panel.curh )
infolist:SetPos( 1000, 1000 )
return
end
-- Wrap the text, set it, and calculate size
desc = SimpleWrap( desc, maxw )
desc_label:SetText( desc )
desc_label:SizeToContents()
local textw, texth = surface_GetTextSize( desc )
-- If it's bigger than the size of the panel, change it
if (panel.curh < texth + 4) then panel:SetTall( texth + 6 ) else panel:SetTall( panel.curh ) end
if (maxh + texth > panel:GetTall()) then maxw = maxw + 25 end
-- Set other positions/sizes/etc
panel:SetWide( panel.curw + maxw )
infolist:SetPos( panel.curw, 1 )
infolist:SetSize( maxw - 1, panel:GetTall() - 2 )
end
-----------------------------------------------------------
-- FillList
-----------------------------------------------------------
function EDITOR:AC_FillList()
local panel = self.AC_Panel
panel.list:Clear()
panel.Selected = 0
local maxw = 15
surface.SetFont( "E2SmallFont" )
-- Add all suggestions to the list
for count,suggestion in pairs( self.AC_Suggestions ) do
local nice_name = suggestion:nice_str( self )
local name = suggestion:str( self )
local txt = vgui.Create("DLabel")
txt:SetText( "" )
txt.count = count
txt.suggestion = suggestion
-- Override paint to give it the "E2 theme" and to make it highlight when selected
txt.Paint = function( pnl, w, h )
draw_RoundedBox( 1, 1, 1, w-2, h-2, Color( 65, 105, 225, 255 ) )
if (panel.Selected == pnl.count) then
draw_RoundedBox( 0, 2, 2, w - 4 , h - 4, Color(0,0,0,192) )
end
-- I honestly dont have a fucking clue.
-- h2, was being cleaned up instantly for no reason.
surface.SetFont( "E2SmallFont" )
local _, h2 = surface.GetTextSize( nice_name )
surface.SetTextPos( 6, (h / 2) - (h2 / 2) )
surface.SetTextColor( 255,255,255,255 )
surface.DrawText( nice_name )
end
-- Enable mouse presses
txt.OnMousePressed = function( pnl, code )
if (code == MOUSE_LEFT) then
self:AC_SetVisible( false )
self:AC_Use( pnl.suggestion )
end
end
-- Enable mouse hovering
txt.OnCursorEntered = function( pnl )
panel.Selected = pnl.count
self:AC_FillInfoList( pnl.suggestion )
end
panel.list:AddItem( txt )
-- get the width of the widest suggestion
local w,_ = surface_GetTextSize( nice_name )
w = w + 15
if (w > maxw) then maxw = w end
end
-- Size and positions etc
panel:SetSize( maxw, #self.AC_Suggestions * 20 + 2 )
panel.curw = maxw
panel.curh = #self.AC_Suggestions * 20 + 2
panel.list:StretchToParent( 1,1,1,1 )
panel.infolist:SetPos( 1000, 1000 )
end
-----------------------------------------------------------
-- SetVisible
-----------------------------------------------------------
function EDITOR:AC_SetVisible( bool )
if (self.AC_Panel_Visible == bool or !self.AC_Panel) then return end
self.AC_Panel_Visible = bool
self.AC_Panel:SetVisible( bool )
self.AC_Panel.infolist:SetPos( 1000, 1000 )
end
-----------------------------------------------------------
-- Reset
-----------------------------------------------------------
function EDITOR:AC_Reset()
self.AC_HasSuggestions = false
self.AC_Suggestions = false
self.AC_Directives = nil
local panel = self.AC_Panel
if (!panel) then return end
self:AC_SetVisible( false )
panel.list:Clear()
panel.infolist:Clear()
panel:SetSize( 100, 202 )
panel.infolist:SetPos( 1000, 1000 )
panel.infolist:SetSize( 100, 200 )
panel.list:StretchToParent( 1,1,1,1 )
end
---------------------------------------------------------------------------------------------------------
-- CPU/GPU hint box
---------------------------------------------------------------------------------------------------------
local oldpos, haschecked = {0,0}, false
function EDITOR:Think()
if (self:GetParent().E2) then self.Think = nil return end -- E2 doesn't need this
local caret = self:CursorToCaret()
local startpos, word = self:getWordStart( caret, true )
if (word and word != "") then
if !haschecked then
oldpos = {startpos[1],startpos[2]}
haschecked = true
timer.Simple(0.3,function()
if not self then return end
if not self.CursorToCaret then return end
local caret = self:CursorToCaret()
local startpos, word = self:getWordStart( caret, true )
if (startpos[1] == oldpos[1] and startpos[2] == oldpos[2]) then
self.CurrentVarValue = { startpos, word }
end
end)
elseif ((oldpos[1] != startpos[1] or oldpos[2] != startpos[2]) and haschecked) then
haschecked = false
self.CurrentVarValue = nil
oldpos = {0,0}
end
else
self.CurrentVarValue = nil
haschecked = false
oldpos = {0,0}
end
end
---------------------------------------------------------------------------------------------------------
-- helpers for ctrl-left/right
function EDITOR:wordLeft(caret)
local row = self.Rows[caret[1]]
if caret[2] == 1 then
if caret[1] == 1 then return caret end
caret = { caret[1]-1, #self.Rows[caret[1]-1] }
row = self.Rows[caret[1]]
end
local pos = row:sub(1,caret[2]-1):match("[^%w@]()[%w@]+[^%w@]*$")
caret[2] = pos or 1
return caret
end
function EDITOR:wordRight(caret)
local row = self.Rows[caret[1]]
if caret[2] > #row then
if caret[1] == #self.Rows then return caret end
caret = { caret[1]+1, 1 }
row = self.Rows[caret[1]]
if row:sub(1,1) ~= " " then return caret end
end
local pos = row:match("[^%w@]()[%w@]",caret[2])
caret[2] = pos or (#row+1)
return caret
end
function EDITOR:GetTokenAtPosition( caret )
local column = caret[2]
local line = self.PaintRows[caret[1]]
if (line) then
local startindex = 1
for index,data in pairs( line ) do
startindex = startindex+#data[1]
if startindex >= column then return data[3] end
end
end
end
/***************************** Syntax highlighting ****************************/
function EDITOR:ResetTokenizer(row)
self.line = self.Rows[row]
self.position = 0
self.character = ""
self.tokendata = ""
if self:GetParent().E2 then
if row == self.Scroll[1] then
-- This code checks if the visible code is inside a string or a block comment
self.blockcomment = nil
self.multilinestring = nil
local singlelinecomment = false
local str = string_gsub( table_concat( self.Rows, "\n", 1, self.Scroll[1]-1 ), "\r", "" )
for before, char, after in string_gmatch( str, '()([#"\n])()' ) do
local before = string_sub( str, before-1, before-1 )
local after = string_sub( str, after, after )
if not self.blockcomment and not self.multilinestring and not singlelinecomment then
if char == '"' then
self.multilinestring = true
elseif char == "#" and after == "[" then
self.blockcomment = true
elseif char == "#" then
singlelinecomment = true
end
elseif self.multilinestring and char == '"' and before ~= "\\" then
self.multilinestring = nil
elseif self.blockcomment and char == "#" and before == "]" then
self.blockcomment = nil
elseif singlelinecomment and char == "\n" then
singlelinecomment = false
end
end
end
for k,v in pairs( self.e2fs_functions ) do
if v == row then
self.e2fs_functions[k] = nil
end
end
end
end
function EDITOR:NextCharacter()
if not self.character then return end
self.tokendata = self.tokendata .. self.character
self.position = self.position + 1
if self.position <= self.line:len() then
self.character = self.line:sub(self.position, self.position)
else
self.character = nil
end
end
function EDITOR:SkipPattern(pattern)
-- TODO: share code with NextPattern
if !self.character then return nil end
local startpos,endpos,text = self.line:find(pattern, self.position)
if startpos ~= self.position then return nil end
local buf = self.line:sub(startpos, endpos)
if not text then text = buf end
--self.tokendata = self.tokendata .. text
self.position = endpos + 1
if self.position <= #self.line then
self.character = self.line:sub(self.position, self.position)
else
self.character = nil
end
return text
end
function EDITOR:NextPattern(pattern)
if !self.character then return false end
local startpos,endpos,text = self.line:find(pattern, self.position)
if startpos ~= self.position then return false end
local buf = self.line:sub(startpos, endpos)
if not text then text = buf end
self.tokendata = self.tokendata .. text
self.position = endpos + 1
if self.position <= #self.line then
self.character = self.line:sub(self.position, self.position)
else
self.character = nil
end
return true
end
do -- E2 Syntax highlighting
local function istype(tp)
return wire_expression_types[tp:upper()] or tp == "number"
end
-- keywords[name][nextchar!="("]
local keywords = {
-- keywords that can be followed by a "(":
["if"] = { [true] = true, [false] = true },
["elseif"] = { [true] = true, [false] = true },
["while"] = { [true] = true, [false] = true },
["for"] = { [true] = true, [false] = true },
["foreach"] = { [true] = true, [false] = true },
["switch"] = { [true] = true, [false] = true },
["case"] = { [true] = true, [false] = true },
["default"] = { [true] = true, [false] = true },
-- keywords that cannot be followed by a "(":
["else"] = { [true] = true },
["break"] = { [true] = true },
["continue"] = { [true] = true },
//["function"] = { [true] = true },
["return"] = { [true] = true },
["local"] = { [true] = true },
}
-- fallback for nonexistant entries:
setmetatable(keywords, { __index=function(tbl,index) return {} end })
local directives = {
["@name"] = 0, -- all yellow
["@model"] = 0,
["@inputs"] = 1, -- directive yellow, types orange, rest normal
["@outputs"] = 1,
["@persist"] = 1,
["@trigger"] = 2, -- like 1, except that all/none are yellow
["@autoupdate"] = 0,
}
local colors = {
["directive"] = { Color(240, 240, 160), false}, -- yellow
["number"] = { Color(240, 160, 160), false}, -- light red
["function"] = { Color(160, 160, 240), false}, -- blue
["notfound"] = { Color(240, 96, 96), false}, -- dark red
["variable"] = { Color(160, 240, 160), false}, -- light green
["string"] = { Color(128, 128, 128), false}, -- grey
["keyword"] = { Color(160, 240, 240), false}, -- turquoise
["operator"] = { Color(224, 224, 224), false}, -- white
["comment"] = { Color(128, 128, 128), false}, -- grey
["ppcommand"] = { Color(240, 96, 240), false}, -- purple
["typename"] = { Color(240, 160, 96), false}, -- orange
["constant"] = { Color(240, 160, 240), false}, -- pink
["userfunction"] = { Color(102, 122, 102), false}, -- dark grayish-green
["dblclickhighlight"] = { Color(0, 100, 0), false}, -- dark green
}
function EDITOR:GetSyntaxColor(name)
return colors[name][1]
end
function EDITOR:SetSyntaxColors( col )
for k,v in pairs( col ) do
if (colors[k]) then
colors[k][1] = v
end
end
end
function EDITOR:SetSyntaxColor( colorname, colr )
if (!colors[colorname]) then return end
colors[colorname][1] = colr
end
-- cols[n] = { tokendata, color }
local cols = {}
local lastcol
local function addToken(tokenname, tokendata)
local color = colors[tokenname]
if lastcol and color == lastcol[2] then
lastcol[1] = lastcol[1] .. tokendata
else
cols[#cols + 1] = { tokendata, color, tokenname }
lastcol = cols[#cols]
end
end
function EDITOR:SyntaxColorLine(row)
cols,lastcol = {}, nil
self:ResetTokenizer(row)
self:NextCharacter()
-- 0=name 1=port 2=trigger 3=foreach
local highlightmode = nil
if self.blockcomment then
if self:NextPattern(".-]#") then
self.blockcomment = nil
else
self:NextPattern(".*")
end
addToken("comment", self.tokendata)
elseif self.multilinestring then
while self.character do -- Find the ending "
if (self.character == '"') then
self.multilinestring = nil
self:NextCharacter()
break
end
if (self.character == "\\") then self:NextCharacter() end
self:NextCharacter()
end
addToken("string", self.tokendata)
elseif self:NextPattern("^@[^ ]*") then
highlightmode = directives[self.tokendata]
-- check for unknown directives
if not highlightmode then
return {
{ "@", colors.directive },
{ self.line:sub(2), colors.notfound }
}
end
-- check for plain text directives
if highlightmode == 0 then return {{ self.line, colors.directive }} end
-- parse the rest like regular code
cols = {{ self.tokendata, colors.directive }}
end
local found = self:SkipPattern( "( *function)" )
if found then
addToken( "keyword", found ) -- Add "function"
self.tokendata = "" -- Reset tokendata
local spaces = self:SkipPattern( " *" )
if spaces then addToken( "comment", spaces ) end
if self:NextPattern( "[a-z][a-zA-Z0-9]*%s%s*[a-z][a-zA-Z0-9]*:[a-z][a-zA-Z0-9_]*" ) then -- Everything specified (returntype typeindex:funcname)
local returntype, spaces, typeindex, funcname = self.tokendata:match( "([a-z][a-zA-Z0-9]*)(%s%s*)([a-z][a-zA-Z0-9]*):([a-z][a-zA-Z0-9_]*)" )
if istype( returntype ) or returntype == "void" then
addToken( "typename", returntype )
else
addToken( "notfound", returntype )
end
addToken( "comment", spaces )
if istype( typeindex ) then
addToken( "typename", typeindex )
else
addToken( "notfound", typeindex )
end
addToken( "operator", ":" )
addToken( "userfunction", funcname )
if not wire_expression2_funclist[funcname] then
self.e2fs_functions[funcname] = row
end
self.tokendata = ""
elseif self:NextPattern( "[a-z][a-zA-Z0-9]*%s%s*[a-z][a-zA-Z0-9_]*" ) then -- returntype funcname
local returntype, spaces, funcname = self.tokendata:match( "([a-z][a-zA-Z0-9]*)(%s%s*)([a-z][a-zA-Z0-9_]*)" )
if istype( returntype ) or returntype == "void" then
addToken( "typename", returntype )
else
addToken( "notfound", returntype )
end
addToken( "comment", spaces )
if istype( funcname ) then -- Hey... this isn't a function name! :O
addToken( "typename", funcname )
else
addToken( "userfunction", funcname )
end
if not wire_expression2_funclist[funcname] then
self.e2fs_functions[funcname] = row
end
self.tokendata = ""
elseif self:NextPattern( "[a-z][a-zA-Z0-9]*:[a-z][a-zA-Z0-9_]*" ) then -- typeindex:funcname
local typeindex, funcname = self.tokendata:match( "([a-z][a-zA-Z0-9]*):([a-z][a-zA-Z0-9_]*)" )
if istype( typeindex ) then
addToken( "typename", typeindex )
else
addToken( "notfound", typeindex )
end
addToken( "operator", ":" )
addToken( "userfunction", funcname )
if not wire_expression2_funclist[funcname] then
self.e2fs_functions[funcname] = row
end
self.tokendata = ""
elseif self:NextPattern( "[a-z][a-zA-Z0-9_]*" ) then -- funcname
local funcname = self.tokendata:match( "[a-z][a-zA-Z0-9_]*" )
if istype( funcname ) or funcname == "void" then -- Hey... this isn't a function name! :O
addToken( "typename", funcname )
else
addToken( "userfunction", funcname )
if not wire_expression2_funclist[funcname] then
self.e2fs_functions[funcname] = row
end
end
self.tokendata = ""
end
if self:NextPattern( "%(" ) then -- We found a bracket
-- Color the bracket
addToken( "operator", self.tokendata )
while self.character and self.character ~= ")" do -- Loop until the ending bracket
self.tokendata = ""
local spaces = self:SkipPattern( " *" )
if spaces then addToken( "comment", spaces ) end
if self:NextPattern( "%[" ) then -- Found a [
-- Color the bracket
addToken( "operator", self.tokendata )
self.tokendata = ""
while self:NextPattern( "[A-Z][a-zA-Z0-9_]*" ) do -- If we found a variable
addToken( "variable", self.tokendata )
self.tokendata = ""
local spaces = self:SkipPattern( " *" )
if spaces then addToken( "comment", spaces ) end
end
if self:NextPattern( "%]" ) then
addToken( "operator", "]" )
self.tokendata = ""
end
elseif self:NextPattern( "[A-Z][a-zA-Z0-9_]*" ) then -- If we found a variable
-- Color the variable
addToken( "variable", self.tokendata )
self.tokendata = ""
end
if self:NextPattern( ":" ) then -- Check for the colon
addToken( "operator", ":" )
self.tokendata = ""
end
-- Find the type
if self:NextPattern( "[a-z][a-zA-Z0-9_]*" ) then
if istype( self.tokendata ) or self.tokendata == "void" then -- If it's a type
addToken( "typename", self.tokendata )
else -- aww
addToken( "notfound", self.tokendata )
end
else
abort = true
break
end
local spaces = self:SkipPattern( " *" )
if spaces then addToken( "comment", spaces ) end
-- If we found a comma, skip it
if self.character == "," then addToken( "operator", "," ) self:NextCharacter() end
end
end
self.tokendata = ""
if self:NextPattern( "%) *{?" ) then -- check for ending bracket (and perhaps an ending {?)
addToken( "operator", self.tokendata )
end
end
while self.character do
local tokenname = ""
self.tokendata = ""
-- eat all spaces
local spaces = self:SkipPattern(" *")
if spaces then addToken("operator", spaces) end
if !self.character then break end
-- eat next token
if self:NextPattern("^_[A-Z][A-Z_0-9]*") then
local word = self.tokendata
for k,_ in pairs( wire_expression2_constants ) do
if (k == word) then
tokenname = "constant"
end
end
if (tokenname == "") then tokenname = "notfound" end
elseif self:NextPattern("^0[xb][0-9A-F]+") then
tokenname = "number"
elseif self:NextPattern("^[0-9][0-9.e]*") then
tokenname = "number"
elseif self:NextPattern("^[a-z][a-zA-Z0-9_]*") then
local sstr = self.tokendata
if highlightmode then
if highlightmode == 1 and istype(sstr) then
tokenname = "typename"
elseif highlightmode == 2 and (sstr == "all" or sstr == "none") then
tokenname = "directive"
elseif highlightmode == 3 and istype(sstr) then
tokenname = "typename"
highlightmode = nil
else
tokenname = "notfound"
end
else
-- is this a keyword or a function?
local char = self.character or ""
local keyword = char != "("
local spaces = self:SkipPattern(" *") or ""
if self.character == "]" then
-- X[Y,typename]
tokenname = istype(sstr) and "typename" or "notfound"
elseif keywords[sstr][keyword] then
tokenname = "keyword"
if sstr == "foreach" then highlightmode = 3
elseif sstr == "return" and self:NextPattern( "void" ) then
addToken( "keyword", "return" )
tokenname = "typename"
self.tokendata = spaces .. "void"
spaces = ""
end
elseif wire_expression2_funclist[sstr] then
tokenname = "function"
elseif self.e2fs_functions[sstr] then
tokenname = "userfunction"
else
tokenname = "notfound"
local correctName = wire_expression2_funclist_lowercase[sstr:lower()]
if correctName then
self.tokendata = ""
for i = 1,#sstr do
local c = sstr:sub(i,i)
if correctName:sub(i,i) == c then
tokenname = "function"
else
tokenname = "notfound"
end
if i == #sstr then
self.tokendata = c
else
addToken(tokenname, c)
end
end
end
end
addToken(tokenname, self.tokendata)
tokenname = "operator"
self.tokendata = spaces
end
elseif self:NextPattern("^[A-Z][a-zA-Z0-9_]*") then
tokenname = "variable"
elseif self.character == '"' then
self:NextCharacter()
while self.character do -- Find the ending "
if (self.character == '"') then
tokenname = "string"
break
end
if (self.character == "\\") then self:NextCharacter() end
self:NextCharacter()
end
if (tokenname == "") then -- If no ending " was found...
self.multilinestring = true
tokenname = "string"
else
self:NextCharacter()
end
elseif self.character == "#" then
self:NextCharacter()
if (self.character == "[") then -- Check if there is a [ directly after the #
while self.character do -- Find the ending ]
if (self.character == "]") then
self:NextCharacter()
if (self.character == "#") then -- Check if there is a # directly after the ending ]
tokenname = "comment"
break
end
end
if self.character == "\\" then self:NextCharacter() end
self:NextCharacter()
end
if (tokenname == "") then -- If no ending ]# was found...
self.blockcomment = true
tokenname = "comment"
else
self:NextCharacter()
end
end
if (tokenname == "") then
self:NextPattern("[^ ]*") -- Find the whole word
if PreProcessor["PP_"..self.tokendata:sub(2)] then
-- there is a preprocessor command by that name => mark as such
tokenname = "ppcommand"
elseif self.tokendata == "#include" then
tokenname = "keyword"
else
-- eat the rest and mark as a comment
self:NextPattern(".*")
tokenname = "comment"
end
end
else
self:NextCharacter()
tokenname = "operator"
end
addToken(tokenname, self.tokendata)
end
return cols
end -- EDITOR:SyntaxColorLine
end -- do...
do
local colors = {
["normal"] = { Color(255, 255, 136), false},
["opcode"] = { Color(255, 136, 0), false},
["comment"] = { Color(128, 128, 128), false},
["register"] = { Color(255, 255, 136), false},
["number"] = { Color(232, 232, 0), false},
["string"] = { Color(255, 136, 136), false},
["filename"] = { Color(232, 232, 232), false},
["label"] = { Color(255, 255, 176), false},
["keyword"] = { Color(255, 136, 0), false},
["memref"] = { Color(232, 232, 0), false},
["pmacro"] = { Color(136, 136, 255), false},
-- ["compare"] = { Color(255, 186, 40), true},
}
-- Build lookup table for opcodes
local opcodeTable = {}
for k,v in pairs(CPULib.InstructionTable) do
if v.Mnemonic ~= "RESERVED" then
opcodeTable[v.Mnemonic] = true
end
end
-- Build lookup table for keywords
local keywordsList = {
"GOTO","FOR","IF","ELSE","WHILE","DO","SWITCH","CASE","CONST","RETURN","BREAK",
"CONTINUE","EXPORT","INLINE","FORWARD","REGISTER","DB","ALLOC","SCALAR","VECTOR1F",
"VECTOR2F","UV","VECTOR3F","VECTOR4F","COLOR","VEC1F","VEC2F","VEC3F","VEC4F","MATRIX",
"STRING","DB","DEFINE","CODE","DATA","ORG","OFFSET","INT48","FLOAT","CHAR","VOID",
"INT","FLOAT","CHAR","VOID","PRESERVE","ZAP"
}
local keywordsTable = {}
for k,v in pairs(keywordsList) do
keywordsTable[v] = true
end
-- Build lookup table for registers
local registersTable = {
EAX = true,EBX = true,ECX = true,EDX = true,ESI = true,EDI = true,
ESP = true,EBP = true,CS = true,SS = true,DS = true,ES = true,GS = true,
FS = true,KS = true,LS = true
}
for reg=0,31 do registersTable["R"..reg] = true end
for port=0,1023 do registersTable["PORT"..port] = true end
-- Build lookup table for macros
local macroTable = {
["PRAGMA"] = true,
["INCLUDE"] = true,
["#INCLUDE##"] = true,
["DEFINE"] = true,
["IFDEF"] = true,
["IFNDEF"] = true,
["ENDIF"] = true,
["ELSE"] = true,
["UNDEF"] = true,
}
function EDITOR:CPUGPUSyntaxColorLine(row)
local cols = {}
self:ResetTokenizer(row)
self:NextCharacter()
local isGpu = self:GetParent().EditorType == "GPU"
while self.character do
local tokenname = ""
self.tokendata = ""
self:NextPattern(" *")
if !self.character then break end
if self:NextPattern("^[0-9][0-9.]*") then
tokenname = "number"
elseif self:NextPattern("^[a-zA-Z0-9_@.]+:") then
tokenname = "label"
elseif self:NextPattern("^[a-zA-Z0-9_]+") then
local sstr = string.upper(self.tokendata:Trim())
if opcodeTable[sstr] then
tokenname = "opcode"
elseif registersTable[sstr] then
tokenname = "register"
elseif keywordsTable[sstr] then
tokenname = "keyword"
else
tokenname = "normal"
end
elseif (self.character == "'") or (self.character == "\"") then
self:NextCharacter()
while self.character and (self.character != "'") and (self.character != "\"") do
if self.character == "\\" then self:NextCharacter() end
self:NextCharacter()
end
self:NextCharacter()
tokenname = "string"
elseif self:NextPattern("#include <") then --(self.character == "<")
while self.character and (self.character != ">") do
self:NextCharacter()
end
self:NextCharacter()
tokenname = "filename"
elseif self:NextPattern("^//.*$") then
tokenname = "comment"
elseif (self.character == "#") then
self:NextCharacter()
if self:NextPattern("^[a-zA-Z0-9_#]+") then
local sstr = string.sub(string.upper(self.tokendata:Trim()),2)
if macroTable[sstr] then
tokenname = "pmacro"
else
tokenname = "memref"
end
else
tokenname = "memref"
end
elseif (self.character == "[") or (self.character == "]") then
self:NextCharacter()
tokenname = "memref"
else
self:NextCharacter()
tokenname = "normal"
end
color = colors[tokenname]
if #cols > 1 and color == cols[#cols][2] then
cols[#cols][1] = cols[#cols][1] .. self.tokendata
else
cols[#cols + 1] = {self.tokendata, color}
end
end
return cols
end -- EDITOR:SyntaxColorLine
end -- do...
-- register editor panel
vgui.Register("Expression2Editor", EDITOR, "Panel");
concommand.Add("wire_expression2_reloadeditor", function(ply, command, args)
local code = wire_expression2_editor and wire_expression2_editor:GetCode()
wire_expression2_editor = nil
ZCPU_Editor = nil
ZGPU_Editor = nil
include("wire/client/TextEditor.lua")
include("wire/client/wire_expression2_editor.lua")
initE2Editor()
if code then wire_expression2_editor:SetCode(code) end
end)
| apache-2.0 |
n0xus/darkstar | scripts/zones/Port_San_dOria/npcs/Anton.lua | 17 | 1776 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Anton
-- @zone 232
-- @pos -19 -8 27
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
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)
if (player:hasKeyItem(AIRSHIP_PASS) == false) then
player:startEvent(0x0205);
elseif (player:getGil() < 200) then
player:startEvent(0x02cc);
else
player:startEvent(0x025c);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x025c) then
X = player:getXPos();
if (X >= -13 and X <= -8) then
player:delGil(200);
end
end
end;
| gpl-3.0 |
mahdidoraj/secretbot | plugins/anti_chat.lua | 62 | 1069 |
antichat = {}-- An empty table for solving multiple kicking problem
do
local function run(msg, matches)
if is_momod(msg) then -- Ignore mods,owner,admins
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_chat'] then
if data[tostring(msg.to.id)]['settings']['lock_chat'] == 'yes' then
if antichat[msg.from.id] == true then
return
end
send_large_msg("chat#id".. msg.to.id , "chat is not allowed here")
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (chat was locked) ")
chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false)
antichat[msg.from.id] = true
return
end
end
return
end
local function cron()
antichat = {} -- Clear antichat table
end
return {
patterns = {
"([\216-\219][\128-\191])"
},
run = run,
cron = cron
}
end
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
Python1320/wire | lua/wire/stools/clutch.lua | 9 | 10091 | WireToolSetup.setCategory( "Physics" )
WireToolSetup.open( "clutch", "Clutch", "gmod_wire_clutch", nil, "Clutchs" )
if CLIENT then
language.Add( "Tool.wire_clutch.name", "Clutch Tool (Wire)" )
language.Add( "Tool.wire_clutch.desc", "Control rotational friction between props" )
language.Add( "Tool.wire_clutch.0", "Primary: Place/Select a clutch controller\nSecondary: Select an entity to apply the clutch to\nReload: Remove clutch from entity/deselect controller" )
language.Add( "Tool.wire_clutch.1", "Right click on the second entity you want the clutch to apply to" )
language.Add( "undone_wireclutch", "Undone Wire Clutch" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 8 )
if SERVER then
CreateConVar( "wire_clutch_maxlinks", 10 ) -- how many constraints can be added per controller
CreateConVar( "wire_clutch_maxrate", 40 ) -- how many constraints/sec may be changed per controller
end
TOOL.ClientConVar[ "model" ] = "models/jaanus/wiretool/wiretool_siren.mdl"
cleanup.Register( "wire_clutch" )
/*---------------------------------------------------------
-- Server Usermessages --
Send entity tables for the DrawHUD display
---------------------------------------------------------*/
local Send_Links
if SERVER then
// Send info: constraints associated with the selected clutch controller
Send_Links = function( ply, constrained_pairs )
umsg.Start( "wire_clutch_links", ply )
local num_constraints = #constrained_pairs
umsg.Short( num_constraints )
for k, v in pairs( constrained_pairs ) do
umsg.Entity( v.Ent1 )
umsg.Entity( v.Ent2 )
end
umsg.End()
end
end
/*---------------------------------------------------------
-- Client Usermessages --
Receive entity tables for the DrawHUD display
---------------------------------------------------------*/
if CLIENT then
local Linked_Ents = {} -- Table of constrained ents, with Ent1 as k and Ent2 as v
local Unique_Ents = {} -- Table of entities as keys
// Receive stage 0 info
local function Receive_links( um )
table.Empty( Linked_Ents )
local num_constraints = um:ReadShort() or 0
if num_constraints ~= 0 then
for i = 1, num_constraints do
local Ent1 = um:ReadEntity()
local Ent2 = um:ReadEntity()
table.insert( Linked_Ents, {Ent1 = Ent1, Ent2 = Ent2} )
Unique_Ents[Ent1] = true
Unique_Ents[Ent2] = true
end
end
end
usermessage.Hook( "wire_clutch_links", Receive_links )
/*---------------------------------------------------------
-- DrawHUD --
Display clutch constraints associated with a controller
---------------------------------------------------------*/
local function InView( pos2D )
if pos2D.x > 0 and pos2D.y > 0 and pos2D.x < ScrW() and pos2D.y < ScrH() then
return true
end
return false
end
// Client function for drawing a line to represent constraint to world
local function DrawBaseLine( pos, viewpos )
local dist = math.Clamp( viewpos:Distance( pos ), 50, 5000 )
local linelength = 3000 / dist
local pos2D = pos:ToScreen()
local pos1 = { x = pos2D.x + linelength, y = pos2D.y }
local pos2 = { x = pos2D.x - linelength, y = pos2D.y }
surface.DrawLine( pos1.x, pos1.y, pos2.x, pos2.y )
end
// Client function for drawing a circle around the currently selected controller
local function DrawSelectCircle( pos, viewpos )
local pos2D = pos:ToScreen()
if InView( pos2D ) then
surface.DrawCircle( pos2D.x, pos2D.y, 7, Color(255, 100, 100, 255 ) )
end
end
function TOOL:DrawHUD()
local DrawnEnts = {} -- Used to keep track of which ents already have a circle
local controller = self:GetWeapon():GetNetworkedEntity( "WireClutchController" )
if !IsValid( controller ) then return end
// Draw circle around the controller
local viewpos = LocalPlayer():GetViewModel():GetPos()
local controllerpos = controller:LocalToWorld( controller:OBBCenter() )
DrawSelectCircle( controllerpos, viewpos )
local numconstraints_0 = #Linked_Ents
if numconstraints_0 ~= 0 then
// Draw lines between each pair of constrained ents
surface.SetDrawColor( 100, 255, 100, 255 )
// Check whether each entity/position can be drawn
for k, v in pairs( Linked_Ents ) do
local basepos
local pos1, pos2
local IsValid1 = IsValid( v.Ent1 )
local IsValid2 = IsValid( v.Ent2 )
if IsValid1 then pos1 = v.Ent1:GetPos():ToScreen() end
if IsValid2 then pos2 = v.Ent2:GetPos():ToScreen() end
if !IsValid1 and !IsValid2 then
table.remove( Linked_Ents, k )
elseif v.Ent1:IsWorld() then
basepos = v.Ent2:GetPos() + Vector(0, 0, -30)
pos1 = basepos:ToScreen()
elseif v.Ent2:IsWorld() then
basepos = v.Ent1:GetPos() + Vector(0, 0, -30)
pos2 = basepos:ToScreen()
end
if pos1 and pos2 then
if InView( pos1 ) and InView( pos2 ) then
surface.DrawLine( pos1.x, pos1.y, pos2.x, pos2.y )
if !DrawnEnts[v.Ent1] and IsValid1 then
surface.DrawCircle( pos1.x, pos1.y, 5, Color(100, 255, 100, 255 ) )
DrawnEnts[v.Ent1] = true
end
if !DrawnEnts[v.Ent2] and IsValid2 then
surface.DrawCircle( pos2.x, pos2.y, 5, Color(100, 255, 100, 255 ) )
DrawnEnts[v.Ent2] = true
end
if basepos then
DrawBaseLine( basepos, viewpos )
end
end
end
end
end
end
end
if SERVER then
function TOOL:SelectController( controller )
self.controller = controller
self:GetWeapon():SetNetworkedEntity( "WireClutchController", controller or Entity(0) ) -- Must use null entity since nil won't send
// Send constraint from the controller to the client
local constrained_pairs = {}
if IsValid( controller ) then
constrained_pairs = controller:GetConstrainedPairs()
end
Send_Links( self:GetOwner(), constrained_pairs )
end
function TOOL:PostMake(ent)
self:SelectController(ent)
end
function TOOL:LeftClick_Update( trace )
self:PostMake(trace.Entity)
end
end
/*---------------------------------------------------------
-- Right click --
Associates ents with the currently selected controller
---------------------------------------------------------*/
function TOOL:RightClick( trace )
if CLIENT then return true end
local ply = self:GetOwner()
local stage = self:NumObjects()
if !IsValid( self.controller ) then
ply:PrintMessage( HUD_PRINTTALK, "Select a clutch controller with left click first" )
return
end
if ( !IsValid( trace.Entity ) and !trace.Entity:IsWorld() ) or trace.Entity:IsPlayer() then return end
// First click: select the first entity
if stage == 0 then
if trace.Entity:IsWorld() then
ply:PrintMessage( HUD_PRINTTALK, "Select a valid entity" )
return
end
// Check that we won't be going over the max number of links allowed
local maxlinks = GetConVarNumber( "wire_clutch_maxlinks", 10 )
if table.Count( self.controller.clutch_ballsockets ) >= maxlinks then
ply:PrintMessage( HUD_PRINTTALK, "A maximum of " .. tostring( maxlinks ) .. " links are allowed per clutch controller" )
return
end
// Store this entity for use later
local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone )
self:SetObject( 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal )
self:SetStage(1)
// Second click: select the second entity, and update the controller
else
local Ent1, Ent2 = self:GetEnt(1), trace.Entity
if Ent1 == Ent2 then
ply:PrintMessage( HUD_PRINTTALK, "Select a different entity" )
return false
end
// Check that these ents aren't already registered on this controller
if self.controller:ClutchExists( Ent1, Ent2 ) then
ply:PrintMessage( HUD_PRINTTALK, "Entities have already been registered to this controller!" )
return true
end
// Add this constraint to the clutch controller
self.controller:AddClutch( Ent1, Ent2 )
WireLib.AddNotify( ply, "Entities registered with clutch controller", NOTIFY_GENERIC, 7 )
// Update client
Send_Links( ply, self.controller:GetConstrainedPairs() )
self:ClearObjects()
self:SetStage(0)
end
return true
end
/*---------------------------------------------------------
-- Reload --
Remove clutch association between current controller and
the traced entity
Removes all current selections if hits world
---------------------------------------------------------*/
function TOOL:Reload( trace )
local stage = self:NumObjects()
if stage == 1 then
self:ClearObjects()
self:SetStage(0)
return
// Remove clutch associations with this entity
elseif IsValid( self.controller ) then
if trace.Entity:IsWorld() then
self:ClearObjects()
self:SetStage(0)
self.controller = nil
else
for k, v in pairs( self.controller.clutch_ballsockets ) do
if k.Ent1 == trace.Entity or k.Ent2 == trace.Entity then
self.controller:RemoveClutch( k )
end
end
end
// Update client with new constraint info
self:SelectController( self.controller )
end
return true
end
function TOOL:Holster()
self:ClearObjects()
self:SetStage(0)
self:ReleaseGhostEntity()
end
function TOOL.BuildCPanel( panel )
panel:AddControl( "Header", { Text = "#Tool.wire_clutch.name", Description = "#Tool.wire_clutch.desc" } )
WireDermaExts.ModelSelect(panel, "wire_clutch_model", list.Get( "Wire_Misc_Tools_Models" ), 1)
end
if CLIENT then return end
/*---------------------------------------------------------
-- Clutch controller server functions --
---------------------------------------------------------*/
// When a ball socket is removed, clear the entry for each clutch controller
local function OnBallSocketRemoved( const )
if const.Type and const.Type == "" and const:GetClass() == "phys_ragdollconstraint" then
for k, v in pairs( ents.FindByClass("gmod_wire_clutch") ) do
if v.clutch_ballsockets[const] then
v.clutch_ballsockets[const] = nil
v:UpdateOverlay()
end
end
end
end
hook.Add( "EntityRemoved", "wire_clutch_ballsocket_removed", function( ent )
local r, e = xpcall( OnBallSocketRemoved, debug.traceback, ent )
if !r then WireLib.ErrorNoHalt( e .. "\n" ) end
end )
| apache-2.0 |
chengyi818/openwrt | customer/packages/luci/applications/luci-statistics/luasrc/statistics/rrdtool/definitions/interface.lua | 69 | 2769 | --[[
Luci statistics - interface plugin diagram definition
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.statistics.rrdtool.definitions.interface", package.seeall)
function rrdargs( graph, plugin, plugin_instance )
--
-- traffic diagram
--
local traffic = {
-- draw this diagram for each data instance
per_instance = true,
title = "%H: Transfer on %di",
vlabel = "Bytes/s",
-- diagram data description
data = {
-- defined sources for data types, if ommitted assume a single DS named "value" (optional)
sources = {
if_octets = { "tx", "rx" }
},
-- special options for single data lines
options = {
if_octets__tx = {
total = true, -- report total amount of bytes
color = "00ff00", -- tx is green
title = "Bytes (TX)"
},
if_octets__rx = {
flip = true, -- flip rx line
total = true, -- report total amount of bytes
color = "0000ff", -- rx is blue
title = "Bytes (RX)"
}
}
}
}
--
-- packet diagram
--
local packets = {
-- draw this diagram for each data instance
per_instance = true,
title = "%H: Packets on %di",
vlabel = "Packets/s",
-- diagram data description
data = {
-- data type order
types = { "if_packets", "if_errors" },
-- defined sources for data types
sources = {
if_packets = { "tx", "rx" },
if_errors = { "tx", "rx" }
},
-- special options for single data lines
options = {
-- processed packets (tx DS)
if_packets__tx = {
overlay = true, -- don't summarize
total = true, -- report total amount of bytes
color = "00ff00", -- processed tx is green
title = "Processed (tx)"
},
-- processed packets (rx DS)
if_packets__rx = {
overlay = true, -- don't summarize
flip = true, -- flip rx line
total = true, -- report total amount of bytes
color = "0000ff", -- processed rx is blue
title = "Processed (rx)"
},
-- packet errors (tx DS)
if_errors__tx = {
overlay = true, -- don't summarize
total = true, -- report total amount of packets
color = "ff5500", -- tx errors are orange
title = "Errors (tx)"
},
-- packet errors (rx DS)
if_errors__rx = {
overlay = true, -- don't summarize
flip = true, -- flip rx line
total = true, -- report total amount of packets
color = "ff0000", -- rx errors are red
title = "Errors (rx)"
}
}
}
}
return { traffic, packets }
end
| gpl-2.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-DragonSoul/localization.kr.lua | 1 | 6756 | if GetLocale() ~= "koKR" then return end
local L
-------------
-- Morchok --
-------------
L= DBM:GetModLocalization(311)
L:SetWarningLocalization({
KohcromWarning = "%s: %s"
})
L:SetTimerLocalization({
KohcromCD = "크초르모 시전: %s"
})
L:SetOptionLocalization({
KohcromWarning = "$journal:4262가 사용한 주문 알림 보기(영웅 난이도)",
KohcromCD = "$journal:4262가 사용할 주문 바 보기(영웅 난이도)",
RangeFrame = "거리 창 보기(5m, 업적 용도)"
})
---------------------
-- Warlord Zon'ozz --
---------------------
L= DBM:GetModLocalization(324)
L:SetOptionLocalization({
ShadowYell = "$spell:103434 대상이 된 경우 대화로 알리기(영웅 난이도)",
CustomRangeFrame = "교란의 그림자 관련 거리 창 설정(영웅 난이도)",
Never = "거리 창 사용안함",
Normal = "일반 거리 창",
DynamicPhase2 = "고라스의 검은 피 도중에만 숨기기 사용",
DynamicAlways = "항상 약화효과 숨기기 사용"
})
L:SetMiscLocalization({
voidYell = "굴카와스 언고브 느조스."
})
-----------------------------
-- Yor'sahj the Unsleeping --
-----------------------------
L= DBM:GetModLocalization(325)
L:SetWarningLocalization({
warnOozesHit = "핏방울 흡수 (%s) : %s"
})
L:SetTimerLocalization({
timerOozesActive = "핏방울 공격 가능",
timerOozesReach = "핏방울 도착"
})
L:SetOptionLocalization({
warnOozesHit = "흡수된 핏방울 알림 보기",
timerOozesActive = "핏방울 공격 가능 바 보기",
timerOozesReach = "핏방울 도착 바 보기",
RangeFrame = "$spell:104898 활성화 중에 거리 창 보기(4m)(일반 난이도 이상)"
})
L:SetMiscLocalization({
Black = "|cFF424242검정|r",
Purple = "|cFF9932CD보라|r",
Red = "|cFFFF0404빨강|r",
Green = "|cFF088A08초록|r",
Blue = "|cFF0080FF파랑|r",
Yellow = "|cFFFFA901노랑|r"
})
-----------------------
-- Hagara the Binder --
-----------------------
L= DBM:GetModLocalization(317)
L:SetWarningLocalization({
WarnPillars = "%s : %d 남음",
warnFrostTombCast = "8초 후 %s"
})
L:SetTimerLocalization({
TimerSpecial = "다음 번개/얼음"
})
L:SetOptionLocalization({
WarnPillars = "$journal:3919 또는 $journal:4069 남은횟수 알림 보기",
TimerSpecial = "다음 $spell:105256 또는 $spell:105465 바 보기",
RangeFrame = "$spell:105269(3m), $journal:4327(10m) 대상이 된 경우 거리 창 보기",
AnnounceFrostTombIcons = "$spell:104451 대상을 공격대 대화로 알리기(승급 권한 필요)",
SpecialCount = "$spell:105256 또는 $spell:105465 이전에 소리 듣기",
SetBubbles = "$spell:104451이 가능할 때 대화 말풍선을 숨김<br/>(전투 종료 후 원상태로 복구됨)"
})
L:SetMiscLocalization({
TombIconSet = "얼음 무덤 아이콘 : {rt%d} %s"
})
---------------
-- Ultraxion --
---------------
L= DBM:GetModLocalization(331)
L:SetWarningLocalization({
specWarnHourofTwilightN = "5초 후 %s! (%d)"
})
L:SetTimerLocalization({
TimerCombatStart = "울트락시온 활성화"
})
L:SetOptionLocalization({
TimerCombatStart = "울트락시온 활성화 바 보기",
ResetHoTCounter = "황혼의 시간 횟수 재시작 설정",
Never = "사용 안함",
ResetDynamic = "일반 2회, 영웅 3회 단위로 재시작",
Reset3Always = "난이도 구분 없이 3회 단위로 재시작",
SpecWarnHoTN = "황혼의 시간 5초 전 특수 경고 설정(횟수 재시작 설정 필요)",
One = "횟수가 1일때 보기(또는 1, 4, 7 일때)",
Two = "횟수가 2일때 보기(또는 2, 5 일때)",
Three = "횟수가 3일때 보기(또는 3, 6 일때)"
})
L:SetMiscLocalization({
Pull = "엄청난 무언가가 느껴진다. 조화롭지 못한 그의 혼돈이 내 정신을 어지럽히는구나!"
})
-------------------------
-- Warmaster Blackhorn --
-------------------------
L= DBM:GetModLocalization(332)
L:SetWarningLocalization({
SpecWarnElites = "황혼의 정예병!"
})
L:SetTimerLocalization({
TimerCombatStart = "전투 시작",
TimerAdd = "다음 정예병"
})
L:SetOptionLocalization({
TimerCombatStart = "전투 시작 바 보기",
TimerAdd = "다음 황혼의 정예병 등장 바 보기",
SpecWarnElites = "황혼의 정예병 등장시 특수 경고 보기",
SetTextures = "1 단계 진행 도중 텍스쳐 투영 효과 끄기<br/>(2 단계에서 다시 활성화 됩니다.)"
})
L:SetMiscLocalization({
SapperEmote = "비룡이 빠르게 날아와 황혼의 폭파병을 갑판에 떨어뜨립니다!",
Broadside = "spell:110153",
DeckFire = "spell:110095",
GorionaRetreat = "%s|1이;가; 고통에 울부짖으며, 소용돌이치는 구름 속으로 달아납니다."
})
-------------------------
-- Spine of Deathwing --
-------------------------
L= DBM:GetModLocalization(318)
L:SetWarningLocalization({
warnSealArmor = "%s",
SpecWarnTendril = "등에 달라 붙으세요!"
})
L:SetOptionLocalization({
SpecWarnTendril = "$spell:105563 효과가 없을 경우 특수 경고 보기",
InfoFrame = "$spell:105563 없는 대상을 정보 창으로 보기",
ShowShieldInfo = "$spell:105479 흡수량 바 보기(우두머리 체력 바 설정 무시)"
})
L:SetMiscLocalization({
Pull = "저 갑옷! 놈의 갑옷이 벗겨지는군! 갑옷을 뜯어내면 놈을 쓰러뜨릴 기회가 생길 거요!",
NoDebuff = "%s 없음",
PlasmaTarget = "이글거리는 혈장: %s",
DRoll = "회전하려고",
DLevels = "수평으로 균형을"
})
---------------------------
-- Madness of Deathwing --
---------------------------
L= DBM:GetModLocalization(333)
L:SetOptionLocalization({
RangeFrame = "$spell:108649 효과에 맞추어 거리 창 보기(영웅 난이도)"
})
L:SetMiscLocalization({
Pull = "넌 아무것도 못 했다. 내가 이 세상을 조각내주마."
})
-------------
-- Trash --
-------------
L = DBM:GetModLocalization("DSTrash")
L:SetGeneralLocalization({
name = "용의 영혼: 일반구간"
})
L:SetWarningLocalization({
DrakesLeft = "황혼의 습격자 : %d 남음"
})
L:SetTimerLocalization({
timerRoleplay = "이벤트 진행",
TimerDrakes = "%s"
})
L:SetOptionLocalization({
DrakesLeft = "황혼의 습격자 남은횟수 알림 보기",
TimerDrakes = "$spell:109904까지 남은시간 바 보기"
})
L:SetMiscLocalization({
firstRP = "티탄을 찬양하라. 그들이 돌아왔다!",
UltraxionTrash = "다시 만나 반갑군, 알렉스트라자. 난 떠나 있는 동안 좀 바쁘게 지냈다.",
UltraxionTrashEnded = "가련한 녀석들, 이 실험은 위대한 결말을 위한 희생이었다. 알 연구의 결과물을 직접 확인해라."
}) | gpl-2.0 |
alirezanile/Ldcxvx | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
erfan01311/supergroups | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
shayanchabok007/antispamfox | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
Primordus/lua-quickcheck | lqc/threading/thread_pool.lua | 2 | 2446 |
--- Module for creating a thread pool, based on Lua Lanes.
-- @module lqc.threading.thread_pool
-- @alias ThreadPool
local MsgProcessor = require 'lqc.threading.msg_processor'
local map = require 'lqc.helpers.map'
local lanes = require('lanes').configure { with_timers = false }
--- Checks if x is a positive integer (excluding 0)
-- @param x value to be checked
-- @return true if x is a non-zero positive integer; otherwise false.
local function is_positive_integer(x)
return type(x) == 'number' and x % 1 == 0 and x > 0
end
--- Checks if the thread pool args are valid.
-- @return nil; raises an error if invalid args are passed in.
local function check_threadpool_args(num_threads)
if not is_positive_integer(num_threads) then
error 'num_threads should be an integer > 0'
end
end
--- Creates and starts a thread.
-- @param func Function the thread should run after startup
-- @return a new thread object
local function make_thread(func)
return lanes.gen('*', func)()
end
local ThreadPool = {}
local ThreadPool_mt = { __index = ThreadPool }
--- Creates a new thread pool with a specific number of threads
-- @param num_threads Amount of the threads the pool should have
-- @return thread pool with a specific number of threads
function ThreadPool.new(num_threads)
check_threadpool_args(num_threads)
local linda = lanes.linda()
local thread_pool = {
threads = {},
linda = linda,
numjobs = 0
}
for _ = 1, num_threads do
table.insert(thread_pool.threads, make_thread(MsgProcessor.new(linda)))
end
return setmetatable(thread_pool, ThreadPool_mt)
end
--- Schedules a task to a thread in the thread pool
-- @param task A function that should be run on the thread
function ThreadPool:schedule(task)
self.numjobs = self.numjobs + 1
self.linda:send(nil, MsgProcessor.TASK_TAG, task)
end
--- Stops all threads in the threadpool. Blocks until all threads are finished
-- @return a table containing all results (in no specific order)
function ThreadPool:join()
map(self.threads, function() self:schedule(MsgProcessor.STOP_VALUE) end)
map(self.threads, function(thread) thread:join() end)
local results = {}
for _ = 1, self.numjobs - #self.threads do -- don't count stop job at end
local _, result = self.linda:receive(nil, MsgProcessor.RESULT_TAG)
if result ~= MsgProcessor.VOID_RESULT then table.insert(results, result) end
end
return results
end
return ThreadPool
| mit |
MOSAVI17/Informationbot | plugins/dice.lua | 16 | 1228 | local command = 'roll <nDr>'
local doc = [[```
/roll <nDr>
Returns a set of dice rolls, where n is the number of rolls and r is the range. If only a range is given, returns only one roll.
```]]
local triggers = {
'^/roll[@'..bot.username..']*'
}
local action = function(msg)
local input = msg.text_lower:input()
if not input then
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
local count, range
if input:match('^[%d]+d[%d]+$') then
count, range = input:match('([%d]+)d([%d]+)')
elseif input:match('^d?[%d]+$') then
count = 1
range = input:match('^d?([%d]+)$')
else
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
count = tonumber(count)
range = tonumber(range)
if range < 2 then
sendReply(msg, 'The minimum range is 2.')
return
end
if range > 1000 or count > 1000 then
sendReply(msg, 'The maximum range and count are 1000.')
return
end
local output = '*' .. count .. 'd' .. range .. '*\n`'
for i = 1, count do
output = output .. math.random(range) .. '\t'
end
output = output .. '`'
sendMessage(msg.chat.id, output, true, msg.message_id, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
| gpl-2.0 |
qllpa/TAEFWN | plugins/addsudo.lua | 1 | 1973 |
--[[
_____ _ _ _ _____ Dev @lIMyIl
|_ _|__| |__ / \ | | _| ____| Dev @li_XxX_il
| |/ __| '_ \ / _ \ | |/ / _| Dev @h_k_a
| |\__ \ | | |/ ___ \| <| |___ Dev @Aram_omar22
|_||___/_| |_/_/ \_\_|\_\_____| Dev @IXX_I_XXI
CH > @lTSHAKEl_CH
--]]
local function getindex(t,id)
for i,v in pairs(t) do
if v == id then
return i
end
end
return nil
end
function reload_plugins( )
plugins = {}
load_plugins()
end
function h_k_a(msg, matches)
if tonumber (msg.from.id) == 426795071 then
if matches[1]:lower() == "اضف مطور" then
table.insert(_config.sudo_users, tonumber(matches[2]))
print(matches[2] ..'\nتـمـ ☑️ اضـافـه مـطـور فـي الـبـوتـ ❗️')
save_config()
reload_plugins(true)
return matches[2] ..'\nتـمـ ☑️ اضـافـه مـطـور فـي الـبـوتـ ❗️'
elseif matches[1]:lower() == "حذف مطور" then
local k = tonumber(matches[2])
table.remove(_config.sudo_users, getindex( _config.sudo_users, k))
print(matches[2] ..'\nتـمـ ⚠️ حـذفـ الـمـطـور مـن الـبـوتـ ❗️')
save_config()
reload_plugins(true)
return matches[2] ..'\nتـمـ ⚠️ حـذفـ الـمـطـور مـن الـبـوتـ ❗️'
end
end
end
return {
patterns = {
"^(اضف مطور) (%d+)$",
"^(حذف مطور) (%d+)$",
"^[#!/](اضف مطور) (%d+)$",
"^[#!/](حذف مطور) (%d+)$"
},
run = h_k_a
}
-- تم التعديل و التعريب بواسطه @h_k_a
--[[
_____ _ _ _ _____ Dev @lIMyIl
|_ _|__| |__ / \ | | _| ____| Dev @li_XxX_il
| |/ __| '_ \ / _ \ | |/ / _| Dev @h_k_a
| |\__ \ | | |/ ___ \| <| |___ Dev @Aram_omar22
|_||___/_| |_/_/ \_\_|\_\_____| Dev @IXX_I_XXI
CH > @lTSHAKEl_CH
--]]
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Quicksand_Caves/npcs/qm7.lua | 17 | 1904 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: ???
-- Involved in Mission: The Mithra and the Crystal (Zilart 12)
-- @pos -504 20 -419 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(ZILART) == THE_MITHRA_AND_THE_CRYSTAL and player:getVar("ZilartStatus") == 1 and player:hasKeyItem(SCRAP_OF_PAPYRUS) == false) then
if (player:needToZone() and player:getVar("AncientVesselKilled") == 1) then
player:setVar("AncientVesselKilled",0);
player:addKeyItem(SCRAP_OF_PAPYRUS);
player:messageSpecial(KEYITEM_OBTAINED,SCRAP_OF_PAPYRUS);
else
player:startEvent(0x000c);
end
elseif (player:hasCompletedMission(ZILART,THE_MITHRA_AND_THE_CRYSTAL) or player:hasKeyItem(SCRAP_OF_PAPYRUS)) then
player:messageSpecial(YOU_FIND_NOTHING);
else
player:messageSpecial(SOMETHING_IS_BURIED);
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 == 0x000c and option == 1) then
SpawnMob(17629642,600):updateClaim(player); -- Ancient Vessel
end
end; | gpl-3.0 |
n0xus/darkstar | scripts/zones/Metalworks/npcs/Cid.lua | 17 | 11184 | -----------------------------------
-- Area: Metalworks
-- NPC: Cid
-- Starts & Finishes Quest: Cid's Secret, The Usual, Dark Puppet (start)
-- Involved in Mission: Bastok 7-1
-- @pos -12 -12 1 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(BASTOK) == THE_CRYSTAL_LINE and player:getVar("MissionStatus") == 1) then
if (trade:getItemQty(613,1) and trade:getItemCount() == 1) then
player:startEvent(0x01fa);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentday = tonumber(os.date("%j"));
local CidsSecret = player:getQuestStatus(BASTOK,CID_S_SECRET);
local LetterKeyItem = player:hasKeyItem(UNFINISHED_LETTER);
local currentMission = player:getCurrentMission(BASTOK);
local currentCOPMission = player:getCurrentMission(COP);
local UlmiaPath = player:getVar("COP_Ulmia_s_Path");
local TenzenPath = player:getVar("COP_Tenzen_s_Path");
local LouverancePath = player:getVar("COP_Louverance_s_Path");
local TreePathAv=0;
if (currentCOPMission == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day")~=currentday and player:getVar("COP_tenzen_story")== 0 ) then
player:startEvent(0x0381); -- COP event
elseif (currentCOPMission == CALM_BEFORE_THE_STORM and player:hasKeyItem(LETTERS_FROM_ULMIA_AND_PRISHE) == false and player:getVar("COP_Dalham_KILL") == 2 and player:getVar("COP_Boggelmann_KILL") == 2 and player:getVar("Cryptonberry_Executor_KILL")==2) then
player:startEvent(0x037C); -- COP event
elseif (currentCOPMission == FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==2 and player:getVar("Promathia_CID_timer")~=VanadielDayOfTheYear()) then
player:startEvent(0x037A); -- COP event
elseif (currentCOPMission == FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x0359); -- COP event
elseif (currentCOPMission == ONE_TO_BE_FEARED and player:getVar("PromathiaStatus")==0) then
player:startEvent(0x0358); -- COP event
elseif (currentCOPMission == THREE_PATHS and LouverancePath == 6 ) then
player:startEvent(0x0354); -- COP event
elseif (currentCOPMission == THREE_PATHS and LouverancePath == 9 ) then
if (TenzenPath==11 and UlmiaPath==8) then
TreePathAv=6;
elseif (TenzenPath==11) then
TreePathAv=2;
elseif (UlmiaPath==8) then
TreePathAv=4;
else
TreePathAv=1;
end
player:startEvent(0x0355,TreePathAv); -- COP event
elseif (currentCOPMission == THREE_PATHS and TenzenPath == 10 ) then
if (UlmiaPath==8 and LouverancePath==10) then
TreePathAv=5;
elseif (LouverancePath==10) then
TreePathAv=3;
elseif (UlmiaPath==8) then
TreePathAv=4;
else
TreePathAv=1;
end
player:startEvent(0x0356,TreePathAv); -- COP event
elseif (currentCOPMission == THREE_PATHS and UlmiaPath == 7 ) then
if (TenzenPath==11 and LouverancePath==10) then
TreePathAv=3;
elseif (LouverancePath==10) then
TreePathAv=1;
elseif (TenzenPath==11) then
TreePathAv=2;
else
TreePathAv=0;
end
player:startEvent(0x0357,TreePathAv); -- COP event
elseif (currentCOPMission == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus") > 8) then
player:startEvent(0x0352); -- COP event
elseif (currentCOPMission == THE_ENDURING_TUMULT_OF_WAR and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x0351); -- COP event
elseif (currentCOPMission == THE_CALL_OF_THE_WYRMKING and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x034D); -- COP event
elseif (currentCOPMission == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status")== 7 and player:getVar("MEMORIES_OF_A_MAIDEN_Status")== 12) then --two paths are finished ?
player:startEvent(0x034F); -- COP event 3.3
elseif (player:getMainJob() == 8 and player:getMainLvl() >= AF2_QUEST_LEVEL and
player:getQuestStatus(BASTOK,DARK_LEGACY) == QUEST_COMPLETED and player:getQuestStatus(BASTOK,DARK_PUPPET) == QUEST_AVAILABLE) then
player:startEvent(0x02f8); -- Start Quest "Dark Puppet"
elseif (currentMission == GEOLOGICAL_SURVEY) then
if (player:hasKeyItem(RED_ACIDITY_TESTER)) then
player:startEvent(0x01f8);
elseif (player:hasKeyItem(BLUE_ACIDITY_TESTER) == false) then
player:startEvent(0x01f7);
end
elseif (currentMission == THE_CRYSTAL_LINE) then
if (player:hasKeyItem(C_L_REPORTS)) then
player:showText(npc,MISSION_DIALOG_CID_TO_AYAME);
else
player:startEvent(0x01f9);
end
elseif (currentMission == THE_FINAL_IMAGE and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02fb); -- Bastok Mission 7-1
elseif (currentMission == THE_FINAL_IMAGE and player:getVar("MissionStatus") == 2) then
player:startEvent(0x02fc); -- Bastok Mission 7-1 (with Ki)
--Begin Cid's Secret
elseif (player:getFameLevel(BASTOK) >= 4 and CidsSecret == QUEST_AVAILABLE) then
player:startEvent(0x01fb);
elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem == false and player:getVar("CidsSecret_Event") == 1) then
player:startEvent(0x01fc); --After talking to Hilda, Cid gives information on the item she needs
elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem == false) then
player:startEvent(0x01f6); --Reminder dialogue from Cid if you have not spoken to Hilda
elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem) then
player:startEvent(0x01fd);
--End Cid's Secret
else
player:startEvent(0x01f4); -- Standard Dialogue
end
end;
-- 0x01f7 0x01f8 0x01f9 0x01fa 0x01f4 0x01f6 0x02d0 0x01fb 0x01fc 0x01fd 0x025b 0x02f3 0x02f8 0x03f2 0x02fb 0x02fc
-- 0x030c 0x030e 0x031b 0x031c 0x031d 0x031e 0x031f 0x035d 0x034e 0x0350 0x035e 0x035f 0x0353 0x035a 0x034d 0x034f
-- 0x0351 0x0352 0x0354 0x0355 0x0356 0x0357 0x0358 0x0359 0x0364 0x0365 0x0373 0x0374 0x037a 0x037b 0x037c 0x037d
-- 0x037e 0x037f 0x0381 0x0382
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- local currentday = tonumber(os.date("%j"));
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0381) then
player:setVar("COP_tenzen_story",1);
elseif (csid == 0x037C) then
player:addKeyItem(LETTERS_FROM_ULMIA_AND_PRISHE);
player:messageSpecial(KEYITEM_OBTAINED,LETTERS_FROM_ULMIA_AND_PRISHE);
elseif (csid == 0x037A) then
player:setVar("PromathiaStatus",0);
player:setVar("Promathia_CID_timer",0);
player:completeMission(COP,FIRE_IN_THE_EYES_OF_MEN);
player:addMission(COP,CALM_BEFORE_THE_STORM);
elseif (csid == 0x0359) then
player:setVar("PromathiaStatus",2);
player:setVar("Promathia_CID_timer",VanadielDayOfTheYear());
elseif (csid == 0x0357) then
player:setVar("COP_Ulmia_s_Path",8);
elseif (csid == 0x0356) then
player:setVar("COP_Tenzen_s_Path",11);
elseif (csid == 0x0355) then
player:setVar("COP_Louverance_s_Path",10);
elseif (csid == 0x0354) then
player:setVar("COP_Louverance_s_Path",7);
elseif (csid == 0x0352) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,DESIRES_OF_EMPTINESS);
player:addMission(COP,THREE_PATHS);
elseif (csid == 0x0351) then
player:setVar("PromathiaStatus",2);
elseif (csid == 0x0358) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x034D) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,THE_CALL_OF_THE_WYRMKING);
player:addMission(COP,A_VESSEL_WITHOUT_A_CAPTAIN);
elseif (csid == 0x034F) then
-- finishing mission 3.3 and all sub missions
player:setVar("EMERALD_WATERS_Status",0);
player:setVar("MEMORIES_OF_A_MAIDEN_Status",0);
player:completeMission(COP,THE_ROAD_FORKS);
player:addMission(COP,DESCENDANTS_OF_A_LINE_LOST);
player:completeMission(COP,DESCENDANTS_OF_A_LINE_LOST);
player:addMission(COP,COMEDY_OF_ERRORS_ACT_I);
player:completeMission(COP,COMEDY_OF_ERRORS_ACT_I);
player:addMission(COP,TENDING_AGED_WOUNDS ); --starting 3.4 COP mission
elseif (csid == 0x02f8) then
player:addQuest(BASTOK,DARK_PUPPET);
player:setVar("darkPuppetCS",1);
elseif (csid == 0x01f7) then
player:addKeyItem(BLUE_ACIDITY_TESTER);
player:messageSpecial(KEYITEM_OBTAINED, BLUE_ACIDITY_TESTER);
elseif (csid == 0x01f8 or csid == 0x02fc) then
finishMissionTimeline(player,1,csid,option);
elseif (csid == 0x01f9 and option == 0) then
if (player:getVar("MissionStatus") == 0) then
if (player:getFreeSlotsCount(0) >= 1) then
crystal = math.random(4096,4103);
player:addItem(crystal);
player:messageSpecial(ITEM_OBTAINED, crystal);
player:setVar("MissionStatus",1);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal);
end
end
elseif (csid == 0x01fa and option == 0) then
player:tradeComplete();
player:addKeyItem(C_L_REPORTS);
player:messageSpecial(KEYITEM_OBTAINED, C_L_REPORTS);
elseif (csid == 0x02fb) then
player:setVar("MissionStatus",1);
elseif (csid == 0x01fb) then
player:addQuest(BASTOK,CID_S_SECRET);
elseif (csid == 0x01fd) then
if (player:getFreeSlotsCount(0) >= 1) then
player:delKeyItem(UNFINISHED_LETTER);
player:setVar("CidsSecret_Event",0);
player:addItem(13570);
player:messageSpecial(ITEM_OBTAINED,13570); -- Ram Mantle
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,CID_S_SECRET);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13570);
end
end
-- complete chapter "tree path"
if (csid == 0x0355 or csid == 0x0356 or csid == 0x0357) then
if (player:getVar("COP_Tenzen_s_Path")==11 and player:getVar("COP_Ulmia_s_Path")==8 and player:getVar("COP_Louverance_s_Path")==10) then
player:completeMission(COP,THREE_PATHS);
player:addMission(COP,FOR_WHOM_THE_VERSE_IS_SUNG);
player:setVar("PromathiaStatus",0);
end
end
end;
| gpl-3.0 |
n0xus/darkstar | scripts/zones/The_Garden_of_RuHmet/npcs/_iz2.lua | 19 | 1971 | -----------------------------------
-- Area: The Garden of RuHmet
-- NPC: _iz2 (Ebon_Panel)
-- @pos 422.351 -5.180 -100.000 35 | Hume Tower
-----------------------------------
package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Garden_of_RuHmet/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Race = player:getRace();
if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x00CA);
elseif (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus") == 2) then
if ( Race==2 or Race==1) then
player:startEvent(0x0078);
else
player:messageSpecial(NO_NEED_INVESTIGATE);
end
else
player:messageSpecial(NO_NEED_INVESTIGATE);
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 == 0x00CA) then
player:setVar("PromathiaStatus",2);
elseif (0x0078 and option ~=0) then -- Hume
player:addTitle(WARRIOR_OF_THE_CRYSTAL);
player:setVar("PromathiaStatus",3);
player:addKeyItem(LIGHT_OF_VAHZL);
player:messageSpecial(KEYITEM_OBTAINED,LIGHT_OF_VAHZL);
end
end; | gpl-3.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-Party-Cataclysm/localization.de.lua | 1 | 16391 | if GetLocale() ~= "deDE" then return end
local L
-------------------------
-- Blackrock Caverns --
--------------------------
-- Rom'ogg Bonecrusher --
--------------------------
L= DBM:GetModLocalization(105)
-------------------------------
-- Corla, Herald of Twilight --
-------------------------------
L= DBM:GetModLocalization(106)
L:SetWarningLocalization({
WarnAdd = "Add freigesetzt"
})
L:SetOptionLocalization({
WarnAdd = "Warne, wenn ein Add den $spell:75608 Buff verliert"
})
-----------------------
-- Karsh SteelBender --
-----------------------
L= DBM:GetModLocalization(107)
L:SetTimerLocalization({
TimerSuperheated = "Supererhitzte Rüstung (%d)"
})
L:SetOptionLocalization({
TimerSuperheated = "Dauer von $spell:75846 anzeigen"
})
------------
-- Beauty --
------------
L= DBM:GetModLocalization(108)
-----------------------------
-- Ascendant Lord Obsidius --
-----------------------------
L= DBM:GetModLocalization(109)
L:SetOptionLocalization({
SetIconOnBoss = "Setze ein Zeichen auf den Boss nach $spell:76200 "
})
---------------------
-- The Deadmines --
---------------------
-- Glubtok --
-------------
L= DBM:GetModLocalization(89)
-----------------------
-- Helix Gearbreaker --
-----------------------
L= DBM:GetModLocalization(90)
---------------------
-- Foe Reaper 5000 --
---------------------
L= DBM:GetModLocalization(91)
----------------------
-- Admiral Ripsnarl --
----------------------
L= DBM:GetModLocalization(92)
----------------------
-- "Captain" Cookie --
----------------------
L= DBM:GetModLocalization(93)
----------------------
-- Vanessa VanCleef --
----------------------
L= DBM:GetModLocalization(95)
L:SetTimerLocalization({
achievementGauntlet = "Spießrutenlauf"
})
------------------
-- Grim Batol --
---------------------
-- General Umbriss --
---------------------
L= DBM:GetModLocalization(131)
L:SetOptionLocalization{
PingBlitz = "Pingt die Minimap, wenn General Umbriss dich anstürmt"
}
L:SetMiscLocalization{
Blitz = "richtet seine Augen auf |cFFFF0000(%S+)"
}
--------------------------
-- Forgemaster Throngus --
--------------------------
L= DBM:GetModLocalization(132)
-------------------------
-- Drahga Shadowburner --
-------------------------
L= DBM:GetModLocalization(133)
L:SetMiscLocalization{
ValionaYell = "Drache, Ihr werdet tun, was ich sage! Fangt mich!",
Add = "%s wirkt den Zauber"
}
------------
-- Erudax --
------------
L= DBM:GetModLocalization(134)
----------------------------
-- Halls of Origination --
----------------------------
-- Temple Guardian Anhuur --
----------------------------
L= DBM:GetModLocalization(124)
---------------------
-- Earthrager Ptah --
---------------------
L= DBM:GetModLocalization(125)
L:SetMiscLocalization{
Kill = "Ptah... ist... nicht mehr..."
}
--------------
-- Anraphet --
--------------
L= DBM:GetModLocalization(126)
L:SetTimerLocalization({
achievementGauntlet = "Schneller als das Licht"
})
L:SetMiscLocalization({
Brann = "Alles klar, auf geht's! Ich gebe nur noch die letzte Eingangssequenz in den Türmechanismus ein... und..."
})
------------
-- Isiset --
------------
L= DBM:GetModLocalization(127)
L:SetWarningLocalization({
WarnSplitSoon = "Teilung bald"
})
L:SetOptionLocalization({
WarnSplitSoon = "Zeige Vorwarnung für Teilung"
})
-------------
-- Ammunae --
-------------
L= DBM:GetModLocalization(128)
-------------
-- Setesh --
-------------
L= DBM:GetModLocalization(129)
----------
-- Rajh --
----------
L= DBM:GetModLocalization(130)
--------------------------------
-- Lost City of the Tol'vir --
--------------------------------
-- General Husam --
-------------------
L= DBM:GetModLocalization(117)
--------------
-- Lockmaw --
--------------
L= DBM:GetModLocalization(118)
L:SetOptionLocalization{
RangeFrame = "Zeige Abstandsfenster (5m)"
}
----------
-- Augh --
----------
L = DBM:GetModLocalization("Augh")
L:SetGeneralLocalization({
name = "Augh"
})
------------------------
-- High Prophet Barim --
------------------------
L= DBM:GetModLocalization(119)
L:SetOptionLocalization{
BossHealthAdds = "Zeige die Gesundheit der Adds in der Lebensanzeige"
}
------------------------------------
-- Siamat, Lord of the South Wind --
------------------------------------
L= DBM:GetModLocalization(122)
L:SetWarningLocalization{
specWarnPhase2Soon = "Phase 2 in 5 Sekunden"
}
L:SetTimerLocalization({
timerPhase2 = "Phase 2 beginnt"
})
L:SetOptionLocalization{
specWarnPhase2Soon = "Spezialwarnung für baldige Phase 2 (5 Sekunden)",
timerPhase2 = "Zeige Timer für den Beginn von Phase 2"
}
-----------------------
-- Shadowfang Keep --
-----------------------
-- Baron Ashbury --
-------------------
L= DBM:GetModLocalization(96)
-----------------------
-- Baron Silverlaine --
-----------------------
L= DBM:GetModLocalization(97)
--------------------------
-- Commander Springvale --
--------------------------
L= DBM:GetModLocalization(98)
L:SetTimerLocalization({
TimerAdds = "Nächste Adds"
})
L:SetOptionLocalization{
TimerAdds = "Zeige Zeit bis nächste Adds"
}
L:SetMiscLocalization{
YellAdds = "Schlagt die Eindringlinge zurück!"
}
-----------------
-- Lord Walden --
-----------------
L= DBM:GetModLocalization(99)
L:SetWarningLocalization{
specWarnCoagulant = "Grüne Mischung - Lauf!",
specWarnRedMix = "Rote Mischung - Bleib stehen!"
}
L:SetOptionLocalization{
RedLightGreenLight = "Spezialwarnungen für Bewegungen bei Rot/Grün"
}
------------------
-- Lord Godfrey --
------------------
L= DBM:GetModLocalization(100)
---------------------
-- The Stonecore --
---------------------
-- Corborus --
--------------
L= DBM:GetModLocalization(110)
L:SetWarningLocalization({
WarnEmerge = "Auftauchen",
WarnSubmerge = "Abtauchen"
})
L:SetTimerLocalization({
TimerEmerge = "Nächstes Auftauchen",
TimerSubmerge = "Nächstes Abtauchen"
})
L:SetOptionLocalization({
WarnEmerge = "Zeige Warnung für Auftauchen",
WarnSubmerge = "Zeige Warnung für Abtauchen",
TimerEmerge = "Zeige Zeit bis Auftauchen",
TimerSubmerge = "Zeige Zeit bis Abtauchen",
CrystalArrow = "Zeige DBM-Pfeil, wenn $spell:81634 in deiner Nähe ist",
RangeFrame = "Zeige Abstandsfenster (5m)"
})
--------------
-- Slabhide --
--------------
L= DBM:GetModLocalization(111)
L:SetWarningLocalization({
WarnAirphase = "Luftphase",
WarnGroundphase = "Bodenphase",
specWarnCrystalStorm = "Kristallsturm - Geh in Deckung"
})
L:SetTimerLocalization({
TimerAirphase = "Nächste Luftphase",
TimerGroundphase = "Nächste Bodenphase"
})
L:SetOptionLocalization({
WarnAirphase = "Zeige Warnung, wenn Plattenhaut abhebt",
WarnGroundphase = "Zeige Warnung, wenn Plattenhaut landet",
TimerAirphase = "Zeige Zeit bis nächste Luftphase",
TimerGroundphase = "Zeige Zeit bis nächste Bodenphase",
specWarnCrystalStorm = "Spezialwarnung für $spell:92265"
})
-----------
-- Ozruk --
-----------
L= DBM:GetModLocalization(112)
-------------------------
-- High Priestess Azil --
------------------------
L= DBM:GetModLocalization(113)
---------------------------
-- The Vortex Pinnacle --
---------------------------
-- Grand Vizier Ertan --
------------------------
L= DBM:GetModLocalization(114)
L:SetMiscLocalization{
Retract = "%s zieht sein Wirbelsturmschild zurück!"
}
--------------
-- Altairus --
--------------
L= DBM:GetModLocalization(115)
-----------
-- Asaad --
-----------
L= DBM:GetModLocalization(116)
L:SetOptionLocalization({
SpecWarnStaticCling = "Spezialwarnung für $spell:87618"
})
L:SetWarningLocalization({
SpecWarnStaticCling = "SPRING!"
})
---------------------------
-- The Throne of Tides --
---------------------------
-- Lady Naz'jar --
------------------
L= DBM:GetModLocalization(101)
-----======-----------
-- Commander Ulthok --
----------------------
L= DBM:GetModLocalization(102)
-------------------------
-- Erunak Stonespeaker --
-------------------------
L= DBM:GetModLocalization(103)
------------
-- Ozumat --
------------
L= DBM:GetModLocalization(104)
L:SetTimerLocalization{
TimerPhase = "Phase 2"
}
L:SetOptionLocalization{
TimerPhase = "Zeige Zeit bis Phase 2"
}
----------------
-- Zul'Aman --
----------------
-- Akil'zon --
--------------
L= DBM:GetModLocalization(186)
L:SetOptionLocalization{
RangeFrame = "Zeige Abstandsfenster (10m)",
StormArrow = "Zeige DBM-Pfeil für $spell:43648"
}
--------------
-- Nalorakk --
--------------
L= DBM:GetModLocalization(187)
L:SetWarningLocalization{
WarnBear = "Bärform",
WarnBearSoon = "Bärform in 5 Sek",
WarnNormal = "Normalform",
WarnNormalSoon = "Normalform in 5 Sek"
}
L:SetTimerLocalization{
TimerBear = "Bärform",
TimerNormal = "Normalform"
}
L:SetOptionLocalization{
WarnBear = "Zeige Warnung für Bärform",
WarnBearSoon = "Zeige Vorwarnung für Bärform",
WarnNormal = "Zeige Warnung für Normalform",
WarnNormalSoon = "Zeige Vorwarnung für Normalform",
TimerBear = "Zeige Zeit bis Bärform",
TimerNormal = "Zeige Zeit bis Normalform",
InfoFrame = "Zeige Infofenster für Spieler, welche von $spell:42402 betroffen sind"
}
L:SetMiscLocalization{
YellBear = "Ihr provoziert die Bestie, jetzt werdet ihr sie kennenlernen!",
YellNormal = "Macht Platz für Nalorakk!",
PlayerDebuffs = "Anstürmen Debuff"
}
--------------
-- Jan'alai --
--------------
L= DBM:GetModLocalization(188)
L:SetMiscLocalization{
YellBomb = "Jetzt sollt ihr brennen!",
YellHatchAll= "Stärke... und zwar viel davon.",
YellAdds = "Wo is' meine Brut? Was ist mit den Eiern?"
}
-------------
-- Halazzi --
-------------
L= DBM:GetModLocalization(189)
L:SetWarningLocalization{
WarnSpirit = "Geistphase",
WarnNormal = "Normalphase"
}
L:SetOptionLocalization{
WarnSpirit = "Zeige Warnung für Geistphase",
WarnNormal = "Zeige Warnung für Normalphase"
}
L:SetMiscLocalization{
YellSpirit = "Ich kämpfe mit wildem Geist...",
YellNormal = "Geist, zurück zu mir!"
}
-----------------------
-- Hexlord Malacrass --
-----------------------
L= DBM:GetModLocalization(190)
L:SetTimerLocalization{
TimerSiphon = "%s: %s"
}
L:SetOptionLocalization{
TimerSiphon = "Dauer von $spell:43501 anzeigen"
}
L:SetMiscLocalization{
YellPull = "Der Schatten wird euch verschlingen..."
}
-------------
-- Daakara --
-------------
L= DBM:GetModLocalization(191)
L:SetTimerLocalization{
timerNextForm = "Nächster Formwechsel"
}
L:SetOptionLocalization{
timerNextForm = "Zeige Zeit bis Formwechsel",
InfoFrame = "Zeige Infofenster für Spieler, welche von $spell:42402 betroffen sind"
}
L:SetMiscLocalization{
PlayerDebuffs = "Anstürmen Debuff"
}
-----------------
-- Zul'Gurub --
-------------------------
-- High Priest Venoxis --
-------------------------
L= DBM:GetModLocalization(175)
L:SetOptionLocalization{
LinkArrow = "Zeige DBM-Pfeil, wenn du von $spell:96477 betroffen bist"
}
------------------------
-- Bloodlord Mandokir --
------------------------
L= DBM:GetModLocalization(176)
L:SetWarningLocalization{
WarnRevive = "%d Geister verbleiben",
SpecWarnOhgan = "Ohgan wiederbelebt! Angreifen!"
}
L:SetOptionLocalization{
WarnRevive = "Verkünde die Anzahl der verbleibenden Geisterwiederbelebungen",
SpecWarnOhgan = "Zeige Warnung, wenn Ohgan wiederbelebt wird",
SetIconOnOhgan = "Setze ein Zeichen auf Ohgan, wenn er wiederbelebt wird"
}
----------------------
-- Cache of Madness --
----------------------
-------------
-- Gri'lek --
-------------
L= DBM:GetModLocalization(177)
---------------
-- Hazza'rah --
---------------
L= DBM:GetModLocalization(178)
--------------
-- Renataki --
--------------
L= DBM:GetModLocalization(179)
---------------
-- Wushoolay --
---------------
L= DBM:GetModLocalization(180)
----------------------------
-- High Priestess Kilnara --
----------------------------
L= DBM:GetModLocalization(181)
------------
-- Zanzil --
------------
L= DBM:GetModLocalization(184)
L:SetWarningLocalization{
SpecWarnToxic = "Hole Toxische Qual"
}
L:SetOptionLocalization{
SpecWarnToxic = "Spezialwarnung, wenn dir der $spell:96328 Buff fehlt",
InfoFrame = "Zeige Infofenster für Spieler, denen der $spell:96328 Buff fehlt"
}
L:SetMiscLocalization{
PlayerDebuffs = "Keine Toxische Qual"
}
----------------------------
-- Jindo --
----------------------------
L= DBM:GetModLocalization(185)
L:SetWarningLocalization{
WarnBarrierDown = "Schild von Hakkars Ketten zerstört - %d/3 verbleibend"
}
L:SetOptionLocalization{
WarnBarrierDown = "Verkünde Zerstörung der Schilde von Hakkars Ketten"
}
L:SetMiscLocalization{
Kill = "Du hast deine Grenzen überschritten, Jin'do. Diese Macht kannst du nicht kontrollieren. Hast du vergessen, wer ich bin? Hast du vergessen, wozu ich fähig bin?!"
}
----------------
-- End Time --
-------------------
-- Echo of Baine --
-------------------
L= DBM:GetModLocalization(340)
-------------------
-- Echo of Jaina --
-------------------
L= DBM:GetModLocalization(285)
L:SetTimerLocalization{
TimerFlarecoreDetonate = "Flammenkern detoniert"
}
L:SetOptionLocalization{
TimerFlarecoreDetonate = "Zeige Zeit bis $spell:101927 detoniert"
}
----------------------
-- Echo of Sylvanas --
----------------------
L= DBM:GetModLocalization(323)
---------------------
-- Echo of Tyrande --
---------------------
L= DBM:GetModLocalization(283)
--------------
-- Murozond --
--------------
L= DBM:GetModLocalization(289)
L:SetMiscLocalization{
Kill = "Ihr wisst nicht, was Ihr getan habt. Aman'Thul... Was ich... gesehen... habe..."
}
------------------------
-- Well of Eternity --
------------------------
-- Peroth'arn --
----------------
L= DBM:GetModLocalization(290)
L:SetMiscLocalization{
Pull = "Kein Sterblicher überlebt es, sich mir gegenüberzustellen!"
}
-------------
-- Azshara --
-------------
L= DBM:GetModLocalization(291)
L:SetWarningLocalization{
WarnAdds = "Neue Adds bald"
}
L:SetTimerLocalization{
TimerAdds = "Nächste Adds"
}
L:SetOptionLocalization{
WarnAdds = "Verkünde, wenn neue Adds \"erscheinen\"",
TimerAdds = "Zeige Zeit bis nächste Adds \"erscheinen\""
}
L:SetMiscLocalization{
Kill = "Genug. So gern ich auch Gastgeberin bin, muss ich mich doch um wichtigere Angelegenheiten kümmern."
}
-----------------------------
-- Mannoroth and Varo'then --
-----------------------------
L= DBM:GetModLocalization(292)
L:SetTimerLocalization{
TimerTyrandeHelp = "Tyrande braucht Hilfe"
}
L:SetOptionLocalization{
TimerTyrandeHelp = "Zeige Zeit bis Tyrande Hilfe braucht"
}
L:SetMiscLocalization{
Kill = "Malfurion, er hat es geschafft! Das Portal bricht zusammen!"
}
------------------------
-- Hour of Twilight --
------------------------
-- Arcurion --
--------------
L= DBM:GetModLocalization(322)
L:SetTimerLocalization{
TimerCombatStart = "Kampfbeginn"
}
L:SetOptionLocalization{
TimerCombatStart = "Zeige Zeit bis Kampfbeginn"
}
L:SetMiscLocalization{
Event = "Zeigt Euch!",
Pull = "Streitkräfte des Schattenhammers tauchen an den Rändern der Schlucht auf."
}
----------------------
-- Asira Dawnslayer --
----------------------
L= DBM:GetModLocalization(342)
L:SetMiscLocalization{
Pull = "... Das wäre erledigt. Jetzt seid Ihr und Eure tollpatschigen Freunde an der Reihe. Mmm, ich dachte schon, Ihr würdet nie kommen!"
}
---------------------------
-- Archbishop Benedictus --
---------------------------
L= DBM:GetModLocalization(341)
L:SetTimerLocalization{
TimerCombatStart = "Kampfbeginn"
}
L:SetOptionLocalization{
TimerCombatStart = "Zeige Zeit bis Kampfbeginn"
}
L:SetMiscLocalization{
Event = "Und nun, Schamane, werdet Ihr MIR die Drachenseele geben."
}
--------------------
-- World Bosses --
-------------------------
-- Akma'hat --
-------------------------
L = DBM:GetModLocalization("Akmahat")
L:SetGeneralLocalization{
name = "Akma'hat"
}
-----------
-- Garr --
----------
L = DBM:GetModLocalization("Garr")
L:SetGeneralLocalization{
name = "Garr"
}
----------------
-- Julak-Doom --
----------------
L = DBM:GetModLocalization("JulakDoom")
L:SetGeneralLocalization{
name = "Julak-Doom"
}
-----------
-- Mobus --
-----------
L = DBM:GetModLocalization("Mobus")
L:SetGeneralLocalization{
name = "Mobus"
}
-----------
-- Xariona --
-----------
L = DBM:GetModLocalization("Xariona")
L:SetGeneralLocalization{
name = "Xariona"
}
| gpl-2.0 |
rekotc/game-engine-demo | Source/GCC4/3rdParty/luaplus51-all/Src/Modules/luajson/lua/json/encode/strings.lua | 3 | 1990 | --[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <harningt@gmail.com>
]]
local string_char = require("string").char
local pairs = pairs
local util_merge = require("json.util").merge
module("json.encode.strings")
local normalEncodingMap = {
['"'] = '\\"',
['\\'] = '\\\\',
['/'] = '\\/',
['\b'] = '\\b',
['\f'] = '\\f',
['\n'] = '\\n',
['\r'] = '\\r',
['\t'] = '\\t',
['\v'] = '\\v' -- not in official spec, on report, removing
}
local xEncodingMap = {}
for char, encoded in pairs(normalEncodingMap) do
xEncodingMap[char] = encoded
end
-- Pre-encode the control characters to speed up encoding...
-- NOTE: UTF-8 may not work out right w/ JavaScript
-- JavaScript uses 2 bytes after a \u... yet UTF-8 is a
-- byte-stream encoding, not pairs of bytes (it does encode
-- some letters > 1 byte, but base case is 1)
for i = 0, 255 do
local c = string_char(i)
if c:match('[%z\1-\031\128-\255]') and not normalEncodingMap[c] then
-- WARN: UTF8 specializes values >= 0x80 as parts of sequences...
-- without \x encoding, do not allow encoding > 7F
normalEncodingMap[c] = ('\\u%.4X'):format(i)
xEncodingMap[c] = ('\\x%.2X'):format(i)
end
end
local defaultOptions = {
xEncode = false, -- Encode single-bytes as \xXX
-- / is not required to be quoted but it helps with certain decoding
-- Required encoded characters, " \, and 00-1F (0 - 31)
encodeSet = '\\"/%z\1-\031',
encodeSetAppend = nil -- Chars to append to the default set
}
default = nil
strict = nil
function getEncoder(options)
options = options and util_merge({}, defaultOptions, options) or defaultOptions
local encodeSet = options.encodeSet
if options.encodeSetAppend then
encodeSet = encodeSet .. options.encodeSetAppend
end
local encodingMap = options.xEncode and xEncodingMap or normalEncodingMap
local function encodeString(s, state)
return '"' .. s:gsub('[' .. encodeSet .. ']', encodingMap) .. '"'
end
return {
string = encodeString
}
end
| lgpl-3.0 |
n0xus/darkstar | scripts/zones/Windurst_Walls/npcs/_6n8.lua | 17 | 1309 | -----------------------------------
-- Area: Windurst Walls
-- Door: Priming Gate
-- Involved in quest: Toraimarai Turmoil
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
X = player:getXPos();
Z = player:getZPos();
if ((X >= 1.51 and X <= 9.49) and (Z >= 273.1 and Z <= 281)) then
if player:hasKeyItem(267) then
player:startEvent(0x0191);
else player:startEvent (0x0108);
end
else
player:startEvent (0x018b);
end
return 1
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
goblinor/BomBus1 | plugins/list1.lua | 1 | 2495 | --[[
#
#ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#:((
# For More Information ....!
# Developer : reza < @Yagop >
# our channel: @Ntflight
# Version: 1.1
#:))
#ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#
]]
do
local function yagop(msg, matches)
if is_momod(msg) and matches[1]== "list2" then
return [[
🔹دستورات گروهی 🔹
__________________________
/kick + <user|reply> : اخراج | ⛔️
/silent + <user|reply> : سایلنت کردن | 🔕
/block + <user|reply>: بلوك | ♨️
/ban + <user|reply>: بن کردن | 🚷
/unban + <user> : آن بن کردن | ⭕️
/banlist : بن لیست | 🆘
/id : ايدي | 🆔
/kickme : اخراج من | 🚫
_________________________
- دستورات باز و بسته کردن | ✂️
_________________________
/mute audio : قفل صدا | 🔊
/mute photo : قفل عکس | 🌠
/mute video : قفل ویدیو | 🎥
/mute gifs : قفل گیف | 🎡
/mute doc : قفل داکیومنت | 🗂
/mute text : قفل تکست | 📝
/mute all : قفل گروه | 🔕
_________________________
/mute — قفل , /unmute — باز
_________________________
/lock ↴ 🔒 قفل | /unlock ↴ 🔓 باز
links : لینک | 🔗
contacts : مخاطب | 📵
flood : فلود | 🔐
Spam : اسپم | 📊
arabic : کلمات عربی | 🆎
english : کلمات انگلیسی : | 🔡
member : اعضا | 👤
rtl : کاوران | 🚸
Tgservice : ورودی ها | ⚛
sticker : استیکر | 🎡
tag : #تگ | ➕
emoji : اموجی | 😃
bots : ربات ها | 🤖
fwd : فوروارد | ↩️
reply : ریپلی | 🔃
join : جوین شده ها | 🚷
username : نام کاربری | @
media : مدیا | 🆘
badword : کلمات رکیک | 🏧
leave : خروج | 🚶
strict : حفاظت | ⛔️
all : همه | 🔕
_________________________
🔹چگونگی استفاده از دستورات 🔹
🔒/lock + قفل — دستور
🔓/unlock + بازکردن — دستور
_________________________
Channel : @NTFLIGHT 🎗
]]
end
if not is_momod(msg) then
return "Only managers 😐⛔️"
end
end
return {
description = "Help list",
usage = "Help list",
patterns = {
"[#!/](list2)"
},
run = yagop
}
end
| gpl-2.0 |
n0xus/darkstar | scripts/globals/weaponskills/flat_blade.lua | 18 | 1513 | -----------------------------------
-- Flat Blade
-- Sword weapon skill
-- Skill Level: 75
-- Stuns enemy. Chance of stunning varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: None
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.3; params.dex_wsc = 0.0; 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.str_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
local chance = player:getTP()-100 > math.random()*150;
if (damage > 0 and target:hasStatusEffect(EFFECT_STUN) == false and chance) then
target:addStatusEffect(EFFECT_STUN, 1, 0, 4);
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
lduboeuf/lit | deps/require.lua | 2 | 8854 | --[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
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.
--]]
if exports then
exports.name = "luvit/require"
exports.version = "1.2.1"
exports.homepage = "https://github.com/luvit/luvit/blob/master/deps/require.lua"
exports.description = "Luvit's custom require system with relative requires and sane search paths."
exports.tags = {"luvit", "require"}
exports.license = "Apache 2"
exports.author = { name = "Tim Caswell" }
end
local luvi = require('luvi')
local bundle = luvi.bundle
local pathJoin = luvi.path.join
local env = require('env')
local os = require('ffi').os
local uv = require('uv')
local realRequire = _G.require
local tmpBase = os == "Windows" and (env.get("TMP") or uv.cwd()) or
(env.get("TMPDIR") or '/tmp')
local binExt = os == "Windows" and ".dll" or ".so"
-- Package sources
-- $author/$name@$version -> resolves to hash, cached in memory
-- bundle:full/bundle/path
-- full/unix/path
-- C:\\full\windows\path
local fileCache = {}
local function readFile(path)
assert(path)
local data = fileCache[path]
if data ~= nil then return data end
local prefix = path:match("^bundle:/*")
if prefix then
data = bundle.readfile(path:sub(#prefix + 1))
else
local stat = uv.fs_stat(path)
if stat and stat.type == "file" then
local fd = uv.fs_open(path, "r", 511)
if fd then
data = uv.fs_read(fd, stat.size, -1)
uv.fs_close(fd)
end
end
end
fileCache[path] = data and true or false
return data
end
local function scanDir(path)
local bundlePath = path:match("^bundle:/*(.*)")
if bundlePath then
local names, err = bundle.readdir(bundlePath)
if not names then return nil, err end
local i = 1
return function ()
local name = names[i]
if not name then return end
i = i + 1
local stat = assert(bundle.stat(bundlePath .. "/" .. name))
return {
name = name,
type = stat.type,
}
end
else
local req, err = uv.fs_scandir(path)
if not req then return nil, err end
return function ()
return uv.fs_scandir_next(req)
end
end
end
local statCache = {}
local function statFile(path)
local stat, err
stat = statCache[path]
if stat then return stat end
local bundlePath = path:match("^bundle:/*(.*)")
if bundlePath then
stat, err = bundle.stat(bundlePath)
else
stat, err = uv.fs_stat(path)
end
if stat then
statCache[path] = stat
return stat
end
return nil, err or "Problem statting: " .. path
end
local dirCache = {}
local function isDir(path)
assert(path)
local is = dirCache[path]
if is ~= nil then return is end
local prefix = path:match("^bundle:/*")
local stat
if prefix then
stat = bundle.stat(path:sub(#prefix + 1))
else
stat = uv.fs_stat(path)
end
is = stat and (stat.type == "directory") or false
dirCache[path] = is
return is
end
local types = { ".lua", binExt }
local function fixedRequire(path)
assert(path)
local fullPath = path
local data = readFile(fullPath)
if not data then
for i = 1, #types do
fullPath = path .. types[i]
data = readFile(fullPath)
if data then break end
fullPath = pathJoin(path, "init" .. types[i])
data = readFile(fullPath)
if data then break end
end
if not data then return end
end
local prefix = fullPath:match("^bundle:")
local normalizedPath = fullPath
if prefix == "bundle:" and bundle.base then
normalizedPath = fullPath:gsub(prefix, bundle.base)
end
return data, fullPath, normalizedPath
end
local skips = {}
local function moduleRequire(base, name)
assert(base and name)
while true do
if not skips[base] then
local mod, path, key
if isDir(pathJoin(base, "libs")) then
mod, path, key = fixedRequire(pathJoin(base, "libs", name))
if mod then return mod, path, key end
end
if isDir(pathJoin(base, "deps")) then
mod, path, key = fixedRequire(pathJoin(base, "deps", name))
if mod then return mod, path, key end
end
end
-- Stop at filesystem or prefix root (58 is ":")
if base == "/" or base:byte(-1) == 58 then break end
base = pathJoin(base, "..")
end
-- If we didn't find it outside the bundle, look inside the bundle.
if not base:match("^bundle:/*") then
return moduleRequire("bundle:", name)
end
end
local moduleCache = {}
-- Prototype for module tables
-- module.path - is path to module
-- module.dir - is path to directory containing module
-- module.exports - actual exports, initially is an empty table
local Module = {}
local moduleMeta = { __index = Module }
local function makeModule(modulePath)
-- Convert windows paths to unix paths (mostly)
local path = modulePath:gsub("\\", "/")
-- Normalize slashes around prefix to be exactly one after
path = path:gsub("^/*([^/:]+:)/*", "%1/")
return setmetatable({
path = path,
dir = pathJoin(path, ".."),
exports = {}
}, moduleMeta)
end
function Module:load(path)
return readFile(pathJoin(self.dir, './' .. path))
end
function Module:scan(path)
return scanDir(pathJoin(self.dir, './' .. path))
end
function Module:stat(path)
return statFile(pathJoin(self.dir, './' .. path))
end
function Module:action(path, action)
path = pathJoin(self.dir, './' .. path)
local bundlePath = path:match("^bundle:/*(.*)")
if bundlePath then
return bundle.action(bundlePath, action)
else
return action(path)
end
end
function Module:resolve(name)
assert(name, "Missing name to resolve")
local debundled_name = name:match("^bundle:(.*)") or name
if debundled_name:byte(1) == 46 then -- Starts with "."
return fixedRequire(pathJoin(self.dir, name))
elseif debundled_name:byte(1) == 47 then -- Starts with "/"
return fixedRequire(name)
end
return moduleRequire(self.dir, name)
end
function Module:require(name)
assert(name, "Missing name to require")
if package.preload[name] or package.loaded[name] then
return realRequire(name)
end
-- Resolve the path
local data, path, key = self:resolve(name)
if not path then
local success, value = pcall(realRequire, name)
if success then return value end
if not success then
error("No such module '" .. name .. "' in '" .. self.path .. "'\r\n" .. value)
end
end
-- Check in the cache for this module
local module = moduleCache[key]
if module then return module.exports end
-- Put a new module in the cache if not
module = makeModule(path)
moduleCache[key] = module
local ext = path:match("%.[^/\\]+$")
if ext == ".lua" then
local fn = assert(loadstring(data, path))
local global = {
module = module,
exports = module.exports,
require = function (...)
return module:require(...)
end
}
setfenv(fn, setmetatable(global, { __index = _G }))
local ret = fn()
-- Allow returning the exports as well
if ret then module.exports = ret end
elseif ext == binExt then
local fnName = "luaopen_" .. name:match("[^/]+$"):match("^[^%.]+")
local fn, err
local realPath = uv.fs_access(path, "r") and path or uv.fs_access(key, "r") and key
if realPath then
-- If it's a real file, load it directly
fn, err = package.loadlib(realPath, fnName)
if not fn then
error(realPath .. "#" .. fnName .. ": " .. err)
end
else
-- Otherwise, copy to a temporary folder and read from there
local dir = assert(uv.fs_mkdtemp(pathJoin(tmpBase, "lib-XXXXXX")))
path = pathJoin(dir, path:match("[^/\\]+$"))
local fd = uv.fs_open(path, "w", 384) -- 0600
uv.fs_write(fd, data, 0)
uv.fs_close(fd)
fn, err = package.loadlib(path, fnName)
if not fn then
error(path .. "#" .. fnName .. ": " .. err)
end
uv.fs_unlink(path)
uv.fs_rmdir(dir)
end
module.exports = fn()
else
error("Unknown type at '" .. path .. "' for '" .. name .. "' in '" .. self.path .. "'")
end
return module.exports
end
local function generator(modulePath)
assert(modulePath, "Missing path to require generator")
local module = makeModule(modulePath)
local function require(...)
return module:require(...)
end
return require, module
end
return generator
| apache-2.0 |
mstorchak/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/cpu.lua | 74 | 1429 | -- stat/cpu collector
local function scrape()
local stat = get_contents("/proc/stat")
-- system boot time, seconds since epoch
metric("node_boot_time_seconds", "gauge", nil,
string.match(stat, "btime ([0-9]+)"))
-- context switches since boot (all CPUs)
metric("node_context_switches_total", "counter", nil,
string.match(stat, "ctxt ([0-9]+)"))
-- cpu times, per CPU, per mode
local cpu_mode = {"user", "nice", "system", "idle", "iowait", "irq",
"softirq", "steal", "guest", "guest_nice"}
local i = 0
local cpu_metric = metric("node_cpu_seconds_total", "counter")
while true do
local cpu = {string.match(stat,
"cpu"..i.." (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+)")}
if #cpu ~= 10 then
break
end
for ii, mode in ipairs(cpu_mode) do
cpu_metric({cpu="cpu"..i, mode=mode}, cpu[ii] / 100)
end
i = i + 1
end
-- interrupts served
metric("node_intr_total", "counter", nil,
string.match(stat, "intr ([0-9]+)"))
-- processes forked
metric("node_forks_total", "counter", nil,
string.match(stat, "processes ([0-9]+)"))
-- processes running
metric("node_procs_running_total", "gauge", nil,
string.match(stat, "procs_running ([0-9]+)"))
-- processes blocked for I/O
metric("node_procs_blocked_total", "gauge", nil,
string.match(stat, "procs_blocked ([0-9]+)"))
end
return { scrape = scrape }
| gpl-2.0 |
rekotc/game-engine-demo | Source/GCC4/3rdParty/luaplus51-all/Src/Modules/wxLua/samples/calculator.wx.lua | 2 | 14664 | -------------------------------------------------------------------------=---
-- Name: Calculator.wx.lua
-- Purpose: Calculator wxLua sample
-- Author: J Winwood
-- Based on the wxWidgets sample by Marco Ghislanzoni
-- Created: March 2002
-- Updated January 2003 to use XML resources
-- Copyright: (c) 2002-2003 Lomtick Software. All rights reserved.
-- Licence: wxWidgets licence
-------------------------------------------------------------------------=---
-- Load the wxLua module, does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit
package.cpath = package.cpath..";./?.dll;./?.so;../lib/?.so;../lib/vc_dll/?.dll;../lib/bcc_dll/?.dll;../lib/mingw_dll/?.dll;"
require("wx")
-- ---------------------------------------------------------------------------
-- Global variables
dialog = nil -- the wxDialog main toplevel window
xmlResource = nil -- the XML resource handle
txtDisplay = nil -- statictext window for the display
clearDisplay = false
lastNumber = 0 -- the last number pressed, 0 - 9
lastOperationId = nil -- the window id of last operation button pressed
local xpmdata =
{
"16 15 5 1",
" c None",
"a c Black",
"b c #FFFFFF",
"c c #808080",
"d c #9DBDCD",
" aaaaaaaaaaaa ",
" addddddddddac ",
" adaaaaaaaadac ",
" adabbbbbbadac ",
" adabbbbbbadac ",
" adaaaaaaaadac ",
" addddddddddac ",
" adaadaadaadac ",
" adaadaadaadac ",
" addddddddddac ",
" adaadaadaadac ",
" adaadaadaadac ",
" addddddddddac ",
" aaaaaaaaaaaac ",
" ccccccccccccc "
}
-- ---------------------------------------------------------------------------
-- return the path part of the currently executing file
function GetExePath()
local function findLast(filePath) -- find index of last / or \ in string
local lastOffset = nil
local offset = nil
repeat
offset = string.find(filePath, "\\") or string.find(filePath, "/")
if offset then
lastOffset = (lastOffset or 0) + offset
filePath = string.sub(filePath, offset + 1)
end
until not offset
return lastOffset
end
local filePath = debug.getinfo(1, "S").source
if string.byte(filePath) == string.byte('@') then
local offset = findLast(filePath)
if offset ~= nil then
-- remove the @ at the front up to just before the path separator
filePath = string.sub(filePath, 2, offset - 1)
else
filePath = "."
end
else
filePath = wx.wxGetCwd()
end
return filePath
end
-- ---------------------------------------------------------------------------
-- Handle the clear button event
function OnClear(event)
txtDisplay:SetLabel("0")
lastNumber = 0
lastOperationId = ID_PLUS
end
-- ---------------------------------------------------------------------------
-- Handle all number button events
function OnNumber(event)
local numberId = event:GetId()
local displayString = txtDisplay:GetLabel()
if (displayString == "0") or (tonumber(displayString) == nil) or clearDisplay then
displayString = ""
end
clearDisplay = false
-- Limit string length to 12 chars
if string.len(displayString) < 12 then
if numberId == ID_DECIMAL then
if not string.find(displayString, ".", 1, 1) then
-- If the first pressed char is "." then we want "0."
if string.len(displayString) == 0 then
displayString = displayString.."0."
else
displayString = displayString.."."
end
end
else
-- map button window ids to numeric values
local idTable = { [ID_0] = 0, [ID_1] = 1, [ID_2] = 2, [ID_3] = 3,
[ID_4] = 4, [ID_5] = 5, [ID_6] = 6, [ID_7] = 7,
[ID_8] = 8, [ID_9] = 9 }
local num = idTable[numberId]
-- If first character entered is 0 we reject it
if (num == 0) and (string.len(displayString) == 0) then
displayString = "0"
elseif displayString == "" then
displayString = tostring(num)
else
displayString = displayString..num
end
end
txtDisplay:SetLabel(displayString)
end
end
-- ---------------------------------------------------------------------------
-- Calculate the operation
function DoOperation(a, b, operationId)
local result = a
if operationId == ID_PLUS then
result = b + a
elseif operationId == ID_MINUS then
result = b - a
elseif operationId == ID_MULTIPLY then
result = b * a
elseif operationId == ID_DIVIDE then
if a == 0 then
result = "Divide by zero error"
else
result = b / a
end
end
return result
end
-- ---------------------------------------------------------------------------
-- Handle all operation button events
function OnOperator(event)
-- Get display content
local displayString = txtDisplay:GetLabel()
local currentNumber = tonumber(displayString)
-- if error message was shown, zero output and ignore operator
if ((currentNumber == nil) or (lastNumber == nil)) then
lastNumber = 0
return
end
-- Get the required lastOperationId
local operationId = event:GetId()
displayString = DoOperation(currentNumber, lastNumber, lastOperationId)
lastNumber = tonumber(displayString)
if (lastOperationId ~= ID_EQUALS) or (operationId == ID_EQUALS) then
txtDisplay:SetLabel(tostring(displayString))
end
clearDisplay = true
lastOperationId = operationId
end
-- ---------------------------------------------------------------------------
-- Handle the quit button event
function OnQuit(event)
event:Skip()
wx.wxMessageBox("wxLua calculator sample based on the calc sample written by Marco Ghislanzoni.\n"..
wxlua.wxLUA_VERSION_STRING.." built with "..wx.wxVERSION_STRING,
"wxLua Calculator",
wx.wxOK + wx.wxICON_INFORMATION, dialog)
dialog:Show(false)
dialog:Destroy()
end
-- ---------------------------------------------------------------------------
-- The main program as a function (makes it easy to exit on error)
function main()
-- xml style resources (if present)
xmlResource = wx.wxXmlResource()
xmlResource:InitAllHandlers()
local xrcFilename = GetExePath().."/calculator.xrc"
local logNo = wx.wxLogNull() -- silence wxXmlResource error msg since we provide them
-- try to load the resource and ask for path to it if not found
while not xmlResource:Load(xrcFilename) do
-- must unload the file before we try again
xmlResource:Unload(xrcFilename)
wx.wxMessageBox("Error loading xrc resources, please choose the path to 'calculator.xrc'.",
"Calculator",
wx.wxOK + wx.wxICON_EXCLAMATION,
wx.NULL)
local fileDialog = wx.wxFileDialog(wx.NULL,
"Open 'calculator.xrc' resource file",
"",
"calculator.xrc",
"XRC files (*.xrc)|*.xrc|All files (*)|*",
wx.wxOPEN + wx.wxFILE_MUST_EXIST)
if fileDialog:ShowModal() == wx.wxID_OK then
xrcFilename = fileDialog:GetPath()
else
return -- quit program
end
end
logNo:delete() -- turn error messages back on
dialog = wx.wxDialog()
if not xmlResource:LoadDialog(dialog, wx.NULL, "Calculator") then
wx.wxMessageBox("Error loading xrc resources!",
"Calculator",
wx.wxOK + wx.wxICON_EXCLAMATION,
wx.NULL)
return -- quit program
end
-- -----------------------------------------------------------------------
-- This is a little awkward, but it's how it's done in C++ too
local bitmap = wx.wxBitmap(xpmdata)
local icon = wx.wxIcon()
icon:CopyFromBitmap(bitmap)
dialog:SetIcon(icon)
bitmap:delete()
icon:delete()
bestSize = dialog:GetBestSize()
dialog:SetSize(bestSize:GetWidth()/2, bestSize:GetHeight())
dialog:SetSizeHints(bestSize:GetWidth()/2, bestSize:GetHeight())
-- initialize the txtDisplay and verify that it's ok
txtDisplay = dialog:FindWindow(xmlResource.GetXRCID("ID_TEXT"))
if not txtDisplay then
wx.wxMessageBox('Unable to find window "ID_TEXT" in the dialog',
"Calculator",
wx.wxOK + wx.wxICON_EXCLAMATION,
wx.NULL)
dialog:Destroy()
return
end
if not txtDisplay:DynamicCast("wxStaticText") then
wx.wxMessageBox('window "ID_TEXT" is not a "wxStaticText" or is not derived from it"',
"Calculator",
wx.wxOK + wx.wxICON_EXCLAMATION,
wx.NULL)
dialog:Destroy()
return
end
txtDisplay:SetLabel("0")
-- init global wxWindow ID values
ID_0 = xmlResource.GetXRCID("ID_0")
ID_1 = xmlResource.GetXRCID("ID_1")
ID_2 = xmlResource.GetXRCID("ID_2")
ID_3 = xmlResource.GetXRCID("ID_3")
ID_4 = xmlResource.GetXRCID("ID_4")
ID_5 = xmlResource.GetXRCID("ID_5")
ID_6 = xmlResource.GetXRCID("ID_6")
ID_7 = xmlResource.GetXRCID("ID_7")
ID_8 = xmlResource.GetXRCID("ID_8")
ID_9 = xmlResource.GetXRCID("ID_9")
ID_DECIMAL = xmlResource.GetXRCID("ID_DECIMAL")
ID_EQUALS = xmlResource.GetXRCID("ID_EQUALS")
ID_PLUS = xmlResource.GetXRCID("ID_PLUS")
ID_MINUS = xmlResource.GetXRCID("ID_MINUS")
ID_MULTIPLY = xmlResource.GetXRCID("ID_MULTIPLY")
ID_DIVIDE = xmlResource.GetXRCID("ID_DIVIDE")
ID_OFF = xmlResource.GetXRCID("ID_OFF")
ID_CLEAR = xmlResource.GetXRCID("ID_CLEAR")
lastOperationId = ID_PLUS
dialog:Connect(ID_0, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_1, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_2, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_3, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_4, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_5, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_6, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_7, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_8, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_9, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_DECIMAL, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnNumber)
dialog:Connect(ID_EQUALS, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnOperator)
dialog:Connect(ID_PLUS, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnOperator)
dialog:Connect(ID_MINUS, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnOperator)
dialog:Connect(ID_MULTIPLY, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnOperator)
dialog:Connect(ID_DIVIDE, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnOperator)
dialog:Connect(ID_OFF, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnQuit)
dialog:Connect(ID_CLEAR, wx.wxEVT_COMMAND_BUTTON_CLICKED, OnClear)
dialog:Connect(wx.wxEVT_CLOSE_WINDOW, OnQuit)
accelTable = wx.wxAcceleratorTable({
{ wx.wxACCEL_NORMAL, string.byte('0'), ID_0 },
{ wx.wxACCEL_NORMAL, string.byte('1'), ID_1 },
{ wx.wxACCEL_NORMAL, string.byte('2'), ID_2 },
{ wx.wxACCEL_NORMAL, string.byte('3'), ID_3 },
{ wx.wxACCEL_NORMAL, string.byte('4'), ID_4 },
{ wx.wxACCEL_NORMAL, string.byte('5'), ID_5 },
{ wx.wxACCEL_NORMAL, string.byte('6'), ID_6 },
{ wx.wxACCEL_NORMAL, string.byte('7'), ID_7 },
{ wx.wxACCEL_NORMAL, string.byte('8'), ID_8 },
{ wx.wxACCEL_NORMAL, string.byte('9'), ID_9 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD0, ID_0 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD1, ID_1 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD2, ID_2 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD3, ID_3 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD4, ID_4 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD5, ID_5 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD6, ID_6 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD7, ID_7 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD8, ID_8 },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD9, ID_9 },
{ wx.wxACCEL_NORMAL, string.byte('.'), ID_DECIMAL },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD_DECIMAL, ID_DECIMAL },
{ wx.wxACCEL_NORMAL, string.byte('='), ID_EQUALS },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD_ENTER, ID_EQUALS },
{ wx.wxACCEL_NORMAL, 13, ID_EQUALS },
{ wx.wxACCEL_NORMAL, string.byte('+'), ID_PLUS },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD_ADD, ID_PLUS },
{ wx.wxACCEL_NORMAL, string.byte('-'), ID_MINUS },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD_SUBTRACT, ID_MINUS },
{ wx.wxACCEL_NORMAL, string.byte('*'), ID_MULTIPLY },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD_MULTIPLY, ID_MULTIPLY },
{ wx.wxACCEL_NORMAL, string.byte('/'), ID_DIVIDE },
{ wx.wxACCEL_NORMAL, wx.VXK_NUMPAD_DIVIDE, ID_DIVIDE },
{ wx.wxACCEL_NORMAL, string.byte('C'), ID_CLEAR },
{ wx.wxACCEL_NORMAL, string.byte('c'), ID_CLEAR },
{ wx.wxACCEL_NORMAL, wx.WXK_ESCAPE, ID_OFF }
})
dialog:SetAcceleratorTable(accelTable)
dialog:Centre()
dialog:Show(true)
end
main()
-- Call wx.wxGetApp():MainLoop() last to start the wxWidgets event loop,
-- otherwise the wxLua program will exit immediately.
-- Does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit since the
-- MainLoop is already running or will be started by the C++ program.
wx.wxGetApp():MainLoop()
| lgpl-3.0 |
n0xus/darkstar | scripts/zones/Temenos/mobs/Air_Elemental.lua | 16 | 1706 | -----------------------------------
-- Area: Temenos E T
-- NPC: Air_Elemental
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobID = mob:getID();
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
switch (mobID): caseof {
-- 100 a 106 inclut (Temenos -Northern Tower )
[16928858] = function (x)
GetNPCByID(16928768+181):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+181):setStatus(STATUS_NORMAL);
end ,
[16928859] = function (x)
GetNPCByID(16928768+217):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+217):setStatus(STATUS_NORMAL);
end ,
[16928860] = function (x)
GetNPCByID(16928768+348):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+348):setStatus(STATUS_NORMAL);
end ,
[16928861] = function (x)
GetNPCByID(16928768+46):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+46):setStatus(STATUS_NORMAL);
end ,
[16929035] = function (x)
if (IsMobDead(16929036)==false) then
DespawnMob(16929036);
SpawnMob(16929042);
end
end ,
}
end; | gpl-3.0 |
n0xus/darkstar | scripts/zones/Buburimu_Peninsula/npcs/Five_of_Spades.lua | 17 | 1483 | -----------------------------------
-- Area: Buburimu Peninsula
-- NPC: Five of Spades
-- Invloved in quests: A Greeting Cardian
-----------------------------------
package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Buburimu_Peninsula/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local AGreetingCardian = player:getQuestStatus(WINDURST,A_GREETING_CARDIAN);
local AGCcs = player:getVar("AGreetingCardian_Event");
if (AGreetingCardian == QUEST_ACCEPTED and AGCcs == 4) then
player:startEvent(0x0001); -- A Greeting Cardian step three
else player:showText(npc,FIVEOFSPADES_DIALOG); -- Standard Dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0001) then
player:setVar("AGreetingCardian_Event",5);
end
end;
| gpl-3.0 |
DEVOmarReal/Omar-Real | plugins/weclome.lua | 1 | 3355 | do
local function run(msg, matches)
local r = get_receiver(msg)
local welc = 'oo:'..msg.to.id
local bay = 'zz:'..msg.to.id
local xxxx = redis:get(welc)
local zzzz = redis:get(bay)
if is_momod(msg) and matches[1]== 'ضع الترحيب' then
redis:set(welc, matches[2])
local text = 'تم ✅ وضع الترحيب في المجموعة 👥👋🏿'..'\n\n'..matches[2]
return reply_msg(msg.id, text, ok_cb, false)
elseif redis:get(welc) and is_momod(msg) and matches[1]== 'ازالة الترحيب' then
redis:del(welc)
local text = 'تم ✅ حذف الترحيب في المجموعة 👥👋🏿'
return reply_msg(msg.id, text, ok_cb, false)
elseif not redis:get(welc) and is_momod(msg) and matches[1]== 'ازالة الترحيب' then
local text = 'الترحيب ✋🏿 محذوف سابقا 👥✔️'
return reply_msg(msg.id, text, ok_cb, false)
elseif redis:get(welc) and is_momod(msg) and matches[1]== 'الترحيب' then
return reply_msg(msg.id, xxxx, ok_cb, true)
elseif not redis:get(welc) and is_momod(msg) and matches[1]== 'الترحيب' then
return 'قم بأضافة 🔶 ترحيب اولا 👥🔕 '
end
if is_momod(msg) and matches[1]== 'ضع التوديع' then
redis:set(bay, matches[2])
local text = 'تم ✅ وضع التوديع في المجموعة 👥👋🏿'..'\n\n'..matches[2]
return reply_msg(msg.id, text, ok_cb, false)
elseif redis:get(bay) and is_momod(msg) and matches[1]== 'ازالة التوديع' then
redis:del(bay)
local text = 'تم ✅ حذف التوديع في المجموعة 👥👋🏿'
return reply_msg(msg.id, text, ok_cb, false)
elseif not redis:get(bay) and is_momod(msg) and matches[1]== 'ازالة التوديع' then
local text = ' التوديع ✋🏿 محذوف سابقا 👥✔️'
return reply_msg(msg.id, text, ok_cb, false)
elseif redis:get(bay) and is_momod(msg) and matches[1]== 'التوديع' then
return reply_msg(msg.id, zzzz, ok_cb, true)
elseif not redis:get(bay) and is_momod(msg) and matches[1]== 'التوديع' then
return 'قم بأضافة 🔶 توديع اولا 👥🔕'
end
if redis:get(bay) and matches[1]== 'chat_del_user' then
return reply_msg(msg.id, zzzz, ok_cb, true)
elseif redis:get(welc) and matches[1]== 'chat_add_user' then
local xxxx = ""..redis:get(welc).."\n"
..''..(msg.action.user.print_name or '')..'\n'
reply_msg(msg.id, xxxx, ok_cb, true)
elseif redis:get(welc) and matches[1]== 'chat_add_user_link' then
local xxxx = ""..redis:get(welc).."\n"
..'@'..(msg.from.username or '')..'\n'
reply_msg(msg.id, xxxx, ok_cb, true)
end
end
return {
patterns = {
"^[!/#](ضع الترحيب) (.*)$",
"^[!/#](ضع التوديع) (.*)$",
"^[!/#](ازالة الترحيب)$",
"^[!/#](ازالة التوديع)$",
"^[!/#](الترحيب)$",
"^[!/#](التوديع)$",
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$"
},
run = run,
}
end
| gpl-2.0 |
Azmaedus/GarrisonJukeBox | libs/AceGUI-3.0/widgets/AceGUIContainer-Window.lua | 7 | 9849 | local AceGUI = LibStub("AceGUI-3.0")
-- Lua APIs
local pairs, assert, type = pairs, assert, type
-- WoW APIs
local PlaySound = PlaySound
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontNormal
----------------
-- Main Frame --
----------------
--[[
Events :
OnClose
]]
do
local Type = "Window"
local Version = 6
local function frameOnShow(this)
this.obj:Fire("OnShow")
end
local function frameOnClose(this)
this.obj:Fire("OnClose")
end
local function closeOnClick(this)
PlaySound(799) -- SOUNDKIT.GS_TITLE_OPTION_EXIT
this.obj:Hide()
end
local function frameOnMouseDown(this)
AceGUI:ClearFocus()
end
local function titleOnMouseDown(this)
this:GetParent():StartMoving()
AceGUI:ClearFocus()
end
local function frameOnMouseUp(this)
local frame = this:GetParent()
frame:StopMovingOrSizing()
local self = frame.obj
local status = self.status or self.localstatus
status.width = frame:GetWidth()
status.height = frame:GetHeight()
status.top = frame:GetTop()
status.left = frame:GetLeft()
end
local function sizerseOnMouseDown(this)
this:GetParent():StartSizing("BOTTOMRIGHT")
AceGUI:ClearFocus()
end
local function sizersOnMouseDown(this)
this:GetParent():StartSizing("BOTTOM")
AceGUI:ClearFocus()
end
local function sizereOnMouseDown(this)
this:GetParent():StartSizing("RIGHT")
AceGUI:ClearFocus()
end
local function sizerOnMouseUp(this)
this:GetParent():StopMovingOrSizing()
end
local function SetTitle(self,title)
self.titletext:SetText(title)
end
local function SetStatusText(self,text)
-- self.statustext:SetText(text)
end
local function Hide(self)
self.frame:Hide()
end
local function Show(self)
self.frame:Show()
end
local function OnAcquire(self)
self.frame:SetParent(UIParent)
self.frame:SetFrameStrata("FULLSCREEN_DIALOG")
self:ApplyStatus()
self:EnableResize(true)
self:Show()
end
local function OnRelease(self)
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
end
-- called to set an external table to store status in
local function SetStatusTable(self, status)
assert(type(status) == "table")
self.status = status
self:ApplyStatus()
end
local function ApplyStatus(self)
local status = self.status or self.localstatus
local frame = self.frame
self:SetWidth(status.width or 700)
self:SetHeight(status.height or 500)
if status.top and status.left then
frame:SetPoint("TOP",UIParent,"BOTTOM",0,status.top)
frame:SetPoint("LEFT",UIParent,"LEFT",status.left,0)
else
frame:SetPoint("CENTER",UIParent,"CENTER")
end
end
local function OnWidthSet(self, width)
local content = self.content
local contentwidth = width - 34
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
end
local function OnHeightSet(self, height)
local content = self.content
local contentheight = height - 57
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end
local function EnableResize(self, state)
local func = state and "Show" or "Hide"
self.sizer_se[func](self.sizer_se)
self.sizer_s[func](self.sizer_s)
self.sizer_e[func](self.sizer_e)
end
local function Constructor()
local frame = CreateFrame("Frame",nil,UIParent)
local self = {}
self.type = "Window"
self.Hide = Hide
self.Show = Show
self.SetTitle = SetTitle
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.SetStatusText = SetStatusText
self.SetStatusTable = SetStatusTable
self.ApplyStatus = ApplyStatus
self.OnWidthSet = OnWidthSet
self.OnHeightSet = OnHeightSet
self.EnableResize = EnableResize
self.localstatus = {}
self.frame = frame
frame.obj = self
frame:SetWidth(700)
frame:SetHeight(500)
frame:SetPoint("CENTER",UIParent,"CENTER",0,0)
frame:EnableMouse()
frame:SetMovable(true)
frame:SetResizable(true)
frame:SetFrameStrata("FULLSCREEN_DIALOG")
frame:SetScript("OnMouseDown", frameOnMouseDown)
frame:SetScript("OnShow",frameOnShow)
frame:SetScript("OnHide",frameOnClose)
frame:SetMinResize(240,240)
frame:SetToplevel(true)
local titlebg = frame:CreateTexture(nil, "BACKGROUND")
titlebg:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Title-Background]])
titlebg:SetPoint("TOPLEFT", 9, -6)
titlebg:SetPoint("BOTTOMRIGHT", frame, "TOPRIGHT", -28, -24)
local dialogbg = frame:CreateTexture(nil, "BACKGROUND")
dialogbg:SetTexture([[Interface\Tooltips\UI-Tooltip-Background]])
dialogbg:SetPoint("TOPLEFT", 8, -24)
dialogbg:SetPoint("BOTTOMRIGHT", -6, 8)
dialogbg:SetVertexColor(0, 0, 0, .75)
local topleft = frame:CreateTexture(nil, "BORDER")
topleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
topleft:SetWidth(64)
topleft:SetHeight(64)
topleft:SetPoint("TOPLEFT")
topleft:SetTexCoord(0.501953125, 0.625, 0, 1)
local topright = frame:CreateTexture(nil, "BORDER")
topright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
topright:SetWidth(64)
topright:SetHeight(64)
topright:SetPoint("TOPRIGHT")
topright:SetTexCoord(0.625, 0.75, 0, 1)
local top = frame:CreateTexture(nil, "BORDER")
top:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
top:SetHeight(64)
top:SetPoint("TOPLEFT", topleft, "TOPRIGHT")
top:SetPoint("TOPRIGHT", topright, "TOPLEFT")
top:SetTexCoord(0.25, 0.369140625, 0, 1)
local bottomleft = frame:CreateTexture(nil, "BORDER")
bottomleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottomleft:SetWidth(64)
bottomleft:SetHeight(64)
bottomleft:SetPoint("BOTTOMLEFT")
bottomleft:SetTexCoord(0.751953125, 0.875, 0, 1)
local bottomright = frame:CreateTexture(nil, "BORDER")
bottomright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottomright:SetWidth(64)
bottomright:SetHeight(64)
bottomright:SetPoint("BOTTOMRIGHT")
bottomright:SetTexCoord(0.875, 1, 0, 1)
local bottom = frame:CreateTexture(nil, "BORDER")
bottom:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottom:SetHeight(64)
bottom:SetPoint("BOTTOMLEFT", bottomleft, "BOTTOMRIGHT")
bottom:SetPoint("BOTTOMRIGHT", bottomright, "BOTTOMLEFT")
bottom:SetTexCoord(0.376953125, 0.498046875, 0, 1)
local left = frame:CreateTexture(nil, "BORDER")
left:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
left:SetWidth(64)
left:SetPoint("TOPLEFT", topleft, "BOTTOMLEFT")
left:SetPoint("BOTTOMLEFT", bottomleft, "TOPLEFT")
left:SetTexCoord(0.001953125, 0.125, 0, 1)
local right = frame:CreateTexture(nil, "BORDER")
right:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
right:SetWidth(64)
right:SetPoint("TOPRIGHT", topright, "BOTTOMRIGHT")
right:SetPoint("BOTTOMRIGHT", bottomright, "TOPRIGHT")
right:SetTexCoord(0.1171875, 0.2421875, 0, 1)
local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
close:SetPoint("TOPRIGHT", 2, 1)
close:SetScript("OnClick", closeOnClick)
self.closebutton = close
close.obj = self
local titletext = frame:CreateFontString(nil, "ARTWORK")
titletext:SetFontObject(GameFontNormal)
titletext:SetPoint("TOPLEFT", 12, -8)
titletext:SetPoint("TOPRIGHT", -32, -8)
self.titletext = titletext
local title = CreateFrame("Button", nil, frame)
title:SetPoint("TOPLEFT", titlebg)
title:SetPoint("BOTTOMRIGHT", titlebg)
title:EnableMouse()
title:SetScript("OnMouseDown",titleOnMouseDown)
title:SetScript("OnMouseUp", frameOnMouseUp)
self.title = title
local sizer_se = CreateFrame("Frame",nil,frame)
sizer_se:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0)
sizer_se:SetWidth(25)
sizer_se:SetHeight(25)
sizer_se:EnableMouse()
sizer_se:SetScript("OnMouseDown",sizerseOnMouseDown)
sizer_se:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_se = sizer_se
local line1 = sizer_se:CreateTexture(nil, "BACKGROUND")
self.line1 = line1
line1:SetWidth(14)
line1:SetHeight(14)
line1:SetPoint("BOTTOMRIGHT", -8, 8)
line1:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
local x = 0.1 * 14/17
line1:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)
local line2 = sizer_se:CreateTexture(nil, "BACKGROUND")
self.line2 = line2
line2:SetWidth(8)
line2:SetHeight(8)
line2:SetPoint("BOTTOMRIGHT", -8, 8)
line2:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
local x = 0.1 * 8/17
line2:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)
local sizer_s = CreateFrame("Frame",nil,frame)
sizer_s:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-25,0)
sizer_s:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",0,0)
sizer_s:SetHeight(25)
sizer_s:EnableMouse()
sizer_s:SetScript("OnMouseDown",sizersOnMouseDown)
sizer_s:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_s = sizer_s
local sizer_e = CreateFrame("Frame",nil,frame)
sizer_e:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,25)
sizer_e:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0)
sizer_e:SetWidth(25)
sizer_e:EnableMouse()
sizer_e:SetScript("OnMouseDown",sizereOnMouseDown)
sizer_e:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_e = sizer_e
--Container Support
local content = CreateFrame("Frame",nil,frame)
self.content = content
content.obj = self
content:SetPoint("TOPLEFT",frame,"TOPLEFT",12,-32)
content:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-12,13)
AceGUI:RegisterAsContainer(self)
return self
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
end
| gpl-2.0 |
RyanTech/LoveLink | Resources/Deprecated.lua | 8 | 32784 | --tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of _G will be deprecated begin
local function ccpLineIntersect(a,b,c,d,s,t)
deprecatedTip("ccpLineIntersect","CCPoint:isLineIntersect")
return CCPoint:isLineIntersect(a,b,c,d,s,t)
end
rawset(_G,"ccpLineIntersect",ccpLineIntersect)
local function CCPointMake(x,y)
deprecatedTip("CCPointMake(x,y)","CCPoint(x,y)")
return CCPoint(x,y)
end
rawset(_G,"CCPointMake",CCPointMake)
local function ccp(x,y)
deprecatedTip("ccp(x,y)","CCPoint(x,y)")
return CCPoint(x,y)
end
rawset(_G,"ccp",ccp)
local function CCSizeMake(width,height)
deprecatedTip("CCSizeMake(width,height)","CCSize(width,height)")
return CCSize(width,height)
end
rawset(_G,"CCSizeMake",CCSizeMake)
local function CCRectMake(x,y,width,height)
deprecatedTip("CCRectMake(x,y,width,height)","CCRect(x,y,width,height)")
return CCRect(x,y,width,height)
end
rawset(_G,"CCRectMake",CCRectMake)
local function ccpNeg(pt)
deprecatedTip("ccpNeg","CCPoint.__sub")
return CCPoint.__sub(CCPoint:new_local(0,0),pt)
end
rawset(_G,"ccpNeg",ccpNeg)
local function ccpAdd(pt1,pt2)
deprecatedTip("ccpAdd","CCPoint.__add")
return CCPoint.__add(pt1,pt2)
end
rawset(_G,"ccpAdd",ccpAdd)
local function ccpSub(pt1,pt2)
deprecatedTip("ccpSub","CCPoint.__sub")
return CCPoint.__sub(pt1,pt2)
end
rawset(_G,"ccpSub",ccpSub)
local function ccpMult(pt,factor)
deprecatedTip("ccpMult","CCPoint.__mul")
return CCPoint.__mul(pt,factor)
end
rawset(_G,"ccpMult",ccpMult)
local function ccpMidpoint(pt1,pt2)
deprecatedTip("ccpMidpoint","CCPoint:getMidpoint")
return pt1:getMidpoint(pt2)
end
rawset(_G,"ccpMidpoint",ccpMidpoint)
local function ccpDot(pt1,pt2)
deprecatedTip("ccpDot","CCPoint:dot")
return pt1:dot(pt2)
end
rawset(_G,"ccpDot",ccpDot)
local function ccpCross(pt1,pt2)
deprecatedTip("ccpCross","CCPoint:cross")
return pt1:cross(pt2)
end
rawset(_G,"ccpCross",ccpCross)
local function ccpPerp(pt)
deprecatedTip("ccpPerp","CCPoint:getPerp")
return pt:getPerp()
end
rawset(_G,"ccpPerp",ccpPerp)
local function ccpRPerp(pt)
deprecatedTip("ccpRPerp","CCPoint:getRPerp")
return pt:getRPerp()
end
rawset(_G,"ccpRPerp",ccpRPerp)
local function ccpProject(pt1,pt2)
deprecatedTip("ccpProject","CCPoint:project")
return pt1:project(pt2)
end
rawset(_G,"ccpProject",ccpProject)
local function ccpRotate(pt1,pt2)
deprecatedTip("ccpRotate","CCPoint:rotate")
return pt1:rotate(pt2)
end
rawset(_G,"ccpRotate",ccpRotate)
local function ccpUnrotate(pt1,pt2)
deprecatedTip("ccpUnrotate","CCPoint:unrotate")
return pt1:unrotate(pt2)
end
rawset(_G,"ccpUnrotate",ccpUnrotate)
local function ccpLengthSQ(pt)
deprecatedTip("ccpLengthSQ","CCPoint:getLengthSq")
return pt:getLengthSq(pt)
end
rawset(_G,"ccpLengthSQ",ccpLengthSQ)
local function ccpDistanceSQ(pt1,pt2)
deprecatedTip("ccpDistanceSQ","CCPoint:__sub(pt1,pt2):getLengthSq")
return (CCPoint.__sub(pt1,pt2)):getLengthSq()
end
rawset(_G,"ccpDistanceSQ",ccpDistanceSQ)
local function ccpLength(pt)
deprecatedTip("ccpLength","CCPoint:getLength")
return pt:getLength()
end
rawset(_G,"ccpLength",ccpLength)
local function ccpDistance(pt1,pt2)
deprecatedTip("ccpDistance","CCPoint:getDistance")
return pt1:getDistance(pt2)
end
rawset(_G,"ccpDistance",ccpDistance)
local function ccpNormalize(pt)
deprecatedTip("ccpNormalize","CCPoint:normalize")
return pt:normalize()
end
rawset(_G,"ccpNormalize",ccpNormalize)
local function ccpForAngle(angle)
deprecatedTip("ccpForAngle","CCPoint:forAngle")
return CCPoint:forAngle(angle)
end
rawset(_G,"ccpForAngle",ccpForAngle)
local function ccpToAngle(pt)
deprecatedTip("ccpToAngle","CCPoint:getAngle")
return pt:getAngle()
end
rawset(_G,"ccpToAngle",ccpToAngle)
local function ccpClamp(pt1,pt2,pt3)
deprecatedTip("ccpClamp","CCPoint:getClampPoint")
return pt1:getClampPoint(pt2, pt3)
end
rawset(_G,"ccpClamp",ccpClamp)
local function ccpFromSize(sz)
deprecatedTip("ccpFromSize(sz)","CCPoint(sz)")
return CCPoint(sz)
end
rawset(_G,"ccpFromSize",ccpFromSize)
local function ccpLerp(pt1,pt2,alpha)
deprecatedTip("ccpLerp","CCPoint:lerp")
return pt1:lerp(pt2,alpha)
end
rawset(_G,"ccpLerp",ccpLerp)
local function ccpFuzzyEqual(pt1,pt2,variance)
deprecatedTip("ccpFuzzyEqual","CCPoint:fuzzyEquals")
return pt1:fuzzyEquals(pt2,variance)
end
rawset(_G,"ccpFuzzyEqual",ccpFuzzyEqual)
local function ccpCompMult(pt1,pt2)
deprecatedTip("ccpCompMult","CCPoint")
return CCPoint(pt1.x * pt2.x , pt1.y * pt2.y)
end
rawset(_G,"ccpCompMult",ccpCompMult)
local function ccpAngleSigned(pt1,pt2)
deprecatedTip("ccpAngleSigned","CCPoint:getAngle")
return pt1:getAngle(pt2)
end
rawset(_G,"ccpAngleSigned",ccpAngleSigned)
local function ccpAngle(pt1,pt2)
deprecatedTip("ccpAngle","CCPoint:getAngle")
return pt1:getAngle(pt2)
end
rawset(_G,"ccpAngle",ccpAngle)
local function ccpRotateByAngle(pt1,pt2,angle)
deprecatedTip("ccpRotateByAngle","CCPoint:rotateByAngle")
return pt1:rotateByAngle(pt2, angle)
end
rawset(_G,"ccpRotateByAngle",ccpRotateByAngle)
local function ccpSegmentIntersect(pt1,pt2,pt3,pt4)
deprecatedTip("ccpSegmentIntersect","CCPoint:isSegmentIntersect")
return CCPoint:isSegmentIntersect(pt1,pt2,pt3,pt4)
end
rawset(_G,"ccpSegmentIntersect",ccpSegmentIntersect)
local function ccpIntersectPoint(pt1,pt2,pt3,pt4)
deprecatedTip("ccpIntersectPoint","CCPoint:getIntersectPoint")
return CCPoint:getIntersectPoint(pt1,pt2,pt3,pt4)
end
rawset(_G,"ccpIntersectPoint",ccpIntersectPoint)
local function ccc3(r,g,b)
deprecatedTip("ccc3(r,g,b)","ccColor3B(r,g,b)")
return ccColor3B(r,g,b)
end
rawset(_G,"ccc3",ccc3)
local function ccc4(r,g,b,a)
deprecatedTip("ccc4(r,g,b,a)","Color4B(r,g,b,a)")
return Color4B(r,g,b,a)
end
rawset(_G,"ccc4",ccc4)
local function ccc4FFromccc3B(color3B)
deprecatedTip("ccc4FFromccc3B(color3B)","Color4F(color3B.r / 255.0,color3B.g / 255.0,color3B.b / 255.0,1.0)")
return Color4F(color3B.r/255.0, color3B.g/255.0, color3B.b/255.0, 1.0)
end
rawset(_G,"ccc4FFromccc3B",ccc4FFromccc3B)
local function ccc4f(r,g,b,a)
deprecatedTip("ccc4f(r,g,b,a)","Color4F(r,g,b,a)")
return Color4F(r,g,b,a)
end
rawset(_G,"ccc4f",ccc4f)
local function ccc4FFromccc4B(color4B)
deprecatedTip("ccc4FFromccc4B(color4B)","Color4F(color4B.r/255.0, color4B.g/255.0, color4B.b/255.0, color4B.a/255.0)")
return Color4F(color4B.r/255.0, color4B.g/255.0, color4B.b/255.0, color4B.a/255.0)
end
rawset(_G,"ccc4FFromccc4B",ccc4FFromccc4B)
local function ccc4FEqual(a,b)
deprecatedTip("ccc4FEqual(a,b)","a:equals(b)")
return a:equals(b)
end
rawset(_G,"ccc4FEqual",ccc4FEqual)
local function vertex2(x,y)
deprecatedTip("vertex2(x,y)","Vertex2F(x,y)")
return Vertex2F(x,y)
end
rawset(_G,"vertex2",vertex2)
local function vertex3(x,y,z)
deprecatedTip("vertex3(x,y,z)","Vertex3F(x,y,z)")
return Vertex3F(x,y,z)
end
rawset(_G,"vertex3",vertex3)
local function tex2(u,v)
deprecatedTip("tex2(u,v)","Tex2F(u,v)")
return Tex2F(u,v)
end
rawset(_G,"tex2",tex2)
local function ccc4BFromccc4F(color4F)
deprecatedTip("ccc4BFromccc4F(color4F)","Color4B(color4F.r * 255.0, color4F.g * 255.0, color4F.b * 255.0, color4B.a * 255.0)")
return Color4B(color4F.r * 255.0, color4F.g * 255.0, color4F.b * 255.0, color4B.a * 255.0)
end
rawset(_G,"ccc4BFromccc4F",ccc4BFromccc4F)
local function ccColor3BDeprecated()
deprecatedTip("ccColor3B","Color3B")
return Color3B
end
_G["ccColor3B"] = ccColor3BDeprecated()
local function ccColor4BDeprecated()
deprecatedTip("ccColor4B","Color4B")
return Color4B
end
_G["ccColor4B"] = ccColor4BDeprecated()
local function ccColor4FDeprecated()
deprecatedTip("ccColor4F","Color4F")
return Color4F
end
_G["ccColor4F"] = ccColor4FDeprecated()
local function ccVertex2FDeprecated()
deprecatedTip("ccVertex2F","Vertex2F")
return Vertex2F
end
_G["ccVertex2F"] = ccVertex2FDeprecated()
local function ccVertex3FDeprecated()
deprecatedTip("ccVertex3F","Vertex3F")
return Vertex3F
end
_G["ccVertex3F"] = ccVertex3FDeprecated()
local function ccTex2FDeprecated()
deprecatedTip("ccTex2F","Tex2F")
return Tex2F
end
_G["ccTex2F"] = ccTex2FDeprecated()
local function ccPointSpriteDeprecated()
deprecatedTip("ccPointSprite","PointSprite")
return PointSprite
end
_G["ccPointSprite"] = ccPointSpriteDeprecated()
local function ccQuad2Deprecated()
deprecatedTip("ccQuad2","Quad2")
return Quad2
end
_G["ccQuad2"] = ccQuad2Deprecated()
local function ccQuad3Deprecated()
deprecatedTip("ccQuad3","Quad3")
return Quad3
end
_G["ccQuad3"] = ccQuad3Deprecated()
local function ccV2FC4BT2FDeprecated()
deprecatedTip("ccV2F_C4B_T2F","V2F_C4B_T2F")
return V2F_C4B_T2F
end
_G["ccV2F_C4B_T2F"] = ccV2FC4BT2FDeprecated()
local function ccV2FC4FT2FDeprecated()
deprecatedTip("ccV2F_C4F_T2F","V2F_C4F_T2F")
return V2F_C4F_T2F
end
_G["ccV2F_C4F_T2F"] = ccV2FC4FT2FDeprecated()
local function ccV3FC4BT2FDeprecated()
deprecatedTip("ccV3F_C4B_T2F","V3F_C4B_T2F")
return V3F_C4B_T2F
end
_G["ccV3F_C4B_T2F"] = ccV3FC4BT2FDeprecated()
local function ccV2FC4BT2FQuadDeprecated()
deprecatedTip("ccV2F_C4B_T2F_Quad","V2F_C4B_T2F_Quad")
return V2F_C4B_T2F_Quad
end
_G["ccV2F_C4B_T2F_Quad"] = ccV2FC4BT2FQuadDeprecated()
local function ccV3FC4BT2FQuadDeprecated()
deprecatedTip("ccV3F_C4B_T2F_Quad","V3F_C4B_T2F_Quad")
return V3F_C4B_T2F_Quad
end
_G["ccV3F_C4B_T2F_Quad"] = ccV3FC4BT2FQuadDeprecated()
local function ccV2FC4FT2FQuadDeprecated()
deprecatedTip("ccV2F_C4F_T2F_Quad","V2F_C4F_T2F_Quad")
return V2F_C4F_T2F_Quad
end
_G["ccV2F_C4F_T2F_Quad"] = ccV2FC4FT2FQuadDeprecated()
local function ccBlendFuncDeprecated()
deprecatedTip("ccBlendFunc","BlendFunc")
return BlendFunc
end
_G["ccBlendFunc"] = ccBlendFuncDeprecated()
local function ccT2FQuadDeprecated()
deprecatedTip("ccT2F_Quad","T2F_Quad")
return T2F_Quad
end
_G["ccT2F_Quad"] = ccT2FQuadDeprecated()
local function ccAnimationFrameDataDeprecated()
deprecatedTip("ccAnimationFrameData","AnimationFrameData")
return AnimationFrameData
end
_G["ccAnimationFrameData"] = ccAnimationFrameDataDeprecated()
local function CCCallFuncNDeprecated( )
deprecatedTip("CCCallFuncN","CCCallFunc")
return CCCallFunc
end
_G["CCCallFuncN"] = CCCallFuncNDeprecated()
--functions of _G will be deprecated end
--functions of CCControl will be deprecated end
local CCControlDeprecated = { }
function CCControlDeprecated.addHandleOfControlEvent(self,func,controlEvent)
deprecatedTip("addHandleOfControlEvent","registerControlEventHandler")
print("come in addHandleOfControlEvent")
self:registerControlEventHandler(func,controlEvent)
end
rawset(CCControl,"addHandleOfControlEvent",CCControlDeprecated.addHandleOfControlEvent)
--functions of CCControl will be deprecated end
--functions of CCEGLView will be deprecated end
local CCEGLViewDeprecated = { }
function CCEGLViewDeprecated.sharedOpenGLView()
deprecatedTip("CCEGLView:sharedOpenGLView","CCEGLView:getInstance")
return CCEGLView:getInstance()
end
rawset(CCEGLView,"sharedOpenGLView",CCEGLViewDeprecated.sharedOpenGLView)
--functions of CCFileUtils will be deprecated end
--functions of CCFileUtils will be deprecated end
local CCFileUtilsDeprecated = { }
function CCFileUtilsDeprecated.sharedFileUtils()
deprecatedTip("CCFileUtils:sharedFileUtils","CCFileUtils:getInstance")
return CCFileUtils:getInstance()
end
rawset(CCFileUtils,"sharedFileUtils",CCFileUtilsDeprecated.sharedFileUtils)
function CCFileUtilsDeprecated.purgeFileUtils()
deprecatedTip("CCFileUtils:purgeFileUtils","CCFileUtils:destroyInstance")
return CCFileUtils:destroyInstance()
end
rawset(CCFileUtils,"purgeFileUtils",CCFileUtilsDeprecated.purgeFileUtils)
--functions of CCFileUtils will be deprecated end
--functions of CCApplication will be deprecated end
local CCApplicationDeprecated = { }
function CCApplicationDeprecated.sharedApplication()
deprecatedTip("CCApplication:sharedApplication","CCApplication:getInstance")
return CCApplication:getInstance()
end
rawset(CCApplication,"sharedApplication",CCApplicationDeprecated.sharedApplication)
--functions of CCApplication will be deprecated end
--functions of CCDirector will be deprecated end
local CCDirectorDeprecated = { }
function CCDirectorDeprecated.sharedDirector()
deprecatedTip("CCDirector:sharedDirector","CCDirector:getInstance")
return CCDirector:getInstance()
end
rawset(CCDirector,"sharedDirector",CCDirectorDeprecated.sharedDirector)
--functions of CCDirector will be deprecated end
--functions of CCUserDefault will be deprecated end
local CCUserDefaultDeprecated = { }
function CCUserDefaultDeprecated.sharedUserDefault()
deprecatedTip("CCUserDefault:sharedUserDefault","CCUserDefault:getInstance")
return CCUserDefault:getInstance()
end
rawset(CCUserDefault,"sharedUserDefault",CCUserDefaultDeprecated.sharedUserDefault)
function CCUserDefaultDeprecated.purgeSharedUserDefault()
deprecatedTip("CCUserDefault:purgeSharedUserDefault","CCUserDefault:destroyInstance")
return CCUserDefault:destroyInstance()
end
rawset(CCUserDefault,"purgeSharedUserDefault",CCUserDefaultDeprecated.purgeSharedUserDefault)
--functions of CCUserDefault will be deprecated end
--functions of CCNotificationCenter will be deprecated end
local CCNotificationCenterDeprecated = { }
function CCNotificationCenterDeprecated.sharedNotificationCenter()
deprecatedTip("CCNotificationCenter:sharedNotificationCenter","CCNotificationCenter:getInstance")
return CCNotificationCenter:getInstance()
end
rawset(CCNotificationCenter,"sharedNotificationCenter",CCNotificationCenterDeprecated.sharedNotificationCenter)
function CCNotificationCenterDeprecated.purgeNotificationCenter()
deprecatedTip("CCNotificationCenter:purgeNotificationCenter","CCNotificationCenter:destroyInstance")
return CCNotificationCenter:destroyInstance()
end
rawset(CCNotificationCenter,"purgeNotificationCenter",CCNotificationCenterDeprecated.purgeNotificationCenter)
--functions of CCNotificationCenter will be deprecated end
--functions of CCTextureCache will be deprecated begin
local CCTextureCacheDeprecated = { }
function CCTextureCacheDeprecated.sharedTextureCache()
deprecatedTip("CCTextureCache:sharedTextureCache","CCTextureCache:getInstance")
return CCTextureCache:getInstance()
end
rawset(CCTextureCache,"sharedTextureCache",CCTextureCacheDeprecated.sharedTextureCache)
function CCTextureCacheDeprecated.purgeSharedTextureCache()
deprecatedTip("CCTextureCache:purgeSharedTextureCache","CCTextureCache:destroyInstance")
return CCTextureCache:destroyInstance()
end
rawset(CCTextureCache,"purgeSharedTextureCache",CCTextureCacheDeprecated.purgeSharedTextureCache)
--functions of CCTextureCache will be deprecated end
--functions of CCGrid3DAction will be deprecated begin
local CCGrid3DActionDeprecated = { }
function CCGrid3DActionDeprecated.vertex(self,pt)
deprecatedTip("vertex","CCGrid3DAction:getVertex")
return self:getVertex(pt)
end
rawset(CCGrid3DAction,"vertex",CCGrid3DActionDeprecated.vertex)
function CCGrid3DActionDeprecated.originalVertex(self,pt)
deprecatedTip("originalVertex","CCGrid3DAction:getOriginalVertex")
return self:getOriginalVertex(pt)
end
rawset(CCGrid3DAction,"originalVertex",CCGrid3DActionDeprecated.originalVertex)
--functions of CCGrid3DAction will be deprecated end
--functions of CCTiledGrid3DAction will be deprecated begin
local CCTiledGrid3DActionDeprecated = { }
function CCTiledGrid3DActionDeprecated.tile(self,pt)
deprecatedTip("tile","CCTiledGrid3DAction:getTile")
return self:getTile(pt)
end
rawset(CCTiledGrid3DAction,"tile",CCTiledGrid3DActionDeprecated.tile)
function CCTiledGrid3DActionDeprecated.originalTile(self,pt)
deprecatedTip("originalTile","CCTiledGrid3DAction:getOriginalTile")
return self:getOriginalTile(pt)
end
rawset(CCTiledGrid3DAction,"originalTile",CCTiledGrid3DActionDeprecated.originalTile)
--functions of CCTiledGrid3DAction will be deprecated end
--functions of CCAnimationCache will be deprecated begin
local CCAnimationCacheDeprecated = { }
function CCAnimationCacheDeprecated.sharedAnimationCache()
deprecatedTip("CCAnimationCache:sharedAnimationCache","CCAnimationCache:getInstance")
return CCAnimationCache:getInstance()
end
rawset(CCAnimationCache,"sharedAnimationCache",CCAnimationCacheDeprecated.sharedAnimationCache)
function CCAnimationCacheDeprecated.purgeSharedAnimationCache()
deprecatedTip("CCAnimationCache:purgeSharedAnimationCache","CCAnimationCache:destroyInstance")
return CCAnimationCache:destroyInstance()
end
rawset(CCAnimationCache,"purgeSharedAnimationCache",CCAnimationCacheDeprecated.purgeSharedAnimationCache)
--functions of CCAnimationCache will be deprecated end
--functions of CCNode will be deprecated begin
local CCNodeDeprecated = { }
function CCNodeDeprecated.boundingBox(self)
deprecatedTip("CCNode:boundingBox","CCNode:getBoundingBox")
return self:getBoundingBox()
end
rawset(CCNode,"boundingBox",CCNodeDeprecated.boundingBox)
function CCNodeDeprecated.numberOfRunningActions(self)
deprecatedTip("CCNode:numberOfRunningActions","CCNode:getNumberOfRunningActions")
return self:getNumberOfRunningActions()
end
rawset(CCNode,"numberOfRunningActions",CCNodeDeprecated.numberOfRunningActions)
--functions of CCNode will be deprecated end
--functions of CCTexture2D will be deprecated begin
local CCTexture2DDeprecated = { }
function CCTexture2DDeprecated.stringForFormat(self)
deprecatedTip("Texture2D:stringForFormat","Texture2D:getStringForFormat")
return self:getStringForFormat()
end
rawset(CCTexture2D,"stringForFormat",CCTexture2DDeprecated.stringForFormat)
function CCTexture2DDeprecated.bitsPerPixelForFormat(self)
deprecatedTip("Texture2D:bitsPerPixelForFormat","Texture2D:getBitsPerPixelForFormat")
return self:getBitsPerPixelForFormat()
end
rawset(CCTexture2D,"bitsPerPixelForFormat",CCTexture2DDeprecated.bitsPerPixelForFormat)
function CCTexture2DDeprecated.bitsPerPixelForFormat(self,pixelFormat)
deprecatedTip("Texture2D:bitsPerPixelForFormat","Texture2D:getBitsPerPixelForFormat")
return self:getBitsPerPixelForFormat(pixelFormat)
end
rawset(CCTexture2D,"bitsPerPixelForFormat",CCTexture2DDeprecated.bitsPerPixelForFormat)
function CCTexture2DDeprecated.defaultAlphaPixelFormat(self)
deprecatedTip("Texture2D:defaultAlphaPixelFormat","Texture2D:getDefaultAlphaPixelFormat")
return self:getDefaultAlphaPixelFormat()
end
rawset(CCTexture2D,"defaultAlphaPixelFormat",CCTexture2DDeprecated.defaultAlphaPixelFormat)
--functions of CCTexture2D will be deprecated end
--functions of CCSpriteFrameCache will be deprecated begin
local CCSpriteFrameCacheDeprecated = { }
function CCSpriteFrameCacheDeprecated.spriteFrameByName(self,szName)
deprecatedTip("CCSpriteFrameCache:spriteFrameByName","CCSpriteFrameCache:getSpriteFrameByName")
return self:getSpriteFrameByName(szName)
end
rawset(CCSpriteFrameCache,"spriteFrameByName",CCSpriteFrameCacheDeprecated.spriteFrameByName)
function CCSpriteFrameCacheDeprecated.sharedSpriteFrameCache()
deprecatedTip("CCSpriteFrameCache:sharedSpriteFrameCache","CCSpriteFrameCache:getInstance")
return CCSpriteFrameCache:getInstance()
end
rawset(CCSpriteFrameCache,"sharedSpriteFrameCache",CCSpriteFrameCacheDeprecated.sharedSpriteFrameCache)
function CCSpriteFrameCacheDeprecated.purgeSharedSpriteFrameCache()
deprecatedTip("CCSpriteFrameCache:purgeSharedSpriteFrameCache","CCSpriteFrameCache:destroyInstance")
return CCSpriteFrameCache:destroyInstance()
end
rawset(CCSpriteFrameCache,"purgeSharedSpriteFrameCache",CCSpriteFrameCacheDeprecated.purgeSharedSpriteFrameCache)
--functions of CCSpriteFrameCache will be deprecated end
--functions of CCTimer will be deprecated begin
local CCTimerDeprecated = { }
function CCTimerDeprecated.timerWithScriptHandler(handler,seconds)
deprecatedTip("CCTimer:timerWithScriptHandler","CCTimer:createWithScriptHandler")
return CCTimer:createWithScriptHandler(handler,seconds)
end
rawset(CCTimer,"timerWithScriptHandler",CCTimerDeprecated.timerWithScriptHandler)
function CCTimerDeprecated.numberOfRunningActionsInTarget(self,target)
deprecatedTip("CCActionManager:numberOfRunningActionsInTarget","CCActionManager:getNumberOfRunningActionsInTarget")
return self:getNumberOfRunningActionsInTarget(target)
end
rawset(CCTimer,"numberOfRunningActionsInTarget",CCTimerDeprecated.numberOfRunningActionsInTarget)
--functions of CCTimer will be deprecated end
--functions of CCMenuItemFont will be deprecated begin
local CCMenuItemFontDeprecated = { }
function CCMenuItemFontDeprecated.fontSize()
deprecatedTip("CCMenuItemFont:fontSize","CCMenuItemFont:getFontSize")
return CCMenuItemFont:getFontSize()
end
rawset(CCMenuItemFont,"fontSize",CCMenuItemFontDeprecated.fontSize)
function CCMenuItemFontDeprecated.fontName()
deprecatedTip("CCMenuItemFont:fontName","CCMenuItemFont:getFontName")
return CCMenuItemFont:getFontName()
end
rawset(CCMenuItemFont,"fontName",CCMenuItemFontDeprecated.fontName)
function CCMenuItemFontDeprecated.fontSizeObj(self)
deprecatedTip("CCMenuItemFont:fontSizeObj","CCMenuItemFont:getFontSizeObj")
return self:getFontSizeObj()
end
rawset(CCMenuItemFont,"fontSizeObj",CCMenuItemFontDeprecated.fontSizeObj)
function CCMenuItemFontDeprecated.fontNameObj(self)
deprecatedTip("CCMenuItemFont:fontNameObj","CCMenuItemFont:getFontNameObj")
return self:getFontNameObj()
end
rawset(CCMenuItemFont,"fontNameObj",CCMenuItemFontDeprecated.fontNameObj)
--functions of CCMenuItemFont will be deprecated end
--functions of CCMenuItemToggle will be deprecated begin
local CCMenuItemToggleDeprecated = { }
function CCMenuItemToggleDeprecated.selectedItem(self)
deprecatedTip("CCMenuItemToggle:selectedItem","CCMenuItemToggle:getSelectedItem")
return self:getSelectedItem()
end
rawset(CCMenuItemToggle,"selectedItem",CCMenuItemToggleDeprecated.selectedItem)
--functions of CCMenuItemToggle will be deprecated end
--functions of CCTileMapAtlas will be deprecated begin
local CCTileMapAtlasDeprecated = { }
function CCTileMapAtlasDeprecated.tileAt(self,pos)
deprecatedTip("CCTileMapAtlas:tileAt","CCTileMapAtlas:getTileAt")
return self:getTileAt(pos)
end
rawset(CCTileMapAtlas,"tileAt",CCTileMapAtlasDeprecated.tileAt)
--functions of CCTileMapAtlas will be deprecated end
--functions of CCTMXLayer will be deprecated begin
local CCTMXLayerDeprecated = { }
function CCTMXLayerDeprecated.tileAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:tileAt","CCTMXLayer:getTileAt")
return self:getTileAt(tileCoordinate)
end
rawset(CCTMXLayer,"tileAt",CCTMXLayerDeprecated.tileAt)
function CCTMXLayerDeprecated.tileGIDAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:tileGIDAt","CCTMXLayer:getTileGIDAt")
return self:getTileGIDAt(tileCoordinate)
end
rawset(CCTMXLayer,"tileGIDAt",CCTMXLayerDeprecated.tileGIDAt)
function CCTMXLayerDeprecated.positionAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:positionAt","CCTMXLayer:getPositionAt")
return self:getPositionAt(tileCoordinate)
end
rawset(CCTMXLayer,"positionAt",CCTMXLayerDeprecated.positionAt)
function CCTMXLayerDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXLayer:propertyNamed","CCTMXLayer:getProperty")
return self:getProperty(propertyName)
end
rawset(CCTMXLayer,"propertyNamed",CCTMXLayerDeprecated.propertyNamed)
--functions of CCTMXLayer will be deprecated end
--functions of SimpleAudioEngine will be deprecated begin
local SimpleAudioEngineDeprecated = { }
function SimpleAudioEngineDeprecated.sharedEngine()
deprecatedTip("SimpleAudioEngine:sharedEngine","SimpleAudioEngine:getInstance")
return SimpleAudioEngine:getInstance()
end
rawset(SimpleAudioEngine,"sharedEngine",SimpleAudioEngineDeprecated.sharedEngine)
--functions of SimpleAudioEngine will be deprecated end
--functions of CCTMXTiledMap will be deprecated begin
local CCTMXTiledMapDeprecated = { }
function CCTMXTiledMapDeprecated.layerNamed(self,layerName)
deprecatedTip("CCTMXTiledMap:layerNamed","CCTMXTiledMap:getLayer")
return self:getLayer(layerName)
end
rawset(CCTMXTiledMap,"layerNamed", CCTMXTiledMapDeprecated.layerNamed)
function CCTMXTiledMapDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXTiledMap:propertyNamed","CCTMXTiledMap:getProperty")
return self:getProperty(propertyName)
end
rawset(CCTMXTiledMap,"propertyNamed", CCTMXTiledMapDeprecated.propertyNamed )
function CCTMXTiledMapDeprecated.propertiesForGID(self,GID)
deprecatedTip("CCTMXTiledMap:propertiesForGID","CCTMXTiledMap:getPropertiesForGID")
return self:getPropertiesForGID(GID)
end
rawset(CCTMXTiledMap,"propertiesForGID", CCTMXTiledMapDeprecated.propertiesForGID)
function CCTMXTiledMapDeprecated.objectGroupNamed(self,groupName)
deprecatedTip("CCTMXTiledMap:objectGroupNamed","CCTMXTiledMap:getObjectGroup")
return self:getObjectGroup(groupName)
end
rawset(CCTMXTiledMap,"objectGroupNamed", CCTMXTiledMapDeprecated.objectGroupNamed)
--functions of CCTMXTiledMap will be deprecated end
--functions of CCTMXMapInfo will be deprecated begin
local CCTMXMapInfoDeprecated = { }
function CCTMXMapInfoDeprecated.getStoringCharacters(self)
deprecatedTip("CCTMXMapInfo:getStoringCharacters","CCTMXMapInfo:isStoringCharacters")
return self:isStoringCharacters()
end
rawset(CCTMXMapInfo,"getStoringCharacters", CCTMXMapInfoDeprecated.getStoringCharacters)
function CCTMXMapInfoDeprecated.formatWithTMXFile(infoTable,tmxFile)
deprecatedTip("CCTMXMapInfo:formatWithTMXFile","CCTMXMapInfo:create")
return CCTMXMapInfo:create(tmxFile)
end
rawset(CCTMXMapInfo,"formatWithTMXFile", CCTMXMapInfoDeprecated.formatWithTMXFile)
function CCTMXMapInfoDeprecated.formatWithXML(infoTable,tmxString,resourcePath)
deprecatedTip("CCTMXMapInfo:formatWithXML","TMXMapInfo:createWithXML")
return CCTMXMapInfo:createWithXML(tmxString,resourcePath)
end
rawset(CCTMXMapInfo,"formatWithXML", CCTMXMapInfoDeprecated.formatWithXML)
--functions of CCTMXMapInfo will be deprecated end
--functions of CCTMXObject will be deprecated begin
local CCTMXObjectGroupDeprecated = { }
function CCTMXObjectGroupDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXObjectGroup:propertyNamed","CCTMXObjectGroup:getProperty")
return self:getProperty(propertyName)
end
rawset(CCTMXObjectGroup,"propertyNamed", CCTMXObjectGroupDeprecated.propertyNamed)
function CCTMXObjectGroupDeprecated.objectNamed(self, objectName)
deprecatedTip("CCTMXObjectGroup:objectNamed","CCTMXObjectGroup:getObject")
return self:getObject(objectName)
end
rawset(CCTMXObjectGroup,"objectNamed", CCTMXObjectGroupDeprecated.objectNamed)
--functions of CCTMXObject will be deprecated end
--functions of WebSocket will be deprecated begin
local targetPlatform = CCApplication:getInstance():getTargetPlatform()
if (kTargetIphone == targetPlatform) or (kTargetIpad == targetPlatform) or (kTargetAndroid == targetPlatform) or (kTargetWindows == targetPlatform) then
local WebSocketDeprecated = { }
function WebSocketDeprecated.sendTextMsg(self, string)
deprecatedTip("WebSocket:sendTextMsg","WebSocket:sendString")
return self:sendString(string)
end
rawset(WebSocket,"sendTextMsg", WebSocketDeprecated.sendTextMsg)
function WebSocketDeprecated.sendBinaryMsg(self, table,tablesize)
deprecatedTip("WebSocket:sendBinaryMsg","WebSocket:sendString")
string.char(unpack(table))
return self:sendString(string.char(unpack(table)))
end
rawset(WebSocket,"sendBinaryMsg", WebSocketDeprecated.sendBinaryMsg)
end
--functions of WebSocket will be deprecated end
--functions of CCDrawPrimitives will be deprecated begin
local CCDrawPrimitivesDeprecated = { }
function CCDrawPrimitivesDeprecated.ccDrawPoint(pt)
deprecatedTip("ccDrawPoint","CCDrawPrimitives.ccDrawPoint")
return CCDrawPrimitives.ccDrawPoint(pt)
end
rawset(_G, "ccDrawPoint", CCDrawPrimitivesDeprecated.ccDrawPoint)
function CCDrawPrimitivesDeprecated.ccDrawLine(origin,destination)
deprecatedTip("ccDrawLine","CCDrawPrimitives.ccDrawLine")
return CCDrawPrimitives.ccDrawLine(origin,destination)
end
rawset(_G, "ccDrawLine", CCDrawPrimitivesDeprecated.ccDrawLine)
function CCDrawPrimitivesDeprecated.ccDrawRect(origin,destination)
deprecatedTip("ccDrawRect","CCDrawPrimitives.ccDrawRect")
return CCDrawPrimitives.ccDrawRect(origin,destination)
end
rawset(_G, "ccDrawRect", CCDrawPrimitivesDeprecated.ccDrawRect)
function CCDrawPrimitivesDeprecated.ccDrawSolidRect(origin,destination,color)
deprecatedTip("ccDrawSolidRect","CCDrawPrimitives.ccDrawSolidRect")
return CCDrawPrimitives.ccDrawSolidRect(origin,destination,color)
end
rawset(_G, "ccDrawSolidRect", CCDrawPrimitivesDeprecated.ccDrawSolidRect)
-- params:... may represent two param(xScale,yScale) or nil
function CCDrawPrimitivesDeprecated.ccDrawCircle(center,radius,angle,segments,drawLineToCenter,...)
deprecatedTip("ccDrawCircle","CCDrawPrimitives.ccDrawCircle")
return CCDrawPrimitives.ccDrawCircle(center,radius,angle,segments,drawLineToCenter,...)
end
rawset(_G, "ccDrawCircle", CCDrawPrimitivesDeprecated.ccDrawCircle)
-- params:... may represent two param(xScale,yScale) or nil
function CCDrawPrimitivesDeprecated.ccDrawSolidCircle(center,radius,angle,segments,...)
deprecatedTip("ccDrawSolidCircle","CCDrawPrimitives.ccDrawSolidCircle")
return CCDrawPrimitives.ccDrawSolidCircle(center,radius,angle,segments,...)
end
rawset(_G, "ccDrawSolidCircle", CCDrawPrimitivesDeprecated.ccDrawSolidCircle)
function CCDrawPrimitivesDeprecated.ccDrawQuadBezier(origin,control,destination,segments)
deprecatedTip("ccDrawQuadBezier","CCDrawPrimitives.ccDrawQuadBezier")
return CCDrawPrimitives.ccDrawQuadBezier(origin,control,destination,segments)
end
rawset(_G, "ccDrawQuadBezier", CCDrawPrimitivesDeprecated.ccDrawQuadBezier)
function CCDrawPrimitivesDeprecated.ccDrawCubicBezier(origin,control1,control2,destination,segments)
deprecatedTip("ccDrawCubicBezier","CCDrawPrimitives.ccDrawCubicBezier")
return CCDrawPrimitives.ccDrawCubicBezier(origin,control1,control2,destination,segments)
end
rawset(_G, "ccDrawCubicBezier", CCDrawPrimitivesDeprecated.ccDrawCubicBezier)
function CCDrawPrimitivesDeprecated.ccDrawCatmullRom(arrayOfControlPoints,segments)
deprecatedTip("ccDrawCatmullRom","CCDrawPrimitives.ccDrawCatmullRom")
return CCDrawPrimitives.ccDrawCatmullRom(arrayOfControlPoints,segments)
end
rawset(_G, "ccDrawCatmullRom", CCDrawPrimitivesDeprecated.ccDrawCatmullRom)
function CCDrawPrimitivesDeprecated.ccDrawCardinalSpline(config,tension,segments)
deprecatedTip("ccDrawCardinalSpline","CCDrawPrimitives.ccDrawCardinalSpline")
return CCDrawPrimitives.ccDrawCardinalSpline(config,tension,segments)
end
rawset(_G, "ccDrawCardinalSpline", CCDrawPrimitivesDeprecated.ccDrawCardinalSpline)
function CCDrawPrimitivesDeprecated.ccDrawColor4B(r,g,b,a)
deprecatedTip("ccDrawColor4B","CCDrawPrimitives.ccDrawColor4B")
return CCDrawPrimitives.ccDrawColor4B(r,g,b,a)
end
rawset(_G, "ccDrawColor4B", CCDrawPrimitivesDeprecated.ccDrawColor4B)
function CCDrawPrimitivesDeprecated.ccDrawColor4F(r,g,b,a)
deprecatedTip("ccDrawColor4F","CCDrawPrimitives.ccDrawColor4F")
return CCDrawPrimitives.ccDrawColor4F(r,g,b,a)
end
rawset(_G, "ccDrawColor4F", CCDrawPrimitivesDeprecated.ccDrawColor4F)
function CCDrawPrimitivesDeprecated.ccPointSize(pointSize)
deprecatedTip("ccPointSize","CCDrawPrimitives.ccPointSize")
return CCDrawPrimitives.ccPointSize(pointSize)
end
rawset(_G, "ccPointSize", CCDrawPrimitivesDeprecated.ccPointSize)
--functions of CCDrawPrimitives will be deprecated end
--enums of CCParticleSystem will be deprecated begin
_G["kParticleStartSizeEqualToEndSize"] = _G["kCCParticleStartSizeEqualToEndSize"]
_G["kParticleDurationInfinity"] = _G["kCCParticleDurationInfinity"]
--enums of CCParticleSystem will be deprecated end
--enums of CCRenderTexture will be deprecated begin
local CCRenderTextureDeprecated = { }
function CCRenderTextureDeprecated.newCCImage(self)
deprecatedTip("CCRenderTexture:newCCImage","CCRenderTexture:newImage")
return self:newImage()
end
rawset(CCRenderTexture, "newCCImage", CCRenderTextureDeprecated.newCCImage)
--enums of CCRenderTexture will be deprecated end
| mit |
n0xus/darkstar | scripts/globals/items/warm_egg.lua | 35 | 1186 | -----------------------------------------
-- ID: 4602
-- Item: warm_egg
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Health 18
-- Magic 18
-----------------------------------------
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,300,4602);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 18);
target:addMod(MOD_MP, 18);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 18);
target:delMod(MOD_MP, 18);
end;
| gpl-3.0 |
feiying1460/witi-openwrt | package/ramips/ui/luci-mtk/src/libs/json/luasrc/json.lua | 50 | 13333 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
Decoder:
Info:
null will be decoded to luci.json.null if first parameter of Decoder() is true
Example:
decoder = luci.json.Decoder()
luci.ltn12.pump.all(luci.ltn12.source.string("decodableJSON"), decoder:sink())
luci.util.dumptable(decoder:get())
Known issues:
does not support unicode conversion \uXXYY with XX != 00 will be ignored
Encoder:
Info:
Accepts numbers, strings, nil, booleans as they are
Accepts luci.json.null as replacement for nil
Accepts full associative and full numerically indexed tables
Mixed tables will loose their associative values during conversion
Iterator functions will be encoded as an array of their return values
Non-iterator functions will probably corrupt the encoder
Example:
encoder = luci.json.Encoder(encodableData)
luci.ltn12.pump.all(encoder:source(), luci.ltn12.sink.file(io.open("someFile", w)))
]]--
local nixio = require "nixio"
local util = require "luci.util"
local table = require "table"
local string = require "string"
local coroutine = require "coroutine"
local assert = assert
local tonumber = tonumber
local tostring = tostring
local error = error
local type = type
local pairs = pairs
local ipairs = ipairs
local next = next
local pcall = pcall
local band = nixio.bit.band
local bor = nixio.bit.bor
local rshift = nixio.bit.rshift
local char = string.char
local getmetatable = getmetatable
--- LuCI JSON-Library
-- @cstyle instance
module "luci.json"
--- Directly decode a JSON string
-- @param json JSON-String
-- @return Lua object
function decode(json, ...)
local a = ActiveDecoder(function() return nil end, ...)
a.chunk = json
local s, obj = pcall(a.get, a)
return s and obj or nil
end
--- Direcly encode a Lua object into a JSON string.
-- @param obj Lua Object
-- @return JSON string
function encode(obj, ...)
local out = {}
local e = Encoder(obj, 1, ...):source()
local chnk, err
repeat
chnk, err = e()
out[#out+1] = chnk
until not chnk
return not err and table.concat(out) or nil
end
--- Null replacement function
-- @return null
function null()
return null
end
--- Create a new JSON-Encoder.
-- @class function
-- @name Encoder
-- @param data Lua-Object to be encoded.
-- @param buffersize Blocksize of returned data source.
-- @param fastescape Use non-standard escaping (don't escape control chars)
-- @return JSON-Encoder
Encoder = util.class()
function Encoder.__init__(self, data, buffersize, fastescape)
self.data = data
self.buffersize = buffersize or 512
self.buffer = ""
self.fastescape = fastescape
getmetatable(self).__call = Encoder.source
end
--- Create an LTN12 source providing the encoded JSON-Data.
-- @return LTN12 source
function Encoder.source(self)
local source = coroutine.create(self.dispatch)
return function()
local res, data = coroutine.resume(source, self, self.data, true)
if res then
return data
else
return nil, data
end
end
end
function Encoder.dispatch(self, data, start)
local parser = self.parsers[type(data)]
parser(self, data)
if start then
if #self.buffer > 0 then
coroutine.yield(self.buffer)
end
coroutine.yield()
end
end
function Encoder.put(self, chunk)
if self.buffersize < 2 then
coroutine.yield(chunk)
else
if #self.buffer + #chunk > self.buffersize then
local written = 0
local fbuffer = self.buffersize - #self.buffer
coroutine.yield(self.buffer .. chunk:sub(written + 1, fbuffer))
written = fbuffer
while #chunk - written > self.buffersize do
fbuffer = written + self.buffersize
coroutine.yield(chunk:sub(written + 1, fbuffer))
written = fbuffer
end
self.buffer = chunk:sub(written + 1)
else
self.buffer = self.buffer .. chunk
end
end
end
function Encoder.parse_nil(self)
self:put("null")
end
function Encoder.parse_bool(self, obj)
self:put(obj and "true" or "false")
end
function Encoder.parse_number(self, obj)
self:put(tostring(obj))
end
function Encoder.parse_string(self, obj)
if self.fastescape then
self:put('"' .. obj:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"')
else
self:put('"' ..
obj:gsub('[%c\\"]',
function(char)
return '\\u00%02x' % char:byte()
end
)
.. '"')
end
end
function Encoder.parse_iter(self, obj)
if obj == null then
return self:put("null")
end
if type(obj) == "table" and (#obj == 0 and next(obj)) then
self:put("{")
local first = true
for key, entry in pairs(obj) do
first = first or self:put(",")
first = first and false
self:parse_string(tostring(key))
self:put(":")
self:dispatch(entry)
end
self:put("}")
else
self:put("[")
local first = true
if type(obj) == "table" then
for i=1, #obj do
first = first or self:put(",")
first = first and nil
self:dispatch(obj[i])
end
else
for entry in obj do
first = first or self:put(",")
first = first and nil
self:dispatch(entry)
end
end
self:put("]")
end
end
Encoder.parsers = {
['nil'] = Encoder.parse_nil,
['table'] = Encoder.parse_iter,
['number'] = Encoder.parse_number,
['string'] = Encoder.parse_string,
['boolean'] = Encoder.parse_bool,
['function'] = Encoder.parse_iter
}
--- Create a new JSON-Decoder.
-- @class function
-- @name Decoder
-- @param customnull Use luci.json.null instead of nil for decoding null
-- @return JSON-Decoder
Decoder = util.class()
function Decoder.__init__(self, customnull)
self.cnull = customnull
getmetatable(self).__call = Decoder.sink
end
--- Create an LTN12 sink from the decoder object which accepts the JSON-Data.
-- @return LTN12 sink
function Decoder.sink(self)
local sink = coroutine.create(self.dispatch)
return function(...)
return coroutine.resume(sink, self, ...)
end
end
--- Get the decoded data packets after the rawdata has been sent to the sink.
-- @return Decoded data
function Decoder.get(self)
return self.data
end
function Decoder.dispatch(self, chunk, src_err, strict)
local robject, object
local oset = false
while chunk do
while chunk and #chunk < 1 do
chunk = self:fetch()
end
assert(not strict or chunk, "Unexpected EOS")
if not chunk then break end
local char = chunk:sub(1, 1)
local parser = self.parsers[char]
or (char:match("%s") and self.parse_space)
or (char:match("[0-9-]") and self.parse_number)
or error("Unexpected char '%s'" % char)
chunk, robject = parser(self, chunk)
if parser ~= self.parse_space then
assert(not oset, "Scope violation: Too many objects")
object = robject
oset = true
if strict then
return chunk, object
end
end
end
assert(not src_err, src_err)
assert(oset, "Unexpected EOS")
self.data = object
end
function Decoder.fetch(self)
local tself, chunk, src_err = coroutine.yield()
assert(chunk or not src_err, src_err)
return chunk
end
function Decoder.fetch_atleast(self, chunk, bytes)
while #chunk < bytes do
local nchunk = self:fetch()
assert(nchunk, "Unexpected EOS")
chunk = chunk .. nchunk
end
return chunk
end
function Decoder.fetch_until(self, chunk, pattern)
local start = chunk:find(pattern)
while not start do
local nchunk = self:fetch()
assert(nchunk, "Unexpected EOS")
chunk = chunk .. nchunk
start = chunk:find(pattern)
end
return chunk, start
end
function Decoder.parse_space(self, chunk)
local start = chunk:find("[^%s]")
while not start do
chunk = self:fetch()
if not chunk then
return nil
end
start = chunk:find("[^%s]")
end
return chunk:sub(start)
end
function Decoder.parse_literal(self, chunk, literal, value)
chunk = self:fetch_atleast(chunk, #literal)
assert(chunk:sub(1, #literal) == literal, "Invalid character sequence")
return chunk:sub(#literal + 1), value
end
function Decoder.parse_null(self, chunk)
return self:parse_literal(chunk, "null", self.cnull and null)
end
function Decoder.parse_true(self, chunk)
return self:parse_literal(chunk, "true", true)
end
function Decoder.parse_false(self, chunk)
return self:parse_literal(chunk, "false", false)
end
function Decoder.parse_number(self, chunk)
local chunk, start = self:fetch_until(chunk, "[^0-9eE.+-]")
local number = tonumber(chunk:sub(1, start - 1))
assert(number, "Invalid number specification")
return chunk:sub(start), number
end
function Decoder.parse_string(self, chunk)
local str = ""
local object = nil
assert(chunk:sub(1, 1) == '"', 'Expected "')
chunk = chunk:sub(2)
while true do
local spos = chunk:find('[\\"]')
if spos then
str = str .. chunk:sub(1, spos - 1)
local char = chunk:sub(spos, spos)
if char == '"' then -- String end
chunk = chunk:sub(spos + 1)
break
elseif char == "\\" then -- Escape sequence
chunk, object = self:parse_escape(chunk:sub(spos))
str = str .. object
end
else
str = str .. chunk
chunk = self:fetch()
assert(chunk, "Unexpected EOS while parsing a string")
end
end
return chunk, str
end
function Decoder.utf8_encode(self, s1, s2)
local n = s1 * 256 + s2
if n >= 0 and n <= 0x7F then
return char(n)
elseif n >= 0 and n <= 0x7FF then
return char(
bor(band(rshift(n, 6), 0x1F), 0xC0),
bor(band(n, 0x3F), 0x80)
)
elseif n >= 0 and n <= 0xFFFF then
return char(
bor(band(rshift(n, 12), 0x0F), 0xE0),
bor(band(rshift(n, 6), 0x3F), 0x80),
bor(band(n, 0x3F), 0x80)
)
elseif n >= 0 and n <= 0x10FFFF then
return char(
bor(band(rshift(n, 18), 0x07), 0xF0),
bor(band(rshift(n, 12), 0x3F), 0x80),
bor(band(rshift(n, 6), 0x3F), 0x80),
bor(band(n, 0x3F), 0x80)
)
else
return "?"
end
end
function Decoder.parse_escape(self, chunk)
local str = ""
chunk = self:fetch_atleast(chunk:sub(2), 1)
local char = chunk:sub(1, 1)
chunk = chunk:sub(2)
if char == '"' then
return chunk, '"'
elseif char == "\\" then
return chunk, "\\"
elseif char == "u" then
chunk = self:fetch_atleast(chunk, 4)
local s1, s2 = chunk:sub(1, 2), chunk:sub(3, 4)
s1, s2 = tonumber(s1, 16), tonumber(s2, 16)
assert(s1 and s2, "Invalid Unicode character")
return chunk:sub(5), self:utf8_encode(s1, s2)
elseif char == "/" then
return chunk, "/"
elseif char == "b" then
return chunk, "\b"
elseif char == "f" then
return chunk, "\f"
elseif char == "n" then
return chunk, "\n"
elseif char == "r" then
return chunk, "\r"
elseif char == "t" then
return chunk, "\t"
else
error("Unexpected escaping sequence '\\%s'" % char)
end
end
function Decoder.parse_array(self, chunk)
chunk = chunk:sub(2)
local array = {}
local nextp = 1
local chunk, object = self:parse_delimiter(chunk, "%]")
if object then
return chunk, array
end
repeat
chunk, object = self:dispatch(chunk, nil, true)
table.insert(array, nextp, object)
nextp = nextp + 1
chunk, object = self:parse_delimiter(chunk, ",%]")
assert(object, "Delimiter expected")
until object == "]"
return chunk, array
end
function Decoder.parse_object(self, chunk)
chunk = chunk:sub(2)
local array = {}
local name
local chunk, object = self:parse_delimiter(chunk, "}")
if object then
return chunk, array
end
repeat
chunk = self:parse_space(chunk)
assert(chunk, "Unexpected EOS")
chunk, name = self:parse_string(chunk)
chunk, object = self:parse_delimiter(chunk, ":")
assert(object, "Separator expected")
chunk, object = self:dispatch(chunk, nil, true)
array[name] = object
chunk, object = self:parse_delimiter(chunk, ",}")
assert(object, "Delimiter expected")
until object == "}"
return chunk, array
end
function Decoder.parse_delimiter(self, chunk, delimiter)
while true do
chunk = self:fetch_atleast(chunk, 1)
local char = chunk:sub(1, 1)
if char:match("%s") then
chunk = self:parse_space(chunk)
assert(chunk, "Unexpected EOS")
elseif char:match("[%s]" % delimiter) then
return chunk:sub(2), char
else
return chunk, nil
end
end
end
Decoder.parsers = {
['"'] = Decoder.parse_string,
['t'] = Decoder.parse_true,
['f'] = Decoder.parse_false,
['n'] = Decoder.parse_null,
['['] = Decoder.parse_array,
['{'] = Decoder.parse_object
}
--- Create a new Active JSON-Decoder.
-- @class function
-- @name ActiveDecoder
-- @param customnull Use luci.json.null instead of nil for decoding null
-- @return Active JSON-Decoder
ActiveDecoder = util.class(Decoder)
function ActiveDecoder.__init__(self, source, customnull)
Decoder.__init__(self, customnull)
self.source = source
self.chunk = nil
getmetatable(self).__call = self.get
end
--- Fetches one JSON-object from given source
-- @return Decoded object
function ActiveDecoder.get(self)
local chunk, src_err, object
if not self.chunk then
chunk, src_err = self.source()
else
chunk = self.chunk
end
self.chunk, object = self:dispatch(chunk, src_err, true)
return object
end
function ActiveDecoder.fetch(self)
local chunk, src_err = self.source()
assert(chunk or not src_err, src_err)
return chunk
end
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Cape_Teriggan/npcs/Cermet_Headstone.lua | 17 | 3797 | -----------------------------------
-- Area: Cape Teriggan
-- NPC: Cermet Headstone
-- Involved in Mission: ZM5 Headstone Pilgrimage (Wind Headstone)
-- @pos -107 -8 450 113
-----------------------------------
package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/missions");
require("scripts/zones/Cape_Teriggan/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(949,1) and trade:getItemCount() == 1) then
if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE and player:hasKeyItem(WIND_FRAGMENT) and player:hasCompleteQuest(OUTLANDS,WANDERING_SOULS) == false) then
player:addQuest(OUTLANDS,WANDERING_SOULS);
player:startEvent(0x00CA,949);
elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE) and player:hasCompleteQuest(OUTLANDS,WANDERING_SOULS) == false) then
player:addQuest(OUTLANDS,WANDERING_SOULS);
player:startEvent(0x00CA,949);
else
player:messageSpecial(NOTHING_HAPPENS);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then
-- if requirements are met and 15 mins have passed since mobs were last defeated, spawn them
if (player:hasKeyItem(WIND_FRAGMENT) == false and GetServerVariable("[ZM4]Wind_Headstone_Active") < os.time()) then
player:startEvent(0x00C8,WIND_FRAGMENT);
-- if 15 min window is open and requirements are met, recieve key item
elseif (player:hasKeyItem(WIND_FRAGMENT) == false and GetServerVariable("[ZM4]Wind_Headstone_Active") > os.time()) then
player:addKeyItem(WIND_FRAGMENT);
-- Check and see if all fragments have been found (no need to check wind and dark frag)
if (player:hasKeyItem(ICE_FRAGMENT) and player:hasKeyItem(EARTH_FRAGMENT) and player:hasKeyItem(WATER_FRAGMENT) and
player:hasKeyItem(FIRE_FRAGMENT) and player:hasKeyItem(LIGHTNING_FRAGMENT) and player:hasKeyItem(LIGHT_FRAGMENT)) then
player:messageSpecial(FOUND_ALL_FRAGS,WIND_FRAGMENT);
player:addTitle(BEARER_OF_THE_EIGHT_PRAYERS);
player:completeMission(ZILART,HEADSTONE_PILGRIMAGE);
player:addMission(ZILART,THROUGH_THE_QUICKSAND_CAVES);
else
player:messageSpecial(KEYITEM_OBTAINED,WIND_FRAGMENT);
end
else
player:messageSpecial(ALREADY_OBTAINED_FRAG,WIND_FRAGMENT);
end
elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then
player:messageSpecial(ZILART_MONUMENT);
else
player:messageSpecial(CANNOT_REMOVE_FRAG);
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 == 0x00C8 and option == 1) then
SpawnMob(17240414,300):updateClaim(player); -- Axesarion the Wanderer
SetServerVariable("[ZM4]Wind_Headstone_Active",0);
elseif (csid == 0x00CA) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13248);
else
player:tradeComplete();
player:addItem(13248);
player:messageSpecial(ITEM_OBTAINED,13248);
player:completeQuest(OUTLANDS,WANDERING_SOULS);
player:addTitle(BEARER_OF_BONDS_BEYOND_TIME);
end
end
end; | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.