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 |
|---|---|---|---|---|---|
mynameiscraziu/body | plugins/stats.lua | 33 | 3680 | do
local NUM_MSG_MAX = 6
local TIME_CHECK = 4 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
local kick = chat_del_user(chat_id , user_id, ok_cb, true)
vardump(kick)
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false)
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
firebaugh/Digitowls | WebotsController/Player.old/Vision/detectSpot.lua | 4 | 1499 | module(..., package.seeall);
require('Config'); -- For Ball and Goal Size
require('ImageProc');
require('HeadTransform'); -- For Projection
require('Vision');
-- Dependency
require('Detection');
-- Define Color
colorOrange = 1;
colorYellow = 2;
colorCyan = 4;
colorField = 8;
colorWhite = 16;
use_point_goal=Config.vision.use_point_goal;
headInverted=Config.vision.headInverted;
function detect()
--TODO: test spot detection
spot = {};
spot.detect = 0;
if (Vision.colorCount[colorWhite] < 100) then
return spot;
end
if (Vision.colorCount[colorField] < 5000) then
return spot;
end
local spotPropsB = ImageProc.field_spots(Vision.labelB.data, Vision.labelB.m, Vision.labelB.n);
if (not spotPropsB) then
return spot;
end
spot.propsB = spotPropsB[1];
if (spot.propsB.area < 6) then
return spot;
end
-- get the color statistics of the region (in the large size image)
local spotStats = Vision.bboxStats(colorWhite, spot.propsB.boundingBox);
-- check the major and minor axes
-- the spot is symmetrical so the major and minor axes should be the same
--debugprint('Spot: checking ratio');
if (spotStats.axisMinor < .2*spotStats.axisMajor) then
return spot;
end
spot.propsA = spotStats;
local vcentroid = HeadTransform.coordinatesA(spotStats.centroid, 1);
vcentroid = HeadTransform.projectGround(vcentroid,0);
vcentroid[4] = 1;
spot.v = vcentroid;
--debugprint('Spot found');
spot.detect = 1;
return spot;
end
| gpl-3.0 |
wingo/snabbswitch | lib/pflua/tests/pfquickcheck/pflua_ir.lua | 25 | 1989 | #!/usr/bin/env luajit
-- -*- lua -*-
-- This module generates (a subset of) pflua's IR,
-- for property-based tests of pflua internals.
module(..., package.seeall)
local choose = require("pf.utils").choose
local True, False, Fail, ComparisonOp, BinaryOp, Number, Len
local Binary, Arithmetic, Comparison, Conditional
-- Logical intentionally is not local; it is used elsewhere
function True() return { 'true' } end
function False() return { 'false' } end
function Fail() return { 'fail' } end
function ComparisonOp() return choose({ '<', '>' }) end
function BinaryOp() return choose({ '+', '-', '/' }) end
-- Boundary numbers are often particularly interesting; test them often
function Number()
if math.random() < 0.2
then return math.random(0, 2^32 - 1)
else
return choose({ 0, 1, 2^31-1, 2^31, 2^32-1 })
end
end
function Len() return 'len' end
function Binary(db)
local op, lhs, rhs = BinaryOp(), Arithmetic(db), Arithmetic(db)
if op == '/' then table.insert(db, { '!=', rhs, 0 }) end
return { 'uint32', { op, lhs, rhs } }
end
function PacketAccess(db)
local pkt_access_size = choose({1, 2, 4})
local position = Arithmetic(db)
table.insert(db, {'>=', 'len', {'+', position, pkt_access_size}})
local access = { '[]', position, pkt_access_size }
if pkt_access_size == 1 then return access end
if pkt_access_size == 2 then return { 'ntohs', access } end
if pkt_access_size == 4 then return { 'uint32', { 'ntohs', access } } end
error('unreachable')
end
function Arithmetic(db)
return choose({ Binary, Number, Len, PacketAccess })(db)
end
function Comparison()
local asserts = {}
local expr = { ComparisonOp(), Arithmetic(asserts), Arithmetic(asserts) }
for i=#asserts,1,-1 do
expr = { 'if', asserts[i], expr, { 'fail' } }
end
return expr
end
function Conditional() return { 'if', Logical(), Logical(), Logical() } end
function Logical()
return choose({ Conditional, Comparison, True, False, Fail })()
end
| apache-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Windurst_Woods/npcs/Nya_Labiccio.lua | 16 | 1489 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Nya Labiccio
-- Only sells when Windurst controlls Gustaberg Region
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(GUSTABERG);
if (RegionOwner ~= WINDURST) then
player:showText(npc,NYALABICCIO_CLOSED_DIALOG);
else
player:showText(npc,NYALABICCIO_OPEN_DIALOG);
stock = {
0x0454, 703, --Sulfur
0x026B, 43, --Popoto
0x0263, 36, --Rye Flour
0x1124, 40 --Eggplant
}
showShop(player,WINDURST,stock);
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 |
nye678/OD | TextureManager.lua | 1 | 1468 | --[[---------------------------------------------------------------------------
Jake Robbins
--]]---------------------------------------------------------------------------
--[[---------------------------------------------------------------------------
@name Texture Manager
@text Manager responsible for keeping track of texture data.
--]]
local TextureManager = {
textures = {},
textureTags = {},
idSource = 0
}
--[[---------------------------------------------------------------------------
@name Load Texture
@text Loads a texture from file into the texture manager. Returns the
id number of the texture.
--]]
function TextureManager:loadTexture(filepath)
self.idSource = self.idSource + 1
local id = self.idSource
local texture = love.graphics.newImage(filepath)
self.textures[id] = texture
return id
end
--[[---------------------------------------------------------------------------
@name Set Texture Tag Name
@text Set a tag name for a texture. The texture id can be looked up by
the tag name.
--]]
function TextureManager:setTag(texture, tagName)
self.textureTags[tagName] = texture
end
--[[---------------------------------------------------------------------------
@name Get Tagged Texture
@text Gets a texture id with the given tag.
--]]
function TextureManager:getTagged(tagName)
return self.textureTags[tagName]
end
-------------------------------------------------------------------------------
return TextureManager | mit |
xboybigcampishere/V2MIRROR | plugins/linkpv.lua | 5 | 31027 | do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local 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.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been demoted.')
end
local function 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 == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
if success == -1 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' then
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'rem' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local receiver = 'user#id'..msg.action.user.id
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return false
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id)
send_large_msg(receiver, rules)
end
if matches[1] == 'chat_del_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and matches[2] then
if not is_owner(msg) then
return "Only owner can promote"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'demote' and matches[2] then
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "You can't demote yourself"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
if matches[1] == 'newlink' then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'linkpv' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
send_large_msg('user#id'..msg.from.id, "Group link:\n"..group_link)
end
if matches[1] == 'setowner' then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'help' then
if not is_momod(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
end
return {
patterns = {
"^(linkpv)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
Nax/citizenhack | dat/Rog-strt.lua | 1 | 6059 | -- NetHack 3.7 Rogue.des $NHDT-Date: 1432512784 2015/05/25 00:13:04 $ $NHDT-Branch: master $:$NHDT-Revision: 1.11 $
-- Copyright (c) 1992 by Dean Luick
-- NetHack may be freely redistributed. See license for details.
--
--
-- The "start" level for the quest.
--
-- Here you meet your (besieged) class leader, Master of Thieves
-- and receive your quest assignment.
--
des.level_init({ style = "solidfill", fg = " " });
des.level_flags("mazelevel", "noteleport", "hardfloor", "nommap")
-- 1 2 3 4 5 6 7
--123456789012345678901234567890123456789012345678901234567890123456789012345
des.map([[
---------------------------------.------------------------------------------
|.....|.||..........|....|......|.|.........|.......+............---.......|
|.....|..+..........+....---....S.|...-S-----.-----.|............+.+.......|
|.....+.||........---......|....|.|...|.....|.|...|.---.....------.--------|
|-----|.-------|..|........------.-----.....|.--..|...-------..............|
|.....|........------+------..........+.....|..--S---.........------.-----..
|.....|.------...............-----.}}.--------.|....-------.---....|.+...--|
|..-+--.|....|-----.--------.|...|.....+.....|.|....|.....+.+......|.--....|
|..|....|....|....+.|......|.|...-----.|.....|.--...|.....|.|......|..|....|
|..|.-----S----...|.+....-----...|...|.----..|..|.---....--.---S-----.|----|
|..|.|........|...------.|.S.....|...|....-----.+.|......|..|.......|.|....|
|---.-------..|...|....|.|.|.....|...----.|...|.|---.....|.|-.......|.---..|
...........|..S...|....---.----S----..|...|...+.|..-------.---+-....|...--+|
|---------.---------...|......|....S..|.---...|.|..|...........----.---....|
|........|.........|...+.------....|---.---...|.--+-.----.----....|.+...--+|
|........|.---+---.|----.--........|......-----......|..|..|.--+-.|.-S-.|..|
|........|.|.....|........----------.----.......---.--..|-.|....|.-----.|..|
|----....+.|.....----+---............|..|--------.+.|...SS.|....|.......|..|
|...--+-----.....|......|.------------............---...||.------+--+----..|
|..........S.....|......|.|..........S............|.....||...|.....|....|..|
-------------------------.--------------------------------------------------
]]);
-- Dungeon Description
--REGION:(00,00,75,20),lit,"ordinary"
local streets = selection.floodfill(0,12)
-- The down stairs is at one of the 4 "exits". The others are mimics,
-- mimicing stairwells.
local place = { {33,0}, {0,12}, {25,20}, {75,05} }
shuffle(place)
des.stair({ dir = "down", coord = place[1] })
des.monster({ id = "giant mimic", coord = place[2], appear_as = "ter:staircase down" })
des.monster({ id = "large mimic", coord = place[3], appear_as = "ter:staircase down" })
des.monster({ id = "small mimic", coord = place[4], appear_as = "ter:staircase down" })
-- Portal arrival point
des.levregion({ region = {19,09,19,09}, type="branch" })
-- Doors (secret)
--DOOR:locked|closed|open,(xx,yy)
des.door("locked", 32, 2)
des.door("locked", 63, 9)
des.door("locked", 27,10)
des.door("locked", 31,12)
des.door("locked", 35,13)
des.door("locked", 69,15)
des.door("locked", 56,17)
des.door("locked", 57,17)
des.door("locked", 11,19)
des.door("locked", 37,19)
des.door("locked", 39, 2)
des.door("locked", 49, 5)
des.door("locked", 10, 9)
des.door("locked", 14,12)
-- Doors (regular)
des.door("closed", 52, 1)
des.door("closed", 9, 2)
des.door("closed", 20, 2)
des.door("closed", 65, 2)
des.door("closed", 67, 2)
des.door("closed", 6, 3)
des.door("closed", 21, 5)
des.door("closed", 38, 5)
des.door("closed", 69, 6)
des.door("closed", 4, 7)
des.door("closed", 39, 7)
des.door("closed", 58, 7)
des.door("closed", 60, 7)
des.door("closed", 18, 8)
des.door("closed", 20, 9)
des.door("closed", 48,10)
des.door("closed", 46,12)
des.door("closed", 62,12)
des.door("closed", 74,12)
des.door("closed", 23,14)
des.door("closed", 23,14)
des.door("closed", 50,14)
des.door("closed", 68,14)
des.door("closed", 74,14)
des.door("closed", 14,15)
des.door("closed", 63,15)
des.door("closed", 9,17)
des.door("closed", 21,17)
des.door("closed", 50,17)
des.door("closed", 6,18)
des.door("closed", 65,18)
des.door("closed", 68,18)
-- Master of Thieves
des.monster({ id = "Master of Thieves", coord = {36, 11}, inventory = function()
des.object({ id = "leather armor", spe = 5 });
des.object({ id = "silver dagger", spe = 4 });
des.object({ id = "dagger", spe = 2, quantity = d(2,4), buc = "not-cursed" });
end })
-- The treasure of Master of Thieves
des.object("chest", 36, 11)
-- thug guards, room #1
des.monster("thug", 28, 10)
des.monster("thug", 29, 11)
des.monster("thug", 30, 09)
des.monster("thug", 31, 07)
-- thug guards, room #2
des.monster("thug", 31, 13)
des.monster("thug", 33, 14)
des.monster("thug", 30, 15)
--thug guards, room #3
des.monster("thug", 35, 09)
des.monster("thug", 36, 13)
-- Non diggable walls
des.non_diggable(selection.area(00,00,75,20))
-- Random traps
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
des.trap()
--
-- Monsters to get in the way.
--
-- West exit
des.monster({ id = "leprechaun", x=01, y=12, peaceful=0 })
des.monster({ id = "water nymph", x=02, y=12, peaceful=0 })
-- North exit
des.monster({ id = "water nymph", x=33, y=01, peaceful=0 })
des.monster({ id = "leprechaun", x=33, y=02, peaceful=0 })
-- East exit
des.monster({ id = "water nymph", x=74, y=05, peaceful=0 })
des.monster({ id = "leprechaun", x=74, y=04, peaceful=0 })
-- South exit
des.monster({ id = "leprechaun", x=25, y=19, peaceful=0 })
des.monster({ id = "water nymph", x=25, y=18, peaceful=0 })
-- Wandering the streets.
for i=1,4 + math.random(1 - 1,1*3) do
des.monster({ id = "water nymph", coord = {streets:rndcoord(1)}, peaceful=0 })
des.monster({ id = "leprechaun", coord = {streets:rndcoord(1)}, peaceful=0 })
end
for i=1,7 + math.random(1 - 1,1*3) do
des.monster({ id = "chameleon", coord = {streets:rndcoord(1)}, peaceful=0 })
end
| mit |
dtsund/dtsund-crawl-mod | source/test/corpse.lua | 1 | 1112 | -----------------------------------------------------------------------
-- Tests for corpse gen.
-----------------------------------------------------------------------
local p = dgn.point(20, 20)
debug.goto_place("D:20")
local function ok(corpse, pattern)
dgn.reset_level()
dgn.fill_grd_area(1, 1, dgn.GXM - 2, dgn.GYM - 2, 'floor')
dgn.create_item(p.x, p.y, corpse)
local items = dgn.items_at(p.x, p.y)
assert(#items > 0, "Could not create item for '" .. corpse .. "'")
assert(#items == 1, "Unexpected item count for '" .. corpse .. "'")
local item = items[1]
local name = item.name('')
pattern = pattern or corpse
assert(string.find(name, pattern, 1, true),
"Unexpected item name: " .. name .. ", expected: " .. pattern)
end
local function fail(corpse, pattern)
assert(not pcall(function ()
ok(corpse, pattern)
end),
"Expected item '" .. corpse .. "' to fail, but it did not")
end
-- All set up!
ok("hydra corpse")
ok("hippogriff skeleton")
ok("any corpse", "corpse")
ok("rat chunk", "chunk of rat")
fail("zombie chunk")
| gpl-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Spire_of_Dem/npcs/_0j3.lua | 39 | 1330 | -----------------------------------
-- Area: Spire_of_Dem
-- NPC: web of regret
-----------------------------------
package.loaded["scripts/zones/Spire_of_Dem/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/zones/Spire_of_Dem/TextIDs");
-----------------------------------
-- 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 1;
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 |
Kosmos82/kosmosdarkstar | scripts/zones/Upper_Jeuno/npcs/Emitt.lua | 14 | 3662 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Emitt
-- @pos -95 0 160 244
-------------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/conquest");
require("scripts/zones/Upper_Jeuno/TextIDs");
local guardnation = OTHER; -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno).
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Menu1 = getArg1(guardnation,player);
local Menu3 = conquestRanking();
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
player:startEvent(0x7ffb,Menu1,0,Menu3,0,0,Menu6,Menu7,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (player:getNation() == 0) then
inventory = SandInv;
size = table.getn(SandInv);
elseif (player:getNation() == 1) then
inventory = BastInv;
size = table.getn(BastInv);
else
inventory = WindInv;
size = table.getn(WindInv);
end
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]); -- can't equip = 2 ?
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
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
itemCP = inventory[Item + 1];
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;
break;
end;
end;
end;
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Phomiuna_Aqueducts/npcs/_0rn.lua | 13 | 1641 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: _0rn (Oil lamp)
-- @pos -60 -23 60 27
-----------------------------------
package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Phomiuna_Aqueducts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorOffset = npc:getID();
player:messageSpecial(LAMP_OFFSET+2); -- water lamp
npc:openDoor(7); -- lamp animation
local element = VanadielDayElement();
--printf("element: %u",element);
if (element == 2) then -- waterday
if (GetNPCByID(DoorOffset+7):getAnimation() == 8) then -- lamp fire open?
GetNPCByID(DoorOffset-2):openDoor(15); -- Open Door _0rk
end
elseif (element == 5) then -- lighningday
if (GetNPCByID(DoorOffset+2):getAnimation() == 8) then -- lamp lightning open?
GetNPCByID(DoorOffset-2):openDoor(15); -- Open Door _0rk
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/The_Garden_of_RuHmet/npcs/_iz2.lua | 13 | 1986 | -----------------------------------
-- 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 |
Kosmos82/kosmosdarkstar | scripts/globals/items/apple_pie.lua | 18 | 1261 | -----------------------------------------
-- ID: 4413
-- Item: Apple Pie
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Magic 25
-- Agility -1
-- Intelligence 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4413);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 25);
target:addMod(MOD_AGI,-1);
target:addMod(MOD_INT, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 25);
target:delMod(MOD_AGI,-1);
target:delMod(MOD_INT, 3);
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/mobskills/Absolute_Terror.lua | 28 | 1378 | ---------------------------------------------------
-- Absolute Terror
-- Causes Terror, which causes the victim to be stunned for the duration of the effect, this can not be removed.
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_SUPER_BUFF)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_INVINCIBLE)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then
return 1;
elseif (target:isBehind(mob, 48) == true) then
return 1;
elseif (mob:AnimationSub() == 1) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_TERROR;
local power = 30;
-- Three minutes is WAY too long, especially on Wyrms. Reduced to Wiki's definition of 'long time'. Reference: http://wiki.ffxiclopedia.org/wiki/Absolute_Terror
local duration = 30;
if (skill:isAoE()) then
duration = 10;
end;
skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration));
return typeEffect;
end
| gpl-3.0 |
harveyhu2012/luci | applications/luci-coovachilli/luasrc/model/cbi/coovachilli_network.lua | 79 | 1639 | --[[
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$
]]--
require("luci.sys")
require("luci.ip")
m = Map("coovachilli")
-- tun
s1 = m:section(TypedSection, "tun")
s1.anonymous = true
s1:option( Flag, "usetap" )
s1:option( Value, "tundev" ).optional = true
s1:option( Value, "txqlen" ).optional = true
net = s1:option( Value, "net" )
for _, route in ipairs(luci.sys.net.routes()) do
if route.device ~= "lo" and route.dest:prefix() < 32 then
net:value( route.dest:string() )
end
end
s1:option( Value, "dynip" ).optional = true
s1:option( Value, "statip" ).optional = true
s1:option( Value, "dns1" ).optional = true
s1:option( Value, "dns2" ).optional = true
s1:option( Value, "domain" ).optional = true
s1:option( Value, "ipup" ).optional = true
s1:option( Value, "ipdown" ).optional = true
s1:option( Value, "conup" ).optional = true
s1:option( Value, "condown" ).optional = true
-- dhcp config
s2 = m:section(TypedSection, "dhcp")
s2.anonymous = true
dif = s2:option( Value, "dhcpif" )
for _, nif in ipairs(luci.sys.net.devices()) do
if nif ~= "lo" then dif:value(nif) end
end
s2:option( Value, "dhcpmac" ).optional = true
s2:option( Value, "lease" ).optional = true
s2:option( Value, "dhcpstart" ).optional = true
s2:option( Value, "dhcpend" ).optional = true
s2:option( Flag, "eapolenable" )
return m
| apache-2.0 |
smasty/rocks2git | rocks2git/config.lua | 1 | 1916 | -- Rocks2Git configuration
-- Part of the LuaDist project - http://luadist.org
-- Author: Martin Srank, hello@smasty.net
-- License: MIT
module("rocks2git.config", package.seeall)
local path = require "pl.path"
local file = require "pl.file"
local stringx = require "pl.stringx"
local logging = require "logging"
-- Configuration ---------------------------------------------------------------
luarocks_timeout = 10 -- Timeout (in sec) for LuaRocks downloads
-- Directories -----------------------------------------------------------------
local data_dir = path.abspath("data")
mirror_dir = path.join(data_dir, "luarocks-mirror") -- LuaRocks rockspec mirror repository
repo_dir = path.join(data_dir, "repos") -- Base path for module repositories
temp_dir = path.join(data_dir, "tmp") -- Temp dir for LuaRocks downloaded modules
manifest_file = path.join(data_dir, "manifest-file") -- Manifest file with module dependencies
-- Blacklist -------------------------------------------------------------------
blacklist_file = path.join(data_dir, "module-blacklist") -- Module blacklist file
blacklist = stringx.split(file.read(blacklist_file))
-- Logging ---------------------------------------------------------------------
log_level = logging.WARN -- Logging level.
log_file = path.join(data_dir, "logs/rocks2git-%s.log") -- Log output file path - %s in place of date
log_date_format = "%Y-%m-%d" -- Log date format
-- Git configuration -----------------------------------------------------------
git_user_name = "LunaCI" -- Author of the Git commits.
git_user_mail = "lunaci@luadist.org" -- Author's e-mail
git_module_source = "git://github.com/LuaDist2/%s.git" -- Module source endpoint - Use %s in place of module name
| mit |
Kosmos82/kosmosdarkstar | scripts/globals/spells/paralyze.lua | 14 | 1952 | -----------------------------------------
-- Spell: Paralyze
-- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:hasStatusEffect(EFFECT_PARALYSIS)) then --effect already on, do nothing
spell:setMsg(75);
else
-- Calculate duration.
local duration = math.random(20,120);
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
-- Grabbing variables for paralyze potency
local pMND = caster:getStat(MOD_MND);
local mMND = target:getStat(MOD_MND);
local dMND = (pMND - mMND);
-- Calculate potency.
local potency = (pMND + dMND)/5; --simplified from (2 * (pMND + dMND)) / 10
if potency > 25 then
potency = 25;
end
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
potency = potency * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
--printf("Duration : %u",duration);
--printf("Potency : %u",potency);
local resist = applyResistanceEffect(caster,spell,target,dMND,35,0,EFFECT_PARALYSIS);
if (resist >= 0.5) then --there are no quarter or less hits, if target resists more than .5 spell is resisted completely
if (target:addStatusEffect(EFFECT_PARALYSIS,potency,0,duration*resist)) then
spell:setMsg(236);
else
-- no effect
spell:setMsg(75);
end
else
-- resist
spell:setMsg(85);
end
end
return EFFECT_PARALYSIS;
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/items/strip_of_buffalo_jerky.lua | 18 | 1385 | -----------------------------------------
-- ID: 5196
-- Item: strip_of_buffalo_jerky
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Strength 4
-- Mind -3
-- Attack % 18
-- Attack Cap 65
-----------------------------------------
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,1800,5196);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 4);
target:addMod(MOD_MND, -3);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 65);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 4);
target:delMod(MOD_MND, -3);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 65);
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Cloister_of_Tremors/mobs/Galgalim.lua | 7 | 1114 | -----------------------------------
-- Area: Cloister of Tremors
-- MOB: Galgalim
-- Involved in Quest: The Puppet Master
-----------------------------------
require("scripts/globals/settings");
-----------------------------------
-- OnMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- OnMobDeath Action
-----------------------------------
function onMobDeath(mob, killer, ally)
ally:setVar("BCNM_Killed",1);
record = 300;
partyMembers = 6;
pZone = ally:getZoneID();
ally:startEvent(0x7d01,0,record,0,(os.time() - ally:getVar("BCNM_Timer")),partyMembers,0,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/mobskills/Haymaker.lua | 33 | 1189 | ---------------------------------------------
-- Haymaker
--
-- Description: Punches the daylights out of all targets in front. Additional effect: Amnesia
-- Type: Physical
-- Utsusemi/Blink absorb: Unknown
-- Range: Front cone
-- Notes: Only used by Gurfurlur the Menacing.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 316) then
local mobSkin = mob:getModelId();
if (mobSkin == 1867) then
return 0;
else
return 1;
end
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_H2H,info.hitslanded);
local typeEffect = EFFECT_AMNESIA;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 60);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/spells/bluemagic/venom_shell.lua | 26 | 1389 | -----------------------------------------
-- Spell: Venom Shell
-- Poisons enemies within range and gradually reduces their HP
-- Spell cost: 86 MP
-- Monster Type: Aquans
-- Spell Type: Magical (Water)
-- Blue Magic Points: 3
-- Stat Bonus: MND+2
-- Level: 42
-- Casting Time: 3 seconds
-- Recast Time: 45 seconds
-- Magic Bursts on: Reverberation, Distortion, and Darkness
-- Combos: Clear Mind
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local typeEffect = EFFECT_POISON
local dINT = caster:getStat(MOD_MND) - target:getStat(MOD_MND);
local resist = applyResistanceEffect(caster,spell,target,dINT,BLUE_SKILL,0,typeEffect);
local duration = 180 * resist;
local power = 6;
if (resist > 0.5) then -- Do it!
if (target:addStatusEffect(typeEffect,power,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end;
return typeEffect;
end;
| gpl-3.0 |
zfm888/bazi_server | common/lib/luaLib/luatz/timetable.lua | 3 | 6980 | local strftime = require "luatz.strftime".strftime
local strformat = string.format
local floor = math.floor
local idiv do
-- Try and use actual integer division when available (Lua 5.3+)
local idiv_loader, err = (loadstring or load)([[return function(n,d) return n//d end]], "idiv")
if idiv_loader then
idiv = idiv_loader()
else
idiv = function(n, d)
return floor(n/d)
end
end
end
local mon_lengths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
-- Number of days in year until start of month; not corrected for leap years
local months_to_days_cumulative = { 0 }
for i = 2, 12 do
months_to_days_cumulative [ i ] = months_to_days_cumulative [ i-1 ] + mon_lengths [ i-1 ]
end
-- For Sakamoto's Algorithm (day of week)
local sakamoto = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
local function is_leap ( y )
if (y % 4) ~= 0 then
return false
elseif (y % 100) ~= 0 then
return true
else
return (y % 400) == 0
end
end
local function year_length ( y )
return is_leap ( y ) and 366 or 365
end
local function month_length ( m , y )
if m == 2 then
return is_leap ( y ) and 29 or 28
else
return mon_lengths [ m ]
end
end
local function leap_years_since ( year )
return idiv ( year , 4 ) - idiv ( year , 100 ) + idiv ( year , 400 )
end
local function day_of_year ( day , month , year )
local yday = months_to_days_cumulative [ month ]
if month > 2 and is_leap ( year ) then
yday = yday + 1
end
return yday + day
end
local function day_of_week ( day , month , year )
if month < 3 then
year = year - 1
end
return ( year + leap_years_since ( year ) + sakamoto[month] + day ) % 7 + 1
end
local function borrow ( tens , units , base )
local frac = tens % 1
units = units + frac * base
tens = tens - frac
return tens , units
end
local function carry ( tens , units , base )
if units >= base then
tens = tens + idiv ( units , base )
units = units % base
elseif units < 0 then
tens = tens - 1 + idiv ( -units , base )
units = base - ( -units % base )
end
return tens , units
end
-- Modify parameters so they all fit within the "normal" range
local function normalise ( year , month , day , hour , min , sec )
-- `month` and `day` start from 1, need -1 and +1 so it works modulo
month , day = month - 1 , day - 1
-- Convert everything (except seconds) to an integer
-- by propagating fractional components down.
year , month = borrow ( year , month , 12 )
-- Carry from month to year first, so we get month length correct in next line around leap years
year , month = carry ( year , month , 12 )
month , day = borrow ( month , day , month_length ( floor ( month + 1 ) , year ) )
day , hour = borrow ( day , hour , 24 )
hour , min = borrow ( hour , min , 60 )
min , sec = borrow ( min , sec , 60 )
-- Propagate out of range values up
-- e.g. if `min` is 70, `hour` increments by 1 and `min` becomes 10
-- This has to happen for all columns after borrowing, as lower radixes may be pushed out of range
min , sec = carry ( min , sec , 60 ) -- TODO: consider leap seconds?
hour , min = carry ( hour , min , 60 )
day , hour = carry ( day , hour , 24 )
-- Ensure `day` is not underflowed
-- Add a whole year of days at a time, this is later resolved by adding months
-- TODO[OPTIMIZE]: This could be slow if `day` is far out of range
while day < 0 do
year = year - 1
day = day + year_length ( year )
end
year , month = carry ( year , month , 12 )
-- TODO[OPTIMIZE]: This could potentially be slow if `day` is very large
while true do
local i = month_length ( month + 1 , year )
if day < i then break end
day = day - i
month = month + 1
if month >= 12 then
month = 0
year = year + 1
end
end
-- Now we can place `day` and `month` back in their normal ranges
-- e.g. month as 1-12 instead of 0-11
month , day = month + 1 , day + 1
return year , month , day , hour , min , sec
end
local leap_years_since_1970 = leap_years_since ( 1970 )
local function timestamp ( year , month , day , hour , min , sec )
year , month , day , hour , min , sec = normalise ( year , month , day , hour , min , sec )
local days_since_epoch = day_of_year ( day , month , year )
+ 365 * ( year - 1970 )
-- Each leap year adds one day
+ ( leap_years_since ( year - 1 ) - leap_years_since_1970 ) - 1
return days_since_epoch * (60*60*24)
+ hour * (60*60)
+ min * 60
+ sec
end
local timetable_methods = { }
function timetable_methods:unpack ( )
return assert ( self.year , "year required" ) ,
assert ( self.month , "month required" ) ,
assert ( self.day , "day required" ) ,
self.hour or 12 ,
self.min or 0 ,
self.sec or 0 ,
self.yday ,
self.wday
end
function timetable_methods:normalise ( )
local year , month , day
year , month , day , self.hour , self.min , self.sec = normalise ( self:unpack ( ) )
self.day = day
self.month = month
self.year = year
self.yday = day_of_year ( day , month , year )
self.wday = day_of_week ( day , month , year )
return self
end
timetable_methods.normalize = timetable_methods.normalise -- American English
function timetable_methods:timestamp ( )
return timestamp ( self:unpack ( ) )
end
function timetable_methods:rfc_3339 ( )
local year , month , day , hour , min , sec = self:unpack ( )
local sec , msec = borrow ( sec , 0 , 1000 )
return strformat ( "%04u-%02u-%02uT%02u:%02u:%02d.%03d" , year , month , day , hour , min , sec , msec )
end
function timetable_methods:strftime ( format_string )
return strftime ( format_string , self )
end
local timetable_mt
local function coerce_arg ( t )
if getmetatable ( t ) == timetable_mt then
return t:timestamp ( )
end
return t
end
timetable_mt = {
__index = timetable_methods ;
__tostring = timetable_methods.rfc_3339 ;
__eq = function ( a , b )
return a:timestamp ( ) == b:timestamp ( )
end ;
__lt = function ( a , b )
return a:timestamp ( ) < b:timestamp ( )
end ;
__sub = function ( a , b )
return coerce_arg ( a ) - coerce_arg ( b )
end ;
}
local function cast_timetable ( tm )
return setmetatable ( tm , timetable_mt )
end
local function new_timetable ( year , month , day , hour , min , sec , yday , wday )
return cast_timetable {
year = year ;
month = month ;
day = day ;
hour = hour ;
min = min ;
sec = sec ;
yday = yday ;
wday = wday ;
}
end
function timetable_methods:clone ( )
return new_timetable ( self:unpack ( ) )
end
local function new_from_timestamp ( ts )
if type ( ts ) ~= "number" then
error ( "bad argument #1 to 'new_from_timestamp' (number expected, got " .. type ( ts ) .. ")" , 2 )
end
return new_timetable ( 1970 , 1 , 1 , 0 , 0 , ts ):normalise ( )
end
return {
is_leap = is_leap ;
day_of_year = day_of_year ;
day_of_week = day_of_week ;
normalise = normalise ;
timestamp = timestamp ;
new = new_timetable ;
new_from_timestamp = new_from_timestamp ;
cast = cast_timetable ;
timetable_mt = timetable_mt ;
}
| gpl-3.0 |
squeek502/luvit | tests/test-require.lua | 6 | 4035 | --[[
Copyright 2012 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.
--]]
require('tap')(function (test)
local makeRequire = require('require')
local pathJoin = require('luvi').path.join
local p = require('utils').prettyPrint
local base = pathJoin(module.dir, "fixtures/fake.lua")
_G.num_loaded = 0
test("native lua require should still be there", function ()
p(require, _G.require)
assert(require ~= _G.require)
end)
test("relative require with extension", function ()
local require = makeRequire(base)
local mod1 = require('./libs/module1/init.lua')
assert(_G.num_loaded == 1)
assert(mod1[1] == "module1")
end)
test("relative require as package with index", function ()
local require = makeRequire(base)
local mod1 = require('./libs/module1')
p(_G.num_loaded)
assert(_G.num_loaded == 1)
assert(mod1[1] == "module1")
end)
test("relative require with auto-extension", function ()
local require = makeRequire(base)
local mod1 = require('./libs/module1/init')
assert(_G.num_loaded == 1)
assert(mod1[1] == "module1")
end)
test("cached with different paths", function ()
local require = makeRequire(base)
local mod1_1 = require('./libs/module1/init.lua')
local mod1_2 = require('./libs/module1/init')
local mod1_3 = require('./libs/module1')
assert(_G.num_loaded == 1)
assert(mod1_1 == mod1_2)
assert(mod1_2 == mod1_3)
end)
test("Lots-o-requires", function ()
local require = makeRequire(base)
local m1 = require("module1")
local m1_m2 = require("module1/module2")
local m2_m2 = require("module2/module2")
local m3 = require("module3")
local rm1 = require("./libs/module1")
local rm1_m2 = require("./libs/module1/module2")
local rm2_m2 = require("./libs/module2/module2")
local rm3 = require('./libs/module3')
local rm2sm1_m2 = require("./libs/module2/../module1/module2")
local rm1sm2_m2 = require("./libs/module1/../module2/module2")
assert(_G.num_loaded == 4)
assert(m1 == rm1)
assert(m1_m2 == rm1_m2 and m1_m2 == rm2sm1_m2)
assert(m2_m2 == rm2_m2 and m2_m2 == rm1sm2_m2)
assert(m3 == rm3)
end)
test("inter-dependencies", function ()
local require = makeRequire(base)
local callbacks = {}
_G.onexit = function (fn)
callbacks[#callbacks + 1] = fn
end
local e = require('./a')
p(e)
p{
A=e.A(),
C=e.C(),
D=e.D(),
}
assert(e.A() == 'A')
assert(e.C() == 'C')
assert(e.D() == 'D')
for i = 1, #callbacks do
callbacks[i]()
end
p(e)
p{
A=e.A(),
C=e.C(),
D=e.D(),
}
assert(e.A() == 'A done')
assert(e.C() == 'C done')
assert(e.D() == 'D done')
end)
test("circular dependencies", function ()
local require = makeRequire(base)
local parent = require('parent');
p(parent)
assert(parent.child.parent == parent)
local child = require('child');
p(child)
assert(child.parent.child == child)
end)
test("deps folder", function ()
local require = makeRequire(base)
_G.num_loaded = 0
local N = require('moduleN')
p(N, _G.num_loaded)
assert(_G.num_loaded == 2)
assert(N[1] == 'moduleN')
assert(N.M[1] == 'moduleM')
end)
end)
-- -- Test native addons
-- --[[
-- local vectors = {
-- require("vector"),
-- require("vector-renamed"),
-- }
-- assert(vectors[1] == vectors[2], "Symlinks should realpath and load real module and reuse cache")
-- ]]
| apache-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Mhaura/npcs/Mauriri.lua | 13 | 1056 | ----------------------------------
-- Area: Mhaura
-- NPC: Mauriri
-- Type: Item Deliverer
-- @pos 10.883 -15.99 66.186 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, MAURIRI_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 |
Kosmos82/kosmosdarkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Sanraku.lua | 28 | 9794 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Sanraku
-- Type: Zeni NM pop item and trophy management.
-- @pos -125.724 0.999 22.136 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/besieged");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--[[
local trophies =
{
2616, 2617, 2618, 2613, 2614, 2615, 2610, 2611, 2612,
2609, 2626, 2627, 2628, 2623, 2624, 2625, 2620, 2621,
2622, 2619, 2636, 2637, 2638, 2633, 2634, 2635, 2630,
2631, 2632, 2629
}
local seals =
{
MAROON_SEAL, MAROON_SEAL, MAROON_SEAL,
APPLE_GREEN_SEAL,APPLE_GREEN_SEAL,APPLE_GREEN_SEAL,
CHARCOAL_GREY_SEAL, DEEP_PURPLE_SEAL, CHESTNUT_COLORED_SEAL,
LILAC_COLORED_SEAL,
CERISE_SEAL,CERISE_SEAL,CERISE_SEAL,
SALMON_COLORED_SEAL,SALMON_COLORED_SEAL,SALMON_COLORED_SEAL,
PURPLISH_GREY_SEAL, GOLD_COLORED_SEAL, COPPER_COLORED_SEAL,
BRIGHT_BLUE_SEAL,
PINE_GREEN_SEAL,PINE_GREEN_SEAL,PINE_GREEN_SEAL,
AMBER_COLORED_SEAL,AMBER_COLORED_SEAL,AMBER_COLORED_SEAL,
FALLOW_COLORED_SEAL,TAUPE_COLORED_SEAL,SIENNA_COLORED_SEAL,
LAVENDER_COLORED_SEAL
}
if (trade:getItemCount() == 1) then
if (trade:hasItemQty(2477,1)) then -- Trade Soul Plate
zeni = math.random(1,200); -- random value since soul plates aren't implemented yet.
player:tradeComplete();
player:addCurrency("zeni_point", zeni);
player:startEvent(0x038E,zeni);
else
znm = -1;
found = false;
while (znm <= 30) and not(found) do
znm = znm + 1;
found = trade:hasItemQty(trophies[znm + 1],1);
end;
if (found) then
znm = znm + 1;
if (player:hasKeyItem(seals[znm]) == false) then
player:tradeComplete();
player:addKeyItem(seals[znm]);
player:startEvent(0x0390,0,0,0,seals[znm]);
else
player:messageSpecial(SANCTION + 8,seals[znm]); -- You already possess .. (not sure this is authentic)
end
end
end
end
]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (player:getVar("ZeniStatus") == 0) then
player:startEvent(0x038c);
else
local param = 2140136440; -- Defaut bitmask, Tier 1 ZNM Menu + don't ask option
-- Tinnin Path
if (player:hasKeyItem(MAROON_SEAL)) then
param = param - 0x38; -- unlocks Tinnin path tier 2 ZNMs.
end;
if (player:hasKeyItem(APPLE_GREEN_SEAL)) then
param = param - 0x1C0; -- unlocks Tinnin path tier 3 ZNMs.
end;
if (player:hasKeyItem(CHARCOAL_GREY_SEAL) and player:hasKeyItem(DEEP_PURPLE_SEAL) and player:hasKeyItem(CHESTNUT_COLORED_SEAL)) then
param = param - 0x200; -- unlocks Tinnin.
end;
-- Sarameya Path
if (player:hasKeyItem(CERISE_SEAL)) then
param = param - 0xE000; -- unlocks Sarameya path tier 2 ZNMs.
end;
if (player:hasKeyItem(SALMON_COLORED_SEAL)) then
param = param - 0x70000; -- unlocks Sarameya path tier 3 ZNMs.
end;
if (player:hasKeyItem(PURPLISH_GREY_SEAL) and player:hasKeyItem(GOLD_COLORED_SEAL) and player:hasKeyItem(COPPER_COLORED_SEAL)) then
param = param - 0x80000; -- unlocks Sarameya.
end;
-- Tyger Path
if (player:hasKeyItem(PINE_GREEN_SEAL)) then
param = param - 0x3800000; -- unlocks Tyger path tier 2 ZNMs.
end;
if (player:hasKeyItem(AMBER_COLORED_SEAL)) then
param = param - 0x1C000000; -- unlocks Tyger path tier 3 ZNMs.
end;
if (player:hasKeyItem(TAUPE_COLORED_SEAL) and player:hasKeyItem(FALLOW_COLORED_SEAL) and player:hasKeyItem(SIENNA_COLORED_SEAL)) then
param = param - 0x20000000; -- unlocks Tyger.
end;
if (player:hasKeyItem(LILAC_COLORED_SEAL) and player:hasKeyItem(BRIGHT_BLUE_SEAL) and player:hasKeyItem(LAVENDER_COLORED_SEAL)) then
param = param - 0x40000000; -- unlocks Pandemonium Warden.
end;
player:startEvent(0x038D,param);
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("updateRESULT: %u",option);
--[[
local lures =
{
2580, 2581, 2582, 2577, 2578, 2579, 2574, 2575, 2576,
2573, 2590, 2591, 2592, 2587, 2588, 2589, 2584, 2585,
2586, 2583, 2600, 2601, 2602, 2597, 2598, 2599, 2594,
2595, 2596, 2593, 2572
}
local seals =
{
MAROON_SEAL, MAROON_SEAL, MAROON_SEAL,
APPLE_GREEN_SEAL,APPLE_GREEN_SEAL,APPLE_GREEN_SEAL,
CHARCOAL_GREY_SEAL, DEEP_PURPLE_SEAL, CHESTNUT_COLORED_SEAL,
LILAC_COLORED_SEAL,
CERISE_SEAL,CERISE_SEAL,CERISE_SEAL,
SALMON_COLORED_SEAL,SALMON_COLORED_SEAL,SALMON_COLORED_SEAL,
PURPLISH_GREY_SEAL, GOLD_COLORED_SEAL, COPPER_COLORED_SEAL,
BRIGHT_BLUE_SEAL,
PINE_GREEN_SEAL,PINE_GREEN_SEAL,PINE_GREEN_SEAL,
AMBER_COLORED_SEAL,AMBER_COLORED_SEAL,AMBER_COLORED_SEAL,
FALLOW_COLORED_SEAL,TAUPE_COLORED_SEAL,SIENNA_COLORED_SEAL,
LAVENDER_COLORED_SEAL
}
if (csid == 0x038D) then
local zeni = player:getCurrency("zeni_point");
if (option >= 300 and option <= 302) then
if (option == 300) then
salt = SICKLEMOON_SALT;
elseif (option == 301) then
salt = SILVER_SEA_SALT;
elseif (option == 302) then
salt = CYAN_DEEP_SALT
end;
if (zeni < 500) then
player:updateEvent(2,500); -- not enough zeni
elseif (player:hasKeyItem(salt)) then
player:updateEvent(3,500); -- has salt already
else
player:updateEvent(1,500,0,salt);
player:addKeyItem(salt);
player:delCurrency("zeni_point", 500);
end
else -- player is interested in buying a pop item.
n = option % 10;
if (n <= 2) then
if (option == 130 or option == 440) then
tier = 5;
else
tier = 1;
end;
elseif (n >= 3 and n <= 5) then
tier = 2;
elseif (n >= 6 and n <= 8) then
tier = 3;
else
tier = 4;
end
cost = tier * 1000; -- static pricing for now.
if (option >= 100 and option <= 130) then
player:updateEvent(0,0,0,0,0,0,cost);
elseif (option >= 400 and option <=440) then
if (option == 440) then
option = 430;
end
item = lures[option-399]
if (option == 430) then -- Pandemonium Warden
keyitem1 = LILAC_COLORED_SEAL; keyitem2 = BRIGHT_BLUE_SEAL; keyitem3 = LAVENDER_COLORED_SEAL;
elseif (option == 409) then -- Tinnin
keyitem1 = CHARCOAL_GREY_SEAL; keyitem2 = DEEP_PURPLE_SEAL; keyitem3 = CHESTNUT_COLORED_SEAL;
elseif (option == 419) then -- Sarameya
keyitem1 = PURPLISH_GREY_SEAL; keyitem2 = GOLD_COLORED_SEAL; keyitem3 = COPPER_COLORED_SEAL;
elseif (option == 429) then -- Tyger
keyitem1 = TAUPE_COLORED_SEAL; keyitem2 = FALLOW_COLORED_SEAL; keyitem3 = SIENNA_COLORED_SEAL;
else
keyitem1 = seals[option - 402]; keyitem2 = nil; keyitem3 = nil;
end
if (cost > zeni) then
player:updateEvent(2, cost, item, keyitem1,keyitem2,keyitem3); -- you don't have enough zeni.
elseif (player:addItem(item)) then
if (keyitem1 ~= nil) then
player:delKeyItem(keyitem1);
end
if (keyitem2 ~= nil) then
player:delKeyItem(keyitem2);
end
if (keyitem3 ~= nil) then
player:delKeyItem(keyitem3);
end
player:updateEvent(1, cost, item, keyitem1,keyitem2,keyitem3);
player:delCurrency("zeni_point", cost);
else
player:updateEvent(4, cost, item, keyitem1,keyitem2,keyitem3); -- Cannot obtain.
end
elseif (option == 500) then -- player has declined to buy a pop item
player:updateEvent(1,1); -- restore the "Gaining access to the islets" option.
else
-- print("onEventSelection - CSID:",csid);
-- print("onEventSelection - option ===",option);
end
end
end
]]
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("finishRESULT: %u",option);
--[[
if (csid == 0x038c) then
player:setVar("ZeniStatus",1);
player:addCurrency("zeni_point", 2000);
end
]]
end; | gpl-3.0 |
rigeirani/creed | 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 |
Ingenious-Gaming/sf_addons | lua/starfall/libs_cl/panel/dhtmlcontrols.lua | 1 | 1326 | SF.Panel.DHTMLControls = {}
local this_methods, this_metamethods = SF.Typedef( "Panel.DHTMLControls", SF.Panel.Panel.Metatable )
local punwrap = SF.Panel.unwrap
local function pwrap( object )
object = SF.Panel.wrap( object )
debug.setmetatable( object, this_metamethods )
return object
end
this_metamethods.__newindex = SF.Panel.Panel.Metatable.__newindex
SF.Panel.DHTMLControls.wrap = pwrap
SF.Panel.DHTMLControls.unwrap = punwrap
SF.Panel.DHTMLControls.Methods = this_methods
SF.Panel.DHTMLControls.Metatable = this_metamethods
--- Links the controls to the DHTML frame supplied
--@param html The DHTML window to link
function this_methods:setHTML( html )
SF.CheckType( self, this_metamethods )
SF.CheckType( html, SF.Panel.DHTML.Metatable )
punwrap( self ):SetHTML( punwrap( html ) )
end
--- Updates the history of the browser
--@param url The url to add to the history
function this_methods:updateHistory( url )
SF.CheckType( self, this_metamethods )
SF.CheckType( url, "string" )
punwrap( self ):UpdateHistory( url )
end
--- Sets the color of the control buttons
--@param color The new color of the buttons
function this_methods:setButtonColor( color )
SF.CheckType( self, this_metamethods )
SF.CheckType( color, SF.Types[ "Color" ] )
punwrap( self ):SetButtonColor( SF.UnwrapObject( color ) )
end | gpl-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/AlTaieu/mobs/Jailer_of_Justice.lua | 6 | 1415 | -----------------------------------
-- Area: Al'Taieu
-- NM: Jailer of Justice
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob, target)
local popTime = mob:getLocalVar("lastPetPop");
-- ffxiclopedia says 30 sec, bgwiki says 1-2 min..
-- Going with 60 seconds until I see proof of retails timing.
if (os.time() - popTime > 60) then
local alreadyPopped = false;
for Xzomit = mob:getID()+1, mob:getID()+6 do
if (alreadyPopped == true) then
break;
else
if (GetMobAction(Xzomit) == ACTION_NONE or GetMobAction(Xzomit) == ACTION_SPAWN) then
SpawnMob(Xzomit, 300):updateEnmity(target);
mob:setLocalVar("lastPetPop", os.time());
alreadyPopped = true;
end
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer, ally)
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Garlaige_Citadel_[S]/npcs/Randecque.lua | 29 | 1746 | -----------------------------------
-- Area: Garlaige Citadel [S]
-- NPC: Randecque
-- @pos 61 -6 137 164
-- Notes: Gives Red Letter required to start "Steamed Rams"
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Garlaige_Citadel_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCampaignAllegiance() > 0) then
if (player:getCampaignAllegiance() == 2) then
player:startEvent(3);
else
-- message for other nations missing
player:startEvent(3);
end
elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == true) then
player:startEvent(2);
elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == false) then
player:startEvent(1);
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 == 1 and option == 0) then
player:addKeyItem(RED_RECOMMENDATION_LETTER);
player:messageSpecial(KEYITEM_OBTAINED, RED_RECOMMENDATION_LETTER);
end
end; | gpl-3.0 |
firebaugh/Digitowls | WebotsController/Player/BodyFSM/NaoDemo/BodyFSM.lua | 3 | 1325 | module(..., package.seeall);
require('Body')
require('fsm')
require('bodyIdle')
require('bodyStart')
require('bodyStop')
require('bodyReady')
require('bodySearch')
require('bodyApproach')
require('bodyKick')
require('bodyPosition')
sm = fsm.new(bodyIdle);
sm:add_state(bodyStart);
sm:add_state(bodyStop);
sm:add_state(bodyReady);
sm:add_state(bodySearch);
sm:add_state(bodyApproach);
sm:add_state(bodyKick);
sm:add_state(bodyPosition);
sm:set_transition(bodyStart, 'done', bodyPosition);
sm:set_transition(bodyPosition, 'timeout', bodyPosition);
sm:set_transition(bodyPosition, 'ballLost', bodySearch);
sm:set_transition(bodyPosition, 'ballClose', bodyApproach);
sm:set_transition(bodySearch, 'ball', bodyPosition);
sm:set_transition(bodySearch, 'timeout', bodyPosition);
sm:set_transition(bodyApproach, 'ballFar', bodyPosition);
sm:set_transition(bodyApproach, 'ballLost', bodySearch);
sm:set_transition(bodyApproach, 'timeout', bodyPosition);
sm:set_transition(bodyApproach, 'kick', bodyKick);
sm:set_transition(bodyKick, 'done', bodyPosition);
sm:set_transition(bodyPosition, 'fall', bodyPosition);
sm:set_transition(bodyApproach, 'fall', bodyPosition);
sm:set_transition(bodyKick, 'fall', bodyPosition);
function entry()
sm:entry()
end
function update()
sm:update();
end
function exit()
sm:exit();
end
| gpl-3.0 |
aStonedPenguin/fprp | entities/weapons/keys/cl_menu.lua | 1 | 7073 | local function AddButtonToFrame(Frame)
Frame:SetTall(Frame:GetTall() + 110);
local button = vgui.Create("DButton", Frame);
button:SetPos(10, Frame:GetTall() - 110);
button:SetSize(180, 100);
return button
end
local function AdminMenuAdditions(Frame, ent, entType)
local DisableOwnage = AddButtonToFrame(Frame);
DisableOwnage:SetText(fprp.getPhrase(ent:getKeysNonOwnable() and "allow_ownership" or "disallow_ownership"));
DisableOwnage.DoClick = function() Frame:Close() RunConsoleCommand("fprp", "toggleownable") end
if ent:getKeysNonOwnable() and entType then
local DoorTitle = AddButtonToFrame(Frame);
DoorTitle:SetText(fprp.getPhrase("set_x_title", entType));
DoorTitle.DoClick = function()
Derma_StringRequest(fprp.getPhrase("set_x_title", entType), fprp.getPhrase("set_x_title_long", entType), "", function(text)
RunConsoleCommand("fprp", "title", text);
if ValidPanel(Frame) then
Frame:Close();
end
end,
function() end, fprp.getPhrase("ok"), fprp.getPhrase("cancel"))
end
else
local EditDoorGroups = AddButtonToFrame(Frame);
EditDoorGroups:SetText(fprp.getPhrase("edit_door_group"));
EditDoorGroups.DoClick = function()
local menu = DermaMenu();
local groups = menu:AddSubMenu(fprp.getPhrase("door_groups"));
local teams = menu:AddSubMenu(fprp.getPhrase("jobs"));
local add = teams:AddSubMenu(fprp.getPhrase("add"));
local remove = teams:AddSubMenu(fprp.getPhrase("remove"));
menu:AddOption(fprp.getPhrase("none"), function() RunConsoleCommand("fprp", "togglegroupownable") Frame:Close() end)
for k,v in pairs(RPExtraTeamDoors) do
groups:AddOption(k, function()
RunConsoleCommand("fprp", "togglegroupownable", k);
if ValidPanel(Frame) then
Frame:Close();
end
end);
end
local doorTeams = ent:getKeysDoorTeams();
for k,v in pairs(RPExtraTeams) do
if not doorTeams or not doorTeams[k] then
add:AddOption(v.name, function()
RunConsoleCommand("fprp", "toggleteamownable", k);
if ValidPanel(Frame) then
Frame:Close();
end
end);
else
remove:AddOption(v.name, function()
RunConsoleCommand("fprp", "toggleteamownable", k);
if ValidPanel(Frame) then
Frame:Close();
end
end);
end
end
menu:Open();
end
end
end
fprp.stub{
name = "openKeysMenu",
description = "Open the keys/F2 menu.",
parameters = {},
realm = "Client",
returns = {},
metatable = fprp
}
local KeyFrameVisible = false
function fprp.openKeysMenu(um)
if KeyFrameVisible then return end
local ent = LocalPlayer():GetEyeTrace().Entity
-- Don't open the menu if the entity is not ownable, the entity is too far away or the door settings are not loaded yet
if not IsValid(ent) or not ent:isKeysOwnable() or ent:GetPos():Distance(LocalPlayer():GetPos()) > 200 then return end
KeyFrameVisible = true
local Frame = vgui.Create("DFrame");
Frame:SetSize(200, 30) -- base size
Frame:SetVisible(true);
Frame:MakePopup();
function Frame:Think()
local ent = LocalPlayer():GetEyeTrace().Entity
if not IsValid(ent) or not ent:isKeysOwnable() or ent:GetPos():Distance(LocalPlayer():GetPos()) > 200 then
self:Close();
end
if not self.Dragging then return end
local x = gui.MouseX() - self.Dragging[1]
local y = gui.MouseY() - self.Dragging[2]
x = math.Clamp(x, 0, ScrW() - self:GetWide());
y = math.Clamp(y, 0, ScrH() - self:GetTall());
self:SetPos(x, y);
end
local entType = fprp.getPhrase(ent:IsVehicle() and "vehicle" or "door");
Frame:SetTitle(fprp.getPhrase("x_options", entType:gsub("^%a", string.upper)));
function Frame:Close()
KeyFrameVisible = false
self:SetVisible(false);
self:Remove();
end
if ent:isKeysOwnedBy(LocalPlayer()) then
local Owndoor = AddButtonToFrame(Frame);
Owndoor:SetText(fprp.getPhrase("sell_x", entType));
Owndoor.DoClick = function() RunConsoleCommand("fprp", "toggleown") Frame:Close() end
local AddOwner = AddButtonToFrame(Frame);
AddOwner:SetText(fprp.getPhrase("add_owner"));
AddOwner.DoClick = function()
local menu = DermaMenu();
menu.found = false
for k,v in pairs(fprp.nickSortedPlayers()) do
if not ent:isKeysOwnedBy(v) and not ent:isKeysAllowedToOwn(v) then
local steamID = v:SteamID();
menu.found = true
menu:AddOption(v:Nick(), function() RunConsoleCommand("fprp", "ao", steamID) end)
end
end
if not menu.found then
menu:AddOption(fprp.getPhrase("noone_available"), function() end)
end
menu:Open();
end
local RemoveOwner = AddButtonToFrame(Frame);
RemoveOwner:SetText(fprp.getPhrase("remove_owner"));
RemoveOwner.DoClick = function()
local menu = DermaMenu();
for k,v in pairs(fprp.nickSortedPlayers()) do
if (ent:isKeysOwnedBy(v) and not ent:isMasterOwner(v)) or ent:isKeysAllowedToOwn(v) then
local steamID = v:SteamID();
menu.found = true
menu:AddOption(v:Nick(), function() RunConsoleCommand("fprp", "ro", steamID) end)
end
end
if not menu.found then
menu:AddOption(fprp.getPhrase("noone_available"), function() end)
end
menu:Open();
end
if not ent:isMasterOwner(LocalPlayer()) then
RemoveOwner:SetDisabled(true);
end
local DoorTitle = AddButtonToFrame(Frame);
DoorTitle:SetText(fprp.getPhrase("set_x_title", entType));
DoorTitle.DoClick = function()
Derma_StringRequest(fprp.getPhrase("set_x_title", entType), fprp.getPhrase("set_x_title_long", entType), "", function(text)
RunConsoleCommand("fprp", "title", text);
if ValidPanel(Frame) then
Frame:Close();
end
end,
function() end, fprp.getPhrase("ok"), fprp.getPhrase("cancel"))
end
elseif not ent:isKeysOwnedBy(LocalPlayer()) and not ent:isKeysOwned() and not ent:getKeysNonOwnable() and not ent:getKeysDoorGroup() and not ent:getKeysDoorTeams() then
if LocalPlayer():hasfprpPrivilege("rp_doorManipulation") then
local Owndoor = AddButtonToFrame(Frame);
Owndoor:SetText(fprp.getPhrase("buy_x", entType));
Owndoor.DoClick = function() RunConsoleCommand("fprp", "toggleown") Frame:Close() end
AdminMenuAdditions(Frame, ent, entType);
else
RunConsoleCommand("fprp", "toggleown");
Frame:Close();
KeyFrameVisible = true
timer.Simple(0.3, function() KeyFrameVisible = false end)
end
elseif not ent:isKeysOwnedBy(LocalPlayer()) and ent:isKeysAllowedToOwn(LocalPlayer()) then
if LocalPlayer():hasfprpPrivilege("rp_doorManipulation") then
local Owndoor = AddButtonToFrame(Frame);
Owndoor:SetText(fprp.getPhrase("coown_x", entType));
Owndoor.DoClick = function() RunConsoleCommand("fprp", "toggleown") Frame:Close() end
AdminMenuAdditions(Frame, ent, entType);
else
RunConsoleCommand("fprp", "toggleown");
Frame:Close();
KeyFrameVisible = true
timer.Simple(0.3, function() KeyFrameVisible = false end)
end
elseif LocalPlayer():hasfprpPrivilege("rp_doorManipulation") then
AdminMenuAdditions(Frame, ent, entType);
else
Frame:Close();
end
Frame:Center();
Frame:SetSkin(GAMEMODE.Config.fprpSkin);
end
usermessage.Hook("KeysMenu", fprp.openKeysMenu);
| mit |
Kosmos82/kosmosdarkstar | scripts/globals/items/ilm-long_salmon_sub.lua | 18 | 1492 | -----------------------------------------
-- ID: 4266
-- Item: ilm-long_salmon_sub
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Dexterity 2
-- Agility 1
-- Vitality 1
-- Intelligence 2
-- Mind -2
-- Ranged ACC 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4266);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, 1);
target:addMod(MOD_INT, 2);
target:addMod(MOD_MND, -2);
target:addMod(MOD_RACC, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, 1);
target:delMod(MOD_INT, 2);
target:delMod(MOD_MND, -2);
target:delMod(MOD_RACC, 3);
end;
| gpl-3.0 |
Igalia/snabb | src/apps/lwaftr/lwutil.lua | 4 | 5728 | module(..., package.seeall)
local constants = require("apps.lwaftr.constants")
local S = require("syscall")
local bit = require("bit")
local ffi = require("ffi")
local lib = require("core.lib")
local cltable = require("lib.cltable")
local binary = require("lib.yang.binary")
local band = bit.band
local cast = ffi.cast
local uint16_ptr_t = ffi.typeof("uint16_t*")
local uint32_ptr_t = ffi.typeof("uint32_t*")
local constants_ipv6_frag = constants.ipv6_frag
local ehs = constants.ethernet_header_size
local o_ipv4_flags = constants.o_ipv4_flags
local ntohs = lib.ntohs
-- Return device PCI address, queue ID, and queue configuration.
function parse_instance(conf)
if conf.worker_config then
local device = conf.worker_config.device
local id = conf.worker_config.queue_id
local queue = conf.softwire_config.instance[device].queue[id]
return device, id, queue
else
local device, id
for dev in pairs(conf.softwire_config.instance) do
assert(not device, "Config contains more than one device")
device = dev
end
for queue in pairs(conf.softwire_config.instance[device].queue) do
assert(not id, "Config contains more than one queue")
id = queue
end
return device, id, conf.softwire_config.instance[device].queue[id]
end
end
function is_on_a_stick(conf, device)
local instance = conf.softwire_config.instance[device]
if not instance.external_device then return true end
return device == instance.external_device
end
function is_lowest_queue(conf)
local device, id = parse_instance(conf)
for n in pairs(conf.softwire_config.instance[device].queue) do
if id > n then return false end
end
return true
end
function num_queues(conf)
local n = 0
local device, id = parse_instance(conf)
for _ in pairs(conf.softwire_config.instance[device].queue) do
n = n + 1
end
return n
end
function select_instance(conf)
local copier = binary.config_copier_for_schema_by_name('snabb-softwire-v3')
local device, id = parse_instance(conf)
local copy = copier(conf)()
local instance = copy.softwire_config.instance
for other_device, queues in pairs(conf.softwire_config.instance) do
if other_device ~= device then
instance[other_device] = nil
else
for other_id, _ in pairs(queues.queue) do
if other_id ~= id then
instance[device].queue[other_id] = nil
end
end
end
end
return copy
end
function merge_instance (conf)
local function table_merge(t1, t2)
local ret = {}
for k,v in pairs(t1) do ret[k] = v end
for k,v in pairs(t2) do ret[k] = v end
return ret
end
local copier = binary.config_copier_for_schema_by_name('snabb-softwire-v3')
local copy = copier(conf)()
local _, _, queue = parse_instance(conf)
copy.softwire_config.external_interface = table_merge(
conf.softwire_config.external_interface, queue.external_interface)
copy.softwire_config.internal_interface = table_merge(
conf.softwire_config.internal_interface, queue.internal_interface)
return copy
end
function get_ihl_from_offset(pkt, offset)
local ver_and_ihl = pkt.data[offset]
return band(ver_and_ihl, 0xf) * 4
end
-- The rd16/wr16/rd32/wr32 functions are provided for convenience.
-- They do NO conversion of byte order; that is the caller's responsibility.
function rd16(offset)
return cast(uint16_ptr_t, offset)[0]
end
function wr16(offset, val)
cast(uint16_ptr_t, offset)[0] = val
end
function rd32(offset)
return cast(uint32_ptr_t, offset)[0]
end
function wr32(offset, val)
cast(uint32_ptr_t, offset)[0] = val
end
function keys(t)
local result = {}
for k,_ in pairs(t) do
table.insert(result, k)
end
return result
end
local uint64_ptr_t = ffi.typeof('uint64_t*')
function ipv6_equals(a, b)
local x, y = ffi.cast(uint64_ptr_t, a), ffi.cast(uint64_ptr_t, b)
return x[0] == y[0] and x[1] == y[1]
end
-- Local bindings for constants that are used in the hot path of the
-- data plane. Not having them here is a 1-2% performance penalty.
local o_ethernet_ethertype = constants.o_ethernet_ethertype
local n_ethertype_ipv4 = constants.n_ethertype_ipv4
local n_ethertype_ipv6 = constants.n_ethertype_ipv6
function is_ipv6(pkt)
return rd16(pkt.data + o_ethernet_ethertype) == n_ethertype_ipv6
end
function is_ipv4(pkt)
return rd16(pkt.data + o_ethernet_ethertype) == n_ethertype_ipv4
end
function is_ipv6_fragment(pkt)
if not is_ipv6(pkt) then return false end
return pkt.data[ehs + constants.o_ipv6_next_header] == constants_ipv6_frag
end
function is_ipv4_fragment(pkt)
if not is_ipv4(pkt) then return false end
-- Either the packet has the "more fragments" flag set,
-- or the fragment offset is non-zero, or both.
local flag_more_fragments_mask = 0x2000
local non_zero_offset = 0x1FFF
local flags_and_frag_offset = ntohs(rd16(pkt.data + ehs + o_ipv4_flags))
return band(flags_and_frag_offset, flag_more_fragments_mask) ~= 0 or
band(flags_and_frag_offset, non_zero_offset) ~= 0
end
function write_to_file(filename, content)
local fd, err = io.open(filename, "wt+")
if not fd then error(err) end
fd:write(content)
fd:close()
end
function fatal (msg)
print(msg)
main.exit(1)
end
function file_exists(path)
local stat = S.stat(path)
return stat and stat.isreg
end
function dir_exists(path)
local stat = S.stat(path)
return stat and stat.isdir
end
function nic_exists(pci_addr)
local devices="/sys/bus/pci/devices"
return dir_exists(("%s/%s"):format(devices, pci_addr)) or
dir_exists(("%s/0000:%s"):format(devices, pci_addr))
end
| apache-2.0 |
ychoucha/minetest-game-mineclone | mods/farming/carrots.lua | 3 | 2399 | minetest.register_node("farming:carrot_1", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
drop = "farming:carrot_item",
tiles = {"farming_carrot_1.png"},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.125, 0.5}
},
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1,dig_by_water=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_node("farming:carrot_2", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
drop = "farming:carrot_item",
tiles = {"farming_carrot_2.png"},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.125, 0.5}
},
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1,dig_by_water=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_node("farming:carrot_3", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
drop = "farming:carrot_item",
tiles = {"farming_carrot_3.png"},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.125, 0.5}
},
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1,dig_by_water=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_node("farming:carrot", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
tiles = {"farming_carrot_4.png"},
drop = {
max_items = 1,
items = {
{ items = {'farming:carrot_item 2'} },
{ items = {'farming:carrot_item 3'}, rarity = 2 },
{ items = {'farming:carrot_item 4'}, rarity = 5 }
}
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1,dig_by_water=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_craftitem("farming:carrot_item", {
description = "Carrot",
inventory_image = "farming_carrot.png",
on_use = minetest.item_eat(3),
on_place = function(itemstack, placer, pointed_thing)
return farming:place_seed(itemstack, placer, pointed_thing, "farming:carrot_1")
end
})
minetest.register_craftitem("farming:carrot_item_gold", {
description = "Golden Carrot",
inventory_image = "farming_carrot_gold.png",
on_use = minetest.item_eat(3),
})
minetest.register_craft({
output = "farming:carrot_item_gold",
recipe = {
{'default:gold_lump'},
{'farming:carrot_item'},
}
})
farming:add_plant("farming:carrot", {"farming:carrot_1", "farming:carrot_2", "farming:carrot_3"}, 50, 20)
| lgpl-2.1 |
Kosmos82/kosmosdarkstar | scripts/zones/Castle_Oztroja/npcs/Treasure_Chest.lua | 13 | 3776 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Treasure Chest
-- Involved In Quest: Scattered into Shadow
-- @pos 7.378 -16.293 -193.590 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Castle_Oztroja/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 43;
local TreasureMinLvL = 33;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--trade:hasItemQty(1035,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(1035,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: AF1 BST QUEST Beast collar -----------
if (player:getQuestStatus(JEUNO,SCATTERED_INTO_SHADOW) == QUEST_ACCEPTED and
player:getVar("scatIntoShadowCS") == 1 and player:hasItem(13121) == false) 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:addItem(13121);
player:messageSpecial(ITEM_OBTAINED,13121); -- Beast collar
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,1035);
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 |
Kosmos82/kosmosdarkstar | scripts/zones/Kazham/npcs/Ronta-Onta.lua | 12 | 4477 | -----------------------------------
-- 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,30);
player:completeQuest(OUTLANDS,TRIAL_BY_FIRE);
end
end
end; | gpl-3.0 |
Kazuo256/luxproject | lib/lux/class.lua | 1 | 5446 | --[[
--
-- Copyright (c) 2013-2017 Wilson Kazuo Mizutani
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to
-- deal in the Software without restriction, including without limitation the
-- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-- sell copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE
--
--]]
--- A class-based implementation object oriented programming.
-- Ironically, this is actually a prototype, which means it inherits from
-- @{lux.prototype}, but otherwise provides its own mechanism for OOP.
-- Be sure to check @{instance}, @{inherit} and @{super} usages.
--
-- ***This module requires macro takeover in order to work properly***
--
-- @usage
-- local MyClass = require 'lux.class' :new{}
-- @prototype lux.class
local class = require 'lux.prototype' :new {}
--- Defines how an instance of the class should be constructed.
-- This function is supposed to only be overriden, not called from the user's
-- side. By populating the `_ENV` parameter provided in this factory-like
-- strategy method is what creates class instances in this OOP feature.
-- This is actually done automatically: every "global" variable or function
-- you define inside this function is instead stored as a corresponding object
-- field.
--
-- @tparam object obj
-- The to-be-constructed object. On Lua5.2+, you may name it _ENV if you know
-- what you are doing.
--
-- @param ...
-- Arguments required by the construction of objects from the current class
--
-- @see some.lua
--
-- @usage
-- local MyClass = require 'lux.class' :new{}
-- local print = print -- must explicitly enclosure dependencies
-- function MyClass:instance (obj, x)
-- -- public field
-- obj.y = 1337
-- -- private field
-- local a_number = 42
-- -- public method
-- function obj.show ()
-- print(a_number + x)
-- end
-- end
--
-- myobj = MyClass(8001)
-- -- call without colons!
-- myobj.show()
function class:instance (_ENV, ...)
-- Does nothing
end
--- Makes this class inherit from another.
-- This guarantess that instances from the former are also instances from the
-- latter. The semantics differs from that of inheritance through prototyping!
-- Also, it is necessary to call @{super} inside the current class'
-- @{instance} definition method since there is no way of guessing how the
-- parent class' constructor should be called.
--
-- @tparam class another_class
-- The class being inherited from
--
-- @see class:super
--
-- @usage
-- local class = require 'lux.class'
-- local ParentClass = class:new{}
-- local ChildClass = class:new{}
-- ChildClass:inherit(ParentClass)
function class:inherit (another_class)
assert(not self.__parent, "Multiple inheritance not allowed!")
assert(another_class:__super() == class, "Must inherit a class!")
self.__parent = another_class
end
local makeInstance
function makeInstance (ofclass, obj, ...)
ofclass:instance(obj, ...)
end
local operator_meta = {}
function operator_meta:__newindex (key, value)
rawset(self, "__"..key, value)
end
--- The class constructor.
-- This is how someone actually instantiates objects from this class system.
-- After having created a new class and defined its @{instance} method, calling
-- the class itself behaves as expected by calling the constructor that will
-- use the @{instance} method to create the object.
--
-- @param ...
-- The constructor parameters as specified in the @{instance}
--
-- @treturn object
-- A new instance from the current class.
function class:__call (...)
local obj = {
__class = self,
__extended = not self.__parent,
__operator = setmetatable({}, operator_meta)
}
makeInstance(self, obj, ...)
assert(obj.__extended, "Missing call to parent constructor!")
return setmetatable(obj, obj.__operator)
end
class.__init = {
__call = class.__call
}
--- Calls the parent class' constructor.
-- Should only be called inside this class' @{instance} definition method when
-- it inherits from another class.
--
-- @tparam object obj
-- The object being constructed by the child class, that is, the `_ENV`
-- parameter passed to @{instance}
--
-- @param ...
-- The parent class' constructor parameters
--
-- @see class:inherit
--
-- @usage
-- -- After ChildClass inherited ParentClass
-- function ChildClass:instance (obj, x, y)
-- self:super(obj, x + y) -- parent's constructor parameters
-- -- Finish instancing
-- end
function class:super (obj, ...)
assert(not obj.__extended, "Already called parent constructor!")
makeInstance(self.__parent, obj, ...)
obj.__extended = true
end
return class
| mit |
Igalia/snabb | lib/luajit/dynasm/dasm_x86.lua | 32 | 71256 | ------------------------------------------------------------------------------
-- DynASM x86/x64 module.
--
-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
local x64 = x64
-- Module information:
local _info = {
arch = x64 and "x64" or "x86",
description = "DynASM x86/x64 module",
version = "1.4.0",
vernum = 10400,
release = "2015-10-18",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub
local concat, sort, remove = table.concat, table.sort, table.remove
local bit = bit or require("bit")
local band, bxor, shl, shr = bit.band, bit.bxor, bit.lshift, bit.rshift
-- Inherited tables and callbacks.
local g_opt, g_arch
local wline, werror, wfatal, wwarn
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
-- int arg, 1 buffer pos:
"DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB",
-- action arg (1 byte), int arg, 1 buffer pos (reg/num):
"VREG", "SPACE",
-- ptrdiff_t arg, 1 buffer pos (address): !x64
"SETLABEL", "REL_A",
-- action arg (1 byte) or int arg, 2 buffer pos (link, offset):
"REL_LG", "REL_PC",
-- action arg (1 byte) or int arg, 1 buffer pos (link):
"IMM_LG", "IMM_PC",
-- action arg (1 byte) or int arg, 1 buffer pos (offset):
"LABEL_LG", "LABEL_PC",
-- action arg (1 byte), 1 buffer pos (offset):
"ALIGN",
-- action args (2 bytes), no buffer pos.
"EXTERN",
-- action arg (1 byte), no buffer pos.
"ESC",
-- no action arg, no buffer pos.
"MARK",
-- action arg (1 byte), no buffer pos, terminal action:
"SECTION",
-- no args, no buffer pos, terminal action:
"STOP"
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number (dynamically generated below).
local map_action = {}
-- First action number. Everything below does not need to be escaped.
local actfirst = 256-#action_names
-- Action list buffer and string (only used to remove dupes).
local actlist = {}
local actstr = ""
-- Argument list for next dasm_put(). Start with offset 0 into action list.
local actargs = { 0 }
-- Current number of section buffer positions for dasm_put().
local secpos = 1
-- VREG kind encodings, pre-shifted by 5 bits.
local map_vreg = {
["modrm.rm.m"] = 0x00,
["modrm.rm.r"] = 0x20,
["opcode"] = 0x20,
["sib.base"] = 0x20,
["sib.index"] = 0x40,
["modrm.reg"] = 0x80,
["vex.v"] = 0xa0,
["imm.hi"] = 0xc0,
}
-- Current number of VREG actions contributing to REX/VEX shrinkage.
local vreg_shrink_count = 0
------------------------------------------------------------------------------
-- Compute action numbers for action names.
for n,name in ipairs(action_names) do
local num = actfirst + n - 1
map_action[name] = num
end
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
local last = actlist[nn] or 255
actlist[nn] = nil -- Remove last byte.
if nn == 0 then nn = 1 end
out:write("static const unsigned char ", name, "[", nn, "] = {\n")
local s = " "
for n,b in ipairs(actlist) do
s = s..b..","
if #s >= 75 then
assert(out:write(s, "\n"))
s = " "
end
end
out:write(s, last, "\n};\n\n") -- Add last byte back.
end
------------------------------------------------------------------------------
-- Add byte to action list.
local function wputxb(n)
assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, a, num)
wputxb(assert(map_action[action], "bad action name `"..action.."'"))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Optionally add a VREG action.
local function wvreg(kind, vreg, psz, sk, defer)
if not vreg then return end
waction("VREG", vreg)
local b = assert(map_vreg[kind], "bad vreg kind `"..vreg.."'")
if b < (sk or 0) then
vreg_shrink_count = vreg_shrink_count + 1
end
if not defer then
b = b + vreg_shrink_count * 8
vreg_shrink_count = 0
end
wputxb(b + (psz or 0))
end
-- Add call to embedded DynASM C code.
local function wcall(func, args)
wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true)
end
-- Delete duplicate action list chunks. A tad slow, but so what.
local function dedupechunk(offset)
local al, as = actlist, actstr
local chunk = char(unpack(al, offset+1, #al))
local orig = find(as, chunk, 1, true)
if orig then
actargs[1] = orig-1 -- Replace with original offset.
for i=offset+1,#al do al[i] = nil end -- Kill dupe.
else
actstr = as..chunk
end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
local offset = actargs[1]
if #actlist == offset then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
dedupechunk(offset)
wcall("put", actargs) -- Add call to dasm_put().
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped byte.
local function wputb(n)
if n >= actfirst then waction("ESC") end -- Need to escape byte.
wputxb(n)
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 10
local map_global = setmetatable({}, { __index = function(t, name)
if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end
local n = next_global
if n > 246 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end})
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=10,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("enum {\n")
for i=10,next_global-1 do
out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=10,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern = -1
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n < -256 then werror("too many extern labels") end
next_extern = n - 1
t[name] = n
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
local t = {}
for name, n in pairs(map_extern) do t[-n] = name end
out:write("Extern labels:\n")
for i=1,-next_extern-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
local t = {}
for name, n in pairs(map_extern) do t[-n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=1,-next_extern-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
local map_archdef = {} -- Ext. register name -> int. name.
local map_reg_rev = {} -- Int. register name -> ext. name.
local map_reg_num = {} -- Int. register name -> register number.
local map_reg_opsize = {} -- Int. register name -> operand size.
local map_reg_valid_base = {} -- Int. register name -> valid base register?
local map_reg_valid_index = {} -- Int. register name -> valid index register?
local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex.
local reg_list = {} -- Canonical list of int. register names.
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for _PTx macros).
local addrsize = x64 and "q" or "d" -- Size for address operands.
-- Helper functions to fill register maps.
local function mkrmap(sz, cl, names)
local cname = format("@%s", sz)
reg_list[#reg_list+1] = cname
map_archdef[cl] = cname
map_reg_rev[cname] = cl
map_reg_num[cname] = -1
map_reg_opsize[cname] = sz
if sz == addrsize or sz == "d" then
map_reg_valid_base[cname] = true
map_reg_valid_index[cname] = true
end
if names then
for n,name in ipairs(names) do
local iname = format("@%s%x", sz, n-1)
reg_list[#reg_list+1] = iname
map_archdef[name] = iname
map_reg_rev[iname] = name
map_reg_num[iname] = n-1
map_reg_opsize[iname] = sz
if sz == "b" and n > 4 then map_reg_needrex[iname] = false end
if sz == addrsize or sz == "d" then
map_reg_valid_base[iname] = true
map_reg_valid_index[iname] = true
end
end
end
for i=0,(x64 and sz ~= "f") and 15 or 7 do
local needrex = sz == "b" and i > 3
local iname = format("@%s%x%s", sz, i, needrex and "R" or "")
if needrex then map_reg_needrex[iname] = true end
local name
if sz == "o" or sz == "y" then name = format("%s%d", cl, i)
elseif sz == "f" then name = format("st%d", i)
else name = format("r%d%s", i, sz == addrsize and "" or sz) end
map_archdef[name] = iname
if not map_reg_rev[iname] then
reg_list[#reg_list+1] = iname
map_reg_rev[iname] = name
map_reg_num[iname] = i
map_reg_opsize[iname] = sz
if sz == addrsize or sz == "d" then
map_reg_valid_base[iname] = true
map_reg_valid_index[iname] = true
end
end
end
reg_list[#reg_list+1] = ""
end
-- Integer registers (qword, dword, word and byte sized).
if x64 then
mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"})
end
mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"})
mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"})
mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"})
map_reg_valid_index[map_archdef.esp] = false
if x64 then map_reg_valid_index[map_archdef.rsp] = false end
if x64 then map_reg_needrex[map_archdef.Rb] = true end
map_archdef["Ra"] = "@"..addrsize
-- FP registers (internally tword sized, but use "f" as operand size).
mkrmap("f", "Rf")
-- SSE registers (oword sized, but qword and dword accessible).
mkrmap("o", "xmm")
-- AVX registers (yword sized, but oword, qword and dword accessible).
mkrmap("y", "ymm")
-- Operand size prefixes to codes.
local map_opsize = {
byte = "b", word = "w", dword = "d", qword = "q", oword = "o", yword = "y",
tword = "t", aword = addrsize,
}
-- Operand size code to number.
local map_opsizenum = {
b = 1, w = 2, d = 4, q = 8, o = 16, y = 32, t = 10,
}
-- Operand size code to name.
local map_opsizename = {
b = "byte", w = "word", d = "dword", q = "qword", o = "oword", y = "yword",
t = "tword", f = "fpword",
}
-- Valid index register scale factors.
local map_xsc = {
["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3,
}
-- Condition codes.
local map_cc = {
o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7,
s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15,
c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7,
pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15,
}
-- Reverse defines for registers.
function _M.revdef(s)
return gsub(s, "@%w+", map_reg_rev)
end
-- Dump register names and numbers
local function dumpregs(out)
out:write("Register names, sizes and internal numbers:\n")
for _,reg in ipairs(reg_list) do
if reg == "" then
out:write("\n")
else
local name = map_reg_rev[reg]
local num = map_reg_num[reg]
local opsize = map_opsizename[map_reg_opsize[reg]]
out:write(format(" %-5s %-8s %s\n", name, opsize,
num < 0 and "(variable)" or num))
end
end
end
------------------------------------------------------------------------------
-- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC).
local function wputlabel(aprefix, imm, num)
if type(imm) == "number" then
if imm < 0 then
waction("EXTERN")
wputxb(aprefix == "IMM_" and 0 or 1)
imm = -imm-1
else
waction(aprefix.."LG", nil, num);
end
wputxb(imm)
else
waction(aprefix.."PC", imm, num)
end
end
-- Put signed byte or arg.
local function wputsbarg(n)
if type(n) == "number" then
if n < -128 or n > 127 then
werror("signed immediate byte out of range")
end
if n < 0 then n = n + 256 end
wputb(n)
else waction("IMM_S", n) end
end
-- Put unsigned byte or arg.
local function wputbarg(n)
if type(n) == "number" then
if n < 0 or n > 255 then
werror("unsigned immediate byte out of range")
end
wputb(n)
else waction("IMM_B", n) end
end
-- Put unsigned word or arg.
local function wputwarg(n)
if type(n) == "number" then
if shr(n, 16) ~= 0 then
werror("unsigned immediate word out of range")
end
wputb(band(n, 255)); wputb(shr(n, 8));
else waction("IMM_W", n) end
end
-- Put signed or unsigned dword or arg.
local function wputdarg(n)
local tn = type(n)
if tn == "number" then
wputb(band(n, 255))
wputb(band(shr(n, 8), 255))
wputb(band(shr(n, 16), 255))
wputb(shr(n, 24))
elseif tn == "table" then
wputlabel("IMM_", n[1], 1)
else
waction("IMM_D", n)
end
end
-- Put operand-size dependent number or arg (defaults to dword).
local function wputszarg(sz, n)
if not sz or sz == "d" or sz == "q" then wputdarg(n)
elseif sz == "w" then wputwarg(n)
elseif sz == "b" then wputbarg(n)
elseif sz == "s" then wputsbarg(n)
else werror("bad operand size") end
end
-- Put multi-byte opcode with operand-size dependent modifications.
local function wputop(sz, op, rex, vex, vregr, vregxb)
local psz, sk = 0, nil
if vex then
local tail
if vex.m == 1 and band(rex, 11) == 0 then
if x64 and vregxb then
sk = map_vreg["modrm.reg"]
else
wputb(0xc5)
tail = shl(bxor(band(rex, 4), 4), 5)
psz = 3
end
end
if not tail then
wputb(0xc4)
wputb(shl(bxor(band(rex, 7), 7), 5) + vex.m)
tail = shl(band(rex, 8), 4)
psz = 4
end
local reg, vreg = 0, nil
if vex.v then
reg = vex.v.reg
if not reg then werror("bad vex operand") end
if reg < 0 then reg = 0; vreg = vex.v.vreg end
end
if sz == "y" or vex.l then tail = tail + 4 end
wputb(tail + shl(bxor(reg, 15), 3) + vex.p)
wvreg("vex.v", vreg)
rex = 0
if op >= 256 then werror("bad vex opcode") end
else
if rex ~= 0 then
if not x64 then werror("bad operand size") end
elseif (vregr or vregxb) and x64 then
rex = 0x10
sk = map_vreg["vex.v"]
end
end
local r
if sz == "w" then wputb(102) end
-- Needs >32 bit numbers, but only for crc32 eax, word [ebx]
if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end
if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end
if op >= 65536 then
if rex ~= 0 then
local opc3 = band(op, 0xffff00)
if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then
wputb(64 + band(rex, 15)); rex = 0; psz = 2
end
end
wputb(shr(op, 16)); op = band(op, 0xffff); psz = psz + 1
end
if op >= 256 then
local b = shr(op, 8)
if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end
wputb(b); op = band(op, 255); psz = psz + 1
end
if rex ~= 0 then wputb(64 + band(rex, 15)); psz = 2 end
if sz == "b" then op = op - 1 end
wputb(op)
return psz, sk
end
-- Put ModRM or SIB formatted byte.
local function wputmodrm(m, s, rm, vs, vrm)
assert(m < 4 and s < 16 and rm < 16, "bad modrm operands")
wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7))
end
-- Put ModRM/SIB plus optional displacement.
local function wputmrmsib(t, imark, s, vsreg, psz, sk)
local vreg, vxreg
local reg, xreg = t.reg, t.xreg
if reg and reg < 0 then reg = 0; vreg = t.vreg end
if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end
if s < 0 then s = 0 end
-- Register mode.
if sub(t.mode, 1, 1) == "r" then
wputmodrm(3, s, reg)
wvreg("modrm.reg", vsreg, psz+1, sk, vreg)
wvreg("modrm.rm.r", vreg, psz+1, sk)
return
end
local disp = t.disp
local tdisp = type(disp)
-- No base register?
if not reg then
local riprel = false
if xreg then
-- Indexed mode with index register only.
-- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp)
wputmodrm(0, s, 4)
if imark == "I" then waction("MARK") end
wvreg("modrm.reg", vsreg, psz+1, sk, vxreg)
wputmodrm(t.xsc, xreg, 5)
wvreg("sib.index", vxreg, psz+2, sk)
else
-- Pure 32 bit displacement.
if x64 and tdisp ~= "table" then
wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp)
wvreg("modrm.reg", vsreg, psz+1, sk)
if imark == "I" then waction("MARK") end
wputmodrm(0, 4, 5)
else
riprel = x64
wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp)
wvreg("modrm.reg", vsreg, psz+1, sk)
if imark == "I" then waction("MARK") end
end
end
if riprel then -- Emit rip-relative displacement.
if match("UWSiI", imark) then
werror("NYI: rip-relative displacement followed by immediate")
end
-- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f.
wputlabel("REL_", disp[1], 2)
else
wputdarg(disp)
end
return
end
local m
if tdisp == "number" then -- Check displacement size at assembly time.
if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too)
if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0]
elseif disp >= -128 and disp <= 127 then m = 1
else m = 2 end
elseif tdisp == "table" then
m = 2
end
-- Index register present or esp as base register: need SIB encoding.
if xreg or band(reg, 7) == 4 then
wputmodrm(m or 2, s, 4) -- ModRM.
if m == nil or imark == "I" then waction("MARK") end
wvreg("modrm.reg", vsreg, psz+1, sk, vxreg or vreg)
wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB.
wvreg("sib.index", vxreg, psz+2, sk, vreg)
wvreg("sib.base", vreg, psz+2, sk)
else
wputmodrm(m or 2, s, reg) -- ModRM.
if (imark == "I" and (m == 1 or m == 2)) or
(m == nil and (vsreg or vreg)) then waction("MARK") end
wvreg("modrm.reg", vsreg, psz+1, sk, vreg)
wvreg("modrm.rm.m", vreg, psz+1, sk)
end
-- Put displacement.
if m == 1 then wputsbarg(disp)
elseif m == 2 then wputdarg(disp)
elseif m == nil then waction("DISP", disp) end
end
------------------------------------------------------------------------------
-- Return human-readable operand mode string.
local function opmodestr(op, args)
local m = {}
for i=1,#args do
local a = args[i]
m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?")
end
return op.." "..concat(m, ",")
end
-- Convert number to valid integer or nil.
local function toint(expr)
local n = tonumber(expr)
if n then
if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then
werror("bad integer number `"..expr.."'")
end
return n
end
end
-- Parse immediate expression.
local function immexpr(expr)
-- &expr (pointer)
if sub(expr, 1, 1) == "&" then
return "iPJ", format("(ptrdiff_t)(%s)", sub(expr,2))
end
local prefix = sub(expr, 1, 2)
-- =>expr (pc label reference)
if prefix == "=>" then
return "iJ", sub(expr, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "iJ", map_global[sub(expr, 3)]
end
-- [<>][1-9] (local label reference)
local dir, lnum = match(expr, "^([<>])([1-9])$")
if dir then -- Fwd: 247-255, Bkwd: 1-9.
return "iJ", lnum + (dir == ">" and 246 or 0)
end
local extname = match(expr, "^extern%s+(%S+)$")
if extname then
return "iJ", map_extern[extname]
end
-- expr (interpreted as immediate)
return "iI", expr
end
-- Parse displacement expression: +-num, +-expr, +-opsize*num
local function dispexpr(expr)
local disp = expr == "" and 0 or toint(expr)
if disp then return disp end
local c, dispt = match(expr, "^([+-])%s*(.+)$")
if c == "+" then
expr = dispt
elseif not c then
werror("bad displacement expression `"..expr.."'")
end
local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$")
local ops, imm = map_opsize[opsize], toint(tailops)
if ops and imm then
if c == "-" then imm = -imm end
return imm*map_opsizenum[ops]
end
local mode, iexpr = immexpr(dispt)
if mode == "iJ" then
if c == "-" then werror("cannot invert label reference") end
return { iexpr }
end
return expr -- Need to return original signed expression.
end
-- Parse register or type expression.
local function rtexpr(expr)
if not expr then return end
local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
local rnum = map_reg_num[reg]
if not rnum then
werror("type `"..(tname or expr).."' needs a register override")
end
if not map_reg_valid_base[reg] then
werror("bad base register override `"..(map_reg_rev[reg] or reg).."'")
end
return reg, rnum, tp
end
return expr, map_reg_num[expr]
end
-- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }.
local function parseoperand(param)
local t = {}
local expr = param
local opsize, tailops = match(param, "^(%w+)%s*(.+)$")
if opsize then
t.opsize = map_opsize[opsize]
if t.opsize then expr = tailops end
end
local br = match(expr, "^%[%s*(.-)%s*%]$")
repeat
if br then
t.mode = "xm"
-- [disp]
t.disp = toint(br)
if t.disp then
t.mode = x64 and "xm" or "xmO"
break
end
-- [reg...]
local tp
local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$")
reg, t.reg, tp = rtexpr(reg)
if not t.reg then
-- [expr]
t.mode = x64 and "xm" or "xmO"
t.disp = dispexpr("+"..br)
break
end
if t.reg == -1 then
t.vreg, tailr = match(tailr, "^(%b())(.*)$")
if not t.vreg then werror("bad variable register expression") end
end
-- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr]
local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$")
if xsc then
if not map_reg_valid_index[reg] then
werror("bad index register `"..map_reg_rev[reg].."'")
end
t.xsc = map_xsc[xsc]
t.xreg = t.reg
t.vxreg = t.vreg
t.reg = nil
t.vreg = nil
t.disp = dispexpr(tailsc)
break
end
if not map_reg_valid_base[reg] then
werror("bad base register `"..map_reg_rev[reg].."'")
end
-- [reg] or [reg+-disp]
t.disp = toint(tailr) or (tailr == "" and 0)
if t.disp then break end
-- [reg+xreg...]
local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$")
xreg, t.xreg, tp = rtexpr(xreg)
if not t.xreg then
-- [reg+-expr]
t.disp = dispexpr(tailr)
break
end
if not map_reg_valid_index[xreg] then
werror("bad index register `"..map_reg_rev[xreg].."'")
end
if t.xreg == -1 then
t.vxreg, tailx = match(tailx, "^(%b())(.*)$")
if not t.vxreg then werror("bad variable register expression") end
end
-- [reg+xreg*xsc...]
local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$")
if xsc then
t.xsc = map_xsc[xsc]
tailx = tailsc
end
-- [...] or [...+-disp] or [...+-expr]
t.disp = dispexpr(tailx)
else
-- imm or opsize*imm
local imm = toint(expr)
if not imm and sub(expr, 1, 1) == "*" and t.opsize then
imm = toint(sub(expr, 2))
if imm then
imm = imm * map_opsizenum[t.opsize]
t.opsize = nil
end
end
if imm then
if t.opsize then werror("bad operand size override") end
local m = "i"
if imm == 1 then m = m.."1" end
if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end
if imm >= -128 and imm <= 127 then m = m.."S" end
t.imm = imm
t.mode = m
break
end
local tp
local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$")
reg, t.reg, tp = rtexpr(reg)
if t.reg then
if t.reg == -1 then
t.vreg, tailr = match(tailr, "^(%b())(.*)$")
if not t.vreg then werror("bad variable register expression") end
end
-- reg
if tailr == "" then
if t.opsize then werror("bad operand size override") end
t.opsize = map_reg_opsize[reg]
if t.opsize == "f" then
t.mode = t.reg == 0 and "fF" or "f"
else
if reg == "@w4" or (x64 and reg == "@d4") then
wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'"))
end
t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm")
end
t.needrex = map_reg_needrex[reg]
break
end
-- type[idx], type[idx].field, type->field -> [reg+offset_expr]
if not tp then werror("bad operand `"..param.."'") end
t.mode = "xm"
t.disp = format(tp.ctypefmt, tailr)
else
t.mode, t.imm = immexpr(expr)
if sub(t.mode, -1) == "J" then
if t.opsize and t.opsize ~= addrsize then
werror("bad operand size override")
end
t.opsize = addrsize
end
end
end
until true
return t
end
------------------------------------------------------------------------------
-- x86 Template String Description
-- ===============================
--
-- Each template string is a list of [match:]pattern pairs,
-- separated by "|". The first match wins. No match means a
-- bad or unsupported combination of operand modes or sizes.
--
-- The match part and the ":" is omitted if the operation has
-- no operands. Otherwise the first N characters are matched
-- against the mode strings of each of the N operands.
--
-- The mode string for each operand type is (see parseoperand()):
-- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl
-- FP register: "f", +"F" for st0
-- Index operand: "xm", +"O" for [disp] (pure offset)
-- Immediate: "i", +"S" for signed 8 bit, +"1" for 1,
-- +"I" for arg, +"P" for pointer
-- Any: +"J" for valid jump targets
--
-- So a match character "m" (mixed) matches both an integer register
-- and an index operand (to be encoded with the ModRM/SIB scheme).
-- But "r" matches only a register and "x" only an index operand
-- (e.g. for FP memory access operations).
--
-- The operand size match string starts right after the mode match
-- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty.
-- The effective data size of the operation is matched against this list.
--
-- If only the regular "b", "w", "d", "q", "t" operand sizes are
-- present, then all operands must be the same size. Unspecified sizes
-- are ignored, but at least one operand must have a size or the pattern
-- won't match (use the "byte", "word", "dword", "qword", "tword"
-- operand size overrides. E.g.: mov dword [eax], 1).
--
-- If the list has a "1" or "2" prefix, the operand size is taken
-- from the respective operand and any other operand sizes are ignored.
-- If the list contains only ".", all operand sizes are ignored.
-- If the list has a "/" prefix, the concatenated (mixed) operand sizes
-- are compared to the match.
--
-- E.g. "rrdw" matches for either two dword registers or two word
-- registers. "Fx2dq" matches an st0 operand plus an index operand
-- pointing to a dword (float) or qword (double).
--
-- Every character after the ":" is part of the pattern string:
-- Hex chars are accumulated to form the opcode (left to right).
-- "n" disables the standard opcode mods
-- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q")
-- "X" Force REX.W.
-- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode.
-- "m"/"M" generates ModRM/SIB from the 1st/2nd operand.
-- The spare 3 bits are either filled with the last hex digit or
-- the result from a previous "r"/"R". The opcode is restored.
-- "u" Use VEX encoding, vvvv unused.
-- "v"/"V" Use VEX encoding, vvvv from 1st/2nd operand (the operand is
-- removed from the list used by future characters).
-- "L" Force VEX.L
--
-- All of the following characters force a flush of the opcode:
-- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand.
-- "s" stores a 4 bit immediate from the last register operand,
-- followed by 4 zero bits.
-- "S" stores a signed 8 bit immediate from the last operand.
-- "U" stores an unsigned 8 bit immediate from the last operand.
-- "W" stores an unsigned 16 bit immediate from the last operand.
-- "i" stores an operand sized immediate from the last operand.
-- "I" dito, but generates an action code to optionally modify
-- the opcode (+2) for a signed 8 bit immediate.
-- "J" generates one of the REL action codes from the last operand.
--
------------------------------------------------------------------------------
-- Template strings for x86 instructions. Ordered by first opcode byte.
-- Unimplemented opcodes (deliberate omissions) are marked with *.
local map_op = {
-- 00-05: add...
-- 06: *push es
-- 07: *pop es
-- 08-0D: or...
-- 0E: *push cs
-- 0F: two byte opcode prefix
-- 10-15: adc...
-- 16: *push ss
-- 17: *pop ss
-- 18-1D: sbb...
-- 1E: *push ds
-- 1F: *pop ds
-- 20-25: and...
es_0 = "26",
-- 27: *daa
-- 28-2D: sub...
cs_0 = "2E",
-- 2F: *das
-- 30-35: xor...
ss_0 = "36",
-- 37: *aaa
-- 38-3D: cmp...
ds_0 = "3E",
-- 3F: *aas
inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m",
dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m",
push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or
"rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i",
pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m",
-- 60: *pusha, *pushad, *pushaw
-- 61: *popa, *popad, *popaw
-- 62: *bound rdw,x
-- 63: x86: *arpl mw,rw
movsxd_2 = x64 and "rm/qd:63rM",
fs_0 = "64",
gs_0 = "65",
o16_0 = "66",
a16_0 = not x64 and "67" or nil,
a32_0 = x64 and "67",
-- 68: push idw
-- 69: imul rdw,mdw,idw
-- 6A: push ib
-- 6B: imul rdw,mdw,S
-- 6C: *insb
-- 6D: *insd, *insw
-- 6E: *outsb
-- 6F: *outsd, *outsw
-- 70-7F: jcc lb
-- 80: add... mb,i
-- 81: add... mdw,i
-- 82: *undefined
-- 83: add... mdw,S
test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi",
-- 86: xchg rb,mb
-- 87: xchg rdw,mdw
-- 88: mov mb,r
-- 89: mov mdw,r
-- 8A: mov r,mb
-- 8B: mov r,mdw
-- 8C: *mov mdw,seg
lea_2 = "rx1dq:8DrM",
-- 8E: *mov seg,mdw
-- 8F: pop mdw
nop_0 = "90",
xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm",
cbw_0 = "6698",
cwde_0 = "98",
cdqe_0 = "4898",
cwd_0 = "6699",
cdq_0 = "99",
cqo_0 = "4899",
-- 9A: *call iw:idw
wait_0 = "9B",
fwait_0 = "9B",
pushf_0 = "9C",
pushfd_0 = not x64 and "9C",
pushfq_0 = x64 and "9C",
popf_0 = "9D",
popfd_0 = not x64 and "9D",
popfq_0 = x64 and "9D",
sahf_0 = "9E",
lahf_0 = "9F",
mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi",
movsb_0 = "A4",
movsw_0 = "66A5",
movsd_0 = "A5",
cmpsb_0 = "A6",
cmpsw_0 = "66A7",
cmpsd_0 = "A7",
-- A8: test Rb,i
-- A9: test Rdw,i
stosb_0 = "AA",
stosw_0 = "66AB",
stosd_0 = "AB",
lodsb_0 = "AC",
lodsw_0 = "66AD",
lodsd_0 = "AD",
scasb_0 = "AE",
scasw_0 = "66AF",
scasd_0 = "AF",
-- B0-B7: mov rb,i
-- B8-BF: mov rdw,i
-- C0: rol... mb,i
-- C1: rol... mdw,i
ret_1 = "i.:nC2W",
ret_0 = "C3",
-- C4: *les rdw,mq
-- C5: *lds rdw,mq
-- C6: mov mb,i
-- C7: mov mdw,i
-- C8: *enter iw,ib
leave_0 = "C9",
-- CA: *retf iw
-- CB: *retf
int3_0 = "CC",
int_1 = "i.:nCDU",
into_0 = "CE",
-- CF: *iret
-- D0: rol... mb,1
-- D1: rol... mdw,1
-- D2: rol... mb,cl
-- D3: rol... mb,cl
-- D4: *aam ib
-- D5: *aad ib
-- D6: *salc
-- D7: *xlat
-- D8-DF: floating point ops
-- E0: *loopne
-- E1: *loope
-- E2: *loop
-- E3: *jcxz, *jecxz
-- E4: *in Rb,ib
-- E5: *in Rdw,ib
-- E6: *out ib,Rb
-- E7: *out ib,Rdw
call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J",
jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB
-- EA: *jmp iw:idw
-- EB: jmp ib
-- EC: *in Rb,dx
-- ED: *in Rdw,dx
-- EE: *out dx,Rb
-- EF: *out dx,Rdw
lock_0 = "F0",
int1_0 = "F1",
repne_0 = "F2",
repnz_0 = "F2",
rep_0 = "F3",
repe_0 = "F3",
repz_0 = "F3",
-- F4: *hlt
cmc_0 = "F5",
-- F6: test... mb,i; div... mb
-- F7: test... mdw,i; div... mdw
clc_0 = "F8",
stc_0 = "F9",
-- FA: *cli
cld_0 = "FC",
std_0 = "FD",
-- FE: inc... mb
-- FF: inc... mdw
-- misc ops
not_1 = "m:F72m",
neg_1 = "m:F73m",
mul_1 = "m:F74m",
imul_1 = "m:F75m",
div_1 = "m:F76m",
idiv_1 = "m:F77m",
imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi",
imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi",
movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:",
movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:",
bswap_1 = "rqd:0FC8r",
bsf_2 = "rmqdw:0FBCrM",
bsr_2 = "rmqdw:0FBDrM",
bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU",
btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU",
btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU",
bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU",
shld_3 = "mriqdw:0FA4RmU|mrC/qq:0FA5Rm|mrC/dd:|mrC/ww:",
shrd_3 = "mriqdw:0FACRmU|mrC/qq:0FADRm|mrC/dd:|mrC/ww:",
rdtsc_0 = "0F31", -- P1+
rdpmc_0 = "0F33", -- P6+
cpuid_0 = "0FA2", -- P1+
-- floating point ops
fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m",
fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m",
fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m",
fpop_0 = "DDD8", -- Alias for fstp st0.
fist_1 = "xw:nDF2m|xd:DB2m",
fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m",
fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m",
fxch_0 = "D9C9",
fxch_1 = "ff:D9C8r",
fxch_2 = "fFf:D9C8r|Fff:D9C8R",
fucom_1 = "ff:DDE0r",
fucom_2 = "Fff:DDE0R",
fucomp_1 = "ff:DDE8r",
fucomp_2 = "Fff:DDE8R",
fucomi_1 = "ff:DBE8r", -- P6+
fucomi_2 = "Fff:DBE8R", -- P6+
fucomip_1 = "ff:DFE8r", -- P6+
fucomip_2 = "Fff:DFE8R", -- P6+
fcomi_1 = "ff:DBF0r", -- P6+
fcomi_2 = "Fff:DBF0R", -- P6+
fcomip_1 = "ff:DFF0r", -- P6+
fcomip_2 = "Fff:DFF0R", -- P6+
fucompp_0 = "DAE9",
fcompp_0 = "DED9",
fldenv_1 = "x.:D94m",
fnstenv_1 = "x.:D96m",
fstenv_1 = "x.:9BD96m",
fldcw_1 = "xw:nD95m",
fstcw_1 = "xw:n9BD97m",
fnstcw_1 = "xw:nD97m",
fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m",
fnstsw_1 = "Rw:nDFE0|xw:nDD7m",
fclex_0 = "9BDBE2",
fnclex_0 = "DBE2",
fnop_0 = "D9D0",
-- D9D1-D9DF: unassigned
fchs_0 = "D9E0",
fabs_0 = "D9E1",
-- D9E2: unassigned
-- D9E3: unassigned
ftst_0 = "D9E4",
fxam_0 = "D9E5",
-- D9E6: unassigned
-- D9E7: unassigned
fld1_0 = "D9E8",
fldl2t_0 = "D9E9",
fldl2e_0 = "D9EA",
fldpi_0 = "D9EB",
fldlg2_0 = "D9EC",
fldln2_0 = "D9ED",
fldz_0 = "D9EE",
-- D9EF: unassigned
f2xm1_0 = "D9F0",
fyl2x_0 = "D9F1",
fptan_0 = "D9F2",
fpatan_0 = "D9F3",
fxtract_0 = "D9F4",
fprem1_0 = "D9F5",
fdecstp_0 = "D9F6",
fincstp_0 = "D9F7",
fprem_0 = "D9F8",
fyl2xp1_0 = "D9F9",
fsqrt_0 = "D9FA",
fsincos_0 = "D9FB",
frndint_0 = "D9FC",
fscale_0 = "D9FD",
fsin_0 = "D9FE",
fcos_0 = "D9FF",
-- SSE, SSE2
andnpd_2 = "rmo:660F55rM",
andnps_2 = "rmo:0F55rM",
andpd_2 = "rmo:660F54rM",
andps_2 = "rmo:0F54rM",
clflush_1 = "x.:0FAE7m",
cmppd_3 = "rmio:660FC2rMU",
cmpps_3 = "rmio:0FC2rMU",
cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:",
cmpss_3 = "rrio:F30FC2rMU|rxi/od:",
comisd_2 = "rro:660F2FrM|rx/oq:",
comiss_2 = "rro:0F2FrM|rx/od:",
cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:",
cvtdq2ps_2 = "rmo:0F5BrM",
cvtpd2dq_2 = "rmo:F20FE6rM",
cvtpd2ps_2 = "rmo:660F5ArM",
cvtpi2pd_2 = "rx/oq:660F2ArM",
cvtpi2ps_2 = "rx/oq:0F2ArM",
cvtps2dq_2 = "rmo:660F5BrM",
cvtps2pd_2 = "rro:0F5ArM|rx/oq:",
cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:",
cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:",
cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM",
cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM",
cvtss2sd_2 = "rro:F30F5ArM|rx/od:",
cvtss2si_2 = "rr/do:F30F2DrM|rr/qo:|rxd:|rx/qd:",
cvttpd2dq_2 = "rmo:660FE6rM",
cvttps2dq_2 = "rmo:F30F5BrM",
cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:",
cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:",
fxsave_1 = "x.:0FAE0m",
fxrstor_1 = "x.:0FAE1m",
ldmxcsr_1 = "xd:0FAE2m",
lfence_0 = "0FAEE8",
maskmovdqu_2 = "rro:660FF7rM",
mfence_0 = "0FAEF0",
movapd_2 = "rmo:660F28rM|mro:660F29Rm",
movaps_2 = "rmo:0F28rM|mro:0F29Rm",
movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:",
movdqa_2 = "rmo:660F6FrM|mro:660F7FRm",
movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm",
movhlps_2 = "rro:0F12rM",
movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm",
movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm",
movlhps_2 = "rro:0F16rM",
movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm",
movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm",
movmskpd_2 = "rr/do:660F50rM",
movmskps_2 = "rr/do:0F50rM",
movntdq_2 = "xro:660FE7Rm",
movnti_2 = "xrqd:0FC3Rm",
movntpd_2 = "xro:660F2BRm",
movntps_2 = "xro:0F2BRm",
movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm",
movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm",
movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm",
movupd_2 = "rmo:660F10rM|mro:660F11Rm",
movups_2 = "rmo:0F10rM|mro:0F11Rm",
orpd_2 = "rmo:660F56rM",
orps_2 = "rmo:0F56rM",
pause_0 = "F390",
pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nRmU", -- Mem op: SSE4.1 only.
pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:",
pmovmskb_2 = "rr/do:660FD7rM",
prefetchnta_1 = "xb:n0F180m",
prefetcht0_1 = "xb:n0F181m",
prefetcht1_1 = "xb:n0F182m",
prefetcht2_1 = "xb:n0F183m",
pshufd_3 = "rmio:660F70rMU",
pshufhw_3 = "rmio:F30F70rMU",
pshuflw_3 = "rmio:F20F70rMU",
pslld_2 = "rmo:660FF2rM|rio:660F726mU",
pslldq_2 = "rio:660F737mU",
psllq_2 = "rmo:660FF3rM|rio:660F736mU",
psllw_2 = "rmo:660FF1rM|rio:660F716mU",
psrad_2 = "rmo:660FE2rM|rio:660F724mU",
psraw_2 = "rmo:660FE1rM|rio:660F714mU",
psrld_2 = "rmo:660FD2rM|rio:660F722mU",
psrldq_2 = "rio:660F733mU",
psrlq_2 = "rmo:660FD3rM|rio:660F732mU",
psrlw_2 = "rmo:660FD1rM|rio:660F712mU",
rcpps_2 = "rmo:0F53rM",
rcpss_2 = "rro:F30F53rM|rx/od:",
rsqrtps_2 = "rmo:0F52rM",
rsqrtss_2 = "rmo:F30F52rM",
sfence_0 = "0FAEF8",
shufpd_3 = "rmio:660FC6rMU",
shufps_3 = "rmio:0FC6rMU",
stmxcsr_1 = "xd:0FAE3m",
ucomisd_2 = "rro:660F2ErM|rx/oq:",
ucomiss_2 = "rro:0F2ErM|rx/od:",
unpckhpd_2 = "rmo:660F15rM",
unpckhps_2 = "rmo:0F15rM",
unpcklpd_2 = "rmo:660F14rM",
unpcklps_2 = "rmo:0F14rM",
xorpd_2 = "rmo:660F57rM",
xorps_2 = "rmo:0F57rM",
-- SSE3 ops
fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m",
addsubpd_2 = "rmo:660FD0rM",
addsubps_2 = "rmo:F20FD0rM",
haddpd_2 = "rmo:660F7CrM",
haddps_2 = "rmo:F20F7CrM",
hsubpd_2 = "rmo:660F7DrM",
hsubps_2 = "rmo:F20F7DrM",
lddqu_2 = "rxo:F20FF0rM",
movddup_2 = "rmo:F20F12rM",
movshdup_2 = "rmo:F30F16rM",
movsldup_2 = "rmo:F30F12rM",
-- SSSE3 ops
pabsb_2 = "rmo:660F381CrM",
pabsd_2 = "rmo:660F381ErM",
pabsw_2 = "rmo:660F381DrM",
palignr_3 = "rmio:660F3A0FrMU",
phaddd_2 = "rmo:660F3802rM",
phaddsw_2 = "rmo:660F3803rM",
phaddw_2 = "rmo:660F3801rM",
phsubd_2 = "rmo:660F3806rM",
phsubsw_2 = "rmo:660F3807rM",
phsubw_2 = "rmo:660F3805rM",
pmaddubsw_2 = "rmo:660F3804rM",
pmulhrsw_2 = "rmo:660F380BrM",
pshufb_2 = "rmo:660F3800rM",
psignb_2 = "rmo:660F3808rM",
psignd_2 = "rmo:660F380ArM",
psignw_2 = "rmo:660F3809rM",
-- SSE4.1 ops
blendpd_3 = "rmio:660F3A0DrMU",
blendps_3 = "rmio:660F3A0CrMU",
blendvpd_3 = "rmRo:660F3815rM",
blendvps_3 = "rmRo:660F3814rM",
dppd_3 = "rmio:660F3A41rMU",
dpps_3 = "rmio:660F3A40rMU",
extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU",
insertps_3 = "rrio:660F3A41rMU|rxi/od:",
movntdqa_2 = "rxo:660F382ArM",
mpsadbw_3 = "rmio:660F3A42rMU",
packusdw_2 = "rmo:660F382BrM",
pblendvb_3 = "rmRo:660F3810rM",
pblendw_3 = "rmio:660F3A0ErMU",
pcmpeqq_2 = "rmo:660F3829rM",
pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:",
pextrd_3 = "mri/do:660F3A16RmU",
pextrq_3 = "mri/qo:660F3A16RmU",
-- pextrw is SSE2, mem operand is SSE4.1 only
phminposuw_2 = "rmo:660F3841rM",
pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:",
pinsrd_3 = "rmi/od:660F3A22rMU",
pinsrq_3 = "rmi/oq:660F3A22rXMU",
pmaxsb_2 = "rmo:660F383CrM",
pmaxsd_2 = "rmo:660F383DrM",
pmaxud_2 = "rmo:660F383FrM",
pmaxuw_2 = "rmo:660F383ErM",
pminsb_2 = "rmo:660F3838rM",
pminsd_2 = "rmo:660F3839rM",
pminud_2 = "rmo:660F383BrM",
pminuw_2 = "rmo:660F383ArM",
pmovsxbd_2 = "rro:660F3821rM|rx/od:",
pmovsxbq_2 = "rro:660F3822rM|rx/ow:",
pmovsxbw_2 = "rro:660F3820rM|rx/oq:",
pmovsxdq_2 = "rro:660F3825rM|rx/oq:",
pmovsxwd_2 = "rro:660F3823rM|rx/oq:",
pmovsxwq_2 = "rro:660F3824rM|rx/od:",
pmovzxbd_2 = "rro:660F3831rM|rx/od:",
pmovzxbq_2 = "rro:660F3832rM|rx/ow:",
pmovzxbw_2 = "rro:660F3830rM|rx/oq:",
pmovzxdq_2 = "rro:660F3835rM|rx/oq:",
pmovzxwd_2 = "rro:660F3833rM|rx/oq:",
pmovzxwq_2 = "rro:660F3834rM|rx/od:",
pmuldq_2 = "rmo:660F3828rM",
pmulld_2 = "rmo:660F3840rM",
ptest_2 = "rmo:660F3817rM",
roundpd_3 = "rmio:660F3A09rMU",
roundps_3 = "rmio:660F3A08rMU",
roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:",
roundss_3 = "rrio:660F3A0ArMU|rxi/od:",
-- SSE4.2 ops
crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:",
pcmpestri_3 = "rmio:660F3A61rMU",
pcmpestrm_3 = "rmio:660F3A60rMU",
pcmpgtq_2 = "rmo:660F3837rM",
pcmpistri_3 = "rmio:660F3A63rMU",
pcmpistrm_3 = "rmio:660F3A62rMU",
popcnt_2 = "rmqdw:F30FB8rM",
-- SSE4a
extrq_2 = "rro:660F79rM",
extrq_3 = "riio:660F780mUU",
insertq_2 = "rro:F20F79rM",
insertq_4 = "rriio:F20F78rMUU",
lzcnt_2 = "rmqdw:F30FBDrM",
movntsd_2 = "xr/qo:nF20F2BRm",
movntss_2 = "xr/do:F30F2BRm",
-- popcnt is also in SSE4.2
-- AES-NI
aesdec_2 = "rmo:660F38DErM",
aesdeclast_2 = "rmo:660F38DFrM",
aesenc_2 = "rmo:660F38DCrM",
aesenclast_2 = "rmo:660F38DDrM",
aesimc_2 = "rmo:660F38DBrM",
aeskeygenassist_3 = "rmio:660F3ADFrMU",
pclmulqdq_3 = "rmio:660F3A44rMU",
-- AVX FP ops
vaddsubpd_3 = "rrmoy:660FVD0rM",
vaddsubps_3 = "rrmoy:F20FVD0rM",
vandpd_3 = "rrmoy:660FV54rM",
vandps_3 = "rrmoy:0FV54rM",
vandnpd_3 = "rrmoy:660FV55rM",
vandnps_3 = "rrmoy:0FV55rM",
vblendpd_4 = "rrmioy:660F3AV0DrMU",
vblendps_4 = "rrmioy:660F3AV0CrMU",
vblendvpd_4 = "rrmroy:660F3AV4BrMs",
vblendvps_4 = "rrmroy:660F3AV4ArMs",
vbroadcastf128_2 = "rx/yo:660F38u1ArM",
vcmppd_4 = "rrmioy:660FVC2rMU",
vcmpps_4 = "rrmioy:0FVC2rMU",
vcmpsd_4 = "rrrio:F20FVC2rMU|rrxi/ooq:",
vcmpss_4 = "rrrio:F30FVC2rMU|rrxi/ood:",
vcomisd_2 = "rro:660Fu2FrM|rx/oq:",
vcomiss_2 = "rro:0Fu2FrM|rx/od:",
vcvtdq2pd_2 = "rro:F30FuE6rM|rx/oq:|rm/yo:",
vcvtdq2ps_2 = "rmoy:0Fu5BrM",
vcvtpd2dq_2 = "rmoy:F20FuE6rM",
vcvtpd2ps_2 = "rmoy:660Fu5ArM",
vcvtps2dq_2 = "rmoy:660Fu5BrM",
vcvtps2pd_2 = "rro:0Fu5ArM|rx/oq:|rm/yo:",
vcvtsd2si_2 = "rr/do:F20Fu2DrM|rx/dq:|rr/qo:|rxq:",
vcvtsd2ss_3 = "rrro:F20FV5ArM|rrx/ooq:",
vcvtsi2sd_3 = "rrm/ood:F20FV2ArM|rrm/ooq:F20FVX2ArM",
vcvtsi2ss_3 = "rrm/ood:F30FV2ArM|rrm/ooq:F30FVX2ArM",
vcvtss2sd_3 = "rrro:F30FV5ArM|rrx/ood:",
vcvtss2si_2 = "rr/do:F30Fu2DrM|rxd:|rr/qo:|rx/qd:",
vcvttpd2dq_2 = "rmo:660FuE6rM|rm/oy:660FuLE6rM",
vcvttps2dq_2 = "rmoy:F30Fu5BrM",
vcvttsd2si_2 = "rr/do:F20Fu2CrM|rx/dq:|rr/qo:|rxq:",
vcvttss2si_2 = "rr/do:F30Fu2CrM|rxd:|rr/qo:|rx/qd:",
vdppd_4 = "rrmio:660F3AV41rMU",
vdpps_4 = "rrmioy:660F3AV40rMU",
vextractf128_3 = "mri/oy:660F3AuL19RmU",
vextractps_3 = "mri/do:660F3Au17RmU",
vhaddpd_3 = "rrmoy:660FV7CrM",
vhaddps_3 = "rrmoy:F20FV7CrM",
vhsubpd_3 = "rrmoy:660FV7DrM",
vhsubps_3 = "rrmoy:F20FV7DrM",
vinsertf128_4 = "rrmi/yyo:660F3AV18rMU",
vinsertps_4 = "rrrio:660F3AV21rMU|rrxi/ood:",
vldmxcsr_1 = "xd:0FuAE2m",
vmaskmovps_3 = "rrxoy:660F38V2CrM|xrroy:660F38V2ERm",
vmaskmovpd_3 = "rrxoy:660F38V2DrM|xrroy:660F38V2FRm",
vmovapd_2 = "rmoy:660Fu28rM|mroy:660Fu29Rm",
vmovaps_2 = "rmoy:0Fu28rM|mroy:0Fu29Rm",
vmovd_2 = "rm/od:660Fu6ErM|rm/oq:660FuX6ErM|mr/do:660Fu7ERm|mr/qo:",
vmovq_2 = "rro:F30Fu7ErM|rx/oq:|xr/qo:660FuD6Rm",
vmovddup_2 = "rmy:F20Fu12rM|rro:|rx/oq:",
vmovhlps_3 = "rrro:0FV12rM",
vmovhpd_2 = "xr/qo:660Fu17Rm",
vmovhpd_3 = "rrx/ooq:660FV16rM",
vmovhps_2 = "xr/qo:0Fu17Rm",
vmovhps_3 = "rrx/ooq:0FV16rM",
vmovlhps_3 = "rrro:0FV16rM",
vmovlpd_2 = "xr/qo:660Fu13Rm",
vmovlpd_3 = "rrx/ooq:660FV12rM",
vmovlps_2 = "xr/qo:0Fu13Rm",
vmovlps_3 = "rrx/ooq:0FV12rM",
vmovmskpd_2 = "rr/do:660Fu50rM|rr/dy:660FuL50rM",
vmovmskps_2 = "rr/do:0Fu50rM|rr/dy:0FuL50rM",
vmovntpd_2 = "xroy:660Fu2BRm",
vmovntps_2 = "xroy:0Fu2BRm",
vmovsd_2 = "rx/oq:F20Fu10rM|xr/qo:F20Fu11Rm",
vmovsd_3 = "rrro:F20FV10rM",
vmovshdup_2 = "rmoy:F30Fu16rM",
vmovsldup_2 = "rmoy:F30Fu12rM",
vmovss_2 = "rx/od:F30Fu10rM|xr/do:F30Fu11Rm",
vmovss_3 = "rrro:F30FV10rM",
vmovupd_2 = "rmoy:660Fu10rM|mroy:660Fu11Rm",
vmovups_2 = "rmoy:0Fu10rM|mroy:0Fu11Rm",
vorpd_3 = "rrmoy:660FV56rM",
vorps_3 = "rrmoy:0FV56rM",
vpermilpd_3 = "rrmoy:660F38V0DrM|rmioy:660F3Au05rMU",
vpermilps_3 = "rrmoy:660F38V0CrM|rmioy:660F3Au04rMU",
vperm2f128_4 = "rrmiy:660F3AV06rMU",
vptestpd_2 = "rmoy:660F38u0FrM",
vptestps_2 = "rmoy:660F38u0ErM",
vrcpps_2 = "rmoy:0Fu53rM",
vrcpss_3 = "rrro:F30FV53rM|rrx/ood:",
vrsqrtps_2 = "rmoy:0Fu52rM",
vrsqrtss_3 = "rrro:F30FV52rM|rrx/ood:",
vroundpd_3 = "rmioy:660F3AV09rMU",
vroundps_3 = "rmioy:660F3AV08rMU",
vroundsd_4 = "rrrio:660F3AV0BrMU|rrxi/ooq:",
vroundss_4 = "rrrio:660F3AV0ArMU|rrxi/ood:",
vshufpd_4 = "rrmioy:660FVC6rMU",
vshufps_4 = "rrmioy:0FVC6rMU",
vsqrtps_2 = "rmoy:0Fu51rM",
vsqrtss_2 = "rro:F30Fu51rM|rx/od:",
vsqrtpd_2 = "rmoy:660Fu51rM",
vsqrtsd_2 = "rro:F20Fu51rM|rx/oq:",
vstmxcsr_1 = "xd:0FuAE3m",
vucomisd_2 = "rro:660Fu2ErM|rx/oq:",
vucomiss_2 = "rro:0Fu2ErM|rx/od:",
vunpckhpd_3 = "rrmoy:660FV15rM",
vunpckhps_3 = "rrmoy:0FV15rM",
vunpcklpd_3 = "rrmoy:660FV14rM",
vunpcklps_3 = "rrmoy:0FV14rM",
vxorpd_3 = "rrmoy:660FV57rM",
vxorps_3 = "rrmoy:0FV57rM",
vzeroall_0 = "0FuL77",
vzeroupper_0 = "0Fu77",
-- AVX2 FP ops
vbroadcastss_2 = "rx/od:660F38u18rM|rx/yd:|rro:|rr/yo:",
vbroadcastsd_2 = "rx/yq:660F38u19rM|rr/yo:",
-- *vgather* (!vsib)
vpermpd_3 = "rmiy:660F3AuX01rMU",
vpermps_3 = "rrmy:660F38V16rM",
-- AVX, AVX2 integer ops
-- In general, xmm requires AVX, ymm requires AVX2.
vaesdec_3 = "rrmo:660F38VDErM",
vaesdeclast_3 = "rrmo:660F38VDFrM",
vaesenc_3 = "rrmo:660F38VDCrM",
vaesenclast_3 = "rrmo:660F38VDDrM",
vaesimc_2 = "rmo:660F38uDBrM",
vaeskeygenassist_3 = "rmio:660F3AuDFrMU",
vlddqu_2 = "rxoy:F20FuF0rM",
vmaskmovdqu_2 = "rro:660FuF7rM",
vmovdqa_2 = "rmoy:660Fu6FrM|mroy:660Fu7FRm",
vmovdqu_2 = "rmoy:F30Fu6FrM|mroy:F30Fu7FRm",
vmovntdq_2 = "xroy:660FuE7Rm",
vmovntdqa_2 = "rxoy:660F38u2ArM",
vmpsadbw_4 = "rrmioy:660F3AV42rMU",
vpabsb_2 = "rmoy:660F38u1CrM",
vpabsd_2 = "rmoy:660F38u1ErM",
vpabsw_2 = "rmoy:660F38u1DrM",
vpackusdw_3 = "rrmoy:660F38V2BrM",
vpalignr_4 = "rrmioy:660F3AV0FrMU",
vpblendvb_4 = "rrmroy:660F3AV4CrMs",
vpblendw_4 = "rrmioy:660F3AV0ErMU",
vpclmulqdq_4 = "rrmio:660F3AV44rMU",
vpcmpeqq_3 = "rrmoy:660F38V29rM",
vpcmpestri_3 = "rmio:660F3Au61rMU",
vpcmpestrm_3 = "rmio:660F3Au60rMU",
vpcmpgtq_3 = "rrmoy:660F38V37rM",
vpcmpistri_3 = "rmio:660F3Au63rMU",
vpcmpistrm_3 = "rmio:660F3Au62rMU",
vpextrb_3 = "rri/do:660F3Au14nRmU|rri/qo:|xri/bo:",
vpextrw_3 = "rri/do:660FuC5rMU|xri/wo:660F3Au15nRmU",
vpextrd_3 = "mri/do:660F3Au16RmU",
vpextrq_3 = "mri/qo:660F3Au16RmU",
vphaddw_3 = "rrmoy:660F38V01rM",
vphaddd_3 = "rrmoy:660F38V02rM",
vphaddsw_3 = "rrmoy:660F38V03rM",
vphminposuw_2 = "rmo:660F38u41rM",
vphsubw_3 = "rrmoy:660F38V05rM",
vphsubd_3 = "rrmoy:660F38V06rM",
vphsubsw_3 = "rrmoy:660F38V07rM",
vpinsrb_4 = "rrri/ood:660F3AV20rMU|rrxi/oob:",
vpinsrw_4 = "rrri/ood:660FVC4rMU|rrxi/oow:",
vpinsrd_4 = "rrmi/ood:660F3AV22rMU",
vpinsrq_4 = "rrmi/ooq:660F3AVX22rMU",
vpmaddubsw_3 = "rrmoy:660F38V04rM",
vpmaxsb_3 = "rrmoy:660F38V3CrM",
vpmaxsd_3 = "rrmoy:660F38V3DrM",
vpmaxuw_3 = "rrmoy:660F38V3ErM",
vpmaxud_3 = "rrmoy:660F38V3FrM",
vpminsb_3 = "rrmoy:660F38V38rM",
vpminsd_3 = "rrmoy:660F38V39rM",
vpminuw_3 = "rrmoy:660F38V3ArM",
vpminud_3 = "rrmoy:660F38V3BrM",
vpmovmskb_2 = "rr/do:660FuD7rM|rr/dy:660FuLD7rM",
vpmovsxbw_2 = "rroy:660F38u20rM|rx/oq:|rx/yo:",
vpmovsxbd_2 = "rroy:660F38u21rM|rx/od:|rx/yq:",
vpmovsxbq_2 = "rroy:660F38u22rM|rx/ow:|rx/yd:",
vpmovsxwd_2 = "rroy:660F38u23rM|rx/oq:|rx/yo:",
vpmovsxwq_2 = "rroy:660F38u24rM|rx/od:|rx/yq:",
vpmovsxdq_2 = "rroy:660F38u25rM|rx/oq:|rx/yo:",
vpmovzxbw_2 = "rroy:660F38u30rM|rx/oq:|rx/yo:",
vpmovzxbd_2 = "rroy:660F38u31rM|rx/od:|rx/yq:",
vpmovzxbq_2 = "rroy:660F38u32rM|rx/ow:|rx/yd:",
vpmovzxwd_2 = "rroy:660F38u33rM|rx/oq:|rx/yo:",
vpmovzxwq_2 = "rroy:660F38u34rM|rx/od:|rx/yq:",
vpmovzxdq_2 = "rroy:660F38u35rM|rx/oq:|rx/yo:",
vpmuldq_3 = "rrmoy:660F38V28rM",
vpmulhrsw_3 = "rrmoy:660F38V0BrM",
vpmulld_3 = "rrmoy:660F38V40rM",
vpshufb_3 = "rrmoy:660F38V00rM",
vpshufd_3 = "rmioy:660Fu70rMU",
vpshufhw_3 = "rmioy:F30Fu70rMU",
vpshuflw_3 = "rmioy:F20Fu70rMU",
vpsignb_3 = "rrmoy:660F38V08rM",
vpsignw_3 = "rrmoy:660F38V09rM",
vpsignd_3 = "rrmoy:660F38V0ArM",
vpslldq_3 = "rrioy:660Fv737mU",
vpsllw_3 = "rrmoy:660FVF1rM|rrioy:660Fv716mU",
vpslld_3 = "rrmoy:660FVF2rM|rrioy:660Fv726mU",
vpsllq_3 = "rrmoy:660FVF3rM|rrioy:660Fv736mU",
vpsraw_3 = "rrmoy:660FVE1rM|rrioy:660Fv714mU",
vpsrad_3 = "rrmoy:660FVE2rM|rrioy:660Fv724mU",
vpsrldq_3 = "rrioy:660Fv733mU",
vpsrlw_3 = "rrmoy:660FVD1rM|rrioy:660Fv712mU",
vpsrld_3 = "rrmoy:660FVD2rM|rrioy:660Fv722mU",
vpsrlq_3 = "rrmoy:660FVD3rM|rrioy:660Fv732mU",
vptest_2 = "rmoy:660F38u17rM",
-- AVX2 integer ops
vbroadcasti128_2 = "rx/yo:660F38u5ArM",
vinserti128_4 = "rrmi/yyo:660F3AV38rMU",
vextracti128_3 = "mri/oy:660F3AuL39RmU",
vpblendd_4 = "rrmioy:660F3AV02rMU",
vpbroadcastb_2 = "rro:660F38u78rM|rx/ob:|rr/yo:|rx/yb:",
vpbroadcastw_2 = "rro:660F38u79rM|rx/ow:|rr/yo:|rx/yw:",
vpbroadcastd_2 = "rro:660F38u58rM|rx/od:|rr/yo:|rx/yd:",
vpbroadcastq_2 = "rro:660F38u59rM|rx/oq:|rr/yo:|rx/yq:",
vpermd_3 = "rrmy:660F38V36rM",
vpermq_3 = "rmiy:660F3AuX00rMU",
-- *vpgather* (!vsib)
vperm2i128_4 = "rrmiy:660F3AV46rMU",
vpmaskmovd_3 = "rrxoy:660F38V8CrM|xrroy:660F38V8ERm",
vpmaskmovq_3 = "rrxoy:660F38VX8CrM|xrroy:660F38VX8ERm",
vpsllvd_3 = "rrmoy:660F38V47rM",
vpsllvq_3 = "rrmoy:660F38VX47rM",
vpsravd_3 = "rrmoy:660F38V46rM",
vpsrlvd_3 = "rrmoy:660F38V45rM",
vpsrlvq_3 = "rrmoy:660F38VX45rM",
-- Intel ADX
adcx_2 = "rmqd:660F38F6rM",
adox_2 = "rmqd:F30F38F6rM",
}
------------------------------------------------------------------------------
-- Arithmetic ops.
for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3,
["and"] = 4, sub = 5, xor = 6, cmp = 7 } do
local n8 = shl(n, 3)
map_op[name.."_2"] = format(
"mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi",
1+n8, 3+n8, n, n, 5+n8, n)
end
-- Shift ops.
for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3,
shl = 4, shr = 5, sar = 7, sal = 4 } do
map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n)
end
-- Conditional ops.
for cc,n in pairs(map_cc) do
map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X
map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n)
map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+
end
-- FP arithmetic ops.
for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3,
sub = 4, subr = 5, div = 6, divr = 7 } do
local nc = 0xc0 + shl(n, 3)
local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8))
local fn = "f"..name
map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n)
if n == 2 or n == 3 then
map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n)
else
map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n)
map_op[fn.."p_1"] = format("ff:DE%02Xr", nr)
map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr)
end
map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n)
end
-- FP conditional moves.
for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do
local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6)
map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+
map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+
end
-- SSE / AVX FP arithmetic ops.
for name,n in pairs{ sqrt = 1, add = 8, mul = 9,
sub = 12, min = 13, div = 14, max = 15 } do
map_op[name.."ps_2"] = format("rmo:0F5%XrM", n)
map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n)
map_op[name.."pd_2"] = format("rmo:660F5%XrM", n)
map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n)
if n ~= 1 then
map_op["v"..name.."ps_3"] = format("rrmoy:0FV5%XrM", n)
map_op["v"..name.."ss_3"] = format("rrro:F30FV5%XrM|rrx/ood:", n)
map_op["v"..name.."pd_3"] = format("rrmoy:660FV5%XrM", n)
map_op["v"..name.."sd_3"] = format("rrro:F20FV5%XrM|rrx/ooq:", n)
end
end
-- SSE2 / AVX / AVX2 integer arithmetic ops (66 0F leaf).
for name,n in pairs{
paddb = 0xFC, paddw = 0xFD, paddd = 0xFE, paddq = 0xD4,
paddsb = 0xEC, paddsw = 0xED, packssdw = 0x6B,
packsswb = 0x63, packuswb = 0x67, paddusb = 0xDC,
paddusw = 0xDD, pand = 0xDB, pandn = 0xDF, pavgb = 0xE0,
pavgw = 0xE3, pcmpeqb = 0x74, pcmpeqd = 0x76,
pcmpeqw = 0x75, pcmpgtb = 0x64, pcmpgtd = 0x66,
pcmpgtw = 0x65, pmaddwd = 0xF5, pmaxsw = 0xEE,
pmaxub = 0xDE, pminsw = 0xEA, pminub = 0xDA,
pmulhuw = 0xE4, pmulhw = 0xE5, pmullw = 0xD5,
pmuludq = 0xF4, por = 0xEB, psadbw = 0xF6, psubb = 0xF8,
psubw = 0xF9, psubd = 0xFA, psubq = 0xFB, psubsb = 0xE8,
psubsw = 0xE9, psubusb = 0xD8, psubusw = 0xD9,
punpckhbw = 0x68, punpckhwd = 0x69, punpckhdq = 0x6A,
punpckhqdq = 0x6D, punpcklbw = 0x60, punpcklwd = 0x61,
punpckldq = 0x62, punpcklqdq = 0x6C, pxor = 0xEF
} do
map_op[name.."_2"] = format("rmo:660F%02XrM", n)
map_op["v"..name.."_3"] = format("rrmoy:660FV%02XrM", n)
end
------------------------------------------------------------------------------
local map_vexarg = { u = false, v = 1, V = 2 }
-- Process pattern string.
local function dopattern(pat, args, sz, op, needrex)
local digit, addin, vex
local opcode = 0
local szov = sz
local narg = 1
local rex = 0
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 6 positions.
if secpos+6 > maxsecpos then wflush() end
-- Process each character.
for c in gmatch(pat.."|", ".") do
if match(c, "%x") then -- Hex digit.
digit = byte(c) - 48
if digit > 48 then digit = digit - 39
elseif digit > 16 then digit = digit - 7 end
opcode = opcode*16 + digit
addin = nil
elseif c == "n" then -- Disable operand size mods for opcode.
szov = nil
elseif c == "X" then -- Force REX.W.
rex = 8
elseif c == "L" then -- Force VEX.L.
vex.l = true
elseif c == "r" then -- Merge 1st operand regno. into opcode.
addin = args[1]; opcode = opcode + (addin.reg % 8)
if narg < 2 then narg = 2 end
elseif c == "R" then -- Merge 2nd operand regno. into opcode.
addin = args[2]; opcode = opcode + (addin.reg % 8)
narg = 3
elseif c == "m" or c == "M" then -- Encode ModRM/SIB.
local s
if addin then
s = addin.reg
opcode = opcode - band(s, 7) -- Undo regno opcode merge.
else
s = band(opcode, 15) -- Undo last digit.
opcode = shr(opcode, 4)
end
local nn = c == "m" and 1 or 2
local t = args[nn]
if narg <= nn then narg = nn + 1 end
if szov == "q" and rex == 0 then rex = rex + 8 end
if t.reg and t.reg > 7 then rex = rex + 1 end
if t.xreg and t.xreg > 7 then rex = rex + 2 end
if s > 7 then rex = rex + 4 end
if needrex then rex = rex + 16 end
local psz, sk = wputop(szov, opcode, rex, vex, s < 0, t.vreg or t.vxreg)
opcode = nil
local imark = sub(pat, -1) -- Force a mark (ugly).
-- Put ModRM/SIB with regno/last digit as spare.
wputmrmsib(t, imark, s, addin and addin.vreg, psz, sk)
addin = nil
elseif map_vexarg[c] ~= nil then -- Encode using VEX prefix
local b = band(opcode, 255); opcode = shr(opcode, 8)
local m = 1
if b == 0x38 then m = 2
elseif b == 0x3a then m = 3 end
if m ~= 1 then b = band(opcode, 255); opcode = shr(opcode, 8) end
if b ~= 0x0f then
werror("expected `0F', `0F38', or `0F3A' to precede `"..c..
"' in pattern `"..pat.."' for `"..op.."'")
end
local v = map_vexarg[c]
if v then v = remove(args, v) end
b = band(opcode, 255)
local p = 0
if b == 0x66 then p = 1
elseif b == 0xf3 then p = 2
elseif b == 0xf2 then p = 3 end
if p ~= 0 then opcode = shr(opcode, 8) end
if opcode ~= 0 then wputop(nil, opcode, 0); opcode = 0 end
vex = { m = m, p = p, v = v }
else
if opcode then -- Flush opcode.
if szov == "q" and rex == 0 then rex = rex + 8 end
if needrex then rex = rex + 16 end
if addin and addin.reg == -1 then
local psz, sk = wputop(szov, opcode - 7, rex, vex, true)
wvreg("opcode", addin.vreg, psz, sk)
else
if addin and addin.reg > 7 then rex = rex + 1 end
wputop(szov, opcode, rex, vex)
end
opcode = nil
end
if c == "|" then break end
if c == "o" then -- Offset (pure 32 bit displacement).
wputdarg(args[1].disp); if narg < 2 then narg = 2 end
elseif c == "O" then
wputdarg(args[2].disp); narg = 3
else
-- Anything else is an immediate operand.
local a = args[narg]
narg = narg + 1
local mode, imm = a.mode, a.imm
if mode == "iJ" and not match("iIJ", c) then
werror("bad operand size for label")
end
if c == "S" then
wputsbarg(imm)
elseif c == "U" then
wputbarg(imm)
elseif c == "W" then
wputwarg(imm)
elseif c == "i" or c == "I" then
if mode == "iJ" then
wputlabel("IMM_", imm, 1)
elseif mode == "iI" and c == "I" then
waction(sz == "w" and "IMM_WB" or "IMM_DB", imm)
else
wputszarg(sz, imm)
end
elseif c == "J" then
if mode == "iPJ" then
waction("REL_A", imm) -- !x64 (secpos)
else
wputlabel("REL_", imm, 2)
end
elseif c == "s" then
local reg = a.reg
if reg < 0 then
wputb(0)
wvreg("imm.hi", a.vreg)
else
wputb(shl(reg, 4))
end
else
werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'")
end
end
end
end
end
------------------------------------------------------------------------------
-- Mapping of operand modes to short names. Suppress output with '#'.
local map_modename = {
r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm",
f = "stx", F = "st0", J = "lbl", ["1"] = "1",
I = "#", S = "#", O = "#",
}
-- Return a table/string showing all possible operand modes.
local function templatehelp(template, nparams)
if nparams == 0 then return "" end
local t = {}
for tm in gmatch(template, "[^%|]+") do
local s = map_modename[sub(tm, 1, 1)]
s = s..gsub(sub(tm, 2, nparams), ".", function(c)
return ", "..map_modename[c]
end)
if not match(s, "#") then t[#t+1] = s end
end
return t
end
-- Match operand modes against mode match part of template.
local function matchtm(tm, args)
for i=1,#args do
if not match(args[i].mode, sub(tm, i, i)) then return end
end
return true
end
-- Handle opcodes defined with template strings.
map_op[".template__"] = function(params, template, nparams)
if not params then return templatehelp(template, nparams) end
local args = {}
-- Zero-operand opcodes have no match part.
if #params == 0 then
dopattern(template, args, "d", params.op, nil)
return
end
-- Determine common operand size (coerce undefined size) or flag as mixed.
local sz, szmix, needrex
for i,p in ipairs(params) do
args[i] = parseoperand(p)
local nsz = args[i].opsize
if nsz then
if sz and sz ~= nsz then szmix = true else sz = nsz end
end
local nrex = args[i].needrex
if nrex ~= nil then
if needrex == nil then
needrex = nrex
elseif needrex ~= nrex then
werror("bad mix of byte-addressable registers")
end
end
end
-- Try all match:pattern pairs (separated by '|').
local gotmatch, lastpat
for tm in gmatch(template, "[^%|]+") do
-- Split off size match (starts after mode match) and pattern string.
local szm, pat = match(tm, "^(.-):(.*)$", #args+1)
if pat == "" then pat = lastpat else lastpat = pat end
if matchtm(tm, args) then
local prefix = sub(szm, 1, 1)
if prefix == "/" then -- Exactly match leading operand sizes.
for i = #szm,1,-1 do
if i == 1 then
dopattern(pat, args, sz, params.op, needrex) -- Process pattern.
return
elseif args[i-1].opsize ~= sub(szm, i, i) then
break
end
end
else -- Match common operand size.
local szp = sz
if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes.
if prefix == "1" then szp = args[1].opsize; szmix = nil
elseif prefix == "2" then szp = args[2].opsize; szmix = nil end
if not szmix and (prefix == "." or match(szm, szp or "#")) then
dopattern(pat, args, szp, params.op, needrex) -- Process pattern.
return
end
end
gotmatch = true
end
end
local msg = "bad operand mode"
if gotmatch then
if szmix then
msg = "mixed operand size"
else
msg = sz and "bad operand size" or "missing operand size"
end
end
werror(msg.." in `"..opmodestr(params.op, args).."'")
end
------------------------------------------------------------------------------
-- x64-specific opcode for 64 bit immediates and displacements.
if x64 then
function map_op.mov64_2(params)
if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end
if secpos+2 > maxsecpos then wflush() end
local opcode, op64, sz, rex, vreg
local op64 = match(params[1], "^%[%s*(.-)%s*%]$")
if op64 then
local a = parseoperand(params[2])
if a.mode ~= "rmR" then werror("bad operand mode") end
sz = a.opsize
rex = sz == "q" and 8 or 0
opcode = 0xa3
else
op64 = match(params[2], "^%[%s*(.-)%s*%]$")
local a = parseoperand(params[1])
if op64 then
if a.mode ~= "rmR" then werror("bad operand mode") end
sz = a.opsize
rex = sz == "q" and 8 or 0
opcode = 0xa1
else
if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then
werror("bad operand mode")
end
op64 = params[2]
if a.reg == -1 then
vreg = a.vreg
opcode = 0xb8
else
opcode = 0xb8 + band(a.reg, 7)
end
rex = a.reg > 7 and 9 or 8
end
end
local psz, sk = wputop(sz, opcode, rex, nil, vreg)
wvreg("opcode", vreg, psz, sk)
waction("IMM_D", format("(unsigned int)(%s)", op64))
waction("IMM_D", format("(unsigned int)((%s)>>32)", op64))
end
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
local function op_data(params)
if not params then return "imm..." end
local sz = sub(params.op, 2, 2)
if sz == "a" then sz = addrsize end
for _,p in ipairs(params) do
local a = parseoperand(p)
if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then
werror("bad mode or size in `"..p.."'")
end
if a.mode == "iJ" then
wputlabel("IMM_", a.imm, 1)
else
wputszarg(sz, a.imm)
end
if secpos+2 > maxsecpos then wflush() end
end
end
map_op[".byte_*"] = op_data
map_op[".sbyte_*"] = op_data
map_op[".word_*"] = op_data
map_op[".dword_*"] = op_data
map_op[".aword_*"] = op_data
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_2"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end
if secpos+2 > maxsecpos then wflush() end
local a = parseoperand(params[1])
local mode, imm = a.mode, a.imm
if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then
-- Local label (1: ... 9:) or global label (->global:).
waction("LABEL_LG", nil, 1)
wputxb(imm)
elseif mode == "iJ" then
-- PC label (=>pcexpr:).
waction("LABEL_PC", imm)
else
werror("bad label definition")
end
-- SETLABEL must immediately follow LABEL_LG/LABEL_PC.
local addr = params[2]
if addr then
local a = parseoperand(addr)
if a.mode == "iPJ" then
waction("SETLABEL", a.imm)
else
werror("bad label assignment")
end
end
end
map_op[".label_1"] = map_op[".label_2"]
------------------------------------------------------------------------------
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]]
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", nil, 1)
wputxb(align-1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
-- Spacing pseudo-opcode.
map_op[".space_2"] = function(params)
if not params then return "num [, filler]" end
if secpos+1 > maxsecpos then wflush() end
waction("SPACE", params[1])
local fill = params[2]
if fill then
fill = tonumber(fill)
if not fill or fill < 0 or fill > 255 then werror("bad filler") end
end
wputxb(fill or 0)
end
map_op[".space_1"] = map_op[".space_2"]
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
if reg and not map_reg_valid_base[reg] then
werror("bad base register `"..(map_reg_rev[reg] or reg).."'")
end
-- Add #type to defines. A bit unclean to put it in map_archdef.
map_archdef["#"..name] = "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
map_type[name] = {
ctype = ctype,
ctypefmt = format("Dt%X(%%s)", num),
reg = reg,
}
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg and map_reg_rev[tp.reg] or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION")
wputxb(num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpregs(out)
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = map_coreop })
setmetatable(map_def, { __index = map_archdef })
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| apache-2.0 |
Kosmos82/kosmosdarkstar | scripts/globals/weaponskills/herculean_slash.lua | 10 | 1568 | -----------------------------------
-- Herculean Slash
-- Great Sword weapon skill
-- Skill Level: 290
-- Paralyzes target. Duration of effect varies with TP.
-- Aligned with the Snow Gorget, Thunder Gorget & Breeze Gorget.
-- Aligned with the Snow Belt, Thunder Belt & Breeze Belt.
-- Element: Ice
-- Modifiers: VIT:60%
-- As this is a magic-based weaponskill it is also modified by Magic Attack Bonus.
-- 100%TP 200%TP 300%TP
-- 3.50 3.50 3.50
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.ftp100 = 3.5; params.ftp200 = 3.5; params.ftp300 = 3.5;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.6; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_ICE;
params.skill = SKILL_GSD;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.vit_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary);
if (damage > 0) then
local duration = (tp/1000 * 60)
if (target:hasStatusEffect(EFFECT_PARALYSIS) == false) then
target:addStatusEffect(EFFECT_PARALYSIS, 30, 0, duration);
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Northern_San_dOria/npcs/Villion.lua | 13 | 1480 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Villion
-- Type: Adventurer's Assistant NPC
-- Involved in Quest: Flyers for Regine
-- @zone: 231
-- @pos -157.524 4.000 263.818
--
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeVilion") == 0) then
player:messageSpecial(VILLION_DIALOG);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradeVilion",1);
player:messageSpecial(FLYER_ACCEPTED);
player:tradeComplete();
elseif (player:getVar("tradeVilion") ==1) then
player:messageSpecial(FLYER_ALREADY);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0278);
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 |
sumory/orange | orange/plugins/kafka/handler.lua | 2 | 4213 | local BasePlugin = require("orange.plugins.base_handler")
local cjson = require "cjson"
local producer = require "resty.kafka.producer"
local KafkaHandler = BasePlugin:extend()
KafkaHandler.PRIORITY = 2000
function KafkaHandler:new(store)
KafkaHandler.super.new(self, "kafka-plugin")
self.store = store
end
local function errlog(...)
ngx.log(ngx.ERR,'[Kafka]',...)
end
local do_log = function(log_table)
-- 定义kafka broker地址,ip需要和kafka的host.name配置一致
local broker_list = context.config.plugin_config.kafka.broker_list
local kafka_topic = context.config.plugin_config.kafka.topic
local producer_config = context.config.plugin_config.kafka.producer_config
-- 定义json便于日志数据整理收集
-- 转换json为字符串
local message = cjson.encode(log_table);
-- 定义kafka异步生产者
local bp = producer:new(broker_list, producer_config)
-- 发送日志消息,send第二个参数key,用于kafka路由控制:
-- key为nill(空)时,一段时间向同一partition写入数据
-- 指定key,按照key的hash写入到对应的partition
local ok, err = bp:send(kafka_topic, nil, message)
if not ok then
errlog("kafka send err:", err)
return
end
end
local function log(premature,log_table)
if premature then
errlog("timer premature")
return
end
local ok,err = pcall(do_log,log_table)
if not ok then
errlog("failed to record log by kafka",err)
local ok,err = ngx.timer.at(0,log,log_table)
if not ok then
errlog ("faild to create timer",err)
end
end
end
-- log_format main '$remote_addr - $remote_user [$time_local] "$request" '
-- '$status $body_bytes_sent "$http_referer" '
-- '"$http_user_agent" "$request_time" "$ssl_protocol" "$ssl_cipher" "$http_x_forwarded_for"'
-- '"$upstream_addr" "$upstream_status" "$upstream_response_length" "$upstream_response_time"';
function KafkaHandler:log()
local log_json = {}
log_json["remote_addr"] = ngx.var.remote_addr and ngx.var.remote_addr or '-'
log_json["remote_user"] = ngx.var.remote_user and ngx.var.remote_user or '-'
log_json["time_local"] = ngx.var.time_local and ngx.var.time_local or '-'
log_json['request'] = ngx.var.request and ngx.var.request or '-'
log_json["status"] = ngx.var.status and ngx.var.status or '-'
log_json["body_bytes_sent"] = ngx.var.body_bytes_sent and ngx.var.body_bytes_sent or '-'
log_json["http_referer"] = ngx.var.http_referer and ngx.var.http_referer or '-'
log_json["http_user_agent"] = ngx.var.http_user_agent and ngx.var.http_user_agent or '-'
log_json["request_time"] = ngx.var.request_time and ngx.var.request_time or '-'
log_json["uri"]=ngx.var.uri and ngx.var.uri or '-'
log_json["args"]=ngx.var.args and ngx.var.args or '-'
log_json["host"]=ngx.var.host and ngx.var.host or '-'
log_json["request_body"]=ngx.var.request_body and ngx.var.request_body or '-'
log_json['ssl_protocol'] = ngx.var.ssl_protocol and ngx.var.ssl_protocol or ' -'
log_json['ssl_cipher'] = ngx.var.ssl_cipher and ngx.var.ssl_cipher or ' -'
log_json['upstream_addr'] = ngx.var.upstream_addr and ngx.var.upstream_addr or ' -'
log_json['upstream_status'] = ngx.var.upstream_status and ngx.var.upstream_status or ' -'
log_json['upstream_response_length'] = ngx.var.upstream_response_length and ngx.var.upstream_response_length or ' -'
log_json["http_x_forwarded_for"] = ngx.var.http_x_forwarded_for and ngx.var.http_x_forwarded_for or '-'
log_json["upstream_response_time"] = ngx.var.upstream_response_time and ngx.var.upstream_response_time or '-'
log_json["upstream_url"] = "http://" .. ngx.var.upstream_url .. ngx.var.upstream_request_uri or '';
log_json["request_headers"] = ngx.req.get_headers();
log_json["response_headers"] = ngx.resp.get_headers();
log_json["server_addr"] = ngx.var.server_addr
local ok,err = ngx.timer.at(0,log,log_json)
if not ok then
errlog ("faild to create timer",err)
end
end
return KafkaHandler
| mit |
Kosmos82/kosmosdarkstar | scripts/globals/mobskills/Tidal_Slash.lua | 37 | 1331 | ---------------------------------------------
-- Tidal Slash
--
-- Description: Deals Water<a href="http://images.wikia.com/ffxi/images/b/b7/Exclamation.gif" class="image" title="Verification Needed" data-image-name="Exclamation.gif" id="Exclamation-gif"><img alt="Verification Needed" src="http://images1.wikia.nocookie.net/__cb20061130211022/ffxi/images/thumb/b/b7/Exclamation.gif/14px-Exclamation.gif" width="14" height="12" /> damage in a threefold attack to targets in a fan-shaped area of effect.
-- Type: Physical?
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: Melee?
-- Notes: Used only by Merrows equipped with a spear. If they lost their spear, they'll use Hysteric Barrage instead.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 3;
local accmod = 1;
local dmgmod = 1;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
utunnels/mjpeg-player-for-LOVE-engine | mplayermt.lua | 1 | 4958 | -- A movie player for LÖVE engine 0.8.0, version 2
-- Coded by utunnels (utunnels@hotmail.com)
-- Example:
--[[
require "mplayer"
function love.load()
mplayer = VideoPlayer.create("path_to_your_movie_folder")
mplayer:start()
end
function love.update(dt)
mplayer:play()
end
function love.draw()
mplayer:draw()
end
]]--
--[[
Files in movie folder:
audio.ogg -- optional
video.mjpeg -- it should be a renamed avi file encoded using mjpeg, without audio
conf.lua -- optional, it is executed after the player is created
]]--
VideoPlayer = {}
VideoPlayer.__index = VideoPlayer
function VideoPlayer.create(vidPath)
local self = {}
setmetatable(self, VideoPlayer)
self.vidPath = vidPath
self.movieFps = 15
local ok, mconf
ok, mconf = pcall(love.filesystem.load, self.vidPath.."/conf.lua")
if ok and mconf then
mconf(self)
end
return self
end
function bytes_to_int(s)
local b1,b2,b3,b4 = s:byte(1,4)
local n = b1 + b2*256 + b3*65536 + b4*16777216
n = (n > 2147483647) and (n - 4294967296) or n
return n
end
--http://msdn.microsoft.com/en-us/library/windows/desktop/dd318189(v=vs.85).aspx
function VideoPlayer:parseAVI()
local f = self.videoSource
f:seek(0)
while true do
local b,s = f:read(4)
if s~=4 then
break
elseif b=="avih" then
local _,_=f:read(4) --skip size
local n,_=f:read(4)
self.movieFps = 1000000/bytes_to_int(n)
local _,_=f:read(12) --skip size
local l,_=f:read(4)
self.totalFrames = bytes_to_int(l)
elseif b=="movi" then
f:seek(f:tell()-8)
local n,_=f:read(4)
local l = bytes_to_int(n)
local st = f:tell()+8
local ft = f:tell()+l+8
self.frameTable = {}
for i=1,self.totalFrames do
f:seek(ft+16*(i-1)+8)
local o,_=f:read(4)
self.frameTable[i]=bytes_to_int(o)+st
end
break
end
end
end
function VideoPlayer:start()
self.videoSource = love.filesystem.newFile(self.vidPath.."/video.mjpeg")
self.videoSource:open("r")
self:parseAVI()
self.currentFrame = 0
self.videoFrame = nil
self.stopped = false
local apath = self.vidPath.."/audio.ogg"
if love.filesystem.exists(apath) then
self.audioSource = love.audio.newSource(apath, "stream")
self.audioSource:play()
end
self.movieStartTime = love.timer.getTime()
self.loader = love.thread.newThread( "loader", "mjpegdecoder.lua")
self.loader:start()
self:request(1)
end
function VideoPlayer:stop()
if self.audioSource then
self.audioSource:stop()
self.audioSource = nil
end
self.videoSource:close()
self.stopped = true
self.videoFrame = nil
self.lastDecoded = nil
if self.loader then
self.loader:set("frame", "quit")
end
self.loader = nil
end
function VideoPlayer:cleanBuffer()
if (not self.gcThreshold) or self.gcThreshold<collectgarbage("count") then
collectgarbage("collect")
end
end
function VideoPlayer.newPaddedImage(source)
if not love.graphics.isSupported("npot") then
local w, h = source:getWidth(), source:getHeight()
-- Find closest power-of-two.
local wp = math.pow(2, math.ceil(math.log(w)/math.log(2)))
local hp = math.pow(2, math.ceil(math.log(h)/math.log(2)))
-- Only pad if needed:
if wp ~= w or hp ~= h then
if not padded then
padded = love.image.newImageData(wp, hp)
end
padded:paste(source, 0, 0)
return love.graphics.newImage(padded)
end
end
return love.graphics.newImage(source)
end
function VideoPlayer:updateVideoFrame(frm)
if not self.videoFrame or not self.videoFrame.refresh then
self.videoFrame = VideoPlayer.newPaddedImage(frm)
else
self.videoFrame:getData():paste(frm,0,0)
self.videoFrame:refresh()
end
end
function VideoPlayer:request(f)
self.loader:set("frame", f)
self.loader:set("file", self.videoSource)
self.loader:set("pos", self.frameTable[f])
end
function VideoPlayer:play()
if self.stopped then
return
end
local mtime = 0
if not self.audioSource or self.audioSource:isStopped() then
mtime = love.timer.getTime() - self.movieStartTime
else
mtime = self.audioSource:tell("seconds")
end
local f = math.floor(mtime*self.movieFps)
self:cleanBuffer()
if f>self.currentFrame then
if self.loader:get("working") then
local frm = self.loader:demand("decoded")
if frm then
self:updateVideoFrame(frm)
self.lastDecoded = frm
end
end
self:request(f+2)
self.currentFrame = f
end
end
function VideoPlayer:draw(x, y, size)
local frm = self.lastDecoded
if frm and self.videoFrame then
love.graphics.draw(self.videoFrame, x or 0, y or 0,0,size or love.graphics.getWidth()/frm:getWidth(), size or love.graphics.getHeight()/frm:getHeight())
--love.graphics.draw(videoFrame,0,0)
love.graphics.print(string.format("fps: %d", love.timer.getFPS()), 10, 10)
end
end
| unlicense |
Kosmos82/kosmosdarkstar | scripts/zones/Port_San_dOria/npcs/Teilsa.lua | 13 | 1814 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Teilsa
-- Adventurer's Assistant
-- Only recieving Adv.Coupon and simple talk event are scrited
-- This NPC participates in Quests and Missions
-------------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(0x218,1) == true) then
player:startEvent(0x0264);
player:addGil(GIL_RATE*50);
player:tradeComplete();
end
-- "Flyers for Regine" conditional script
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x023d);
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 == 0x0264) then
player:messageSpecial(GIL_OBTAINED,GIL_RATE*50);
end
end;
| gpl-3.0 |
hadow/OpenRA | mods/ra/maps/soviet-04b/soviet04b-reinforcements_teams.lua | 6 | 2753 | Civs = { civ1, civ2, civ3, civ4 }
Village = { civ1, civ3, civ4, village1, village3 }
Guards = { Guard1, Guard2, Guard3 }
SovietMCV = { "mcv" }
InfantryReinfGreece = { "e1", "e1", "e1", "e1", "e1" }
Avengers = { "jeep", "1tnk", "2tnk", "2tnk", "1tnk" }
Patrol1Group = { "jeep", "jeep", "2tnk", "2tnk" }
Patrol2Group = { "jeep", "1tnk", "1tnk", "1tnk" }
AlliedInfantryTypes = { "e1", "e3" }
AlliedArmorTypes = { "jeep", "jeep", "1tnk", "1tnk", "1tnk" }
InfAttack = { }
ArmorAttack = { }
InfReinfPath = { NRoadPoint.Location, CrossroadsPoint.Location, ToVillageRoadPoint.Location, VillagePoint.Location }
Patrol1Path = { ToVillageRoadPoint.Location, ToBridgePoint.Location, InBasePoint.Location }
Patrol2Path = { EntranceSouthPoint.Location, ToRadarBridgePoint.Location, IslandPoint.Location, ToRadarBridgePoint.Location }
VillageCamArea = { CPos.New(37, 58),CPos.New(37, 59),CPos.New(37, 60),CPos.New(38, 60),CPos.New(39, 60), CPos.New(40, 60), CPos.New(41, 60), CPos.New(35, 57), CPos.New(34, 57), CPos.New(33, 57), CPos.New(32, 57) }
if Map.LobbyOption("difficulty") == "easy" then
ArmorReinfGreece = { "jeep", "1tnk", "1tnk" }
else
ArmorReinfGreece = { "jeep", "jeep", "1tnk", "1tnk", "1tnk" }
end
AttackPaths =
{
{ CrossroadsPoint, ToVillageRoadPoint, VillagePoint },
{ EntranceSouthPoint, OrefieldSouthPoint },
{ CrossroadsPoint, ToBridgePoint }
}
ReinfInf = function()
if Radar.IsDead or Radar.Owner ~= Greece then
return
end
Reinforcements.Reinforce(Greece, InfantryReinfGreece, InfReinfPath, 0, function(soldier)
soldier.Hunt()
end)
end
ReinfArmor = function()
if not Radar.IsDead and Radar.Owner == Greece then
RCheck = true
Reinforcements.Reinforce(Greece, ArmorReinfGreece, InfReinfPath, 0, function(soldier)
soldier.Hunt()
end)
end
end
BringPatrol1 = function()
if Radar.IsDead or Radar.Owner ~= Greece then
return
end
local units = Reinforcements.Reinforce(Greece, Patrol1Group, { NRoadPoint.Location }, 0)
Utils.Do(units, function(patrols)
patrols.Patrol(Patrol1Path, true, 250)
end)
Trigger.OnAllKilled(units, function()
if Map.LobbyOption("difficulty") == "hard" then
Trigger.AfterDelay(DateTime.Minutes(4), BringPatrol1)
else
Trigger.AfterDelay(DateTime.Minutes(7), BringPatrol1)
end
end)
end
BringPatrol2 = function()
if Radar.IsDead or Radar.Owner ~= Greece then
return
end
local units = Reinforcements.Reinforce(Greece, Patrol2Group, { NRoadPoint.Location }, 0)
Utils.Do(units, function(patrols)
patrols.Patrol(Patrol2Path, true, 250)
end)
Trigger.OnAllKilled(units, function()
if Map.LobbyOption("difficulty") == "hard" then
Trigger.AfterDelay(DateTime.Minutes(4), BringPatrol2)
else
Trigger.AfterDelay(DateTime.Minutes(7), BringPatrol2)
end
end)
end
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Northern_San_dOria/npcs/Mulaujeant.lua | 27 | 2466 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Mulaujeant
-- Involved in Quests: Missionary Man
-- @zone 231
-- @pos -175 0 181
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day
starttime = player:getVar("MissionaryMan_date");
MissionaryManVar = player:getVar("MissionaryManVar");
if (MissionaryManVar == 2) then
player:startEvent(0x02ba,0,1146); -- Start statue creation
elseif (MissionaryManVar == 3 and (starttime == realday or player:needToZone() == true)) then
player:startEvent(0x02bb); -- During statue creation
elseif (MissionaryManVar == 3 and starttime ~= realday and player:needToZone() == false) then
player:startEvent(0x02bc); -- End of statue creation
elseif (MissionaryManVar == 4) then
player:startEvent(0x02bd); -- During quest (after creation)
else
player:startEvent(0x02b9); -- 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 == 0x02ba) then
player:setVar("MissionaryManVar",3);
player:setVar("MissionaryMan_date", os.date("%j")); -- %M for next minute, %j for next day
player:delKeyItem(RAUTEINOTS_PARCEL);
player:needToZone(true);
elseif (csid == 0x02bc) then
player:setVar("MissionaryManVar",4);
player:setVar("MissionaryMan_date", 0);
player:addKeyItem(SUBLIME_STATUE_OF_THE_GODDESS);
player:messageSpecial(KEYITEM_OBTAINED,SUBLIME_STATUE_OF_THE_GODDESS);
end
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Kazham/npcs/Pofhu_Tendelicon.lua | 15 | 1056 | -----------------------------------
-- Area: Kazham
-- NPC: Pofhu Tendelicon
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00A9); -- scent from Blue Rafflesias
else
player:startEvent(0x0040);
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 |
Kosmos82/kosmosdarkstar | scripts/zones/Northern_San_dOria/npcs/Pagisalis.lua | 25 | 3103 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Pagisalis
-- Involved In Quest: Enveloped in Darkness
-- @zone 231
-- @pos
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,UNDYING_FLAMES) == QUEST_ACCEPTED) then
if (trade:hasItemQty(913,2) and trade:getItemCount() == 2) then -- Trade Lump of Beeswax
player:startEvent(0x0233);
end
end
if (player:hasKeyItem(OLD_POCKET_WATCH) and player:hasKeyItem(OLD_BOOTS) == false) then
if (trade:hasItemQty(828,1) and trade:getItemCount() == 1) then -- Trade Velvet Cloth
player:startEvent(0x0025);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
sanFame = player:getFameLevel(SANDORIA);
undyingFlames = player:getQuestStatus(SANDORIA,UNDYING_FLAMES);
if (player:hasKeyItem(OLD_POCKET_WATCH)) then
player:startEvent(0x0030);
elseif (player:hasKeyItem(OLD_BOOTS)) then
player:startEvent(0x003A);
elseif (sanFame >= 2 and undyingFlames == QUEST_AVAILABLE) then
player:startEvent(0x0232);
elseif (undyingFlames == QUEST_ACCEPTED) then
player:startEvent(0x0235);
elseif (undyingFlames == QUEST_COMPLETED) then
player:startEvent(0x0236);
else
player:startEvent(0x0234)
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 == 0x0232 and option == 0) then
player:addQuest(SANDORIA,UNDYING_FLAMES);
elseif (csid == 0x0233) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13211); -- Friars Rope
else
player:tradeComplete();
player:addTitle(FAITH_LIKE_A_CANDLE);
player:addItem(13211);
player:messageSpecial(ITEM_OBTAINED,13211); -- Friars Rope
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,UNDYING_FLAMES);
end
elseif (csid == 0x0025) then
player:tradeComplete();
player:delKeyItem(OLD_POCKET_WATCH);
player:addKeyItem(OLD_BOOTS);
player:messageSpecial(KEYITEM_OBTAINED,OLD_BOOTS);
end
end; | gpl-3.0 |
sprunk/Zero-K-Infrastructure | MissionEditor/MissionEditor2/MissionBase/LuaUI/Widgets/gui_api_hide_hax.lua | 7 | 1693 | function widget:GetInfo()
return {
name = "GUI Hide Hax",
desc = "Allows hiding of non-registered GUI elements",
author = "KingRaptor (L.J. Lim)",
date = "2012.10.26",
license = "GNU GPL v2",
layer = -math.huge,
enabled = true,
handler = true,
api = true,
}
end
local noHide = {}
local layers = {} -- [widget] == layer
local hidden = false
local function HideGUI()
if hidden then return end
hidden = true
Spring.SendCommands("mapmarks 0")
-- hook widgetHandler to allow us to override the DrawScreen callin
local wh = widgetHandler
wh.oldDrawScreenList = wh.DrawScreenList
wh.DrawScreenList = noHide
end
local function UnhideGUI()
if not hidden then return end
hidden = false
Spring.SendCommands("mapmarks 1")
local wh = widgetHandler
wh.DrawScreenList = wh.oldDrawScreenList
end
local function AddNoHide(wdgt)
-- sort by layer
local layer = wdgt:GetInfo().layer
layers[wdgt] = layer
local index = #noHide + 1
for i=1,#noHide do
if layer < layers[noHide[i]] then
index = i
end
end
table.insert(noHide, index, wdgt)
--Spring.Echo("no hide", #noHide, index)
end
local function RemoveNoHide(wdgt)
for i=1,#noHide do
if noHide[i] == wdgt then
table.remove(noHide, index)
break
end
end
local wh = widgetHandler
layers[wdgt] = nil
end
function widget:Initialize()
WG.HideGUI = HideGUI
WG.UnhideGUI = UnhideGUI
WG.AddNoHideWidget = AddNoHide
WG.RemoveNoHideWidget = RemoveNoHide
WG.IsGUIHidden = function() return hidden end
end
function widget:Shutdown()
UnhideGUI()
WG.HideGUI = nil
WG.UnhideGUI = nil
WG.AddNoHideWidget = nil
WG.RemoveNoHideWidget = nil
WG.IsGUIHidden = nil
end | gpl-3.0 |
RobberPhex/thrift | lib/lua/TSocket.lua | 113 | 2996 | ---- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you 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.
--
require 'TTransport'
require 'libluasocket'
-- TSocketBase
TSocketBase = TTransportBase:new{
__type = 'TSocketBase',
timeout = 1000,
host = 'localhost',
port = 9090,
handle
}
function TSocketBase:close()
if self.handle then
self.handle:destroy()
self.handle = nil
end
end
-- Returns a table with the fields host and port
function TSocketBase:getSocketInfo()
if self.handle then
return self.handle:getsockinfo()
end
terror(TTransportException:new{errorCode = TTransportException.NOT_OPEN})
end
function TSocketBase:setTimeout(timeout)
if timeout and ttype(timeout) == 'number' then
if self.handle then
self.handle:settimeout(timeout)
end
self.timeout = timeout
end
end
-- TSocket
TSocket = TSocketBase:new{
__type = 'TSocket',
host = 'localhost',
port = 9090
}
function TSocket:isOpen()
if self.handle then
return true
end
return false
end
function TSocket:open()
if self.handle then
self:close()
end
-- Create local handle
local sock, err = luasocket.create_and_connect(
self.host, self.port, self.timeout)
if err == nil then
self.handle = sock
end
if err then
terror(TTransportException:new{
message = 'Could not connect to ' .. self.host .. ':' .. self.port
.. ' (' .. err .. ')'
})
end
end
function TSocket:read(len)
local buf = self.handle:receive(self.handle, len)
if not buf or string.len(buf) ~= len then
terror(TTransportException:new{errorCode = TTransportException.UNKNOWN})
end
return buf
end
function TSocket:write(buf)
self.handle:send(self.handle, buf)
end
function TSocket:flush()
end
-- TServerSocket
TServerSocket = TSocketBase:new{
__type = 'TServerSocket',
host = 'localhost',
port = 9090
}
function TServerSocket:listen()
if self.handle then
self:close()
end
local sock, err = luasocket.create(self.host, self.port)
if not err then
self.handle = sock
else
terror(err)
end
self.handle:settimeout(self.timeout)
self.handle:listen()
end
function TServerSocket:accept()
local client, err = self.handle:accept()
if err then
terror(err)
end
return TSocket:new({handle = client})
end
| apache-2.0 |
Igalia/snabb | lib/ljsyscall/syscall/linux/ffi.lua | 4 | 22381 | -- ffi definitions of Linux types
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local abi = require "syscall.abi"
local ffi = require "ffi"
require "syscall.ffitypes"
local arch = require("syscall.linux." .. abi.arch .. ".ffi") -- architecture specific definitions
local defs = {}
local function append(str) defs[#defs + 1] = str end
append [[
typedef uint32_t mode_t;
typedef unsigned short int sa_family_t;
typedef uint64_t rlim64_t;
typedef unsigned long nlink_t;
typedef unsigned long ino_t;
typedef long time_t;
typedef int32_t daddr_t;
typedef long blkcnt_t;
typedef long blksize_t;
typedef int32_t clockid_t;
typedef long clock_t;
typedef uint32_t off32_t; /* only used for eg mmap2 on Linux */
typedef uint32_t le32; /* this is little endian - not really using it yet */
typedef uint32_t id_t;
typedef unsigned int tcflag_t;
typedef unsigned int speed_t;
typedef int timer_t;
typedef uint64_t fsblkcnt_t;
typedef uint64_t fsfilcnt_t;
/* despite glibc, Linux uses 32 bit dev_t */
typedef uint32_t dev_t;
typedef unsigned long aio_context_t;
typedef unsigned long nfds_t;
// should be a word, but we use 32 bits as bitops are signed 32 bit in LuaJIT at the moment
typedef int32_t fd_mask;
// again should be a long, and we have wrapped in a struct
// TODO ok to wrap Lua types but not syscall? https://github.com/justincormack/ljsyscall/issues/36
// TODO is this size right? check
struct cpu_set_t {
int32_t val[1024 / (8 * sizeof (int32_t))];
};
typedef int mqd_t;
typedef int idtype_t; /* defined as enum */
struct timespec {
time_t tv_sec;
long tv_nsec;
};
// misc
typedef void (*sighandler_t) (int);
// structs
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
struct itimerspec {
struct timespec it_interval;
struct timespec it_value;
};
struct itimerval {
struct timeval it_interval;
struct timeval it_value;
};
typedef struct __fsid_t {
int __val[2];
} fsid_t;
//static const int UTSNAME_LENGTH = 65;
struct utsname {
char sysname[65];
char nodename[65];
char release[65];
char version[65];
char machine[65];
char domainname[65];
};
struct pollfd {
int fd;
short int events;
short int revents;
};
typedef struct { /* based on Linux FD_SETSIZE = 1024, the kernel can do more, so can increase */
fd_mask fds_bits[1024 / (sizeof (fd_mask) * 8)];
} fd_set;
struct ucred {
pid_t pid;
uid_t uid;
gid_t gid;
};
struct rlimit64 {
rlim64_t rlim_cur;
rlim64_t rlim_max;
};
struct sysinfo {
long uptime;
unsigned long loads[3];
unsigned long totalram;
unsigned long freeram;
unsigned long sharedram;
unsigned long bufferram;
unsigned long totalswap;
unsigned long freeswap;
unsigned short procs;
unsigned short pad;
unsigned long totalhigh;
unsigned long freehigh;
unsigned int mem_unit;
char _f[20-2*sizeof(long)-sizeof(int)]; /* TODO ugh, remove calculation */
};
struct timex {
unsigned int modes;
long int offset;
long int freq;
long int maxerror;
long int esterror;
int status;
long int constant;
long int precision;
long int tolerance;
struct timeval time;
long int tick;
long int ppsfreq;
long int jitter;
int shift;
long int stabil;
long int jitcnt;
long int calcnt;
long int errcnt;
long int stbcnt;
int tai;
int :32; int :32; int :32; int :32;
int :32; int :32; int :32; int :32;
int :32; int :32; int :32;
};
typedef union sigval {
int sival_int;
void *sival_ptr;
} sigval_t;
struct cmsghdr {
size_t cmsg_len;
int cmsg_level;
int cmsg_type;
char cmsg_data[?];
};
struct msghdr {
void *msg_name;
socklen_t msg_namelen;
struct iovec *msg_iov;
size_t msg_iovlen;
void *msg_control;
size_t msg_controllen;
int msg_flags;
};
struct mmsghdr {
struct msghdr msg_hdr;
unsigned int msg_len;
};
struct sockaddr {
sa_family_t sa_family;
char sa_data[14];
};
struct sockaddr_storage {
sa_family_t ss_family;
unsigned long int __ss_align;
char __ss_padding[128 - 2 * sizeof(unsigned long int)]; /* total length 128 TODO no calculations */
};
struct sockaddr_in {
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
unsigned char sin_zero[8];
};
struct sockaddr_in6 {
sa_family_t sin6_family;
in_port_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
};
struct sockaddr_un {
sa_family_t sun_family;
char sun_path[108];
};
struct sockaddr_nl {
sa_family_t nl_family;
unsigned short nl_pad;
uint32_t nl_pid;
uint32_t nl_groups;
};
struct sockaddr_ll {
unsigned short sll_family;
unsigned short sll_protocol; /* __be16 */
int sll_ifindex;
unsigned short sll_hatype;
unsigned char sll_pkttype;
unsigned char sll_halen;
unsigned char sll_addr[8];
};
struct nlmsghdr {
uint32_t nlmsg_len;
uint16_t nlmsg_type;
uint16_t nlmsg_flags;
uint32_t nlmsg_seq;
uint32_t nlmsg_pid;
};
struct rtgenmsg {
unsigned char rtgen_family;
};
struct ifinfomsg {
unsigned char ifi_family;
unsigned char __ifi_pad;
unsigned short ifi_type;
int ifi_index;
unsigned ifi_flags;
unsigned ifi_change;
};
struct rtattr {
unsigned short rta_len;
unsigned short rta_type;
};
struct nlmsgerr {
int error;
struct nlmsghdr msg;
};
struct rtmsg {
unsigned char rtm_family;
unsigned char rtm_dst_len;
unsigned char rtm_src_len;
unsigned char rtm_tos;
unsigned char rtm_table;
unsigned char rtm_protocol;
unsigned char rtm_scope;
unsigned char rtm_type;
unsigned int rtm_flags;
};
static const int IFNAMSIZ = 16;
struct ifmap {
unsigned long mem_start;
unsigned long mem_end;
unsigned short base_addr;
unsigned char irq;
unsigned char dma;
unsigned char port;
};
struct rtnl_link_stats {
uint32_t rx_packets;
uint32_t tx_packets;
uint32_t rx_bytes;
uint32_t tx_bytes;
uint32_t rx_errors;
uint32_t tx_errors;
uint32_t rx_dropped;
uint32_t tx_dropped;
uint32_t multicast;
uint32_t collisions;
uint32_t rx_length_errors;
uint32_t rx_over_errors;
uint32_t rx_crc_errors;
uint32_t rx_frame_errors;
uint32_t rx_fifo_errors;
uint32_t rx_missed_errors;
uint32_t tx_aborted_errors;
uint32_t tx_carrier_errors;
uint32_t tx_fifo_errors;
uint32_t tx_heartbeat_errors;
uint32_t tx_window_errors;
uint32_t rx_compressed;
uint32_t tx_compressed;
};
struct ndmsg {
uint8_t ndm_family;
uint8_t ndm_pad1;
uint16_t ndm_pad2;
int32_t ndm_ifindex;
uint16_t ndm_state;
uint8_t ndm_flags;
uint8_t ndm_type;
};
struct nda_cacheinfo {
uint32_t ndm_confirmed;
uint32_t ndm_used;
uint32_t ndm_updated;
uint32_t ndm_refcnt;
};
struct ndt_stats {
uint64_t ndts_allocs;
uint64_t ndts_destroys;
uint64_t ndts_hash_grows;
uint64_t ndts_res_failed;
uint64_t ndts_lookups;
uint64_t ndts_hits;
uint64_t ndts_rcv_probes_mcast;
uint64_t ndts_rcv_probes_ucast;
uint64_t ndts_periodic_gc_runs;
uint64_t ndts_forced_gc_runs;
};
struct ndtmsg {
uint8_t ndtm_family;
uint8_t ndtm_pad1;
uint16_t ndtm_pad2;
};
struct ndt_config {
uint16_t ndtc_key_len;
uint16_t ndtc_entry_size;
uint32_t ndtc_entries;
uint32_t ndtc_last_flush;
uint32_t ndtc_last_rand;
uint32_t ndtc_hash_rnd;
uint32_t ndtc_hash_mask;
uint32_t ndtc_hash_chain_gc;
uint32_t ndtc_proxy_qlen;
};
typedef struct {
unsigned int clock_rate;
unsigned int clock_type;
unsigned short loopback;
} sync_serial_settings;
typedef struct {
unsigned int clock_rate;
unsigned int clock_type;
unsigned short loopback;
unsigned int slot_map;
} te1_settings;
typedef struct {
unsigned short encoding;
unsigned short parity;
} raw_hdlc_proto;
typedef struct {
unsigned int t391;
unsigned int t392;
unsigned int n391;
unsigned int n392;
unsigned int n393;
unsigned short lmi;
unsigned short dce;
} fr_proto;
typedef struct {
unsigned int dlci;
} fr_proto_pvc;
typedef struct {
unsigned int dlci;
char master[IFNAMSIZ];
} fr_proto_pvc_info;
typedef struct {
unsigned int interval;
unsigned int timeout;
} cisco_proto;
struct if_settings {
unsigned int type;
unsigned int size;
union {
raw_hdlc_proto *raw_hdlc;
cisco_proto *cisco;
fr_proto *fr;
fr_proto_pvc *fr_pvc;
fr_proto_pvc_info *fr_pvc_info;
sync_serial_settings *sync;
te1_settings *te1;
} ifs_ifsu;
};
struct ifreq {
union {
char ifrn_name[IFNAMSIZ];
} ifr_ifrn;
union {
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
struct sockaddr ifru_netmask;
struct sockaddr ifru_hwaddr;
short ifru_flags;
int ifru_ivalue;
int ifru_mtu;
struct ifmap ifru_map;
char ifru_slave[IFNAMSIZ];
char ifru_newname[IFNAMSIZ];
void * ifru_data;
struct if_settings ifru_settings;
} ifr_ifru;
};
struct ifaddrmsg {
uint8_t ifa_family;
uint8_t ifa_prefixlen;
uint8_t ifa_flags;
uint8_t ifa_scope;
uint32_t ifa_index;
};
struct ifa_cacheinfo {
uint32_t ifa_prefered;
uint32_t ifa_valid;
uint32_t cstamp;
uint32_t tstamp;
};
struct rta_cacheinfo {
uint32_t rta_clntref;
uint32_t rta_lastuse;
uint32_t rta_expires;
uint32_t rta_error;
uint32_t rta_used;
uint32_t rta_id;
uint32_t rta_ts;
uint32_t rta_tsage;
};
struct fdb_entry {
uint8_t mac_addr[6];
uint8_t port_no;
uint8_t is_local;
uint32_t ageing_timer_value;
uint8_t port_hi;
uint8_t pad0;
uint16_t unused;
};
struct inotify_event {
int wd;
uint32_t mask;
uint32_t cookie;
uint32_t len;
char name[?];
};
struct linux_dirent64 {
uint64_t d_ino;
int64_t d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name[0];
};
struct flock64 {
short int l_type;
short int l_whence;
off_t l_start;
off_t l_len;
pid_t l_pid;
};
typedef union epoll_data {
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
} epoll_data_t;
struct signalfd_siginfo {
uint32_t ssi_signo;
int32_t ssi_errno;
int32_t ssi_code;
uint32_t ssi_pid;
uint32_t ssi_uid;
int32_t ssi_fd;
uint32_t ssi_tid;
uint32_t ssi_band;
uint32_t ssi_overrun;
uint32_t ssi_trapno;
int32_t ssi_status;
int32_t ssi_int;
uint64_t ssi_ptr;
uint64_t ssi_utime;
uint64_t ssi_stime;
uint64_t ssi_addr;
uint8_t __pad[48];
};
struct io_event {
uint64_t data;
uint64_t obj;
int64_t res;
int64_t res2;
};
struct seccomp_data {
int nr;
uint32_t arch;
uint64_t instruction_pointer;
uint64_t args[6];
};
struct sock_filter {
uint16_t code;
uint8_t jt;
uint8_t jf;
uint32_t k;
};
struct bpf_insn {
uint8_t code; /* opcode */
uint8_t dst_reg:4; /* dest register */
uint8_t src_reg:4; /* source register */
uint16_t off; /* signed offset */
uint32_t imm; /* signed immediate constant */
};
struct sock_fprog {
unsigned short len;
struct sock_filter *filter;
};
union bpf_attr {
struct {
uint32_t map_type;
uint32_t key_size;
uint32_t value_size;
uint32_t max_entries;
};
struct {
uint32_t map_fd;
uint64_t key __attribute__((aligned(8)));
union {
uint64_t value __attribute__((aligned(8)));
uint64_t next_key __attribute__((aligned(8)));
};
uint64_t flags;
};
struct {
uint32_t prog_type;
uint32_t insn_cnt;
uint64_t insns __attribute__((aligned(8)));
uint64_t license __attribute__((aligned(8)));
uint32_t log_level;
uint32_t log_size;
uint64_t log_buf __attribute__((aligned(8)));
uint32_t kern_version;
};
struct {
uint64_t pathname __attribute__((aligned(8)));
uint32_t bpf_fd;
uint32_t file_flags;
};
} __attribute__((aligned(8)));
struct perf_event_attr {
uint32_t pe_type;
uint32_t size;
uint64_t pe_config;
union {
uint64_t sample_period;
uint64_t sample_freq;
};
uint64_t pe_sample_type;
uint64_t read_format;
uint32_t disabled:1,
inherit:1,
pinned:1,
exclusive:1,
exclude_user:1,
exclude_kernel:1,
exclude_hv:1,
exclude_idle:1,
mmap:1,
comm:1,
freq:1,
inherit_stat:1,
enable_on_exec:1,
task:1,
watermark:1,
precise_ip:2,
mmap_data:1,
sample_id_all:1,
exclude_host:1,
exclude_guest:1,
exclude_callchain_kernel:1,
exclude_callchain_user:1,
mmap2:1,
comm_exec:1,
use_clockid:1,
__reserved_1a:6;
uint32_t __reserved_1b;
union {
uint32_t wakeup_events;
uint32_t wakeup_watermark;
};
uint32_t bp_type;
union {
uint64_t bp_addr;
uint64_t config1;
};
union {
uint64_t bp_len;
uint64_t config2;
};
uint64_t branch_sample_type;
uint64_t sample_regs_user;
uint32_t sample_stack_user;
int32_t clockid;
uint64_t sample_regs_intr;
uint32_t aux_watermark;
uint32_t __reserved_2;
};
struct perf_event_mmap_page {
uint32_t version;
uint32_t compat_version;
uint32_t lock;
uint32_t index;
int64_t offset;
uint64_t time_enabled;
uint64_t time_running;
union {
uint64_t capabilities;
struct {
uint32_t cap_bit0 : 1,
cap_bit0_is_deprecated : 1,
cap_user_rdpmc : 1,
cap_user_time : 1,
cap_user_time_zero : 1;
};
};
uint16_t pmc_width;
uint16_t time_shift;
uint32_t time_mult;
uint64_t time_offset;
uint64_t __reserved[120];
volatile uint64_t data_head;
volatile uint64_t data_tail;
volatile uint64_t data_offset;
volatile uint64_t data_size;
uint64_t aux_head;
uint64_t aux_tail;
uint64_t aux_offset;
uint64_t aux_size;
};
struct perf_event_header {
uint32_t type;
uint16_t misc;
uint16_t size;
};
struct mq_attr {
long mq_flags, mq_maxmsg, mq_msgsize, mq_curmsgs, __unused[4];
};
struct termios2 {
tcflag_t c_iflag;
tcflag_t c_oflag;
tcflag_t c_cflag;
tcflag_t c_lflag;
cc_t c_line;
cc_t c_cc[19];
speed_t c_ispeed;
speed_t c_ospeed;
};
struct input_event {
struct timeval time;
uint16_t type;
uint16_t code;
int32_t value;
};
struct input_id {
uint16_t bustype;
uint16_t vendor;
uint16_t product;
uint16_t version;
};
struct input_absinfo {
int32_t value;
int32_t minimum;
int32_t maximum;
int32_t fuzz;
int32_t flat;
int32_t resolution;
};
struct input_keymap_entry {
uint8_t flags;
uint8_t len;
uint16_t index;
uint32_t keycode;
uint8_t scancode[32];
};
struct ff_replay {
uint16_t length;
uint16_t delay;
};
struct ff_trigger {
uint16_t button;
uint16_t interval;
};
struct ff_envelope {
uint16_t attack_length;
uint16_t attack_level;
uint16_t fade_length;
uint16_t fade_level;
};
struct ff_constant_effect {
int16_t level;
struct ff_envelope envelope;
};
struct ff_ramp_effect {
int16_t start_level;
int16_t end_level;
struct ff_envelope envelope;
};
struct ff_condition_effect {
uint16_t right_saturation;
uint16_t left_saturation;
int16_t right_coeff;
int16_t left_coeff;
uint16_t deadband;
int16_t center;
};
struct ff_periodic_effect {
uint16_t waveform;
uint16_t period;
int16_t magnitude;
int16_t offset;
uint16_t phase;
struct ff_envelope envelope;
uint32_t custom_len;
int16_t *custom_data;
};
struct ff_rumble_effect {
uint16_t strong_magnitude;
uint16_t weak_magnitude;
};
struct ff_effect {
uint16_t type;
int16_t id;
uint16_t direction;
struct ff_trigger trigger;
struct ff_replay replay;
union {
struct ff_constant_effect constant;
struct ff_ramp_effect ramp;
struct ff_periodic_effect periodic;
struct ff_condition_effect condition[2];
struct ff_rumble_effect rumble;
} u;
};
typedef struct {
int val[2];
} kernel_fsid_t;
/* we define the underlying structs not the pointer typedefs for capabilities */
struct user_cap_header {
uint32_t version;
int pid;
};
struct user_cap_data {
uint32_t effective;
uint32_t permitted;
uint32_t inheritable;
};
/* this are overall capabilities structs to put metatables on */
struct cap {
uint32_t cap[2];
};
struct capabilities {
uint32_t version;
int pid;
struct cap effective;
struct cap permitted;
struct cap inheritable;
};
struct xt_get_revision {
char name[29];
uint8_t revision;
};
struct vfs_cap_data {
le32 magic_etc;
struct {
le32 permitted; /* Little endian */
le32 inheritable; /* Little endian */
} data[2];
};
typedef struct {
void *ss_sp;
int ss_flags;
size_t ss_size;
} stack_t;
struct sched_param {
int sched_priority;
/* unused after here */
int sched_ss_low_priority;
struct timespec sched_ss_repl_period;
struct timespec sched_ss_init_budget;
int sched_ss_max_repl;
};
struct tun_filter {
uint16_t flags;
uint16_t count;
uint8_t addr[0][6];
};
struct tun_pi {
uint16_t flags;
uint16_t proto; /* __be16 */
};
struct vhost_vring_state {
unsigned int index;
unsigned int num;
};
struct vhost_vring_file {
unsigned int index;
int fd;
};
struct vhost_vring_addr {
unsigned int index;
unsigned int flags;
uint64_t desc_user_addr;
uint64_t used_user_addr;
uint64_t avail_user_addr;
uint64_t log_guest_addr;
};
struct vhost_memory_region {
uint64_t guest_phys_addr;
uint64_t memory_size;
uint64_t userspace_addr;
uint64_t flags_padding;
};
struct vhost_memory {
uint32_t nregions;
uint32_t padding;
struct vhost_memory_region regions[0];
};
struct rusage {
struct timeval ru_utime;
struct timeval ru_stime;
long ru_maxrss;
long ru_ixrss;
long ru_idrss;
long ru_isrss;
long ru_minflt;
long ru_majflt;
long ru_nswap;
long ru_inblock;
long ru_oublock;
long ru_msgsnd;
long ru_msgrcv;
long ru_nsignals;
long ru_nvcsw;
long ru_nivcsw;
};
struct scm_timestamping {
struct timespec ts[3];
};
]]
append(arch.nsig or [[
static const int _NSIG = 64;
]]
)
append(arch.sigset or [[
// again, should be a long
static const int _NSIG_BPW = 32;
typedef struct {
int32_t sig[_NSIG / _NSIG_BPW];
} sigset_t;
]]
)
-- both Glibc and Musl have larger termios at least for some architectures; I believe this is correct for kernel
append(arch.termios or [[
struct termios {
tcflag_t c_iflag;
tcflag_t c_oflag;
tcflag_t c_cflag;
tcflag_t c_lflag;
cc_t c_line;
cc_t c_cc[19];
};
]]
)
-- Linux struct siginfo padding depends on architecture
if abi.abi64 then
append [[
static const int SI_MAX_SIZE = 128;
static const int SI_PAD_SIZE = (SI_MAX_SIZE / sizeof (int)) - 4;
]]
else
append [[
static const int SI_MAX_SIZE = 128;
static const int SI_PAD_SIZE = (SI_MAX_SIZE / sizeof (int)) - 3;
]]
end
append(arch.siginfo or [[
typedef struct siginfo {
int si_signo;
int si_errno;
int si_code;
union {
int _pad[SI_PAD_SIZE];
struct {
pid_t si_pid;
uid_t si_uid;
} kill;
struct {
int si_tid;
int si_overrun;
sigval_t si_sigval;
} timer;
struct {
pid_t si_pid;
uid_t si_uid;
sigval_t si_sigval;
} rt;
struct {
pid_t si_pid;
uid_t si_uid;
int si_status;
clock_t si_utime;
clock_t si_stime;
} sigchld;
struct {
void *si_addr;
} sigfault;
struct {
long int si_band;
int si_fd;
} sigpoll;
} _sifields;
} siginfo_t;
]]
)
-- this is the type used by the rt_sigaction syscall NB have renamed the fields to sa_
append(arch.sigaction or [[
struct k_sigaction {
void (*sa_handler)(int);
unsigned long sa_flags;
void (*sa_restorer)(void);
unsigned sa_mask[2];
};
]]
)
-- these could vary be arch but do not yet
append [[
static const int sigev_preamble_size = sizeof(int) * 2 + sizeof(sigval_t);
static const int sigev_max_size = 64;
static const int sigev_pad_size = (sigev_max_size - sigev_preamble_size) / sizeof(int);
typedef struct sigevent {
sigval_t sigev_value;
int sigev_signo;
int sigev_notify;
union {
int _pad[sigev_pad_size];
int _tid;
struct {
void (*_function)(sigval_t);
void *_attribute;
} _sigev_thread;
} _sigev_un;
} sigevent_t;
]]
append(arch.ucontext) -- there is no default for ucontext and related types as very machine specific
if arch.statfs then append(arch.statfs)
else
-- Linux struct statfs/statfs64 depends on 64/32 bit
if abi.abi64 then
append [[
typedef long statfs_word;
]]
else
append [[
typedef uint32_t statfs_word;
]]
end
append [[
struct statfs64 {
statfs_word f_type;
statfs_word f_bsize;
uint64_t f_blocks;
uint64_t f_bfree;
uint64_t f_bavail;
uint64_t f_files;
uint64_t f_ffree;
kernel_fsid_t f_fsid;
statfs_word f_namelen;
statfs_word f_frsize;
statfs_word f_flags;
statfs_word f_spare[4];
};
]]
end
append(arch.stat)
-- epoll packed on x86_64 only (so same as x86)
append(arch.epoll or [[
struct epoll_event {
uint32_t events;
epoll_data_t data;
};
]]
)
-- endian dependent
if abi.le then
append [[
struct iocb {
uint64_t aio_data;
uint32_t aio_key, aio_reserved1;
uint16_t aio_lio_opcode;
int16_t aio_reqprio;
uint32_t aio_fildes;
uint64_t aio_buf;
uint64_t aio_nbytes;
int64_t aio_offset;
uint64_t aio_reserved2;
uint32_t aio_flags;
uint32_t aio_resfd;
};
]]
else
append [[
struct iocb {
uint64_t aio_data;
uint32_t aio_reserved1, aio_key;
uint16_t aio_lio_opcode;
int16_t aio_reqprio;
uint32_t aio_fildes;
uint64_t aio_buf;
uint64_t aio_nbytes;
int64_t aio_offset;
uint64_t aio_reserved2;
uint32_t aio_flags;
uint32_t aio_resfd;
};
]]
end
-- functions, minimal for Linux as mainly use syscall
append [[
long syscall(int number, ...);
int gettimeofday(struct timeval *tv, void *tz);
int clock_gettime(clockid_t clk_id, struct timespec *tp);
void exit(int status);
]]
ffi.cdef(table.concat(defs, ""))
| apache-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Windurst_Waters/npcs/Olaky-Yayulaky.lua | 13 | 1061 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Olaky-Yayulaky
-- Type: Item Depository
-- @zone: 238
-- @pos -61.247 -4.5 72.551
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x038e);
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 |
aStonedPenguin/fprp | gamemode/modules/fadmin/fadmin/cl_interface/sh_commontimes.lua | 1 | 1745 | /*---------------------------------------------------------------------------
Common times for several punishment actions
---------------------------------------------------------------------------*/
FAdmin.PlayerActions.commonTimes = {}
FAdmin.PlayerActions.commonTimes[0] = "Indefinitely"
FAdmin.PlayerActions.commonTimes[10] = "10 seconds"
FAdmin.PlayerActions.commonTimes[30] = "30 seconds"
FAdmin.PlayerActions.commonTimes[60] = "1 minute"
FAdmin.PlayerActions.commonTimes[300] = "5 minutes"
FAdmin.PlayerActions.commonTimes[600] = "10 minutes"
function FAdmin.PlayerActions.addTimeSubmenu(menu, submenuText, submenuClick, submenuItemClick)
local SubMenu = menu:AddSubMenu(submenuText, submenuClick);
local Padding = vgui.Create("DPanel");
Padding:SetPaintBackgroundEnabled(false);
Padding:SetSize(1,5);
SubMenu:AddPanel(Padding);
local SubMenuTitle = vgui.Create("DLabel");
SubMenuTitle:SetText(" Time:\n");
SubMenuTitle:SetFont("UiBold");
SubMenuTitle:SizeToContents();
SubMenuTitle:SetTextColor(color_black);
SubMenu:AddPanel(SubMenuTitle);
for secs, Time in SortedPairs(FAdmin.PlayerActions.commonTimes) do
SubMenu:AddOption(Time, function() submenuItemClick(secs) end)
end
end
function FAdmin.PlayerActions.addTimeMenu(ItemClick)
local menu = DermaMenu();
local Padding = vgui.Create("DPanel");
Padding:SetPaintBackgroundEnabled(false);
Padding:SetSize(1,5);
menu:AddPanel(Padding);
local Title = vgui.Create("DLabel");
Title:SetText(" Time:\n");
Title:SetFont("UiBold");
Title:SizeToContents();
Title:SetTextColor(color_black);
menu:AddPanel(Title);
for secs, Time in SortedPairs(FAdmin.PlayerActions.commonTimes) do
menu:AddOption(Time, function() ItemClick(secs) end)
end
menu:Open();
end
| mit |
Kosmos82/kosmosdarkstar | scripts/globals/items/balik_sandvici_+1.lua | 18 | 1425 | -----------------------------------------
-- ID: 5591
-- Item: Balik Sandvic +1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Dexterity 3
-- Agility 1
-- Intelligence 3
-- Mind -2
-- Ranged ACC 6
-----------------------------------------
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,5591);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_INT, 3);
target:addMod(MOD_MND, -2);
target:addMod(MOD_RACC, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_INT, 3);
target:delMod(MOD_MND, -2);
target:delMod(MOD_RACC, 6);
end;
| gpl-3.0 |
deweerdt/h2o | deps/brotli/premake5.lua | 14 | 1706 | -- A solution contains projects, and defines the available configurations
solution "brotli"
configurations { "Release", "Debug" }
platforms { "x64", "x86" }
targetdir "bin"
location "buildfiles"
flags "RelativeLinks"
includedirs { "c/include" }
filter "configurations:Release"
optimize "Speed"
flags { "StaticRuntime" }
filter "configurations:Debug"
flags { "Symbols" }
filter { "platforms:x64" }
architecture "x86_64"
filter { "platforms:x86" }
architecture "x86"
configuration { "gmake" }
buildoptions { "-Wall -fno-omit-frame-pointer" }
location "buildfiles/gmake"
configuration { "xcode4" }
location "buildfiles/xcode4"
configuration "linux"
links "m"
configuration { "macosx" }
defines { "OS_MACOSX" }
project "brotlicommon"
kind "SharedLib"
language "C"
files { "c/common/**.h", "c/common/**.c" }
project "brotlicommon_static"
kind "StaticLib"
targetname "brotlicommon"
language "C"
files { "c/common/**.h", "c/common/**.c" }
project "brotlidec"
kind "SharedLib"
language "C"
files { "c/dec/**.h", "c/dec/**.c" }
links "brotlicommon"
project "brotlidec_static"
kind "StaticLib"
targetname "brotlidec"
language "C"
files { "c/dec/**.h", "c/dec/**.c" }
links "brotlicommon_static"
project "brotlienc"
kind "SharedLib"
language "C"
files { "c/enc/**.h", "c/enc/**.c" }
links "brotlicommon"
project "brotlienc_static"
kind "StaticLib"
targetname "brotlienc"
language "C"
files { "c/enc/**.h", "c/enc/**.c" }
links "brotlicommon_static"
project "brotli"
kind "ConsoleApp"
language "C"
linkoptions "-static"
files { "c/tools/brotli.c" }
links { "brotlicommon_static", "brotlidec_static", "brotlienc_static" }
| mit |
Kosmos82/kosmosdarkstar | scripts/zones/RuLude_Gardens/npcs/Albiona.lua | 13 | 1382 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Albiona
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuLude_Gardens/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,0) == false) then
player:startEvent(10089);
else
player:startEvent(0x0092);
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 == 10089) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",0,true);
end
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/The_Eldieme_Necropolis/npcs/qm7.lua | 57 | 2181 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: qm7 (??? - Ancient Papyrus Shreds)
-- Involved in Quest: In Defiant Challenge
-- @pos 105.275 -32 92.551 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(ANCIENT_PAPYRUS_SHRED1);
player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED1);
end
if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1088, 1);
player:messageSpecial(ITEM_OBTAINED, 1088);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088);
end
end
if (player:hasItem(1088)) then
player:delKeyItem(ANCIENT_PAPYRUS_SHRED1);
player:delKeyItem(ANCIENT_PAPYRUS_SHRED2);
player:delKeyItem(ANCIENT_PAPYRUS_SHRED3);
end
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 |
King098/LuaFramework-ToLua-FairyGUI | Assets/LuaFramework/Lua/Logic/Network.lua | 5 | 3627 |
require "Common/define"
require "Common/protocal"
require "Common/functions"
Event = require 'events'
require "3rd/pblua/login_pb"
require "3rd/pbc/protobuf"
local sproto = require "3rd/sproto/sproto"
local core = require "sproto.core"
local print_r = require "3rd/sproto/print_r"
Network = {};
local this = Network;
local transform;
local gameObject;
local islogging = false;
function Network.Start()
logWarn("Network.Start!!");
Event.AddListener(Protocal.Connect, this.OnConnect);
Event.AddListener(Protocal.Message, this.OnMessage);
Event.AddListener(Protocal.Exception, this.OnException);
Event.AddListener(Protocal.Disconnect, this.OnDisconnect);
end
--Socket消息--
function Network.OnSocket(key, data)
Event.Brocast(tostring(key), data);
end
--当连接建立时--
function Network.OnConnect()
logWarn("Game Server connected!!");
end
--异常断线--
function Network.OnException()
islogging = false;
NetManager:SendConnect();
logError("OnException------->>>>");
end
--连接中断,或者被踢掉--
function Network.OnDisconnect()
islogging = false;
logError("OnDisconnect------->>>>");
end
--登录返回--
function Network.OnMessage(buffer)
if TestProtoType == ProtocalType.BINARY then
this.TestLoginBinary(buffer);
end
if TestProtoType == ProtocalType.PB_LUA then
this.TestLoginPblua(buffer);
end
if TestProtoType == ProtocalType.PBC then
this.TestLoginPbc(buffer);
end
if TestProtoType == ProtocalType.SPROTO then
this.TestLoginSproto(buffer);
end
----------------------------------------------------
local ctrl = CtrlManager.GetCtrl(CtrlNames.Message);
if ctrl ~= nil then
ctrl:Awake();
end
logWarn('OnMessage-------->>>');
end
--二进制登录--
function Network.TestLoginBinary(buffer)
local protocal = buffer:ReadByte();
local str = buffer:ReadString();
log('TestLoginBinary: protocal:>'..protocal..' str:>'..str);
end
--PBLUA登录--
function Network.TestLoginPblua(buffer)
local protocal = buffer:ReadByte();
local data = buffer:ReadBuffer();
local msg = login_pb.LoginResponse();
msg:ParseFromString(data);
log('TestLoginPblua: protocal:>'..protocal..' msg:>'..msg.id);
end
--PBC登录--
function Network.TestLoginPbc(buffer)
local protocal = buffer:ReadByte();
local data = buffer:ReadBuffer();
local path = Util.DataPath.."lua/3rd/pbc/addressbook.pb";
local addr = io.open(path, "rb")
local buffer = addr:read "*a"
addr:close()
protobuf.register(buffer)
local decode = protobuf.decode("tutorial.Person" , data)
print(decode.name)
print(decode.id)
for _,v in ipairs(decode.phone) do
print("\t"..v.number, v.type)
end
log('TestLoginPbc: protocal:>'..protocal);
end
--SPROTO登录--
function Network.TestLoginSproto(buffer)
local protocal = buffer:ReadByte();
local code = buffer:ReadBuffer();
local sp = sproto.parse [[
.Person {
name 0 : string
id 1 : integer
email 2 : string
.PhoneNumber {
number 0 : string
type 1 : integer
}
phone 3 : *PhoneNumber
}
.AddressBook {
person 0 : *Person(id)
others 1 : *Person
}
]]
local addr = sp:decode("AddressBook", code)
print_r(addr)
log('TestLoginSproto: protocal:>'..protocal);
end
--卸载网络监听--
function Network.Unload()
Event.RemoveListener(Protocal.Connect);
Event.RemoveListener(Protocal.Message);
Event.RemoveListener(Protocal.Exception);
Event.RemoveListener(Protocal.Disconnect);
logWarn('Unload Network...');
end | mit |
Kosmos82/kosmosdarkstar | scripts/globals/items/plate_of_bream_sushi_+1.lua | 17 | 1478 | -----------------------------------------
-- ID: 5177
-- Item: plate_of_bream_sushi_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Dexterity 6
-- Vitality 5
-- Accuracy % 17
-- Ranged ACC % 17
-- Sleep Resist 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,3600,5177);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 6);
target:addMod(MOD_VIT, 5);
target:addMod(MOD_FOOD_ACCP, 17);
target:addMod(MOD_FOOD_RACCP, 17);
target:addMod(MOD_SLEEPRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 6);
target:delMod(MOD_VIT, 5);
target:delMod(MOD_FOOD_ACCP, 17);
target:delMod(MOD_FOOD_RACCP, 17);
target:delMod(MOD_SLEEPRES, 5);
end;
| gpl-3.0 |
tinymins/MY | MY_!Base/src/lib/InfoCache.lua | 1 | 5231 | --------------------------------------------------------
-- This file is part of the JX3 Plugin Project.
-- @desc : ¼üÖµ¶ÔÎļþ·Ö¸ô¿ìËٴ洢ģ¿é
-- @copyright: Copyright (c) 2009 Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local string, math, table = string, math, table
-- lib apis caching
local X = MY
local UI, GLOBAL, CONSTANT, wstring, lodash = X.UI, X.GLOBAL, X.CONSTANT, X.wstring, X.lodash
-------------------------------------------------------------------------------------------------------
local function DefaultValueComparer(v1, v2)
if v1 == v2 then
return 0
else
return 1
end
end
--[[
Sample:
------------------
-- Get an instance
local IC = X.InfoCache('cache/PLAYER_INFO/{$relserver}/TONG/<SEG>.{$lang}.jx3dat', 2, 3000)
--------------------
-- Setter and Getter
-- Set value
IC['Test'] = 'this is a demo'
-- Get value
print(IC['Test'])
-------------
-- Management
IC('save') -- Save to DB
IC('save', 6000) -- Save to DB with a max unvisited time
IC('save', nil, 5) -- Save to DB with a max saving len
IC('save', nil, nil, true) -- Save to DB and release memory
IC('save', 6000, 5, true) -- Save to DB with a max unvisited time and a max saving len and release memory
IC('clear') -- Delete all data
]]
function X.InfoCache(SZ_DATA_PATH, SEG_LEN, L1_SIZE, ValueComparer)
if not ValueComparer then
ValueComparer = DefaultValueComparer
end
local aCache, tCache = {}, setmetatable({}, { __mode = 'v' }) -- high speed L1 CACHE
local tInfos, tInfoVisit, tInfoModified = {}, {}, {}
return setmetatable({}, {
__index = function(t, k)
-- if hit in L1 CACHE
if tCache[k] then
-- Log('INFO CACHE L1 HIT ' .. k)
return tCache[k]
end
-- read info from saved data
local szSegID = table.concat({string.byte(k, 1, SEG_LEN)}, '-')
if not tInfos[szSegID] then
tInfos[szSegID] = X.LoadLUAData((SZ_DATA_PATH:gsub('<SEG>', szSegID))) or {}
end
tInfoVisit[szSegID] = GetTime()
return tInfos[szSegID][k]
end,
__newindex = function(t, k, v)
local bModified
------------------------------------------------------
-- judge if info has been updated and need to be saved
-- read from L1 CACHE
local tInfo = tCache[k]
local szSegID = table.concat({string.byte(k, 1, SEG_LEN)}, '-')
-- read from DataBase if L1 CACHE not hit
if not tInfo then
if not tInfos[szSegID] then
tInfos[szSegID] = X.LoadLUAData((SZ_DATA_PATH:gsub('<SEG>', szSegID))) or {}
end
tInfo = tInfos[szSegID][k]
tInfoVisit[szSegID] = GetTime()
end
-- judge data
if tInfo then
bModified = ValueComparer(v, tInfo) ~= 0
else
bModified = true
end
------------
-- save info
-- update L1 CACHE
if bModified or not tCache[k] then
if #aCache > L1_SIZE then
table.remove(aCache, 1)
end
table.insert(aCache, v)
tCache[k] = v
end
------------------
-- update DataBase
if bModified then
-- save info to DataBase
if not tInfos[szSegID] then
tInfos[szSegID] = X.LoadLUAData((SZ_DATA_PATH:gsub('<SEG>', szSegID))) or {}
end
tInfos[szSegID][k] = v
tInfoVisit[szSegID] = GetTime()
tInfoModified[szSegID] = GetTime()
end
end,
__call = function(t, cmd, arg0, arg1, ...)
if cmd == 'clear' then
-- clear all data file
tInfos, tInfoVisit, tInfoModified = {}, {}, {}
local aSeg = {}
for i = 1, SEG_LEN do
table.insert(aSeg, 0)
end
while aSeg[SEG_LEN + 1] ~= 1 do
local szSegID = table.concat(aSeg, '-')
local szPath = SZ_DATA_PATH:gsub('<SEG>', szSegID)
if IsFileExist(X.GetLUADataPath(szPath)) then
X.SaveLUAData(szPath, nil)
-- Log('INFO CACHE CLEAR @' .. szSegID)
end
-- bit add one
local i = 1
aSeg[i] = (aSeg[i] or 0) + 1
while aSeg[i] == 256 do
aSeg[i] = 0
i = i + 1
aSeg[i] = (aSeg[i] or 0) + 1
end
end
elseif cmd == 'save' then -- save data to db, if nCount has been set and data saving reach the max, fn will return true
local dwTime = arg0
local nCount = arg1
local bCollect = arg2
-- save info data
for szSegID, dwLastVisitTime in pairs(tInfoVisit) do
if not dwTime or dwTime > dwLastVisitTime then
if nCount then
if nCount == 0 then
return true
end
nCount = nCount - 1
end
if tInfoModified[szSegID] then
X.SaveLUAData((SZ_DATA_PATH:gsub('<SEG>', szSegID)), tInfos[szSegID])
--[[#DEBUG BEGIN]]
else
X.Debug('InfoCache', 'INFO Unloaded: ' .. szSegID, X.DEBUG_LEVEL.LOG)
--[[#DEBUG END]]
end
if bCollect then
tInfos[szSegID] = nil
end
tInfoVisit[szSegID] = nil
tInfoModified[szSegID] = nil
end
end
end
end
})
end
| bsd-3-clause |
cyrilis/luvit-mongodb | src/collection.lua | 1 | 4925 | local Emitter = require('core').Emitter
local Cursor = require("./cursor")
local Collection = Emitter:extend()
function Collection:initialize(db, collectionName)
self.collectionName = collectionName
self.db = db
end
function Collection:find(query, cb)
return Cursor:new(self, query, cb)
end
function Collection:distinct(field, query, cb)
if type(query) == "function" and not cb then
cb = query
query = nil
end
local cmd = {{"_order_", "distinct", self.collectionName}, {"_order_", "key", field} }
if query then
table.insert(cmd, {"_order_", "query", query})
end
self.db:query("$cmd", cmd, nil, nil, 1, function(err, res)
if err then
cb(err, nil)
return
end
if res[1]["errmsg"] or res[1]["err"] then
cb(res[1])
return
end
cb(err, res[1].values)
end, nil)
end
function Collection:drop(cb)
local cmd = {["drop"] = self.collectionName }
self.db:query("$cmd", cmd, nil, nil, 1, function(err, res)
if err then
cb(err, nil)
return
end
if res[1]["errmsg"] or res[1]["err"] then
cb(res[1])
return
end
cb(nil, res[1])
end, nil)
end
function Collection:dropIndex(index, cb)
local collectionName = self.collectionName
local indexes = index
local cmd = {
{ "_order_", "dropIndexes", collectionName },
{ "_order_", "index", indexes}
}
self.db:query("$cmd", cmd, nil, nil, 1, function(err, res)
local result = res[1]
if result.ok == 1 then
cb(err, result)
else
cb(err or result)
end
end, nil)
end
function Collection:dropIndexes(cb)
local collectionName = self.collectionName
local indexes = "*"
local cmd = {
{ "_order_", "dropIndexes", collectionName },
{ "_order_", "index", indexes}
}
self.db:query("$cmd", cmd, nil, nil, 1, function(err, res)
local result = res[1]
if result.ok == 1 then
cb(err, result)
else
cb(err or result)
end
end, nil)
end
function Collection:ensureIndex(index, cb)
self:createIndex(index, cb)
end
function Collection:createIndex(index, options, cb)
local collectionName = self.collectionName
local indexes
local name = ""
if type(options) == "function" then
cb = options
options = {}
end
if type(index) == "string" then
indexes = index
else
if #index > 0 then
for k,v in pairs(index) do
if type(k) == "number" then
k = v[2]
end
name = name .. "_" .. k
end
else
for k,v in pairs(index) do
name = name .. "_" .. k
end
end
local indexElem = { key = index, name = name }
for k, v in pairs(options) do
indexElem[k] = v
end
indexes = {indexElem}
end
local cmd = {
{ "_order_", "createIndexes", collectionName },
{ "_order_", "indexes", indexes}
}
self.db:query("$cmd", cmd, nil, nil, 1, function(err, res)
local result = res[1]
if result.ok == 1 then
cb(err, result)
else
cb(err or result)
end
end, nil)
end
function Collection:getIndex(cb)
local collectionName = self.collectionName
local indexes = "*"
local cmd = {
["listIndexes"] = collectionName
}
self.db:query("$cmd", cmd, nil, nil, 1, function(err, res)
local result = res[1]
if result.ok == 1 then
cb(err, result)
else
cb(err or result)
end
end, nil)
end
function Collection:findAndModify(query, update, cb)
local cursor = Cursor:new(self,query)
return cursor:update(update, cb)
end
function Collection:findOne(query, cb)
assert(cb and type(cb) == "function", "Callback should pass as 2nd param.")
return Cursor:new(self, query):limit(1):exec(function (err, res)
if err then
cb(err)
return false
else
cb(nil, res[1])
end
end)
end
function Collection:insert(doc, cb)
self.db:insert(self.collectionName, doc, nil, cb)
end
function Collection:remove(query, cb)
local cursor = Cursor:new(self, query)
return cursor:remove(cb)
end
function Collection:renameCollection(newName, cb)
local oldCollectionName = self.db.db .. "." ..self.collectionName .. "\0"
local newCollectionName = self.db.db .. "." ..newName .. "\0"
local cmd = {
{"_order_", "renameCollection", oldCollectionName},
{"_order_", "to", newCollectionName }
}
self.db:query("$cmd", cmd, nil, nil, 1, function(err, res)
cb(err, res)
end, nil)
end
return Collection
| mit |
Kosmos82/kosmosdarkstar | scripts/zones/Upper_Jeuno/npcs/Chocobo.lua | 13 | 4964 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Chocobo
-- Finishes Quest: Chocobo's Wounds
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Upper_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
ChocobosWounds = player:getQuestStatus(JEUNO,CHOCOBO_S_WOUNDS);
if (ChocobosWounds == 0) then
player:startEvent(0x003e);
elseif (ChocobosWounds == 1) then
count = trade:getItemCount();
gil = trade:getGil();
if (trade:hasItemQty(4545,1)) then
player:startEvent(0x004c);
elseif (trade:hasItemQty(534,1) and gil == 0 and count == 1) then
--Check feeding status.
feed = player:getVar("ChocobosWounds_Event");
feedMin = player:getVar("ChocobosWounds_Min");
feedReady = (feedMin <= os.time())
if (feed == 1) then
player:startEvent(0x0039);
elseif (feedReady == true) then
if (feed == 2) then
player:startEvent(0x003a);
elseif (feed == 3) then
player:startEvent(0x003b);
elseif (feed == 4) then
player:startEvent(0x003c);
elseif (feed == 5) then
player:startEvent(0x003f);
elseif (feed == 6) then
player:startEvent(0x0040);
end
else
if (feed > 2) then
player:startEvent(0x0049);
end
end
end
else
if (trade:hasItemQty(4545,1)) then
player:startEvent(0x0026);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
ChocobosWounds = player:getQuestStatus(JEUNO,CHOCOBO_S_WOUNDS);
if (ChocobosWounds == QUEST_COMPLETED and player:hasKeyItem(CHOCOBO_LICENSE) == false) then
-- this is a quick hack to let people get their license if it was lost
player:addKeyItem(CHOCOBO_LICENSE);
player:messageSpecial(KEYITEM_OBTAINED, CHOCOBO_LICENSE);
elseif (ChocobosWounds == QUEST_AVAILABLE) then
player:startEvent(0x003e);
elseif (ChocobosWounds == QUEST_ACCEPTED) then
feed = player:getVar("ChocobosWounds_Event");
if (feed == 1) then
player:startEvent(0x0067);
elseif (feed == 2) then
player:startEvent(0x0033);
elseif (feed == 3) then
player:startEvent(0x0034);
elseif (feed == 4) then
player:startEvent(0x003d);
elseif (feed == 5) then
player:startEvent(0x002e);
elseif (feed == 6) then
player:startEvent(0x0037);
end
elseif (ChocobosWounds == 2) then
player:startEvent(0x0037);
else
player:startEvent(0x0036);
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 == 0x0039) then
player:setVar("ChocobosWounds_Event", 2);
player:setVar("ChocobosWounds_Min",os.time() + 60);
elseif (csid == 0x003a) then
player:setVar("ChocobosWounds_Event", 3);
player:setVar("ChocobosWounds_Min",os.time() + 60);
elseif (csid == 0x003b) then
player:setVar("ChocobosWounds_Event", 4);
player:setVar("ChocobosWounds_Min",os.time() + 60);
player:tradeComplete();
player:startEvent(0x0063);
elseif (csid == 0x003c) then
player:setVar("ChocobosWounds_Event", 5);
player:setVar("ChocobosWounds_Min",os.time() + 60);
player:tradeComplete();
elseif (csid == 0x003f) then
player:setVar("ChocobosWounds_Event", 6);
player:setVar("ChocobosWounds_Min",os.time() + 60);
player:tradeComplete();
elseif (csid == 0x0040) then
player:addKeyItem(CHOCOBO_LICENSE);
player:messageSpecial(KEYITEM_OBTAINED, CHOCOBO_LICENSE);
player:addTitle(CHOCOBO_TRAINER);
player:setVar("ChocobosWounds_Event", 0);
player:setVar("ChocobosWounds_Min", 0);
player:addFame(JEUNO,30);
player:tradeComplete();
player:completeQuest(JEUNO,CHOCOBO_S_WOUNDS);
end
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Mamook/npcs/Logging_Point.lua | 13 | 1044 | -----------------------------------
-- Area: Mamook
-- NPC: Logging Point
-----------------------------------
package.loaded["scripts/zones/Mamook/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/logging");
require("scripts/zones/Mamook/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startLogging(player,player:getZoneID(),npc,trade,0x00D7);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fi.lua | 13 | 1076 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Odin's Gate
-- @pos 100 -34 110 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
player:messageSpecial(SOLID_STONE);
end
return 0;
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 |
vim-scripts/rogue.vim | autoload/rogue/curses.lua | 1 | 2917 | local g = Rogue -- alias
g.COLOR = true
g.update_flag = false
g.dungeon = {}
local dungeon_buffer = {}
local dungeon_str_buffer = {}
local last_row_str = {}
local last_print_area = ''
g.descs = {}
g.screen = {}
function g.init_curses()
for i = 0, g.DROWS-1 do
g.dungeon[i] = {}
dungeon_buffer[i] = {}
dungeon_str_buffer[i] = {}
dungeon_str_buffer[i].col = 0
dungeon_str_buffer[i].str = ''
last_row_str[i] = ''
g.descs[i] = ''
g.screen[i] = ''
for j = 0, g.DCOLS-1 do
g.dungeon[i][j] = {}
dungeon_buffer[i][j] = ' '
end
end
end
local function dungeon_row(row)
return table.concat(dungeon_buffer[row], '', 0, g.DCOLS-1)
end
function g.dungeon_buffer_concat()
local t = {}
for i = 0, g.DROWS-1 do
table.insert(t, dungeon_row(i) .. ';')
end
return table.concat(t)
end
function g.dungeon_buffer_restore(str)
local t = g.split(str, ';')
for i, v in ipairs(t) do
for j = 1, #v do
dungeon_buffer[i-1][j-1] = string.char(v:byte(j))
end
end
end
function g.clear()
for i = 0, g.DROWS-1 do
for j = 0, g.DCOLS-1 do
dungeon_buffer[i][j] = ' '
end
g.mvaddstr(i, 0, '')
end
g.refresh()
end
function g.mvinch(row, col)
return dungeon_buffer[row][col]
end
function g.mvaddch(row, col, ch)
dungeon_buffer[row][col] = ch
end
function g.mvaddstr(row, col, str)
dungeon_str_buffer[row].col = col
dungeon_str_buffer[row].str = str
end
function g.refresh()
if vim then
vim.command("normal gg")
end
local update = false
local done_redraw = false
for i = 0, g.DROWS-1 do
local row_str
if dungeon_str_buffer[i].str == '' then
row_str = dungeon_row(i)
else
row_str = dungeon_row(i):sub(1, dungeon_str_buffer[i].col)
end
if vim then
if i == g.DROWS-1 and vim.eval("&lines") == g.DROWS then
row_str = row_str .. dungeon_str_buffer[i].str
if g.update_flag or row_str ~= last_print_area then
vim.command("redraw")
print((vim.eval("has('gui_running')") ~= 0 and '' or ' ') .. row_str)
vim.command("redrawstatus")
last_print_area = row_str
done_redraw = true
end
else
if g.update_flag and i == 0 and vim.eval("&lines") > g.DROWS then
print(' ')
end
if dungeon_str_buffer[i].str ~= '' then
if g.COLOR then
row_str = row_str .. '$$' .. dungeon_str_buffer[i].str
else
row_str = row_str .. dungeon_str_buffer[i].str
row_str = row_str:gsub('%(%w%(', '')
end
end
if g.update_flag or row_str ~= last_row_str[i] then
local cmd_str
cmd_str = 'call setline(' .. tostring(i + 1) .. ', "' .. row_str .. '")'
vim.command(cmd_str)
last_row_str[i] = row_str
update = true
end
end
else
row_str = row_str .. dungeon_str_buffer[i].str
print(row_str)
end
g.screen[i] = row_str:gsub("%$%$", ""):gsub("%(%w%(", ""):gsub('\\\\', '\\')
end
g.update_flag = false
if update and not done_redraw then
vim.command("redraw")
end
end
| mit |
mikroskeem/advanced-sandbox | gamemode/player_extension.lua | 1 | 2595 |
local meta = FindMetaTable( "Player" )
-- Return if there's nothing to add on to
if (!meta) then return end
g_SBoxObjects = {}
function meta:CheckLimit( str )
-- No limits in single player
if (game.SinglePlayer()) then return true end
local c = cvars.Number( "avsbox_max"..str, 0 )
if ( c < 0 ) then return true end
if ( self:GetCount( str ) > c-1 ) then self:LimitHit( str ) return false end
return true
end
function meta:GetCount( str, minus )
if ( CLIENT ) then
return self:GetNetworkedInt( "Count."..str, 0 )
end
minus = minus or 0
if ( !self:IsValid() ) then return end
local key = self:UniqueID()
local tab = g_SBoxObjects[ key ]
if ( !tab || !tab[ str ] ) then
self:SetNetworkedInt( "Count."..str, 0 )
return 0
end
local c = 0
for k, v in pairs ( tab[ str ] ) do
if ( v:IsValid() ) then
c = c + 1
else
tab[ str ][ k ] = nil
end
end
self:SetNetworkedInt( "Count."..str, c - minus )
return c
end
function meta:AddCount( str, ent )
if ( SERVER ) then
local key = self:UniqueID()
g_SBoxObjects[ key ] = g_SBoxObjects[ key ] or {}
g_SBoxObjects[ key ][ str ] = g_SBoxObjects[ key ][ str ] or {}
local tab = g_SBoxObjects[ key ][ str ]
table.insert( tab, ent )
-- Update count (for client)
self:GetCount( str )
ent:CallOnRemove( "GetCountUpdate", function( ent, ply, str ) ply:GetCount(str, 1) end, self, str )
end
end
function meta:LimitHit( str )
self:SendLua( "GAMEMODE:LimitHit( '".. str .."' )" )
end
function meta:AddCleanup( type, ent )
cleanup.Add( self, type, ent )
end
if (SERVER) then
function meta:GetTool( mode )
local wep = self:GetWeapon( "gmod_tool" )
if (!wep || !wep:IsValid()) then return nil end
local tool = wep:GetToolObject( mode )
if (!tool) then return nil end
return tool
end
function meta:SendHint( str, delay )
self.Hints = self.Hints or {}
if (self.Hints[ str ]) then return end
self:SendLua( "GAMEMODE:AddHint( '"..str.."', "..delay.." )" )
self.Hints[ str ] = true
end
function meta:SuppressHint( str )
self.Hints = self.Hints or {}
if (self.Hints[ str ]) then return end
self:SendLua( "GAMEMODE:SuppressHint( '"..str.."' )" )
self.Hints[ str ] = true
end
else
function meta:GetTool( mode )
local wep
for _, ent in pairs( ents.FindByClass( "gmod_tool" ) ) do
if ( ent:GetOwner() == self ) then wep = ent break end
end
if (!wep || !wep:IsValid()) then return nil end
local tool = wep:GetToolObject( mode )
if (!tool) then return nil end
return tool
end
end
| mit |
Igalia/snabb | lib/luajit/testsuite/test/lib/bit.lua | 6 | 2716 | local bit = require"bit"
local byte, ipairs, tostring, pcall = string.byte, ipairs, tostring, pcall
local vb = {
0, 1, -1, 2, -2, 0x12345678, 0x87654321,
0x33333333, 0x77777777, 0x55aa55aa, 0xaa55aa55,
0x7fffffff, 0x80000000, 0xffffffff
}
local function cksum(name, s, r)
local z = 0
for i=1,#s do z = (z + byte(s, i)*i) % 2147483629 end
if z ~= r then
error("bit."..name.." test failed (got "..z..", expected "..r..")", 0)
end
end
local function check_unop(name, r)
local f = bit[name]
local s = ""
if pcall(f) or pcall(f, "z") or pcall(f, true) then
error("bit."..name.." fails to detect argument errors", 0)
end
for _,x in ipairs(vb) do s = s..","..tostring(f(x)) end
cksum(name, s, r)
end
local function check_binop(name, r)
local f = bit[name]
local s = ""
if pcall(f) or pcall(f, "z") or pcall(f, true) then
error("bit."..name.." fails to detect argument errors", 0)
end
for _,x in ipairs(vb) do
for _2,y in ipairs(vb) do s = s..","..tostring(f(x, y)) --[[io.write(_, " ", _2, " ", x, " ", y, " ", f(x, y), "\n")]] end
end
cksum(name, s, r)
end
local function check_binop_range(name, r, yb, ye)
local f = bit[name]
local s = ""
if pcall(f) or pcall(f, "z") or pcall(f, true) or pcall(f, 1, true) then
error("bit."..name.." fails to detect argument errors", 0)
end
for _,x in ipairs(vb) do
for y=yb,ye do s = s..","..tostring(f(x, y)) end
end
cksum(name, s, r)
end
local function check_shift(name, r)
check_binop_range(name, r, 0, 31)
end
do --- Minimal sanity checks.
assert(0x7fffffff == 2147483647, "broken hex literals")
assert(0xffffffff == -1 or 0xffffffff == 2^32-1, "broken hex literals")
assert(tostring(-1) == "-1", "broken tostring()")
assert(tostring(0xffffffff) == "-1" or tostring(0xffffffff) == "4294967295", "broken tostring()")
end
do --- Basic argument processing.
assert(bit.tobit(1) == 1)
assert(bit.band(1) == 1)
assert(bit.bxor(1,2) == 3)
assert(bit.bor(1,2,4,8,16,32,64,128) == 255)
end
do --- unop test vectors
check_unop("tobit", 277312)
check_unop("bnot", 287870)
check_unop("bswap", 307611)
end
do --- binop test vectors
check_binop("band", 41206764)
check_binop("bor", 51253663)
check_binop("bxor", 79322427)
end
do --- shift test vectors
check_shift("lshift", 325260344)
check_shift("rshift", 139061800)
check_shift("arshift", 111364720)
check_shift("rol", 302401155)
check_shift("ror", 302316761)
end
do --- tohex test vectors
check_binop_range("tohex", 47880306, -8, 8)
end
do --- Don't propagate TOBIT narrowing across two conversions.
local tobit = bit.tobit
local k = 0x8000000000003
for i=1,100 do assert(tobit(k % (2^32)) == 3) end
end
| apache-2.0 |
RobberPhex/thrift | test/lua/test_basic_server.lua | 30 | 3451 | -- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you 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.
require('ThriftTest_ThriftTest')
require('TSocket')
require('TBufferedTransport')
require('TFramedTransport')
require('THttpTransport')
require('TCompactProtocol')
require('TJsonProtocol')
require('TBinaryProtocol')
require('TServer')
require('liblualongnumber')
--------------------------------------------------------------------------------
-- Handler
TestHandler = ThriftTestIface:new{}
-- Stops the server
function TestHandler:testVoid()
end
function TestHandler:testString(str)
return str
end
function TestHandler:testBool(bool)
return bool
end
function TestHandler:testByte(byte)
return byte
end
function TestHandler:testI32(i32)
return i32
end
function TestHandler:testI64(i64)
return i64
end
function TestHandler:testDouble(d)
return d
end
function TestHandler:testBinary(by)
return by
end
function TestHandler:testStruct(thing)
return thing
end
--------------------------------------------------------------------------------
-- Test
local server
function teardown()
if server then
server:close()
end
end
function parseArgs(rawArgs)
local opt = {
protocol='binary',
transport='buffered',
port='9090',
}
for i, str in pairs(rawArgs) do
if i > 0 then
k, v = string.match(str, '--(%w+)=(%w+)')
assert(opt[k] ~= nil, 'Unknown argument')
opt[k] = v
end
end
return opt
end
function testBasicServer(rawArgs)
local opt = parseArgs(rawArgs)
-- Handler & Processor
local handler = TestHandler:new{}
assert(handler, 'Failed to create handler')
local processor = ThriftTestProcessor:new{
handler = handler
}
assert(processor, 'Failed to create processor')
-- Server Socket
local socket = TServerSocket:new{
port = opt.port
}
assert(socket, 'Failed to create server socket')
-- Transport & Factory
local transports = {
buffered = TBufferedTransportFactory,
framed = TFramedTransportFactory,
http = THttpTransportFactory,
}
assert(transports[opt.transport], 'Failed to create framed transport factory')
local trans_factory = transports[opt.transport]:new{}
local protocols = {
binary = TBinaryProtocolFactory,
compact = TCompactProtocolFactory,
json = TJSONProtocolFactory,
}
local prot_factory = protocols[opt.protocol]:new{}
assert(prot_factory, 'Failed to create binary protocol factory')
-- Simple Server
server = TSimpleServer:new{
processor = processor,
serverTransport = socket,
transportFactory = trans_factory,
protocolFactory = prot_factory
}
assert(server, 'Failed to create server')
-- Serve
server:serve()
server = nil
end
testBasicServer(arg)
teardown()
| apache-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Northern_San_dOria/npcs/Arnau.lua | 13 | 1785 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Arnau
-- Involved in Mission: Save the Children
-- @pos 148 0 139 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status") == 2) then
player:startEvent(0x0033); --COP event
elseif (player:getCurrentMission(SANDORIA) == SAVE_THE_CHILDREN and player:getVar("MissionStatus") < 2) then
player:startEvent(0x02b5);
elseif (player:hasCompletedMission(SANDORIA,SAVE_THE_CHILDREN) and player:getVar("OptionalCSforSTC") == 1) then
player:startEvent(0x02b6);
else
player:startEvent(0x0014);
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 == 0x0033) then
player:setVar("EMERALD_WATERS_Status",3);
elseif (csid == 0x02b5) then
player:setVar("MissionStatus",2);
elseif (csid == 0x02b6) then
player:setVar("OptionalCSforSTC",0);
end
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Toraimarai_Canal/npcs/qm11.lua | 13 | 1560 | -----------------------------------
-- Area: Toraimarai Canal
-- NPC: ???
-- Involved In Quest: Wild Card
-- @zone 169 // not accurate
-- @pos 220 16 -50 // not accurate
-----------------------------------
package.loaded["scripts/zones/Toraimarai_Canal/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Toraimarai_Canal/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("rootProblem") == 2) then
if (player:getVar("rootProblemQ1") == 2 and player:getVar("rootProblemQ2") == 2) then
player:startEvent(0x30);
end
elseif (player:getVar("rootProblem") == 3) then
player:startEvent(0x37);
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);
if (csid == 0x30 and option ~= 0) then
SpawnMob(17469516,180):updateClaim(player);
end
end;
| gpl-3.0 |
april-org/april-ann | packages/language_model/ngram_lira/test/test_ppl_ngramlira.lua | 3 | 1179 | local check = utest.check
local path = arg[0]:get_path()
local vocab = lexClass.load(io.open(path .. "vocab"))
local model = language_models.load(path .. "dihana3gram.lira.gz",
vocab, "<s>", "</s>")
local unk_id = -1
local result = language_models.test_set_ppl{
lm = model,
vocab = vocab,
testset = path .. "frase",
debug_flag = -1,
use_bcc = true,
use_ecc = true
}
check.lt( math.abs(result.ppl - 17.223860768396), 1e-03 )
check.lt( math.abs(result.ppl1 - 26.996595980386), 1e-03 )
check.lt( math.abs(result.logprob + 27.194871135223), 1e-03 )
check.eq( result.numsentences, 3 )
check.eq( result.numunks, 2 )
check.eq( result.numwords, 19 )
-----------------------------------------------------------------------------
local hist_based_lira_model = ngram.lira.history_based_model{
lira_model = model,
trie_vector = util.trie_vector(18),
init_word_id = vocab:getWordId("<s>"),
}
local result2 = language_models.test_set_ppl{
lm = hist_based_lira_model,
vocab = vocab,
testset = path .. "frase",
debug_flag = -1,
use_bcc = true,
use_ecc = true,
}
for i,v in pairs(result) do check.eq( v, result2[i] ) end
| gpl-3.0 |
wingo/snabbswitch | src/lib/hardware/pci.lua | 4 | 7702 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
local S = require("syscall")
local lib = require("core.lib")
--- ### Hardware device information
devices = {}
--- Array of all supported hardware devices.
---
--- Each entry is a "device info" table with these attributes:
---
--- * `pciaddress` e.g. `"0000:83:00.1"`
--- * `vendor` id hex string e.g. `"0x8086"` for Intel.
--- * `device` id hex string e.g. `"0x10fb"` for 82599 chip.
--- * `interface` name of Linux interface using this device e.g. `"eth0"`.
--- * `status` string Linux operational status, or `nil` if not known.
--- * `driver` Lua module that supports this hardware e.g. `"intel10g"`.
--- * `usable` device was suitable to use when scanned? `yes` or `no`
--- Initialize (or re-initialize) the `devices` table.
function scan_devices ()
for _,device in ipairs(lib.files_in_directory("/sys/bus/pci/devices")) do
local info = device_info(device)
if info.driver then table.insert(devices, info) end
end
end
function device_info (pciaddress)
local info = {}
local p = path(pciaddress)
assert(S.stat(p), ("No such device: %s"):format(pciaddress))
info.pciaddress = canonical(pciaddress)
info.vendor = lib.firstline(p.."/vendor")
info.device = lib.firstline(p.."/device")
info.model = which_model(info.vendor, info.device)
info.driver = which_driver(info.vendor, info.device)
if info.driver then
info.interface = lib.firstfile(p.."/net")
if info.interface then
info.status = lib.firstline(p.."/net/"..info.interface.."/operstate")
end
end
info.usable = lib.yesno(is_usable(info))
return info
end
--- Return the path to the sysfs directory for `pcidev`.
function path(pcidev) return "/sys/bus/pci/devices/"..qualified(pcidev) end
model = {
["82599_SFP"] = 'Intel 82599 SFP',
["82574L"] = 'Intel 82574L',
["82571"] = 'Intel 82571',
["82599_T3"] = 'Intel 82599 T3',
["X540"] = 'Intel X540',
["X520"] = 'Intel X520',
["i350"] = 'Intel 350',
["i210"] = 'Intel 210',
}
-- Supported cards indexed by vendor and device id.
local cards = {
["0x8086"] = {
["0x10fb"] = {model = model["82599_SFP"], driver = 'apps.intel.intel_app'},
["0x10d3"] = {model = model["82574L"], driver = 'apps.intel.intel_app'},
["0x105e"] = {model = model["82571"], driver = 'apps.intel.intel_app'},
["0x151c"] = {model = model["82599_T3"], driver = 'apps.intel.intel_app'},
["0x1528"] = {model = model["X540"], driver = 'apps.intel.intel_app'},
["0x154d"] = {model = model["X520"], driver = 'apps.intel.intel_app'},
["0x1521"] = {model = model["i350"], driver = 'apps.intel.intel1g'},
["0x157b"] = {model = model["i210"], driver = 'apps.intel.intel1g'},
},
["0x1924"] = {
["0x0903"] = {model = 'SFN7122F', driver = 'apps.solarflare.solarflare'}
},
}
-- Return the name of the Lua module that implements support for this device.
function which_driver (vendor, device)
local card = cards[vendor] and cards[vendor][device]
return card and card.driver
end
function which_model (vendor, device)
local card = cards[vendor] and cards[vendor][device]
return card and card.model
end
--- ### Device manipulation.
--- Return true if `device` is safely available for use, or false if
--- the operating systems to be using it.
function is_usable (info)
return info.driver and (info.interface == nil or info.status == 'down')
end
--- Force Linux to release the device with `pciaddress`.
--- The corresponding network interface (e.g. `eth0`) will disappear.
function unbind_device_from_linux (pciaddress)
root_check()
local p = path(pciaddress).."/driver/unbind"
if lib.can_write(p) then
lib.writefile(path(pciaddress).."/driver/unbind", qualified(pciaddress))
end
end
-- ### Access PCI devices using Linux sysfs (`/sys`) filesystem
-- sysfs is an interface towards the Linux kernel based on special
-- files that are implemented as callbacks into the kernel. Here are
-- some background links about sysfs:
-- - High-level: <http://en.wikipedia.org/wiki/Sysfs>
-- - Low-level: <https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt>
-- PCI hardware device registers can be memory-mapped via sysfs for
-- "Memory-Mapped I/O" by device drivers. The trick is to `mmap()` a file
-- such as:
-- /sys/bus/pci/devices/0000:00:04.0/resource0
-- and then read and write that memory to access the device.
-- Memory map PCI device configuration space.
-- Return two values:
-- Pointer for memory-mapped access.
-- File descriptor for the open sysfs resource file.
function map_pci_memory_locked(device,n) return map_pci_memory (device, n, true) end
function map_pci_memory_unlocked(device,n) return map_pci_memory (device, n, false) end
function map_pci_memory (device, n, lock)
assert(lock == true or lock == false, "Explicit lock status required")
root_check()
local filepath = path(device).."/resource"..n
local f,err = S.open(filepath, "rdwr, sync")
assert(f, "failed to open resource " .. filepath .. ": " .. tostring(err))
if lock then
assert(f:flock("ex, nb"), "failed to lock " .. filepath)
end
local st = assert(f:stat())
local mem = assert(f:mmap(nil, st.size, "read, write", "shared", 0))
return ffi.cast("uint32_t *", mem), f
end
function close_pci_resource (fd, base)
local st = assert(fd:stat())
S.munmap(base, st.size)
fd:close()
end
--- Enable or disable PCI bus mastering. DMA only works when bus
--- mastering is enabled.
function set_bus_master (device, enable)
root_check()
local f = assert(S.open(path(device).."/config", "rdwr"))
local fd = f:getfd()
local value = ffi.new("uint16_t[1]")
assert(C.pread(fd, value, 2, 0x4) == 2)
if enable then
value[0] = bit.bor(value[0], lib.bits({Master=2}))
else
value[0] = bit.band(value[0], bit.bnot(lib.bits({Master=2})))
end
assert(C.pwrite(fd, value, 2, 0x4) == 2)
f:close()
end
function root_check ()
lib.root_check("error: must run as root to access PCI devices")
end
-- Return the canonical (abbreviated) representation of the PCI address.
--
-- example: canonical("0000:01:00.0") -> "01:00.0"
function canonical (address)
return address:gsub("^0000:", "")
end
-- Return the fully-qualified representation of a PCI address.
--
-- example: qualified("01:00.0") -> "0000:01:00.0"
function qualified (address)
return address:gsub("^%x%x:%x%x[.]%x+$", "0000:%1")
end
--- ### Selftest
---
--- PCI selftest scans for available devices and performs our driver's
--- self-test on each of them.
function selftest ()
print("selftest: pci")
assert(qualified("0000:01:00.0") == "0000:01:00.0", "qualified 1")
assert(qualified( "01:00.0") == "0000:01:00.0", "qualified 2")
assert(qualified( "0a:00.0") == "0000:0a:00.0", "qualified 3")
assert(qualified( "0A:00.0") == "0000:0A:00.0", "qualified 4")
assert(canonical("0000:01:00.0") == "01:00.0", "canonical 1")
assert(canonical( "01:00.0") == "01:00.0", "canonical 2")
scan_devices()
print_device_summary()
end
function print_device_summary ()
local attrs = {"pciaddress", "model", "interface", "status",
"driver", "usable"}
local fmt = "%-11s %-18s %-10s %-7s %-20s %s"
print(fmt:format(unpack(attrs)))
for _,info in ipairs(devices) do
local values = {}
for _,attr in ipairs(attrs) do
table.insert(values, info[attr] or "-")
end
print(fmt:format(unpack(values)))
end
end
| apache-2.0 |
shahabsaf1/MEGA-SATAN | plugins/media.lua | 297 | 1590 | 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 = "",
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 |
Kosmos82/kosmosdarkstar | scripts/zones/Davoi/npcs/Village_Well.lua | 13 | 1985 | -----------------------------------
-- Area: Davoi
-- NPC: Village Well
-- Involved in Quest: Under Oath
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1095,1) and player:getVar("UnderOathCS") == 5) then
player:startEvent(0x0071);
player:tradeComplete();
else
player:messageSpecial(A_WELL);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("UnderOathCS") == 5 and player:hasKeyItem(STRANGE_SHEET_OF_PAPER) and player:hasItem(1095) == false) then -- Under Oath Quest - PLD AF3
SpawnMob(17387970,180):updateClaim(player); --One-eyed_Gwajboj
SpawnMob(17387971,180):updateClaim(player); --Three-eyed_Prozpuz
elseif (player:getVar("UnderOathCS") == 6 and player:hasKeyItem(KNIGHTS_CONFESSION)) then
player:startEvent(0x0070); --Under Oath -- Reads contents of the letter
else
player:messageSpecial(A_WELL);
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 == 0x0071) then
player:addKeyItem(KNIGHTS_CONFESSION);
player:messageSpecial(KEYITEM_OBTAINED,KNIGHTS_CONFESSION);
player:setVar("UnderOathCS",6);
player:delKeyItem(STRANGE_SHEET_OF_PAPER);
end
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Arrapago_Remnants/instances/arrapago_remnants.lua | 29 | 3716 | -----------------------------------
--
-- Salvage: Arrapago Remnants
--
-----------------------------------
require("scripts/globals/instance")
package.loaded["scripts/zones/Arrapago_Remnants/IDs"] = nil;
local Arrapago = require("scripts/zones/Arrapago_Remnants/IDs");
-----------------------------------
-- afterInstanceRegister
-----------------------------------
function afterInstanceRegister(player)
local instance = player:getInstance();
player:messageSpecial(Arrapago.text.TIME_TO_COMPLETE, instance:getTimeLimit());
player:messageSpecial(Arrapago.text.SALVAGE_START, 1);
player:addStatusEffectEx(EFFECT_ENCUMBRANCE_I, EFFECT_ENCUMBRANCE_I, 0xFFFF, 0, 0)
player:addStatusEffectEx(EFFECT_OBLIVISCENCE, EFFECT_OBLIVISCENCE, 0, 0, 0)
player:addStatusEffectEx(EFFECT_OMERTA, EFFECT_OMERTA, 0, 0, 0)
player:addStatusEffectEx(EFFECT_IMPAIRMENT, EFFECT_IMPAIRMENT, 0, 0, 0)
player:addStatusEffectEx(EFFECT_DEBILITATION, EFFECT_DEBILITATION, 0x1FF, 0, 0)
for i = 0,15 do
player:unequipItem(i)
end
end;
-----------------------------------
-- onInstanceCreated
-----------------------------------
function onInstanceCreated(instance)
for i,v in pairs(Arrapago.npcs[1][1]) do
local npc = instance:getEntity(bit.band(v, 0xFFF), TYPE_NPC);
npc:setStatus(STATUS_NORMAL)
end
instance:setStage(1)
end;
-----------------------------------
-- onInstanceTimeUpdate
-----------------------------------
function onInstanceTimeUpdate(instance, elapsed)
updateInstanceTime(instance, elapsed, Arrapago.text)
end;
-----------------------------------
-- onInstanceFailure
-----------------------------------
function onInstanceFailure(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
v:messageSpecial(Arrapago.text.MISSION_FAILED,10,10);
v:startEvent(0x66);
end
end;
-----------------------------------
-- onInstanceProgressUpdate
-----------------------------------
function onInstanceProgressUpdate(instance, progress)
if instance:getStage() == 1 and progress == 10 then
SpawnMob(Arrapago.mobs[1][2].rampart, instance)
elseif instance:getStage() == 3 and progress == 0 then
SpawnMob(Arrapago.mobs[2].astrologer, instance)
end
end;
-----------------------------------
-- onInstanceComplete
-----------------------------------
function onInstanceComplete(instance)
end;
function onRegionEnter(player,region)
if region:GetRegionID() <= 10 then
player:startEvent(199 + region:GetRegionID())
end
end
function onEventUpdate(entity, eventid, result)
if (eventid >= 200 and eventid <= 203) then
local instance = entity:getInstance()
if instance:getProgress() == 0 then
for id = Arrapago.mobs[2][eventid-199].mobs_start, Arrapago.mobs[2][eventid-199].mobs_end do
SpawnMob(id, instance)
end
instance:setProgress(eventid-199)
end
elseif eventid == 204 then
-- spawn floor 3
end
end
function onEventFinish(entity, eventid, result)
local instance = entity:getInstance()
if (eventid >= 200 and eventid <= 203) then
for id = Arrapago.mobs[1][2].mobs_start, Arrapago.mobs[1][2].mobs_end do
DespawnMob(id, instance)
end
DespawnMob(Arrapago.mobs[1][2].rampart, instance)
DespawnMob(Arrapago.mobs[1][2].sabotender, instance)
elseif eventid == 204 then
for _,v in ipairs(Arrapago.mobs[2]) do
for id = v.mobs_start, v.mobs_end do
DespawnMob(id, instance)
end
end
DespawnMob(Arrapago.mobs[2].astrologer, instance)
end
end
| gpl-3.0 |
aqasaeed/seed2 | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fs.lua | 13 | 2636 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: South Plate
-- @pos 185 -32 -10 195
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local state0 = 8;
local state1 = 9;
local DoorOffset = npc:getID() - 27; -- _5f1
if (npc:getAnimation() == 8) then
state0 = 9;
state1 = 8;
end
-- Gates
-- Shiva's Gate
GetNPCByID(DoorOffset):setAnimation(state0);
GetNPCByID(DoorOffset+1):setAnimation(state0);
GetNPCByID(DoorOffset+2):setAnimation(state0);
GetNPCByID(DoorOffset+3):setAnimation(state0);
GetNPCByID(DoorOffset+4):setAnimation(state0);
-- Odin's Gate
GetNPCByID(DoorOffset+5):setAnimation(state1);
GetNPCByID(DoorOffset+6):setAnimation(state1);
GetNPCByID(DoorOffset+7):setAnimation(state1);
GetNPCByID(DoorOffset+8):setAnimation(state1);
GetNPCByID(DoorOffset+9):setAnimation(state1);
-- Leviathan's Gate
GetNPCByID(DoorOffset+10):setAnimation(state0);
GetNPCByID(DoorOffset+11):setAnimation(state0);
GetNPCByID(DoorOffset+12):setAnimation(state0);
GetNPCByID(DoorOffset+13):setAnimation(state0);
GetNPCByID(DoorOffset+14):setAnimation(state0);
-- Titan's Gate
GetNPCByID(DoorOffset+15):setAnimation(state1);
GetNPCByID(DoorOffset+16):setAnimation(state1);
GetNPCByID(DoorOffset+17):setAnimation(state1);
GetNPCByID(DoorOffset+18):setAnimation(state1);
GetNPCByID(DoorOffset+19):setAnimation(state1);
-- Plates
-- East Plate
GetNPCByID(DoorOffset+20):setAnimation(state0);
GetNPCByID(DoorOffset+21):setAnimation(state0);
-- North Plate
GetNPCByID(DoorOffset+22):setAnimation(state0);
GetNPCByID(DoorOffset+23):setAnimation(state0);
-- West Plate
GetNPCByID(DoorOffset+24):setAnimation(state0);
GetNPCByID(DoorOffset+25):setAnimation(state0);
-- South Plate
GetNPCByID(DoorOffset+26):setAnimation(state0);
GetNPCByID(DoorOffset+27):setAnimation(state0);
return 0;
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 |
Kosmos82/kosmosdarkstar | scripts/zones/Yuhtunga_Jungle/TextIDs.lua | 15 | 1884 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6384; -- Obtained: <item>.
GIL_OBTAINED = 6385; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>.
BEASTMEN_BANNER = 7126; -- There is a beastmen's banner.
FISHING_MESSAGE_OFFSET = 7546; -- You can't fish here.
-- Conquest
CONQUEST = 7213; -- You've earned conquest points!
-- Logging
LOGGING_IS_POSSIBLE_HERE = 7688; -- Logging is possible here if you have
HARVESTING_IS_POSSIBLE_HERE = 7695; -- Harvesting is possible here if you have
-- ZM4 Dialog
CANNOT_REMOVE_FRAG = 7667; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed...
ALREADY_OBTAINED_FRAG = 7668; -- You have already obtained this monument's
ALREADY_HAVE_ALL_FRAGS = 7669; -- You have obtained all of the fragments. You must hurry to the ruins of the ancient shrine!
FOUND_ALL_FRAGS = 7670; -- You now have all 8 fragments of light!
ZILART_MONUMENT = 7671; -- It is an ancient Zilart monument.
-- Rafflesia Scent
FLOWER_BLOOMING = 7647; -- A large flower is blooming.
FOUND_NOTHING_IN_FLOWER = 7650; -- You find nothing inside the flower.
FEEL_DIZZY = 7651; -- You feel slightly dizzy. You must have breathed in too much of the pollen.
-- Other
NOTHING_HAPPENS = 119; -- Nothing happens...
-- conquest Base
CONQUEST_BASE = 7045; -- Tallying conquest results...
-- chocobo digging
DIG_THROW_AWAY = 7559; -- You dig up ?Possible Special Code: 01??Possible Special Code: 01??Possible Special Code: 01? ?Possible Special Code: 01??Possible Special Code: 05?$?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?, but your inventory is full.
FIND_NOTHING = 7561; -- You dig and you dig, but find nothing.
| gpl-3.0 |
phi-gamma/luaotfload | src/luaotfload-database.lua | 2 | 127023 | if not modules then modules = { } end modules ['luaotfload-database'] = {
version = "2.8",
comment = "companion to luaotfload-main.lua",
author = "Khaled Hosny, Elie Roux, Philipp Gesang",
copyright = "Luaotfload Development Team",
license = "GNU GPL v2.0"
}
--[[doc--
With version 2.7 we killed of the Fontforge libraries in favor of
the Lua implementation of the OT format reader. There were many
reasons to do this on top of the fact that FF won’t be around at
version 1.0 anymore: In addition to maintainability, memory safety
and general code hygiene, the new reader shows an amazing
performance: Scanning of the 3200 font files on my system takes
around 23 s now, as opposed to 74 s with the Fontforge libs. Memory
usage has improved drastically as well, as illustrated by these
profiles:
GB
1.324^ #
| #
| ::#
| : #::
| @: #:
| @: #:
| @@@: #:
| @@@ @: #:
| @@ @ @ @: #:
| @ @@:@ @ @: #: :
| @@ : @ :@ @ @: #: :
| @@: ::@@ :@@ ::@ :@ @ @: #: : :::
| @@ : :: @@ :@ : @ :@ @ @: #: : :: :
| @@ : ::: @@ :@ ::: @ :@ @ @: #: :: :: :
| @@@@ :: :::: @@ :@ : : @ :@ @ @: #: :: :::: ::
| :@ @@ :: :::: @@ :@ : :: : @ :@ @ @: #: :: :: :: ::
| @:@ @@ :: ::::: @@ :@ : :::: : @ :@ @ @: #: :::: :::: :: ::
| @@:@ @@ :: ::::::: @@ :@ : : :: : @ :@ @ @: #: ::: @: :: :: ::@
| @@@:@ @@ :: :: ::::: @@ :@ ::: :: : @ :@ @ @: #: ::: @: :: :: ::@
| @@@@@:@ @@ ::::::: ::::: @@ :@ ::: :: : @ :@ @ @: #: ::: ::@: :: :: ::@
0 +----------------------------------------------------------------------->GB
0 16.29
This is the memory usage during a complete database rebuild with
the Fontforge libraries. The same action using the new
``getinfo()`` method gives a different picture:
MB
43.37^ #
| @ @ @#
| @@ @ @ @# :
| @@@ : @: @ @ @# :
| @ @@@ : : @: @ @: :@# :
| @ @ @@@ : : @: @ @: :@# :
| @ : : :@ @@@:::: @::@ @: :@#:: :
| :: : @ : @ : :::@ @ :@@@:::::@::@ @:::@#::::
| : @ : :: : :@:: :@: :::::@ @ :@@@:::::@::@:@:::@#::::
| :: :@ : @ ::@:@:::@:: :@: :::::@: :@ :@@@:::::@::@:@:::@#::::
| :: :@::: :@ ::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
| :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
| :::::@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
| ::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
| :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
| :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
| :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
| :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
| :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
| :::: :@::::@::: :@:::@:@: :@::::@::::::::@:::@::@@@:::::@::@:@:::@#::::
0 +----------------------------------------------------------------------->GB
0 3.231
FF peaks at around 1.4 GB after 12.5 GB worth of allocations,
whereas the Lua implementation arrives at around 45 MB after 3.2 GB
total:
impl time(B) total(B) useful-heap(B) extra-heap(B)
fontforge 12,496,407,184 1,421,150,144 1,327,888,638 93,261,506
lua 3,263,698,960 45,478,640 37,231,892 8,246,748
Much of the inefficiency of Fontforge is a direct consequence of
having to parse the entire font to extract what essentially boils
down to a couple hundred bytes of metadata per font. Since some
information like design sizes (oh, Adobe!) is stuffed away in
Opentype tables, the vastly more efficient approach of
fontloader.info() proves insufficient for indexing. Thus, we ended
up using fontloader.open() which causes even the character tables
to be parsed, which incidentally are responsible for most of the
allocations during that peak of 1.4 GB measured above, along with
the encodings:
20.67% (293,781,048B) 0x6A8F72: SplineCharCreate (splineutil.c:3878)
09.82% (139,570,318B) 0x618ACD: _FontViewBaseCreate (fontviewbase.c:84)
08.77% (124,634,384B) 0x6A8FB3: SplineCharCreate (splineutil.c:3885)
04.53% (64,436,904B) in 80 places, all below massif's threshold (1.00%)
02.68% (38,071,520B) 0x64E14E: addKernPair (parsettfatt.c:493)
01.04% (14,735,320B) 0x64DE7D: addPairPos (parsettfatt.c:452)
39.26% (557,942,484B) 0x64A4E0: PsuedoEncodeUnencoded (parsettf.c:5706)
What gives? For 2.7 we expect a rougher transition than a year back
due to the complete revamp of the OT loading code. Breakage of
fragile aspects like font and style names has been anticipated and
addressed prior to the 2016 pretest release. In contrast to the
earlier approach of letting FF do a complete dump and then harvest
identifiers from the output we now have to coordinate with upstream
as to which fields are actually needed in order to provide a
similarly acceptable name → file lookup. On the bright side, these
things are a lot simpler to fix than the rather tedious work of
having users update their Luatex binary =)
--doc]]--
local lpeg = require "lpeg"
local P, lpegmatch = lpeg.P, lpeg.match
local log = luaotfload.log
local logreport = log and log.report or print -- overriden later on
local report_status = log.names_status
local report_status_start = log.names_status_start
local report_status_stop = log.names_status_stop
--- Luatex builtins
local load = load
local next = next
local require = require
local tonumber = tonumber
local unpack = table.unpack
local fonts = fonts or { }
local fontshandlers = fonts.handlers or { }
local otfhandler = fonts.handlers.otf or { }
fonts.handlers = fontshandlers
local gzipload = gzip.load
local gzipsave = gzip.save
local iolines = io.lines
local ioopen = io.open
local iopopen = io.popen
local kpseexpand_path = kpse.expand_path
local kpsefind_file = kpse.find_file
local kpselookup = kpse.lookup
local kpsereadable_file = kpse.readable_file
local lfsattributes = lfs.attributes
local lfschdir = lfs.chdir
local lfscurrentdir = lfs.currentdir
local lfsdir = lfs.dir
local mathabs = math.abs
local mathmin = math.min
local osgetenv = os.getenv
local osgettimeofday = os.gettimeofday
local osremove = os.remove
local stringfind = string.find
local stringformat = string.format
local stringgmatch = string.gmatch
local stringgsub = string.gsub
local stringlower = string.lower
local stringsub = string.sub
local stringupper = string.upper
local tableconcat = table.concat
local tablesort = table.sort
local utf8gsub = unicode.utf8.gsub
local utf8lower = unicode.utf8.lower
local utf8len = unicode.utf8.len
--- these come from Lualibs/Context
local filebasename = file.basename
local filecollapsepath = file.collapsepath or file.collapse_path
local filedirname = file.dirname
local fileextname = file.extname
local fileiswritable = file.iswritable
local filejoin = file.join
local filenameonly = file.nameonly
local filereplacesuffix = file.replacesuffix
local filesplitpath = file.splitpath or file.split_path
local filesuffix = file.suffix
local getwritablepath = caches.getwritablepath
local lfsisdir = lfs.isdir
local lfsisfile = lfs.isfile
local lfsmkdirs = lfs.mkdirs
local lpegsplitat = lpeg.splitat
local stringis_empty = string.is_empty
local stringsplit = string.split
local stringstrip = string.strip
local tableappend = table.append
local tablecontains = table.contains
local tablecopy = table.copy
local tablefastcopy = table.fastcopy
local tabletofile = table.tofile
local tabletohash = table.tohash
local tableserialize = table.serialize
local names = fonts and fonts.names or { }
local name_index = nil --> upvalue for names.data
local lookup_cache = nil --> for names.lookups
--- string -> (string * string)
local make_luanames = function (path)
return filereplacesuffix(path, "lua"),
filereplacesuffix(path, "luc")
end
local format_precedence = {
"otf", "ttc", "ttf", "afm", "pfb"
}
local location_precedence = {
"local", "system", "texmf",
}
local set_location_precedence = function (precedence)
location_precedence = precedence
end
--[[doc--
Auxiliary functions
--doc]]--
--- fontnames contain all kinds of garbage; as a precaution we
--- lowercase and strip them of non alphanumerical characters
--- string -> string
local invalidchars = "[^%a%d]"
local sanitize_fontname = function (str)
if str ~= nil then
str = utf8gsub (utf8lower (str), invalidchars, "")
return str
end
return nil
end
local sanitize_fontnames = function (rawnames)
local result = { }
for category, namedata in next, rawnames do
if type (namedata) == "string" then
result [category] = utf8gsub (utf8lower (namedata),
invalidchars,
"")
else
local target = { }
for field, name in next, namedata do
target [field] = utf8gsub (utf8lower (name),
invalidchars,
"")
end
result [category] = target
end
end
return result
end
local find_files_indeed
find_files_indeed = function (acc, dirs, filter)
if not next (dirs) then --- done
return acc
end
local pwd = lfscurrentdir ()
local dir = dirs[#dirs]
dirs[#dirs] = nil
if lfschdir (dir) then
lfschdir (pwd)
local newfiles = { }
for ent in lfsdir (dir) do
if ent ~= "." and ent ~= ".." then
local fullpath = dir .. "/" .. ent
if filter (fullpath) == true then
if lfsisdir (fullpath) then
dirs[#dirs+1] = fullpath
elseif lfsisfile (fullpath) then
newfiles[#newfiles+1] = fullpath
end
end
end
end
return find_files_indeed (tableappend (acc, newfiles),
dirs, filter)
end
--- could not cd into, so we skip it
return find_files_indeed (acc, dirs, filter)
end
local dummyfilter = function () return true end
--- the optional filter function receives the full path of a file
--- system entity. a filter applies if the first argument it returns is
--- true.
--- string -> function? -> string list
local find_files = function (root, filter)
if lfsisdir (root) then
return find_files_indeed ({}, { root }, filter or dummyfilter)
end
end
--[[doc--
This is a sketch of the luaotfload db:
type dbobj = {
families : familytable;
files : filemap;
status : filestatus;
mappings : fontentry list;
meta : metadata;
}
and familytable = {
local : (format, familyentry) hash; // specified with include dir
texmf : (format, familyentry) hash;
system : (format, familyentry) hash;
}
and familyentry = {
r : sizes; // regular
i : sizes; // italic
b : sizes; // bold
bi : sizes; // bold italic
}
and sizes = {
default : int; // points into mappings or names
optical : (int, int) list; // design size -> index entry
}
and metadata = {
created : string // creation time
formats : string list; // { "otf", "ttf", "ttc" }
local : bool; (* set if local fonts were added to the db *)
modified : string // modification time
statistics : TODO; // created when built with "--stats"
version : float; // index version
}
and filemap = { // created by generate_filedata()
base : {
local : (string, int) hash; // basename -> idx
system : (string, int) hash;
texmf : (string, int) hash;
};
bare : {
local : (string, (string, int) hash) hash; // location -> (barename -> idx)
system : (string, (string, int) hash) hash;
texmf : (string, (string, int) hash) hash;
};
full : (int, string) hash; // idx -> full path
}
and fontentry = { // finalized by collect_families()
basename : string; // file name without path "foo.otf"
conflicts : { barename : int; basename : int }; // filename conflict with font at index; happens with subfonts
familyname : string; // sanitized name of the font family the font belongs to, usually from the names table
fontname : string; // sanitized name of the font
format : string; // "otf" | "ttf" | "afm" (* | "pfb" *)
fullname : string; // sanitized full name of the font including style modifiers
fullpath : string; // path to font in filesystem
index : int; // index in the mappings table
italicangle : float; // italic angle; non-zero with oblique faces
location : string; // "texmf" | "system" | "local"
metafamily : string; // alternative family identifier if appropriate, sanitized
plainname : string; // unsanitized font name
typographicsubfamily : string; // sanitized preferred subfamily (names table 14)
psname : string; // PostScript name
size : (false | float * float * float); // if available, size info from the size table converted from decipoints
subfamily : string; // sanitized subfamily (names table 2)
subfont : (int | bool); // integer if font is part of a TrueType collection ("ttc")
version : string; // font version string
weight : int; // usWeightClass
}
and filestatus = (string, // fullname
{ index : int list; // pointer into mappings
timestamp : int; }) dict
beware that this is a reconstruction and may be incomplete or out of
date. Last update: 2014-04-06, describing version 2.51.
mtx-fonts has in names.tma:
type names = {
cache_uuid : uuid;
cache_version : float;
datastate : uuid list;
fallbacks : (filetype, (basename, int) hash) hash;
families : (basename, int list) hash;
files : (filename, fullname) hash;
indices : (fullname, int) hash;
mappings : (filetype, (basename, int) hash) hash;
names : ? (empty hash) ?;
rejected : (basename, int) hash;
specifications: fontentry list;
}
and fontentry = {
designsize : int;
familyname : string;
filename : string;
fontname : string;
format : string;
fullname : string;
maxsize : int;
minsize : int;
modification : int;
rawname : string;
style : string;
subfamily : string;
variant : string;
weight : string;
width : string;
}
--doc]]--
--- string list -> string option -> dbobj
local initialize_namedata = function (formats, created)
local now = os.date "%Y-%m-%d %H:%M:%S" --- i. e. "%F %T" on POSIX systems
return {
status = { }, -- was: status; map abspath -> mapping
mappings = { }, -- TODO: check if still necessary after rewrite
files = { }, -- created later
meta = {
created = created or now,
formats = formats,
["local"] = false,
modified = now,
statistics = { },
version = names.version,
},
}
end
--- When loading a lua file we try its binary complement first, which
--- is assumed to be located at an identical path, carrying the suffix
--- .luc.
--- string -> (string * table)
local load_lua_file = function (path)
local foundname = filereplacesuffix (path, "luc")
local code = nil
local fh = ioopen (foundname, "rb") -- try bin first
if fh then
local chunk = fh:read"*all"
fh:close()
code = load (chunk, "b")
end
if not code then --- fall back to text file
foundname = filereplacesuffix (path, "lua")
fh = ioopen(foundname, "rb")
if fh then
local chunk = fh:read"*all"
fh:close()
code = load (chunk, "t")
end
end
if not code then --- probe gzipped file
foundname = filereplacesuffix (path, "lua.gz")
local chunk = gzipload (foundname)
if chunk then
code = load (chunk, "t")
end
end
if not code then return nil, nil end
return foundname, code ()
end
--- define locals in scope
local access_font_index
local find_closest
local flush_lookup_cache
local generate_filedata
local get_font_filter
local group_modifiers
local load_names
local lookup_font_name
local getmetadata
local order_design_sizes
local ot_fullinfo
local read_blacklist
local reload_db
local lookup_fullpath
local save_lookups
local save_names
local set_font_filter
local t1_fullinfo
local update_names
--- state of the database
local fonts_reloaded = false
--- limit output when approximate font matching (luaotfload-tool -F)
local fuzzy_limit = 1 --- display closest only
--- bool? -> -> bool? -> dbobj option
load_names = function (dry_run, no_rebuild)
local starttime = osgettimeofday ()
local foundname, data = load_lua_file (config.luaotfload.paths.index_path_lua)
if data then
logreport ("log", 0, "db",
"Font names database loaded from %s", foundname)
logreport ("term", 3, "db",
"Font names database loaded from %s", foundname)
logreport ("info", 3, "db", "Loading took %0.f ms.",
1000 * (osgettimeofday () - starttime))
local db_version, names_version
if data.meta then
db_version = data.meta.version
else
--- Compatibility branch; the version info used to be
--- stored in the table root which is why updating from
--- an earlier index version broke.
db_version = data.version or -42 --- invalid
end
names_version = names.version
if db_version ~= names_version then
logreport ("both", 0, "db",
[[Version mismatch; expected %d, got %d.]],
names_version, db_version)
if not fonts_reloaded then
logreport ("both", 0, "db", [[Force rebuild.]])
data = update_names (initialize_namedata (get_font_filter ()),
true, false)
if not data then
logreport ("both", 0, "db",
"Database creation unsuccessful.")
end
end
end
else
if no_rebuild == true then
logreport ("both", 2, "db",
[[Database does not exist, skipping rebuild though.]])
return false
end
logreport ("both", 0, "db",
[[Font names database not found, generating new one.]])
logreport ("both", 0, "db",
[[This can take several minutes; please be patient.]])
data = update_names (initialize_namedata (get_font_filter ()),
nil, dry_run)
if not data then
logreport ("both", 0, "db", "Database creation unsuccessful.")
end
end
return data
end
--[[doc--
access_font_index -- Provide a reference of the index table. Will
cause the index to be loaded if not present.
--doc]]--
access_font_index = function ()
if not name_index then name_index = load_names () end
return name_index
end
getmetadata = function ()
if not name_index then
name_index = load_names (false, true)
if name_index then return tablefastcopy (name_index.meta) end
end
return false
end
--- unit -> unit
local load_lookups
load_lookups = function ( )
local foundname, data = load_lua_file(config.luaotfload.paths.lookup_path_lua)
if data then
logreport ("log", 0, "cache", "Lookup cache loaded from %s.", foundname)
logreport ("term", 3, "cache",
"Lookup cache loaded from %s.", foundname)
else
logreport ("both", 1, "cache",
"No lookup cache, creating empty.")
data = { }
end
lookup_cache = data
end
local regular_synonym = {
book = true,
normal = true,
plain = true,
regular = true,
roman = true,
}
local italic_synonym = {
oblique = true,
slanted = true,
italic = true,
}
local bold_synonym = {
bold = true,
black = true,
heavy = true,
}
local style_category = {
regular = "r",
bold = "b",
bolditalic = "bi",
italic = "i",
r = "regular",
b = "bold",
bi = "bolditalic",
i = "italic",
}
local type1_metrics = { "tfm", "ofm", }
local lookup_filename = function (filename)
if not name_index then name_index = load_names () end
local files = name_index.files
local basedata = files.base
local baredata = files.bare
for i = 1, #location_precedence do
local location = location_precedence [i]
local basenames = basedata [location]
local barenames = baredata [location]
local idx
if basenames ~= nil then
idx = basenames [filename]
if idx then
goto done
end
end
if barenames ~= nil then
for j = 1, #format_precedence do
local format = format_precedence [j]
local filemap = barenames [format]
if filemap then
idx = barenames [format] [filename]
if idx then
break
end
end
end
end
::done::
if idx then
return files.full [idx]
end
end
end
--[[doc--
lookup_font_file -- The ``file:`` are ultimately delegated here.
The lookups are kind of a blunt instrument since they try locating
the file using every conceivable method, which is quite
inefficient. Nevertheless, resolving files that way is rarely the
bottleneck.
--doc]]--
local dummy_findfile = resolvers.findfile -- from basics-gen
--- string -> string * string * bool
local lookup_font_file
lookup_font_file = function (filename)
local found = lookup_filename (filename)
if not found then
found = dummy_findfile(filename)
end
if found then
return found, nil, true
end
for i=1, #type1_metrics do
local format = type1_metrics[i]
if resolvers.findfile(filename, format) then
return file.addsuffix(filename, format), format, true
end
end
if not fonts_reloaded and config.luaotfload.db.update_live == true then
return reload_db (stringformat ("File not found: %s.", filename),
lookup_font_file,
filename)
end
return filename, nil, false
end
--[[doc--
get_font_file -- Look up the file of an entry in the mappings
table. If the index is valid, pass on the name and subfont index
after verifing the existence of the resolved file. This
verification differs depending the index entry’s ``location``
field:
* ``texmf`` fonts are verified using the (slow) function
``kpse.lookup()``;
* other locations are tested by resolving the full path and
checking for the presence of a file there.
--doc]]--
--- int -> bool * (string * int) option
local get_font_file = function (index)
local entry = name_index.mappings [index]
if not entry then
return false
end
local basename = entry.basename
if entry.location == "texmf" then
if kpselookup(basename) then
return true, basename, entry.subfont
end
else --- system, local
local fullname = name_index.files.full [index]
if lfsisfile (fullname) then
return true, basename, entry.subfont
end
end
return false
end
--[[doc--
We need to verify if the result of a cached lookup actually exists in
the texmf or filesystem. Again, due to the schizoprenic nature of the
font managment we have to check both the system path and the texmf.
--doc]]--
local verify_font_file = function (basename)
local path = lookup_fullpath (basename)
if path and lfsisfile(path) then
return true
end
if kpsefind_file(basename) then
return true
end
return false
end
--[[doc--
Lookups can be quite costly, more so the less specific they are.
Even if we find a matching font eventually, the next time the
user compiles Eir document E will have to stand through the delay
again.
Thus, some caching of results -- even between runs -- is in order.
We’ll just store successful name: lookups in a separate cache file.
type lookup_cache = (string, (string * num)) dict
The spec is expected to be modified in place (ugh), so we’ll have to
catalogue what fields actually influence its behavior.
Idk what the “spec” resolver is for.
lookup inspects modifies
---------- ----------------- ---------------------------
file: name forced, name
name:[*] name, style, sub, resolved, sub, name, forced
optsize, size
spec: name, sub resolved, sub, name, forced
[*] name: contains both the name resolver from luatex-fonts and
lookup_font_name () below
From my reading of font-def.lua, what a resolver does is
basically rewrite the “name” field of the specification record
with the resolution.
Also, the fields “resolved”, “sub”, “force” etc. influence the outcome.
--doc]]--
local concat_char = "#"
local hash_fields = {
--- order is important
"specification", "style", "sub", "optsize", "size",
}
local n_hash_fields = #hash_fields
--- spec -> string
local hash_request = function (specification)
local key = { } --- segments of the hash
for i=1, n_hash_fields do
local field = specification[hash_fields[i]]
if field then
key[#key+1] = field
end
end
return tableconcat(key, concat_char)
end
--- 'a -> 'a -> table -> (string * int|boolean * boolean)
local lookup_font_name_cached
lookup_font_name_cached = function (specification)
if not lookup_cache then load_lookups () end
local request = hash_request(specification)
logreport ("both", 4, "cache", "Looking for %q in cache ...",
request)
local found = lookup_cache [request]
--- case 1) cache positive ----------------------------------------
if found then --- replay fields from cache hit
logreport ("info", 4, "cache", "Found!")
local basename = found[1]
--- check the presence of the file in case it’s been removed
local success = verify_font_file (basename)
if success == true then
return basename, found[2], true
end
logreport ("both", 4, "cache",
"Cached file not found; resolving again.")
else
logreport ("both", 4, "cache", "Not cached; resolving.")
end
--- case 2) cache negative ----------------------------------------
--- first we resolve normally ...
local filename, subfont = lookup_font_name (specification)
if not filename then
return nil, nil
end
--- ... then we add the fields to the cache ... ...
local entry = { filename, subfont }
logreport ("both", 4, "cache", "New entry: %s.", request)
lookup_cache [request] = entry
--- obviously, the updated cache needs to be stored.
--- TODO this should trigger a save only once the
--- document is compiled (finish_pdffile callback?)
logreport ("both", 5, "cache", "Saving updated cache.")
local success = save_lookups ()
if not success then --- sad, but not critical
logreport ("both", 0, "cache", "Error writing cache.")
end
return filename, subfont
end
--- this used to be inlined; with the lookup cache we don’t
--- have to be parsimonious wrt function calls anymore
--- “found” is the match accumulator
local add_to_match = function (found, size, face)
local continue = true
local optsize = face.size
if optsize and next (optsize) then
local dsnsize, maxsize, minsize
dsnsize = optsize[1]
maxsize = optsize[2]
minsize = optsize[3]
if size ~= nil
and (dsnsize == size or (size > minsize and size <= maxsize))
then
found[1] = face
continue = false ---> break
else
found[#found+1] = face
end
else
found[1] = face
continue = false ---> break
end
return found, continue
end
local choose_closest = function (distances)
local closest = 2^51
local match
for i = 1, #distances do
local d, index = unpack (distances [i])
if d < closest then
closest = d
match = index
end
end
return match
end
--[[doc--
choose_size -- Pick a font face of appropriate size (in sp) from
the list of family members with matching style. There are three
categories:
1. exact matches: if there is a face whose design size equals
the asked size, it is returned immediately and no further
candidates are inspected.
2. range matches: of all faces in whose design range the
requested size falls the one whose center the requested
size is closest to is returned.
3. out-of-range matches: of all other faces (i. e. whose range
is above or below the asked size) the one is chosen whose
boundary (upper or lower) is closest to the requested size.
4. default matches: if no design size or a design size of zero
is requested, the face with the default size is returned.
--doc]]--
--- int * int * int * int list -> int -> int
local choose_size = function (sizes, askedsize)
local mappings = name_index.mappings
local match = sizes.default
local exact
local inrange = { } --- distance * index list
local norange = { } --- distance * index list
local fontname, subfont
if askedsize ~= 0 then
--- firstly, look for an exactly matching design size or
--- matching range
for i = 1, #sizes do
local dsnsize, high, low, index = unpack (sizes [i])
if dsnsize == askedsize then
--- exact match, this is what we were looking for
exact = index
goto skip
elseif askedsize <= low then
--- below range, add to the norange table
local d = low - askedsize
norange [#norange + 1] = { d, index }
elseif askedsize > high then
--- beyond range, add to the norange table
local d = askedsize - high
norange [#norange + 1] = { d, index }
else
--- range match
local d = 0
-- should always be true. Just in case there's some
-- weried fonts out there
if dsnsize > low and dsnsize < high then
d = dsnsize - askedsize
else
d = ((low + high) / 2) - askedsize
end
if d < 0 then
d = -d
end
inrange [#inrange + 1] = { d, index }
end
end
end
::skip::
if exact then
match = exact
elseif #inrange > 0 then
match = choose_closest (inrange)
elseif #norange > 0 then
match = choose_closest (norange)
end
return match
end
--[[doc--
lookup_familyname -- Query the families table for an entry
matching the specification.
The parameters “name” and “style” are pre-sanitized.
--doc]]--
--- spec -> string -> string -> int -> string * int
local lookup_familyname = function (specification, name, style, askedsize)
local families = name_index.families
local mappings = name_index.mappings
local candidates = nil
--- arrow code alert
for i = 1, #location_precedence do
local location = location_precedence [i]
local locgroup = families [location]
for j = 1, #format_precedence do
local format = format_precedence [j]
local fmtgroup = locgroup [format]
if fmtgroup then
local familygroup = fmtgroup [name]
if familygroup then
local stylegroup = familygroup [style]
if stylegroup then --- suitable match
candidates = stylegroup
goto done
end
end
end
end
end
if true then
return nil, nil
end
::done::
index = choose_size (candidates, askedsize)
local success, resolved, subfont = get_font_file (index)
if not success then
return nil, nil
end
logreport ("info", 2, "db", "Match found: %s(%d).",
resolved, subfont or 0)
return resolved, subfont
end
local lookup_fontname = function (specification, name, style)
local mappings = name_index.mappings
local fallback = nil
local lastresort = nil
style = style_category [style]
for i = 1, #mappings do
local face = mappings [i]
local typographicsubfamily = face.typographicsubfamily
local subfamily = face.subfamily
if face.fontname == name
or face.fullname == name
or face.psname == name
then
return face.basename, face.subfont
elseif face.familyname == name then
if typographicsubfamily == style
or subfamily == style
then
fallback = face
elseif regular_synonym [typographicsubfamily]
or regular_synonym [subfamily]
then
lastresort = face
end
elseif face.metafamily == name
and ( regular_synonym [typographicsubfamily]
or regular_synonym [subfamily])
then
lastresort = face
end
end
if fallback then
return fallback.basename, fallback.subfont
end
if lastresort then
return lastresort.basename, lastresort.subfont
end
return nil, nil
end
local design_size_dimension --- scale asked size if not using bp
local set_size_dimension --- called from config
do
--- cf. TeXbook p. 57; the index stores sizes pre-scaled from bp to
--- sp. This allows requesting sizes we got from the TeX end
--- without further conversion. For the other options *pt* and *dd*
--- we scale the requested size as though the value in the font was
--- specified in the requested unit.
--- From @zhouyan:
--- Let P be the asked size in pt, and Aᵤ = CᵤP, where u is the
--- designed unit, pt, bp, or dd, and
---
--- Cpt = 1, Cbp = 7200/7227, Cdd = 1157/1238.
---
--- That is, Aᵤ is the asked size in the desired unit. Let D be the
--- de-sign size (assumed to be in the unit of bp) as reported by
--- the font (divided by 10; in all the following we ignore the
--- factor 2^16 ).
---
--- For simplicity, consider only the case of exact match to the
--- design size. That is, we would like to have Aᵤ = D. Let A′ᵤ = αᵤP
--- and D′ = βD be the scaled values used in comparisons. For the
--- comparison to work correctly, we need,
---
--- Aᵤ = D ⟺ A′ᵤ = D′ ,
---
--- and thus αᵤ = βCᵤ. The fix in PR 400 is the case of β = 1. The
--- fix for review is β = 7227/7200, and the value of αᵤ is thus
--- correct for pt, bp, but not for dd.
local dimens = {
bp = false,
pt = 7227 / 7200,
dd = (7227 / 7200) * (1157 / 1238),
}
design_size_dimension = dimens.bp
set_size_dimension = function (dim)
local conv = dimens [dim]
if conv ~= nil then
logreport ("both", 4, "db",
"Interpreting design sizes as %q, factor %.6f.",
dim, conv)
design_size_dimension = conv
return
end
logreport ("both", 0, "db",
"Invalid dimension %q requested for design sizes; \z
ignoring.")
end
end
--[[doc--
lookup_font_name -- Perform a name: lookup. This first queries the
font families table and, if there is no match for the spec, the
font names table.
The return value is a pair consisting of the file name and the
subfont index if appropriate..
the request specification has the fields:
· features: table
· normal: set of { ccmp clig itlc kern liga locl mark mkmk rlig }
· ???
· forced: string
· lookup: "name"
· method: string
· name: string
· resolved: string
· size: int
· specification: string (== <lookup> ":" <name>)
· sub: string
The “size” field deserves special attention: if its value is
negative, then it actually specifies a scalefactor of the
design size of the requested font. This happens e.g. if a font is
requested without an explicit “at size”. If the font is part of a
larger collection with different design sizes, this complicates
matters a bit: Normally, the resolver prefers fonts that have a
design size as close as possible to the requested size. If no
size specified, then the design size is implied. But which design
size should that be? Xetex appears to pick the “normal” (unmarked)
size: with Adobe fonts this would be the one that is neither
“caption” nor “subhead” nor “display” &c ... For fonts by Adobe this
seems to be the one that does not receive a “typographicsubfamily”
field. (IOW Adobe uses the “typographicsubfamily” field to encode
the design size in more or less human readable format.) However,
this is not true of LM and EB Garamond. As this matters only where
there are multiple design sizes to a given font/style combination,
we put a workaround in place that chooses that unmarked version.
The first return value of “lookup_font_name” is the file name of the
requested font (string). It can be passed to the fullname resolver
get_font_file().
The second value is either “false” or an integer indicating the
subfont index in a TTC.
--doc]]--
--- table -> string * (int | bool)
lookup_font_name = function (specification)
local resolved, subfont
if not name_index then name_index = load_names () end
local name = sanitize_fontname (specification.name)
local style = sanitize_fontname (specification.style) or "r"
local askedsize = specification.optsize
if askedsize then
askedsize = tonumber (askedsize) * 65536
else
askedsize = specification.size
if not askedsize or askedsize < 0 then
askedsize = 0
end
end
if design_size_dimension ~= false then
askedsize = design_size_dimension * askedsize
end
resolved, subfont = lookup_familyname (specification,
name,
style,
askedsize)
if not resolved then
resolved, subfont = lookup_fontname (specification,
name,
style)
end
if not resolved then
if not fonts_reloaded and config.luaotfload.db.update_live == true then
return reload_db (stringformat ("Font %s not found.",
specification.name or "<?>"),
lookup_font_name,
specification)
end
end
return resolved, subfont
end
lookup_fullpath = function (fontname, ext) --- getfilename()
if not name_index then name_index = load_names () end
local files = name_index.files
local basedata = files.base
local baredata = files.bare
for i = 1, #location_precedence do
local location = location_precedence [i]
local basenames = basedata [location]
local idx
if basenames ~= nil then
idx = basenames [fontname]
end
if ext then
local barenames = baredata [location] [ext]
if not idx and barenames ~= nil then
idx = barenames [fontname]
end
end
if idx then
return files.full [idx]
end
end
return ""
end
--- when reload is triggered we update the database
--- and then re-run the caller with the arg list
--- string -> ('a -> 'a) -> 'a list -> 'a
reload_db = function (why, caller, ...)
local namedata = name_index
local formats = tableconcat (namedata.meta.formats, ",")
logreport ("both", 0, "db",
"Reload initiated (formats: %s); reason: %q.",
formats, why)
set_font_filter (formats)
namedata = update_names (namedata, false, false)
if namedata then
fonts_reloaded = true
name_index = namedata
return caller (...)
end
logreport ("both", 0, "db", "Database update unsuccessful.")
end
--- string -> string -> int
local iterative_levenshtein = function (s1, s2)
local costs = { }
local len1, len2 = #s1, #s2
for i = 0, len1 do
local last = i
for j = 0, len2 do
if i == 0 then
costs[j] = j
else
if j > 0 then
local current = costs[j-1]
if stringsub(s1, i, i) ~= stringsub(s2, j, j) then
current = mathmin(current, last, costs[j]) + 1
end
costs[j-1] = last
last = current
end
end
end
if i > 0 then costs[len2] = last end
end
return costs[len2]--- lower right has the distance
end
--- string list -> string list
local delete_dupes = function (lst)
local n0 = #lst
if n0 == 0 then return lst end
tablesort (lst)
local ret = { }
local last
for i = 1, n0 do
local cur = lst[i]
if cur ~= last then
last = cur
ret[#ret + 1] = cur
end
end
logreport (false, 8, "query",
"Removed %d duplicate names.", n0 - #ret)
return ret
end
--- string -> int -> bool
find_closest = function (name, limit)
local name = sanitize_fontname (name)
limit = limit or fuzzy_limit
if not name_index then name_index = load_names () end
if not name_index or type (name_index) ~= "table" then
if not fonts_reloaded then
return reload_db("Font index missing.", find_closest, name)
end
return false
end
local by_distance = { } --- (int, string list) dict
local distances = { } --- int list
local cached = { } --- (string, int) dict
local mappings = name_index.mappings
local n_fonts = #mappings
for n = 1, n_fonts do
local current = mappings[n]
--[[
This is simplistic but surpisingly fast.
Matching is performed against the “fullname” field
of a db record in preprocessed form. We then store the
raw “fullname” at its edit distance.
We should probably do some weighting over all the
font name categories as well as whatever agrep
does.
--]]
local fullname = current.plainname
local sfullname = current.fullname
local dist = cached[sfullname]--- maybe already calculated
if not dist then
dist = iterative_levenshtein(name, sfullname)
cached[sfullname] = dist
end
local namelst = by_distance[dist]
if not namelst then --- first entry
namelst = { fullname }
distances[#distances+1] = dist
else --- append
namelst[#namelst+1] = fullname
end
by_distance[dist] = namelst
end
--- print the matches according to their distance
local n_distances = #distances
if n_distances > 0 then --- got some data
tablesort(distances)
limit = mathmin(n_distances, limit)
logreport (false, 1, "query",
"Displaying %d distance levels.", limit)
for i = 1, limit do
local dist = distances[i]
local namelst = delete_dupes (by_distance[dist])
logreport (false, 0, "query",
"Distance from \"%s\": %s\n "
.. tableconcat (namelst, "\n "),
name, dist)
end
return true
end
return false
end --- find_closest()
--- string -> uint -> bool * (string | rawdata)
local read_font_file = function (filename, subfont)
local fontdata = otfhandler.readers.getinfo (filename,
{ subfont = subfont
, details = false
, platformnames = true
, rawfamilynames = true
})
local msg = fontdata.comment
if msg then
return false, msg
end
return true, fontdata
end
local load_font_file = function (filename, subfont)
local err, ret = read_font_file (filename, subfont)
if err == false then
logreport ("both", 1, "db", "ERROR: failed to open %q: %q.",
tostring (filename), tostring (ret))
return
end
return ret
end
--- Design sizes in the fonts are specified in decipoints. For the
--- index these values are prescaled to sp which is what we’re dealing
--- with at the TeX end.
local get_size_info do --- too many upvalues :/
--- rawdata -> (int * int * int | bool)
local sp = 2^16 -- pt
local bp = 7227 / 7200 -- pt
get_size_info = function (rawinfo)
local design_size = rawinfo.design_size
local design_range_top = rawinfo.design_range_top
local design_range_bottom = rawinfo.design_range_bottom
local fallback_size = design_size ~= 0 and design_size
or design_range_bottom ~= 0 and design_range_bottom
or design_range_top ~= 0 and design_range_top
if fallback_size then
design_size = ((design_size or fallback_size) * sp) / 10
design_range_top = ((design_range_top or fallback_size) * sp) / 10
design_range_bottom = ((design_range_bottom or fallback_size) * sp) / 10
design_size = design_size * bp
design_range_top = design_range_top * bp
design_range_bottom = design_range_bottom * bp
return {
design_size, design_range_top, design_range_bottom,
}
end
return false
end
end ---[local get_size_info]
--[[doc--
map_enlish_names -- Names-table for Lua fontloader objects. This
may vanish eventually once we ditch Fontforge completely. Only
subset of entries of that table are actually relevant so we’ll
stick to that part.
--doc]]--
local get_english_names = function (metadata)
local namesource
local platformnames = metadata.platformnames
--[[--
Hans added the “platformnames” option for us to access parts of
the original name table. The names are unreliable and
completely disorganized, sure, but the Windows variant of the
field often contains the superior information. Case in point:
["platformnames"]={
["macintosh"]={
["compatiblefullname"]="Garamond Premr Pro Smbd It",
["family"]="Garamond Premier Pro",
["fullname"]="Garamond Premier Pro Semibold Italic",
["postscriptname"]="GaramondPremrPro-SmbdIt",
["subfamily"]="Semibold Italic",
},
["windows"]={
["family"]="Garamond Premr Pro Smbd",
["fullname"]="GaramondPremrPro-SmbdIt",
["postscriptname"]="GaramondPremrPro-SmbdIt",
["subfamily"]="Italic",
["typographicfamily"]="Garamond Premier Pro",
["typographicsubfamily"]="Semibold Italic",
},
},
The essential bit is contained as “typographicfamily” (which we
call for historical reasons the “preferred family”) and the
“subfamily”. Only Why this is the case, only Adobe knows for
certain.
--]]--
if platformnames then
--namesource = platformnames.macintosh or platformnames.windows
namesource = platformnames.windows or platformnames.macintosh
end
return namesource or metadata
end
--[[--
In case of broken PS names we set some dummies.
For this reason we copy what is necessary whilst keeping the table
structure the same as in the tfmdata.
--]]--
local get_raw_info = function (metadata, basename)
local fontname = metadata.fontname
local fullname = metadata.fullname
if not fontname or not fullname then
--- Broken names table, e.g. avkv.ttf with UTF-16 strings;
--- we put some dummies in place like the fontloader
--- (font-otf.lua) does.
logreport ("both", 3, "db",
"Invalid names table of font %s, using dummies. \z
Reported: fontname=%q, fullname=%q.",
tostring (basename), tostring (fontname),
tostring (fullname))
fontname = "bad-fontname-" .. basename
fullname = "bad-fullname-" .. basename
end
return {
familyname = metadata.familyname,
fontname = fontname,
fullname = fullname,
italicangle = metadata.italicangle,
names = metadata.names,
units_per_em = metadata.units_per_em,
version = metadata.version,
design_size = metadata.design_size or metadata.designsize,
design_range_top = metadata.design_range_top or metadata.maxsize,
design_range_bottom = metadata.design_range_bottom or metadata.minsize,
}
end
local organize_namedata = function (rawinfo,
nametable,
basename,
info)
local default_name = nametable.compatiblefullname
or nametable.fullname
or nametable.postscriptname
or rawinfo.fullname
or rawinfo.fontname
or info.fullname
or info.fontname
local default_family = nametable.typographicfamily
or nametable.family
or rawinfo.familyname
or info.familyname
-- local default_modifier = nametable.typographicsubfamily
-- or nametable.subfamily
local fontnames = {
--- see
--- https://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html
--- http://www.microsoft.com/typography/OTSPEC/name.htm#NameIDs
english = {
--- where a “compatiblefullname” field is given, the value
--- of “fullname” is either identical or differs by
--- separating the style with a hyphen and omitting spaces.
--- (According to the spec, “compatiblefullname” is
--- “Macintosh only”.) Of the three “fullname” fields, this
--- one appears to be the one with the entire name given in
--- a legible, non-abbreviated fashion, for most fonts at
--- any rate. However, in some fonts (e.g. CMU) all three
--- fields are identical.
fullname = --[[ 18 ]] nametable.compatiblefullname
or --[[ 4 ]] nametable.fullname
or default_name,
--- we keep both the “preferred family” and the “family”
--- values around since both are valid but can turn out
--- quite differently, e.g. with Latin Modern:
--- typographicfamily: “Latin Modern Sans”,
--- family: “LM Sans 10”
family = --[[ 1 ]] nametable.family or default_family,
subfamily = --[[ 2 ]] nametable.subfamily or rawinfo.subfamilyname,
psname = --[[ 6 ]] nametable.postscriptname,
typographicfamily = --[[ 16 ]] nametable.typographicfamily,
typographicsubfamily = --[[ 17 ]] nametable.typographicsubfamily,
},
metadata = {
fullname = rawinfo.fullname,
fontname = rawinfo.fontname,
familyname = rawinfo.familyname,
},
info = {
fullname = info.fullname,
familyname = info.familyname,
fontname = info.fontname,
},
}
return {
sanitized = sanitize_fontnames (fontnames),
fontname = rawinfo.fontname,
fullname = rawinfo.fullname,
familyname = rawinfo.familyname,
}
end
local dashsplitter = lpegsplitat "-"
local split_fontname = function (fontname)
--- sometimes the style hides in the latter part of the
--- fontname, separated by a dash, e.g. “Iwona-Regular”,
--- “GFSSolomos-Regular”
local splitted = { lpegmatch (dashsplitter, fontname) }
if next (splitted) then
return sanitize_fontname (splitted [#splitted])
end
end
local organize_styledata = function (metadata, rawinfo, info)
local pfminfo = metadata.pfminfo
local names = rawinfo.names
return {
--- see http://www.microsoft.com/typography/OTSPEC/features_pt.htm#size
size = get_size_info (rawinfo),
pfmweight = pfminfo and pfminfo.weight or metadata.pfmweight or 400,
weight = rawinfo.weight or metadata.weight or "unspecified",
split = split_fontname (rawinfo.fontname),
width = pfminfo and pfminfo.width or metadata.pfmwidth,
italicangle = metadata.italicangle,
--- this is for querying, see www.ntg.nl/maps/40/07.pdf for details
units_per_em = metadata.units_per_em or metadata.units,
version = metadata.version,
}
end
--[[doc--
The data inside an Opentype font file can be quite heterogeneous.
Thus in order to get the relevant information, parts of the original
table as returned by the font file reader need to be relocated.
--doc]]--
--- string -> int -> bool -> string -> fontentry
ot_fullinfo = function (filename,
subfont,
location,
basename,
format,
info)
local metadata = load_font_file (filename, subfont)
if not metadata then
return nil
end
local rawinfo = get_raw_info (metadata, basename)
local nametable = get_english_names (metadata)
local namedata = organize_namedata (rawinfo,
nametable,
basename,
info)
local style = organize_styledata (metadata,
rawinfo,
info)
local res = {
file = { base = basename,
full = filename,
subfont = subfont,
location = location or "system" },
format = format,
names = namedata,
style = style,
version = rawinfo.version,
}
return res
end
--[[doc--
Type1 font inspector. In comparison with OTF, PFB’s contain a good
deal less name fields which makes it tricky in some parts to find a
meaningful representation for the database.
Good read: http://www.adobe.com/devnet/font/pdfs/5004.AFM_Spec.pdf
--doc]]--
--- string -> int -> bool -> string -> fontentry
t1_fullinfo = function (filename, _subfont, location, basename, format)
local sanitized
local metadata = load_font_file (filename)
local fontname = metadata.fontname
local fullname = metadata.fullname
local familyname = metadata.familyname
local italicangle = metadata.italicangle
local style = ""
local weight
sanitized = sanitize_fontnames ({
fontname = fontname,
psname = fullname,
metafamily = familyname,
familyname = familyname,
weight = metadata.weight, --- string identifier
typographicsubfamily = style,
})
weight = sanitized.weight
if weight == "bold" then
style = weight
end
if italicangle ~= 0 then
style = style .. "italic"
end
return {
basename = basename,
fullpath = filename,
subfont = false,
location = location or "system",
format = format,
fullname = sanitized.fullname,
fontname = sanitized.fontname,
familyname = sanitized.familyname,
plainname = fullname,
psname = sanitized.fontname,
version = metadata.version,
size = false,
typographicsubfamily = style ~= "" and style or weight,
weight = metadata.pfminfo and pfminfo.weight or 400,
italicangle = italicangle,
}
end
local loaders = {
otf = ot_fullinfo,
ttc = ot_fullinfo,
ttf = ot_fullinfo,
afm = t1_fullinfo,
pfb = t1_fullinfo,
}
--- not side-effect free!
local compare_timestamps = function (fullname,
currentstatus,
currententrystatus,
currentmappings,
targetstatus,
targetentrystatus,
targetmappings)
local currenttimestamp = currententrystatus
and currententrystatus.timestamp
local targettimestamp = lfsattributes (fullname, "modification")
if targetentrystatus ~= nil
and targetentrystatus.timestamp == targettimestamp then
logreport ("log", 3, "db", "Font %q already read.", fullname)
return false
end
targetentrystatus.timestamp = targettimestamp
targetentrystatus.index = targetentrystatus.index or { }
if currenttimestamp == targettimestamp
and not targetentrystatus.index [1]
then
--- copy old namedata into new
for _, currentindex in next, currententrystatus.index do
local targetindex = #targetentrystatus.index
local fullinfo = currentmappings [currentindex]
local location = #targetmappings + 1
targetmappings [location] = fullinfo
targetentrystatus.index [targetindex + 1] = location
end
logreport ("log", 3, "db", "Font %q already indexed.", fullname)
return false
end
return true
end
local insert_fullinfo = function (fullname,
basename,
n_font,
loader,
format,
location,
targetmappings,
targetentrystatus,
info)
local fullinfo = loader (fullname, n_font,
location, basename,
format, info)
if not fullinfo then
return false
end
local index = targetentrystatus.index [n_font]
if not index then
index = #targetmappings + 1
end
targetmappings [index] = fullinfo
targetentrystatus.index [n_font] = index
return true
end
--- we return true if the font is new or re-indexed
--- string -> dbobj -> dbobj -> bool
local read_font_names = function (fullname,
currentnames,
targetnames,
location)
local targetmappings = targetnames.mappings
local targetstatus = targetnames.status --- by full path
local targetentrystatus = targetstatus [fullname]
if targetentrystatus == nil then
targetentrystatus = { }
targetstatus [fullname] = targetentrystatus
end
local currentmappings = currentnames.mappings
local currentstatus = currentnames.status
local currententrystatus = currentstatus [fullname]
local basename = filebasename (fullname)
local barename = filenameonly (fullname)
local entryname = fullname
if location == "texmf" then
entryname = basename
end
--- 1) skip if blacklisted
if names.blacklist[fullname] or names.blacklist[basename] then
logreport ("log", 2, "db",
"Ignoring blacklisted font %q.", fullname)
return false
end
--- 2) skip if known with same timestamp
if not compare_timestamps (fullname,
currentstatus,
currententrystatus,
currentmappings,
targetstatus,
targetentrystatus,
targetmappings)
then
return false
end
--- 3) new font; choose a loader, abort if unknown
local format = stringlower (filesuffix (basename))
local loader = loaders [format] --- ot_fullinfo, t1_fullinfo
if not loader then
logreport ("both", 0, "db",
"Unknown format: %q, skipping.", format)
return false
end
--- 4) get basic info, abort if fontloader can’t read it
local err, info = read_font_file (fullname)
if err == false then
logreport ("log", 1, "db",
"Failed to read basic information from %q: %q",
basename, tostring (info))
return false
end
--- 5) check for subfonts and process each of them
if type (info) == "table" and #info >= 1 then --- ttc
local success = false --- true if at least one subfont got read
for n_font = 1, #info do
if insert_fullinfo (fullname, basename, n_font,
loader, format, location,
targetmappings, targetentrystatus,
info)
then
success = true
end
end
return success
end
return insert_fullinfo (fullname, basename, false,
loader, format, location,
targetmappings, targetentrystatus,
info)
end
local path_normalize
do
--- os.type and os.name are constants so we
--- choose a normalization function in advance
--- instead of testing with every call
local os_type, os_name = os.type, os.name
local filecollapsepath = filecollapsepath
local lfsreadlink = lfs.readlink
--- windows and dos
if os_type == "windows" or os_type == "msdos" then
--- ms platfom specific stuff
path_normalize = function (path)
path = stringgsub(path, '\\', '/')
path = stringlower(path)
path = filecollapsepath(path)
return path
end
--[[doc--
The special treatment for cygwin was removed with a patch submitted
by Ken Brown.
Reference: http://cygwin.com/ml/cygwin/2013-05/msg00006.html
--doc]]--
else -- posix
path_normalize = function (path)
local dest = lfsreadlink(path)
if dest then
if kpsereadable_file(dest) then
path = dest
elseif kpsereadable_file(filejoin(filedirname(path), dest)) then
path = filejoin(file.dirname(path), dest)
else
-- broken symlink?
end
end
path = filecollapsepath(path)
return path
end
end
end
local blacklist = { }
local p_blacklist --- prefixes of dirs
--- string list -> string list
local collapse_prefixes = function (lst)
--- avoid redundancies in blacklist
if #lst < 2 then
return lst
end
tablesort(lst)
local cur = lst[1]
local result = { cur }
for i=2, #lst do
local elm = lst[i]
if stringsub(elm, 1, #cur) ~= cur then
--- different prefix
cur = elm
result[#result+1] = cur
end
end
return result
end
--- string list -> string list -> (string, bool) hash_t
local create_blacklist = function (blacklist, whitelist)
local result = { }
local dirs = { }
logreport ("info", 2, "db", "Blacklisting %d files and directories.",
#blacklist)
for i=1, #blacklist do
local entry = blacklist[i]
if lfsisdir(entry) then
dirs[#dirs+1] = entry
else
result[blacklist[i]] = true
end
end
logreport ("info", 2, "db", "Whitelisting %d files.", #whitelist)
for i=1, #whitelist do
result[whitelist[i]] = nil
end
dirs = collapse_prefixes(dirs)
--- build the disjunction of the blacklisted directories
for i=1, #dirs do
local p_dir = P(dirs[i])
if p_blacklist then
p_blacklist = p_blacklist + p_dir
else
p_blacklist = p_dir
end
end
if p_blacklist == nil then
--- always return false
p_blacklist = lpeg.Cc(false)
end
return result
end
--- unit -> unit
read_blacklist = function ()
local files = {
kpselookup ("luaotfload-blacklist.cnf",
{all=true, format="tex"})
}
local blacklist = { }
local whitelist = { }
if files and type(files) == "table" then
for _, path in next, files do
for line in iolines (path) do
line = stringstrip(line) -- to get rid of lines like " % foo"
local first_chr = stringsub(line, 1, 1)
if first_chr == "%" or stringis_empty(line) then
-- comment or empty line
elseif first_chr == "-" then
logreport ("both", 3, "db",
"Whitelisted file %q via %q.",
line, path)
whitelist[#whitelist+1] = stringsub(line, 2, -1)
else
local cmt = stringfind(line, "%%")
if cmt then
line = stringsub(line, 1, cmt - 1)
end
line = stringstrip(line)
logreport ("both", 3, "db",
"Blacklisted file %q via %q.",
line, path)
blacklist[#blacklist+1] = line
end
end
end
end
names.blacklist = create_blacklist(blacklist, whitelist)
end
local p_font_filter
do
local extension_pattern = function (list)
if type (list) ~= "table" or #list == 0 then return P(-1) end
local pat
for i=#list, 1, -1 do
local e = list[i]
if not pat then
pat = P(e)
else
pat = pat + P(e)
end
end
pat = pat * P(-1)
return (1 - pat)^1 * pat
end
--- small helper to adjust the font filter pattern (--formats
--- option)
local current_formats = { }
set_font_filter = function (formats)
if not formats or type (formats) ~= "string" then
return
end
if splitcomma == nil then
splitcomma = luaotfload.parsers and luaotfload.parsers.splitcomma
end
if stringsub (formats, 1, 1) == "+" then -- add
formats = lpegmatch (splitcomma, stringsub (formats, 2))
if formats then
current_formats = tableappend (current_formats, formats)
end
elseif stringsub (formats, 1, 1) == "-" then -- add
formats = lpegmatch (splitcomma, stringsub (formats, 2))
if formats then
local newformats = { }
for i = 1, #current_formats do
local fmt = current_formats[i]
local include = true
for j = 1, #formats do
if current_formats[i] == formats[j] then
include = false
goto skip
end
end
newformats[#newformats+1] = fmt
::skip::
end
current_formats = newformats
end
else -- set
formats = lpegmatch (splitcomma, formats)
if formats then
current_formats = formats
end
end
p_font_filter = extension_pattern (current_formats)
end
get_font_filter = function (formats)
return tablefastcopy (current_formats)
end
end
local locate_matching_pfb = function (afmfile, dir)
local pfbname = filereplacesuffix (afmfile, "pfb")
local pfbpath = dir .. "/" .. pfbname
if lfsisfile (pfbpath) then
return pfbpath
end
--- Check for match in texmf too
return kpsefind_file (pfbname, "type1 fonts")
end
local process_dir_tree
process_dir_tree = function (acc, dirs, done)
if not next (dirs) then --- done
return acc
end
local pwd = lfscurrentdir ()
local dir = dirs[#dirs]
dirs[#dirs] = nil
if not lfschdir (dir) then
--- Cannot cd; skip.
return process_dir_tree (acc, dirs, done)
end
dir = lfscurrentdir () --- resolve symlinks
lfschdir (pwd)
if tablecontains (done, dir) then
--- Already traversed. Note that it’d be unsafe to rely on the
--- hash part above due to Lua only processing up to 32 bytes
--- of string data. The lookup shouldn’t impact performance too
--- much but we could check the performance of alternative data
--- structures at some point.
return process_dir_tree (acc, dirs, done)
end
local newfiles = { }
local blacklist = names.blacklist
for ent in lfsdir (dir) do
--- filter right away
if ent ~= "." and ent ~= ".." and not blacklist[ent] then
local fullpath = dir .. "/" .. ent
if lfsisdir (fullpath)
and not lpegmatch (p_blacklist, fullpath)
then
dirs[#dirs+1] = fullpath
elseif lfsisfile (fullpath) then
ent = stringlower (ent)
if lpegmatch (p_font_filter, ent) then
if filesuffix (ent) == "afm" then
local pfbpath = locate_matching_pfb (ent, dir)
if pfbpath then
newfiles[#newfiles+1] = pfbpath
end
end
newfiles[#newfiles+1] = fullpath
end
end
end
end
done [#done + 1] = dir
return process_dir_tree (tableappend (acc, newfiles), dirs, done)
end
local process_dir = function (dir)
local pwd = lfscurrentdir ()
if lfschdir (dir) then
dir = lfscurrentdir () --- resolve symlinks
lfschdir (pwd)
local files = { }
local blacklist = names.blacklist
for ent in lfsdir (dir) do
if ent ~= "." and ent ~= ".." and not blacklist[ent] then
local fullpath = dir .. "/" .. ent
if lfsisfile (fullpath) then
ent = stringlower (ent)
if lpegmatch (p_font_filter, ent)
then
if filesuffix (ent) == "afm" then
local pfbpath = locate_matching_pfb (ent, dir)
if pfbpath then
files[#files+1] = pfbpath
end
else
files[#files+1] = fullpath
end
end
end
end
end
return files
end
return { }
end
--- string -> bool -> string list
local find_font_files = function (root, recurse)
if lfsisdir (root) then
if recurse == true then
return process_dir_tree ({}, { root }, {})
else --- kpathsea already delivered the necessary subdirs
return process_dir (root)
end
end
end
--- truncate_string -- Cut the first part of a string to fit it
--- into a given terminal width. The parameter “restrict” (int)
--- indicates the number of characters already consumed on the
--- line.
local truncate_string = function (str, restrict)
local tw = config.luaotfload.misc.termwidth
local wd = tw - restrict
local len = utf8len (str)
if wd - len < 0 then
--- combined length exceeds terminal,
str = ".." .. stringsub(str, len - wd + 2)
end
return str
end
--[[doc--
collect_font_filenames_dir -- Traverse the directory root at
``dirname`` looking for font files. Returns a list of {*filename*;
*location*} pairs.
--doc]]--
--- string -> string -> string * string list
local collect_font_filenames_dir = function (dirname, location)
if lpegmatch (p_blacklist, dirname) then
logreport ("both", 4, "db",
"Skipping blacklisted directory %s.", dirname)
--- ignore
return { }
end
local found = find_font_files (dirname, location ~= "texmf" and location ~= "local")
if not found then
logreport ("both", 4, "db",
"No such directory: %q; skipping.", dirname)
return { }
end
local nfound = #found
local files = { }
logreport ("both", 4, "db",
"%d font files detected in %s.",
nfound, dirname)
for j = 1, nfound do
local fullname = found[j]
files[#files + 1] = { path_normalize (fullname), location }
end
return files
end
--- string list -> string list
local filter_out_pwd = function (dirs)
local result = { }
if stripslashes == nil then
stripslashes = luaotfload.parsers and luaotfload.parsers.stripslashes
end
local pwd = path_normalize (lpegmatch (stripslashes,
lfscurrentdir ()))
for i = 1, #dirs do
--- better safe than sorry
local dir = path_normalize (lpegmatch (stripslashes, dirs[i]))
if dir == "." or dir == pwd then
logreport ("both", 3, "db",
"Path “%s” matches $PWD (“%s”), skipping.",
dir, pwd)
else
result[#result+1] = dir
end
end
return result
end
local path_separator = os.type == "windows" and ";" or ":"
--[[doc--
collect_font_filenames_texmf -- Scan texmf tree for font files
relying on the kpathsea variables $OPENTYPEFONTS and $TTFONTS of
texmf.cnf.
The current working directory comes as “.” (texlive) or absolute
path (miktex) and will always be filtered out.
Returns a list of { *filename*; *location* } pairs.
--doc]]--
--- unit -> string * string list
local collect_font_filenames_texmf = function ()
local osfontdir = kpseexpand_path "$OSFONTDIR"
if stringis_empty (osfontdir) then
logreport ("both", 1, "db", "Scanning TEXMF for fonts...")
else
logreport ("both", 1, "db", "Scanning TEXMF and $OSFONTDIR for fonts...")
if log.get_loglevel () > 3 then
local osdirs = filesplitpath (osfontdir)
logreport ("both", 0, "db", "$OSFONTDIR has %d entries:", #osdirs)
for i = 1, #osdirs do
logreport ("both", 0, "db", "[%d] %s", i, osdirs[i])
end
end
end
fontdirs = kpseexpand_path "$OPENTYPEFONTS"
fontdirs = fontdirs .. path_separator .. kpseexpand_path "$TTFONTS"
fontdirs = fontdirs .. path_separator .. kpseexpand_path "$T1FONTS"
fontdirs = fontdirs .. path_separator .. kpseexpand_path "$AFMFONTS"
if stringis_empty (fontdirs) then
return { }
end
local tasks = filter_out_pwd (filesplitpath (fontdirs))
logreport ("both", 3, "db",
"Initiating scan of %d directories.", #tasks)
local files = { }
for _, dir in next, tasks do
files = tableappend (files, collect_font_filenames_dir (dir, "texmf"))
end
logreport ("both", 3, "db", "Collected %d files.", #files)
return files
end
--- unit -> string list
local function get_os_dirs ()
if os.name == 'macosx' then
return {
filejoin(kpseexpand_path('~'), "Library/Fonts"),
"/Library/Fonts",
"/System/Library/Fonts",
"/Network/Library/Fonts",
}
elseif os.type == "windows" or os.type == "msdos" then
local windir = osgetenv("WINDIR")
return { filejoin(windir, 'Fonts') }
else
local fonts_conves = { --- plural, much?
"/usr/local/etc/fonts/fonts.conf",
"/etc/fonts/fonts.conf",
}
if not luaotfload.parsers then
logreport ("log", 0, "db", "Fatal: no fonts.conf parser.")
end
local os_dirs = luaotfload.parsers.read_fonts_conf(fonts_conves, find_files)
return os_dirs
end
return {}
end
--[[doc--
count_removed -- Count paths that do not exist in the file system.
--doc]]--
--- string list -> size_t
local count_removed = function (files)
if not files or not files.full then
logreport ("log", 4, "db", "Empty file store; no data to work with.")
return 0
end
local old = files.full
logreport ("log", 4, "db", "Checking removed files.")
local nrem = 0
local nold = #old
for i = 1, nold do
local f = old[i]
if not kpsereadable_file (f) then
logreport ("log", 2, "db",
"File %s does not exist in file system.")
nrem = nrem + 1
end
end
return nrem
end
--[[doc--
retrieve_namedata -- Scan the list of collected fonts and populate
the list of namedata.
· dirname : name of the directory to scan
· currentnames : current font db object
· targetnames : font db object to fill
· dry_run : don’t touch anything
Returns the number of fonts that were actually added to the index.
--doc]]--
--- string * string list -> dbobj -> dbobj -> bool? -> int * int
local retrieve_namedata = function (files, currentnames, targetnames, dry_run)
local nfiles = #files
local nnew = 0
logreport ("info", 1, "db", "Scanning %d collected font files ...", nfiles)
local bylocation = { texmf = { 0, 0 }
, ["local"] = { 0, 0 }
, system = { 0, 0 }
}
report_status_start (2, 4)
for i = 1, nfiles do
local fullname, location = unpack (files[i])
local count = bylocation[location]
count[1] = count[1] + 1
if dry_run == true then
local truncated = truncate_string (fullname, 43)
logreport ("log", 2, "db", "Would have been loading %s.", fullname)
report_status ("term", "db", "Would have been loading %s", truncated)
--- skip the read_font_names part
else
local truncated = truncate_string (fullname, 32)
logreport ("log", 2, "db", "Loading font %s.", fullname)
report_status ("term", "db", "Loading font %s", truncated)
local new = read_font_names (fullname, currentnames,
targetnames, location)
if new == true then
nnew = nnew + 1
count[2] = count[2] + 1
end
end
end
report_status_stop ("term", "db", "Scanned %d files, %d new.", nfiles, nnew)
for location, count in next, bylocation do
logreport ("term", 4, "db", " * %s: %d files, %d new",
location, count[1], count[2])
end
return nnew
end
--- unit -> string * string list
local collect_font_filenames_system = function ()
local n_scanned, n_new = 0, 0
logreport ("info", 1, "db", "Scanning system fonts...")
logreport ("info", 2, "db",
"Searching in static system directories...")
local files = { }
for _, dir in next, get_os_dirs () do
tableappend (files, collect_font_filenames_dir (dir, "system"))
end
logreport ("term", 3, "db", "Collected %d files.", #files)
return files
end
--- unit -> bool
flush_lookup_cache = function ()
lookup_cache = { }
collectgarbage "collect"
return true
end
--[[doc--
collect_font_filenames_local -- Scan $PWD (during a TeX run)
for font files.
Side effect: This sets the “local” flag in the subtable “meta” to
prevent the merged table from being saved to disk.
TODO the local tree could be cached in $PWD.
--doc]]--
--- unit -> string * string list
local collect_font_filenames_local = function ()
local pwd = lfscurrentdir ()
logreport ("both", 1, "db", "Scanning for fonts in $PWD (%q) ...", pwd)
local files = collect_font_filenames_dir (pwd, "local")
local nfiles = #files
if nfiles > 0 then
targetnames.meta["local"] = true --- prevent saving to disk
logreport ("term", 1, "db", "Found %d files.", pwd)
else
logreport ("term", 1, "db",
"Couldn’t find a thing here. What a waste.", pwd)
end
logreport ("term", 3, "db", "Collected %d files.", #files)
return files
end
--- fontentry list -> filemap
generate_filedata = function (mappings)
logreport ("both", 2, "db", "Creating filename map.")
local nmappings = #mappings
local files = {
bare = {
["local"] = { },
system = { }, --- mapped to mapping format -> index in full
texmf = { }, --- mapped to mapping format -> “true”
},
base = {
["local"] = { },
system = { }, --- mapped to index in “full”
texmf = { }, --- set; all values are “true”
},
full = { }, --- non-texmf
}
local base = files.base
local bare = files.bare
local full = files.full
local conflicts = {
basenames = 0,
barenames = 0,
}
for index = 1, nmappings do
local entry = mappings [index]
local filedata = entry.file
local format
local location
local fullpath
local basename
local barename
local subfont
if filedata then --- new entry
format = entry.format --- otf, afm, ...
location = filedata.location --- texmf, system, ...
fullpath = filedata.full
basename = filedata.base
barename = filenameonly (fullpath)
subfont = filedata.subfont
else
format = entry.format --- otf, afm, ...
location = entry.location --- texmf, system, ...
fullpath = entry.fullpath
basename = entry.basename
barename = filenameonly (fullpath)
subfont = entry.subfont
end
entry.index = index
--- 1) add to basename table
local inbase = base [location] --- no format since the suffix is known
if inbase then
local present = inbase [basename]
if present then
logreport ("both", 4, "db",
"Conflicting basename: %q already indexed \z
in category %s, ignoring.",
barename, location)
conflicts.basenames = conflicts.basenames + 1
--- track conflicts per font
local conflictdata = entry.conflicts
if not conflictdata then
entry.conflicts = { basename = present }
else -- some conflicts already detected
conflictdata.basename = present
end
else
inbase [basename] = index
end
else
inbase = { basename = index }
base [location] = inbase
end
--- 2) add to barename table
local inbare = bare [location] [format]
if inbare then
local present = inbare [barename]
if present then
logreport ("both", 4, "db",
"Conflicting barename: %q already indexed \z
in category %s/%s, ignoring.",
barename, location, format)
conflicts.barenames = conflicts.barenames + 1
--- track conflicts per font
local conflictdata = entry.conflicts
if not conflictdata then
entry.conflicts = { barename = present }
else -- some conflicts already detected
conflictdata.barename = present
end
else
inbare [barename] = index
end
else
inbare = { [barename] = index }
bare [location] [format] = inbare
end
--- 3) add to fullpath map
full [index] = fullpath
end --- mapping traversal
return files
end
local bold_spectrum_low = 501 --- 500 is medium, 900 heavy/black
local normal_weight = 400
local bold_weight = 700
local normal_width = 5
local pick_style
local pick_fallback_style
local check_regular
do
local choose_exact = function (field)
--- only clean matches, without guessing
if italic_synonym [field] then
return "i"
end
if stringsub (field, 1, 10) == "bolditalic"
or stringsub (field, 1, 11) == "boldoblique" then
return "bi"
end
if stringsub (field, 1, 4) == "bold" then
return "b"
end
if stringsub (field, 1, 6) == "italic" then
return "i"
end
return false
end
pick_style = function (typographicsubfamily, subfamily)
local style
if typographicsubfamily then
style = choose_exact (typographicsubfamily)
if style then return style end
elseif subfamily then
style = choose_exact (subfamily)
if style then return style end
end
return false
end
pick_fallback_style = function (italicangle, pfmweight, width)
--[[--
More aggressive, but only to determine bold faces.
Note: Before you make this test more inclusive, ensure
no fonts are matched in the bold synonym spectrum over
a literally “bold[italic]” one. In the past, heuristics
been tried but ultimately caused unwanted modifiers
polluting the lookup table. What doesn’t work is, e. g.
treating weights > 500 as bold or allowing synonyms like
“heavy”, “black”.
--]]--
if width == normal_width then
if pfmweight == bold_weight then
--- bold spectrum matches
if italicangle == 0 then
return "b"
end
return "bi"
elseif pfmweight == normal_weight then
if italicangle ~= 0 then
return "i"
end
end
end
return false
end
--- we use only exact matches here since there are constructs
--- like “regularitalic” (Cabin, Bodoni Old Fashion)
check_regular = function (typographicsubfamily,
subfamily,
italicangle,
weight,
width,
pfmweight)
local plausible_weight = false
--[[--
This filters out undesirable candidates that specify their
typographicsubfamily or subfamily as “regular” but are actually of
“semibold” or other weight—another drawback of the
oversimplifying classification into only three styles (r, i,
b, bi).
--]]--
if italicangle == 0 then
if pfmweight == 400 then
--[[--
Some fonts like Dejavu advertise an undistinguished
regular and a “condensed” version with the same
weight whilst also providing the style info in the
typographic subfamily instead of the subfamily (i. e.
the converse of what Adobe’s doing). The only way to
weed out the undesired pseudo-regular shape is to
peek at its advertised width (4 vs. 5).
--]]--
if width then
plausible_weight = width == normal_width
else
plausible_weight = true
end
elseif weight and regular_synonym [weight] then
plausible_weight = true
end
end
if plausible_weight then
if subfamily then
if regular_synonym [subfamily] then return "r" end
elseif typographicsubfamily then
if regular_synonym [typographicsubfamily] then return "r" end
end
end
return false
end
end
local pull_values = function (entry)
local file = entry.file
local names = entry.names
local style = entry.style
local sanitized = names.sanitized
local english = sanitized.english
local info = sanitized.info
local metadata = sanitized.metadata
--- pull file info ...
entry.basename = file.base
entry.fullpath = file.full
entry.location = file.location
entry.subfont = file.subfont
--- pull name info ...
entry.psname = english.psname
entry.fontname = info.fontname or metadata.fontname
entry.fullname = english.fullname or info.fullname
entry.typographicsubfamily = english.typographicsubfamily
entry.familyname = metadata.familyname or english.typographicfamily or english.family
entry.plainname = names.fullname
entry.subfamily = english.subfamily
--- pull style info ...
entry.italicangle = style.italicangle
entry.size = style.size
entry.weight = style.weight
entry.width = style.width
entry.pfmweight = style.pfmweight
if config.luaotfload.db.strip == true then
entry.file = nil
entry.names = nil
entry.style = nil
end
end
local add_family = function (name, subtable, modifier, entry)
if not name then --- probably borked font
return
end
local familytable = subtable [name]
if not familytable then
familytable = { }
subtable [name] = familytable
end
familytable [#familytable + 1] = {
index = entry.index,
modifier = modifier,
}
end
local get_subtable = function (families, entry)
local location = entry.location
local format = entry.format
local subtable = families [location] [format]
if not subtable then
subtable = { }
families [location] [format] = subtable
end
return subtable
end
local collect_families = function (mappings)
logreport ("info", 2, "db", "Analyzing families.")
local families = {
["local"] = { },
system = { },
texmf = { },
}
for i = 1, #mappings do
local entry = mappings [i]
if entry.file then
pull_values (entry)
end
local subtable = get_subtable (families, entry)
local familyname = entry.familyname
local typographicsubfamily = entry.typographicsubfamily
local subfamily = entry.subfamily
local weight = entry.weight
local width = entry.width
local pfmweight = entry.pfmweight
local italicangle = entry.italicangle
local modifier = pick_style (typographicsubfamily, subfamily)
if not modifier then --- regular, exact only
modifier = check_regular (typographicsubfamily,
subfamily,
italicangle,
weight,
width,
pfmweight)
end
if not modifier then
modifier = pick_fallback_style (italicangle, pfmweight, width)
end
if modifier then
add_family (familyname, subtable, modifier, entry)
end
end
collectgarbage "collect"
return families
end
--[[doc--
group_modifiers -- For not-quite-bold faces, determine whether
they can fill in for a missing bold face slot in a matching family.
Some families like Lucida do not contain real bold / bold italic
members. Instead, they have semibold variants at weight 600 which
we must add in a separate pass.
--doc]]--
local style_categories = { "r", "b", "i", "bi" }
local bold_categories = { "b", "bi" }
group_modifiers = function (mappings, families)
logreport ("info", 2, "db", "Analyzing shapes, weights, and styles.")
for location, location_data in next, families do
for format, format_data in next, location_data do
for familyname, collected in next, format_data do
local styledata = { } --- will replace the “collected” table
--- First, fill in the ordinary style data that
--- fits neatly into the four relevant modifier
--- categories.
for _, modifier in next, style_categories do
local entries
for key, info in next, collected do
if info.modifier == modifier then
if not entries then
entries = { }
end
local index = info.index
local entry = mappings [index]
local size = entry.size
if size then
entries [#entries + 1] = {
size [1],
size [2],
size [3],
index,
}
else
entries.default = index
end
collected [key] = nil
end
styledata [modifier] = entries
end
end
--- At this point the family set may still lack
--- entries for bold or bold italic. We will fill
--- those in using the modifier with the numeric
--- weight that is closest to bold (700).
if next (collected) then --- there are uncategorized entries
for _, modifier in next, bold_categories do
if not styledata [modifier] then
local closest
local minimum = 2^51
for key, info in next, collected do
local info_modifier = tonumber (info.modifier) and "b" or "bi"
if modifier == info_modifier then
local index = info.index
local entry = mappings [index]
local weight = entry.pfmweight
local diff = weight < 700 and 700 - weight or weight - 700
if diff < minimum then
minimum = diff
closest = weight
end
end
end
if closest then
--- We know there is a substitute face for the modifier.
--- Now we scan the list again to extract the size data
--- in case the shape is available at multiple sizes.
local entries = { }
for key, info in next, collected do
local info_modifier = tonumber (info.modifier) and "b" or "bi"
if modifier == info_modifier then
local index = info.index
local entry = mappings [index]
local size = entry.size
if entry.pfmweight == closest then
if size then
entries [#entries + 1] = {
size [1],
size [2],
size [3],
index,
}
else
entries.default = index
end
end
end
end
styledata [modifier] = entries
end
end
end
end
format_data [familyname] = styledata
end
end
end
return families
end
local cmp_sizes = function (a, b)
return a [1] < b [1]
end
order_design_sizes = function (families)
logreport ("info", 2, "db", "Ordering design sizes.")
for location, data in next, families do
for format, data in next, data do
for familyname, data in next, data do
for style, data in next, data do
tablesort (data, cmp_sizes)
end
end
end
end
return families
end
--[[doc--
collect_font_filenames -- Scan the three search path categories for
font files. This constitutes the first pass of the update mode.
--doc]]--
--- unit -> string * string list
local collect_font_filenames = function ()
logreport ("info", 4, "db", "Scanning the filesystem for font files.")
local filenames = { }
local bisect = config.luaotfload.misc.bisect
local max_fonts = config.luaotfload.db.max_fonts --- XXX revisit for lua 5.3 wrt integers
tableappend (filenames, collect_font_filenames_texmf ())
tableappend (filenames, collect_font_filenames_system ())
if config.luaotfload.db.scan_local == true then
tableappend (filenames, collect_font_filenames_local ())
end
--- Now drop everything above max_fonts.
if max_fonts < #filenames then
filenames = { unpack (filenames, 1, max_fonts) }
end
--- And choose the requested slice if in bisect mode.
if bisect then
return { unpack (filenames, bisect[1], bisect[2]) }
end
return filenames
end
--[[doc--
nth_font_file -- Return the filename of the nth font.
--doc]]--
--- int -> string
local nth_font_filename = function (n)
logreport ("info", 4, "db", "Picking font file no. %d.", n)
if not p_blacklist then
read_blacklist ()
end
local filenames = collect_font_filenames ()
return filenames[n] and filenames[n][1] or "<error>"
end
--[[doc--
font_slice -- Return the fonts in the range from lo to hi.
--doc]]--
local font_slice = function (lo, hi)
logreport ("info", 4, "db", "Retrieving font files nos. %d--%d.", lo, hi)
if not p_blacklist then
read_blacklist ()
end
local filenames = collect_font_filenames ()
local result = { }
for i = lo, hi do
result[#result + 1] = filenames[i][1]
end
return result
end
--[[doc
count_font_files -- Return the number of files found by
collect_font_filenames. This function is exported primarily
for use with luaotfload-tool.lua in bisect mode.
--doc]]--
--- unit -> int
local count_font_files = function ()
logreport ("info", 4, "db", "Counting font files.")
if not p_blacklist then
read_blacklist ()
end
return #collect_font_filenames ()
end
--- dbobj -> stats
local collect_statistics = function (mappings)
local sum_dsnsize, n_dsnsize = 0, 0
local fullname, family, families = { }, { }, { }
local subfamily, typographicsubfamily = { }, { }
local addtohash = function (hash, item)
if item then
local times = hash [item]
if times then
hash [item] = times + 1
else
hash [item] = 1
end
end
end
local appendtohash = function (hash, key, value)
if key and value then
local entry = hash [key]
if entry then
entry [#entry + 1] = value
else
hash [key] = { value }
end
end
end
local addtoset = function (hash, key, value)
if key and value then
local set = hash [key]
if set then
set [value] = true
else
hash [key] = { [value] = true }
end
end
end
local setsize = function (set)
local n = 0
for _, _ in next, set do
n = n + 1
end
return n
end
local hashsum = function (hash)
local n = 0
for _, m in next, hash do
n = n + m
end
return n
end
for _, entry in next, mappings do
local style = entry.style
local names = entry.names.sanitized
local englishnames = names.english
addtohash (fullname, englishnames.fullname)
addtohash (family, englishnames.family)
addtohash (subfamily, englishnames.subfamily)
addtohash (typographicsubfamily, englishnames.typographicsubfamily)
addtoset (families, englishnames.family, englishnames.fullname)
local sizeinfo = entry.style.size
if sizeinfo then
sum_dsnsize = sum_dsnsize + sizeinfo [1]
n_dsnsize = n_dsnsize + 1
end
end
--inspect (families)
local n_fullname = setsize (fullname)
local n_family = setsize (family)
if log.get_loglevel () > 1 then
local pprint_top = function (hash, n, set)
local freqs = { }
local items = { }
for item, value in next, hash do
if set then
freq = setsize (value)
else
freq = value
end
local ifreq = items [freq]
if ifreq then
ifreq [#ifreq + 1] = item
else
items [freq] = { item }
freqs [#freqs + 1] = freq
end
end
tablesort (freqs)
local from = #freqs
local to = from - (n - 1)
if to < 1 then
to = 1
end
for i = from, to, -1 do
local freq = freqs [i]
local itemlist = items [freq]
if type (itemlist) == "table" then
itemlist = tableconcat (itemlist, ", ")
end
logreport ("both", 0, "db",
" · %4d × %s.",
freq, itemlist)
end
end
logreport ("both", 0, "", "~~~~ font index statistics ~~~~")
logreport ("both", 0, "db",
" · Collected %d fonts (%d names) in %d families.",
#mappings, n_fullname, n_family)
pprint_top (families, 4, true)
logreport ("both", 0, "db",
" · %d different “subfamily” kinds.",
setsize (subfamily))
pprint_top (subfamily, 4)
logreport ("both", 0, "db",
" · %d different “typographicsubfamily” kinds.",
setsize (typographicsubfamily))
pprint_top (typographicsubfamily, 4)
end
local mean_dsnsize = 0
if n_dsnsize > 0 then
mean_dsnsize = sum_dsnsize / n_dsnsize
end
return {
mean_dsnsize = mean_dsnsize,
names = {
fullname = n_fullname,
families = n_family,
},
-- style = {
-- subfamily = subfamily,
-- typographicsubfamily = typographicsubfamily,
-- },
}
end
--- force: dictate rebuild from scratch
--- dry_dun: don’t write to the db, just scan dirs
--- dbobj? -> bool? -> bool? -> dbobj
update_names = function (currentnames, force, dry_run)
local targetnames
local n_new = 0
local n_rem = 0
local conf = config.luaotfload
if conf.run.live ~= false and conf.db.update_live == false then
logreport ("info", 2, "db", "Skipping database update.")
--- skip all db updates
return currentnames or name_index
end
local starttime = osgettimeofday ()
--[[
The main function, scans everything
- “targetnames” is the final table to return
- force is whether we rebuild it from scratch or not
]]
logreport ("both", 1, "db",
"Updating the font names database"
.. (force and " forcefully." or "."))
if config.luaotfload.db.skip_read == true then
--- the difference to a “dry run” is that we don’t search
--- for font files entirely. we also ignore the “force”
--- parameter since it concerns only the font files.
logreport ("info", 2, "db",
"Ignoring font files, reusing old data.")
currentnames = load_names (false)
targetnames = currentnames
else
if force then
currentnames = initialize_namedata (get_font_filter ())
else
if not currentnames or not next (currentnames) then
currentnames = load_names (dry_run)
end
if currentnames.meta.version ~= names.version then
logreport ("both", 1, "db",
"No font names database or old \z
one found; generating new one.")
currentnames = initialize_namedata (get_font_filter ())
end
end
targetnames = initialize_namedata (get_font_filter (),
currentnames.meta and currentnames.meta.created)
read_blacklist ()
--- pass 1: Collect the names of all fonts we are going to process.
local font_filenames = collect_font_filenames ()
--- pass 2: read font files (normal case) or reuse information
--- present in index
n_rem = count_removed (currentnames.files)
n_new = retrieve_namedata (font_filenames,
currentnames,
targetnames,
dry_run)
logreport ("info", 3, "db",
"Found %d font files; %d new, %d stale entries.",
#font_filenames, n_new, n_rem)
end
--- pass 3 (optional): collect some stats about the raw font info
if config.luaotfload.misc.statistics == true then
targetnames.meta.statistics = collect_statistics
(targetnames.mappings)
end
--- we always generate the file lookup tables because
--- non-texmf entries are redirected there and the mapping
--- needs to be 100% consistent
--- pass 4: build filename table
targetnames.files = generate_filedata (targetnames.mappings)
--- pass 5: build family lookup table
targetnames.families = collect_families (targetnames.mappings)
--- pass 6: arrange style and size info
targetnames.families = group_modifiers (targetnames.mappings,
targetnames.families)
--- pass 7: order design size tables
targetnames.families = order_design_sizes (targetnames.families)
logreport ("info", 3, "db",
"Rebuilt in %0.f ms.",
1000 * (osgettimeofday () - starttime))
name_index = targetnames
if dry_run ~= true then
if n_new + n_rem == 0 then
logreport ("info", 2, "db",
"No new or removed fonts, skip saving to disk.")
else
local success, reason = save_names ()
if not success then
logreport ("both", 0, "db",
"Failed to save database to disk: %s",
reason)
end
end
if flush_lookup_cache () and save_lookups () then
logreport ("both", 2, "cache", "Lookup cache emptied.")
return targetnames
end
end
return targetnames
end
--- unit -> bool
save_lookups = function ( )
local paths = config.luaotfload.paths
local luaname, lucname = paths.lookup_path_lua, paths.lookup_path_luc
if fileiswritable (luaname) and fileiswritable (lucname) then
tabletofile (luaname, lookup_cache, true)
osremove (lucname)
caches.compile (lookup_cache, luaname, lucname)
--- double check ...
if lfsisfile (luaname) and lfsisfile (lucname) then
logreport ("both", 3, "cache", "Lookup cache saved.")
return true
end
logreport ("info", 0, "cache", "Could not compile lookup cache.")
return false
end
logreport ("info", 0, "cache", "Lookup cache file not writable.")
if not fileiswritable (luaname) then
logreport ("info", 0, "cache", "Failed to write %s.", luaname)
end
if not fileiswritable (lucname) then
logreport ("info", 0, "cache", "Failed to write %s.", lucname)
end
return false
end
--- save_names() is usually called without the argument
--- dbobj? -> bool * string option
save_names = function (currentnames)
if not currentnames then
currentnames = name_index
end
if not currentnames or type (currentnames) ~= "table" then
return false, "invalid names table"
elseif currentnames.meta and currentnames.meta["local"] then
return false, "table contains local entries"
end
local paths = config.luaotfload.paths
local luaname, lucname = paths.index_path_lua, paths.index_path_luc
if fileiswritable (luaname) and fileiswritable (lucname) then
osremove (lucname)
local gzname = luaname .. ".gz"
if config.luaotfload.db.compress then
local serialized = tableserialize (currentnames, true)
gzipsave (gzname, serialized)
caches.compile (currentnames, "", lucname)
else
tabletofile (luaname, currentnames, true)
caches.compile (currentnames, luaname, lucname)
end
logreport ("info", 2, "db", "Font index saved at ...")
local success = false
if lfsisfile (luaname) then
logreport ("info", 2, "db", "Text: " .. luaname)
success = true
end
if lfsisfile (gzname) then
logreport ("info", 2, "db", "Gzip: " .. gzname)
success = true
end
if lfsisfile (lucname) then
logreport ("info", 2, "db", "Byte: " .. lucname)
success = true
end
if success then
return true
else
logreport ("info", 0, "db", "Could not compile font index.")
return false
end
end
logreport ("info", 0, "db", "Index file not writable")
if not fileiswritable (luaname) then
logreport ("info", 0, "db", "Failed to write %s.", luaname)
end
if not fileiswritable (lucname) then
logreport ("info", 0, "db", "Failed to write %s.", lucname)
end
return false
end
--[[doc--
Below set of functions is modeled after mtx-cache.
--doc]]--
--- string -> string -> string list -> string list -> string list -> unit
local print_cache = function (category, path, luanames, lucnames, rest)
local report_indeed = function (...)
logreport ("info", 0, "cache", ...)
end
report_indeed("Luaotfload cache: %s", category)
report_indeed("location: %s", path)
report_indeed("[raw] %4i", #luanames)
report_indeed("[compiled] %4i", #lucnames)
report_indeed("[other] %4i", #rest)
report_indeed("[total] %4i", #luanames + #lucnames + #rest)
end
--- string -> string -> string list -> bool -> bool
local purge_from_cache = function (category, path, list, all)
logreport ("info", 1, "cache", "Luaotfload cache: %s %s",
(all and "erase" or "purge"), category)
logreport ("info", 1, "cache", "location: %s", path)
local n = 0
for i=1,#list do
local filename = list[i]
if stringfind(filename,"luatex%-cache") then -- safeguard
if all then
logreport ("info", 5, "cache", "Removing %s.", filename)
osremove(filename)
n = n + 1
else
local suffix = filesuffix(filename)
if suffix == "lua" then
local checkname = file.replacesuffix(
filename, "lua", "luc")
if lfsisfile(checkname) then
logreport ("info", 5, "cache", "Removing %s.", filename)
osremove(filename)
n = n + 1
end
end
end
end
end
logreport ("info", 1, "cache", "Removed lua files : %i", n)
return true
end
--- string -> string list -> int -> string list -> string list -> string list ->
--- (string list * string list * string list * string list)
local collect_cache collect_cache = function (path, all, n, luanames,
lucnames, rest)
if not all then
local all = find_files (path)
local luanames, lucnames, rest = { }, { }, { }
return collect_cache(nil, all, 1, luanames, lucnames, rest)
end
local filename = all[n]
if filename then
local suffix = filesuffix(filename)
if suffix == "lua" then
luanames[#luanames+1] = filename
elseif suffix == "luc" then
lucnames[#lucnames+1] = filename
else
rest[#rest+1] = filename
end
return collect_cache(nil, all, n+1, luanames, lucnames, rest)
end
return luanames, lucnames, rest, all
end
local getwritablecachepath = function ( )
--- fonts.handlers.otf doesn’t exist outside a Luatex run,
--- so we have to improvise
local writable = getwritablepath (config.luaotfload.paths.cache_dir, "")
if writable then
return writable
end
end
local getreadablecachepaths = function ( )
local readables = caches.getreadablepaths
(config.luaotfload.paths.cache_dir)
local result = { }
if readables then
for i=1, #readables do
local readable = readables[i]
if lfsisdir (readable) then
result[#result+1] = readable
end
end
end
return result
end
--- unit -> unit
local purge_cache = function ( )
local writable_path = getwritablecachepath ()
local luanames, lucnames, rest = collect_cache(writable_path)
if log.get_loglevel() > 1 then
print_cache("writable path", writable_path, luanames, lucnames, rest)
end
local success = purge_from_cache("writable path", writable_path, luanames, false)
return success
end
--- unit -> unit
local erase_cache = function ( )
local writable_path = getwritablecachepath ()
local luanames, lucnames, rest, all = collect_cache(writable_path)
if log.get_loglevel() > 1 then
print_cache("writable path", writable_path, luanames, lucnames, rest)
end
local success = purge_from_cache("writable path", writable_path, all, true)
return success
end
local separator = function ( )
logreport ("info", 0, string.rep("-", 67))
end
--- unit -> unit
local show_cache = function ( )
local readable_paths = getreadablecachepaths ()
local writable_path = getwritablecachepath ()
local luanames, lucnames, rest = collect_cache(writable_path)
separator ()
print_cache ("writable path", writable_path,
luanames, lucnames, rest)
texio.write_nl""
for i=1,#readable_paths do
local readable_path = readable_paths[i]
if readable_path ~= writable_path then
local luanames, lucnames = collect_cache (readable_path)
print_cache ("readable path",
readable_path, luanames, lucnames, rest)
end
end
separator()
return true
end
-----------------------------------------------------------------------
--- API assumptions of the fontloader
-----------------------------------------------------------------------
--- PHG: we need to investigate these, maybe they’re useful as early
--- hooks
local ignoredfile = function () return false end
local reportmissingbase = function ()
logreport ("info", 0, "db", --> bug‽
"Font name database not found but expected by fontloader.")
fonts.names.reportmissingbase = nil
end
local reportmissingname = function ()
logreport ("info", 0, "db", --> bug‽
"Fontloader attempted to lookup name before Luaotfload \z
was initialized.")
fonts.names.reportmissingname = nil
end
local getfilename = function (a1, a2)
logreport ("info", 6, "db", --> bug‽
"Fontloader looked up font file (%s, %s) before Luaotfload \z
was initialized.", tostring(a1), tostring(a2))
return lookup_fullpath (a1, a2)
end
local resolve = function (name, subfont)
logreport ("info", 6, "db", --> bug‽
"Fontloader attempted to resolve name (%s, %s) before \z
Luaotfload was initialized.", tostring(name), tostring(subfont))
return lookup_font_name { name = name, sub = subfont }
end
local api = {
ignoredfile = ignoredfile,
reportmissingbase = reportmissingbase,
reportmissingname = reportmissingname,
getfilename = getfilename,
resolve = resolve,
}
-----------------------------------------------------------------------
--- export functionality to the namespace “fonts.names”
-----------------------------------------------------------------------
local export = {
set_font_filter = set_font_filter,
set_size_dimension = set_size_dimension,
flush_lookup_cache = flush_lookup_cache,
save_lookups = save_lookups,
load = load_names,
access_font_index = access_font_index,
data = function () return name_index end,
save = save_names,
update = update_names,
lookup_font_file = lookup_font_file,
lookup_font_name = lookup_font_name,
lookup_font_name_cached = lookup_font_name_cached,
getfilename = lookup_fullpath,
lookup_fullpath = lookup_fullpath,
read_blacklist = read_blacklist,
sanitize_fontname = sanitize_fontname,
getmetadata = getmetadata,
set_location_precedence = set_location_precedence,
count_font_files = count_font_files,
nth_font_filename = nth_font_filename,
font_slice = font_slice,
--- font cache
purge_cache = purge_cache,
erase_cache = erase_cache,
show_cache = show_cache,
find_closest = find_closest,
}
return {
init = function ()
--- the font loader namespace is “fonts”, same as in Context
--- we need to put some fallbacks into place for when running
--- as a script
if not fonts then return false end
logreport = luaotfload.log.report
local fonts = fonts
fonts.names = fonts.names or names
fonts.formats = fonts.formats or { }
fonts.definers = fonts.definers or { resolvers = { } }
names.blacklist = blacklist
names.version = 5 --- increase monotonically
names.data = nil --- contains the loaded database
names.lookups = nil --- contains the lookup cache
for sym, ref in next, export do names[sym] = ref end
for sym, ref in next, api do names[sym] = names[sym] or ref end
return true
end
}
-- vim:tw=71:sw=4:ts=4:expandtab
| gpl-2.0 |
8jsr/n7r | plugins/whitelist.lua | 2 | 2508 | do
local function get_message_callback (extra , success, result)
if result.service then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
end
end
else
user_id = result.from.peer_id
end
local receiver = extra.receiver
local hash = "whitelist"
local is_whitelisted = redis:sismember(hash, user_id)
if is_whitelisted then
redis:srem(hash, user_id)
send_large_msg(receiver, "User/Bot ["..user_id.."] removed from whitelist")
else
redis:sadd(hash, user_id)
send_large_msg(receiver, "User/Bot ["..user_id.."] added to whitelist")
end
end
local function whitelist_res (extra, success, result)
local user_id = result.peer_id
local receiver = extra.receiver
local hash = "whitelist"
local is_whitelisted = redis:sismember(hash, user_id)
if is_whitelisted then
redis:srem(hash, user_id)
send_large_msg(receiver, "User/Bot ["..user_id.."] removed from whitelist")
else
redis:sadd(hash, user_id)
send_large_msg(receiver, "User/Bot ["..user_id.."] added to whitelist")
end
end
local function run (msg, matches)
if matches[1] == "whitelist" and is_admin1(msg) then
local hash = "whitelist"
local user_id = ""
if type(msg.reply_id) ~= "nil" then
local receiver = get_receiver(msg)
get_message(msg.reply_id, get_message_callback, {receiver = receiver})
elseif string.match(matches[2], '^%d+$') then
local user_id = matches[2]
local is_whitelisted = redis:sismember(hash, user_id)
if is_whitelisted then
redis:srem(hash, user_id)
return "User/Bot ["..user_id.."] removed from whitelist"
else
redis:sadd(hash, user_id)
return "User/Bot ["..user_id.."] added to whitelist"
end
elseif not string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
resolve_username(username, whitelist_res, {receiver = receiver})
end
end
if matches[1] == "clean" and matches[2] == 'whitelist' and is_admin1(msg) then
local hash = 'whitelist'
redis:del(hash)
return "Whitelist Cleaned"
end
end
return {
patterns = {
"^[#!/](whitelist)$",
"^[#!/](whitelist) (.*)$",
"^[#!/](clean) (.*)$"
},
run = run
}
end
--Dev @j_Aa_Ff_Rr :)
--Fev @MMed_98 | gpl-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Mhaura/npcs/HomePoint#1.lua | 27 | 1254 | -----------------------------------
-- Area: Mhaura
-- NPC: HomePoint#1
-- @pos -12.750 -15.791 87.286 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 40);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
firebaugh/Digitowls | Player/Vision/detectBall.lua | 1 | 3978 | module(..., package.seeall);
require('Config'); -- For Ball and Goal Size
require('ImageProc');
require('HeadTransform'); -- For Projection
require('Vision');
require('Body');
require('shm');
require('vcm');
require('Detection');
require('Debug');
-- Define Color
colorOrange = 1;
colorYellow = 2;
colorCyan = 4;
colorField = 8;
colorWhite = 16;
use_point_goal=Config.vision.use_point_goal;
headInverted=Config.vision.headInverted;
headZ = Config.head.camOffsetZ;
function detect(color)
local ball = {};
ball.detect = 0;
-- threshold check on the total number of ball pixels in the image
if (Vision.colorCount[color] < 6) then
Debug.vprint(2,1,'total orange pixels threshold fail : '..Vision.colorCount[color]..' < 6');
return ball;
end
local diameter = Config.vision.ball_diameter;
-- find connected components of ball pixels
ballPropsB = ImageProc.connected_regions(Vision.labelB.data, Vision.labelB.m, Vision.labelB.n, color);
--ballPropsB = ImageProc.connected_regions(labelB.data, labelB.m, labelB.n, HeadTransform.get_horizonB(), color);
if (#ballPropsB == 0) then
return ball;
end
-- get largest blob
ball.propsB = ballPropsB[1];
ball.propsA = Vision.bboxStats(color, ballPropsB[1].boundingBox);
ball.bboxA = Vision.bboxB2A(ballPropsB[1].boundingBox);
-- threshold checks on the region properties
if ((ball.propsA.area < 6) or (ball.propsA.area < 0.35*Vision.bboxArea(ball.propsA.boundingBox))) then
Debug.vprint(2,1,'Threshold check fail');
return ball;
else
-- diameter of the area
dArea = math.sqrt((4/math.pi)*ball.propsA.area);
-- Find the centroid of the ball
ballCentroid = ball.propsA.centroid;
--[[
print('focalA: '..focalA);
print('centroid: '..ballCentroid[1]..', '..ballCentroid[2]);
print('diameter: '..diameter);
print('dArea: '..dArea);
print('axisMajor: '..ball.propsA.axisMajor);
--]]
-- Coordinates of ball
scale = math.max(dArea/diameter, ball.propsA.axisMajor/diameter);
v = HeadTransform.coordinatesA(ballCentroid, scale);
--[[
print('scale: '..scale);
print('v0: '..v[1]..', '..v[2]..', '..v[3]);
--]]
--Ball height check
if v[3] > Config.vision.ball_height_max then
Debug.vprint(2,1,'Height check fail');
return ball;
else
if Config.vision.check_for_ground == 1 then
-- ground check
-- is ball cut off at the bottom of the image?
if (ballCentroid[2] < 120 - dArea) then
-- bounding box
fieldBBox = {};
fieldBBox[1] = ballCentroid[1] - 30;
fieldBBox[2] = ballCentroid[1] + 30;
fieldBBox[3] = ballCentroid[2] + .5*dArea;
fieldBBox[4] = ballCentroid[2] + .5*dArea + 20;
-- color stats for the bbox
fieldBBoxStats = ImageProc.color_stats(Vision.labelA.data, Vision.labelA.m, Vision.labelA.n, colorField, fieldBBox);
-- is there green under the ball?
if (fieldBBoxStats.area < 400) then
-- if there is no field under the ball it may be because its on a white line
whiteBBoxStats = ImageProc.color_stats(Vision.labelA.data, Vision.labelA.m, Vision.labelA.n, colorWhite, fieldBBox);
if (whiteBBoxStats.area < 150) then
Debug.vprint(2,1,'ground check fail');
return ball;
end
end
end
end
end
end
-- Project to ground plane
if (v[3] < -headZ) then
v = (-headZ/v[3])*v;
end
--Discount body offset:
uBodyOffset = mcm.get_walk_bodyOffset();
v[1] = v[1] - uBodyOffset[1];
v[2] = v[2] - uBodyOffset[2];
ball.v = v;
ball.detect = 1;
--print('v: '..ball.v[1]..', '..ball.v[2]..', '..ball.v[3]);
ball.r = math.sqrt(ball.v[1]^2 + ball.v[2]^2);
-- How much to update the particle filter
ball.dr = 0.25*ball.r;
ball.da = 10*math.pi/180;
Debug.vprint(1,1,'BALL DETECTED');
return ball;
end
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/weaponskills/starburst.lua | 11 | 1301 | -----------------------------------
-- Starburst
-- Staff weapon skill
-- Skill Level: 100
-- Deals light or darkness elemental damage. Damage varies with TP.
-- Aligned with the Shadow Gorget & Aqua Gorget.
-- Aligned with the Shadow Belt & Aqua Belt.
-- Element: Light/Dark (Random)
-- Modifiers: : STR:40% MND:40%
-- 100%TP 200%TP 300%TP
-- 1.00 2.00 2.50
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.0; 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.ele = ELE_DARK; params.ele = ELE_LIGHT
params.skill = SKILL_STF;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4; params.mnd_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Tech-IT-Easy/Teach-IT-Easy | Project/src/games/Progg/progg_skin.lua | 1 | 11333 | --[[TEACH IT EASY, an educational games platform
Copyright (C) 2015 Linköping University
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
MIT LICENSE:
Copyright (c) 2015 Zenterio AB
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
-----------------------------------------------------------
-- This class keeps track of fixed positions and freetype
-- objects that are used in the programming game module.
--
-- Currently only specifies information relevant for the
-- right hand part of the screen
--
-- @Author:Created by Vilhelm Granath,Nov 10,2015
-- @Author:Updated by
-----------------------------------------------------------
if ADConfig.isSimulator then
script_path = ""
else
script_path = sys.root_path()
end
-- preset positions for the right-hand menu
row_spacing = screen:get_width() * 0.25 * 0.25 * 0.25
col_spacing = screen:get_height() * 0.65 * (1/17)
command_width = screen:get_width() * 0.25 * 0.25
command_height = screen:get_width() * 0.25 * 0.25
first_row = col_spacing
first_column = screen:get_width() * 0.75 + row_spacing
-- preset freetype objects for text in the right-hand menu
command_1 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column-command_width*0.25, y=first_row-command_height*0.20}, script_path..'data/GROBOLD.ttf')
command_2 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column+(command_width+row_spacing)-command_width*0.25, y=first_row-command_height*0.20}, script_path..'data/GROBOLD.ttf')
command_3 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column+2*(command_width+row_spacing)-command_width*0.25, y=first_row-command_height*0.20}, script_path..'data/GROBOLD.ttf')
command_4 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column-command_width*0.25, y=first_row-command_height*0.2+(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_5 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column+(command_width+row_spacing)-command_width*0.25, y=first_row-command_height*0.20+(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_6 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column+2*(command_width+row_spacing)-command_width*0.25, y=first_row-command_height*0.20+(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_7 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column-command_width*0.25, y=first_row-command_height*0.20+2*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_8 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column+(command_width+row_spacing)-command_width*0.25, y=first_row-command_height*0.20+2*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_9 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column+2*(command_width+row_spacing)-command_width*0.25, y=first_row-command_height*0.20+2*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_10 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column-command_width*0.25, y=first_row-command_height*0.20+3*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_play = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.65, {x= first_column+command_width*0.25, y=first_row+command_height*0.10+3*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_0 = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.4, {x= first_column-command_width*0.15, y=first_row-command_height*0.05+3*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_play_small = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.45, {x= first_column+command_width*0.20, y=first_row+command_height*0.30+3*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
command_back = sys.new_freetype({g=255, r=255, b=255, a=255}, command_height*0.45, {x= first_column+(1.66)*command_width+row_spacing+command_width*0.20, y=first_row+command_height*0.30+3*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
move_instruction_line1 = sys.new_freetype({r=255, g=255, b=255, a=255}, command_height*0.36, {x= first_column-command_width*0.12, y=first_row-command_height*0.20 + 0.5*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
move_instruction_line2 = sys.new_freetype({r=255, g=255, b=255, a=255}, command_height*0.36, {x= first_column-command_width*0.12, y=first_row-command_height*0.20 + 1*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
move_instruction_line3 = sys.new_freetype({r=255, g=255, b=255, a=255}, command_height*0.36, {x= first_column-command_width*0.12, y=first_row-command_height*0.20 + 1.5*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
move_instruction_line4 = sys.new_freetype({r=255, g=255, b=255, a=255}, command_height*0.36, {x= first_column-command_width*0.12, y=first_row-command_height*0.20 + 2*(command_height+col_spacing)}, script_path..'data/GROBOLD.ttf')
clearAll = sys.new_freetype({r=255, g=255, b=255, a=255}, command_height*0.7, {x= first_column, y=first_row+0.10*command_width}, script_path..'data/GROBOLD.ttf')
nr_1 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+0.15*command_height, y=first_row+0.05*command_width}, script_path..'data/GROBOLD.ttf')
nr_2 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+(command_width+row_spacing)+0.15*command_height, y=first_row+0.05*command_width}, script_path..'data/GROBOLD.ttf')
nr_3 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+2*(command_width+row_spacing)+0.15*command_height, y=first_row+0.05*command_width}, script_path..'data/GROBOLD.ttf')
nr_4 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+0.15*command_height, y=first_row+(command_height+col_spacing)+0.05*command_width}, script_path..'data/GROBOLD.ttf')
nr_5 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+(command_width+row_spacing)+0.15*command_height, y=first_row+(command_height+col_spacing)+0.05*command_width}, script_path..'data/GROBOLD.ttf')
nr_6 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+2*(command_width+row_spacing)+0.15*command_height, y=first_row+(command_height+col_spacing)+0.05*command_width}, script_path..'data/GROBOLD.ttf')
nr_7 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+0.15*command_height, y=first_row+2*(command_height+col_spacing)+0.05*command_width}, script_path..'data/GROBOLD.ttf')
nr_8 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+(command_width+row_spacing)+0.15*command_height, y=first_row+2*(command_height+col_spacing)+0.05*command_width}, script_path..'data/GROBOLD.ttf')
nr_9 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+2*(command_width+row_spacing)+0.15*command_height, y=first_row+2*(command_height+col_spacing)+0.05*command_width}, script_path..'data/GROBOLD.ttf')
nr_10 = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.8, {x= first_column+0.15*command_height, y=first_row+3*(command_height+col_spacing)+0.05*command_width}, script_path..'data/GROBOLD.ttf')
clear_on_nr9_top = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.25, {x= first_column+2*(command_width+row_spacing)+0.06*command_height, y=first_row+2*(command_height+col_spacing)+0.25*command_width}, script_path..'data/GROBOLD.ttf')
clear_on_nr9_bot = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.25, {x= first_column+2*(command_width+row_spacing)+0.02*command_height, y=first_row+2*(command_height+col_spacing)+0.55*command_width}, script_path..'data/GROBOLD.ttf')
nr_on_loop = sys.new_freetype({r=34, g=59, b=94, a=255}, command_height*0.5, { x = screen:get_width()*(0.90), y = screen:get_height()*0.67}, script_path..'data/GROBOLD.ttf')
-- preset freetype objects for text in the map
win_1 = sys.new_freetype({r=34, g=59, b=94, a=255}, screen:get_width()* 0.04, {x= screen:get_width()*0.08, y=screen:get_height()*0.15}, script_path..'data/GROBOLD.ttf')
win_2 = sys.new_freetype({r=34, g=59, b=94, a=255}, screen:get_width()* 0.04, {x= screen:get_width()*0.08, y=screen:get_height()*0.24}, script_path..'data/GROBOLD.ttf')
win_3 = sys.new_freetype({r=34, g=59, b=94, a=255}, screen:get_width()* 0.04, {x= screen:get_width()*0.08, y=screen:get_height()*0.33}, script_path..'data/GROBOLD.ttf')
win_4 = sys.new_freetype({r=255, g=255, b=255, a=255}, screen:get_width()* 0.04, {x= screen:get_width()*0.08, y=screen:get_height()*0.42}, script_path..'data/GROBOLD.ttf')
exit_1 = sys.new_freetype({r=34, g=59, b=94, a=255}, screen:get_width()* 0.04, {x= screen:get_width()*0.08, y=screen:get_height()*0.15}, script_path..'data/GROBOLD.ttf')
exit_2 = sys.new_freetype({r=34, g=59, b=94, a=255}, screen:get_width()* 0.04, {x= screen:get_width()*0.08, y=screen:get_height()*0.24}, script_path..'data/GROBOLD.ttf')
exit_3 = sys.new_freetype({r=225, g=225, b=255, a=255}, screen:get_width()* 0.04, {x= screen:get_width()*0.08, y=screen:get_height()*0.33}, script_path..'data/GROBOLD.ttf')
exit_4 = sys.new_freetype({r=255, g=255, b=255, a=255}, screen:get_width()* 0.04, {x= screen:get_width()*0.08, y=screen:get_height()*0.42}, script_path..'data/GROBOLD.ttf')
--preset border thickness for highighting in BottomMenu
highlight_border_thickness = screen:get_width() * 0.002344 | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/items/serving_of_golden_royale.lua | 18 | 1474 | -----------------------------------------
-- ID: 5558
-- Item: Serving of Golden Royale
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10
-- MP +10
-- Intelligence +2
-- HP Recoverd while healing 2
-- MP Recovered while healing 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5558);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_MP, 10);
target:addMod(MOD_INT, 2);
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_MP, 10);
target:delMod(MOD_INT, 2);
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/The_Garden_of_RuHmet/mobs/Jailer_of_Fortitude.lua | 5 | 2633 | -----------------------------------
-- Area: The Garden of Ru'Hmet
-- NPC: Jailer_of_Fortitude
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
-- Give it two hour
mob:setMobMod(MOBMOD_MAIN_2HOUR, 1);
mob:setMobMod(MOBMOD_2HOUR_MULTI, 1);
-- Change animation to humanoid w/ prismatic core
mob:AnimationSub(1);
mob:setModelId(1169);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob)
local delay = mob:getLocalVar("delay");
local LastCast = mob:getLocalVar("LAST_CAST");
local spell = mob:getLocalVar("COPY_SPELL");
if (mob:getBattleTime() - LastCast > 30) then
mob:setLocalVar("COPY_SPELL", 0);
mob:setLocalVar("delay", 0);
end;
if (IsMobDead(16921016)==false or IsMobDead(16921017)==false) then -- check for kf'ghrah
if (spell > 0 and mob:hasStatusEffect(EFFECT_SILENCE) == false) then
if (delay >= 3) then
mob:castSpell(spell);
mob:setLocalVar("COPY_SPELL", 0);
mob:setLocalVar("delay", 0);
else
mob:setLocalVar("delay", delay+1);
end;
end;
end;
end;
-----------------------------------
-- onMagicHit Action
-----------------------------------
function onMagicHit(caster,target,spell)
if (spell:tookEffect() and (caster:isPC() or caster:isPet()) and spell:getSpellGroup() ~= SPELLGROUP_BLUE ) then
-- Handle mimicked spells
target:setLocalVar("COPY_SPELL", spell:getID());
target:setLocalVar("LAST_CAST", target:getBattleTime());
target:setLocalVar("reflectTime", target:getBattleTime());
target:AnimationSub(1);
end;
return 1;
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer, npc)
-- Despawn the pets if alive
DespawnMob(Kf_Ghrah_WHM);
DespawnMob(Kf_Ghrah_BLM);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
-- Set 15 mins respawn
local qm1 = GetNPCByID(Jailer_of_Fortitude_QM);
qm1:updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME);
-- Move it to a random location
local qm1position = math.random(1,5);
qm1:setPos(Jailer_of_Fortitude_QM_POS[qm1position][1], Jailer_of_Fortitude_QM_POS[qm1position][2], Jailer_of_Fortitude_QM_POS[qm1position][3]);
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/spells/bluemagic/sandspin.lua | 25 | 1814 | -----------------------------------------
-- Spell: Sandspin
-- Deals earth damage to enemies within range. Additional Effect: Accuracy Down
-- Spell cost: 10 MP
-- Monster Type: Amorphs
-- Spell Type: Magical (Earth)
-- Blue Magic Points: 2
-- Stat Bonus: VIT+1
-- Level: 1
-- Casting Time: 1.5 seconds
-- Recast Time: 9.75 seconds
-- Magic Bursts on: Scission, Gravitation, Darkness
-- Combos: None
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.multiplier = 1.0;
params.tMultiplier = 1.0;
params.duppercap = 13;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.2;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0);
if (damage > 0 and resist > 0.0625) then
if (target:canGainStatusEffect(EFFECT_ACCURACY_DOWN)) then
target:addStatusEffect(EFFECT_ACCURACY_DOWN,20,3,60);
end
end
return damage;
end; | gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/globals/items/bird_egg.lua | 18 | 1171 | -----------------------------------------
-- ID: 4570
-- Item: Bird Egg
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Health 6
-- Magic 6
-----------------------------------------
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,4570);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 6);
target:addMod(MOD_MP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 6);
target:delMod(MOD_MP, 6);
end;
| gpl-3.0 |
harveyhu2012/luci | applications/luci-splash/luasrc/controller/splash/splash.lua | 50 | 4511 | module("luci.controller.splash.splash", package.seeall)
local uci = luci.model.uci.cursor()
local util = require "luci.util"
function index()
entry({"admin", "services", "splash"}, cbi("splash/splash"), _("Client-Splash"), 90)
entry({"admin", "services", "splash", "splashtext" }, form("splash/splashtext"), _("Splashtext"), 10)
local e
e = node("splash")
e.target = call("action_dispatch")
node("splash", "activate").target = call("action_activate")
node("splash", "splash").target = template("splash_splash/splash")
node("splash", "blocked").target = template("splash/blocked")
entry({"admin", "status", "splash"}, call("action_status_admin"), _("Client-Splash"))
local page = node("splash", "publicstatus")
page.target = call("action_status_public")
page.leaf = true
end
function action_dispatch()
local uci = luci.model.uci.cursor_state()
local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) or ""
local access = false
uci:foreach("luci_splash", "lease", function(s)
if s.mac and s.mac:lower() == mac then access = true end
end)
uci:foreach("luci_splash", "whitelist", function(s)
if s.mac and s.mac:lower() == mac then access = true end
end)
if #mac > 0 and access then
luci.http.redirect(luci.dispatcher.build_url())
else
luci.http.redirect(luci.dispatcher.build_url("splash", "splash"))
end
end
function blacklist()
leased_macs = { }
uci:foreach("luci_splash", "blacklist",
function(s) leased_macs[s.mac:lower()] = true
end)
return leased_macs
end
function action_activate()
local ip = luci.http.getenv("REMOTE_ADDR") or "127.0.0.1"
local mac = luci.sys.net.ip4mac(ip:match("^[\[::ffff:]*(%d+.%d+%.%d+%.%d+)\]*$"))
local uci_state = require "luci.model.uci".cursor_state()
local blacklisted = false
if mac and luci.http.formvalue("accept") then
uci:foreach("luci_splash", "blacklist",
function(s) if s.mac:lower() == mac or s.mac == mac then blacklisted = true end
end)
if blacklisted then
luci.http.redirect(luci.dispatcher.build_url("splash" ,"blocked"))
else
local redirect_url = uci:get("luci_splash", "general", "redirect_url")
if not redirect_url then
redirect_url = uci_state:get("luci_splash_locations", mac:gsub(':', ''):lower(), "location")
end
if not redirect_url then
redirect_url = luci.model.uci.cursor():get("freifunk", "community", "homepage") or 'http://www.freifunk.net'
end
remove_redirect(mac:gsub(':', ''):lower())
os.execute("luci-splash lease "..mac.." >/dev/null 2>&1")
luci.http.redirect(redirect_url)
end
else
luci.http.redirect(luci.dispatcher.build_url())
end
end
function action_status_admin()
local uci = luci.model.uci.cursor_state()
local macs = luci.http.formvaluetable("save")
local changes = {
whitelist = { },
blacklist = { },
lease = { },
remove = { }
}
for key, _ in pairs(macs) do
local policy = luci.http.formvalue("policy.%s" % key)
local mac = luci.http.protocol.urldecode(key)
if policy == "whitelist" or policy == "blacklist" then
changes[policy][#changes[policy]+1] = mac
elseif policy == "normal" then
changes["lease"][#changes["lease"]+1] = mac
elseif policy == "kicked" then
changes["remove"][#changes["remove"]+1] = mac
end
end
if #changes.whitelist > 0 then
os.execute("luci-splash whitelist %s >/dev/null"
% table.concat(changes.whitelist))
end
if #changes.blacklist > 0 then
os.execute("luci-splash blacklist %s >/dev/null"
% table.concat(changes.blacklist))
end
if #changes.lease > 0 then
os.execute("luci-splash lease %s >/dev/null"
% table.concat(changes.lease))
end
if #changes.remove > 0 then
os.execute("luci-splash remove %s >/dev/null"
% table.concat(changes.remove))
end
luci.template.render("admin_status/splash", { is_admin = true })
end
function action_status_public()
luci.template.render("admin_status/splash", { is_admin = false })
end
function remove_redirect(mac)
local mac = mac:lower()
mac = mac:gsub(":", "")
local uci = require "luci.model.uci".cursor_state()
local redirects = uci:get_all("luci_splash_locations")
--uci:load("luci_splash_locations")
uci:revert("luci_splash_locations")
-- For all redirects
for k, v in pairs(redirects) do
if v[".type"] == "redirect" then
if v[".name"] ~= mac then
-- Rewrite state
uci:section("luci_splash_locations", "redirect", v[".name"], {
location = v.location
})
end
end
end
uci:save("luci_splash_redirects")
end
| apache-2.0 |
firebaugh/Digitowls | WebotsController/Player/Motion/keyframes/km_Nao_KickForwardRight.lua | 5 | 5476 | local mot = {};
mot.servos = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22};
mot.keyframes = {
{
angles = {0.0, 0.0, 0.911, 0.661, -0.512, -0.827, -0.232, -0.011, -0.387, 1.355, -0.779, 0.048, -0.232, -0.023, -0.357, 1.338, -0.792, 0.003, 1.226, -0.457, 1.300, 0.391, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.800;
},
{
angles = {0.0, 0.0, 0.924, 1.000, -0.514, -0.833, 0.000, -0.387, -0.425, 0.851, -0.419, 0.420, 0.000, -0.327, -0.400, 1.000, -0.570, 0.300, 1.239, -0.600, 0.015, 0.405, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 1.000;
},
{
angles = {0.0, 0.0, 0.924, 1.000, -0.514, -0.833, 0.000, -0.387, -0.425, 0.851, -0.419, 0.420, 0.000, -0.327, -0.300, 0.900, -0.600, 0.340, 1.239, -0.600, 0.015, 0.405, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.400;
},
{
angles = {0.0, 0.0, 0.911, 1.000, -0.512, -0.827, 0.020, -0.391, -0.423, 0.842, -0.416, 0.420, 0.020, -0.396, -0.150, 1.594, -1.094, 0.051, 1.226, -0.600, 0.017, 0.391, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.900;
},
{
angles = {0.0, 0.0, 0.911, 1.000, -0.512, -0.827, 0.020, -0.391, -0.423, 0.842, -0.416, 0.420, 0.020, -0.396, -0.150, 1.594, -1.094, 0.051, 1.226, -0.600, 0.017, 0.391, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.600;
},
{
angles = {0.0, 0.0, 0.908, 1.000, -0.512, -0.827, 0.023, -0.393, -0.420, 0.838, -0.420, 0.420, 0.023, -0.399, -1.000, 1.300, -0.450, 0.296, 1.855, -0.600, 0.020, 0.393, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.120;
},
{
angles = {0.0, 0.0, 0.908, 1.000, -0.512, -0.827, 0.023, -0.393, -0.420, 0.838, -0.420, 0.420, 0.023, -0.399, -0.960, 1.106, -0.589, 0.296, 1.855, -0.600, 0.020, 0.393, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.140;
},
{
angles = {0.0, 0.0, 0.908, 1.000, -0.512, -0.827, 0.014, -0.393, -0.423, 0.841, -0.423, 0.420, 0.014, -0.393, -0.957, 1.483, -0.578, 0.296, 1.853, -0.600, 0.020, 0.393, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.180;
},
{
angles = {0.0, 0.0, 0.908, 1.000, -0.512, -0.828, 0.015, -0.393, -0.423, 0.839, -0.423, 0.420, 0.015, -0.394, -0.957, 1.483, -0.578, 0.296, 1.853, -0.600, 0.020, 0.393, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.200;
},
{
angles = {0.0, 0.0, 0.924, 1.000, -0.514, -0.833, 0.000, -0.387, -0.425, 0.851, -0.419, 0.420, 0.000, -0.327, -0.400, 1.000, -0.570, 0.300, 1.239, -0.600, 0.015, 0.405, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.700;
},
{
angles = {0.0, 0.0, 0.911, 0.669, -0.512, -0.816, -0.232, -0.006, -0.377, 1.356, -0.776, 0.048, -0.232, -0.022, -0.354, 1.342, -0.792, -0.002, 1.227, -0.459, 0.017, 0.393, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.600;
},
{
angles = {0.0, -0.436, 2.094, 0.349, -1.789, -1.396, -0.000, 0.017, -0.757, 1.491, -0.734, -0.017, 0.000, -0.017, -0.757, 1.491, -0.734, 0.017, 2.094, -0.349, 1.300, 1.396, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.700;
},
{
angles = {-0.000, -0.436, 2.094, 0.349, -1.789, -1.396, -0.000, 0.017, -0.757, 1.491, -0.734, -0.017, 0.000, -0.017, -0.757, 1.491, -0.734, 0.017, 2.094, -0.349, 1.300, 1.396, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 0.300;
},
{
angles = {0.0, -0.678, 1.468, 0.229, -1.273, -0.305, 0.000, -0.003, -0.396, 0.946, -0.548, 0.002, 0.000, 0.026, -0.397, 0.945, -0.548, -0.025, 1.494, -0.253, 1.216, 0.502, },
stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, },
duration = 1.000;
},
};
return mot;
| gpl-3.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Meriphataud_Mountains_[S]/npcs/Telepoint.lua | 13 | 1265 | -----------------------------------
-- Area: Meriphataud Mountains [S]
-- NPC: Telepoint
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Meriphataud_Mountains_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(MERIPHATAUD_GATE_CRYSTAL) == false) then
player:addKeyItem(MERIPHATAUD_GATE_CRYSTAL);
player:messageSpecial(KEYITEM_OBTAINED,MERIPHATAUD_GATE_CRYSTAL);
else
player:messageSpecial(ALREADY_OBTAINED_TELE);
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 |
shadow0162/countly-sdk-cocos2d-x | luabindings/auto/api/AgentManager.lua | 146 | 1798 |
--------------------------------
-- @module AgentManager
-- @parent_module plugin
--------------------------------
--
-- @function [parent=#AgentManager] getSocialPlugin
-- @param self
-- @return plugin::ProtocolSocial#plugin::ProtocolSocial ret (return value: cc.plugin::ProtocolSocial)
--------------------------------
--
-- @function [parent=#AgentManager] getAdsPlugin
-- @param self
-- @return plugin::ProtocolAds#plugin::ProtocolAds ret (return value: cc.plugin::ProtocolAds)
--------------------------------
--
-- @function [parent=#AgentManager] purge
-- @param self
--------------------------------
--
-- @function [parent=#AgentManager] getUserPlugin
-- @param self
-- @return plugin::ProtocolUser#plugin::ProtocolUser ret (return value: cc.plugin::ProtocolUser)
--------------------------------
--
-- @function [parent=#AgentManager] getIAPPlugin
-- @param self
-- @return plugin::ProtocolIAP#plugin::ProtocolIAP ret (return value: cc.plugin::ProtocolIAP)
--------------------------------
--
-- @function [parent=#AgentManager] getSharePlugin
-- @param self
-- @return plugin::ProtocolShare#plugin::ProtocolShare ret (return value: cc.plugin::ProtocolShare)
--------------------------------
--
-- @function [parent=#AgentManager] getAnalyticsPlugin
-- @param self
-- @return plugin::ProtocolAnalytics#plugin::ProtocolAnalytics ret (return value: cc.plugin::ProtocolAnalytics)
--------------------------------
--
-- @function [parent=#AgentManager] destroyInstance
-- @param self
--------------------------------
--
-- @function [parent=#AgentManager] getInstance
-- @param self
-- @return plugin::AgentManager#plugin::AgentManager ret (return value: cc.plugin::AgentManager)
return nil
| mit |
Kosmos82/kosmosdarkstar | scripts/zones/Bastok_Mines/npcs/Tibelda.lua | 16 | 1350 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Tibelda
-- Only sells when Bastok controlls Valdeaunia Region
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(VALDEAUNIA);
if (RegionOwner ~= BASTOK) then
player:showText(npc,TIBELDA_CLOSED_DIALOG);
else
player:showText(npc,TIBELDA_OPEN_DIALOG);
stock = {
0x111e, 29, --Frost Turnip
0x027e, 170 --Sage
}
showShop(player,BASTOK,stock);
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 |
sprunk/Zero-K-Infrastructure | Benchmarker/Benchmarks/games/fps_war2.sdd/LuaRules/Gadgets/dbg_fps_log.lua | 12 | 1749 |
function gadget:GetInfo()
return {
name = "Gadget_Fps_Log",
desc = "Some random logging",
author = "Licho",
date = "2013",
license = "GNU GPL, v2 or later",
layer = 1,
enabled = true -- loaded by default?
}
end
local GetTimer = Spring.GetTimer
local DiffTimers = Spring.DiffTimers
local START_GRACE = 64 -- do not report this first frames
if (gadgetHandler:IsSyncedCode()) then
function gadget:GameFrame(gf)
SendToUnsynced("gameFrame", gf)
end
else
local frameTimer= GetTimer()
local gfTimer = GetTimer()
local lastGameFrame = 0
local gf_dt_exceed_count = 100 -- how many can exceeded limit
local gf_dt_limit = 0.1 -- limit for the test
function gadget:Update()
local newTimer = GetTimer()
--local gf = Spring.GetGameFrame()
if (Spring.GetGameFrame() > START_GRACE) then
Spring.Echo("!transmitlobby g_update_dt: "..DiffTimers(newTimer, frameTimer))
end
frameTimer = newTimer
end
function gadget:GameOver()
local num = 0
if gf_dt_exceed_count <= 0 then
num = 1
end
Spring.Echo("!transmitlobby gf_dt_exceed:"..num)
end
local function gameFrame(_, gf)
if gf > lastGameFrame then
local newTimer = GetTimer()
if (Spring.GetGameFrame() > START_GRACE) then
local gf_dt = DiffTimers(newTimer, gfTimer) / (gf - lastGameFrame)
if (gf_dt > gf_dt_limit) then
gf_dt_exceed_count = gf_dt_exceed_count - 1
if gf_dt_exceed_count == 0 then
Spring.Echo("!transmitlobby gf_dt_exceed:1")
gf_dt_exceed_count = math.huge
end
end
Spring.Echo("!transmitlobby g_gameframe_dt: "..gf_dt)
end
lastGameFrame = gf
gfTimer = newTimer
end
end
function gadget:Initialize()
gadgetHandler:AddSyncAction("gameFrame", gameFrame)
end
end | gpl-3.0 |
mynameiscraziu/body | plugins/vote.lua | 615 | 2128 | do
local _file_votes = './data/votes.lua'
function read_file_votes ()
local f = io.open(_file_votes, "r+")
if f == nil then
print ('Created voting file '.._file_votes)
serialize_to_file({}, _file_votes)
else
print ('Values loaded: '.._file_votes)
f:close()
end
return loadfile (_file_votes)()
end
function clear_votes (chat)
local _votes = read_file_votes ()
_votes [chat] = {}
serialize_to_file(_votes, _file_votes)
end
function votes_result (chat)
local _votes = read_file_votes ()
local results = {}
local result_string = ""
if _votes [chat] == nil then
_votes[chat] = {}
end
for user,vote in pairs (_votes[chat]) do
if (results [vote] == nil) then
results [vote] = user
else
results [vote] = results [vote] .. ", " .. user
end
end
for vote,users in pairs (results) do
result_string = result_string .. vote .. " : " .. users .. "\n"
end
return result_string
end
function save_vote(chat, user, vote)
local _votes = read_file_votes ()
if _votes[chat] == nil then
_votes[chat] = {}
end
_votes[chat][user] = vote
serialize_to_file(_votes, _file_votes)
end
function run(msg, matches)
if (matches[1] == "ing") then
if (matches [2] == "reset") then
clear_votes (tostring(msg.to.id))
return "Voting statistics reset.."
elseif (matches [2] == "stats") then
local votes_result = votes_result (tostring(msg.to.id))
if (votes_result == "") then
votes_result = "[No votes registered]\n"
end
return "Voting statistics :\n" .. votes_result
end
else
save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2])))
return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2]))
end
end
return {
description = "Plugin for voting in groups.",
usage = {
"!voting reset: Reset all the votes.",
"!vote [number]: Cast the vote.",
"!voting stats: Shows the statistics of voting."
},
patterns = {
"^!vot(ing) (reset)",
"^!vot(ing) (stats)",
"^!vot(e) ([0-9]+)$"
},
run = run
}
end | gpl-2.0 |
Tech-IT-Easy/Teach-IT-Easy | Project/tests/luacov/src/luacov/stats.lua | 1 | 2342 | -----------------------------------------------------
-- Manages the file with statistics (being) collected.
-- In general the module requires that its property <code>stats.statsfile</code>
-- has been set to the filename of the statsfile to create, load, etc.
-- @class module
-- @name luacov.stats
local stats = {}
-----------------------------------------------------
-- Loads the stats file.
-- @return table with data. The table maps filenames to stats tables.
-- Per-file tables map line numbers to hits or nils when there are no hits.
-- Additionally, .max field contains maximum line number
-- and .max_hits contains maximum number of hits in the file.
function stats.load()
local data = {}
local fd = io.open(stats.statsfile, "r")
if not fd then
return nil
end
while true do
local max = fd:read("*n")
if not max then
break
end
local skip = fd:read(1)
if skip ~= ":" then
break
end
local filename = fd:read("*l")
if not filename then
break
end
data[filename] = {
max = max,
max_hits = 0
}
for i = 1, max do
local hits = fd:read("*n")
if not hits then
break
end
local skip = fd:read(1)
if skip ~= " " then
break
end
if hits > 0 then
data[filename][i] = hits
data[filename].max_hits = math.max(data[filename].max_hits, hits)
end
end
end
fd:close()
return data
end
--------------------------------
-- Opens the statfile
-- @return filehandle
function stats.start()
return io.open(stats.statsfile, "w")
end
--------------------------------
-- Closes the statfile
-- @param fd filehandle to the statsfile
function stats.stop(fd)
fd:close()
end
--------------------------------
-- Saves data to the statfile
-- @param data data to store
-- @param fd filehandle where to store
function stats.save(data, fd)
fd:seek("set")
for filename, filedata in pairs(data) do
local max = filedata.max
fd:write(max, ":", filename, "\n")
for i = 1, max do
local hits = filedata[i]
if not hits then
hits = 0
end
fd:write(hits, " ")
end
fd:write("\n")
end
fd:flush()
end
return stats
| gpl-3.0 |
Igalia/snabb | src/lib/protocol/header.lua | 9 | 11831 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
-- Protocol header base class
--
-- This is an abstract class (should not be instantiated)
--
-- Derived classes must implement the following class variables
--
-- _name a string that describes the header type in a
-- human readable form
--
-- _ulp a table that holds information about the "upper
-- layer protocols" supported by the header. It
-- contains two keys
-- method the name of the method of the header
-- class whose result identifies the ULP
-- and is used as key for the class_map
-- table
-- class_map a table whose keys must represent
-- valid return values of the instance
-- method given by the 'method' name
-- above. The corresponding value must
-- be the name of the header class that
-- parses this particular ULP
--
-- In the simplest case, a protocol header consists of a single data
-- structure of a fixed size, e.g. an untagged Ethernet II header.
-- Such headers are supported by this framework in a straight forward
-- manner. More complex headers may have representations that differ
-- in size and structure, depending on the use-case, e.g. GRE.
-- Headers of that kind can be supported as long as all variants can
-- be enumerated and represented by a separate fixed-sized data
-- structure. This requirement is necessary because all data
-- structures must be pre-allocated for performance reasons and to
-- support the instance recycling mechanism of the class framework.
-- Each header is described by a ctype object that serves as a
-- template for the header.
--
-- A protocol header can be created in two different manners. In the
-- first case (provided by the new() constructor method), the protocol
-- instance contains the header structure itself, where as in the
-- second case (provided by the new_from_mem() constructor), the
-- protocol instance contains a pointer to an arbitrary location in
-- memory where the actual header resides (usually a packet buffer).
-- The pointer is cast to the appropriate ctype to access the fields
-- of the header.
--
-- To support the second mode of creation for protocols with variable
-- header structures, one of the headers must be designated as the
-- "base header". It must be chosen such that it contains enough
-- information to determine the actual header that is present in
-- memory.
--
-- The constructors in the header base class deal exclusively with the
-- base header, i.e. the instances created by the new() and
-- new_from_mem() methods only provide access to the fields present in
-- the base header. Protocols that implement variable headers must
-- extend the base methods to select the appropriate header variant.
--
-- The header class uses the following data structures to support this
-- mechanism. Each header variant is described by a table with the
-- following elements
--
-- t the ctype that represents the header itself
-- ptr_t a ctype constructed by ffi.typeof("$*", ctype) used for
-- casting of pointers
-- box_t a ctype that represents a "box" to store a ptr_t, i.e.
-- ffi.typeof("$[1]", ptr_t)
--
-- These tables are stored as an array in the class variable _headers,
-- where, by definition, the first element designates the base header.
--
-- This array is initialized by the class method init(), which must be
-- called by every derived class.
--
-- When a new instance of a protocol class is created, it receives its
-- own, private array of headers stored in the instance variable of
-- the same name. The elements from the header tables stored in the
-- class are inherited by the instance by means of setmetatable().
-- For each header, one instance of the header itself and one instance
-- of a box are created from the t and box_t ctypes, respectively.
-- These objects are stored in the keys "data" and "box" and are
-- private to the instance. The following schematic should make the
-- relationship clearer
--
-- class._headers = {
-- [1] = { t = ...,
-- ptr_t = ...,
-- box_t = ...,
-- }, <---------------+
-- [2] = { t = ..., |
-- ptr_t = ..., |
-- box_t = ..., |
-- }, <------------+ |
-- ... | |
-- } | |
-- | |
-- instance._headers = { | |
-- [1] = { data = t(), | |
-- box = box_t()| |
-- }, ----------------+ metatable
-- [2] = { data = t(), |
-- box = box_t()|
-- }, -------------+ metatable
-- ...
-- }
--
-- The constructors of the base class store a reference to the base
-- header (i.e. _headers[1]) in the instance variable _header. In
-- other words, the box and data can be accessed by dereferencing
-- _header.data and _header.box, respectively.
--
-- This initialization is common to both constructors. The difference
-- lies in the contents of the pointer stored in the box. The new()
-- constructor stores a pointer to the data object, i.e.
--
-- _header.box[0] = ffi.cast(_header.ptr_t, _header.data)
--
-- where as the new_from_mem() constructor stores the pointer to the
-- region of memory supplied as argument to the method call, i.e.
--
-- _header.box[0] = ffi.cast(_header.ptr_t, mem)
--
-- In that case, the _header.data object is not used at all.
--
-- When a derived class overrides these constructors, it should first
-- call the construcor of the super class, which will initialize the
-- base header as described above. An extension of the new() method
-- will replace the reference to the base header stored in _header by
-- a reference to the header variant selected by the configuration
-- passed as arguments to the method, i.e. it will eventually do
--
-- _header = _headers[foo]
--
-- where <foo> is the index of the selected header.
--
-- An extension of the new_from_mem() constructor uses the base header
-- to determine the actual header variant to use and override the base
-- header with it.
--
-- Refer to the lib.protocol.ethernet and lib.protocol.gre classes for
-- examples.
--
-- For convenience, the class variable class._header exists as well
-- and contains a reference to the base header class._headers[1].
-- This promotes the instance methods sizeof() and ctype() to class
-- methods, which will provide the size and ctype of a protocol's base
-- header from the class itself. For example, the size of an ethernet
-- header can be obtained by
--
-- local ethernet = require("lib.protocol.ethernet")
-- local ether_size = ethernet:sizeof()
--
-- without creating an instance first.
module(..., package.seeall)
local ffi = require("ffi")
local header = subClass(nil)
-- Class methods
-- Initialize a subclass with a set of headers, which must contain at
-- least one element (the base header).
function header:init (headers)
assert(self and headers and #headers > 0)
self._singleton_p = #headers == 1
local _headers = {}
for i = 1, #headers do
local header = {}
local ctype = headers[i]
header.t = ctype
header.ptr_t = ffi.typeof("$*", ctype)
header.box_t = ffi.typeof("$*[1]", ctype)
header.meta = { __index = header }
_headers[i] = header
end
self._headers = _headers
self._header = _headers[1]
end
-- Initialize an instance of the class. If the instance is new (has
-- not been recycled), an instance of each header struct and a box
-- that holds a pointer to it are allocated. A reference to the base
-- header is installed in the _header instance variable.
local function _new (self)
local o = header:superClass().new(self)
if not o._recycled then
-- Allocate boxes and headers for all variants of the
-- classe's header structures
o._headers = {}
for i = 1, #self._headers do
-- This code is only executed when a new instance is created
-- via the class construcor, i.e. self is the class itself
-- (as opposed to the case when an instance is recycled by
-- calling the constructor as an instance method, in which
-- case self would be the instance instead of the class).
-- This is why it is safe to use self._headers[i].meta as
-- metatable here. The effect is that the ctypes are
-- inherited from the class while the data and box table are
-- private to the instance.
local _header = setmetatable({}, self._headers[i].meta)
_header.data = _header.t()
_header.box = _header.box_t()
o._headers[i] = _header
end
end
-- Make the base header the active header
o._header = o._headers[1]
return o
end
-- Initialize the base protocol header with 0 and store a pointer to
-- it in the header box.
function header:new ()
local o = _new(self)
local header = o._header
ffi.fill(header.data, ffi.sizeof(header.t))
header.box[0] = ffi.cast(header.ptr_t, header.data)
return o
end
-- This alternative constructor creates a protocol header from a chunk
-- of memory by "overlaying" a header structure. In this mode, the
-- protocol ctype _header.data is unused and _header.box stores the
-- pointer to the memory location supplied by the caller.
function header:new_from_mem (mem, size)
local o = _new(self)
local header = o._header
if ffi.sizeof(header.t) > size then
o:free()
return nil
end
header.box[0] = ffi.cast(header.ptr_t, mem)
return o
end
-- Instance methods
-- Return a reference to the header
function header:header ()
return self._header.box[0][0]
end
-- Return a pointer to the header
function header:header_ptr ()
return self._header.box[0]
end
-- Return the ctype of header
function header:ctype ()
return self._header.t
end
-- Return the size of the header
function header:sizeof ()
return ffi.sizeof(self._header.t)
end
-- Return true if <other> is of the same type and contains identical
-- data, false otherwise.
function header:eq (other)
local ctype = self:ctype()
local size = self:sizeof()
local other_ctype = other:ctype()
return (ctype == other_ctype and
ffi.string(self:header_ptr(), size) ==
ffi.string(other:header_ptr(), size))
end
-- Copy the header to some location in memory (usually a packet
-- buffer). The caller must make sure that there is enough space at
-- the destination. If relocate is a true value, the copy is promoted
-- to be the active storage of the header.
function header:copy (dst, relocate)
ffi.copy(dst, self:header_ptr(), self:sizeof())
if relocate then
self._header.box[0] = ffi.cast(self._header.ptr_t, dst)
end
end
-- Create a new protocol instance that is a copy of this instance.
-- This is horribly inefficient and should not be used in the fast
-- path.
function header:clone ()
local header = self:ctype()()
local sizeof = ffi.sizeof(header)
ffi.copy(header, self:header_ptr(), sizeof)
return self:class():new_from_mem(header, sizeof)
end
-- Return the class that can handle the upper layer protocol or nil if
-- the protocol is not supported or the protocol has no upper-layer.
function header:upper_layer ()
local method = self._ulp.method
if not method then return nil end
local class = self._ulp.class_map[self[method](self)]
if class then
if package.loaded[class] then
return package.loaded[class]
else
return require(class)
end
else
return nil
end
end
return header
| apache-2.0 |
Igalia/snabb | lib/ljsyscall/syscall/netbsd/c.lua | 24 | 2452 | -- This sets up the table of C functions for BSD
-- We need to override functions that are versioned as the old ones selected otherwise
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local abi = require "syscall.abi"
local version = require "syscall.netbsd.version".version
local ffi = require "ffi"
local function inlibc_fn(k) return ffi.C[k] end
-- Syscalls that just return ENOSYS but are in libc.
local nosys_calls
if version == 6 then nosys_calls = {
openat = true,
faccessat = true,
symlinkat = true,
mkdirat = true,
unlinkat = true,
renameat = true,
fstatat = true,
fchmodat = true,
fchownat = true,
mkfifoat = true,
mknodat = true,
}
end
local C = setmetatable({}, {
__index = function(C, k)
if nosys_calls and nosys_calls[k] then return nil end
if pcall(inlibc_fn, k) then
C[k] = ffi.C[k] -- add to table, so no need for this slow path again
return C[k]
else
return nil
end
end
})
-- for NetBSD we use libc names not syscalls, as assume you will have libc linked or statically linked with all symbols exported.
-- this is so we can use NetBSD libc even where syscalls have been redirected to rump calls.
-- use new versions
C.mount = C.__mount50
C.stat = C.__stat50
C.fstat = C.__fstat50
C.lstat = C.__lstat50
C.getdents = C.__getdents30
C.socket = C.__socket30
C.select = C.__select50
C.pselect = C.__pselect50
C.fhopen = C.__fhopen40
C.fhstat = C.__fhstat50
C.fhstatvfs1 = C.__fhstatvfs140
C.utimes = C.__utimes50
C.posix_fadvise = C.__posix_fadvise50
C.lutimes = C.__lutimes50
C.futimes = C.__futimes50
C.getfh = C.__getfh30
C.kevent = C.__kevent50
C.mknod = C.__mknod50
C.pollts = C.__pollts50
C.gettimeofday = C.__gettimeofday50
C.settimeofday = C.__settimeofday50
C.adjtime = C.__adjtime50
C.setitimer = C.__setitimer50
C.getitimer = C.__getitimer50
C.clock_gettime = C.__clock_gettime50
C.clock_settime = C.__clock_settime50
C.clock_getres = C.__clock_getres50
C.nanosleep = C.__nanosleep50
C.timer_settime = C.__timer_settime50
C.timer_gettime = C.__timer_gettime50
-- use underlying syscall not wrapper
C.getcwd = C.__getcwd
C.sigaction = C.__libc_sigaction14 -- TODO not working I think need to use tramp_sigaction, see also netbsd pause()
return C
| apache-2.0 |
Kosmos82/kosmosdarkstar | scripts/zones/Norg/npcs/HomePoint#2.lua | 27 | 1236 | -----------------------------------
-- Area: Norg
-- NPC: HomePoint#2
-- @pos -65 -5 54 252
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Norg/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 104);
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 |
thing-nacho/slua | build/luajit-2.1.0/src/host/genlibbc.lua | 51 | 4965 | ----------------------------------------------------------------------------
-- Lua script to dump the bytecode of the library functions written in Lua.
-- The resulting 'buildvm_libbc.h' is used for the build process of LuaJIT.
----------------------------------------------------------------------------
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
local ffi = require("ffi")
local bit = require("bit")
local vmdef = require("jit.vmdef")
local bcnames = vmdef.bcnames
local format = string.format
local isbe = (string.byte(string.dump(function() end), 5) % 2 == 1)
local function usage(arg)
io.stderr:write("Usage: ", arg and arg[0] or "genlibbc",
" [-o buildvm_libbc.h] lib_*.c\n")
os.exit(1)
end
local function parse_arg(arg)
local outfile = "-"
if not (arg and arg[1]) then
usage(arg)
end
if arg[1] == "-o" then
outfile = arg[2]
if not outfile then usage(arg) end
table.remove(arg, 1)
table.remove(arg, 1)
end
return outfile
end
local function read_files(names)
local src = ""
for _,name in ipairs(names) do
local fp = assert(io.open(name))
src = src .. fp:read("*a")
fp:close()
end
return src
end
local function transform_lua(code)
local fixup = {}
local n = -30000
code = string.gsub(code, "CHECK_(%w*)%((.-)%)", function(tp, var)
n = n + 1
fixup[n] = { "CHECK", tp }
return format("%s=%d", var, n)
end)
code = string.gsub(code, "PAIRS%((.-)%)", function(var)
fixup.PAIRS = true
return format("nil, %s, 0", var)
end)
return "return "..code, fixup
end
local function read_uleb128(p)
local v = p[0]; p = p + 1
if v >= 128 then
local sh = 7; v = v - 128
repeat
local r = p[0]
v = v + bit.lshift(bit.band(r, 127), sh)
sh = sh + 7
p = p + 1
until r < 128
end
return p, v
end
-- ORDER LJ_T
local name2itype = {
str = 5, func = 9, tab = 12, int = 14, num = 15
}
local BC = {}
for i=0,#bcnames/6-1 do
BC[string.gsub(string.sub(bcnames, i*6+1, i*6+6), " ", "")] = i
end
local xop, xra = isbe and 3 or 0, isbe and 2 or 1
local xrc, xrb = isbe and 1 or 2, isbe and 0 or 3
local function fixup_dump(dump, fixup)
local buf = ffi.new("uint8_t[?]", #dump+1, dump)
local p = buf+5
local n, sizebc
p, n = read_uleb128(p)
local start = p
p = p + 4
p = read_uleb128(p)
p = read_uleb128(p)
p, sizebc = read_uleb128(p)
local rawtab = {}
for i=0,sizebc-1 do
local op = p[xop]
if op == BC.KSHORT then
local rd = p[xrc] + 256*p[xrb]
rd = bit.arshift(bit.lshift(rd, 16), 16)
local f = fixup[rd]
if f then
if f[1] == "CHECK" then
local tp = f[2]
if tp == "tab" then rawtab[p[xra]] = true end
p[xop] = tp == "num" and BC.ISNUM or BC.ISTYPE
p[xrb] = 0
p[xrc] = name2itype[tp]
else
error("unhandled fixup type: "..f[1])
end
end
elseif op == BC.TGETV then
if rawtab[p[xrb]] then
p[xop] = BC.TGETR
end
elseif op == BC.TSETV then
if rawtab[p[xrb]] then
p[xop] = BC.TSETR
end
elseif op == BC.ITERC then
if fixup.PAIRS then
p[xop] = BC.ITERN
end
end
p = p + 4
end
return ffi.string(start, n)
end
local function find_defs(src)
local defs = {}
for name, code in string.gmatch(src, "LJLIB_LUA%(([^)]*)%)%s*/%*(.-)%*/") do
local env = {}
local tcode, fixup = transform_lua(code)
local func = assert(load(tcode, "", nil, env))()
defs[name] = fixup_dump(string.dump(func, true), fixup)
defs[#defs+1] = name
end
return defs
end
local function gen_header(defs)
local t = {}
local function w(x) t[#t+1] = x end
w("/* This is a generated file. DO NOT EDIT! */\n\n")
w("static const int libbc_endian = ") w(isbe and 1 or 0) w(";\n\n")
local s = ""
for _,name in ipairs(defs) do
s = s .. defs[name]
end
w("static const uint8_t libbc_code[] = {\n")
local n = 0
for i=1,#s do
local x = string.byte(s, i)
w(x); w(",")
n = n + (x < 10 and 2 or (x < 100 and 3 or 4))
if n >= 75 then n = 0; w("\n") end
end
w("0\n};\n\n")
w("static const struct { const char *name; int ofs; } libbc_map[] = {\n")
local m = 0
for _,name in ipairs(defs) do
w('{"'); w(name); w('",'); w(m) w('},\n')
m = m + #defs[name]
end
w("{NULL,"); w(m); w("}\n};\n\n")
return table.concat(t)
end
local function write_file(name, data)
if name == "-" then
assert(io.write(data))
assert(io.flush())
else
local fp = io.open(name)
if fp then
local old = fp:read("*a")
fp:close()
if data == old then return end
end
fp = assert(io.open(name, "w"))
assert(fp:write(data))
assert(fp:close())
end
end
local outfile = parse_arg(arg)
local src = read_files(arg)
local defs = find_defs(src)
local hdr = gen_header(defs)
write_file(outfile, hdr)
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.