repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
jshackley/darkstar | scripts/zones/Oldton_Movalpolos/npcs/Tarnotik.lua | 19 | 1752 | -----------------------------------
-- Area: Oldton Movalpolos
-- NPC: Tarnotik
-- Type: Standard NPC
-- @pos 160.896 10.999 -55.659 11
-----------------------------------
package.loaded["scripts/zones/Oldton_Movalpolos/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Oldton_Movalpolos/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(COP) >= THREE_PATHS) then
if (trade:getItemCount() == 1 and trade:hasItemQty(1725,1)) then
player:tradeComplete();
player:startEvent(0x0020);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 7 ) then
player:startEvent(0x0022);
else
if (math.random()<0.5) then -- this isnt retail at all.
player:startEvent(0x001e);
else
player:startEvent(0x001f);
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);
if (csid == 0x0020) then
player:setPos(-116,-119,-620,253,13);
elseif (csid == 0x0022) then
player:setVar("COP_Louverance_s_Path",8);
end
end;
| gpl-3.0 |
cellux/zzlua | zzlua.lua | 2 | 1030 | --[[ main ]]--
local function execute_chunk(chunk, err)
if chunk then
chunk()
else
error(err, 0)
end
end
-- process options
local arg_index = 1
local opt_e = false
while arg_index <= #arg do
if arg[arg_index] == '-e' then
opt_e = true
arg_index = arg_index + 1
local script = arg[arg_index]
execute_chunk(loadstring(script))
else
-- the first non-option arg is the path of the script to run
break
end
arg_index = arg_index + 1
end
-- run script (from specified file or stdin)
local script_path = arg[arg_index]
local script_args = {}
for i=arg_index+1,#arg do
table.insert(script_args, arg[i])
end
arg = script_args -- remove zzlua options
-- save the path of the script to arg[0]
arg[0] = script_path
if opt_e and not script_path then
-- if there was a script passed in via -e, but we didn't get a
-- script path on the command line, then don't read from stdin
else
execute_chunk(loadfile(script_path)) -- loadfile(nil) loads from stdin
end
| mit |
badboyam/spider_bot | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
Samanj5/Spam-is-DEAD | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
BeyondTeam/TeleBeyond | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | agpl-3.0 |
abbasgh12345/OMEGAMEW | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
hacker44-h44/h44bot | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
Ombridride/minetest-minetestforfun-server | mods/snow/src/sled.lua | 9 | 5998 | --[[
--=================
--======================================
LazyJ's Fork of Splizard's "Snow" Mod
by LazyJ
version: Umpteen and 7/5ths something or another.
2014_04_12
--======================================
--=================
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
THE LIST OF CHANGES I'VE MADE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* The HUD message that displayed when a player sat on the sled would not go away after the player
got off the sled. I spent hours on trial-and-error while reading the lua_api.txt and scrounging
the Internet for a needle-in-the-haystack solution as to why the hud_remove wasn't working.
Turns out Splizard's code was mostly correct, just not assembled in the right order.
The key to the solution was found in the code of leetelate's scuba mod:
http://forum.minetest.net/viewtopic.php?id=7175
* Changed the wording of the HUD message for clarity.
~~~~~~
TODO
~~~~~~
* Figure out why the player avatars remain in a seated position, even after getting off the sled,
if they flew while on the sled. 'default.player_set_animation', where is a better explanation
for this and what are it's available options?
* Go through, clean-up my notes and get them better sorted. Some are in the code, some are
scattered in my note-taking program. This "Oh, I'll just make a little tweak here and a
little tweak there" project has evolved into something much bigger and more complex
than I originally planned. :p ~ LazyJ
* find out why the sled disappears after rightclicking it ~ HybridDog
--]]
--=============================================================
-- CODE STUFF
--=============================================================
--
-- Helper functions
--
vector.zero = vector.zero or {x=0, y=0, z=0}
local function table_find(t, v)
for i = 1,#t do
if t[i] == v then
return true
end
end
return false
end
local function is_water(pos)
return minetest.get_item_group(minetest.get_node(pos).name, "water") ~= 0
end
--
-- Sled entity
--
local sled = {
physical = true,
collisionbox = {-0.6,-0.25,-0.6, 0.6,0.3,0.6},
visual = "mesh",
mesh = "sled.x",
textures = {"sled.png"},
}
local players_sled = {}
local function join_sled(self, player)
local pos = self.object:getpos()
player:setpos(pos)
local name = player:get_player_name()
players_sled[name] = true
default.player_attached[name] = true
default.player_set_animation(player, "sit" , 30)
self.driver = name
self.object:set_attach(player, "", {x=0,y=-9,z=0}, {x=0,y=90,z=0})
self.object:setyaw(player:get_look_yaw())-- - math.pi/2)
end
local function leave_sled(self, player)
local name = player:get_player_name()
players_sled[name] = false
self.driver = nil
self.object:set_detach()
default.player_attached[name] = false
default.player_set_animation(player, "stand" , 30)
player:set_physics_override({
speed = 1,
jump = 1,
})
player:hud_remove(self.HUD) -- And here is part 2. ~ LazyJ
self.object:remove()
--Give the sled back again
player:get_inventory():add_item("main", "snow:sled")
end
local function sled_rightclick(self, player)
if self.driver then
return
end
join_sled(self, player)
player:set_physics_override({
speed = 2, -- multiplier to default value
jump = 0, -- multiplier to default value
})
-- Here is part 1 of the fix. ~ LazyJ
self.HUD = player:hud_add({
hud_elem_type = "text",
position = {x=0.5, y=0.89},
name = "sled",
scale = {x=2, y=2},
text = "You are on the sled! Press the sneak key to get off the sled.", -- LazyJ
direction = 0,
})
-- End part 1
end
local on_sled_click
if snow.sleds then
on_sled_click = sled_rightclick
else
on_sled_click = function() end
end
snow.register_on_configuring(function(name, v)
if name == "sleds" then
if v then
on_sled_click = sled_rightclick
else
on_sled_click = function() end
end
end
end)
function sled:on_rightclick(player)
on_sled_click(self, player)
end
function sled:on_activate(staticdata, dtime_s)
self.object:set_armor_groups({immortal=1})
self.object:setacceleration({x=0, y=-10, z=0})
if staticdata then
self.v = tonumber(staticdata)
end
end
function sled:get_staticdata()
return tostring(self.v)
end
function sled:on_punch(puncher)
self.object:remove()
if puncher
and puncher:is_player() then
puncher:get_inventory():add_item("main", "snow:sled")
end
end
local driveable_nodes = {"default:snow","default:snowblock","default:ice","default:dirt_with_snow", "group:icemaker"}
local function accelerating_possible(pos)
if is_water(pos) then
return false
end
if table_find(driveable_nodes, minetest.get_node({x=pos.x, y=pos.y-1, z=pos.z}).name) then
return true
end
return false
end
local timer = 0
function sled:on_step(dtime)
if not self.driver then
return
end
timer = timer+dtime
if timer < 1 then
return
end
timer = 0
local player = minetest.get_player_by_name(self.driver)
if not player then
return
end
if player:get_player_control().sneak
or not accelerating_possible(vector.round(self.object:getpos())) then
leave_sled(self, player)
end
end
minetest.register_entity("snow:sled", sled)
minetest.register_craftitem("snow:sled", {
description = "Sled",
inventory_image = "snow_sled.png",
wield_image = "snow_sled.png",
wield_scale = {x=2, y=2, z=1},
liquids_pointable = true,
stack_max = 1,
on_use = function(itemstack, placer)
if players_sled[placer:get_player_name()] then
return
end
local pos = placer:getpos()
if accelerating_possible(vector.round(pos)) then
pos.y = pos.y+0.5
--Get on the sled and remove it from inventory.
minetest.add_entity(pos, "snow:sled"):right_click(placer)
itemstack:take_item(); return itemstack
end
end,
})
minetest.register_craft({
output = "snow:sled",
recipe = {
{"", "", ""},
{"group:stick", "", ""},
{"group:wood", "group:wood", "group:wood"},
},
})
minetest.register_craft({
output = "snow:sled",
recipe = {
{"", "", ""},
{"", "", "group:stick"},
{"group:wood", "group:wood", "group:wood"},
},
})
| unlicense |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/GLProgramState.lua | 3 | 2961 |
--------------------------------
-- @module GLProgramState
-- @extend Ref
--------------------------------
-- overload function: setUniformTexture(string, unsigned int)
--
-- overload function: setUniformTexture(string, cc.Texture2D)
--
-- @function [parent=#GLProgramState] setUniformTexture
-- @param self
-- @param #string str
-- @param #cc.Texture2D texture2d
--------------------------------
-- @function [parent=#GLProgramState] setUniformMat4
-- @param self
-- @param #string str
-- @param #cc.Mat4 mat4
--------------------------------
-- @function [parent=#GLProgramState] getUniformCount
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
-- @function [parent=#GLProgramState] setUniformFloat
-- @param self
-- @param #string str
-- @param #float float
--------------------------------
-- @function [parent=#GLProgramState] setUniformVec3
-- @param self
-- @param #string str
-- @param #cc.Vec3 vec3
--------------------------------
-- @function [parent=#GLProgramState] setGLProgram
-- @param self
-- @param #cc.GLProgram glprogram
--------------------------------
-- @function [parent=#GLProgramState] setUniformVec4
-- @param self
-- @param #string str
-- @param #cc.Vec4 vec4
--------------------------------
-- @function [parent=#GLProgramState] getVertexAttribCount
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
-- @function [parent=#GLProgramState] setUniformInt
-- @param self
-- @param #string str
-- @param #int int
--------------------------------
-- @function [parent=#GLProgramState] setUniformVec2
-- @param self
-- @param #string str
-- @param #cc.Vec2 vec2
--------------------------------
-- @function [parent=#GLProgramState] getVertexAttribsFlags
-- @param self
-- @return unsigned int#unsigned int ret (return value: unsigned int)
--------------------------------
-- @function [parent=#GLProgramState] apply
-- @param self
-- @param #cc.Mat4 mat4
--------------------------------
-- @function [parent=#GLProgramState] getGLProgram
-- @param self
-- @return GLProgram#GLProgram ret (return value: cc.GLProgram)
--------------------------------
-- @function [parent=#GLProgramState] create
-- @param self
-- @param #cc.GLProgram glprogram
-- @return GLProgramState#GLProgramState ret (return value: cc.GLProgramState)
--------------------------------
-- @function [parent=#GLProgramState] getOrCreateWithGLProgramName
-- @param self
-- @param #string str
-- @return GLProgramState#GLProgramState ret (return value: cc.GLProgramState)
--------------------------------
-- @function [parent=#GLProgramState] getOrCreateWithGLProgram
-- @param self
-- @param #cc.GLProgram glprogram
-- @return GLProgramState#GLProgramState ret (return value: cc.GLProgramState)
return nil
| mit |
jshackley/darkstar | scripts/zones/Eastern_Altepa_Desert/npcs/Eaulevisat_RK.lua | 28 | 3153 | -----------------------------------
-- Area: Eastern Altepa desert
-- NPC: Eaulevisat, R.K.
-- Outpost Conquest Guards
-- @pos -257 8 -249 114
------------------------------------
package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil;
--------------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Eastern_Altepa_Desert/TextIDs");
local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = KUZOTZ;
local csid = 0x7ffb;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
katsyoshi/dotfiles | wezterm/wezterm.lua | 1 | 5884 | local wezterm = require 'wezterm'
local os = require 'os'
local act = wezterm.action
local nvtop = { domain = "CurrentPaneDomain", args = {"nvtop"}, }
local htop = { domain = "CurrentPaneDomain", args = {"htop"}, }
local ytop = { domain = "CurrentPaneDomain", args = {"ytop", "-ps",}, }
local cursols = {
{ key = "Enter", mods = "CTRL", action = act.CopyMode { SetSelectionMode = "Block" }, },
{ key = "Escape", mods = "NONE", action = act.CopyMode "Close", },
{ key = "a", mods = "CTRL", action = act.CopyMode "MoveToStartOfLineContent" },
{ key = "b", mods = "ALT", action = act.CopyMode "MoveBackwardWord", },
{ key = "b", mods = "CTRL", action = act.CopyMode "MoveLeft", },
{ key = "e", mods = "CTRL", action = act.CopyMode "MoveToEndOfLineContent" },
{ key = "f", mods = "ALT", action = act.CopyMode "MoveForwardWord", },
{ key = "f", mods = "CTRL", action = act.CopyMode "MoveRight", },
{ key = "g", mods = "CTRL", action = act.CopyMode "Close", },
{ key = "p", mods = "CTRL", action = act.CopyMode "MoveUp", },
{ key = "p", mods = "ALT", action = act.CopyMode "PageUp", },
{ key = "n", mods = "CTRL", action = act.CopyMode "MoveDown", },
{ key = "n", mods = "ALT", action = act.CopyMode "PageDown", },
{ key = "q", mods = "NONE", action = act.CopyMode "Close", },
{ key = "Space", mods = "NONE", action = act.CopyMode { SetSelectionMode = "Cell" }, },
}
local assigned_keys = {
-- emacs like keybindings
{ key = "c", mods = "LEADER", action = act{ SpawnTab = "CurrentPaneDomain" }, },
{ key = "d", mods = "LEADER", action = act{ CloseCurrentTab = { confirm = false }, }, },
{ key = "d", mods = "LEADER|CTRL", action = act{ CloseCurrentPane = { confirm = false }, }, },
{ key = "[", mods = "LEADER", action = "ActivateCopyMode" },
{ key = "w", mods = "LEADER", action = act{ CopyTo = "Clipboard" }, },
{ key = "y", mods = "LEADER", action = act{ PasteFrom = "Clipboard" }, },
{ key = "n", mods = "LEADER", action = act{ ActivateTabRelative = 1 }, },
{ key = "p", mods = "LEADER", action = act{ ActivateTabRelative = -1 }, },
{ key = "v", mods = "LEADER", action = act{ SplitVertical = { domain = "CurrentPaneDomain", }, }, },
{ key = "h", mods = "LEADER", action = act{ SplitHorizontal = { domain = "CurrentPaneDomain", }, }, },
{ key = "o", mods = "LEADER", action = act{ ActivatePaneDirection = "Next", }, },
{ key = "l", mods = "LEADER", action = "ReloadConfiguration", },
{ key = "r", mods = "LEADER|CTRL", action = act{ SplitHorizontal = nvtop }, },
{ key = "R", mods = "LEADER|CTRL", action = act{ SplitVertical = ytop }, },
{ key = "=", mods = "LEADER|SUPER", action = "IncreaseFontSize", },
{ key = "-", mods = "LEADER|SUPER", action = "DecreaseFontSize", },
{ key = "r", mods = "LEADER|SUPER", action = "ResetFontSize", },
}
for i = 0, 9 do
local key_string = tostring(i)
table.insert(
assigned_keys,
{
key = key_string,
mods = "LEADER|ALT",
action = act { ActivateTab = i },
}
)
table.insert(
assigned_keys,
{
key = key_string,
mods = "LEADER|CTRL",
action = act{ MoveTab = i },
}
)
table.insert(
assigned_keys,
{
key = key_string,
mods = "LEADER",
action = act{ ActivatePaneByIndex = i },
}
)
end
local base_dir = wezterm.home_dir .. "/.local/share/wezterm/"
local socket = base_dir .. "wezterm.socket"
local SOLID_LEFT_ARROW = utf8.char(0xe0b2)
local SOLID_RIGHT_ARROW = utf8.char(0xe0b0)
wezterm.on(
"update-right-status",
function(window, _)
local date = wezterm.strftime("%Y/%m/%d(%a) %H:%M ");
local bat = ""
for _, b in ipairs(wezterm.battery_info()) do
bat = "🔋 " .. string.format("%.0f%%", b.state_of_charge * 100)
end
window:set_right_status(
wezterm.format(
{
{ Background = { Color = "#2b2042", }, },
{ Foreground = { Color = "#808080", }, },
{ Text = bat .. " "..date },
}
)
);
end)
wezterm.on(
"format-tab-title",
function(tab, _, _, _, hover, max_width)
local edge_background = "#0b0022"
local background = "#1b1032"
local foreground = "#808080"
if tab.is_active then
background = "#2b2042"
foreground = "#c0c0c0"
elseif hover then
background = "#3b3052"
foreground = "#909090"
end
local edge_foreground = background
-- ensure that the titles fit in the available space,
-- and that we have room for the edges.
local title = wezterm.truncate_right(tab.active_pane.title, max_width-2)
return {
{ Background = { Color = edge_background }, },
{ Foreground = { Color = edge_foreground }, },
{ Text = SOLID_LEFT_ARROW },
{ Background = { Color = background, }, },
{ Foreground = { Color = foreground, }, },
{ Text = title },
{ Background = { Color = edge_background, }, },
{ Foreground = { Color = edge_foreground, }, },
{ Text = SOLID_RIGHT_ARROW, },
}
end)
return {
adjust_window_size_when_changing_font_size = false,
color_scheme = "Dracula",
default_gui_startup_args = { "connect", "wezterm" },
disable_default_key_bindings = true,
font = wezterm.font "Noto Mono for Powerline",
font_size = 10.0,
keys = assigned_keys,
key_tables = {
copy_mode = cursols,
},
leader = { key="t", mods="CTRL", timeout_milliseconds=1000 },
tab_bar_at_bottom = true,
use_ime = true,
unix_domains = {
{
name = "wezterm",
socket_path = socket,
},
},
daemon_options = {
stdout = base_dir .. "stdout",
stderr = base_dir .. "stderr",
pid_file = base_dir .. "pid",
}
}
| mit |
LiberatorUSA/GUCEF | tools/DVPPackTool/premake5.lua | 1 | 1745 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
-- Configuration for module: DVPPackTool
project( "DVPPackTool" )
configuration( {} )
location( os.getenv( "PM5OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM5TARGETDIR" ) )
configuration( {} )
language( "C" )
configuration( { "WIN32" } )
configuration( { WIN32 } )
kind( "WindowedApp" )
configuration( { "NOT WIN32" } )
configuration( {} )
kind( "ConsoleApp" )
configuration( {} )
links( { "DVPACKSYS", "gucefCORE", "gucefMT" } )
links( { "DVPACKSYS", "gucefCORE", "gucefMT" } )
configuration( {} )
vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/DVP_Pack_Tool.c"
} )
configuration( {} )
includedirs( { "../../common/include", "../../dependencies/DVPACKSYS/include", "../../platform/gucefCORE/include", "../../platform/gucefMT/include" } )
configuration( { "ANDROID" } )
includedirs( { "../../platform/gucefCORE/include/android" } )
configuration( { "LINUX32" } )
includedirs( { "../../platform/gucefCORE/include/linux" } )
configuration( { "LINUX64" } )
includedirs( { "../../platform/gucefCORE/include/linux" } )
configuration( { "WIN32" } )
includedirs( { "../../platform/gucefCORE/include/mswin" } )
configuration( { "WIN64" } )
includedirs( { "../../platform/gucefCORE/include/mswin" } )
| apache-2.0 |
jshackley/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fi.lua | 34 | 1105 | -----------------------------------
-- 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 |
jshackley/darkstar | scripts/zones/Castle_Oztroja/npcs/_47l.lua | 17 | 1571 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47l (Torch Stand)
-- Notes: Opens door _471 near password #3
-- @pos -45.228 -17.832 22.392 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorID = npc:getID() - 3;
local DoorA = GetNPCByID(DoorID):getAnimation();
local TorchStandA = npc:getAnimation();
local Torch1 = npc:getID();
local Torch2 = npc:getID() + 1;
if (DoorA == 9 and TorchStandA == 9) then
player:startEvent(0x000a);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
local Torch1 = GetNPCByID(17396173):getID();
local Torch2 = GetNPCByID(Torch1):getID() + 1;
local DoorID = GetNPCByID(Torch1):getID() - 3;
if (option == 1) then
GetNPCByID(Torch1):openDoor(10); -- Torch Lighting
GetNPCByID(Torch2):openDoor(10); -- Torch Lighting
GetNPCByID(DoorID):openDoor(6);
end
end;
--printf("CSID: %u",csid);
--printf("RESULT: %u",option); | gpl-3.0 |
jshackley/darkstar | scripts/globals/effects/tabula_rasa.lua | 37 | 3360 | -----------------------------------
--
--
--
-----------------------------------
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
local regen = effect:getSubPower();
local helix = effect:getPower();
if (target:hasStatusEffect(EFFECT_LIGHT_ARTS) or target:hasStatusEffect(EFFECT_ADDENDUM_WHITE)) then
target:addMod(MOD_BLACK_MAGIC_COST, -30);
target:addMod(MOD_BLACK_MAGIC_CAST, -30);
target:addMod(MOD_BLACK_MAGIC_RECAST, -30);
target:addMod(MOD_REGEN_EFFECT, math.ceil(regen/1.5));
target:addMod(MOD_REGEN_DURATION, math.ceil((regen*2)/1.5));
target:addMod(MOD_HELIX_EFFECT, helix);
target:addMod(MOD_HELIX_DURATION, 108);
elseif (target:hasStatusEffect(EFFECT_DARK_ARTS) or target:hasStatusEffect(EFFECT_ADDENDUM_BLACK)) then
target:addMod(MOD_WHITE_MAGIC_COST, -30);
target:addMod(MOD_WHITE_MAGIC_CAST, -30);
target:addMod(MOD_WHITE_MAGIC_RECAST, -30);
target:addMod(MOD_REGEN_EFFECT, regen);
target:addMod(MOD_REGEN_DURATION, regen*2);
target:addMod(MOD_HELIX_EFFECT, math.ceil(helix/1.5));
target:addMod(MOD_HELIX_DURATION, 36);
else
target:addMod(MOD_BLACK_MAGIC_COST, -10);
target:addMod(MOD_BLACK_MAGIC_CAST, -10);
target:addMod(MOD_BLACK_MAGIC_RECAST, -10);
target:addMod(MOD_WHITE_MAGIC_COST, -10);
target:addMod(MOD_WHITE_MAGIC_CAST, -10);
target:addMod(MOD_WHITE_MAGIC_RECAST, -10);
target:addMod(MOD_REGEN_EFFECT, regen);
target:addMod(MOD_REGEN_DURATION, regen*2);
target:addMod(MOD_HELIX_EFFECT, helix);
target:addMod(MOD_HELIX_DURATION, 108);
end
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local regen = effect:getSubPower();
local helix = effect:getPower();
if (target:hasStatusEffect(EFFECT_LIGHT_ARTS) or target:hasStatusEffect(EFFECT_ADDENDUM_WHITE)) then
target:delMod(MOD_BLACK_MAGIC_COST, -30);
target:delMod(MOD_BLACK_MAGIC_CAST, -30);
target:delMod(MOD_BLACK_MAGIC_RECAST, -30);
target:delMod(MOD_REGEN_EFFECT, math.ceil(regen/1.5));
target:delMod(MOD_REGEN_DURATION, math.ceil((regen*2)/1.5));
target:delMod(MOD_HELIX_EFFECT, helix);
target:delMod(MOD_HELIX_DURATION, 108);
elseif (target:hasStatusEffect(EFFECT_DARK_ARTS) or target:hasStatusEffect(EFFECT_ADDENDUM_BLACK)) then
target:delMod(MOD_WHITE_MAGIC_COST, -30);
target:delMod(MOD_WHITE_MAGIC_CAST, -30);
target:delMod(MOD_WHITE_MAGIC_RECAST, -30);
target:delMod(MOD_REGEN_EFFECT, regen);
target:delMod(MOD_REGEN_DURATION, regen*2);
target:delMod(MOD_HELIX_EFFECT, math.ceil(helix/1.5));
target:delMod(MOD_HELIX_DURATION, 36);
else
target:delMod(MOD_BLACK_MAGIC_COST, -10);
target:delMod(MOD_BLACK_MAGIC_CAST, -10);
target:delMod(MOD_BLACK_MAGIC_RECAST, -10);
target:delMod(MOD_WHITE_MAGIC_COST, -10);
target:delMod(MOD_WHITE_MAGIC_CAST, -10);
target:delMod(MOD_WHITE_MAGIC_RECAST, -10);
target:delMod(MOD_REGEN_EFFECT, regen);
target:delMod(MOD_REGEN_DURATION, regen*2);
target:delMod(MOD_HELIX_EFFECT, helix);
target:delMod(MOD_HELIX_DURATION, 108);
end
end; | gpl-3.0 |
Ombridride/minetest-minetestforfun-server | mods/throwing/tnt_arrow.lua | 9 | 7433 | minetest.register_craftitem("throwing:arrow_tnt", {
description = "TNT arrow",
inventory_image = "throwing_arrow_tnt.png",
})
minetest.register_node("throwing:arrow_tnt_box", {
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
-- Shaft
{-6.5/17, -1.5/17, -1.5/17, 6.5/17, 1.5/17, 1.5/17},
--Spitze
{-4.5/17, 2.5/17, 2.5/17, -3.5/17, -2.5/17, -2.5/17},
{-8.5/17, 0.5/17, 0.5/17, -6.5/17, -0.5/17, -0.5/17},
--Federn
{6.5/17, 1.5/17, 1.5/17, 7.5/17, 2.5/17, 2.5/17},
{7.5/17, -2.5/17, 2.5/17, 6.5/17, -1.5/17, 1.5/17},
{7.5/17, 2.5/17, -2.5/17, 6.5/17, 1.5/17, -1.5/17},
{6.5/17, -1.5/17, -1.5/17, 7.5/17, -2.5/17, -2.5/17},
{7.5/17, 2.5/17, 2.5/17, 8.5/17, 3.5/17, 3.5/17},
{8.5/17, -3.5/17, 3.5/17, 7.5/17, -2.5/17, 2.5/17},
{8.5/17, 3.5/17, -3.5/17, 7.5/17, 2.5/17, -2.5/17},
{7.5/17, -2.5/17, -2.5/17, 8.5/17, -3.5/17, -3.5/17},
}
},
tiles = {"throwing_arrow_tnt.png", "throwing_arrow_tnt.png", "throwing_arrow_tnt_back.png", "throwing_arrow_tnt_front.png", "throwing_arrow_tnt_2.png", "throwing_arrow_tnt.png"},
groups = {not_in_creative_inventory=1},
})
local THROWING_ARROW_ENTITY={
physical = false,
timer=0,
visual = "wielditem",
visual_size = {x=0.1, y=0.1},
textures = {"throwing:arrow_tnt_box"},
lastpos={},
collisionbox = {0,0,0,0,0,0},
}
-- TNT functions copied, would be nice to directly call them through an API...
-- loss probabilities array (one in X will be lost)
local loss_prob = {}
loss_prob["default:cobble"] = 3
loss_prob["default:dirt"] = 4
local radius = tonumber(minetest.setting_get("tnt_radius") or 3)
-- Fill a list with data for content IDs, after all nodes are registered
local cid_data = {}
minetest.after(0, function()
for name, def in pairs(minetest.registered_nodes) do
cid_data[minetest.get_content_id(name)] = {
name = name,
drops = def.drops,
flammable = def.groups.flammable,
}
end
end)
local function rand_pos(center, pos, radius)
pos.x = center.x + math.random(-radius, radius)
pos.z = center.z + math.random(-radius, radius)
end
local function eject_drops(drops, pos, radius)
local drop_pos = vector.new(pos)
for _, item in pairs(drops) do
local count = item:get_count()
local max = item:get_stack_max()
if count > max then
item:set_count(max)
end
while count > 0 do
if count < max then
item:set_count(count)
end
rand_pos(pos, drop_pos, radius)
local obj = minetest.add_item(drop_pos, item)
if obj then
obj:get_luaentity().collect = true
obj:setacceleration({x=0, y=-10, z=0})
obj:setvelocity({x=math.random(-3, 3), y=10,
z=math.random(-3, 3)})
end
count = count - max
end
end
end
local function add_drop(drops, item)
item = ItemStack(item)
local name = item:get_name()
if loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then
return
end
local drop = drops[name]
if drop == nil then
drops[name] = item
else
drop:set_count(drop:get_count() + item:get_count())
end
end
local fire_node = {name="fire:basic_flame"}
local function destroy(drops, pos, cid)
if minetest.is_protected(pos, "") then
return
end
local def = cid_data[cid]
if def and def.flammable then
minetest.set_node(pos, fire_node)
else
minetest.dig_node(pos)
if def then
local node_drops = minetest.get_node_drops(def.name, "")
for _, item in ipairs(node_drops) do
add_drop(drops, item)
end
end
end
end
local function calc_velocity(pos1, pos2, old_vel, power)
local vel = vector.direction(pos1, pos2)
vel = vector.normalize(vel)
vel = vector.multiply(vel, power)
-- Divide by distance
local dist = vector.distance(pos1, pos2)
dist = math.max(dist, 1)
vel = vector.divide(vel, dist)
-- Add old velocity
vel = vector.add(vel, old_vel)
return vel
end
local function entity_physics(pos, radius)
-- Make the damage radius larger than the destruction radius
radius = radius * 2
local objs = minetest.get_objects_inside_radius(pos, radius)
for _, obj in pairs(objs) do
local obj_pos = obj:getpos()
local obj_vel = obj:getvelocity()
local dist = math.max(1, vector.distance(pos, obj_pos))
if obj_vel ~= nil then
obj:setvelocity(calc_velocity(pos, obj_pos,
obj_vel, radius * 10))
end
local damage = (5 / dist) * radius
obj:set_hp(obj:get_hp() - damage)
end
end
local function add_effects(pos, radius)
minetest.add_particlespawner({
amount = 128,
time = 1,
minpos = vector.subtract(pos, radius / 2),
maxpos = vector.add(pos, radius / 2),
minvel = {x=-20, y=-20, z=-20},
maxvel = {x=20, y=20, z=20},
minacc = vector.new(),
maxacc = vector.new(),
minexptime = 1,
maxexptime = 3,
minsize = 8,
maxsize = 16,
texture = "tnt_smoke.png",
})
end
local function explode(pos, radius)
local pos = vector.round(pos)
local vm = VoxelManip()
local pr = PseudoRandom(os.time())
local p1 = vector.subtract(pos, radius)
local p2 = vector.add(pos, radius)
local minp, maxp = vm:read_from_map(p1, p2)
local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
local data = vm:get_data()
local drops = {}
local p = {}
local c_air = minetest.get_content_id("air")
local c_tnt = minetest.get_content_id("tnt:tnt")
local c_tnt_burning = minetest.get_content_id("tnt:tnt_burning")
local c_gunpowder = minetest.get_content_id("tnt:gunpowder")
local c_gunpowder_burning = minetest.get_content_id("tnt:gunpowder_burning")
local c_boom = minetest.get_content_id("tnt:boom")
local c_fire = minetest.get_content_id("fire:basic_flame")
for z = -radius, radius do
for y = -radius, radius do
local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
for x = -radius, radius do
if (x * x) + (y * y) + (z * z) <=
(radius * radius) + pr:next(-radius, radius) then
local cid = data[vi]
p.x = pos.x + x
p.y = pos.y + y
p.z = pos.z + z
if cid == c_tnt or cid == c_gunpowder then
burn(p)
elseif cid ~= c_tnt_burning and
cid ~= c_gunpowder_burning and
cid ~= c_air and
cid ~= c_fire and
cid ~= c_boom then
destroy(drops, p, cid)
end
end
vi = vi + 1
end
end
end
return drops
end
local function boom(pos)
minetest.sound_play("tnt_explode", {pos=pos, gain=1.5, max_hear_distance=2*64})
minetest.set_node(pos, {name="tnt:boom"})
minetest.get_node_timer(pos):start(0.5)
local drops = explode(pos, radius)
entity_physics(pos, radius)
eject_drops(drops, pos, radius)
add_effects(pos, radius)
end
-- Back to the arrow
THROWING_ARROW_ENTITY.on_step = function(self, dtime)
local newpos = self.object:getpos()
if self.lastpos.x ~= nil then
for _, pos in pairs(throwing_get_trajectoire(self, newpos)) do
local node = minetest.get_node(pos)
local objs = minetest.get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2)
for k, obj in pairs(objs) do
if throwing_is_player(self.player, obj) or throwing_is_entity(obj) then
boom(pos)
self.object:remove()
return
end
end
if node.name ~= "air" then
boom(pos)
self.object:remove()
return
end
end
end
self.lastpos={x=pos.x, y=pos.y, z=pos.z}
end
minetest.register_entity("throwing:arrow_tnt_entity", THROWING_ARROW_ENTITY)
minetest.register_craft({
output = 'throwing:arrow_tnt',
recipe = {
{'default:stick', 'tnt:tnt', 'default:bronze_ingot'},
}
})
minetest.register_craft({
output = 'throwing:arrow_tnt',
recipe = {
{'default:bronze_ingot', 'tnt:tnt', 'default:stick'},
}
})
| unlicense |
brads55/nexusmeter | NexusMeter_Config.lua | 1 | 8135 | -- Copyright (C) 2014 Bradley Smith <brad@brad-smith.co.uk>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local RM = Apollo.GetAddon("NexusMeter")
local L = RM.l
function RM.ConfigInit()
local window = RM.configWindow
if not window then
RM.configWindow = { visible = false }
window = RM.configWindow
window.base = Apollo.LoadForm(RM.xmlMainDoc, "ConfigForm", nil, RM)
local anchors = {window.base:GetAnchorOffsets()}
window.base:SetAnchorOffsets(
(Apollo.GetDisplaySize().nWidth - 350) / 2,
(Apollo.GetDisplaySize().nHeight - 280) / 2,
(Apollo.GetDisplaySize().nWidth - 350) / 2 + anchors[3],
(Apollo.GetDisplaySize().nHeight - 280) / 2 + anchors[4])
window.opacity = window.base:FindChild("OpacityBackground")
window.opacity:SetOpacity(0.8)
window.tabs = {}
window.tabs[1] = window.base:FindChild("TabList:Tab1:TabBackground")
window.tabs[2] = window.base:FindChild("TabList:Tab2:TabBackground")
window.tabs[3] = window.base:FindChild("TabList:Tab3:TabBackground")
window.currenttab = 1
window.tabwindows = {}
window.tabwindows[1] = window.base:FindChild("TabWindow1")
window.tabwindows[2] = window.base:FindChild("TabWindow2")
window.tabwindows[3] = window.base:FindChild("TabWindow3")
window.tabwindows[window.currenttab]:Show(true)
window.tabs[window.currenttab]:SetOpacity(0.9)
for i = 2, #window.tabs do
window.tabs[i]:SetOpacity(0.2)
window.tabwindows[i]:Show(false)
end
-- Tab 1
window.lockbutton = window.base:FindChild("LockButton")
window.tooltipsbutton = window.base:FindChild("TooltipsButton")
window.selfbutton = window.base:FindChild("SelfButton")
window.onlybossbutton = window.base:FindChild("OnlyBossButton")
window.percentbutton = window.base:FindChild("ShowPercentButton")
window.absbutton = window.base:FindChild("ShowAbsButton")
window.rankbutton = window.base:FindChild("ShowRankButton")
window.shortbutton = window.base:FindChild("ShowShortButton")
-- Tab 2
window.classcolors = {}
window.classcolors[GameLib.CodeEnumClass.Warrior] = window.base:FindChild("TabWindow2:WarriorColorPicker:Color")
window.classcolors[GameLib.CodeEnumClass.Engineer] = window.base:FindChild("TabWindow2:EngineerColorPicker:Color")
window.classcolors[GameLib.CodeEnumClass.Esper] = window.base:FindChild("TabWindow2:EsperColorPicker:Color")
-- Tab 3
window.opacityslider = window.base:FindChild("TransparencySlider")
window.opacityslider:SetValue(RM.settings.opacity * 10)
window.opacitytext = window.base:FindChild("TransparencyValue")
window.opacitytext:SetText(RM.settings.opacity)
end
window.lockbutton:SetCheck(RM.settings.lock)
window.tooltipsbutton:SetCheck(RM.settings.tooltips)
window.selfbutton:SetCheck(RM.settings.alwaysShowPlayer)
window.onlybossbutton:SetCheck(RM.settings.showOnlyBoss)
window.percentbutton:SetCheck(RM.settings.showPercent)
window.absbutton:SetCheck(RM.settings.showAbsolute)
window.rankbutton:SetCheck(RM.settings.showRankNumber)
window.shortbutton:SetCheck(RM.settings.showShortNumber)
window.base:Show(not window.visible)
window.visible = not window.visible
end
function RM:OnConfigTabEnter(wndHandler, wndControl, x, y)
if wndControl ~= RM.configWindow.tabs[RM.configWindow.currenttab] then
wndControl:SetOpacity(0.6)
end
end
function RM:OnConfigTabExit(wndHandler, wndControl, x, y)
if wndControl ~= RM.configWindow.tabs[RM.configWindow.currenttab] then
wndControl:SetOpacity(0.2)
end
end
function RM:OnConfigButtonClose(wndHandler, wndControl, eMouseButton)
RM.configWindow.base:Show(false)
RM.configWindow.visible = false
end
function RM:OnConfigTabPress(wndHandler, wndControl, eMouseButton, nLastRelativeMouseX, nLastRelativeMouseY)
for i = 1, #RM.configWindow.tabs do
if RM.configWindow.tabs[i] == wndControl and i ~= RM.configWindow.currenttab then
for i = 1, #RM.configWindow.tabs do
RM.configWindow.tabs[i]:SetOpacity(0.2)
RM.configWindow.tabwindows[i]:Show(false)
end
RM.configWindow.currenttab = i
RM.configWindow.tabwindows[RM.configWindow.currenttab]:Show(true)
RM.configWindow.tabs[RM.configWindow.currenttab]:SetOpacity(0.9)
break
end
end
end
function RM:OnConfigHeaderButtonDown(wndHandler, wndControl, eMouseButton, nLastRelativeMouseX, nLastRelativeMouseY)
local window = RM.configWindow
if eMouseButton == 0 then
window.pressed = true
local mouse = Apollo.GetMouse()
window.mouseStartX = mouse.x
window.mouseStartY = mouse.y
local anchor = {window.base:GetAnchorOffsets()}
window.attrStartX = anchor[1]
window.attrStartY = anchor[2]
end
end
function RM:OnConfigHeaderButtonUp(wndHandler, wndControl, eMouseButton, nLastRelativeMouseX, nLastRelativeMouseY)
local window = RM.configWindow
if eMouseButton == 0 then
window.pressed = false
end
end
function RM:OnConfigHeaderMouseMove(wndHandler, wndControl, eMouseButton, nLastRelativeMouseX, nLastRelativeMouseY)
local window = RM.configWindow
if window.pressed then
local mouse = Apollo.GetMouse()
local x = mouse.x - window.mouseStartX + window.attrStartX
local y = mouse.y - window.mouseStartY + window.attrStartY
local anchor = {window.base:GetAnchorOffsets()}
window.base:SetAnchorOffsets(x, y, x + anchor[3] - anchor[1], y + anchor[4] - anchor[2])
end
end
function RM:OnConfigClassColorEnter(wndHandler, wndControl, x, y)
if wndControl == wndHandler then
wndControl:SetOpacity(0.7)
end
end
function RM:OnConfigClassColorExit(wndHandler, wndControl, x, y)
if wndControl == wndHandler then
wndControl:SetOpacity(1)
end
end
function RM:OnConfigClassColorPress(wndHandler, wndControl, eMouseButton, nLastRelativeMouseX, nLastRelativeMouseY)
for key, frame in pairs(RM.configWindow.classcolors) do
if wndControl == frame then
break
end
end
end
function RM:OnConfigLockButton(wndHandler, wndControl, eMouseButton)
RM.settings.lock = not RM.settings.lock
RM.UI.ShowResizer(not RM.settings.lock)
end
function RM:OnConfigTooltipsButton(wndHandler, wndControl, eMouseButton)
RM.settings.tooltips = not RM.settings.tooltips
end
function RM:OnConfigSelfButton(wndHandler, wndControl, eMouseButton)
RM.settings.alwaysShowPlayer = not RM.settings.alwaysShowPlayer
end
function RM:OnConfigOnlyBossButton(wndHandler, wndControl, eMouseButton)
RM.settings.showOnlyBoss = not RM.settings.showOnlyBoss
end
function RM:OnConfigPercentButton(wndHandler, wndControl, eMouseButton)
RM.settings.showPercent = not RM.settings.showPercent
end
function RM:OnConfigAbsButton(wndHandler, wndControl, eMouseButton)
RM.settings.showAbsolute = not RM.settings.showAbsolute
end
function RM:OnConfigRankButton(wndHandler, wndControl, eMouseButton)
RM.settings.showRankNumber = not RM.settings.showRankNumber
end
function RM:OnConfigShortButton(wndHandler, wndControl, eMouseButton)
RM.settings.showShortNumber = not RM.settings.showShortNumber
end
function RM:OnOpacitySliderChanged(wndHandler, wndControl, fNewValue, fOldValue)
RM.configWindow.opacitytext:SetText(fNewValue / 10)
RM.settings.opacity = fNewValue / 10
RM.Windows[1].frames.opacitybackground:SetOpacity(RM.settings.opacity)
end | apache-2.0 |
jshackley/darkstar | scripts/zones/Bastok_Markets/npcs/HomePoint#2.lua | 17 | 1253 | -----------------------------------
-- Area: Bastok Markets
-- NPC: HomePoint#2
-- @pos -328 -12 -33 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Bastok_Markets/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 12);
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 |
majello/google-diff-match-patch | lua/diff_match_patch_test.lua | 264 | 39109 | --[[
* Test Harness for Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Based on the JavaScript implementation by Neil Fraser
* Ported to Lua by Duncan Cross
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
--]]
local dmp = require 'diff_match_patch'
local DIFF_INSERT = dmp.DIFF_INSERT
local DIFF_DELETE = dmp.DIFF_DELETE
local DIFF_EQUAL = dmp.DIFF_EQUAL
-- Utility functions.
local function pretty(v)
if (type(v) == 'string') then
return string.format('%q', v):gsub('\\\n', '\\n')
elseif (type(v) == 'table') then
local str = {}
local next_i = 1
for i, v in pairs(v) do
if (i == next_i) then
next_i = next_i + 1
str[#str + 1] = pretty(v)
else
str[#str + 1] = '[' .. pretty(i) .. ']=' .. pretty(v)
end
end
return '{' .. table.concat(str, ',') .. '}'
else
return tostring(v)
end
end
function assertEquals(...)
local msg, expected, actual
if (select('#', ...) == 2) then
expected, actual = ...
msg = 'Expected: \'' .. pretty(expected)
.. '\' Actual: \'' .. pretty(actual) .. '\''
else
msg, expected, actual = ...
end
assert(expected == actual, msg)
end
function assertTrue(...)
local msg, actual
if (select('#', ...) == 1) then
actual = ...
assertEquals(true, actual)
else
msg, actual = ...
assertEquals(msg, true, actual)
end
end
function assertFalse(...)
local msg, actual
if (select('#', ...) == 1) then
actual = ...
assertEquals(flase, actual)
else
msg, actual = ...
assertEquals(msg, false, actual)
end
end
-- If expected and actual are the equivalent, pass the test.
function assertEquivalent(...)
local msg, expected, actual
expected, actual = ...
msg = 'Expected: \'' .. pretty(expected)
.. '\' Actual: \'' .. pretty(actual) .. '\''
if (_equivalent(expected, actual)) then
assertEquals(msg, pretty(expected), pretty(actual))
else
assertEquals(msg, expected, actual)
end
end
-- Are a and b the equivalent? -- Recursive.
function _equivalent(a, b)
if (a == b) then
return true
end
if (type(a) == 'table') and (type(b) == 'table') then
for k, v in pairs(a) do
if not _equivalent(v, b[k]) then
return false
end
end
for k, v in pairs(b) do
if not _equivalent(v, a[k]) then
return false
end
end
return true
end
return false
end
function diff_rebuildtexts(diffs)
-- Construct the two texts which made up the diff originally.
local text1, text2 = {}, {}
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if (op ~= DIFF_INSERT) then
text1[#text1 + 1] = data
end
if (op ~= DIFF_DELETE) then
text2[#text2 + 1] = data
end
end
return table.concat(text1), table.concat(text2)
end
-- DIFF TEST FUNCTIONS
function testDiffCommonPrefix()
-- Detect any common prefix.
-- Null case.
assertEquals(0, dmp.diff_commonPrefix('abc', 'xyz'))
-- Non-null case.
assertEquals(4, dmp.diff_commonPrefix('1234abcdef', '1234xyz'))
-- Whole case.
assertEquals(4, dmp.diff_commonPrefix('1234', '1234xyz'))
end
function testDiffCommonSuffix()
-- Detect any common suffix.
-- Null case.
assertEquals(0, dmp.diff_commonSuffix('abc', 'xyz'))
-- Non-null case.
assertEquals(4, dmp.diff_commonSuffix('abcdef1234', 'xyz1234'))
-- Whole case.
assertEquals(4, dmp.diff_commonSuffix('1234', 'xyz1234'))
end
function testDiffCommonOverlap()
-- Detect any suffix/prefix overlap.
-- Null case.
assertEquals(0, dmp.diff_commonOverlap('', 'abcd'));
-- Whole case.
assertEquals(3, dmp.diff_commonOverlap('abc', 'abcd'));
-- No overlap.
assertEquals(0, dmp.diff_commonOverlap('123456', 'abcd'));
-- Overlap.
assertEquals(3, dmp.diff_commonOverlap('123456xxx', 'xxxabcd'));
--[[
-- Unicode.
-- Some overly clever languages (C#) may treat ligatures as equal to their
-- component letters. E.g. U+FB01 == 'fi'
-- LUANOTE: No ability to handle Unicode.
assertEquals(0, dmp.diff_commonOverlap('fi', '\ufb01i'));
--]]
end
function testDiffHalfMatch()
-- Detect a halfmatch.
dmp.settings{Diff_Timeout = 1}
-- No match.
assertEquivalent({nil}, {dmp.diff_halfMatch('1234567890', 'abcdef')})
assertEquivalent({nil}, {dmp.diff_halfMatch('12345', '23')})
-- Single Match.
assertEquivalent({'12', '90', 'a', 'z', '345678'},
{dmp.diff_halfMatch('1234567890', 'a345678z')})
assertEquivalent({'a', 'z', '12', '90', '345678'},
{dmp.diff_halfMatch('a345678z', '1234567890')})
assertEquivalent({'abc', 'z', '1234', '0', '56789'},
{dmp.diff_halfMatch('abc56789z', '1234567890')})
assertEquivalent({'a', 'xyz', '1', '7890', '23456'},
{dmp.diff_halfMatch('a23456xyz', '1234567890')})
-- Multiple Matches.
assertEquivalent({'12123', '123121', 'a', 'z', '1234123451234'},
{dmp.diff_halfMatch('121231234123451234123121', 'a1234123451234z')})
assertEquivalent({'', '-=-=-=-=-=', 'x', '', 'x-=-=-=-=-=-=-='},
{dmp.diff_halfMatch('x-=-=-=-=-=-=-=-=-=-=-=-=', 'xx-=-=-=-=-=-=-=')})
assertEquivalent({'-=-=-=-=-=', '', '', 'y', '-=-=-=-=-=-=-=y'},
{dmp.diff_halfMatch('-=-=-=-=-=-=-=-=-=-=-=-=y', '-=-=-=-=-=-=-=yy')})
-- Non-optimal halfmatch.
-- Optimal diff would be -q+x=H-i+e=lloHe+Hu=llo-Hew+y not -qHillo+x=HelloHe-w+Hulloy
assertEquivalent({'qHillo', 'w', 'x', 'Hulloy', 'HelloHe'},
{dmp.diff_halfMatch('qHilloHelloHew', 'xHelloHeHulloy')})
-- Optimal no halfmatch.
dmp.settings{Diff_Timeout = 0}
assertEquivalent({nill}, {dmp.diff_halfMatch('qHilloHelloHew', 'xHelloHeHulloy')})
end
function testDiffCleanupMerge()
-- Cleanup a messy diff.
-- Null case.
local diffs = {}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({}, diffs)
-- No change case.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_INSERT, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_INSERT, 'c'}},
diffs)
-- Merge equalities.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_EQUAL, 'b'}, {DIFF_EQUAL, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'abc'}}, diffs)
-- Merge deletions.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_DELETE, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}}, diffs)
-- Merge insertions.
diffs = {{DIFF_INSERT, 'a'}, {DIFF_INSERT, 'b'}, {DIFF_INSERT, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_INSERT, 'abc'}}, diffs)
-- Merge interweave.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_INSERT, 'b'}, {DIFF_DELETE, 'c'},
{DIFF_INSERT, 'd'}, {DIFF_EQUAL, 'e'}, {DIFF_EQUAL, 'f'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_DELETE, 'ac'}, {DIFF_INSERT, 'bd'}, {DIFF_EQUAL, 'ef'}},
diffs)
-- Prefix and suffix detection.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_INSERT, 'abc'}, {DIFF_DELETE, 'dc'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'd'},
{DIFF_INSERT, 'b'}, {DIFF_EQUAL, 'c'}}, diffs)
-- Prefix and suffix detection with equalities.
diffs = {{DIFF_EQUAL, 'x'}, {DIFF_DELETE, 'a'}, {DIFF_INSERT, 'abc'},
{DIFF_DELETE, 'dc'}, {DIFF_EQUAL, 'y'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'xa'}, {DIFF_DELETE, 'd'},
{DIFF_INSERT, 'b'}, {DIFF_EQUAL, 'cy'}}, diffs)
-- Slide edit left.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_INSERT, 'ba'}, {DIFF_EQUAL, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_INSERT, 'ab'}, {DIFF_EQUAL, 'ac'}}, diffs)
-- Slide edit right.
diffs = {{DIFF_EQUAL, 'c'}, {DIFF_INSERT, 'ab'}, {DIFF_EQUAL, 'a'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'ca'}, {DIFF_INSERT, 'ba'}}, diffs)
-- Slide edit left recursive.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_EQUAL, 'c'},
{DIFF_DELETE, 'ac'}, {DIFF_EQUAL, 'x'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_EQUAL, 'acx'}}, diffs)
-- Slide edit right recursive.
diffs = {{DIFF_EQUAL, 'x'}, {DIFF_DELETE, 'ca'}, {DIFF_EQUAL, 'c'},
{DIFF_DELETE, 'b'}, {DIFF_EQUAL, 'a'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'xca'}, {DIFF_DELETE, 'cba'}}, diffs)
end
function testDiffCleanupSemanticLossless()
-- Slide diffs to match logical boundaries.
-- Null case.
local diffs = {}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({}, diffs)
-- Blank lines.
diffs = {{DIFF_EQUAL, 'AAA\r\n\r\nBBB'}, {DIFF_INSERT, '\r\nDDD\r\n\r\nBBB'},
{DIFF_EQUAL, '\r\nEEE'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'AAA\r\n\r\n'},
{DIFF_INSERT, 'BBB\r\nDDD\r\n\r\n'}, {DIFF_EQUAL, 'BBB\r\nEEE'}}, diffs)
-- Line boundaries.
diffs = {{DIFF_EQUAL, 'AAA\r\nBBB'}, {DIFF_INSERT, ' DDD\r\nBBB'},
{DIFF_EQUAL, ' EEE'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'AAA\r\n'}, {DIFF_INSERT, 'BBB DDD\r\n'},
{DIFF_EQUAL, 'BBB EEE'}}, diffs)
-- Word boundaries.
diffs = {{DIFF_EQUAL, 'The c'}, {DIFF_INSERT, 'ow and the c'},
{DIFF_EQUAL, 'at.'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'The '}, {DIFF_INSERT, 'cow and the '},
{DIFF_EQUAL, 'cat.'}}, diffs)
-- Alphanumeric boundaries.
diffs = {{DIFF_EQUAL, 'The-c'}, {DIFF_INSERT, 'ow-and-the-c'},
{DIFF_EQUAL, 'at.'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'The-'}, {DIFF_INSERT, 'cow-and-the-'},
{DIFF_EQUAL, 'cat.'}}, diffs)
-- Hitting the start.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'ax'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'aax'}}, diffs)
-- Hitting the end.
diffs = {{DIFF_EQUAL, 'xa'}, {DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'a'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'xaa'}, {DIFF_DELETE, 'a'}}, diffs)
-- Sentence boundaries.
diffs = {{DIFF_EQUAL, 'The xxx. The '}, {DIFF_INSERT, 'zzz. The '},
{DIFF_EQUAL, 'yyy.'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'The xxx.'}, {DIFF_INSERT, ' The zzz.'},
{DIFF_EQUAL, ' The yyy.'}}, diffs)
end
function testDiffCleanupSemantic()
-- Cleanup semantically trivial equalities.
-- Null case.
local diffs = {}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({}, diffs)
-- No elimination #1.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, 'cd'}, {DIFF_EQUAL, '12'},
{DIFF_DELETE, 'e'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'ab'}, {DIFF_INSERT, 'cd'}, {DIFF_EQUAL, '12'},
{DIFF_DELETE, 'e'}}, diffs)
-- No elimination #2.
diffs = {{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'ABC'}, {DIFF_EQUAL, '1234'},
{DIFF_DELETE, 'wxyz'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'ABC'}, {DIFF_EQUAL, '1234'},
{DIFF_DELETE, 'wxyz'}}, diffs)
-- Simple elimination.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'b'}, {DIFF_DELETE, 'c'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'b'}}, diffs)
-- Backpass elimination.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_EQUAL, 'cd'}, {DIFF_DELETE, 'e'},
{DIFF_EQUAL, 'f'}, {DIFF_INSERT, 'g'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abcdef'}, {DIFF_INSERT, 'cdfg'}}, diffs)
-- Multiple eliminations.
diffs = {{DIFF_INSERT, '1'}, {DIFF_EQUAL, 'A'}, {DIFF_DELETE, 'B'},
{DIFF_INSERT, '2'}, {DIFF_EQUAL, '_'}, {DIFF_INSERT, '1'},
{DIFF_EQUAL, 'A'}, {DIFF_DELETE, 'B'}, {DIFF_INSERT, '2'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'AB_AB'}, {DIFF_INSERT, '1A2_1A2'}}, diffs)
-- Word boundaries.
diffs = {{DIFF_EQUAL, 'The c'}, {DIFF_DELETE, 'ow and the c'},
{DIFF_EQUAL, 'at.'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_EQUAL, 'The '}, {DIFF_DELETE, 'cow and the '},
{DIFF_EQUAL, 'cat.'}}, diffs)
-- No overlap elimination.
diffs = {{DIFF_DELETE, 'abcxx'}, {DIFF_INSERT, 'xxdef'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abcxx'}, {DIFF_INSERT, 'xxdef'}}, diffs)
-- Overlap elimination.
diffs = {{DIFF_DELETE, 'abcxxx'}, {DIFF_INSERT, 'xxxdef'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_EQUAL, 'xxx'}, {DIFF_INSERT, 'def'}}, diffs)
-- Reverse overlap elimination.
diffs = {{DIFF_DELETE, 'xxxabc'}, {DIFF_INSERT, 'defxxx'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_INSERT, 'def'}, {DIFF_EQUAL, 'xxx'}, {DIFF_DELETE, 'abc'}}, diffs)
-- Two overlap eliminations.
diffs = {{DIFF_DELETE, 'abcd1212'}, {DIFF_INSERT, '1212efghi'}, {DIFF_EQUAL, '----'}, {DIFF_DELETE, 'A3'}, {DIFF_INSERT, '3BC'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abcd'}, {DIFF_EQUAL, '1212'}, {DIFF_INSERT, 'efghi'}, {DIFF_EQUAL, '----'}, {DIFF_DELETE, 'A'}, {DIFF_EQUAL, '3'}, {DIFF_INSERT, 'BC'}}, diffs)
end
function testDiffCleanupEfficiency()
-- Cleanup operationally trivial equalities.
local diffs
dmp.settings{Diff_EditCost = 4}
-- Null case.
diffs = {}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({}, diffs)
-- No elimination.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'wxyz'},
{DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'},
{DIFF_EQUAL, 'wxyz'}, {DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}, diffs)
-- Four-edit elimination.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'xyz'},
{DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'abxyzcd'},
{DIFF_INSERT, '12xyz34'}
}, diffs)
-- Three-edit elimination.
diffs = {
{DIFF_INSERT, '12'},
{DIFF_EQUAL, 'x'},
{DIFF_DELETE, 'cd'},
{DIFF_INSERT, '34'}
}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'xcd'},
{DIFF_INSERT, '12x34'}
}, diffs)
-- Backpass elimination.
diffs = {
{DIFF_DELETE, 'ab'},
{DIFF_INSERT, '12'},
{DIFF_EQUAL, 'xy'},
{DIFF_INSERT, '34'},
{DIFF_EQUAL, 'z'},
{DIFF_DELETE, 'cd'},
{DIFF_INSERT, '56'}
}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'abxyzcd'},
{DIFF_INSERT, '12xy34z56'}
}, diffs)
-- High cost elimination.
dmp.settings{Diff_EditCost = 5}
diffs = {
{DIFF_DELETE, 'ab'},
{DIFF_INSERT, '12'},
{DIFF_EQUAL, 'wxyz'},
{DIFF_DELETE, 'cd'},
{DIFF_INSERT, '34'}
}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'abwxyzcd'},
{DIFF_INSERT, '12wxyz34'}
}, diffs)
dmp.settings{Diff_EditCost = 4}
end
function testDiffPrettyHtml()
-- Pretty print.
local diffs = {
{DIFF_EQUAL, 'a\n'},
{DIFF_DELETE, '<B>b</B>'},
{DIFF_INSERT, 'c&d'}
}
assertEquals(
'<span>a¶<br></span>'
.. '<del style="background:#ffe6e6;"><B>b</B>'
.. '</del><ins style="background:#e6ffe6;">c&d</ins>',
dmp.diff_prettyHtml(diffs)
)
end
function testDiffText()
-- Compute the source and destination texts.
local diffs = {
{DIFF_EQUAL, 'jump'},
{DIFF_DELETE, 's'},
{DIFF_INSERT, 'ed'},
{DIFF_EQUAL, ' over '},
{DIFF_DELETE, 'the'},
{DIFF_INSERT, 'a'},
{DIFF_EQUAL, ' lazy'}
}
assertEquals('jumps over the lazy', dmp.diff_text1(diffs))
assertEquals('jumped over a lazy', dmp.diff_text2(diffs))
end
function testDiffDelta()
-- Convert a diff into delta string.
local diffs = {
{DIFF_EQUAL, 'jump'},
{DIFF_DELETE, 's'},
{DIFF_INSERT, 'ed'},
{DIFF_EQUAL, ' over '},
{DIFF_DELETE, 'the'},
{DIFF_INSERT, 'a'},
{DIFF_EQUAL, ' lazy'},
{DIFF_INSERT, 'old dog'}
}
local text1 = dmp.diff_text1(diffs)
assertEquals('jumps over the lazy', text1)
local delta = dmp.diff_toDelta(diffs)
assertEquals('=4\t-1\t+ed\t=6\t-3\t+a\t=5\t+old dog', delta)
-- Convert delta string into a diff.
assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta))
-- Generates error (19 ~= 20).
success, result = pcall(dmp.diff_fromDelta, text1 .. 'x', delta)
assertEquals(false, success)
-- Generates error (19 ~= 18).
success, result = pcall(dmp.diff_fromDelta, string.sub(text1, 2), delta)
assertEquals(false, success)
-- Generates error (%c3%xy invalid Unicode).
success, result = pcall(dmp.patch_fromDelta, '', '+%c3%xy')
assertEquals(false, success)
--[[
-- Test deltas with special characters.
-- LUANOTE: No ability to handle Unicode.
diffs = {{DIFF_EQUAL, '\u0680 \000 \t %'}, {DIFF_DELETE, '\u0681 \x01 \n ^'}, {DIFF_INSERT, '\u0682 \x02 \\ |'}}
text1 = dmp.diff_text1(diffs)
assertEquals('\u0680 \x00 \t %\u0681 \x01 \n ^', text1)
delta = dmp.diff_toDelta(diffs)
assertEquals('=7\t-7\t+%DA%82 %02 %5C %7C', delta)
--]]
-- Convert delta string into a diff.
assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta))
-- Verify pool of unchanged characters.
diffs = {
{DIFF_INSERT, 'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # '}
}
local text2 = dmp.diff_text2(diffs)
assertEquals(
'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # ',
text2
)
delta = dmp.diff_toDelta(diffs)
assertEquals(
'+A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # ',
delta
)
-- Convert delta string into a diff.
assertEquivalent(diffs, dmp.diff_fromDelta('', delta))
end
function testDiffXIndex()
-- Translate a location in text1 to text2.
-- Translation on equality.
assertEquals(6, dmp.diff_xIndex({
{DIFF_DELETE, 'a'},
{DIFF_INSERT, '1234'},
{DIFF_EQUAL, 'xyz'}
}, 3))
-- Translation on deletion.
assertEquals(2, dmp.diff_xIndex({
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '1234'},
{DIFF_EQUAL, 'xyz'}
}, 4))
end
function testDiffLevenshtein()
-- Levenshtein with trailing equality.
assertEquals(4, dmp.diff_levenshtein({
{DIFF_DELETE, 'abc'},
{DIFF_INSERT, '1234'},
{DIFF_EQUAL, 'xyz'}
}))
-- Levenshtein with leading equality.
assertEquals(4, dmp.diff_levenshtein({
{DIFF_EQUAL, 'xyz'},
{DIFF_DELETE, 'abc'},
{DIFF_INSERT, '1234'}
}))
-- Levenshtein with middle equality.
assertEquals(7, dmp.diff_levenshtein({
{DIFF_DELETE, 'abc'},
{DIFF_EQUAL, 'xyz'},
{DIFF_INSERT, '1234'}
}))
end
function testDiffBisect()
-- Normal.
local a = 'cat'
local b = 'map'
-- Since the resulting diff hasn't been normalized, it would be ok if
-- the insertion and deletion pairs are swapped.
-- If the order changes, tweak this test as required.
assertEquivalent({
{DIFF_DELETE, 'c'},
{DIFF_INSERT, 'm'},
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, 't'},
{DIFF_INSERT, 'p'}
}, dmp.diff_bisect(a, b, 2 ^ 31))
-- Timeout.
assertEquivalent({
{DIFF_DELETE, 'cat'},
{DIFF_INSERT, 'map'}
}, dmp.diff_bisect(a, b, 0))
end
function testDiffMain()
-- Perform a trivial diff.
local a,b
-- Null case.
assertEquivalent({}, dmp.diff_main('', '', false))
-- Equality.
assertEquivalent({
{DIFF_EQUAL, 'abc'}
}, dmp.diff_main('abc', 'abc', false))
-- Simple insertion.
assertEquivalent({
{DIFF_EQUAL, 'ab'},
{DIFF_INSERT, '123'},
{DIFF_EQUAL, 'c'}
}, dmp.diff_main('abc', 'ab123c', false))
-- Simple deletion.
assertEquivalent({
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '123'},
{DIFF_EQUAL, 'bc'}
}, dmp.diff_main('a123bc', 'abc', false))
-- Two insertions.
assertEquivalent({
{DIFF_EQUAL, 'a'},
{DIFF_INSERT, '123'},
{DIFF_EQUAL, 'b'},
{DIFF_INSERT, '456'},
{DIFF_EQUAL, 'c'}
}, dmp.diff_main('abc', 'a123b456c', false))
-- Two deletions.
assertEquivalent({
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '123'},
{DIFF_EQUAL, 'b'},
{DIFF_DELETE, '456'},
{DIFF_EQUAL, 'c'}
}, dmp.diff_main('a123b456c', 'abc', false))
-- Perform a real diff.
-- Switch off the timeout.
dmp.settings{ Diff_Timeout=0 }
-- Simple cases.
assertEquivalent({
{DIFF_DELETE, 'a'},
{DIFF_INSERT, 'b'}
}, dmp.diff_main('a', 'b', false))
assertEquivalent({
{DIFF_DELETE, 'Apple'},
{DIFF_INSERT, 'Banana'},
{DIFF_EQUAL, 's are a'},
{DIFF_INSERT, 'lso'},
{DIFF_EQUAL, ' fruit.'}
}, dmp.diff_main('Apples are a fruit.', 'Bananas are also fruit.', false))
--[[
-- LUANOTE: No ability to handle Unicode.
assertEquivalent({
{DIFF_DELETE, 'a'},
{DIFF_INSERT, '\u0680'},
{DIFF_EQUAL, 'x'},
{DIFF_DELETE, '\t'},
{DIFF_INSERT, '\0'}
}, dmp.diff_main('ax\t', '\u0680x\0', false))
]]--
-- Overlaps.
assertEquivalent({
{DIFF_DELETE, '1'},
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, 'y'},
{DIFF_EQUAL, 'b'},
{DIFF_DELETE, '2'},
{DIFF_INSERT, 'xab'}
}, dmp.diff_main('1ayb2', 'abxab', false))
assertEquivalent({
{DIFF_INSERT, 'xaxcx'},
{DIFF_EQUAL, 'abc'},
{DIFF_DELETE, 'y'}
}, dmp.diff_main('abcy', 'xaxcxabc', false))
assertEquivalent({
{DIFF_DELETE, 'ABCD'},
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '='},
{DIFF_INSERT, '-'},
{DIFF_EQUAL, 'bcd'},
{DIFF_DELETE, '='},
{DIFF_INSERT, '-'},
{DIFF_EQUAL, 'efghijklmnopqrs'},
{DIFF_DELETE, 'EFGHIJKLMNOefg'}
}, dmp.diff_main('ABCDa=bcd=efghijklmnopqrsEFGHIJKLMNOefg',
'a-bcd-efghijklmnopqrs', false))
-- Large equality.
assertEquivalent({
{DIFF_INSERT, ' '},
{DIFF_EQUAL, 'a'},
{DIFF_INSERT, 'nd'},
{DIFF_EQUAL, ' [[Pennsylvania]]'},
{DIFF_DELETE, ' and [[New'}
}, dmp.diff_main('a [[Pennsylvania]] and [[New',
' and [[Pennsylvania]]', false))
-- Timeout.
dmp.settings{Diff_Timeout = 0.1} -- 100ms
-- Increase the text lengths by 1024 times to ensure a timeout.
a = string.rep([[
`Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
]], 1024)
b = string.rep([[
I am the very model of a modern major general,
I've information vegetable, animal, and mineral,
I know the kings of England, and I quote the fights historical,
From Marathon to Waterloo, in order categorical.
]], 1024)
local startTime = os.clock()
dmp.diff_main(a, b)
local endTime = os.clock()
-- Test that we took at least the timeout period.
assertTrue(0.1 <= endTime - startTime)
-- Test that we didn't take forever (be forgiving).
-- Theoretically this test could fail very occasionally if the
-- OS task swaps or locks up for a second at the wrong moment.
assertTrue(0.1 * 2 > endTime - startTime)
dmp.settings{Diff_Timeout = 0}
-- Test the linemode speedup.
-- Must be long to pass the 100 char cutoff.
-- Simple line-mode.
a = string.rep('1234567890\n', 13)
b = string.rep('abcdefghij\n', 13)
assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true))
-- Single line-mode.
a = string.rep('1234567890', 13)
b = string.rep('abcdefghij', 13)
assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true))
-- Overlap line-mode.
a = string.rep('1234567890\n', 13)
b = [[
abcdefghij
1234567890
1234567890
1234567890
abcdefghij
1234567890
1234567890
1234567890
abcdefghij
1234567890
1234567890
1234567890
abcdefghij
]]
local texts_linemode = diff_rebuildtexts(dmp.diff_main(a, b, true))
local texts_textmode = diff_rebuildtexts(dmp.diff_main(a, b, false))
assertEquivalent(texts_textmode, texts_linemode)
-- Test null inputs.
success, result = pcall(dmp.diff_main, nil, nil)
assertEquals(false, success)
end
-- MATCH TEST FUNCTIONS
function testMatchAlphabet()
-- Initialise the bitmasks for Bitap.
-- Unique.
assertEquivalent({a=4, b=2, c=1}, dmp.match_alphabet('abc'))
-- Duplicates.
assertEquivalent({a=37, b=18, c=8}, dmp.match_alphabet('abcaba'))
end
function testMatchBitap()
-- Bitap algorithm.
dmp.settings{Match_Distance=100, Match_Threshold=0.5}
-- Exact matches.
assertEquals(6, dmp.match_bitap('abcdefghijk', 'fgh', 6))
assertEquals(6, dmp.match_bitap('abcdefghijk', 'fgh', 1))
-- Fuzzy matches.
assertEquals(5, dmp.match_bitap('abcdefghijk', 'efxhi', 1))
assertEquals(3, dmp.match_bitap('abcdefghijk', 'cdefxyhijk', 6))
assertEquals(-1, dmp.match_bitap('abcdefghijk', 'bxy', 2))
-- Overflow.
assertEquals(3, dmp.match_bitap('123456789xx0', '3456789x0', 3))
-- Threshold test.
dmp.settings{Match_Threshold = 0.4}
assertEquals(5, dmp.match_bitap('abcdefghijk', 'efxyhi', 2))
dmp.settings{Match_Threshold = 0.3}
assertEquals(-1, dmp.match_bitap('abcdefghijk', 'efxyhi', 2))
dmp.settings{Match_Threshold = 0.0}
assertEquals(2, dmp.match_bitap('abcdefghijk', 'bcdef', 2))
dmp.settings{Match_Threshold = 0.5}
-- Multiple select.
assertEquals(1, dmp.match_bitap('abcdexyzabcde', 'abccde', 4))
assertEquals(9, dmp.match_bitap('abcdexyzabcde', 'abccde', 6))
-- Distance test.
dmp.settings{Match_Distance = 10} -- Strict location.
assertEquals(-1,
dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 25))
assertEquals(1,
dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdxxefg', 2))
dmp.settings{Match_Distance = 1000} -- Loose location.
assertEquals(1,
dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 25))
end
function testMatchMain()
-- Full match.
-- Shortcut matches.
assertEquals(1, dmp.match_main('abcdef', 'abcdef', 1000))
assertEquals(-1, dmp.match_main('', 'abcdef', 2))
assertEquals(4, dmp.match_main('abcdef', '', 4))
assertEquals(4, dmp.match_main('abcdef', 'de', 4))
-- Beyond end match.
assertEquals(4, dmp.match_main("abcdef", "defy", 5))
-- Oversized pattern.
assertEquals(1, dmp.match_main("abcdef", "abcdefy", 1))
-- Complex match.
assertEquals(5, dmp.match_main(
'I am the very model of a modern major general.',
' that berry ',
6
))
-- Test null inputs.
success, result = pcall(dmp.match_main, nil, nil, 0)
assertEquals(false, success)
end
-- PATCH TEST FUNCTIONS
function testPatchObj()
-- Patch Object.
local p = dmp.new_patch_obj()
p.start1 = 21
p.start2 = 22
p.length1 = 18
p.length2 = 17
p.diffs = {
{DIFF_EQUAL, 'jump'},
{DIFF_DELETE, 's'},
{DIFF_INSERT, 'ed'},
{DIFF_EQUAL, ' over '},
{DIFF_DELETE, 'the'},
{DIFF_INSERT, 'a'},
{DIFF_EQUAL, '\nlaz'}
}
local strp = tostring(p)
assertEquals(
'@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n',
strp
)
end
function testPatchFromText()
local strp
strp = ''
assertEquivalent({}, dmp.patch_fromText(strp))
strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n'
assertEquals(strp, tostring(dmp.patch_fromText(strp)[1]))
assertEquals(
'@@ -1 +1 @@\n-a\n+b\n',
tostring(dmp.patch_fromText('@@ -1 +1 @@\n-a\n+b\n')[1])
)
assertEquals(
'@@ -1,3 +0,0 @@\n-abc\n',
tostring(dmp.patch_fromText('@@ -1,3 +0,0 @@\n-abc\n')[1])
)
assertEquals(
'@@ -0,0 +1,3 @@\n+abc\n',
tostring(dmp.patch_fromText('@@ -0,0 +1,3 @@\n+abc\n')[1])
)
-- Generates error.
success, result = pcall(dmp.patch_fromText, 'Bad\nPatch\n')
assertEquals(false, success)
end
function testPatchToText()
local strp, p
strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'
p = dmp.patch_fromText(strp)
assertEquals(strp, dmp.patch_toText(p))
strp = '@@ -1,9 +1,9 @@\n-f\n+F\n oo+fooba\n'
.. '@@ -7,9 +7,9 @@\n obar\n-,\n+.\n tes\n'
p = dmp.patch_fromText(strp)
assertEquals(strp, dmp.patch_toText(p))
end
function testPatchAddContext()
local p
dmp.settings{Patch_Margin = 4}
p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps over the lazy dog.')
assertEquals(
'@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n',
tostring(p)
)
-- Same, but not enough trailing context.
p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps.')
assertEquals(
'@@ -17,10 +17,16 @@\n fox \n-jump\n+somersault\n s.\n',
tostring(p)
)
-- Same, but not enough leading context.
p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps.')
assertEquals('@@ -1,7 +1,8 @@\n Th\n-e\n+at\n qui\n', tostring(p))
-- Same, but with ambiguity.
p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps. The quick brown fox crashes.')
assertEquals('@@ -1,27 +1,28 @@\n Th\n-e\n+at\n quick brown fox jumps. \n', tostring(p))
end
function testPatchMake()
-- Null case.
local patches = dmp.patch_make('', '')
assertEquals('', dmp.patch_toText(patches))
local text1 = 'The quick brown fox jumps over the lazy dog.'
local text2 = 'That quick brown fox jumped over a lazy dog.'
-- Text2+Text1 inputs.
local expectedPatch = '@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n'
.. '@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n'
-- The second patch must be "-21,17 +21,18",
-- not "-22,17 +21,18" due to rolling context.
patches = dmp.patch_make(text2, text1)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Text1+Text2 inputs.
expectedPatch = '@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n'
.. '@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'
patches = dmp.patch_make(text1, text2)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Diff input.
local diffs = dmp.diff_main(text1, text2, false)
patches = dmp.patch_make(diffs)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Text1+Diff inputs.
patches = dmp.patch_make(text1, diffs)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Text1+Text2+Diff inputs (deprecated).
patches = dmp.patch_make(text1, text2, diffs)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Character encoding.
patches = dmp.patch_make('`1234567890-=[]\\;\',./', '~!@#$%^&*()_+{}|="<>?')
assertEquals('@@ -1,21 +1,21 @@\n'
.. '-%601234567890-=%5B%5D%5C;\',./\n'
.. '+~!@#$%25%5E&*()_+%7B%7D%7C=%22%3C%3E?\n', dmp.patch_toText(patches))
-- Character decoding.
diffs = {
{DIFF_DELETE, '`1234567890-=[]\\;\',./'},
{DIFF_INSERT, '~!@#$%^&*()_+{}|="<>?'}
}
assertEquivalent(diffs, dmp.patch_fromText(
'@@ -1,21 +1,21 @@'
.. '\n-%601234567890-=%5B%5D%5C;\',./'
.. '\n+~!@#$%25%5E&*()_+%7B%7D%7C=%22%3C%3E?\n'
)[1].diffs)
-- Long string with repeats.
text1 = string.rep('abcdef', 100)
text2 = text1 .. '123'
expectedPatch = '@@ -573,28 +573,31 @@\n'
.. ' cdefabcdefabcdefabcdefabcdef\n+123\n'
patches = dmp.patch_make(text1, text2)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Test null inputs.
success, result = pcall(dmp.patch_make, nil, nil)
assertEquals(false, success)
end
function testPatchSplitMax()
-- Assumes that dmp.Match_MaxBits is 32.
local patches = dmp.patch_make('abcdefghijklmnopqrstuvwxyz01234567890',
'XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0')
dmp.patch_splitMax(patches)
assertEquals('@@ -1,32 +1,46 @@\n+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\n uv\n+X\n wx\n+X\n yz\n+X\n 012345\n@@ -25,13 +39,18 @@\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n', dmp.patch_toText(patches))
patches = dmp.patch_make('abcdef1234567890123456789012345678901234567890123456789012345678901234567890uvwxyz', 'abcdefuvwxyz')
local oldToText = dmp.patch_toText(patches)
dmp.patch_splitMax(patches)
assertEquals(oldToText, dmp.patch_toText(patches))
patches = dmp.patch_make('1234567890123456789012345678901234567890123456789012345678901234567890', 'abc')
dmp.patch_splitMax(patches)
assertEquals('@@ -1,32 +1,4 @@\n-1234567890123456789012345678\n 9012\n@@ -29,32 +1,4 @@\n-9012345678901234567890123456\n 7890\n@@ -57,14 +1,3 @@\n-78901234567890\n+abc\n', dmp.patch_toText(patches))
patches = dmp.patch_make('abcdefghij , h = 0 , t = 1 abcdefghij , h = 0 , t = 1 abcdefghij , h = 0 , t = 1', 'abcdefghij , h = 1 , t = 1 abcdefghij , h = 1 , t = 1 abcdefghij , h = 0 , t = 1')
dmp.patch_splitMax(patches)
assertEquals('@@ -2,32 +2,32 @@\n bcdefghij , h = \n-0\n+1\n , t = 1 abcdef\n@@ -29,32 +29,32 @@\n bcdefghij , h = \n-0\n+1\n , t = 1 abcdef\n', dmp.patch_toText(patches))
end
function testPatchAddPadding()
-- Both edges full.
local patches = dmp.patch_make('', 'test')
assertEquals('@@ -0,0 +1,4 @@\n+test\n', dmp.patch_toText(patches))
dmp.patch_addPadding(patches)
assertEquals('@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n', dmp.patch_toText(patches))
-- Both edges partial.
patches = dmp.patch_make('XY', 'XtestY')
assertEquals('@@ -1,2 +1,6 @@\n X\n+test\n Y\n', dmp.patch_toText(patches))
dmp.patch_addPadding(patches)
assertEquals('@@ -2,8 +2,12 @@\n %02%03%04X\n+test\n Y%01%02%03\n', dmp.patch_toText(patches))
-- Both edges none.
patches = dmp.patch_make('XXXXYYYY', 'XXXXtestYYYY')
assertEquals('@@ -1,8 +1,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches))
dmp.patch_addPadding(patches)
assertEquals('@@ -5,8 +5,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches))
end
function testPatchApply()
local patches
dmp.settings{Match_Distance = 1000}
dmp.settings{Match_Threshold = 0.5}
dmp.settings{Patch_DeleteThreshold = 0.5}
-- Null case.
patches = dmp.patch_make('', '')
assertEquivalent({'Hello world.', {}},
{dmp.patch_apply(patches, 'Hello world.')})
-- Exact match.
patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.',
'That quick brown fox jumped over a lazy dog.')
assertEquivalent(
{'That quick brown fox jumped over a lazy dog.', {true, true}},
{dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.')})
-- Partial match.
assertEquivalent(
{'That quick red rabbit jumped over a tired tiger.', {true, true}},
{dmp.patch_apply(patches, 'The quick red rabbit jumps over the tired tiger.')})
-- Failed match.
assertEquivalent(
{'I am the very model of a modern major general.', {false, false}},
{dmp.patch_apply(patches, 'I am the very model of a modern major general.')})
-- Big delete, small change.
patches = dmp.patch_make(
'x1234567890123456789012345678901234567890123456789012345678901234567890y',
'xabcy')
assertEquivalent({'xabcy', {true, true}}, {dmp.patch_apply(patches,
'x123456789012345678901234567890-----++++++++++-----'
.. '123456789012345678901234567890y')})
-- Big delete, big change 1.
patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789'
.. '012345678901234567890y', 'xabcy')
assertEquivalent({'xabc12345678901234567890'
.. '---------------++++++++++---------------'
.. '12345678901234567890y', {false, true}},
{dmp.patch_apply(patches, 'x12345678901234567890'
.. '---------------++++++++++---------------'
.. '12345678901234567890y'
)})
-- Big delete, big change 2.
dmp.settings{Patch_DeleteThreshold = 0.6}
patches = dmp.patch_make(
'x1234567890123456789012345678901234567890123456789'
.. '012345678901234567890y',
'xabcy'
)
assertEquivalent({'xabcy', {true, true}}, {dmp.patch_apply(
patches,
'x12345678901234567890---------------++++++++++---------------'
.. '12345678901234567890y'
)}
)
dmp.settings{Patch_DeleteThreshold = 0.5}
-- Compensate for failed patch.
dmp.settings{Match_Threshold = 0, Match_Distance = 0}
patches = dmp.patch_make(
'abcdefghijklmnopqrstuvwxyz--------------------1234567890',
'abcXXXXXXXXXXdefghijklmnopqrstuvwxyz--------------------'
.. '1234567YYYYYYYYYY890'
)
assertEquivalent({
'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567YYYYYYYYYY890',
{false, true}
}, {dmp.patch_apply(
patches,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567890'
)})
dmp.settings{Match_Threshold = 0.5}
dmp.settings{Match_Distance = 1000}
-- No side effects.
patches = dmp.patch_make('', 'test')
local patchstr = dmp.patch_toText(patches)
dmp.patch_apply(patches, '')
assertEquals(patchstr, dmp.patch_toText(patches))
-- No side effects with major delete.
patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.',
'Woof')
patchstr = dmp.patch_toText(patches)
dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.')
assertEquals(patchstr, dmp.patch_toText(patches))
-- Edge exact match.
patches = dmp.patch_make('', 'test')
assertEquivalent({'test', {true}}, {dmp.patch_apply(patches, '')})
-- Near edge exact match.
patches = dmp.patch_make('XY', 'XtestY')
assertEquivalent({'XtestY', {true}}, {dmp.patch_apply(patches, 'XY')})
-- Edge partial match.
patches = dmp.patch_make('y', 'y123')
assertEquivalent({'x123', {true}}, {dmp.patch_apply(patches, 'x')})
end
function runTests()
local passed = 0
local failed = 0
for name, func in pairs(_G) do
if (type(func) == 'function') and tostring(name):match("^test") then
local success, message = pcall(func)
if success then
print(name .. ' Ok.')
passed = passed + 1
else
print('** ' .. name .. ' FAILED: ' .. tostring(message))
failed = failed + 1
end
end
end
print('Tests passed: ' .. passed)
print('Tests failed: ' .. failed)
if failed ~= 0 then
os.exit(1)
end
end
runTests()
| apache-2.0 |
tridge/ardupilot | libraries/AP_Scripting/examples/OOP_example.lua | 9 | 3279 | -- this is an example of how to do object oriented programming in Lua
function constrain(v, minv, maxv)
-- constrain a value between two limits
if v < minv then
return minv
end
if v > maxv then
return maxv
end
return v
end
--[[
a PI controller with feed-forward implemented as a Lua object, using
closure style object
--]]
local function PIFF(kFF,kP,kI,iMax)
-- the new instance. You can put public variables inside this self
-- declaration if you want to
local self = {}
-- private fields as locals
local _kFF = kFF
local _kP = kP or 0.0
local _kI = kI or 0.0
local _kD = kD or 0.0
local _iMax = iMax
local _last_t = nil
local _log_data = {}
local _I = 0
local _counter = 0
-- update the controller.
function self.update(target, current)
local now = millis():tofloat() * 0.001
if not _last_t then
_last_t = now
end
local dt = now - _last_t
_last_t = now
local err = target - current
_counter = _counter + 1
local FF = _kFF * target
local P = _kP * err
_I = _I + _kI * err * dt
if _iMax then
_I = constrain(_I, -_iMax, _iMax)
end
local I = _I
local ret = FF + P + I
_log_data = { target, current, FF, P, I, ret }
return ret
end
-- log the controller internals
function self.log(name)
logger.write(name,'Targ,Curr,FF,P,I,Total','ffffff',table.unpack(_log_data))
end
-- return the instance
return self
end
--[[
another example of a PIFF controller as an object, this time using
metatables. Using metatables uses less memory and object creation is
faster, but access to variables is slower
--]]
local PIFF2 = {}
PIFF2.__index = PIFF2
function PIFF2.new(kFF,kP,kI,iMax)
-- the new instance. You can put public variables inside this self
-- declaration if you want to
local self = setmetatable({},PIFF2)
self.kFF = kFF
self.kP = kP
self.kI = kI
self.iMax = iMax
self.last_t = nil
self.log_data = {}
self.I = 0
self.counter = 0
return self
end
function PIFF2.update(self, target, current)
local now = millis():tofloat() * 0.001
if not self.last_t then
self.last_t = now
end
local dt = now - self.last_t
self.last_t = now
local err = target - current
self.counter = self.counter + 1
local FF = self.kFF * target
local P = self.kP * err
self.I = self.I + self.kI * err * dt
if self.iMax then
self.I = constrain(self.I, -self.iMax, self.iMax)
end
local ret = FF + P + self.I
self.log_data = { target, current, FF, P, self.I, ret }
return ret
end
function PIFF2.log(self, name)
logger.write(name,'Targ,Curr,FF,P,I,Total','ffffff',table.unpack(self.log_data))
end
--[[
declare two PI controllers, using one of each style. Note the use of new() for the metatables style
--]]
local PI_elevator = PIFF(1.1, 0.0, 0.0, 20.0)
local PI_rudder = PIFF2.new(1.1, 0.0, 0.0, 20.0)
function test()
-- note the different syntax for the two varients
elevator = PI_elevator.update(1.0, 0.5)
rudder = PI_rudder:update(2.0, 0.7)
PI_elevator.log("PEL")
PI_rudder:log("PRD")
gcs:send_text(0, "tick: " .. tostring(millis()))
return test, 500
end
return test()
| gpl-3.0 |
kidaa/turbo | spec/iostream_spec.lua | 5 | 21560 | --- Turbo.lua Unit test
--
-- Copyright 2013 John Abrahamsen
--
-- 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.
_G.__TURBO_USE_LUASOCKET__ = os.getenv("TURBO_USE_LUASOCKET") and true or false
local turbo = require 'turbo'
math.randomseed(turbo.util.gettimeofday())
describe("turbo.iostream Namespace", function()
-- Many of the tests rely on the fact that the TCPServer class
-- functions as expected...
describe("IOStream/SSLIOStream classes", function()
before_each(function()
-- Make sure we start with a fresh global IOLoop to
-- avoid random results.
_G.io_loop_instance = nil
end)
it("IOStream:connect, localhost", function()
local io = turbo.ioloop.IOLoop()
local port = math.random(10000,40000)
local connected = false
local failed = false
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
function Server:handle_stream(stream)
stream:close()
end
local srv = Server(io)
srv:listen(port)
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
stream:close()
io:close()
end,
function(err)
failed = true
error("Could not connect.")
end)
end)
io:wait(2)
srv:stop()
assert.truthy(connected)
assert.falsy(failed)
end)
it("IOStream:read_bytes", function()
local io = turbo.ioloop.instance()
local port = math.random(10000,40000)
local connected = false
local data = false
local bytes = turbo.structs.buffer()
for i = 1, 1024*1024 do
bytes:append_luastr_right(string.char(math.random(1, 128)))
end
bytes = tostring(bytes)
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
local srv
function Server:handle_stream(stream)
io:add_callback(function()
coroutine.yield (turbo.async.task(stream.write, stream, bytes))
stream:close()
srv:stop()
end)
end
srv = Server(io)
srv:listen(port)
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
local res = coroutine.yield (turbo.async.task(
stream.read_bytes,stream,1024*1024))
data = true
assert.equal(res, bytes)
stream:close()
io:close()
end,
function(err)
failed = true
io:close()
error("Could not connect.")
end)
end)
io:wait(2)
srv:stop()
assert.truthy(connected)
assert.truthy(data)
end)
it("IOStream:read_until", function()
local delim = "CRLF GALLORE\r\n\r\n\r\n\r\n\r"
local io = turbo.ioloop.instance()
local port = math.random(10000,40000)
local connected, failed = false, false
local data = false
local bytes = turbo.structs.buffer()
for i = 1, 1024*1024*5 do
bytes:append_luastr_right(string.char(math.random(1, 128)))
end
bytes:append_luastr_right(delim)
local bytes2 = tostring(bytes) -- Used to match correct delimiter cut.
for i = 1, 1024*1024 do
bytes:append_luastr_right(string.char(math.random(1, 128)))
end
bytes = tostring(bytes)
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
function Server:handle_stream(stream)
io:add_callback(function()
coroutine.yield (turbo.async.task(stream.write, stream, bytes))
stream:close()
end)
end
local srv = Server(io)
srv:listen(port)
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
assert.equal(stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
local res = coroutine.yield (turbo.async.task(
stream.read_until,stream,delim))
data = true
assert.truthy(res == bytes2)
stream:close()
io:close()
end,
function(err)
failed = true
io:close()
error("Could not connect.")
end), 0)
end)
io:wait(30)
srv:stop()
assert.falsy(failed)
assert.truthy(connected)
assert.truthy(data)
end)
it("IOStream:read_until_pattern", function()
local delim = "CRLF GALLORE\r\n\r\n\r\n\r\n\r"
local io = turbo.ioloop.instance()
local port = math.random(10000,40000)
local connected, failed = false, false
local data = false
local bytes = turbo.structs.buffer()
for i = 1, 1024*1024*5 do
bytes:append_luastr_right(string.char(math.random(1, 128)))
end
bytes:append_luastr_right(delim)
local bytes2 = tostring(bytes) -- Used to match correct delimiter cut.
for i = 1, 1024*1024 do
bytes:append_luastr_right(string.char(math.random(1, 128)))
end
bytes = tostring(bytes)
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
function Server:handle_stream(stream)
io:add_callback(function()
coroutine.yield (turbo.async.task(stream.write, stream, bytes))
stream:close()
end)
end
local srv = Server(io)
srv:listen(port)
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
assert.equal(stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
local res = coroutine.yield (turbo.async.task(
stream.read_until_pattern,stream,delim))
data = true
assert.truthy(res == bytes2)
stream:close()
io:close()
end,
function(err)
failed = true
io:close()
error("Could not connect.")
end), 0)
end)
io:wait(60)
srv:stop()
assert.falsy(failed)
assert.truthy(connected)
assert.truthy(data)
end)
it("IOStream:read_until_close", function()
local io = turbo.ioloop.instance()
local port = math.random(10000,40000)
local connected, failed = false, false
local data = false
local bytes = turbo.structs.buffer()
for i = 1, 1024*1024*5 do
bytes:append_luastr_right(string.char(math.random(1, 128)))
end
bytes = tostring(bytes)
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
function Server:handle_stream(stream)
io:add_callback(function()
coroutine.yield (turbo.async.task(stream.write, stream, bytes))
stream:close()
end)
end
local srv = Server(io)
srv:listen(port)
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
assert.equal(stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
local res = coroutine.yield (turbo.async.task(
stream.read_until_close,stream))
data = true
assert.truthy(stream:closed())
assert.truthy(res == bytes)
io:close()
end,
function(err)
failed = true
io:close()
error("Could not connect.")
end), 0)
end)
io:wait(30)
srv:stop()
assert.falsy(failed)
assert.truthy(connected)
assert.truthy(data)
end)
if turbo.platform.__LINUX__ then
it("IOStream:set_close_callback", function()
local io = turbo.ioloop.IOLoop()
local port = math.random(10000,40000)
local connected = false
local failed = false
local closed = false
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
function Server:handle_stream(stream)
stream:close()
closed = true
end
local srv = Server(io)
srv:listen(port)
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
stream:set_close_callback(function()
assert.truthy(closed)
io:close()
end)
end,
function(err)
failed = true
error("Could not connect.")
end)
end)
io:wait(10)
srv:stop()
assert.truthy(connected)
assert.falsy(failed)
assert.truthy(closed)
end)
it("IOStream:closed", function()
local io = turbo.ioloop.IOLoop()
local port = math.random(10000,40000)
local connected = false
local failed = false
local closed = false
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
function Server:handle_stream(stream)
assert.falsy(stream:closed())
stream:close()
closed = true
end
local srv = Server(io)
srv:listen(port, "127.0.0.1")
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
assert.falsy(stream:closed())
stream:set_close_callback(function()
assert.truthy(stream:closed())
assert.truthy(closed)
io:close()
end)
end,
function(err)
failed = true
error("Could not connect.")
end)
end)
io:wait(10)
srv:stop()
assert.truthy(connected)
assert.falsy(failed)
assert.truthy(closed)
end)
end
it("IOStream:writing", function()
local io = turbo.ioloop.instance()
local port = math.random(10000,40000)
local connected, failed = false, false
local data = false
local bytes = turbo.structs.buffer()
for i = 1, 1024*1024 do
bytes:append_luastr_right(string.char(math.random(1, 128)))
end
bytes = tostring(bytes)
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
function Server:handle_stream(stream)
io:add_callback(function()
assert.falsy(stream:writing())
stream:write(bytes, function()
assert.falsy(stream:writing())
stream:close()
end)
assert.truthy(stream:writing())
end)
end
local srv = Server(io)
srv:listen(port)
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
assert.equal(stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
local res = coroutine.yield (turbo.async.task(
stream.read_until_close,stream))
data = true
assert.truthy(stream:closed())
assert.truthy(res == bytes)
io:close()
end,
function(err)
failed = true
io:close()
error("Could not connect.")
end), 0)
end)
end)
it("IOStream:reading", function()
local io = turbo.ioloop.instance()
local port = math.random(10000,40000)
local connected, failed = false, false
local data = false
local bytes = turbo.structs.buffer()
for i = 1, 1024*1024 do
bytes:append_luastr_right(string.char(math.random(1, 128)))
end
bytes = tostring(bytes)
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
function Server:handle_stream(stream)
io:add_callback(function()
coroutine.yield (turbo.async.task(stream.write, stream, bytes))
stream:close()
end)
end
local srv = Server(io)
srv:listen(port)
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
assert.equal(stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
assert.falsy(stream:reading())
stream:read_until_close(function(res)
assert.falsy(stream:reading())
data = true
assert.truthy(stream:closed())
assert.truthy(res == bytes)
io:close()
end)
assert.truthy(stream:reading())
end,
function(err)
failed = true
io:close()
error("Could not connect.")
end), 0)
end)
io:wait(30)
srv:stop()
assert.falsy(failed)
assert.truthy(connected)
assert.truthy(data)
end)
it("IOStream streaming callbacks", function()
local io = turbo.ioloop.instance()
local port = math.random(10000,40000)
local connected, failed = false, false
local data = false
local bytes = turbo.structs.buffer()
local comp = turbo.structs.buffer()
local streamed = 0
-- Server
local Server = class("TestServer", turbo.tcpserver.TCPServer)
function Server:handle_stream(stream)
io:add_callback(function()
for i = 1, 10 do
local rand = turbo.structs.buffer()
for i = 1, 1024*1024 do
rand:append_luastr_right(string.char(math.random(1, 128)))
end
bytes:append_right(rand:get())
coroutine.yield (turbo.async.task(stream.write, stream, tostring(rand)))
end
stream:close()
end)
end
local srv = Server(io)
srv:listen(port)
io:add_callback(function()
-- Client
local fd = turbo.socket.new_nonblock_socket(turbo.socket.AF_INET,
turbo.socket.SOCK_STREAM,
0)
local stream = turbo.iostream.IOStream(fd, io)
assert.equal(stream:connect("127.0.0.1",
port,
turbo.socket.AF_INET,
function()
connected = true
stream:read_until_close(
function(res)
-- Will be called finally.
data = true
comp:append_luastr_right(res)
-- On close callback
io:close()
end, nil,
function(res)
-- Streaming callback
comp:append_luastr_right(res)
streamed = streamed + 1
end)
end,
function(err)
failed = true
io:close()
error("Could not connect.")
end), 0)
end)
io:wait(30)
srv:stop()
assert.falsy(failed)
assert.truthy(connected)
assert.truthy(data)
assert.truthy(tostring(comp) == tostring(bytes))
assert.truthy(streamed > 1)
end)
end)
end) | apache-2.0 |
jshackley/darkstar | scripts/zones/Arrapago_Reef/npcs/qm2.lua | 30 | 1330 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: ??? (Spawn Velionis(ZNM T1))
-- @pos 311 -3 27 54
-----------------------------------
package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Arrapago_Reef/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local mobID = 16998872;
if (trade:hasItemQty(2600,1) and trade:getItemCount() == 1) then -- Trade Golden Teeth
if (GetMobAction(mobID) == ACTION_NONE) then
player:tradeComplete();
SpawnMob(mobID):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Shrike78/Shilke2D | Shilke2D/Texture/TextureAtlasComposer.lua | 1 | 2157 | --[[---
TextureAtlasComposer implements ITextureAtlas and allows to work with different atlas textures
without caring about how textures are grouped together.
It's possible in this way to use logical atlas where texture are larger than
Texture.MAX_WIDTH * Texture.MAX_HEIGHT
--]]
TextureAtlasComposer = class(nil, ITextureAtlas)
function TextureAtlasComposer:init()
self.atlases = {}
end
---Clears inner structs and disposes all the added atlas
function TextureAtlasComposer:dispose()
self:clear(true)
end
--[[---
Adds a new atlas
@tparam ITextureAtlas atlas the atlas to be added
@treturn bool success. Doesn't add the same atlas twice
--]]
function TextureAtlasComposer:addAtlas(atlas)
local ownership = ownership ~= false
if table.find(self.atlases, atlas) == 0 then
self.atlases[#self.atlases+1] = atlas
return true
end
return false
end
--[[---
Removes the atlas from the list of composed atlases
@tparam ITextureAtlas atlas the atlas to remove
@treturn ITextureAtlas the removed atlas. nil if not present
--]]
function TextureAtlasComposer:removeAtlas(atlas)
return table.removeObj(self.atlases, atlas)
end
--[[---
Removes all the atlas and optionally dispose them
@tparam[opt=false] bool dispose if to dispose or not removed atlases
--]]
function TextureAtlasComposer:clear(dispose)
if dispose then
for _,atlas in ipairs(self.atlases) do
atlas:dispose()
end
end
table.clear(self.atlases)
end
--[[---
Returns all the regions sorted by name, that begin with "prefix".
If no prefix is provided it returns all the regions
@param prefix optional, prefix to select region names
@return list of regions
--]]
function TextureAtlasComposer:getSortedNames(prefix)
local sortedRegions = {}
for _,atlas in ipairs(self.atlases) do
table.extend(sortedRegions, atlas:getSortedNames(prefix))
end
table.sort(sortedRegions)
return sortedRegions
end
--if "name" is a registered named region, it get the referenced atlas
--and returns the subtexture
function TextureAtlasComposer:getTexture(name)
for _,atlas in ipairs(self.atlases) do
local t = atlas:getTexture(name)
if t then
return t
end
end
return nil
end
| mit |
jshackley/darkstar | scripts/globals/treasure.lua | 18 | 19457 | -------------------------------------------------
-- Treasure functions
-- Info from:
-- http://wiki.ffxiclopedia.org/wiki/Picking_your_Coffers_and_Chests
-- http://ffxi.allakhazam.com/db/jobs.html?fjob=10&mid=1086187627165365190&num=150
-------------------------------------------------
require("scripts/globals/settings");
-------------------------------------------------
-- THF tools/keys & their chance increment
-------------------------------------------------
skeletonKey = 0x45B; -- 1115
livingKey = 0x3FF; -- 1023
thftools = 0x3FE; -- 1022
SK_SUCCESS_INCREMENT = 0.2
LK_SUCCESS_INCREMENT = 0.15
TTK_SUCCESS_INCREMENT = 0.1
---------------------------------------
-- Spawn Mimic
---------------------------------------
function spawnMimic(zone,npc,player)
-- zone,mobid
mimic = {147,17379783,
153,17404338,
151,17396144,
161,17436965,
197,17584426,
160,17432583,
195,17576271,
200,17596728,
205,17617157,
174,17490230,
150,17391805,
12,16826564,
208,17629190,
130,17309979,
176,17498564,
159,17428497,
169,17469761,
177,17502567};
for nb = 1, table.getn(mimic), 2 do
if (zone == mimic[nb]) then
SpawnMob(mimic[nb + 1],120):updateEnmity(player);
setMobPos(mimic[nb + 1],npc:getXPos(),npc:getYPos(),npc:getZPos(),npc:getRotPos());
break;
else
printf("treasure.lua Mimic missing from zone %d", zone);
end
end
end;
---------------------------------------
-- Items
---------------------------------------
BurstScroll = 0x12D4;
MagesBalladII = 0x1383;
AdeptsRope = 0x33AE;
ElectrumHairpin = 0x3610;
PhalanxRing = 0x34CC;
GigantAxe = 0x4146;
TropicalShield = 0x3035;
ElectrumRing = 0x34CB;
EmethPick = 0x4122;
Falcastra = 0x4183;
LifeBelt = 0x33AF;
CougarBaghnakhs = 0x413E;
PyroRobe = 0x359B;
MothAxe = 0x414F;
ShieldEarring = 0x3435;
FrostShield = 0x3032;
ReplicaMaul = 0x4412;
BattleGloves = 0x31FF;
HeatRod = 0x42AF;
ForceBelt = 0x33A6;
FlameBoomerang = 0x438B;
SafeguardRing = 0x394E;
LightGauntlets = 0x3699;
HiReraiser = 0x104D;
PhysicalEarring = 0x3456;
VileElixir1 = 0x104F;
---------------------------------------
-- Gems
---------------------------------------
Amber = 0x32E;
Amethyst = 0x320;
Ametrine = 0x32B;
Aquamarine = 0x317;
Chrysoberyl = 0x321;
ClearTopaz = 0x329;
Fluorite = 0x32A;
Garnet = 0x316;
Goshenite = 0x328;
LapisLazuli = 0x31B;
LightOpal = 0x31C;
Moonstone = 0x322;
Onyx = 0x31F;
Painite = 0x31D;
Peridot = 0x314;
Sardonyx = 0x327;
Sphene = 0x32F;
Sunstone = 0x323;
Tourmaline = 0x326;
Turquoise = 0x31E;
Zircon = 0x325;
-------------------------------------------------
-- AF by Zone
-------------------------------------------------
function getAFbyZone(zone)
-- job#1, quest#1, item#1, job#2, quest#2, item#2, ...
if (zone == 147) then -- Beadeaux
-- Beast Jackcoat (BST), Gallant Breeches (PLD), Temple Cyclas (MNK)
return {9,BORGHERTZ_S_WILD_HANDS,12646,
7,BORGHERTZ_S_STALWART_HANDS,14220,
2,BORGHERTZ_S_STRIKING_HANDS,12639};
elseif (zone == 150) then -- Monastic Cavern
-- Chaos Flanchard (DRK), Hunter's Jerkin (RNG), Wizard's Coat (BLM)
return { 8,BORGHERTZ_S_SHADOWY_HANDS,14221,
11,BORGHERTZ_S_CHASING_HANDS,12648,
4,BORGHERTZ_S_SORCEROUS_HANDS,12641};
elseif (zone == 151) then -- Castle Oztroja
-- Chaos Cuirass(DRK), Choral Cannions (BRD), Rogue's Culottes (THF), Warlock's Tabard (RDM)
return { 8,BORGHERTZ_S_SHADOWY_HANDS,12645,
10,BORGHERTZ_S_HARMONIOUS_HANDS,14223,
6,BORGHERTZ_S_SNEAKY_HANDS,14219,
5,BORGHERTZ_S_VERMILLION_HANDS,12642};
elseif (zone == 153) then -- The Boyahda Tree
-- Ninja Hatsuburi (NIN)
return {13,BORGHERTZ_S_LURKING_HANDS,13869};
elseif (zone == 159) then -- Temple of Uggalepih
-- Evoker's Doublet (SMN), Myochin Domaru (SAM)
return {15,BORGHERTZ_S_CALLING_HANDS,12650,
12,BORGHERTZ_S_LOYAL_HANDS,13781};
elseif (zone == 161) then -- Castle Zvahl Baileys
-- Fighter's Cuisses (WAR), Rogue's Vest (THF)
return {1,BORGHERTZ_S_WARRING_HANDS,14214,
6,BORGHERTZ_S_SNEAKY_HANDS,12643};
elseif (zone == 169) then -- Toraimarai Canal
-- Evoker's Pigaches (SMN)
return {15,BORGHERTZ_S_CALLING_HANDS,14103};
elseif (zone == 176) then -- Sea Serpent Grotto
-- Ninja Kyahan (NIN)
return {13,BORGHERTZ_S_LURKING_HANDS,14101};
elseif (zone == 195) then -- The eldieme Necropolis
-- Wizard's Tonban (BLM)
return {4,BORGHERTZ_S_SORCEROUS_HANDS,14217};
elseif (zone == 197) then -- Crawler's Nest
-- Choral Roundlet (BRD), Fighter's Mask (WAR), Healer's Pantaloons (WHM), Hunter's Braccae (RNG)
return {10,BORGHERTZ_S_HARMONIOUS_HANDS,13857,
1,BORGHERTZ_S_WARRING_HANDS,12511,
3,BORGHERTZ_S_HEALING_HANDS,14216,
11,BORGHERTZ_S_CHASING_HANDS,14224};
elseif (zone == 200) then -- Garlaige Citadel
-- Beast Helm (BST), Gallant Coronet (PLD), Healer's Cap (WHM), Temple Crown (MNK), Warlock's Tights (RDM)
return {9,BORGHERTZ_S_WILD_HANDS,12517,
7,BORGHERTZ_S_STALWART_HANDS,12515,
3,BORGHERTZ_S_HEALING_HANDS,13855,
2,BORGHERTZ_S_STRIKING_HANDS,12512,
5,BORGHERTZ_S_VERMILLION_HANDS,14218};
elseif (zone == 205) then -- Ifrit's Cauldron
-- Drachen Mail (DRG)
return {14,BORGHERTZ_S_DRAGON_HANDS,12649};
elseif (zone == 208) then -- Quicksand Caves
-- Drachen Greaves (DRG), Myochin Haidate (SAM)
return {14,BORGHERTZ_S_DRAGON_HANDS,14102,
12,BORGHERTZ_S_LOYAL_HANDS,14225};
end
end
---------------------------------------
-- Returns the success increment depending on the THF tool used.
---------------------------------------
function thfKeySuccess(trade,playerLVL,treasureLVL)
sk = trade:hasItemQty(skeletonKey,1);
lk = trade:hasItemQty(livingKey,1);
ttk = trade:hasItemQty(thftools,1);
success = 0;
if ( sk ) then
success = (playerLVL/treasureLVL) - 0.50 + SK_SUCCESS_INCREMENT;
elseif ( lk ) then
success = (playerLVL/treasureLVL) - 0.50 + LK_SUCCESS_INCREMENT;
elseif ( ttk ) then
success = (playerLVL/treasureLVL) - 0.50 + TTK_SUCCESS_INCREMENT;
end
return success;
end
---------------------------------------
-- Returns true if the key is a THF "key", false in other case.
---------------------------------------
function isTHFKey(trade)
sk = trade:hasItemQty(skeletonKey,1);
lk = trade:hasItemQty(livingKey,1);
ttk = trade:hasItemQty(thftools,1);
if ( sk or lk or ttk ) then
return true;
else
return false;
end
end
---------------------------------------
-- Chance calculation based on job, key used and lvl of the chest/coffer
---------------------------------------
function openChance(player,npc,trade,TreasureType,treasureLVL,minLVL,questItemNeeded)
success = 0;
chance_answer = {nil,nil}; -- {success%,messageType}
weak = player:getStatusEffect(EFFECT_WEAKNESS);
illu = player:getVar("["..player:getZoneID().."]".."Treasure_"..TreasureType);
-- SE impleted this in order to prevent coffer farming.
-- Noone in the same area can open more than 1 coffer per hour except for AF, maps or quests items.
if (weak ~= nil) then -- old code: os.time() <= weak
chance_answer = {-1,CHEST_WEAK};
elseif (os.time() < illu and questItemNeeded == 0) then
UpdateTreasureSpawnPoint(npc:getID());
if (TreasureType == "Chest") then
chance_answer = {-2,CHEST_ILLUSION};
elseif (TreasureType == "Coffer") then
if (isTHFKey(trade)) then
chance_answer = {-1,CHEST_ILLUSION}; -- if you used a THF tool you will lose it.
else
chance_answer = {-2,CHEST_ILLUSION}; -- if you traded a zone key droped from mobs you will keep the key
end
end
elseif (not(isTHFKey(trade))) then
chance_answer = {1,nil}; -- Zone Key is always 100% success
elseif (player:getMainJob() == 6 and player:getMainLvl() >= minLVL) then -- ifplayer is THF with level higher or equal than minimun lv for coffer/chest
success = thfKeySuccess(trade,player:getMainLvl(),treasureLVL);
chance_answer = {success,nil};
else
-- Player is not THF (as main job) or doesn't haven enough level to open the coffer
chance_answer = {-1,CHEST_FAIL};
end
return chance_answer;
end
function chestLoot(zone,npc)
--[[-----------------------------------------------
Chest Loot
---------------------------------------------------
---------------------------------------
-- Items
---------------------------------------
BurstScroll = 0x12D4;
MagesBalladII = 0x1383;
AdeptsRope = 0x33AE;
ElectrumHairpin = 0x3610;
PhalanxRing = 0x34CC;
GigantAxe = 0x4146;
TropicalShield = 0x3035;
ElectrumRing = 0x34CB;
EmethPick = 0x4122;
Falcastra = 0x4183;
LifeBelt = 0x33AF;
CougarBaghnakhs = 0x413E;
PyroRobe = 0x359B;
MothAxe = 0x414F;
ShieldEarring = 0x3435;
FrostShield = 0x3032;
ReplicaMaul = 0x4412;
BattleGloves = 0x31FF;
HeatRod = 0x42AF;
ForceBelt = 0x33A6;
FlameBoomerang = 0x438B;
SafeguardRing = 0x394E;
LightGauntlets = 0x3699;
HiReraiser = 0x104D;
PhysicalEarring = 0x3456;
VileElixir1 = 0x104F;
---------------------------------------
-- Gems
---------------------------------------
Amber = 0x32E;
Amethyst = 0x320;
Ametrine = 0x32B;
Aquamarine = 0x317;
Chrysoberyl = 0x321;
ClearTopaz = 0x329;
Fluorite = 0x32A;
Garnet = 0x316;
Goshenite = 0x328;
Jadeite = 0x310;
LapisLazuli = 0x31B;
LightOpal = 0x31C;
Moonstone = 0x322;
Onyx = 0x31F;
Painite = 0x31D;
Peridot = 0x314;
Sardonyx = 0x327;
Sphene = 0x32F;
Sunstone = 0x323;
Tourmaline = 0x326;
Turquoise = 0x31E;
Zircon = 0x325;
Description:
Gil = Zone, { [1] Drop rate, [2] Minimum gil, [3] Maximum gil }
Gems = Zone, { [1] Drop rate, [2] gem1, [3] gem2, [4] gem3, ... ,[10] gem10 }
Items = Zone, { [1] Drop rate, [2] item1, [3] item2}
Date:
Any update should be here with the date which was modified as well as an URL where info was taken.
* 07/21/2009
URL : http://wiki.ffxiclopedia.org/wiki/Treasure_Chest/Coffer_Guide
Done : First collection of all the loot and drop rate.
* 19/06/2013
Done : Drop and drop rate by zone
--]]-----------------------------------------------
gil = {147,{0.152,3440,9000},
151,{0.440,3200,6320},
161,{0.382,5000,13950},
162,{0.306,5000,10000},
197,{0.394,4702,10000},
191,{0.308,450,900},
149,{0.429,3060,6320},
157,{0.355,2450,7000},
158,{0.355,2450,7000},
195,{0.421,5100,12450},
204,{0.469,4050,7920},
141,{0.500,800,2100},
200,{0.576,4425,10000},
145,{0.448,800,1600},
196,{0.302,1980,3600},
192,{0.459,450,1034},
194,{0.459,450,1034},
190,{0.474,390,1300},
213,{0.806,3200,11679},
198,{0.525,1800,5200},
11,{0.731,3200,6400},
193,{0.310,1800,3600},
143,{0.455,840,1600},
9,{0.762,5200,12500},
28,{0.929,5100,9900},
176,{0.929,3355,8900},
142,{0.450,800,235}};
gems = {147,{0.090,0x32B,0x316,0x31C,0x31E,0x328,0x32F},
151,{0.080,0x32B,0x316,0x328,0x31C,0x314,0x327,0x32F,0x31E},
161,{0.008,0x32B,0x316,0x328,0x314,0x31F,0x32F},
162,{0.204,0x31E,0x316,0x328,0x314,0x32F,0x31C},
197,{0.162,0x32B,0x316,0x328,0x31C,0x31F,0x314,0x32F,0x31E},
191,{0.230,0x32E,0x320,0x329,0x31B,0x327,0x326},
149,{0.107,0x32B,0x316,0x328,0x31C,0x31F,0x314,0x32F,0x31E},
157,{0.161,0x32E,0x320,0x329,0x31B,0x31C,0x31F,0x326},
158,{0.161,0x32E,0x320,0x329,0x31B,0x31C,0x31F,0x326},
195,{0.105,0x32B,0x328,0x31C,0x31F,0x32F,0x316},
204,{0.091,0x32B,0x316,0x328,0x31C,0x31F,0x314,0x32F,0x31E},
141,{0.036,0x32E,0x320,0x31B,0x327,0x326},
200,{0.059,0x32B,0x316,0x328,0x31C,0x31F,0x314,0x32F,0x31E},
145,{0.069,0x32E,0x320,0x329,0x31B,0x327,0x326},
196,{0.233,0x326,0x329,0x32E,0x320,0x31C,0x31B,0x31F},
192,{0.109,0x32E,0x320,0x329,0x31B,0x326},
194,{0.109,0x32E,0x320,0x329,0x31B,0x326},
190,{0.093,0x32E,0x320,0x329,0x31B,0x327,0x326},
213,{0.194,0x32B,0x316,0x328,0x31C,0x31F,0x314,0x32F,0x31E},
198,{0.060,0x32E,0x320,0x329,0x31B,0x31C,0x31F,0x327,0x326},
11,{0.269,0x32B,0x328,0x31C,0x31F,0x314,0x32F,0x31E},
193,{0.214,0x320,0x329,0x326,0x327,0x31C,0x31B,0x32E,0x31F},
143,{0.136,0x31B,0x320,0x32E,0x327,0x326,0x329},
9,{0.238,0x32B,0x31E,0x32F,0x316,0x31F,0x314,0x328},
28,{0.071,0x316,0x31F,0x32F,0x314,0x31C},
176,{0.071,0x32B,0x328,0x316,0x31C,0x32F,0x314,0x31F,0x31E},
142,{0.100,0x32E,0x320,0x31B,0x327,0x326}};
items = {147,{0.758,0x33AE},
151,{0.480,0x3610},
161,{0.610,0x34CC},
162,{0.490,0x34CC},
197,{0.444,0x4146},
191,{0.462,0x3035},
149,{0.464,0x34CB},
157,{0.484,0x4122},
158,{0.484,0x4122},
195,{0.474,0x4183},
204,{0.440,0x33AF},
141,{0.464,0x413E},
200,{0.365,0x359B},
145,{0.483,0x3435},
196,{0.465,0x3032,0x4412},
192,{0.432,0x414F},
194,{0.432,0x414F},
190,{0.433,0x31FF},
213,{},
198,{0.415,0x42AF},
11,{},
193,{0.476,0x33A6},
143,{0.409,0x438B},
9,{},
28,{},
176,{},
142,{0.450,0x413E}};
-- Loot calculation
rand = math.random();
rand = math.random();
rand = math.random();
for u = 1, table.getn(gil), 2 do
if (gil[u] == zone) then
if (rand <= gil[u + 1][1]) then
reward = {"gil",math.random(gil[u + 1][2],gil[u + 1][3])};
elseif (rand <= (gil[u + 1][1] + gems[u + 1][1])) then
local num_gems = 0;
local curr_gem = 2;
while(gems[u + 1][curr_gem] ~= nil) do
curr_gem = curr_gem +1;
num_gems = num_gems + 1;
end
rand_gem = math.random(1,num_gems) + 1;
reward = {"item",gems[u + 1][rand_gem]};
else
local num_item = 0;
local curr_item = 2;
while(items[u + 1][curr_item] ~= nil) do
curr_item = curr_item +1;
num_item = num_item + 1;
end
rand_item = math.random(1,num_item) + 1;
reward = {"item",items[u + 1][rand_item]};
end
break;
end
end
return reward;
end
function cofferLoot(zone,npc)
--[[-----------------------------------------------
Chest Loot
---------------------------------------------------
---------------------------------------
-- Items
---------------------------------------
BurstScroll = 0x12D4;
MagesBalladII = 0x1383;
AdeptsRope = 0x33AE;
ElectrumHairpin = 0x3610;
PhalanxRing = 0x34CC;
GigantAxe = 0x4146;
TropicalShield = 0x3035;
ElectrumRing = 0x34CB;
EmethPick = 0x4122;
Falcastra = 0x4183;
LifeBelt = 0x33AF;
CougarBaghnakhs = 0x413E;
PyroRobe = 0x359B;
MothAxe = 0x414F;
ScreamFungus = 0x115F
ShieldEarring = 0x3435;
FrostShield = 0x3032;
ReplicaMaul = 0x4412;
BattleGloves = 0x31FF;
HeatRod = 0x42AF;
ForceBelt = 0x33A6;
FlameBoomerang = 0x438B;
SafeguardRing = 0x394E;
LightGauntlets = 0x3699;
HiReraiser = 0x104D;
PhysicalEarring = 0x3456;
VileElixir1 = 0x104F;
---------------------------------------
-- Gems
---------------------------------------
Amber = 0x32E;
Amethyst = 0x320;
Ametrine = 0x32B;
Aquamarine = 0x317;
Chrysoberyl = 0x321;
ClearTopaz = 0x329;
Fluorite = 0x32A;
Garnet = 0x316;
Goshenite = 0x328;
Jadeite = 0x310;
LapisLazuli = 0x31B;
LightOpal = 0x31C;
Moonstone = 0x322;
Onyx = 0x31F;
Painite = 0x31D;
Peridot = 0x314;
Sardonyx = 0x327;
Sphene = 0x32F;
Sunstone = 0x323;
Tourmaline = 0x326;
Turquoise = 0x31E;
Zircon = 0x325;
Description:
Gil = Zone, { [1] Drop rate, [2] Minimum gil, [3] Maximum gil }
Gems = Zone, { [1] Drop rate, [2] gem1, [3] gem2, [4] gem3, ... ,[10] gem10 }
Items = Zone, { [1] Drop rate, [2] item1, [3] item2}
Date:
Any update should be here with the date which was modified as well as an URL where info was taken.
* 07/21/2009
URL : http://wiki.ffxiclopedia.org/wiki/Treasure_Chest/Coffer_Guide
Done : First collection of all the loot and drop rate.
* 19/06/2013
Done : Drop and drop rate by zone
--]]-----------------------------------------------
gil = {147,{0.375,4700,25000},
153,{0.793,7110,20520},
151,{0.652,7320,18000},
161,{0.731,6300,26880},
197,{0.387,6040,12100},
160,{0.700,8000,16770},
195,{0.500,7590,18039},
200,{0.750,6668,18700},
205,{0.897,7200,21060},
174,{0.943,5200,16100},
150,{0.818,7320,14400},
12,{0.927,9800,19180},
208,{0.773,6160,16100},
130,{0.821,9576,19460},
176,{0.550,6145,19580},
159,{0.846,7320,14400},
169,{0.900,7440,14280},
177,{0.500,9940,18900}};
gems = {147,{0.240,0x317,0x321,0x322,0x31D,0x314,0x323,0x325,0x32A,0x310},
153,{0.092,0x317,0x321,0x32A,0x310,0x322,0x323,0x325,0x31D},
151,{0.044,0x317,0x321,0x32A,0x310,0x322,0x31D,0x323,0x325},
161,{0.080,0x317,0x321,0x32A,0x310,0x322,0x31D,0x323,0x325},
197,{0.387,0x317,0x321,0x310,0x31D,0x325,0x323},
160,{0.300,0x31D,0x325},
195,{0.250,0x321,0x32A,0x322,0x31D,0x323},
200,{0.125,0x321,0x310,0x322},
205,{0.103,0x322,0x31D,0x323,0x321,0x32A,0x317},
174,{0.057,0x322,0x321,0x31D,0x310,0x323,0x317,0x325,0x32A},
150,{0.055,0x321,0x32A,0x310,0x322,0x31D,0x323},
12,{0.073,0x317,0x31D,0x310,0x323,0x325,0x321,0x322},
208,{0.227,0x317,0x321,0x32A,0x310,0x31D,0x323},
130,{0.179,0x317,0x321,0x32A,0x310,0x322,0x31D,0x325,0x323},
176,{0.450,0x317,0x32A,0x310,0x322,0x323,0x31D,0x321},
159,{0.154,0x31D,0x321,0x32A,0x322,0x325,0x323},
169,{0.100,0x317,0x321,0x310,0x322,0x31D,0x323,0x325},
177,{0.500,0x317,0x325}};
items = {147,{0.385,0x12D4},
153,{0.115,0x115F},
151,{0.304,0x394E},
161,{0.189,0x1383},
197,{0.226,0x104D},
160,{},
195,{0.250,0x104F},
200,{0.125,0x3699},
205,{},
174,{},
150,{0.127,0x3456},
12,{},
208,{},
130,{},
176,{},
159,{},
169,{},
177,{}};
-- Loot calculation
rand = math.random();
rand = math.random();
rand = math.random();
for u = 1, table.getn(gil), 2 do
if (gil[u] == zone) then
if (rand <= gil[u + 1][1]) then
reward = {"gil",math.random(gil[u + 1][2],gil[u + 1][3])};
elseif (rand <= (gil[u + 1][1] + gems[u + 1][1])) then
local num_gems = 0;
local curr_gem = 2;
while(gems[u + 1][curr_gem] ~= nil) do
curr_gem = curr_gem +1;
num_gems = num_gems + 1;
end
rand_gem = math.random(1,num_gems) + 1;
reward = {"item",gems[u + 1][rand_gem]};
else
local num_item = 0;
local curr_item = 2;
while(items[u + 1][curr_item] ~= nil) do
curr_item = curr_item +1;
num_item = num_item + 1;
end
rand_item = math.random(1,num_item) + 1;
reward = {"item",items[u + 1][rand_item]};
end
break;
end
end
return reward;
end | gpl-3.0 |
LiberatorUSA/GUCEF | plugins/GUI/guidriverXWinGL/premake4.lua | 1 | 2055 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
-- Configuration for module: guidriverXWinGL
configuration( { "LINUX" } )
project( "guidriverXWinGL" )
configuration( {} )
location( os.getenv( "PM4OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM4TARGETDIR" ) )
configuration( {} )
language( "C" )
configuration( { "LINUX" } )
language( "C++" )
configuration( { "LINUX" } )
configuration( { LINUX } )
kind( "SharedLib" )
configuration( { LINUX } )
links( { "gucefCORE", "gucefGUI", "gucefMT" } )
links( { "GL", "X11", "gucefCORE", "gucefGUI", "gucefMT" } )
configuration( { LINUX } )
defines( { "GUIDRIVERXWINGL_BUILD_MODULE" } )
configuration( { "LINUX" } )
vpaths { ["Platform Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/guidriverXWinGL.h",
"include/guidriverXWinGL_config.h",
"include/guidriverXWinGL_CXWinGLWindowContext.h",
"include/guidriverXWinGL_CXWinGLWindowManagerImp.h",
"include/guidriverXWinGL_macros.h",
"include/guidriverXWinGL_pluginAPI.h"
} )
vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/guidriverXWinGL_CXWinGLWindowContext.cpp",
"src/guidriverXWinGL_CXWinGLWindowManagerImp.cpp",
"src/guidriverXWinGL_pluginAPI.cpp"
} )
configuration( {} )
includedirs( { "../../../common/include", "../../../gucefCORE/include", "../../../gucefGUI/include", "../../../gucefIMAGE/include", "../../../gucefMT/include", "../../../gucefVFS/include" } )
configuration( { "LINUX" } )
includedirs( { "../../../gucefCORE/include/linux", "include" } )
| apache-2.0 |
tridge/ardupilot | libraries/AP_Scripting/examples/arming-check-wp1-takeoff.lua | 18 | 1073 | -- This script runs a custom arming check for index == 1 and it must be a takeoff missionn item
local auth_id = arming:get_aux_auth_id()
local MAV_CMD_NAV_TAKEOFF = 22
local MAV_CMD_NAV_VTOL_TAKEOFF = 84
function update() -- this is the loop which periodically runs
if auth_id then
local cmd_id = mission:get_current_nav_id()
local index = mission:get_current_nav_index()
if not cmd_id or not index then
arming:set_aux_auth_failed(auth_id, "Could not retrieve mission")
elseif ((index ~= 0) and (index ~= 1)) then
-- index of 0 is valid because when you switch to AUTO it will automatically change to 1
arming:set_aux_auth_failed(auth_id, "Mission index is not ready")
elseif ((cmd_id ~= MAV_CMD_NAV_TAKEOFF) and (cmd_id ~= MAV_CMD_NAV_VTOL_TAKEOFF)) then
arming:set_aux_auth_failed(auth_id, "Mission is not ready to takeoff")
else
arming:set_aux_auth_passed(auth_id)
end
end
return update, 2000 -- reschedules the loop in 2 seconds
end
return update() -- run immediately before starting to reschedule
| gpl-3.0 |
xya/coroutines | examples/pingpong.lua | 1 | 1966 | -- Copyright (c) 2009, 2011, Pierre-Andre Saulais <pasaulais@free.fr>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the <organization> nor the
-- names of its contributors may be used to endorse or promote products
-- derived from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function ping(arg)
local n = arg
local ok = true
local co_pong = coroutine.create(pong)
repeat
print("ping! " .. n)
ok, n = coroutine.resume(co_pong, n + 1)
until not ok or coroutine.status(co_pong) == 'dead'
end
function pong(arg)
local n = arg
while n < 10 do
print("pong! " .. n)
n = coroutine.yield(n + 1)
end
end
ping(1)
| bsd-3-clause |
Ombridride/minetest-minetestforfun-server | mods/runes/registration.lua | 8 | 1235 | -- Rune definitions : registration.lua
runes.datas.items = {
["project"] = {
description = "Projection rune",
img = "runes_projection",
type = "craftitem",
needed_mana = {
["minor"] = 15,
["medium"] = 30,
["major"] = 45,
},
},
["damager"] = {
description = "Damaging rune",
img = "runes_damaging",
type = "craftitem",
needed_mana = {
["minor"] = 180,
["medium"] = 190,
["major"] = 230
}
},
["earthquake"] = {
description = "Earth Quake rune",
img = "runes_earthquake",
type = "craftitem",
needed_mana = {
["minor"] = 70,
["medium"] = 80,
["major"] = 90
}
},
["heal"] = {
description = "Healing rune",
img = "runes_heal",
type = "cube"
},
["gotome"] = {
description = "Go to me rune",
img = "runes_go_to_me",
type = "cube",
needed_mana = {
["minor"] = 40,
["medium"] = 50,
["major"] = 75
}
},
["megamana"] = {
description = "Mega Mana",
img = {
["minor"] = "default_diamond.png",
["medium"] = "default_diamond.png",
["major"] = "default_diamond.png"
},
type = "craftitem"
},
}
for key, value in pairs(runes.datas.items) do
local runereg = table.copy(value)
runereg.name = key
runes.functions.register_rune(runereg)
end
| unlicense |
Ombridride/minetest-minetestforfun-server | minetestforfun_game/mods/farming/cucumber.lua | 12 | 1435 |
--[[
Original textures from DocFarming mod
https://forum.minetest.net/viewtopic.php?id=3948
]]
local S = farming.intllib
-- cucumber
minetest.register_craftitem("farming:cucumber", {
description = S("Cucumber"),
inventory_image = "farming_cucumber.png",
on_place = function(itemstack, placer, pointed_thing)
return farming.place_seed(itemstack, placer, pointed_thing, "farming:cucumber_1")
end,
on_use = minetest.item_eat(4),
})
-- cucumber definition
local crop_def = {
drawtype = "plantlike",
tiles = {"farming_cucumber_1.png"},
paramtype = "light",
walkable = false,
buildable_to = true,
drop = "",
selection_box = farming.select,
groups = {
snappy = 3, flammable = 2, plant = 1, attached_node = 1,
not_in_creative_inventory = 1, growing = 1
},
sounds = default.node_sound_leaves_defaults()
}
-- stage 1
minetest.register_node("farming:cucumber_1", table.copy(crop_def))
-- stage 2
crop_def.tiles = {"farming_cucumber_2.png"}
minetest.register_node("farming:cucumber_2", table.copy(crop_def))
-- stage 3
crop_def.tiles = {"farming_cucumber_3.png"}
minetest.register_node("farming:cucumber_3", table.copy(crop_def))
-- stage 4 (final)
crop_def.tiles = {"farming_cucumber_4.png"}
crop_def.groups.growing = 0
crop_def.drop = {
items = {
{items = {'farming:cucumber'}, rarity = 1},
{items = {'farming:cucumber 2'}, rarity = 2},
}
}
minetest.register_node("farming:cucumber_4", table.copy(crop_def))
| unlicense |
jshackley/darkstar | scripts/zones/Southern_San_dOria/npcs/Clainomille.lua | 34 | 1302 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Clainomille
-- Type: Standard NPC
-- @zone: 230
-- @pos -72.771 0.999 -6.112
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0265);
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 |
iofun/treehouse | luerl/d3efc4b5b22433b5dc80161e9f9c4b03.lua | 1 | 2133 | -- Each Supply Depot raises the Terran's population limit by eight.
-- Our unit function table
local this_unit = {}
-- Where we are and fast we move
local x, y, dx, dy
-- Our name
local name = "Terran_Supply_Depot"
-- Our color
local color = "blue"
-- Our BWAPI unit type
local type = 109
-- Size of a clock tick msec
local tick
-- It's me, the unit structure
local me = unit.self()
-- The standard local variables
local label = "medium_structure"
local armor = 1
local hitpoints,shield = 500,0
local ground_damage,air_damage = 0,0
local ground_cooldown,air_cooldown = 0,0
local ground_range,air_range = 0,0
local sight = 8
local supply = 8
local cooldown = 40
local mineral = 100
local gas = 0
local holdkey = "s"
-- The size of the region
local xsize,ysize = region.size()
-- The unit interface.
function this_unit.start() end
function this_unit.get_position() return x,y end
function this_unit.set_position(a1, a2) x,y = a1,a2 end
function this_unit.get_speed() return dx,dy end
function this_unit.set_speed(a1, a2) dx,dy = a1,a2 end
function this_unit.set_tick(a1) tick = a1 end
local function move_xy_bounce(x, y, dx, dy, valid_x, valid_y)
local nx = x + dx
local ny = y + dy
-- Bounce off the edge
if (not valid_x(nx)) then
nx = x - dx
dx = -dx
end
-- Bounce off the edge
if (not valid_y(ny)) then
ny = y - dy
dy = -dy
end
return nx, ny, dx, dy
end
local function move(x, y, dx, dy)
local nx,ny,ndx,ndy = move_xy_bounce(x, y, dx, dy,
region.valid_x, region.valid_y)
-- Where we were and where we are now.
local osx,osy = region.sector(x, y)
local nsx,nsy = region.sector(nx, ny)
if (osx ~= nsx or osy ~= nsy) then
-- In new sector, move us to the right sector
region.rem_sector(x, y)
region.add_sector(nx, ny)
end
return nx,ny,ndx,ndy
end
function this_unit.tick()
x,y,dx,dy = move(x, y, dx, dy)
end
function this_unit.attack()
-- The unit has been zapped and will die
region.rem_sector(x, y)
end
-- Return the unit table
return this_unit
| agpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Mines/npcs/Parraggoh.lua | 36 | 2331 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Parraggoh
-- Finishes Quest: Beauty and the Galka
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
BeautyAndTheGalka = player:getQuestStatus(BASTOK,BEAUTY_AND_THE_GALKA);
BeautyAndTheGalkaDenied = player:getVar("BeautyAndTheGalkaDenied");
PalboroughMinesLogs = player:hasKeyItem(2);
if (PalboroughMinesLogs == true) then
player:startEvent(0x000a);
elseif (BeautyAndTheGalka == QUEST_ACCEPTED) then
Message = math.random(0,1);
if (Message == 1) then
player:startEvent(0x0008);
else
player:startEvent(0x0009);
end
elseif (BeautyAndTheGalkaDenied == 1) then
player:startEvent(0x0007);
elseif (BeautyAndTheGalka == QUEST_COMPLETED) then
player:startEvent(0x000c);
else
player:startEvent(0x000b);
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 == 0x0007 and option == 0) then
player:addQuest(BASTOK,BEAUTY_AND_THE_GALKA);
elseif (csid == 0x000a) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(BASTOK,BEAUTY_AND_THE_GALKA);
player:setVar("BeautyAndTheGalkaDenied",0);
player:delKeyItem(PALBOROUGH_MINES_LOGS);
player:addFame(BASTOK,BAS_FAME*75);
player:addItem(16465);
player:messageSpecial(ITEM_OBTAINED,16465);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16465);
end
end
end;
| gpl-3.0 |
zdimension/UniRaider | FreeRaider/FreeRaider/bin/Debug/scripts/strings/italian/global_items.lua | 7 | 3026 | -- OPENTOMB INVENTORY GLOBAL ITEM NAMES
-- by Lwmte, Sep 2014
--------------------------------------------------------------------------------
-- In this file, we list all the global item names used across all games.
-- Non-global item names should be eventually listed in level-specific scripts.
-- Note that names list not always resemble item list, as we also introduce
-- game-specific global item names (e.g. compass was replaced by watch in TR2-3)
--------------------------------------------------------------------------------
ITEM_NAME_COMPASS = "Bussola"
ITEM_NAME_WATCH = "Statistiche"
ITEM_NAME_PASSPORT = "Gioca"
ITEM_NAME_LARAHOME = "Casa di Lara"
ITEM_NAME_VIDEO = "Opzioni video"
ITEM_NAME_AUDIO = "Opzioni audio"
ITEM_NAME_CONTROLS = "Configurazione controlli"
ITEM_NAME_LOAD = "Carica Partita"
ITEM_NAME_SAVE = "Salva Partita"
ITEM_NAME_MAP = "Mappa"
ITEM_NAME_PISTOLS = "Pistole"
ITEM_NAME_SHOTGUN = "Fucile"
ITEM_NAME_MAGNUMS = "Magnums"
ITEM_NAME_AUTOMAGS = "Pistole Automatiche"
ITEM_NAME_DESERTEAGLE = "Desert Eagle"
ITEM_NAME_REVOLVER = "Revolver"
ITEM_NAME_UZIS = "Uzi"
ITEM_NAME_M16 = "M16"
ITEM_NAME_MP5 = "MP5"
ITEM_NAME_HK = "Fucile H&K"
ITEM_NAME_GRENADEGUN = "Lanciagranate"
ITEM_NAME_ROCKETGUN = "Lanciarazzi"
ITEM_NAME_HARPOONGUN = "Fiocina"
ITEM_NAME_CROSSBOW = "Balestra"
ITEM_NAME_GRAPPLEGUN = "Rampino"
ITEM_NAME_LASERSIGHT = "Mirino Laser"
ITEM_NAME_BINOCULARS = "Binocolo"
ITEM_NAME_SILENCER = "Silenziatore"
ITEM_NAME_REVOLVER_LASERSIGHT = "Revolver + Mirino Laser"
ITEM_NAME_CROSSBOW_LASERSIGHT = "Balestra + Mirino Laser"
ITEM_NAME_HK_LASERSIGHT = "Fucile H&K + Mirino Laser"
-- We don't need to specify each ammo name, as usually one weapon
-- has one type of ammo. This was changed since TR4, for which we
-- specify some ammo names explicitly.
ITEM_NAME_PISTOL_AMMO = "Munizioni Pistole"
ITEM_NAME_SHOTGUN_AMMO = "Munizioni Fucile"
ITEM_NAME_SHOTGUN_NORMAL_AMMO = "Munizioni Fucile Normali"
ITEM_NAME_SHOTGUN_WIDESHOT_AMMO = "Munizioni Fucile Wideshot"
ITEM_NAME_MAGNUM_AMMO = "Munizioni Magnums"
ITEM_NAME_AUTOMAG_AMMO = "Munizioni Pistole Automatiche"
ITEM_NAME_DESERTEAGLE_AMMO = "Munizioni Desert Eagle"
ITEM_NAME_REVOLVER_AMMO = "Munizioni Revolver"
ITEM_NAME_UZI_AMMO = "Munizioni Uzi"
ITEM_NAME_M16_AMMO = "Munizioni M16"
ITEM_NAME_MP5_AMMO = "Munizioni MP5"
ITEM_NAME_HK_AMMO = "Munizioni Fucile H&K"
ITEM_NAME_GRENADEGUN_AMMO = "Granate"
ITEM_NAME_GRENADEGUN_NORMAL_AMMO = "Granate Normali"
ITEM_NAME_GRENADEGUN_SUPER_AMMO = "Granate Super"
ITEM_NAME_GRENADEGUN_FLASH_AMMO = "Granate Flash"
ITEM_NAME_ROCKETGUN_AMMO = "Razzi"
ITEM_NAME_HARPOONGUN_AMMO = "Arpioni"
ITEM_NAME_CROSSBOW_NORMAL_AMMO = "Dardi Normali"
ITEM_NAME_CROSSBOW_POISON_AMMO = "Dardi Avvelenati"
ITEM_NAME_CROSSBOW_EXPLOSIVE_AMMO = "Dardi Esplosivi"
ITEM_NAME_GRAPPLEGUN_AMMO = "Munizioni Rampino"
ITEM_NAME_FLARES = "Bengala"
ITEM_NAME_TORCH = "Torcia" -- Don't know why we may need this?..
ITEM_NAME_SMALL_MEDIPACK = "Medipack Piccolo"
ITEM_NAME_LARGE_MEDIPACK = "Medipack Grande"
| gpl-2.0 |
Ombridride/minetest-minetestforfun-server | mods/pipeworks/vacuum_tubes.lua | 7 | 4296 | if pipeworks.enable_sand_tube then
pipeworks.register_tube("pipeworks:sand_tube", {
description = "Vacuuming Pneumatic Tube Segment",
inventory_image = "pipeworks_sand_tube_inv.png",
short = "pipeworks_sand_tube_short.png",
noctr = { "pipeworks_sand_tube_noctr.png" },
plain = { "pipeworks_sand_tube_plain.png" },
ends = { "pipeworks_sand_tube_end.png" },
node_def = { groups = {vacuum_tube = 1}},
})
minetest.register_craft( {
output = "pipeworks:sand_tube_1 2",
recipe = {
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" },
{ "group:sand", "group:sand", "group:sand" },
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }
},
})
minetest.register_craft( {
output = "pipeworks:sand_tube_1",
recipe = {
{ "group:sand", "pipeworks:tube_1", "group:sand" },
},
})
end
if pipeworks.enable_mese_sand_tube then
pipeworks.register_tube("pipeworks:mese_sand_tube", {
description = "Adjustable Vacuuming Pneumatic Tube Segment",
inventory_image = "pipeworks_mese_sand_tube_inv.png",
short = "pipeworks_mese_sand_tube_short.png",
noctr = { "pipeworks_mese_sand_tube_noctr.png" },
plain = { "pipeworks_mese_sand_tube_plain.png" },
ends = { "pipeworks_mese_sand_tube_end.png" },
node_def = {
groups = {vacuum_tube = 1},
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_int("dist", 0)
meta:set_string("formspec", "size[2.1,0.8]"..
"image[0,0;1,1;pipeworks_mese_sand_tube_inv.png]"..
"field[1.3,0.4;1,1;dist;radius;${dist}]"..
default.gui_bg..
default.gui_bg_img)
meta:set_string("infotext", "Adjustable Vacuuming Pneumatic Tube Segment")
end,
on_receive_fields = function(pos,formname,fields,sender)
if not pipeworks.may_configure(pos, sender) then return end
local meta = minetest.get_meta(pos)
local dist = tonumber(fields.dist)
if dist then
dist = math.max(0, dist)
dist = math.min(8, dist)
meta:set_int("dist", dist)
meta:set_string("infotext", ("Adjustable Vacuuming Pneumatic Tube Segment (%dm)"):format(dist))
end
end,
},
})
minetest.register_craft( {
output = "pipeworks:mese_sand_tube_1 2",
recipe = {
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" },
{ "group:sand", "default:mese_crystal", "group:sand" },
{ "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }
},
})
minetest.register_craft( {
type = "shapeless",
output = "pipeworks:mese_sand_tube_1",
recipe = {
"pipeworks:sand_tube_1",
"default:mese_crystal_fragment",
"default:mese_crystal_fragment",
"default:mese_crystal_fragment",
"default:mese_crystal_fragment"
},
})
end
local sqrt_3 = math.sqrt(3)
local tube_inject_item = pipeworks.tube_inject_item
local get_objects_inside_radius = minetest.get_objects_inside_radius
local function vacuum(pos, radius)
radius = radius + 0.5
-- Modification made by MFF to reduce lag
local max_items = 0
for _, object in pairs(get_objects_inside_radius(pos, sqrt_3 * radius)) do
local lua_entity = object:get_luaentity()
if not object:is_player() and lua_entity and lua_entity.name == "__builtin:item" then
max_items = max_items + 1
if max_items > 50 then
object:remove()
else
local obj_pos = object:getpos()
local x1, y1, z1 = pos.x, pos.y, pos.z
local x2, y2, z2 = obj_pos.x, obj_pos.y, obj_pos.z
if x1 - radius <= x2 and x2 <= x1 + radius
and y1 - radius <= y2 and y2 <= y1 + radius
and z1 - radius <= z2 and z2 <= z1 + radius then
if lua_entity.itemstring ~= "" then
tube_inject_item(pos, pos, vector.new(0, 0, 0), lua_entity.itemstring)
lua_entity.itemstring = ""
end
object:remove()
end
end
end
end
end
minetest.register_abm({nodenames = {"group:vacuum_tube"},
interval = 4,
chance = 1,
label = "Vacuum tubes",
action = function(pos, node, active_object_count, active_object_count_wider)
if node.name:find("pipeworks:sand_tube") then
vacuum(pos, 2)
else
local radius = minetest.get_meta(pos):get_int("dist")
vacuum(pos, radius)
end
end
})
| unlicense |
goksie/newfies-dialer | lua/libs/example.lua | 4 | 4800 | --
-- Newfies-Dialer License
-- http://www.newfies-dialer.org
--
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this file,
-- You can obtain one at http://mozilla.org/MPL/2.0/.
--
-- Copyright (C) 2011-2014 Star2Billing S.L.
--
-- The Initial Developer of the Original Code is
-- Arezqui Belaid <info@star2billing.com>
--
--
-- Test & demonstration file for "fsm.lua"
--
FSM = require "fsm"
-- function playmessage()
-- print("Play Message")
-- end
-- -- Define your state transitions here
-- local myStateTransitionTable = {
-- {"section1", "start", "section1", playmessage},
-- {"section1", "DTMF1", "section2", action1},
-- {"state2", "event2", "state3", action2},
-- {"state3", "event1", "state1", action3},
-- {"*", "event3", "state3", action3}, -- for any state
-- {"*", "*", "unknow", unknow} -- exception handler
-- }
function action1() print("Performing action 1") end
function action2() print("Performing action 2") end
function action3() print("Performing action 3") end
function unknow()
print("Performing unknow")
fsm:fire("event0")
end
function notunknow() print("Performing notunknow") end
-- Define your state transitions here
local myStateTransitionTable = {
{"state1", "event1", "state2", action1},
{"state2", "event2", "state3", action2},
{"state3", "event1", "state1", action3},
{"*", "event3", "state3", action3}, -- for any state
{"*", "*", "unknow", unknow}, -- exception handler
{"unknow", "event0", "state2", notunknow},
{"unknow", "*", "state1", notunknow}
}
-- Create your finite state machine
fsm = FSM.new(myStateTransitionTable)
-- Use your finite state machine
-- which starts by default with the first defined state
print("Current FSM state: " .. fsm:get())
-- Or you can set another state
fsm:set("state2")
print("Current FSM state: " .. fsm:get())
-- Resond on "event" and last set "state"
fsm:fire("event3")
print("Current FSM state: " .. fsm:get())
fsm:fire("event1")
print("Current FSM state: " .. fsm:get())
fsm:fire("bloufff")
print("Current FSM state: " .. fsm:get())
-- function action1() print("Performing action 1") end
-- function action2() print("Performing action 2") end
-- function action3() print("Action 3: Exception raised") end
-- function action4() print("Wildcard in action !!!") end
-- -- Define your state transitions here
-- local myStateTransitionTable = {
-- {"state1", "event1", "state2", action1},
-- {"state2", "event2", "state3", action2}
-- }
-- -- Create your instance of a finite state machine
-- fsm = FSM.new(myStateTransitionTable)
-- -- print( "Constant UNKNOWN = " .. UNKNOWN )
-- print( "Constant FSM.UNKNOWN = " .. FSM.UNKNOWN )
-- -- Use your finite state machine
-- -- which starts by default with the first defined state
-- print("Current FSM state: " .. fsm:get())
-- -- Or you can set another state
-- fsm:set("state2")
-- print("Current FSM state: " .. fsm:get())
-- -- Respond on "event" and last set "state"
-- fsm:fire("event2")
-- print("Current FSM state: " .. fsm:get())
-- -- Force exception
-- print("Force exception by firing unknown event")
-- fsm:fire("event3")
-- print("Current FSM state: " .. fsm:get())
-- -- Test automated exception handling
-- local myStateTransitionTable2 = {
-- {"state1", "event1", "state2", action1},
-- {"state2", "event2", "state3", action2},
-- {"*" , "event3", "state1", action4},
-- {"*" , "?", "state1", action3}
-- }
-- -- Create your instance of a finite state machine
-- fsm2 = FSM.new(myStateTransitionTable2)
-- fsm2:set("state2")
-- print("\nCurrent FSM-2 state: " .. fsm2:get())
-- fsm2:delete({{"state2", "event2"}} )
-- -- Force exception
-- fsm2:fire("event2")
-- fsm2:delete({{"*", "?"}} )
-- print("Force third exception (silence = true)")
-- fsm2:silent() -- prevent unknown state-event notificaton to be printed
-- fsm2:fire("event3")
-- print("Current FSM-2 state after firing wildcard 'event3': " .. fsm2:get())
-- fsm2:add({{"*" , "*", "state2", action3}})
-- fsm2:fire("event2")
-- print("Current FSM-2 state: " .. fsm2:get())
-- print("Current FSM state: " .. fsm:get())
--[[
Expected output:
Constant FSM.UNKNONW = *.*
Current FSM state: state1
Current FSM state: state2
Performing action 2
Current FSM state: state3
Force exception by firing unknown event
FSM: unknown combination: state3.event3
Current FSM state: state1
Current FSM-2 state: state2
FSM: unknown combination: state2.event2
Force third exception (silence = true)
Wildcard in action !!!
Current FSM-2 state after firing wildcard 'event3': state1
Action 3: Exception raised
Current FSM-2 state: state2
Current FSM state: state1
--]] | mpl-2.0 |
coolsvap/kubernetes | test/images/echoserver/template.lua | 195 | 17200 | -- vendored from https://raw.githubusercontent.com/bungle/lua-resty-template/1f9a5c24fc7572dbf5be0b9f8168cc3984b03d24/lib/resty/template.lua
-- only modification: remove / from HTML_ENTITIES to not escape it, and fix the appropriate regex.
--[[
Copyright (c) 2014 - 2017 Aapo Talvensaari
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--]]
local setmetatable = setmetatable
local loadstring = loadstring
local loadchunk
local tostring = tostring
local setfenv = setfenv
local require = require
local capture
local concat = table.concat
local assert = assert
local prefix
local write = io.write
local pcall = pcall
local phase
local open = io.open
local load = load
local type = type
local dump = string.dump
local find = string.find
local gsub = string.gsub
local byte = string.byte
local null
local sub = string.sub
local ngx = ngx
local jit = jit
local var
local _VERSION = _VERSION
local _ENV = _ENV
local _G = _G
local HTML_ENTITIES = {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
}
local CODE_ENTITIES = {
["{"] = "{",
["}"] = "}",
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
["/"] = "/"
}
local VAR_PHASES
local ok, newtab = pcall(require, "table.new")
if not ok then newtab = function() return {} end end
local caching = true
local template = newtab(0, 12)
template._VERSION = "1.9"
template.cache = {}
local function enabled(val)
if val == nil then return true end
return val == true or (val == "1" or val == "true" or val == "on")
end
local function trim(s)
return gsub(gsub(s, "^%s+", ""), "%s+$", "")
end
local function rpos(view, s)
while s > 0 do
local c = sub(view, s, s)
if c == " " or c == "\t" or c == "\0" or c == "\x0B" then
s = s - 1
else
break
end
end
return s
end
local function escaped(view, s)
if s > 1 and sub(view, s - 1, s - 1) == "\\" then
if s > 2 and sub(view, s - 2, s - 2) == "\\" then
return false, 1
else
return true, 1
end
end
return false, 0
end
local function readfile(path)
local file = open(path, "rb")
if not file then return nil end
local content = file:read "*a"
file:close()
return content
end
local function loadlua(path)
return readfile(path) or path
end
local function loadngx(path)
local vars = VAR_PHASES[phase()]
local file, location = path, vars and var.template_location
if sub(file, 1) == "/" then file = sub(file, 2) end
if location and location ~= "" then
if sub(location, -1) == "/" then location = sub(location, 1, -2) end
local res = capture(concat{ location, '/', file})
if res.status == 200 then return res.body end
end
local root = vars and (var.template_root or var.document_root) or prefix
if sub(root, -1) == "/" then root = sub(root, 1, -2) end
return readfile(concat{ root, "/", file }) or path
end
do
if ngx then
VAR_PHASES = {
set = true,
rewrite = true,
access = true,
content = true,
header_filter = true,
body_filter = true,
log = true
}
template.print = ngx.print or write
template.load = loadngx
prefix, var, capture, null, phase = ngx.config.prefix(), ngx.var, ngx.location.capture, ngx.null, ngx.get_phase
if VAR_PHASES[phase()] then
caching = enabled(var.template_cache)
end
else
template.print = write
template.load = loadlua
end
if _VERSION == "Lua 5.1" then
local context = { __index = function(t, k)
return t.context[k] or t.template[k] or _G[k]
end }
if jit then
loadchunk = function(view)
return assert(load(view, nil, nil, setmetatable({ template = template }, context)))
end
else
loadchunk = function(view)
local func = assert(loadstring(view))
setfenv(func, setmetatable({ template = template }, context))
return func
end
end
else
local context = { __index = function(t, k)
return t.context[k] or t.template[k] or _ENV[k]
end }
loadchunk = function(view)
return assert(load(view, nil, nil, setmetatable({ template = template }, context)))
end
end
end
function template.caching(enable)
if enable ~= nil then caching = enable == true end
return caching
end
function template.output(s)
if s == nil or s == null then return "" end
if type(s) == "function" then return template.output(s()) end
return tostring(s)
end
function template.escape(s, c)
if type(s) == "string" then
if c then return gsub(s, "[}{\">/<'&]", CODE_ENTITIES) end
return gsub(s, "[\"><'&]", HTML_ENTITIES)
end
return template.output(s)
end
function template.new(view, layout)
assert(view, "view was not provided for template.new(view, layout).")
local render, compile = template.render, template.compile
if layout then
if type(layout) == "table" then
return setmetatable({ render = function(self, context)
local context = context or self
context.blocks = context.blocks or {}
context.view = compile(view)(context)
layout.blocks = context.blocks or {}
layout.view = context.view or ""
return layout:render()
end }, { __tostring = function(self)
local context = self
context.blocks = context.blocks or {}
context.view = compile(view)(context)
layout.blocks = context.blocks or {}
layout.view = context.view
return tostring(layout)
end })
else
return setmetatable({ render = function(self, context)
local context = context or self
context.blocks = context.blocks or {}
context.view = compile(view)(context)
return render(layout, context)
end }, { __tostring = function(self)
local context = self
context.blocks = context.blocks or {}
context.view = compile(view)(context)
return compile(layout)(context)
end })
end
end
return setmetatable({ render = function(self, context)
return render(view, context or self)
end }, { __tostring = function(self)
return compile(view)(self)
end })
end
function template.precompile(view, path, strip)
local chunk = dump(template.compile(view), strip ~= false)
if path then
local file = open(path, "wb")
file:write(chunk)
file:close()
end
return chunk
end
function template.compile(view, key, plain)
assert(view, "view was not provided for template.compile(view, key, plain).")
if key == "no-cache" then
return loadchunk(template.parse(view, plain)), false
end
key = key or view
local cache = template.cache
if cache[key] then return cache[key], true end
local func = loadchunk(template.parse(view, plain))
if caching then cache[key] = func end
return func, false
end
function template.parse(view, plain)
assert(view, "view was not provided for template.parse(view, plain).")
if not plain then
view = template.load(view)
if byte(view, 1, 1) == 27 then return view end
end
local j = 2
local c = {[[
context=... or {}
local function include(v, c) return template.compile(v)(c or context) end
local ___,blocks,layout={},blocks or {}
]] }
local i, s = 1, find(view, "{", 1, true)
while s do
local t, p = sub(view, s + 1, s + 1), s + 2
if t == "{" then
local e = find(view, "}}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
c[j] = "___[#___+1]=template.escape("
c[j+1] = trim(sub(view, p, e - 1))
c[j+2] = ")\n"
j=j+3
s, i = e + 1, e + 2
end
end
elseif t == "*" then
local e = find(view, "*}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
c[j] = "___[#___+1]=template.output("
c[j+1] = trim(sub(view, p, e - 1))
c[j+2] = ")\n"
j=j+3
s, i = e + 1, e + 2
end
end
elseif t == "%" then
local e = find(view, "%}", p, true)
if e then
local z, w = escaped(view, s)
if z then
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
i = s
else
local n = e + 2
if sub(view, n, n) == "\n" then
n = n + 1
end
local r = rpos(view, s - 1)
if i <= r then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, r)
c[j+2] = "]=]\n"
j=j+3
end
c[j] = trim(sub(view, p, e - 1))
c[j+1] = "\n"
j=j+2
s, i = n - 1, n
end
end
elseif t == "(" then
local e = find(view, ")}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
local f = sub(view, p, e - 1)
local x = find(f, ",", 2, true)
if x then
c[j] = "___[#___+1]=include([=["
c[j+1] = trim(sub(f, 1, x - 1))
c[j+2] = "]=],"
c[j+3] = trim(sub(f, x + 1))
c[j+4] = ")\n"
j=j+5
else
c[j] = "___[#___+1]=include([=["
c[j+1] = trim(f)
c[j+2] = "]=])\n"
j=j+3
end
s, i = e + 1, e + 2
end
end
elseif t == "[" then
local e = find(view, "]}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
c[j] = "___[#___+1]=include("
c[j+1] = trim(sub(view, p, e - 1))
c[j+2] = ")\n"
j=j+3
s, i = e + 1, e + 2
end
end
elseif t == "-" then
local e = find(view, "-}", p, true)
if e then
local x, y = find(view, sub(view, s, e + 1), e + 2, true)
if x then
local z, w = escaped(view, s)
if z then
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
i = s
else
y = y + 1
x = x - 1
if sub(view, y, y) == "\n" then
y = y + 1
end
local b = trim(sub(view, p, e - 1))
if b == "verbatim" or b == "raw" then
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
c[j] = "___[#___+1]=[=["
c[j+1] = sub(view, e + 2, x)
c[j+2] = "]=]\n"
j=j+3
else
if sub(view, x, x) == "\n" then
x = x - 1
end
local r = rpos(view, s - 1)
if i <= r then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, r)
c[j+2] = "]=]\n"
j=j+3
end
c[j] = 'blocks["'
c[j+1] = b
c[j+2] = '"]=include[=['
c[j+3] = sub(view, e + 2, x)
c[j+4] = "]=]\n"
j=j+5
end
s, i = y - 1, y
end
end
end
elseif t == "#" then
local e = find(view, "#}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
e = e + 2
if sub(view, e, e) == "\n" then
e = e + 1
end
s, i = e - 1, e
end
end
end
s = find(view, "{", s + 1, true)
end
s = sub(view, i)
if s and s ~= "" then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = s
c[j+2] = "]=]\n"
j=j+3
end
c[j] = "return layout and include(layout,setmetatable({view=table.concat(___),blocks=blocks},{__index=context})) or table.concat(___)"
return concat(c)
end
function template.render(view, context, key, plain)
assert(view, "view was not provided for template.render(view, context, key, plain).")
return template.print(template.compile(view, key, plain)(context))
end
return template | apache-2.0 |
jshackley/darkstar | scripts/zones/Metalworks/npcs/Raibaht.lua | 17 | 3140 | -----------------------------------
-- Area: Metalworks
-- NPC: Raibaht
-- Starts and Finishes Quest: Dark Legacy
-- Involved in Quest: The Usual, Riding on the Clouds
-- @pos -27 -10 -1 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 7) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local darkLegacy = player:getQuestStatus(BASTOK,DARK_LEGACY);
local mLvl = player:getMainLvl();
local mJob = player:getMainJob();
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,5) == false) then
player:startEvent(0x03a5);
elseif (darkLegacy == QUEST_AVAILABLE and mJob == 8 and mLvl >= AF1_QUEST_LEVEL) then
player:startEvent(0x02ef); -- Start Quest "Dark Legacy"
elseif (player:hasKeyItem(DARKSTEEL_FORMULA)) then
player:startEvent(0x02f3); -- Finish Quest "Dark Legacy"
elseif (player:hasKeyItem(127) and player:getVar("TheUsual_Event") ~= 1) then
player:startEvent(0x01fe);
else
player:startEvent(0x01f5);
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 == 0x01fe and option == 0) then
player:setVar("TheUsual_Event",1);
elseif (csid == 0x02ef) then
player:addQuest(BASTOK,DARK_LEGACY);
player:setVar("darkLegacyCS",1);
elseif (csid == 0x02f3) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16798); -- Raven Scythe
else
player:delKeyItem(DARKSTEEL_FORMULA);
player:addItem(16798);
player:messageSpecial(ITEM_OBTAINED, 16798); -- Raven Scythe
player:setVar("darkLegacyCS",0);
player:addFame(BASTOK,AF1_FAME);
player:completeQuest(BASTOK,DARK_LEGACY);
end
elseif (csid == 0x03a5) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",5,true);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Nashmau/npcs/Tsutsuroon.lua | 38 | 1260 | -----------------------------------
-- Area: Nashmau
-- NPC: Tsutsuroon
-- Type: Tenshodo Merchant
-- @pos -15.193 0.000 31.356 53
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/keyitems");
require("scripts/zones/Nashmau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then
if (player:sendGuild(60431, 1, 23, 7)) then
player:showText(npc,TSUTSUROON_SHOP_DIALOG);
end
else
-- player:startEvent(0x0096);
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 |
Shrike78/Shilke2D | Samples/BitmapData/hitTestEx.lua | 1 | 5929 | --[[
The sample shows the usage of BitmapData hitTest/hitTestEx.
To better show collisions the viewport is scaled by a factor 2 in both directions.
This functions allow to make a per pixel hit test of two MOAIImages
(the extended version support also BitampRegions) given their relative
position and a minimum alpha level (per image) used to identify transparent
pixels.
The functions work only with CPU BitmapRegions (MOAIImages), not with textures
beacuse textures cannot be queried for pixel informations.
If a per pixel collision detection is required then it's possible to keep a
reference to the src MOAIImage and use it to make hit tests on Images/Textures.
NB: the functions work only with not scaled and not rotated images
--]]
-- uncomment to debug touch and keyboard callbacks. works with Mobdebug
--__DEBUG_CALLBACKS__ = true
--include Shilke2D lib
require("Shilke2D/include")
local WIDTH,HEIGHT = 512,340
local SCALEX,SCALEY = 2,2
local FPS = 60
--different alphalevels lead to different collision detection results.
--this value is used either for pixelHitTest configuration, either for
--collision detection between images
local ALPHALEVEL = 0
--the working dir of the application
IO.setWorkingDir("Assets/PlanetCute")
--used for collision detection in update call
local boyImg, girlImg
function setup()
local shilke = Shilke2D.current
--show as overlay fps and memory allocation
shilke:showStats(true,true)
--the stage is the base displayObjContainer of the scene. Everything need to be connected to the
--stage to be displayed.
local stage = shilke.stage
stage:setBackgroundColor(Color.GREY)
local planetCuteBmp = BitmapData.fromFile("PlanetCute_optimized.png")
local planetCuteTxt = Texture(planetCuteBmp)
local atlas = TexturePacker.loadSparrowFormat("PlanetCute_optimized.xml", planetCuteTxt)
local boyTxt = atlas:getTexture("Character Boy.png")
boyImg = Image(boyTxt)
boyImg:setPosition(WIDTH/4,2*HEIGHT/4)
boyImg:addEventListener(Event.TOUCH,onSpriteTouched)
stage:addChild(boyImg)
--we retrieve the subtexture that was originally "Character Cat Girl".png and that is now a subregion of
--the atlas texture
local girlTxt = atlas:getTexture("Character Cat Girl.png")
--we create a static img setting the Pivot in top center position
girlImg = Image(girlTxt)
girlImg:setPosition(3*WIDTH/4,2*HEIGHT/4)
girlImg:addEventListener(Event.TOUCH,onSpriteTouched)
stage:addChild(girlImg)
--setting framed to false would lead to higher memory usage (larger bitmaps) and
--worst performances (more pixel to test)
local framed = true
--Create two smaller framed MOAIImages and release larger planetCuteBmp
local boyBmp, boyFrame = BitmapData.cloneRegion(planetCuteBmp, boyTxt, framed)
local girlBmp, girlFrame = BitmapData.cloneRegion(planetCuteBmp, girlTxt, framed)
planetCuteBmp = nil
--enable pixelPrecisionHitTests using the newly created bitmap regions
boyImg:enablePixelHitTest(ALPHALEVEL, boyBmp, boyFrame)
girlImg:enablePixelHitTest(ALPHALEVEL, girlBmp, girlFrame)
local info = TextField(400,40,"Drag the characters and make them overlap.\nAlpha level is " .. ALPHALEVEL)
info:setPosition(WIDTH/2,80)
info:setHAlignment(TextField.CENTER_JUSTIFY)
stage:addChild(info)
collisionInfo = TextField(200,20, "")
collisionInfo:setPosition(WIDTH/2,120)
collisionInfo:setHAlignment(TextField.CENTER_JUSTIFY)
stage:addChild(collisionInfo)
end
--update is called once per frame and allows to logically update status of objects
function update(elapsedTime)
--the choosen textures have the same size. The images are both created with a default centered
--pivot point, so the position can be used to calculate hitTest without any correction, even if
--it refers to the center of the texture instead of the top left point
--In a different situation the two position should be calculated displacing the imgs position
--by their pivot position, or getting the bounds of images in stage target space and using the
--x,y coordinates of the resulting rect
local bx,by = boyImg:getPosition()
local gx,gy = girlImg:getPosition()
local bCollision = false
--get the required infos directly from images
local _, boyBmp, boyRegion = boyImg:getPixelHitTestParams()
local _, girlBmp, girlRegion = boyImg:getPixelHitTestParams()
--the method accepts a position and an alpha treshold for the first texture and a second texture with
--its position and alpha level.
bCollision = BitmapData.hitTestEx(boyBmp, bx, by, ALPHALEVEL, girlBmp, gx, gy, ALPHALEVEL, boyFrame, girlFrame, 2)
hitTestText = "hitTest"
--update test result message
collisionInfo:setText("hitTest = " .. tostring(bCollision))
end
function onSpriteTouched(e)
local touch = e.touch
local sender = e.sender
local target = e.target
if touch.state == Touch.BEGAN then
--calling this function force the touch manager to address always this object for
--touch/mouse events until Touch.ENDED state. That avoid other objects to steal the focus from the
--dragged one
Shilke2D.current:startDrag(touch,target)
--force to red to show that is currently 'attached'
target:setColor(255,128,128)
elseif touch.state == Touch.MOVING then
--check if the target exists: the sender notifies moving events the start inside it even if the
--move ending point is outside it, and so the target it's different or nil.
--If it exists and it's the same currently "dragged" by Shilke2D, then translate it
if target and target == Shilke2D.current:getDraggedObj(touch) then
--Global Translate allows to translate an obj based on stage coordinates.
target:globalTranslate(touch.deltaX,touch.deltaY)
end
else
--end of Touch event, reset to neutral color
target:setColor(255,255,255)
end
end
--shilke2D initialization. it requires width, height and fps. Optional a scale value for x / y.
shilke2D = Shilke2D(WIDTH,HEIGHT,FPS,SCALEX,SCALEY)
shilke2D:start() | mit |
jshackley/darkstar | scripts/globals/items/plate_of_mushroom_risotto.lua | 36 | 1383 | -----------------------------------------
-- ID: 4434
-- Item: Plate of Mushroom Risotto
-- Food Effect: 3 Hr, All Races
-----------------------------------------
-- MP 30
-- Strength -1
-- Vitality 3
-- Mind 3
-- 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,10800,4434);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 30);
target:addMod(MOD_STR, -1);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_MND, 3);
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 30);
target:delMod(MOD_STR, -1);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_MND, 3);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
ff94315/hiwifi-openwrt-HC5661-HC5761 | staging_dir/target-mipsel_r2_uClibc-0.9.33.2/root-ralink/usr/lib/lua/ssl/https.lua | 3 | 4086 | ----------------------------------------------------------------------------
-- LuaSec 0.4.1
-- Copyright (C) 2009-2011 PUC-Rio
--
-- Author: Pablo Musa
-- Author: Tomas Guisasola
---------------------------------------------------------------------------
local socket = require("socket")
local ssl = require("ssl")
local ltn12 = require("ltn12")
local http = require("socket.http")
local url = require("socket.url")
local table = require("table")
local string = require("string")
local try = socket.try
local type = type
local pairs = pairs
local getmetatable = getmetatable
local unpack = unpack
module("ssl.https")
_VERSION = "0.4.1"
_COPYRIGHT = "LuaSec 0.4.1 - Copyright (C) 2009-2011 PUC-Rio"
-- Default settings
PORT = 443
local cfg = {
protocol = "tlsv1",
options = "all",
verify = "none",
}
--------------------------------------------------------------------
-- Auxiliar Functions
--------------------------------------------------------------------
-- Insert default HTTPS port.
local function default_https_port(u)
return url.build(url.parse(u, {port = PORT}))
end
-- Convert an URL to a table according to Luasocket needs.
local function urlstring_totable(url, body, result_table)
url = {
url = default_https_port(url),
method = body and "POST" or "GET",
sink = ltn12.sink.table(result_table)
}
if body then
url.source = ltn12.source.string(body)
url.headers = {
["content-length"] = #body,
["content-type"] = "application/x-www-form-urlencoded",
}
end
return url
end
-- Forward calls to the real connection object.
local function reg(conn)
local mt = getmetatable(conn.sock).__index
for name, method in pairs(mt) do
if type(method) == "function" then
conn[name] = function (self, ...)
return method(self.sock, ...)
end
end
end
end
-- Return a function which performs the SSL/TLS connection.
local function tcp(params)
params = params or {}
-- Default settings
for k, v in pairs(cfg) do
params[k] = params[k] or v
end
-- Force client mode
params.mode = "client"
-- 'create' function for LuaSocket
return function ()
local conn = {}
conn.sock = try(socket.tcp())
local st = getmetatable(conn.sock).__index.settimeout
function conn:settimeout(...)
conn.timeout = {...}
return st(self.sock, ...)
end
-- Replace TCP's connection function
function conn:connect(host, port)
try(self.sock:connect(host, port))
self.sock = try(ssl.wrap(self.sock, params))
self.sock:settimeout(unpack(self.timeout))
try(self.sock:dohandshake())
reg(self, getmetatable(self.sock))
return 1
end
return conn
end
end
--------------------------------------------------------------------
-- Main Function
--------------------------------------------------------------------
-- Make a HTTP request over secure connection. This function receives
-- the same parameters of LuaSocket's HTTP module (except 'proxy' and
-- 'redirect') plus LuaSec parameters.
--
-- @param url mandatory (string or table)
-- @param body optional (string)
-- @return (string if url == string or 1), code, headers, status
--
function request(url, body)
local result_table = {}
local stringrequest = type(url) == "string"
if stringrequest then
url = urlstring_totable(url, body, result_table)
else
url.url = default_https_port(url.url)
end
if http.PROXY or url.proxy then
return nil, "proxy not supported"
elseif url.redirect then
return nil, "redirect not supported"
elseif url.create then
return nil, "create function not permitted"
end
-- New 'create' function to establish a secure connection
url.create = tcp(url)
local res, code, headers, status = http.request(url)
if res and stringrequest then
return table.concat(result_table), code, headers, status
end
return res, code, headers, status
end
| gpl-2.0 |
georgekang/jit-construct | dynasm/dasm_arm64.lua | 42 | 34807 | ------------------------------------------------------------------------------
-- DynASM ARM64 module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
-- Module information:
local _info = {
arch = "arm",
description = "DynASM ARM64 module",
version = "1.3.0",
vernum = 10300,
release = "2014-12-03",
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, setmetatable, rawget = assert, setmetatable, rawget
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub
local concat, sort, insert = table.concat, table.sort, table.insert
local bit = bit or require("bit")
local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift
local ror, tohex = bit.ror, bit.tohex
-- 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 = {
"STOP", "SECTION", "ESC", "REL_EXT",
"ALIGN", "REL_LG", "LABEL_LG",
"REL_PC", "LABEL_PC", "IMM", "IMM6", "IMM12", "IMM13W", "IMM13X", "IMML",
}
-- 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.
local map_action = {}
for n,name in ipairs(action_names) do
map_action[name] = n-1
end
-- Action list buffer.
local actlist = {}
-- 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
------------------------------------------------------------------------------
-- 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
if nn == 0 then nn = 1; actlist[0] = map_action.STOP end
out:write("static const unsigned int ", name, "[", nn, "] = {\n")
for i = 1,nn-1 do
assert(out:write("0x", tohex(actlist[i]), ",\n"))
end
assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n"))
end
------------------------------------------------------------------------------
-- Add word to action list.
local function wputxw(n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, val, a, num)
local w = assert(map_action[action], "bad action name `"..action.."'")
wputxw(w * 0x10000 + (val or 0))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
if #actlist == actargs[1] then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true)
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped word.
local function wputw(n)
if n <= 0x000fffff then waction("ESC") end
wputxw(n)
end
-- Reserve position for word.
local function wpos()
local pos = #actlist+1
actlist[pos] = ""
return pos
end
-- Store word to reserved position.
local function wputpos(pos, n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
if n <= 0x000fffff then
insert(actlist, pos+1, n)
n = map_action.ESC * 0x10000
end
actlist[pos] = n
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 20
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 > 2047 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=20,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=20,next_global-1 do
out:write(" ", prefix, 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=20,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 = 0
local map_extern_ = {}
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n > 2047 then werror("too many extern labels") end
next_extern = n + 1
t[name] = n
map_extern_[n] = name
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
out:write("Extern labels:\n")
for i=0,next_extern-1 do
out:write(format(" %s\n", map_extern_[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
out:write("static const char *const ", name, "[] = {\n")
for i=0,next_extern-1 do
out:write(" \"", map_extern_[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
-- Ext. register name -> int. name.
local map_archdef = { xzr = "@x31", wzr = "@w31", lr = "x30", }
-- Int. register name -> ext. name.
local map_reg_rev = { ["@x31"] = "xzr", ["@w31"] = "wzr", x30 = "lr", }
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for Dt... macros).
-- Reverse defines for registers.
function _M.revdef(s)
return map_reg_rev[s] or s
end
local map_shift = { lsl = 0, lsr = 1, asr = 2, }
local map_extend = {
uxtb = 0, uxth = 1, uxtw = 2, uxtx = 3,
sxtb = 4, sxth = 5, sxtw = 6, sxtx = 7,
}
local map_cond = {
eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7,
hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14,
hs = 2, lo = 3,
}
------------------------------------------------------------------------------
local parse_reg_type
local function parse_reg(expr)
if not expr then werror("expected register name") end
local tname, ovreg = match(expr, "^([%w_]+):(@?%l%d+)$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
if not reg then
werror("type `"..(tname or expr).."' needs a register override")
end
expr = reg
end
local ok31, rt, r = match(expr, "^(@?)([xwqdshb])([123]?[0-9])$")
if r then
r = tonumber(r)
if r <= 30 or (r == 31 and ok31 ~= "" or (rt ~= "w" and rt ~= "x")) then
if not parse_reg_type then
parse_reg_type = rt
elseif parse_reg_type ~= rt then
werror("register size mismatch")
end
return r, tp
end
end
werror("bad register name `"..expr.."'")
end
local function parse_reg_base(expr)
if expr == "sp" then return 0x3e0 end
local base, tp = parse_reg(expr)
if parse_reg_type ~= "x" then werror("bad register type") end
parse_reg_type = false
return shl(base, 5), tp
end
local parse_ctx = {}
local loadenv = setfenv and function(s)
local code = loadstring(s, "")
if code then setfenv(code, parse_ctx) end
return code
end or function(s)
return load(s, "", nil, parse_ctx)
end
-- Try to parse simple arithmetic, too, since some basic ops are aliases.
local function parse_number(n)
local x = tonumber(n)
if x then return x end
local code = loadenv("return "..n)
if code then
local ok, y = pcall(code)
if ok then return y end
end
return nil
end
local function parse_imm(imm, bits, shift, scale, signed)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n then
if signed then
local s = sar(m, bits-1)
if s == 0 then return shl(m, shift)
elseif s == -1 then return shl(m + shl(1, bits), shift) end
else
if sar(m, bits) == 0 then return shl(m, shift) end
end
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm)
return 0
end
end
local function parse_imm12(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
if shr(n, 12) == 0 then
return shl(n, 10)
elseif band(n, 0xff000fff) == 0 then
return shr(n, 2) + 0x00400000
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM12", 0, imm)
return 0
end
end
local function parse_imm13(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
local r64 = parse_reg_type == "x"
if n and n % 1 == 0 and n >= 0 and n <= 0xffffffff then
local inv = false
if band(n, 1) == 1 then n = bit.bnot(n); inv = true end
local t = {}
for i=1,32 do t[i] = band(n, 1); n = shr(n, 1) end
local b = table.concat(t)
b = b..(r64 and (inv and "1" or "0"):rep(32) or b)
local p0, p1, p0a, p1a = b:match("^(0+)(1+)(0*)(1*)")
if p0 then
local w = p1a == "" and (r64 and 64 or 32) or #p1+#p0a
if band(w, w-1) == 0 and b == b:sub(1, w):rep(64/w) then
local s = band(-2*w, 0x3f) - 1
if w == 64 then s = s + 0x1000 end
if inv then
return shl(w-#p1-#p0, 16) + shl(s+w-#p1, 10)
else
return shl(w-#p0, 16) + shl(s+#p1, 10)
end
end
end
werror("out of range immediate `"..imm.."'")
elseif r64 then
waction("IMM13X", 0, format("(unsigned int)(%s)", imm))
actargs[#actargs+1] = format("(unsigned int)((unsigned long long)(%s)>>32)", imm)
return 0
else
waction("IMM13W", 0, imm)
return 0
end
end
local function parse_imm6(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
if n >= 0 and n <= 63 then
return shl(band(n, 0x1f), 19) + (n >= 32 and 0x80000000 or 0)
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM6", 0, imm)
return 0
end
end
local function parse_imm_load(imm, scale)
local n = parse_number(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n and m >= 0 and m < 0x1000 then
return shl(m, 10) + 0x01000000 -- Scaled, unsigned 12 bit offset.
elseif n >= -256 and n < 256 then
return shl(band(n, 511), 12) -- Unscaled, signed 9 bit offset.
end
werror("out of range immediate `"..imm.."'")
else
waction("IMML", 0, imm)
return 0
end
end
local function parse_fpimm(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
local m, e = math.frexp(n)
local s, e2 = 0, band(e-2, 7)
if m < 0 then m = -m; s = 0x00100000 end
m = m*32-16
if m % 1 == 0 and m >= 0 and m <= 15 and sar(shl(e2, 29), 29)+2 == e then
return s + shl(e2, 17) + shl(m, 13)
end
werror("out of range immediate `"..imm.."'")
else
werror("NYI fpimm action")
end
end
local function parse_shift(expr)
local s, s2 = match(expr, "^(%S+)%s*(.*)$")
s = map_shift[s]
if not s then werror("expected shift operand") end
return parse_imm(s2, 6, 10, 0, false) + shl(s, 22)
end
local function parse_lslx16(expr)
local n = match(expr, "^lsl%s*#(%d+)$")
n = tonumber(n)
if not n then werror("expected shift operand") end
if band(n, parse_reg_type == "x" and 0xffffffcf or 0xffffffef) ~= 0 then
werror("bad shift amount")
end
return shl(n, 17)
end
local function parse_extend(expr)
local s, s2 = match(expr, "^(%S+)%s*(.*)$")
if s == "lsl" then
s = parse_reg_type == "x" and 3 or 2
else
s = map_extend[s]
end
if not s then werror("expected extend operand") end
return (s2 == "" and 0 or parse_imm(s2, 3, 10, 0, false)) + shl(s, 13)
end
local function parse_cond(expr, inv)
local c = map_cond[expr]
if not c then werror("expected condition operand") end
return shl(bit.bxor(c, inv), 12)
end
local function parse_load(params, nparams, n, op)
if params[n+2] then werror("too many operands") end
local pn, p2 = params[n], params[n+1]
local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$")
if not p1 then
if not p2 then
local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local base, tp = parse_reg_base(reg)
if tp then
waction("IMML", 0, format(tp.ctypefmt, tailr))
return op + base
end
end
end
werror("expected address operand")
end
local scale = shr(op, 30)
if p2 then
if wb == "!" then werror("bad use of '!'") end
op = op + parse_reg_base(p1) + parse_imm(p2, 9, 12, 0, true) + 0x400
elseif wb == "!" then
local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$")
if not p1a then werror("bad use of '!'") end
op = op + parse_reg_base(p1a) + parse_imm(p2a, 9, 12, 0, true) + 0xc00
else
local p1a, p2a = match(p1, "^([^,%s]*)%s*(.*)$")
op = op + parse_reg_base(p1a)
if p2a ~= "" then
local imm = match(p2a, "^,%s*#(.*)$")
if imm then
op = op + parse_imm_load(imm, scale)
else
local p2b, p3b, p3s = match(p2a, "^,%s*([^,%s]*)%s*,?%s*(%S*)%s*(.*)$")
op = op + shl(parse_reg(p2b), 16) + 0x00200800
if parse_reg_type ~= "x" and parse_reg_type ~= "w" then
werror("bad index register type")
end
if p3b == "" then
if parse_reg_type ~= "x" then werror("bad index register type") end
op = op + 0x6000
else
if p3s == "" or p3s == "#0" then
elseif p3s == "#"..scale then
op = op + 0x1000
else
werror("bad scale")
end
if parse_reg_type == "x" then
if p3b == "lsl" and p3s ~= "" then op = op + 0x6000
elseif p3b == "sxtx" then op = op + 0xe000
else
werror("bad extend/shift specifier")
end
else
if p3b == "uxtw" then op = op + 0x4000
elseif p3b == "sxtw" then op = op + 0xc000
else
werror("bad extend/shift specifier")
end
end
end
end
else
if wb == "!" then werror("bad use of '!'") end
op = op + 0x01000000
end
end
return op
end
local function parse_load_pair(params, nparams, n, op)
if params[n+2] then werror("too many operands") end
local pn, p2 = params[n], params[n+1]
local scale = shr(op, 30) == 0 and 2 or 3
local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$")
if not p1 then
if not p2 then
local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local base, tp = parse_reg_base(reg)
if tp then
waction("IMM", 32768+7*32+15+scale*1024, format(tp.ctypefmt, tailr))
return op + base + 0x01000000
end
end
end
werror("expected address operand")
end
if p2 then
if wb == "!" then werror("bad use of '!'") end
op = op + 0x00800000
else
local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$")
if p1a then p1, p2 = p1a, p2a else p2 = "#0" end
op = op + (wb == "!" and 0x01800000 or 0x01000000)
end
return op + parse_reg_base(p1) + parse_imm(p2, 7, 15, scale, true)
end
local function parse_label(label, def)
local prefix = sub(label, 1, 2)
-- =>label (pc label reference)
if prefix == "=>" then
return "PC", 0, sub(label, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "LG", map_global[sub(label, 3)]
end
if def then
-- [1-9] (local label definition)
if match(label, "^[1-9]$") then
return "LG", 10+tonumber(label)
end
else
-- [<>][1-9] (local label reference)
local dir, lnum = match(label, "^([<>])([1-9])$")
if dir then -- Fwd: 1-9, Bkwd: 11-19.
return "LG", lnum + (dir == ">" and 0 or 10)
end
-- extern label (extern label reference)
local extname = match(label, "^extern%s+(%S+)$")
if extname then
return "EXT", map_extern[extname]
end
end
werror("bad label `"..label.."'")
end
local function branch_type(op)
if band(op, 0x7c000000) == 0x14000000 then return 0 -- B, BL
elseif shr(op, 24) == 0x54 or band(op, 0x7e000000) == 0x34000000 or
band(op, 0x3b000000) == 0x18000000 then
return 0x800 -- B.cond, CBZ, CBNZ, LDR* literal
elseif band(op, 0x7e000000) == 0x36000000 then return 0x1000 -- TBZ, TBNZ
elseif band(op, 0x9f000000) == 0x10000000 then return 0x2000 -- ADR
elseif band(op, 0x9f000000) == band(0x90000000) then return 0x3000 -- ADRP
else
assert(false, "unknown branch type")
end
end
------------------------------------------------------------------------------
local map_op, op_template
local function op_alias(opname, f)
return function(params, nparams)
if not params then return "-> "..opname:sub(1, -3) end
f(params, nparams)
op_template(params, map_op[opname], nparams)
end
end
local function alias_bfx(p)
p[4] = "#("..p[3]:sub(2)..")+("..p[4]:sub(2)..")-1"
end
local function alias_bfiz(p)
parse_reg(p[1])
if parse_reg_type == "w" then
p[3] = "#-("..p[3]:sub(2)..")%32"
p[4] = "#("..p[4]:sub(2)..")-1"
else
p[3] = "#-("..p[3]:sub(2)..")%64"
p[4] = "#("..p[4]:sub(2)..")-1"
end
end
local alias_lslimm = op_alias("ubfm_4", function(p)
parse_reg(p[1])
local sh = p[3]:sub(2)
if parse_reg_type == "w" then
p[3] = "#-("..sh..")%32"
p[4] = "#31-("..sh..")"
else
p[3] = "#-("..sh..")%64"
p[4] = "#63-("..sh..")"
end
end)
-- Template strings for ARM instructions.
map_op = {
-- Basic data processing instructions.
add_3 = "0b000000DNMg|11000000pDpNIg|8b206000pDpNMx",
add_4 = "0b000000DNMSg|0b200000DNMXg|8b200000pDpNMXx|8b200000pDpNxMwX",
adds_3 = "2b000000DNMg|31000000DpNIg|ab206000DpNMx",
adds_4 = "2b000000DNMSg|2b200000DNMXg|ab200000DpNMXx|ab200000DpNxMwX",
cmn_2 = "2b00001fNMg|3100001fpNIg|ab20601fpNMx",
cmn_3 = "2b00001fNMSg|2b20001fNMXg|ab20001fpNMXx|ab20001fpNxMwX",
sub_3 = "4b000000DNMg|51000000pDpNIg|cb206000pDpNMx",
sub_4 = "4b000000DNMSg|4b200000DNMXg|cb200000pDpNMXx|cb200000pDpNxMwX",
subs_3 = "6b000000DNMg|71000000DpNIg|eb206000DpNMx",
subs_4 = "6b000000DNMSg|6b200000DNMXg|eb200000DpNMXx|eb200000DpNxMwX",
cmp_2 = "6b00001fNMg|7100001fpNIg|eb20601fpNMx",
cmp_3 = "6b00001fNMSg|6b20001fNMXg|eb20001fpNMXx|eb20001fpNxMwX",
neg_2 = "4b0003e0DMg",
neg_3 = "4b0003e0DMSg",
negs_2 = "6b0003e0DMg",
negs_3 = "6b0003e0DMSg",
adc_3 = "1a000000DNMg",
adcs_3 = "3a000000DNMg",
sbc_3 = "5a000000DNMg",
sbcs_3 = "7a000000DNMg",
ngc_2 = "5a0003e0DMg",
ngcs_2 = "7a0003e0DMg",
and_3 = "0a000000DNMg|12000000pDNig",
and_4 = "0a000000DNMSg",
orr_3 = "2a000000DNMg|32000000pDNig",
orr_4 = "2a000000DNMSg",
eor_3 = "4a000000DNMg|52000000pDNig",
eor_4 = "4a000000DNMSg",
ands_3 = "6a000000DNMg|72000000DNig",
ands_4 = "6a000000DNMSg",
tst_2 = "6a00001fNMg|7200001fNig",
tst_3 = "6a00001fNMSg",
bic_3 = "0a200000DNMg",
bic_4 = "0a200000DNMSg",
orn_3 = "2a200000DNMg",
orn_4 = "2a200000DNMSg",
eon_3 = "4a200000DNMg",
eon_4 = "4a200000DNMSg",
bics_3 = "6a200000DNMg",
bics_4 = "6a200000DNMSg",
movn_2 = "12800000DWg",
movn_3 = "12800000DWRg",
movz_2 = "52800000DWg",
movz_3 = "52800000DWRg",
movk_2 = "72800000DWg",
movk_3 = "72800000DWRg",
-- TODO: this doesn't cover all valid immediates for mov reg, #imm.
mov_2 = "2a0003e0DMg|52800000DW|320003e0pDig|11000000pDpNg",
mov_3 = "2a0003e0DMSg",
mvn_2 = "2a2003e0DMg",
mvn_3 = "2a2003e0DMSg",
adr_2 = "10000000DBx",
adrp_2 = "90000000DBx",
csel_4 = "1a800000DNMCg",
csinc_4 = "1a800400DNMCg",
csinv_4 = "5a800000DNMCg",
csneg_4 = "5a800400DNMCg",
cset_2 = "1a9f07e0Dcg",
csetm_2 = "5a9f03e0Dcg",
cinc_3 = "1a800400DNmcg",
cinv_3 = "5a800000DNmcg",
cneg_3 = "5a800400DNmcg",
ccmn_4 = "3a400000NMVCg|3a400800N5VCg",
ccmp_4 = "7a400000NMVCg|7a400800N5VCg",
madd_4 = "1b000000DNMAg",
msub_4 = "1b008000DNMAg",
mul_3 = "1b007c00DNMg",
mneg_3 = "1b00fc00DNMg",
smaddl_4 = "9b200000DxNMwAx",
smsubl_4 = "9b208000DxNMwAx",
smull_3 = "9b207c00DxNMw",
smnegl_3 = "9b20fc00DxNMw",
smulh_3 = "9b407c00DNMx",
umaddl_4 = "9ba00000DxNMwAx",
umsubl_4 = "9ba08000DxNMwAx",
umull_3 = "9ba07c00DxNMw",
umnegl_3 = "9ba0fc00DxNMw",
umulh_3 = "9bc07c00DNMx",
udiv_3 = "1ac00800DNMg",
sdiv_3 = "1ac00c00DNMg",
-- Bit operations.
sbfm_4 = "13000000DN12w|93400000DN12x",
bfm_4 = "33000000DN12w|b3400000DN12x",
ubfm_4 = "53000000DN12w|d3400000DN12x",
extr_4 = "13800000DNM2w|93c00000DNM2x",
sxtb_2 = "13001c00DNw|93401c00DNx",
sxth_2 = "13003c00DNw|93403c00DNx",
sxtw_2 = "93407c00DxNw",
uxtb_2 = "53001c00DNw",
uxth_2 = "53003c00DNw",
sbfx_4 = op_alias("sbfm_4", alias_bfx),
bfxil_4 = op_alias("bfm_4", alias_bfx),
ubfx_4 = op_alias("ubfm_4", alias_bfx),
sbfiz_4 = op_alias("sbfm_4", alias_bfiz),
bfi_4 = op_alias("bfm_4", alias_bfiz),
ubfiz_4 = op_alias("ubfm_4", alias_bfiz),
lsl_3 = function(params, nparams)
if params and params[3]:byte() == 35 then
return alias_lslimm(params, nparams)
else
return op_template(params, "1ac02000DNMg", nparams)
end
end,
lsr_3 = "1ac02400DNMg|53007c00DN1w|d340fc00DN1x",
asr_3 = "1ac02800DNMg|13007c00DN1w|9340fc00DN1x",
ror_3 = "1ac02c00DNMg|13800000DNm2w|93c00000DNm2x",
clz_2 = "5ac01000DNg",
cls_2 = "5ac01400DNg",
rbit_2 = "5ac00000DNg",
rev_2 = "5ac00800DNw|dac00c00DNx",
rev16_2 = "5ac00400DNg",
rev32_2 = "dac00800DNx",
-- Loads and stores.
["strb_*"] = "38000000DwL",
["ldrb_*"] = "38400000DwL",
["ldrsb_*"] = "38c00000DwL|38800000DxL",
["strh_*"] = "78000000DwL",
["ldrh_*"] = "78400000DwL",
["ldrsh_*"] = "78c00000DwL|78800000DxL",
["str_*"] = "b8000000DwL|f8000000DxL|bc000000DsL|fc000000DdL",
["ldr_*"] = "18000000DwB|58000000DxB|1c000000DsB|5c000000DdB|b8400000DwL|f8400000DxL|bc400000DsL|fc400000DdL",
["ldrsw_*"] = "98000000DxB|b8800000DxL",
-- NOTE: ldur etc. are handled by ldr et al.
["stp_*"] = "28000000DAwP|a8000000DAxP|2c000000DAsP|6c000000DAdP",
["ldp_*"] = "28400000DAwP|a8400000DAxP|2c400000DAsP|6c400000DAdP",
["ldpsw_*"] = "68400000DAxP",
-- Branches.
b_1 = "14000000B",
bl_1 = "94000000B",
blr_1 = "d63f0000Nx",
br_1 = "d61f0000Nx",
ret_0 = "d65f03c0",
ret_1 = "d65f0000Nx",
-- b.cond is added below.
cbz_2 = "34000000DBg",
cbnz_2 = "35000000DBg",
tbz_3 = "36000000DTBw|36000000DTBx",
tbnz_3 = "37000000DTBw|37000000DTBx",
-- Miscellaneous instructions.
-- TODO: hlt, hvc, smc, svc, eret, dcps[123], drps, mrs, msr
-- TODO: sys, sysl, ic, dc, at, tlbi
-- TODO: hint, yield, wfe, wfi, sev, sevl
-- TODO: clrex, dsb, dmb, isb
nop_0 = "d503201f",
brk_0 = "d4200000",
brk_1 = "d4200000W",
-- Floating point instructions.
fmov_2 = "1e204000DNf|1e260000DwNs|1e270000DsNw|9e660000DxNd|9e670000DdNx|1e201000DFf",
fabs_2 = "1e20c000DNf",
fneg_2 = "1e214000DNf",
fsqrt_2 = "1e21c000DNf",
fcvt_2 = "1e22c000DdNs|1e624000DsNd",
-- TODO: half-precision and fixed-point conversions.
fcvtas_2 = "1e240000DwNs|9e240000DxNs|1e640000DwNd|9e640000DxNd",
fcvtau_2 = "1e250000DwNs|9e250000DxNs|1e650000DwNd|9e650000DxNd",
fcvtms_2 = "1e300000DwNs|9e300000DxNs|1e700000DwNd|9e700000DxNd",
fcvtmu_2 = "1e310000DwNs|9e310000DxNs|1e710000DwNd|9e710000DxNd",
fcvtns_2 = "1e200000DwNs|9e200000DxNs|1e600000DwNd|9e600000DxNd",
fcvtnu_2 = "1e210000DwNs|9e210000DxNs|1e610000DwNd|9e610000DxNd",
fcvtps_2 = "1e280000DwNs|9e280000DxNs|1e680000DwNd|9e680000DxNd",
fcvtpu_2 = "1e290000DwNs|9e290000DxNs|1e690000DwNd|9e690000DxNd",
fcvtzs_2 = "1e380000DwNs|9e380000DxNs|1e780000DwNd|9e780000DxNd",
fcvtzu_2 = "1e390000DwNs|9e390000DxNs|1e790000DwNd|9e790000DxNd",
scvtf_2 = "1e220000DsNw|9e220000DsNx|1e620000DdNw|9e620000DdNx",
ucvtf_2 = "1e230000DsNw|9e230000DsNx|1e630000DdNw|9e630000DdNx",
frintn_2 = "1e244000DNf",
frintp_2 = "1e24c000DNf",
frintm_2 = "1e254000DNf",
frintz_2 = "1e25c000DNf",
frinta_2 = "1e264000DNf",
frintx_2 = "1e274000DNf",
frinti_2 = "1e27c000DNf",
fadd_3 = "1e202800DNMf",
fsub_3 = "1e203800DNMf",
fmul_3 = "1e200800DNMf",
fnmul_3 = "1e208800DNMf",
fdiv_3 = "1e201800DNMf",
fmadd_4 = "1f000000DNMAf",
fmsub_4 = "1f008000DNMAf",
fnmadd_4 = "1f200000DNMAf",
fnmsub_4 = "1f208000DNMAf",
fmax_3 = "1e204800DNMf",
fmaxnm_3 = "1e206800DNMf",
fmin_3 = "1e205800DNMf",
fminnm_3 = "1e207800DNMf",
fcmp_2 = "1e202000NMf|1e202008NZf",
fcmpe_2 = "1e202010NMf|1e202018NZf",
fccmp_4 = "1e200400NMVCf",
fccmpe_4 = "1e200410NMVCf",
fcsel_4 = "1e200c00DNMCf",
-- TODO: crc32*, aes*, sha*, pmull
-- TODO: SIMD instructions.
}
for cond,c in pairs(map_cond) do
map_op["b"..cond.."_1"] = tohex(0x54000000+c).."B"
end
------------------------------------------------------------------------------
-- Handle opcodes defined with template strings.
local function parse_template(params, template, nparams, pos)
local op = tonumber(sub(template, 1, 8), 16)
local n = 1
local rtt = {}
parse_reg_type = false
-- Process each character.
for p in gmatch(sub(template, 9), ".") do
local q = params[n]
if p == "D" then
op = op + parse_reg(q); n = n + 1
elseif p == "N" then
op = op + shl(parse_reg(q), 5); n = n + 1
elseif p == "M" then
op = op + shl(parse_reg(q), 16); n = n + 1
elseif p == "A" then
op = op + shl(parse_reg(q), 10); n = n + 1
elseif p == "m" then
op = op + shl(parse_reg(params[n-1]), 16)
elseif p == "p" then
if q == "sp" then params[n] = "@x31" end
elseif p == "g" then
if parse_reg_type == "x" then
op = op + 0x80000000
elseif parse_reg_type ~= "w" then
werror("bad register type")
end
parse_reg_type = false
elseif p == "f" then
if parse_reg_type == "d" then
op = op + 0x00400000
elseif parse_reg_type ~= "s" then
werror("bad register type")
end
parse_reg_type = false
elseif p == "x" or p == "w" or p == "d" or p == "s" then
if parse_reg_type ~= p then
werror("register size mismatch")
end
parse_reg_type = false
elseif p == "L" then
op = parse_load(params, nparams, n, op)
elseif p == "P" then
op = parse_load_pair(params, nparams, n, op)
elseif p == "B" then
local mode, v, s = parse_label(q, false); n = n + 1
local m = branch_type(op)
waction("REL_"..mode, v+m, s, 1)
elseif p == "I" then
op = op + parse_imm12(q); n = n + 1
elseif p == "i" then
op = op + parse_imm13(q); n = n + 1
elseif p == "W" then
op = op + parse_imm(q, 16, 5, 0, false); n = n + 1
elseif p == "T" then
op = op + parse_imm6(q); n = n + 1
elseif p == "1" then
op = op + parse_imm(q, 6, 16, 0, false); n = n + 1
elseif p == "2" then
op = op + parse_imm(q, 6, 10, 0, false); n = n + 1
elseif p == "5" then
op = op + parse_imm(q, 5, 16, 0, false); n = n + 1
elseif p == "V" then
op = op + parse_imm(q, 4, 0, 0, false); n = n + 1
elseif p == "F" then
op = op + parse_fpimm(q); n = n + 1
elseif p == "Z" then
if q ~= "#0" and q ~= "#0.0" then werror("expected zero immediate") end
n = n + 1
elseif p == "S" then
op = op + parse_shift(q); n = n + 1
elseif p == "X" then
op = op + parse_extend(q); n = n + 1
elseif p == "R" then
op = op + parse_lslx16(q); n = n + 1
elseif p == "C" then
op = op + parse_cond(q, 0); n = n + 1
elseif p == "c" then
op = op + parse_cond(q, 1); n = n + 1
else
assert(false)
end
end
wputpos(pos, op)
end
function op_template(params, template, nparams)
if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 3 positions.
if secpos+3 > maxsecpos then wflush() end
local pos = wpos()
local lpos, apos, spos = #actlist, #actargs, secpos
local ok, err
for t in gmatch(template, "[^|]+") do
ok, err = pcall(parse_template, params, t, nparams, pos)
if ok then return end
secpos = spos
actlist[lpos+1] = nil
actlist[lpos+2] = nil
actlist[lpos+3] = nil
actargs[apos+1] = nil
actargs[apos+2] = nil
actargs[apos+3] = nil
end
error(err, 0)
end
map_op[".template__"] = op_template
------------------------------------------------------------------------------
-- 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_1"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr" end
if secpos+1 > maxsecpos then wflush() end
local mode, n, s = parse_label(params[1], true)
if mode == "EXT" then werror("bad label definition") end
waction("LABEL_"..mode, n, s, 1)
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
map_op[".long_*"] = function(params)
if not params then return "imm..." end
for _,p in ipairs(params) do
local n = tonumber(p)
if not n then werror("bad immediate `"..p.."'") end
if n < 0 then n = n + 2^32 end
wputw(n)
if secpos+2 > maxsecpos then wflush() end
end
end
-- 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])
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", align-1, nil, 1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
------------------------------------------------------------------------------
-- 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
-- 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 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", 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))
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
------------------------------------------------------------------------------
| bsd-2-clause |
jshackley/darkstar | scripts/globals/spells/carnage_elegy.lua | 18 | 1702 | -----------------------------------------
-- Spell: Battlefield Elegy
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local duration = 180;
local power = 512;
local pCHR = caster:getStat(MOD_CHR);
local mCHR = target:getStat(MOD_CHR);
local dCHR = (pCHR - mCHR);
local resm = applyResistance(caster,spell,target,dCHR,SINGING_SKILL,0);
if (resm < 0.5) then
spell:setMsg(85);--resist message
return 1;
end
if (100 * math.random() < target:getMod(MOD_SLOWRES)) then
spell:setMsg(85); -- resisted spell
else
local iBoost = caster:getMod(MOD_ELEGY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost*10;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
-- Try to overwrite weaker elegy
if (target:addStatusEffect(EFFECT_ELEGY,power,0,duration)) then
spell:setMsg(237);
else
spell:setMsg(75); -- no effect
end
end
return EFFECT_ELEGY;
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/marinara_pizza_+1.lua | 14 | 1646 | -----------------------------------------
-- ID: 5744
-- Item: marinara_pizza +1
-- Food Effect: 4hours, All Races
-----------------------------------------
-- Health Points 25
-- Attack +21% (cap 55)
-- Accuracy +11% (cap 58)
-- Undead Killer
-----------------------------------------
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,14400,5744);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 25);
target:addMod(MOD_FOOD_ATTP, 21);
target:addMod(MOD_FOOD_ATT_CAP, 55);
target:addMod(MOD_FOOD_ACCP, 11);
target:addMod(MOD_FOOD_ACC_CAP, 58);
target:addMod(MOD_UNDEAD_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 25);
target:delMod(MOD_FOOD_ATTP, 21);
target:delMod(MOD_FOOD_ATT_CAP, 55);
target:delMod(MOD_FOOD_ACCP, 11);
target:delMod(MOD_FOOD_ACC_CAP, 58);
target:delMod(MOD_UNDEAD_KILLER, 5);
end;
| gpl-3.0 |
marcparadise/chef-server | omnibus/tests/routing/default_org_route_test.lua | 11 | 1660 | -- Default Org tests.
-- Default Org
table.insert(shared_chef_tests, {"/nodes", {TEST_ORG, "erchef", "nodes"}})
table.insert(shared_chef_tests, {"/nodes/", {TEST_ORG, "erchef", "nodes"}})
table.insert(shared_chef_tests, {"/environments/envname/nodes", {TEST_ORG, "erchef", "environments", "envname"}})
table.insert(shared_chef_tests, {"/environments/envname/nodes/", {TEST_ORG, "erchef", "environments", "envname"}})
table.insert(shared_chef_tests, {"/environments/envname/node", {TEST_ORG, "erchef", "environments", "envname"}})
table.insert(shared_chef_tests, {"/environments/envname/nodesbad", {TEST_ORG, "erchef", "environments", "envname"}})
table.insert(shared_chef_tests, {"/search", {TEST_ORG, "erchef", "search"}})
table.insert(shared_chef_tests, {"/search/", {TEST_ORG, "erchef", "search"}})
table.insert(shared_chef_tests, {"/search/blah", {TEST_ORG, "erchef", "search"}})
table.insert(shared_chef_tests, {"/search?x=1", {TEST_ORG, "erchef", "search"}})
for _k, val in pairs{ "cookbooks", "data" ,"roles", "sandboxes", "environments", "clients", "nodes" } do
table.insert(shared_chef_tests, {"/" .. val, {TEST_ORG, "erchef", val}})
table.insert(shared_chef_tests, {"/" .. val .. "/", {TEST_ORG, "erchef", val}})
table.insert(shared_chef_tests, {"/" .. val .. "/abc", {TEST_ORG, "erchef", val, "abc"}})
table.insert(shared_chef_tests, {"/" .. val .. "/abc/subcomponent", {TEST_ORG, "erchef", val, "abc"}})
table.insert(shared_chef_tests, {"/" .. val .. "/b@d!dent", {TEST_ORG, "erchef", val, "b@d!dent"}})
end
| apache-2.0 |
myth384/AdiButtonAuras | rules/Warrior.lua | 1 | 3692 | --[[
AdiButtonAuras - Display auras on action buttons.
Copyright 2013-2014 Adirelle (adirelle@gmail.com)
All rights reserved.
This file is part of AdiButtonAuras.
AdiButtonAuras 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.
AdiButtonAuras 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 AdiButtonAuras. If not, see <http://www.gnu.org/licenses/>.
--]]
local _, addon = ...
if not addon.isClass("WARRIOR") then return end
AdiButtonAuras:RegisterRules(function()
Debug('Adding warrior rules')
return {
ImportPlayerSpells { "WARRIOR" },
-- Shield Barrier
Configure {
"Shield Barrier",
L['Suggest using Shield Barrier at 60 Rage or more. Flash at maximum Rage.'],
112048, -- Shield Barrier
"player",
{ "UNIT_POWER_FREQUENT", "UNIT_MAXPOWER" },
function(_, model)
local power = UnitPower("player")
if power == UnitPowerMax("player") then
model.flash = true
elseif power >= 60 then
model.hint = true
end
end,
112048, -- Shield Barrier (Protection only)
},
-- Rend
Configure {
"RefreshRend",
format(
L["%s when your debuff %s should be refreshed on %s."],
DescribeHighlight("flash"), -- hint or flash
GetSpellInfo(772), -- Rend
DescribeAllTokens("enemy") -- enemy string
),
772, -- Rend
"enemy",
{ "UNIT_AURA", "UNIT_COMBAT" }, -- fast enough to be usable
function(units, model)
local _, _, expiration = GetPlayerDebuff(units.enemy, 772)
if expiration then
local rendDuration = 18 -- Rend lasts 18s
local refreshWindow = rendDuration * 0.3 -- New 30% rule for WoD ticks
if expiration - GetTime() < refreshWindow then -- abuse sub 30% double tick mechanic :)
model.flash = true -- flash is better for this
end
end
end,
772, -- Rend (Arms only)
},
-- Execute
Configure {
"Execute",
format(
L["%s when %s is below %s%% health."],
DescribeHighlight("flash"),
DescribeAllTokens("enemy"),
20
),
{ 5308, 163201 }, -- Execute
"enemy",
{ "UNIT_HEALTH", "UNIT_MAXHEALTH" },
function(units, model)
local foe = units.enemy
if UnitHealth(foe) / UnitHealthMax(foe) <= 0.20 then
model.flash = true
end
end,
},
}
end)
-- GLOBALS: AddRuleFor BuffAliases BuildAuraHandler_FirstOf BuildAuraHandler_Longest
-- GLOBALS: BuildAuraHandler_Single BuildDesc BuildKey Configure DebuffAliases Debug
-- GLOBALS: DescribeAllSpells DescribeAllTokens DescribeFilter DescribeHighlight
-- GLOBALS: DescribeLPSSource GetComboPoints GetEclipseDirection GetNumGroupMembers
-- GLOBALS: GetShapeshiftFormID GetSpellBonusHealing GetSpellInfo GetTime
-- GLOBALS: GetTotemInfo HasPetSpells ImportPlayerSpells L LongestDebuffOf
-- GLOBALS: PLAYER_CLASS PassiveModifier PetBuffs SelfBuffAliases SelfBuffs
-- GLOBALS: SharedSimpleBuffs SharedSimpleDebuffs ShowPower SimpleBuffs
-- GLOBALS: SimpleDebuffs UnitCanAttack UnitCastingInfo UnitChannelInfo UnitClass
-- GLOBALS: UnitHealth UnitHealthMax UnitIsDeadOrGhost UnitIsPlayer UnitPower
-- GLOBALS: UnitPowerMax UnitStagger bit ceil floor format ipairs math min pairs
-- GLOBALS: print select string table tinsert GetPlayerBuff GetPlayerDebuff ShowStacks
| gpl-3.0 |
GradysGhost/gradysghost-admin-tools | config/awesome/rc.lua | 1 | 16167 | -- Standard awesome library
require("awful")
require("awful.autofocus")
require("awful.rules")
-- Theme handling library
require("beautiful")
-- Notification library
require("naughty")
-- Load Debian menu entries
require("debian.menu")
-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, there were errors during startup!",
text = awesome.startup_errors })
end
-- Handle runtime errors after startup
do
local in_error = false
awesome.add_signal("debug::error", function (err)
-- Make sure we don't go into an endless error loop
if in_error then return end
in_error = true
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, an error happened!",
text = err })
in_error = false
end)
end
-- }}}
-- {{{ Variable definitions
-- Themes define colours, icons, and wallpapers
beautiful.init("/home/ryan/.config/awesome/theme.lua")
-- This is used later as the default terminal and editor to run.
terminal = "x-terminal-emulator"
editor = os.getenv("EDITOR") or "editor"
editor_cmd = terminal .. " -e " .. editor
file_browser = "nautilus"
graphical_editor = "geany"
xlock = "xlock"
volume = "gnome-sound-applet"
-- Default modkey.
-- Usually, Mod4 is the key with a logo between Control and Alt.
-- If you do not like this or do not have such a key,
-- I suggest you to remap Mod4 to another key using xmodmap or other tools.
-- However, you can use another modifier like Mod1, but it may interact with others.
modkey = "Mod4"
-- Table of layouts to cover with awful.layout.inc, order matters.
layouts =
{
awful.layout.suit.spiral.dwindle,
awful.layout.suit.magnifier,
awful.layout.suit.floating,
awful.layout.suit.tile,
awful.layout.suit.tile.left,
awful.layout.suit.tile.bottom,
awful.layout.suit.tile.top,
awful.layout.suit.fair,
awful.layout.suit.fair.horizontal,
awful.layout.suit.spiral,
awful.layout.suit.max,
awful.layout.suit.max.fullscreen
}
-- }}}
-- {{{ Tags
-- Define a tag table which hold all screen tags.
tags = {}
for s = 1, screen.count() do
-- Each screen has its own tag table.
tags[s] = awful.tag({ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}, s, layouts[1])
end
-- }}}
-- {{{ Menu
-- Create a laucher widget and a main menu
myawesomemenu = {
{ "Work Layout", "/home/ryan/.worklayout" },
{ "manual", terminal .. " -e man awesome" },
{ "edit config", editor_cmd .. " " .. awesome.conffile },
{ "restart", awesome.restart },
{ "quit", awesome.quit }
}
mymainmenu = awful.menu({ items = { { "awesome", myawesomemenu, beautiful.awesome_icon },
{ "Debian", debian.menu.Debian_menu.Debian },
{ "open terminal", terminal }
}
})
mylauncher = awful.widget.launcher({ image = image(beautiful.awesome_icon),
menu = mymainmenu })
-- }}}
-- {{{ Wibox
-- Create a textclock widget
mytextclock = awful.widget.textclock({ align = "right" })
-- Create a systray
mysystray = widget({ type = "systray" })
-- Create a wibox for each screen and add it
mywibox = {}
mypromptbox = {}
mylayoutbox = {}
mytaglist = {}
mytaglist.buttons = awful.util.table.join(
awful.button({ }, 1, awful.tag.viewonly),
awful.button({ modkey }, 1, awful.client.movetotag),
awful.button({ }, 3, awful.tag.viewtoggle),
awful.button({ modkey }, 3, awful.client.toggletag),
awful.button({ }, 4, awful.tag.viewnext),
awful.button({ }, 5, awful.tag.viewprev)
)
mytasklist = {}
mytasklist.buttons = awful.util.table.join(
awful.button({ }, 1, function (c)
if c == client.focus then
c.minimized = true
else
if not c:isvisible() then
awful.tag.viewonly(c:tags()[1])
end
-- This will also un-minimize
-- the client, if needed
client.focus = c
c:raise()
end
end),
awful.button({ }, 3, function ()
if instance then
instance:hide()
instance = nil
else
instance = awful.menu.clients({ width=250 })
end
end),
awful.button({ }, 4, function ()
awful.client.focus.byidx(1)
if client.focus then client.focus:raise() end
end),
awful.button({ }, 5, function ()
awful.client.focus.byidx(-1)
if client.focus then client.focus:raise() end
end))
for s = 1, screen.count() do
-- Create a promptbox for each screen
mypromptbox[s] = awful.widget.prompt({ layout = awful.widget.layout.horizontal.leftright })
-- Create an imagebox widget which will contains an icon indicating which layout we're using.
-- We need one layoutbox per screen.
mylayoutbox[s] = awful.widget.layoutbox(s)
mylayoutbox[s]:buttons(awful.util.table.join(
awful.button({ }, 1, function () awful.layout.inc(layouts, 1) end),
awful.button({ }, 3, function () awful.layout.inc(layouts, -1) end),
awful.button({ }, 4, function () awful.layout.inc(layouts, 1) end),
awful.button({ }, 5, function () awful.layout.inc(layouts, -1) end)))
-- Create a taglist widget
mytaglist[s] = awful.widget.taglist(s, awful.widget.taglist.label.all, mytaglist.buttons)
-- Create a tasklist widget
mytasklist[s] = awful.widget.tasklist(function(c)
return awful.widget.tasklist.label.currenttags(c, s)
end, mytasklist.buttons)
-- Create the wibox
mywibox[s] = awful.wibox({ position = "top", screen = s })
-- Add widgets to the wibox - order matters
mywibox[s].widgets = {
{
mylauncher,
mytaglist[s],
mypromptbox[s],
layout = awful.widget.layout.horizontal.leftright
},
mylayoutbox[s],
mytextclock,
s == 1 and mysystray or nil,
mytasklist[s],
layout = awful.widget.layout.horizontal.rightleft
}
end
-- }}}
-- {{{ Mouse bindings
root.buttons(awful.util.table.join(
awful.button({ }, 3, function () mymainmenu:toggle() end),
awful.button({ }, 4, awful.tag.viewnext),
awful.button({ }, 5, awful.tag.viewprev)
))
-- }}}
-- {{{ Key bindings
globalkeys = awful.util.table.join(
awful.key({ modkey, }, "Left", awful.tag.viewprev ),
awful.key({ modkey, }, "Right", awful.tag.viewnext ),
awful.key({ modkey, }, "Escape", awful.tag.history.restore),
awful.key({ modkey, }, "j",
function ()
awful.client.focus.byidx( 1)
if client.focus then client.focus:raise() end
end),
awful.key({ modkey, }, "k",
function ()
awful.client.focus.byidx(-1)
if client.focus then client.focus:raise() end
end),
awful.key({ modkey, }, "w", function () mymainmenu:show({keygrabber=true}) end),
-- Layout manipulation
awful.key({ modkey, "Shift" }, "j", function () awful.client.swap.byidx( 1) end),
awful.key({ modkey, "Shift" }, "k", function () awful.client.swap.byidx( -1) end),
awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end),
awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end),
awful.key({ modkey, }, "u", awful.client.urgent.jumpto),
awful.key({ modkey, }, "Tab",
function ()
awful.client.focus.history.previous()
if client.focus then
client.focus:raise()
end
end),
-- Standard program
awful.key({ modkey, }, "Return", function () awful.util.spawn(terminal) end),
awful.key({ modkey, }, "f", function () awful.util.spawn(file_browser) end),
awful.key({ modkey, }, "e", function () awful.util.spawn(graphical_editor) end),
awful.key({ modkey, }, "l", function () awful.util.spawn(xlock) end),
awful.key({ modkey, }, "p", function() awful.util.spawn("gnome-screenshot -i") end),
awful.key({ modkey, "Control" }, "r", awesome.restart),
awful.key({ modkey, "Shift" }, "q", awesome.quit),
awful.key({ modkey, }, "l", function () awful.tag.incmwfact( 0.05) end),
awful.key({ modkey, }, "h", function () awful.tag.incmwfact(-0.05) end),
awful.key({ modkey, "Shift" }, "h", function () awful.tag.incnmaster( 1) end),
awful.key({ modkey, "Shift" }, "l", function () awful.tag.incnmaster(-1) end),
awful.key({ modkey, "Control" }, "h", function () awful.tag.incncol( 1) end),
awful.key({ modkey, "Control" }, "l", function () awful.tag.incncol(-1) end),
awful.key({ modkey, }, "space", function () awful.layout.inc(layouts, 1) end),
awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(layouts, -1) end),
awful.key({ modkey, "Control" }, "n", awful.client.restore),
-- Prompt
awful.key({ modkey }, "r", function () mypromptbox[mouse.screen]:run() end),
awful.key({ modkey }, "x",
function ()
awful.prompt.run({ prompt = "Run Lua code: " },
mypromptbox[mouse.screen].widget,
awful.util.eval, nil,
awful.util.getdir("cache") .. "/history_eval")
end)
)
clientkeys = awful.util.table.join(
awful.key({ modkey, }, "f", function (c) c.fullscreen = not c.fullscreen end),
awful.key({ modkey, "Shift" }, "c", function (c) c:kill() end),
awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle ),
awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end),
awful.key({ modkey, }, "o", awful.client.movetoscreen ),
awful.key({ modkey, "Shift" }, "r", function (c) c:redraw() end),
awful.key({ modkey, }, "t", function (c) c.ontop = not c.ontop end),
awful.key({ modkey, }, "n",
function (c)
-- The client currently has the input focus, so it cannot be
-- minimized, since minimized clients can't have the focus.
c.minimized = true
end),
awful.key({ modkey, }, "m",
function (c)
c.maximized_horizontal = not c.maximized_horizontal
c.maximized_vertical = not c.maximized_vertical
end)
)
-- Compute the maximum number of digit we need, limited to 9
keynumber = 0
for s = 1, screen.count() do
keynumber = math.min(9, math.max(#tags[s], keynumber));
end
-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it works on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, keynumber do
globalkeys = awful.util.table.join(globalkeys,
awful.key({ modkey }, "#" .. i + 9,
function ()
local screen = mouse.screen
if tags[screen][i] then
awful.tag.viewonly(tags[screen][i])
end
end),
awful.key({ modkey, "Control" }, "#" .. i + 9,
function ()
local screen = mouse.screen
if tags[screen][i] then
awful.tag.viewtoggle(tags[screen][i])
end
end),
awful.key({ modkey, "Shift" }, "#" .. i + 9,
function ()
if client.focus and tags[client.focus.screen][i] then
awful.client.movetotag(tags[client.focus.screen][i])
end
end),
awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
function ()
if client.focus and tags[client.focus.screen][i] then
awful.client.toggletag(tags[client.focus.screen][i])
end
end))
end
clientbuttons = awful.util.table.join(
awful.button({ }, 1, function (c) client.focus = c; c:raise() end),
awful.button({ modkey }, 1, awful.mouse.client.move),
awful.button({ modkey }, 3, awful.mouse.client.resize))
-- Set keys
root.keys(globalkeys)
-- }}}
-- {{{ Rules
awful.rules.rules = {
-- All clients will match this rule.
{ rule = { },
properties = { border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = true,
keys = clientkeys,
buttons = clientbuttons } },
{ rule = { class = "MPlayer" },
properties = { floating = true } },
{ rule = { class = "pinentry" },
properties = { floating = true } },
{ rule = { class = "gimp" },
properties = { floating = true } },
-- Set Firefox to always map on tags number 2 of screen 1.
-- { rule = { class = "Firefox" },
-- properties = { tag = tags[1][2] } },
}
-- }}}
-- {{{ Signals
-- Signal function to execute when a new client appears.
client.add_signal("manage", function (c, startup)
-- Add a titlebar
-- awful.titlebar.add(c, { modkey = modkey })
-- Enable sloppy focus
c:add_signal("mouse::enter", function(c)
if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
and awful.client.focus.filter(c) then
client.focus = c
end
end)
if not startup then
-- Set the windows at the slave,
-- i.e. put it at the end of others instead of setting it master.
-- awful.client.setslave(c)
-- Put windows in a smart way, only if they does not set an initial position.
if not c.size_hints.user_position and not c.size_hints.program_position then
awful.placement.no_overlap(c)
awful.placement.no_offscreen(c)
end
end
end)
client.add_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.add_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- }}}
awful.util.spawn_with_shell("xrandr --output HDMI2 --mode 1920x1080 --output HDMI3 --mode 1920x1080 --right-of HDMI2");
awful.util.spawn(volume);
awful.util.spawn("bash /home/ryan/.desktop");
awful.util.spawn("glippy");
| gpl-3.0 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/TurnOffTiles.lua | 3 | 1326 |
--------------------------------
-- @module TurnOffTiles
-- @extend TiledGrid3DAction
--------------------------------
-- @function [parent=#TurnOffTiles] turnOnTile
-- @param self
-- @param #cc.Vec2 vec2
--------------------------------
-- @function [parent=#TurnOffTiles] turnOffTile
-- @param self
-- @param #cc.Vec2 vec2
--------------------------------
-- @function [parent=#TurnOffTiles] shuffle
-- @param self
-- @param #unsigned int int
-- @param #unsigned int int
--------------------------------
-- overload function: create(float, size_table, unsigned int)
--
-- overload function: create(float, size_table)
--
-- @function [parent=#TurnOffTiles] create
-- @param self
-- @param #float float
-- @param #size_table size
-- @param #unsigned int int
-- @return TurnOffTiles#TurnOffTiles ret (retunr value: cc.TurnOffTiles)
--------------------------------
-- @function [parent=#TurnOffTiles] startWithTarget
-- @param self
-- @param #cc.Node node
--------------------------------
-- @function [parent=#TurnOffTiles] clone
-- @param self
-- @return TurnOffTiles#TurnOffTiles ret (return value: cc.TurnOffTiles)
--------------------------------
-- @function [parent=#TurnOffTiles] update
-- @param self
-- @param #float float
return nil
| mit |
jshackley/darkstar | scripts/globals/spells/dokumori_san.lua | 18 | 1204 | -----------------------------------------
-- Spell: Dokumori: San
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effect = EFFECT_POISON;
-- Base Stats
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
--Duration Calculation
local duration = 360 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0);
local power = 20;
--Calculates resist chanve from Reist Blind
if (target:hasStatusEffect(effect)) then
spell:setMsg(75); -- no effect
return effect;
end
if (math.random(0,100) >= target:getMod(MOD_POISONRES)) then
if (duration >= 120) then
if (target:addStatusEffect(effect,power,3,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end
else
spell:setMsg(284);
end
return effect;
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/LaLoff_Amphitheater/bcnms/ark_angels_1.lua | 17 | 3035 | -----------------------------------
-- Area: LaLoff Amphitheater
-- Name: Ark Angels 1 (Hume)
-----------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
-----------------------------------
-- Death cutscenes:
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- Hume
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvan
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompletedMission(ZILART,ARK_ANGELS)) then
player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,0,1); -- winning CS (allow player to skip)
else
player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,0,0); -- winning CS (allow player to skip)
end
elseif (leavecode == 4) then
player:startEvent(0x7d02, 0, 0, 0, 0, 0, instance:getEntrance(), 180); -- player lost
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
local AAKeyitems = (player:hasKeyItem(SHARD_OF_ARROGANCE) and player:hasKeyItem(SHARD_OF_COWARDICE)
and player:hasKeyItem(SHARD_OF_ENVY) and player:hasKeyItem(SHARD_OF_RAGE));
if (csid == 0x7d01) then
if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then
player:addKeyItem(SHARD_OF_APATHY);
player:messageSpecial(KEYITEM_OBTAINED,SHARD_OF_APATHY);
if (AAKeyitems == true) then
player:completeMission(ZILART,ARK_ANGELS);
player:addMission(ZILART,THE_SEALED_SHRINE);
player:setVar("ZilartStatus",0);
end
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/dried_date_+1.lua | 35 | 1357 | -----------------------------------------
-- ID: 5574
-- Item: dried_date_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 12
-- Magic 22
-- Agility -1
-- Intelligence 4
-----------------------------------------
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,5574);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 12);
target:addMod(MOD_MP, 22);
target:addMod(MOD_AGI, -1);
target:addMod(MOD_INT, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 12);
target:delMod(MOD_MP, 22);
target:delMod(MOD_AGI, -1);
target:delMod(MOD_INT, 4);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Woods/npcs/Kopua-Mobua_AMAN.lua | 62 | 1375 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Kopua-Mobua A.M.A.N.
-- Type: Mentor Recruiter
-- @pos -23.134 1.749 -67.284 241
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local var = 0;
if (player:getMentor() == 0) then
if (player:getMainLvl() >= 30 and player:getPlaytime() >= 648000) then
var = 1;
end
elseif (player:getMentor() >= 1) then
var = 2;
end
player:startEvent(0X272A, var);
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 == 0X272A and option == 0) then
player:setMentor(1);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Dynamis-Beaucedine/Zone.lua | 28 | 2655 | -----------------------------------
--
-- Zone: Dynamis-Beaucedine
--
-----------------------------------
package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Dynamis-Beaucedine/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-284.751,-39.923,-422.948,235);
end
if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaBeaucedine]UniqueID")) then
if (player:isBcnmsFull() == 1) then
if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then
inst = player:addPlayerToDynamis(1284);
if (inst == 1) then
player:bcnmEnter(1284);
else
cs = 0;
end
else
player:bcnmEnter(1284);
end
else
inst = player:bcnmRegister(1284);
if (inst == 1) then
player:bcnmEnter(1284);
else
cs = 0;
end
end
else
cs = 0;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0) then
player:setPos(-284.751,-39.923,-422.948,235,0x6F);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Cloister_of_Frost/npcs/Cermet_Headstone.lua | 17 | 2645 | -----------------------------------
-- Area: Cloister of Frost
-- NPC: Cermet Headstone
-- Involved in Mission: ZM5 Headstone Pilgrimage (Ice Fragment)
-- @pos 566 0 606 203
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Frost/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/missions");
require("scripts/zones/Cloister_of_Frost/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then
if (player:hasKeyItem(ICE_FRAGMENT) == false) then
player:startEvent(0x00C8,ICE_FRAGMENT);
elseif (player:hasKeyItem(239) and player:hasKeyItem(240) and player:hasKeyItem(241) and
player:hasKeyItem(242) and player:hasKeyItem(243) and player:hasKeyItem(244) and
player:hasKeyItem(245) and player:hasKeyItem(246)) then
player:messageSpecial(ALREADY_HAVE_ALL_FRAGS);
elseif (player:hasKeyItem(ICE_FRAGMENT)) then
player:messageSpecial(ALREADY_OBTAINED_FRAG,ICE_FRAGMENT);
end
elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then
player:messageSpecial(ZILART_MONUMENT);
else
player:messageSpecial(CANNOT_REMOVE_FRAG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x00C8 and option == 1) then
player:addKeyItem(ICE_FRAGMENT);
-- Check and see if all fragments have been found (no need to check ice and dark frag)
if (player:hasKeyItem(FIRE_FRAGMENT) and player:hasKeyItem(EARTH_FRAGMENT) and player:hasKeyItem(WATER_FRAGMENT) and
player:hasKeyItem(WIND_FRAGMENT) and player:hasKeyItem(LIGHTNING_FRAGMENT) and player:hasKeyItem(LIGHT_FRAGMENT)) then
player:messageSpecial(FOUND_ALL_FRAGS,ICE_FRAGMENT);
player:addTitle(BEARER_OF_THE_EIGHT_PRAYERS);
player:completeMission(ZILART,HEADSTONE_PILGRIMAGE);
player:addMission(ZILART,THROUGH_THE_QUICKSAND_CAVES);
else
player:messageSpecial(KEYITEM_OBTAINED,ICE_FRAGMENT);
end
end
end; | gpl-3.0 |
taoyunxing/trafficserver | lib/luajit/src/host/genminilua.lua | 127 | 11962 | ----------------------------------------------------------------------------
-- Lua script to generate a customized, minified version of Lua.
-- The resulting 'minilua' 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 sub, match, gsub = string.sub, string.match, string.gsub
local LUA_VERSION = "5.1.5"
local LUA_SOURCE
local function usage()
io.stderr:write("Usage: ", arg and arg[0] or "genminilua",
" lua-", LUA_VERSION, "-source-dir\n")
os.exit(1)
end
local function find_sources()
LUA_SOURCE = arg and arg[1]
if not LUA_SOURCE then usage() end
if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end
local fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then
LUA_SOURCE = LUA_SOURCE.."src/"
fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then usage() end
end
local all = fp:read("*a")
fp:close()
if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then
io.stderr:write("Error: version mismatch\n")
usage()
end
end
local LUA_FILES = {
"lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c",
"lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c",
"llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c",
"lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c",
}
local REMOVE_LIB = {}
gsub([[
collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset
select tostring xpcall
foreach foreachi getn maxn setn
popen tmpfile seek setvbuf __tostring
clock date difftime execute getenv rename setlocale time tmpname
dump gfind len reverse
LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME
]], "%S+", function(name)
REMOVE_LIB[name] = true
end)
local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, }
local CUSTOM_MAIN = [[
typedef unsigned int UB;
static UB barg(lua_State *L,int idx){
union{lua_Number n;U64 b;}bn;
bn.n=lua_tonumber(L,idx)+6755399441055744.0;
if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number");
return(UB)bn.b;
}
#define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1;
static int tobit(lua_State *L){
BRET(barg(L,1))}
static int bnot(lua_State *L){
BRET(~barg(L,1))}
static int band(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)}
static int bor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)}
static int bxor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)}
static int lshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)}
static int rshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)}
static int arshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)}
static int rol(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))}
static int ror(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))}
static int bswap(lua_State *L){
UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)}
static int tohex(lua_State *L){
UB b=barg(L,1);
int n=lua_isnone(L,2)?8:(int)barg(L,2);
const char *hexdigits="0123456789abcdef";
char buf[8];
int i;
if(n<0){n=-n;hexdigits="0123456789ABCDEF";}
if(n>8)n=8;
for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;}
lua_pushlstring(L,buf,(size_t)n);
return 1;
}
static const struct luaL_Reg bitlib[] = {
{"tobit",tobit},
{"bnot",bnot},
{"band",band},
{"bor",bor},
{"bxor",bxor},
{"lshift",lshift},
{"rshift",rshift},
{"arshift",arshift},
{"rol",rol},
{"ror",ror},
{"bswap",bswap},
{"tohex",tohex},
{NULL,NULL}
};
int main(int argc, char **argv){
lua_State *L = luaL_newstate();
int i;
luaL_openlibs(L);
luaL_register(L, "bit", bitlib);
if (argc < 2) return sizeof(void *);
lua_createtable(L, 0, 1);
lua_pushstring(L, argv[1]);
lua_rawseti(L, -2, 0);
lua_setglobal(L, "arg");
if (luaL_loadfile(L, argv[1]))
goto err;
for (i = 2; i < argc; i++)
lua_pushstring(L, argv[i]);
if (lua_pcall(L, argc - 2, 0, 0)) {
err:
fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
return 1;
}
lua_close(L);
return 0;
}
]]
local function read_sources()
local t = {}
for i, name in ipairs(LUA_FILES) do
local fp = assert(io.open(LUA_SOURCE..name, "r"))
t[i] = fp:read("*a")
assert(fp:close())
end
t[#t+1] = CUSTOM_MAIN
return table.concat(t)
end
local includes = {}
local function merge_includes(src)
return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name)
if includes[name] then return "" end
includes[name] = true
local fp = assert(io.open(LUA_SOURCE..name, "r"))
local src = fp:read("*a")
assert(fp:close())
src = gsub(src, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "")
src = gsub(src, "#endif%s*$", "")
return merge_includes(src)
end)
end
local function get_license(src)
return match(src, "/%*+\n%* Copyright %(.-%*/\n")
end
local function fold_lines(src)
return gsub(src, "\\\n", " ")
end
local strings = {}
local function save_str(str)
local n = #strings+1
strings[n] = str
return "\1"..n.."\2"
end
local function save_strings(src)
src = gsub(src, '"[^"\n]*"', save_str)
return gsub(src, "'[^'\n]*'", save_str)
end
local function restore_strings(src)
return gsub(src, "\1(%d+)\2", function(numstr)
return strings[tonumber(numstr)]
end)
end
local function def_istrue(def)
return def == "INT_MAX > 2147483640L" or
def == "LUAI_BITSINT >= 32" or
def == "SIZE_Bx < LUAI_BITSINT-1" or
def == "cast" or
def == "defined(LUA_CORE)" or
def == "MINSTRTABSIZE" or
def == "LUA_MINBUFFER" or
def == "HARDSTACKTESTS" or
def == "UNUSED"
end
local head, defs = {[[
#ifdef _MSC_VER
typedef unsigned __int64 U64;
#else
typedef unsigned long long U64;
#endif
int _CRT_glob = 0;
]]}, {}
local function preprocess(src)
local t = { match(src, "^(.-)#") }
local lvl, on, oldon = 0, true, {}
for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do
if pp == "if" or pp == "ifdef" or pp == "ifndef" then
lvl = lvl + 1
oldon[lvl] = on
on = def_istrue(def)
elseif pp == "else" then
if oldon[lvl] then
if on == false then on = true else on = false end
end
elseif pp == "elif" then
if oldon[lvl] then
on = def_istrue(def)
end
elseif pp == "endif" then
on = oldon[lvl]
lvl = lvl - 1
elseif on then
if pp == "include" then
if not head[def] and not REMOVE_EXTINC[def] then
head[def] = true
head[#head+1] = "#include "..def.."\n"
end
elseif pp == "define" then
local k, sp, v = match(def, "([%w_]+)(%s*)(.*)")
if k and not (sp == "" and sub(v, 1, 1) == "(") then
defs[k] = gsub(v, "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
else
t[#t+1] = "#define "..def.."\n"
end
elseif pp ~= "undef" then
error("unexpected directive: "..pp.." "..def)
end
end
if on then t[#t+1] = txt end
end
return gsub(table.concat(t), "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
end
local function merge_header(src, license)
local hdr = string.format([[
/* This is a heavily customized and minimized copy of Lua %s. */
/* It's only used to build LuaJIT. It does NOT have all standard functions! */
]], LUA_VERSION)
return hdr..license..table.concat(head)..src
end
local function strip_unused1(src)
return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func)
return REMOVE_LIB[func] and "" or line
end)
end
local function strip_unused2(src)
return gsub(src, "Symbolic Execution.-}=", "")
end
local function strip_unused3(src)
src = gsub(src, "extern", "static")
src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(")
src = gsub(src, "#define lua_assert[^\n]*\n", "")
src = gsub(src, "lua_assert%b();?", "")
src = gsub(src, "default:\n}", "default:;\n}")
src = gsub(src, "lua_lock%b();", "")
src = gsub(src, "lua_unlock%b();", "")
src = gsub(src, "luai_threadyield%b();", "")
src = gsub(src, "luai_userstateopen%b();", "{}")
src = gsub(src, "luai_userstate%w+%b();", "")
src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser")
src = gsub(src, "trydecpoint%(ls,seminfo%)",
"luaX_lexerror(ls,\"malformed number\",TK_NUMBER)")
src = gsub(src, "int c=luaZ_lookahead%b();", "")
src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;",
"return 1;")
src = gsub(src, "getfuncname%b():", "NULL:")
src = gsub(src, "getobjname%b():", "NULL:")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "")
src = gsub(src, "(twoto%b()%()", "%1(size_t)")
src = gsub(src, "i<sizenode", "i<(int)sizenode")
return gsub(src, "\n\n+", "\n")
end
local function strip_comments(src)
return gsub(src, "/%*.-%*/", " ")
end
local function strip_whitespace(src)
src = gsub(src, "^%s+", "")
src = gsub(src, "%s*\n%s*", "\n")
src = gsub(src, "[ \t]+", " ")
src = gsub(src, "(%W) ", "%1")
return gsub(src, " (%W)", "%1")
end
local function rename_tokens1(src)
src = gsub(src, "getline", "getline_")
src = gsub(src, "struct ([%w_]+)", "ZX%1")
return gsub(src, "union ([%w_]+)", "ZY%1")
end
local function rename_tokens2(src)
src = gsub(src, "ZX([%w_]+)", "struct %1")
return gsub(src, "ZY([%w_]+)", "union %1")
end
local function func_gather(src)
local nodes, list = {}, {}
local pos, len = 1, #src
while pos < len do
local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos)
if d then
local n = #list+1
list[n] = d
nodes[w] = n
else
local s
d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos)
if not d then
d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos)
if not d then d = match(src, "^[^\n]*\n", pos) end
end
if s == "{" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
if sub(d, -2) == "{\n" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
end
end
local k, v = nil, d
if w == "typedef" then
if match(d, "^typedef enum") then
head[#head+1] = d
else
k = match(d, "([%w_]+);\n$")
if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end
end
elseif w == "enum" then
head[#head+1] = v
elseif w ~= nil then
k = match(d, "^[^\n]-([%w_]+)[(%[=]")
if k then
if w ~= "static" and k ~= "main" then v = "static "..d end
else
k = w
end
end
if w and k then
local o = nodes[k]
if o then nodes["*"..k] = o end
local n = #list+1
list[n] = v
nodes[k] = n
end
end
pos = pos + #d
end
return nodes, list
end
local function func_visit(nodes, list, used, n)
local i = nodes[n]
for m in string.gmatch(list[i], "[%w_]+") do
if nodes[m] then
local j = used[m]
if not j then
used[m] = i
func_visit(nodes, list, used, m)
elseif i < j then
used[m] = i
end
end
end
end
local function func_collect(src)
local nodes, list = func_gather(src)
local used = {}
func_visit(nodes, list, used, "main")
for n,i in pairs(nodes) do
local j = used[n]
if j and j < i then used["*"..n] = j end
end
for n,i in pairs(nodes) do
if not used[n] then list[i] = "" end
end
return table.concat(list)
end
find_sources()
local src = read_sources()
src = merge_includes(src)
local license = get_license(src)
src = fold_lines(src)
src = strip_unused1(src)
src = save_strings(src)
src = strip_unused2(src)
src = strip_comments(src)
src = preprocess(src)
src = strip_whitespace(src)
src = strip_unused3(src)
src = rename_tokens1(src)
src = func_collect(src)
src = rename_tokens2(src)
src = restore_strings(src)
src = merge_header(src, license)
io.write(src)
| apache-2.0 |
jshackley/darkstar | scripts/zones/Dynamis-San_dOria/bcnms/dynamis_sandoria.lua | 22 | 1331 | -----------------------------------
-- Area: Dynamis San d'Oria
-- Name: Dynamis San d'Oria
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[DynaSandoria]UniqueID",player:getDynamisUniqueID(1281));
SetServerVariable("[DynaSandoria]Boss_Trigger",0);
SetServerVariable("[DynaSandoria]Already_Received",0);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("DynamisID",GetServerVariable("[DynaSandoria]UniqueID"));
local realDay = os.time();
if (DYNA_MIDNIGHT_RESET == true) then
realDay = getMidnight() - 86400;
end
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then
player:setVar("dynaWaitxDay",realDay);
end
end;
-- Leaving the Dynamis by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish he dynamis
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 4) then
GetNPCByID(17535224):setStatus(2);
SetServerVariable("[DynaSandoria]UniqueID",0);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Dangruf_Wadi/TextIDs.lua | 15 | 1316 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6543; -- Obtained: <item>.
GIL_OBTAINED = 6544; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6546; -- Obtained key item: <keyitem>.
FISHING_MESSAGE_OFFSET = 7204; -- You can't fish here.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7424; -- You unlock the chest!
CHEST_FAIL = 7425; -- fails to open the chest.
CHEST_TRAP = 7426; -- The chest was trapped!
CHEST_WEAK = 7427; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7428; -- The chest was a mimic!
CHEST_MOOGLE = 7429; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7430; -- The chest was but an illusion...
CHEST_LOCKED = 7431; -- The chest appears to be locked.
-- Other Text
GEOMAGNETIC_FOUNT = 7166; -- A faint energy wafts up from the ground.
SMALL_HOLE = 7478; -- There is a small hole here.
-- conquest Base
CONQUEST_BASE = 0;
-- Strange Apparatus
DEVICE_NOT_WORKING = 7313; -- The device is not working.
SYS_OVERLOAD = 7322; -- arning! Sys...verload! Enterin...fety mode. ID eras...d
YOU_LOST_THE = 7327; -- You lost the #.
| gpl-3.0 |
wolf9s/packages | lang/luaexpat/files/compat-5.1r5/compat-5.1.lua | 251 | 6391 | --
-- Compat-5.1
-- Copyright Kepler Project 2004-2006 (http://www.keplerproject.org/compat)
-- According to Lua 5.1
-- $Id: compat-5.1.lua,v 1.22 2006/02/20 21:12:47 carregal Exp $
--
_COMPAT51 = "Compat-5.1 R5"
local LUA_DIRSEP = '/'
local LUA_OFSEP = '_'
local OLD_LUA_OFSEP = ''
local POF = 'luaopen_'
local LUA_PATH_MARK = '?'
local LUA_IGMARK = ':'
local assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type = assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type
local find, format, gfind, gsub, sub = string.find, string.format, string.gfind, string.gsub, string.sub
--
-- avoid overwriting the package table if it's already there
--
package = package or {}
local _PACKAGE = package
package.path = LUA_PATH or os.getenv("LUA_PATH") or
("./?.lua;" ..
"/usr/local/share/lua/5.0/?.lua;" ..
"/usr/local/share/lua/5.0/?/?.lua;" ..
"/usr/local/share/lua/5.0/?/init.lua" )
package.cpath = LUA_CPATH or os.getenv("LUA_CPATH") or
"./?.so;" ..
"./l?.so;" ..
"/usr/local/lib/lua/5.0/?.so;" ..
"/usr/local/lib/lua/5.0/l?.so"
--
-- make sure require works with standard libraries
--
package.loaded = package.loaded or {}
package.loaded.debug = debug
package.loaded.string = string
package.loaded.math = math
package.loaded.io = io
package.loaded.os = os
package.loaded.table = table
package.loaded.base = _G
package.loaded.coroutine = coroutine
local _LOADED = package.loaded
--
-- avoid overwriting the package.preload table if it's already there
--
package.preload = package.preload or {}
local _PRELOAD = package.preload
--
-- looks for a file `name' in given path
--
local function findfile (name, pname)
name = gsub (name, "%.", LUA_DIRSEP)
local path = _PACKAGE[pname]
assert (type(path) == "string", format ("package.%s must be a string", pname))
for c in gfind (path, "[^;]+") do
c = gsub (c, "%"..LUA_PATH_MARK, name)
local f = io.open (c)
if f then
f:close ()
return c
end
end
return nil -- not found
end
--
-- check whether library is already loaded
--
local function loader_preload (name)
assert (type(name) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
assert (type(_PRELOAD) == "table", "`package.preload' must be a table")
return _PRELOAD[name]
end
--
-- Lua library loader
--
local function loader_Lua (name)
assert (type(name) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
local filename = findfile (name, "path")
if not filename then
return false
end
local f, err = loadfile (filename)
if not f then
error (format ("error loading module `%s' (%s)", name, err))
end
return f
end
local function mkfuncname (name)
name = gsub (name, "^.*%"..LUA_IGMARK, "")
name = gsub (name, "%.", LUA_OFSEP)
return POF..name
end
local function old_mkfuncname (name)
--name = gsub (name, "^.*%"..LUA_IGMARK, "")
name = gsub (name, "%.", OLD_LUA_OFSEP)
return POF..name
end
--
-- C library loader
--
local function loader_C (name)
assert (type(name) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
local filename = findfile (name, "cpath")
if not filename then
return false
end
local funcname = mkfuncname (name)
local f, err = loadlib (filename, funcname)
if not f then
funcname = old_mkfuncname (name)
f, err = loadlib (filename, funcname)
if not f then
error (format ("error loading module `%s' (%s)", name, err))
end
end
return f
end
local function loader_Croot (name)
local p = gsub (name, "^([^.]*).-$", "%1")
if p == "" then
return
end
local filename = findfile (p, "cpath")
if not filename then
return
end
local funcname = mkfuncname (name)
local f, err, where = loadlib (filename, funcname)
if f then
return f
elseif where ~= "init" then
error (format ("error loading module `%s' (%s)", name, err))
end
end
-- create `loaders' table
package.loaders = package.loaders or { loader_preload, loader_Lua, loader_C, loader_Croot, }
local _LOADERS = package.loaders
--
-- iterate over available loaders
--
local function load (name, loaders)
-- iterate over available loaders
assert (type (loaders) == "table", "`package.loaders' must be a table")
for i, loader in ipairs (loaders) do
local f = loader (name)
if f then
return f
end
end
error (format ("module `%s' not found", name))
end
-- sentinel
local sentinel = function () end
--
-- new require
--
function _G.require (modname)
assert (type(modname) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
local p = _LOADED[modname]
if p then -- is it there?
if p == sentinel then
error (format ("loop or previous error loading module '%s'", modname))
end
return p -- package is already loaded
end
local init = load (modname, _LOADERS)
_LOADED[modname] = sentinel
local actual_arg = _G.arg
_G.arg = { modname }
local res = init (modname)
if res then
_LOADED[modname] = res
end
_G.arg = actual_arg
if _LOADED[modname] == sentinel then
_LOADED[modname] = true
end
return _LOADED[modname]
end
-- findtable
local function findtable (t, f)
assert (type(f)=="string", "not a valid field name ("..tostring(f)..")")
local ff = f.."."
local ok, e, w = find (ff, '(.-)%.', 1)
while ok do
local nt = rawget (t, w)
if not nt then
nt = {}
t[w] = nt
elseif type(t) ~= "table" then
return sub (f, e+1)
end
t = nt
ok, e, w = find (ff, '(.-)%.', e+1)
end
return t
end
--
-- new package.seeall function
--
function _PACKAGE.seeall (module)
local t = type(module)
assert (t == "table", "bad argument #1 to package.seeall (table expected, got "..t..")")
local meta = getmetatable (module)
if not meta then
meta = {}
setmetatable (module, meta)
end
meta.__index = _G
end
--
-- new module function
--
function _G.module (modname, ...)
local ns = _LOADED[modname]
if type(ns) ~= "table" then
ns = findtable (_G, modname)
if not ns then
error (string.format ("name conflict for module '%s'", modname))
end
_LOADED[modname] = ns
end
if not ns._NAME then
ns._NAME = modname
ns._M = ns
ns._PACKAGE = gsub (modname, "[^.]*$", "")
end
setfenv (2, ns)
for i, f in ipairs (arg) do
f (ns)
end
end
| gpl-2.0 |
jshackley/darkstar | scripts/commands/completemission.lua | 25 | 1238 | ---------------------------------------------------------------------------------------------------
-- func: @completemission <logID> <missionID> <player>
-- desc: Completes the given mission for the target player, if that mission is currently active.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "iis"
};
function onTrigger(player, logId, missionId, target)
if (missionId == nil or logId == nil) then
player:PrintToPlayer( "You must enter a valid log id and mission id!" );
player:PrintToPlayer( "@completemission <logID> <missionID> <player>" );
return;
end
if (target == nil) then
target = player:getName();
end
local targ = GetPlayerByName( target );
if (targ ~= nil) then
targ:completeMission( logId, missionId );
player:PrintToPlayer( string.format( "Completed Mission for log %u with ID %u for %s", logId, missionId, target ) );
else
player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) );
player:PrintToPlayer( "@completemission <logID> <missionID> <player>" );
end
end; | gpl-3.0 |
hockeychaos/Core-Scripts-1 | CoreScriptsRoot/StarterScript.lua | 1 | 3624 | -- Creates all neccessary scripts for the gui on initial load, everything except build tools
-- Created by Ben T. 10/29/10
-- Please note that these are loaded in a specific order to diminish errors/perceived load time by user
local scriptContext = game:GetService("ScriptContext")
local touchEnabled = game:GetService("UserInputService").TouchEnabled
local RobloxGui = game:GetService("CoreGui"):WaitForChild("RobloxGui")
local soundFolder = Instance.new("Folder")
soundFolder.Name = "Sounds"
soundFolder.Parent = RobloxGui
-- This can be useful in cases where a flag configuration issue causes requiring a CoreScript to fail
local function safeRequire(moduleScript)
local moduleReturnValue = nil
local success, err = pcall(function() moduleReturnValue = require(moduleScript) end)
if not success then
warn("Failure to Start CoreScript module" ..moduleScript.Name.. ".\n" ..err)
end
return moduleReturnValue
end
-- TopBar
scriptContext:AddCoreScriptLocal("CoreScripts/Topbar", RobloxGui)
-- MainBotChatScript (the Lua part of Dialogs)
scriptContext:AddCoreScriptLocal("CoreScripts/MainBotChatScript2", RobloxGui)
-- In-game notifications script
scriptContext:AddCoreScriptLocal("CoreScripts/NotificationScript2", RobloxGui)
-- Performance Stats Management
scriptContext:AddCoreScriptLocal("CoreScripts/PerformanceStatsManagerScript",
RobloxGui)
-- Chat script
spawn(function() safeRequire(RobloxGui.Modules.ChatSelector) end)
spawn(function() safeRequire(RobloxGui.Modules.PlayerlistModule) end)
-- Purchase Prompt Script
scriptContext:AddCoreScriptLocal("CoreScripts/PurchasePromptScript2", RobloxGui)
-- Prompt Block Player Script
scriptContext:AddCoreScriptLocal("CoreScripts/BlockPlayerPrompt", RobloxGui)
scriptContext:AddCoreScriptLocal("CoreScripts/FriendPlayerPrompt", RobloxGui)
-- Backpack!
spawn(function() safeRequire(RobloxGui.Modules.BackpackScript) end)
scriptContext:AddCoreScriptLocal("CoreScripts/VehicleHud", RobloxGui)
scriptContext:AddCoreScriptLocal("CoreScripts/GamepadMenu", RobloxGui)
scriptContext:AddCoreScriptLocal("CoreScripts/GamepadMenuOld", RobloxGui)
if touchEnabled then -- touch devices don't use same control frame
-- only used for touch device button generation
scriptContext:AddCoreScriptLocal("CoreScripts/ContextActionTouch", RobloxGui)
RobloxGui:WaitForChild("ControlFrame")
RobloxGui.ControlFrame:WaitForChild("BottomLeftControl")
RobloxGui.ControlFrame.BottomLeftControl.Visible = false
end
spawn(function()
local VRService = game:GetService('VRService')
local function onVREnabledChanged()
if VRService.VREnabled then
safeRequire(RobloxGui.Modules.VR.VirtualKeyboard)
safeRequire(RobloxGui.Modules.VR.UserGui)
end
end
onVREnabledChanged()
VRService:GetPropertyChangedSignal("VREnabled"):connect(onVREnabledChanged)
end)
-- Boot up the VR App Shell
if UserSettings().GameSettings:InStudioMode() then
local VRService = game:GetService('VRService')
local function onVREnabledChanged()
if VRService.VREnabled then
local shellInVRSuccess, shellInVRFlagValue = pcall(function() return settings():GetFFlag("EnabledAppShell3D") end)
local shellInVR = (shellInVRSuccess and shellInVRFlagValue == true)
local modulesFolder = RobloxGui.Modules
local appHomeModule = modulesFolder:FindFirstChild('Shell') and modulesFolder:FindFirstChild('Shell'):FindFirstChild('AppHome')
if shellInVR and appHomeModule then
safeRequire(appHomeModule)
end
end
end
spawn(function()
if VRService.VREnabled then
onVREnabledChanged()
end
VRService:GetPropertyChangedSignal("VREnabled"):connect(onVREnabledChanged)
end)
end
| apache-2.0 |
davidhealey/reascript | luaScripts/UACC/MIDI UACC Menu.lua | 1 | 3863 | --[[
* ReaScript Name: UACC Menu
* Written: 27/06/2017
* Last Updated: 27/06/2017
* Author: David Healey
--]]
package.path = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] .."../?.lua;".. package.path
require('daves reaper midi package v1-0')
local ccNum = 32
local INSERT_BEFORE = 0; --Set to 1 if you want the CC data inserted before each selected note
gfx.init("UACC", 1, 1)
gfx.x = gfx.mouse_x
gfx.y = gfx.mouse_y
input = gfx.showmenu(">Long|1: Long Generic|2: Long Alternative|3: Long Octave|4: Long Octave muted|5: Long Small (half)|6: Long Small muted (half muted)|7: Long Muted (cs/stopped)|8: Long Soft (flautando/hollow)|9: Long Hard (cuivre/overblown/nasty)|10: Long Harmonic|11: Long Trem (tremolando/flutter)|12: Long Trem muted (tremolando/flutter cs/stopped)|13: Long Trem soft (trem sul pont)|14: Long Trem hard (flutter overblown)|15: Long Term sul|16: Long Vibrato (molto or vib. only)|17: Long Higher (bells up/sul asto)|18: Long Lower (sul pont)|<19: Undefined|>Legato|20: Legato Generic|21: Legato Alternative|22: Legato Octave|23: Legato Octave muted|24: Legato Small|25: Legato Small muted|26: Legato Muted|27: Legato Soft|28: Legato Hard|29: Legato Harmonic|30: Legato Trem|31: Legato Slow (portamento/glissandi)|32: Legato Fast|33: Legato Slurred (legato runs)|34: Legato Detaché|35: Legato Higher (sul tasto)|36: Legato Lower (sul pont)|37: Undefined|38: Undefined|<39: Undefined|>Short|40: Short Generic|41: Short Alternative|42: Short Staccatissimo/very short)|43: Short Spiccato/very short soft|44: Short Leisurely (longer staccato)|45: Short Octave|46: Short Octave muted|47: Short Muted (cs/stopped)|48: Short Soft (brushed/feathered)|49: Short Hard (dig)|50: Short Tenuto|51: Short Tenuto soft|52: Short Marcato|53: Short Marcato soft|54: Short Marcato hard (bells up)|55: Short Marcato longer|56: Short Plucked (pizzicato)|57: Short Plucked hard (Bartok)|58: Short Struck (Col legno)|59: Short Higher (bells up/sul tasto)|60: Short Lower (sul pont)|61: Short Harmonic|62: Undefined|63: Undefined|64: Undefined|65: Undefined|66: Undefined|67: Undefined|68: Undefined|<69: Undefined|>Decorative|70: Trill min 2nd|71: Trill maj 2nd|72: Trill min 3rd|73: Trill maj 3rd|74: Trill perf 4th|75: Multitongue|76: Multitongue muted|77: Undefined|78: Undefined|79: Undefined|80: Synced - 120bpm (trem/trill)|81: Synced - 150bpm (trem/trill)|82: Synced - 180bpm (trem/trill)|83: Undefined|84: Undefined|85: Undefined|86: Undefined|87: Undefined|88: Undefined|<89: Undefined|>Phrases and Dynamics|90: FX 1|91: FX 2|92: FX 3|93: FX 4|94: FX 5|95: FX 6|96: FX 7|97: FX 8|98: FX 9|99: FX 10|100: Upwards (rips and runs)|101: Downwards (falls and runs)|102: Crescendo|103: Diminuendo|104: Arc|105: Slides|106: Undefined|107: Undefined|108: Undefined|<109: Undefined|>Various|110: Disco upwards (rips)|111: Disco downwards (falls)|112: Undefined|113: Undefined|114: Undefined|115: Undefined|116: Undefined|117: Undefined|118: Undefined|119: Undefined|120: Undefined|121: Undefined|123: Undefined|124: Undefined|125: Undefined|126: Undefined|<127: Undefined||Select UACC For Selected Note|Delete UACC For Selected Notes")
if input ~= 0 then
reaper.Undo_BeginBlock();
if input < 127 then
drmp.deleteCCUnderSelectedNotes(ccNum) --Remove existing UACC data
if INSERT_BEFORE == 1 then
drmp.insertCCBeforeSelectedNotes(ccNum, input) --Insert selected UACC data
else
drmp.insertCCAtSelectedNotes(ccNum, input) --Insert selected UACC data
end
reaper.Undo_EndBlock("MIDI Insert UACC From Menu",-1)
else
if input == 127 then
drmp.selectCCEventsUnderSelectedNotes(ccNum)
reaper.Undo_EndBlock("MIDI Select UACC Events Under Selected Notes",-1);
end
if input == 128 then
drmp.deleteCCUnderSelectedNotes(ccNum)
reaper.Undo_EndBlock("MIDI Delete UACC Under Selected Notes",-1)
end
end
end
gfx.quit() | gpl-3.0 |
SLE-TheRealOne/Factorio-SwiftInserter | prototypes/entities.lua | 1 | 1093 | local swift = util.table.deepcopy(data.raw["inserter"]["fast-inserter"])
swift.name = "swiftSpeedInserter"
swift.energy_source =
{
type = "electric",
usage_priority = "secondary-input",
drain = "0.8kW"
}
swift.name = "swift-inserter"
swift.icon = "__SwiftInserter__/graphics/swift-inserter.png"
swift.hand_base_picture =
{
filename = "__SwiftInserter__/graphics/swift-inserter-hand-base.png",
width = "8",
height = "34"
}
swift.hand_closed_picture =
{
filename = "__SwiftInserter__/graphics/swift-inserter-hand-closed.png",
width = "18",
height = "41"
}
swift.hand_open_picture =
{
filename = "__SwiftInserter__/graphics/swift-inserter-hand-open.png",
width = "18",
height = "41"
}
swift.platform_picture =
{
sheet=
{
filename = "__SwiftInserter__/graphics/swift-inserter-platform.png",
priority = "extra-high",
width = "46",
height = "46"
}
}
swift.energy_per_movement = 5300
swift.energy_per_rotation = 5300
swift.rotation_speed = 0.095
swift.extension_speed = 0.065
swift.minable = {hardness = 0.2, mining_time = 0.5, result = "swift-inserter"}
data:extend({swift}) | apache-2.0 |
jshackley/darkstar | scripts/zones/Southern_San_dOria/npcs/Hanaa_Punaa.lua | 17 | 6224 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Hanaa Punaa
-- Starts and Finishes: A Squire's Test, A Squire's Test II, A Knight's Test
-- @zone 230
-- @pos
-------------------------------------
package.loaded["scripts/zones/Southern_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/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "The Seamstress" , x3 sheepskin trade
if (player:getQuestStatus(SANDORIA,THE_SEAMSTRESS) ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(505,3) and trade:getItemCount() == 3) then
player:startEvent(0x0212);
end
end
-- "Black Tiger Skins", Tiger Hide trade
if (player:getQuestStatus(SANDORIA,BLACK_TIGER_SKINS) == QUEST_ACCEPTED) then
if (trade:hasItemQty(861,3) and trade:getItemCount() == 3) then
player:startEvent(0x0241);
end
end
-- "Lizard Skins", lizard skin trade
if (player:getQuestStatus(SANDORIA,LIZARD_SKINS) ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(852,3) and trade:getItemCount() == 3) then
player:startEvent(0x0231);
end
end
-- "Flyers for Regine"
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Checking Fame Level & Quest
sanFame = player:getFameLevel(SANDORIA);
theSteamStress = player:getQuestStatus(SANDORIA,THE_SEAMSTRESS);
lizardSkins = player:getQuestStatus(SANDORIA,LIZARD_SKINS);
blackTigerSkins = player:getQuestStatus(SANDORIA,BLACK_TIGER_SKINS);
-- "The Seamstress" Quest Status
if (theSteamStress == QUEST_AVAILABLE and player:getVar("theSeamStress") == 1) then
player:startEvent(0x0213);
elseif (theSteamStress == QUEST_AVAILABLE) then
player:startEvent(0x0210);
player:setVar("theSeamStress",1);
elseif (theSteamStress == QUEST_ACCEPTED) then
player:startEvent(0x0211);
elseif (theSteamStress == QUEST_COMPLETED and sanFame < 2) then
player:startEvent(0x024e);
-- "Lizard Skins" Quest Dialogs
elseif (lizardSkins == QUEST_AVAILABLE and player:getVar("lzdSkins") == 1 and sanFame >= 2 and theSteamStress == QUEST_COMPLETED) then
player:startEvent(0x0232);
elseif (lizardSkins == QUEST_AVAILABLE and sanFame >= 2 and theSteamStress == QUEST_COMPLETED) then
player:startEvent(0x022f);
player:setVar("lzdSkins",1);
elseif (lizardSkins == QUEST_ACCEPTED) then
player:startEvent(0x0230);
elseif (lizardSkins == QUEST_COMPLETED and sanFame < 3) then
player:startEvent(0x024f);
-- "Black Tiger Skins" Quest Dialogs
elseif (blackTigerSkins == QUEST_AVAILABLE and player:getVar("blkTigerSkin") == 1 and sanFame >= 3 and theSteamStress == QUEST_COMPLETED and lizardSkins == QUEST_COMPLETED) then
player:startEvent(0x0243 );
elseif (blackTigerSkins == QUEST_AVAILABLE and sanFame >= 3 and theSteamStress == QUEST_COMPLETED and lizardSkins == QUEST_COMPLETED) then
player:startEvent(0x0240);
player:setVar("blkTigerSkin",1);
elseif (blackTigerSkins == QUEST_ACCEPTED) then
player:startEvent(0x0242);
elseif (blackTigerSkins == QUEST_COMPLETED) then
player:startEvent(0x0250);
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);
-- "The Seamstress" Quest
if ((csid == 0x0210 or csid == 0x0213) and option == 0) then
player:addQuest(SANDORIA,THE_SEAMSTRESS);
player:setVar("theSeamStress",0);
elseif (csid == 0x0212) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12696); -- Leather Gloves
else
player:tradeComplete();
player:addTitle(SILENCER_OF_THE_LAMBS);
player:addItem(12696);
player:messageSpecial(ITEM_OBTAINED, 12696); -- Leather Gloves
if (player:getQuestStatus(SANDORIA,THE_SEAMSTRESS) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,THE_SEAMSTRESS);
else
player:addFame(SANDORIA,SAN_FAME*5);
end
end
-- "Liard Skins" Quest
elseif ((csid == 0x022f or csid == 0x0232) and option == 0) then
player:addQuest(SANDORIA,LIZARD_SKINS);
player:setVar("lzdSkins",0);
elseif (csid == 0x0231) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12697); -- Lizard Gloves
else
player:tradeComplete();
player:addTitle(LIZARD_SKINNER);
player:addItem(12697);
player:messageSpecial(ITEM_OBTAINED, 12697); -- Lizard Gloves
if (player:getQuestStatus(SANDORIA,LIZARD_SKINS) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,LIZARD_SKINS);
else
player:addFame(SANDORIA,SAN_FAME*5);
end
end
-- "Black Tiger Skins" Quest
elseif ((csid == 0x0240 or csid == 0x0243) and option == 0) then
player:addQuest(SANDORIA,BLACK_TIGER_SKINS);
player:setVar("blkTigerSkin",0);
elseif (csid == 0x0241) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13119); -- Tyger Stole
else
player:tradeComplete();
player:addTitle(CAT_SKINNER);
player:addItem(13119);
player:messageSpecial(ITEM_OBTAINED, 13119); -- Tyger Stole
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,BLACK_TIGER_SKINS);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Woods/npcs/Illu_Bohjaa.lua | 36 | 2170 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Illu Bohjaa
-- Starts the repeatable quest "Creepy Crawlies"
-- Working 100%
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
CrepyCrawlies = player:getQuestStatus(WINDURST,CREEPY_CRAWLIES);
if (CrepyCrawlies ~= QUEST_AVAILABLE) then
count = trade:getItemCount();
SilkThread = trade:hasItemQty(816,3);
CrawlerCalculus = trade:hasItemQty(1156,3);
if ((SilkThread == true or CrawlerCalculus == true) and count == 3) then
if (SilkThread == true) then
player:addFame(WINDURST,WIN_FAME*15);
elseif (CrawlerCalculus == true) then
player:addFame(WINDURST,WIN_FAME*30);
end
player:tradeComplete();
player:addGil(GIL_RATE*600);
player:completeQuest(WINDURST,CREEPY_CRAWLIES);
player:addTitle(CRAWLER_CULLER);
player:startEvent(0x014f,GIL_RATE*600,816,938,1156);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CrepyCrawlies = player:getQuestStatus(WINDURST,CREEPY_CRAWLIES);
if (CrepyCrawlies == QUEST_AVAILABLE) then
player:startEvent(0x014d,0,816,938,1156);
else
player:startEvent(0x014e,0,816,938,1156);
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 == 0x014d and option == 1) then
player:addQuest(WINDURST,CREEPY_CRAWLIES);
end
end;
| gpl-3.0 |
hockeychaos/Core-Scripts-1 | PlayerScripts/StarterPlayerScripts/ControlScript/MasterControl.lua | 1 | 4832 | --[[
// FileName: MasterControl
// Version 1.0
// Written by: jeditkacheff
// Description: All character control scripts go thru this script, this script makes sure all actions are performed
--]]
-- [[ Constants ]]--
local ZERO_VECTOR3 = Vector3.new(0, 0, 0)
local STATE_JUMPING = Enum.HumanoidStateType.Jumping
local STATE_FREEFALL = Enum.HumanoidStateType.Freefall
local STATE_LANDED = Enum.HumanoidStateType.Landed
--[[ Local Variables ]]--
local MasterControl = {}
local Players = game:GetService('Players')
local RunService = game:GetService('RunService')
local VRService = game:GetService('VRService')
local VREnabled = VRService.VREnabled
while not Players.LocalPlayer do
Players.PlayerAdded:wait()
end
local LocalPlayer = Players.LocalPlayer
local LocalCharacter = LocalPlayer.Character
local CachedHumanoid = nil
local isJumping = false
local moveValue = Vector3.new(0, 0, 0)
local isJumpEnabled = true
local areControlsEnabled = true
--[[ Local Functions ]]--
function MasterControl:GetHumanoid()
if LocalCharacter then
if CachedHumanoid then
return CachedHumanoid
else
CachedHumanoid = LocalCharacter:FindFirstChildOfClass("Humanoid")
return CachedHumanoid
end
end
end
VRService.Changed:connect(function(prop)
if prop == "VREnabled" then
VREnabled = VRService.VREnabled
end
end)
local characterAncestryChangedConn = nil
local characterChildRemovedConn = nil
local function characterAdded(character)
if characterAncestryChangedConn then
characterAncestryChangedConn:disconnect()
end
if characterChildRemovedConn then
characterChildRemovedConn:disconnect()
end
LocalCharacter = character
CachedHumanoid = LocalCharacter:FindFirstChildOfClass("Humanoid")
characterAncestryChangedConn = character.AncestryChanged:connect(function()
if character.Parent == nil then
LocalCharacter = nil
else
LocalCharacter = character
end
end)
characterChildRemovedConn = character.ChildRemoved:connect(function(child)
if child == CachedHumanoid then
CachedHumanoid = nil
end
end)
end
if LocalCharacter then
characterAdded(LocalCharacter)
end
LocalPlayer.CharacterAdded:connect(characterAdded)
local getHumanoid = MasterControl.GetHumanoid
local moveFunc = LocalPlayer.Move
local getUserCFrame = VRService.GetUserCFrame
local updateMovement = function()
if not areControlsEnabled then return end
local humanoid = getHumanoid()
if not humanoid then return end
if isJumpEnabled and isJumping and not humanoid.PlatformStand then
local state = humanoid:GetState()
if state ~= STATE_JUMPING and state ~= STATE_FREEFALL and state ~= STATE_LANDED then
humanoid.Jump = isJumping
end
end
local adjustedMoveValue = moveValue
if VREnabled and workspace.CurrentCamera.HeadLocked then
local vrFrame = getUserCFrame(VRService, Enum.UserCFrame.Head)
local lookVector = Vector3.new(vrFrame.lookVector.X, 0, vrFrame.lookVector.Z).unit
local rotation = CFrame.new(ZERO_VECTOR3, lookVector)
adjustedMoveValue = rotation:vectorToWorldSpace(adjustedMoveValue)
end
moveFunc(LocalPlayer, adjustedMoveValue, true)
end
--[[ Public API ]]--
function MasterControl:Init()
RunService:BindToRenderStep("MasterControlStep", Enum.RenderPriority.Input.Value, updateMovement)
end
function MasterControl:Enable()
areControlsEnabled = true
isJumpEnabled = true
if self.ControlState.Current then
self.ControlState.Current:Enable()
end
end
function MasterControl:Disable()
if self.ControlState.Current then
self.ControlState.Current:Disable()
end
--After current control state is disabled, moveValue has been set to zero,
--Call updateMovement one last time to make sure this propagates to the engine -
--Otherwise if disabled while humanoid is moving, humanoid won't stop moving.
updateMovement()
isJumping = false
areControlsEnabled = false
end
function MasterControl:EnableJump()
isJumpEnabled = true
if areControlsEnabled and self.ControlState:IsTouchJumpModuleUsed() then
self.TouchJumpModule:Enable()
end
end
function MasterControl:DisableJump()
isJumpEnabled = false
if self.ControlState:IsTouchJumpModuleUsed() then
self.TouchJumpModule:Disable()
end
end
function MasterControl:AddToPlayerMovement(playerMoveVector)
moveValue = Vector3.new(moveValue.X + playerMoveVector.X, moveValue.Y + playerMoveVector.Y, moveValue.Z + playerMoveVector.Z)
end
function MasterControl:GetMoveVector()
return moveValue
end
function MasterControl:SetIsJumping(jumping)
if not isJumpEnabled then return end
isJumping = jumping
local humanoid = self:GetHumanoid()
if humanoid and not humanoid.PlatformStand then
humanoid.Jump = isJumping
end
end
function MasterControl:DoJump()
if not isJumpEnabled then return end
local humanoid = self:GetHumanoid()
if humanoid then
humanoid.Jump = true
end
end
return MasterControl
| apache-2.0 |
jshackley/darkstar | scripts/zones/Upper_Delkfutts_Tower/npcs/_4e1.lua | 17 | 1206 | -----------------------------------
-- Area: Upper Delkfutt's Tower
-- NPC: Door
-- @pos 315 16 20 158
-----------------------------------
package.loaded["scripts/zones/Upper_Delkfutts_Tower/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Upper_Delkfutts_Tower/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0002);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0002 and option == 1) then
player:setPos(524, 16, 20, 0, 0xB8); -- to Lower Delkfutt's Tower
end
end; | gpl-3.0 |
catwell/mule | mulelib.lua | 1 | 39048 | require "helpers"
local pp = require("purepack")
require "conf"
local function name(metric_,step_,period_)
return string.format("%s;%s:%s",metric_,
secs_to_time_unit(step_),
secs_to_time_unit(period_))
end
local nop = function() end
local return_0 = function() return 0 end
local NOP_SEQUENCE = {
slots = function() return {} end,
name = function() return "" end,
metric = return_0,
step = return_0,
period = return_0,
slot = nop,
slot_index = return_0,
update = nop,
update_batch = nop,
latest = nop,
latest_timestamp = return_0,
reset = nop,
serialize = nop,
}
function sequence(db_,name_)
local _metric,_step,_period,_name,_seq_storage
local function at(idx_,offset_,a_,b_,c_)
-- a nil offset_ is translated to reading/writing the entire cell (3 items)
if not a_ then
return _seq_storage.get_slot(idx_,offset_)
end
_seq_storage.set_slot(idx_,offset_,a_,b_,c_)
end
local function get_timestamp(idx_)
return at(idx_,0)
end
local function latest(latest_idx_)
local pos = math.floor(_period/_step)
if not latest_idx_ then
return at(pos,0)
end
at(pos,0,latest_idx_)
end
local function indices(sorted_)
if not sorted_ then
return coroutine.wrap(
function()
for i=1,(_period/_step) do
coroutine.yield(i-1)
end
end)
end
local array = {}
for i=1,(_period/_step) do
array[i] = {i-1,get_timestamp(i-1)}
end
table.sort(array, function(u,v) return u[2]<v[2] end)
return coroutine.wrap(
function()
for _,s in ipairs(array) do
coroutine.yield(s[1])
end
end)
end
local function find_latest()
local latest = 0
local latest_idx = 0
for s in indices() do
local timestamp,hits,sum = at(s)
if sum>latest then
latest = sum
latest_idx = s
end
end
return latest_idx,latest
end
local function fix_timestamp(latest_idx)
local new_latest_idx,new_latest = find_latest()
if new_latest>0 then
logw("latest_timestamp - fixing",name_,latest_idx,new_latest_idx,new_latest)
latest(new_latest_idx)
end
return new_latest
end
local function latest_timestamp()
local latest_idx = latest()
if get_timestamp(latest_idx)>0 then
return get_timestamp(latest_idx)
end
-- fix_timestamp(latest_idx) -- enable to fix the latest timestamp
if latest_idx>0 then
logw("latest_timestamp is 0",_name,latest_idx)
end
return get_timestamp(latest_idx)
end
local function reset()
_seq_storage.reset()
_seq_storage.save()
end
_name = name_
_metric,_step,_period = split_name(name_)
if not (_metric and _step and _period ) then
loge("failed creating sequence",name_)
--loge(debug.traceback())
return NOP_SEQUENCE
end
_seq_storage = db_.sequence_storage(name_,_period/_step)
local function update(timestamp_,hits_,sum_,type_)
local idx,adjusted_timestamp = calculate_idx(timestamp_,_step,_period)
local timestamp,hits,sum = at(idx)
-- we need to check whether we should update the current slot
-- or if are way ahead of the previous time the slot was updated
-- over-write its value. We rely on the invariant that timestamp should be >= adjusted_timestamp
if adjusted_timestamp<timestamp then
return
end
if (not type_) then
if adjusted_timestamp==timestamp and hits>0 then
-- no need to worry about the latest here, as we have the same (adjusted) timestamp
hits,sum = hits+(hits_ or 1), sum+sum_
else
hits,sum = hits_ or 1,sum_
end
elseif type_=='=' then
hits,sum = hits_ or 1,sum_
elseif type_=='^' then
hits,sum = hits_ or 1,math.max(sum_,sum)
end
at(idx,nil,adjusted_timestamp,hits,sum)
local lt = latest_timestamp()
if adjusted_timestamp>lt then
latest(idx)
end
_seq_storage.save(_name)
return adjusted_timestamp,sum
end
local function update_batch(slots_,ts,ht,sm)
-- slots is a flat array of arrays.
-- it is kind of ugly that we need to pass the indices to the various cells in each slot, but an inconsistency
-- in the order that is too fundemental to change, forces us to.
local j = 1
local match = string.match
while j<#slots_ do
local timestamp,hits,sum,typ = legit_input_line("",tonumber(slots_[j+sm]),tonumber(slots_[j+ts]),tonumber(slots_[j+ht]))
j = j + 3
update(timestamp,hits,sum,"=")
end
_seq_storage.save(_name)
return j-1
end
local function reset_to_timestamp(timestamp_)
local _,adjusted_timestamp = calculate_idx(timestamp_,_step,_period)
local affected = false
for s in indices() do
local ts = get_timestamp(s)
if ts>0 and ts<=adjusted_timestamp then
update(ts,0,0,'=')
affected = true
end
end
return affected
end
local function serialize(opts_,metric_cb_,slot_cb_)
local date = os.date
local readable = opts_.readable
local average = opts_.stat=="average"
local factor = opts_.factor and tonumber(opts_.factor) or nil
local format = string.format
local function serialize_slot(idx_,skip_empty_,slot_cb_)
local timestamp,hits,sum = at(idx_)
if not skip_empty_ or sum~=0 or hits~=0 or timestamp~=0 then
local value = sum
if average then
value = average and (sum/hits)
elseif factor then
value = sum/factor
end
if readable then
timestamp = format('"%s"',date("%y%m%d:%H%M%S",timestamp))
end
slot_cb_(value,hits,timestamp)
end
end
opts_ = opts_ or {}
metric_cb_(_metric,_step,_period)
local now = time_now()
local latest_ts = latest_timestamp()
local min_timestamp = (opts_.filter=="latest" and latest_ts-_period) or
(opts_.filter=="now" and now-_period) or nil
if opts_.all_slots then
if not opts_.dont_cache then
_seq_storage.cache(name_) -- this is a hint that the sequence can be cached
end
for s in indices(opts_.sorted) do
if not min_timestamp or min_timestamp<get_timestamp(s) then
serialize_slot(s,opts_.skip_empty,slot_cb_)
end
end
return
end
if opts_.timestamps then
for _,t in ipairs(opts_.timestamps) do
if t=="*" then
for s in indices(opts_.sorted) do
serialize_slot(s,true,slot_cb_)
end
else
local ts = to_timestamp(t,now,latest_ts)
if ts then
if type(ts)=="number" then
ts = {ts,ts+_step-1}
end
local visited = {}
for t = ts[1],ts[2],(ts[1]<ts[2] and _step or -_step) do
-- the range can be very large, like 0..1100000 and we'll be recycling through the same slots
-- over and over. We therefore cache the calculated indices and skip those we've seen.
local idx,_ = calculate_idx(t,_step,_period)
if not visited[idx] then
local its = get_timestamp(idx)
if t-its<_period and (not min_timestamp or min_timestamp<its) then
serialize_slot(idx,true,slot_cb_)
end
visited[idx] = true
end
end
end
end
end
end
end
local function slot(idx_)
local ts,h,s = at(idx_)
return { _timestamp = ts, _hits = h, _sum = s }
end
local function to_slots_array()
local slots = {}
local insert = table.insert
for i=0,_period/_step do
local a,b,c = at(i)
insert(slots,a)
insert(slots,b)
insert(slots,c)
end
return slots
end
return {
slots = function() return to_slots_array() end,
name = function() return _name end,
metric = function() return _metric end,
step = function() return _step end,
period = function() return _period end,
slot = slot,
slot_index = function(timestamp_) return calculate_idx(timestamp_,_step,_period) end,
update = update,
update_batch = update_batch,
latest = latest,
latest_timestamp = latest_timestamp,
reset_to_timestamp = reset_to_timestamp,
reset = reset,
serialize = serialize,
}
end
local function sequences_for_prefix(db_,prefix_,retention_pair_,level_)
return coroutine.wrap(
function()
local find = string.find
local yield = coroutine.yield
prefix_ = (prefix_=="*" and "") or prefix_
for name in db_.matching_keys(prefix_,level_) do
if not retention_pair_ or find(name,retention_pair_,1,true) then
yield(sequence(db_,name))
end
end
end)
end
function immediate_metrics(db_,name_,level_)
-- if the name_ has th retention pair in it, we just return it
-- otherwise we provide all the retention pairs
return coroutine.wrap(
function()
for name in db_.matching_keys(name_,0) do
coroutine.yield(sequence(db_,name))
end
end)
end
local function wrap_json(stream_)
local str = stream_.get_string()
if #str==0 then return nil end
return string.format("{\"version\": %d,\n\"data\": %s\n}",
CURRENT_VERSION,
#str>0 and str or '""')
end
local function each_metric(db_,metrics_,retention_pair_,callback_)
for m in split_helper(metrics_,"/") do
for seq in sequences_for_prefix(db_,m,retention_pair_) do
callback_(seq)
end
end
end
function mule(db_)
local _factories = {}
local _sorted_factories
local _alerts = {}
local _anomalies = {} -- these do not persist as they can be recalulated
local _db = db_
local _updated_sequences = {}
local _hints = {}
local _flush_cache_logger = every_nth_call(10,
function()
local a = table_size(_updated_sequences)
if a>0 then
logi("mulelib flush_cache",a)
end
end)
local function uniq_factories()
local factories = _factories
_factories = {}
for fm,rps in pairs(factories) do
_factories[fm] = uniq_pairs(rps)
end
_sorted_factories = keys(_factories)
table.sort(_sorted_factories)
end
local function add_factory(metric_,retentions_)
metric_ = string.match(metric_,"^(.-)%.*$")
for _,rp in ipairs(retentions_) do
local step,period = parse_time_pair(rp)
if step and period then
if step>period then
loge("step greater than period",rp,step,period)
error("step greater than period")
return nil
end
_factories[metric_] = _factories[metric_] or {}
table.insert(_factories[metric_],{step,period})
end
end
-- now we make sure the factories are unique
uniq_factories()
return true
end
local function get_sequences(metric_)
return coroutine.wrap(
function()
local metric_rps = {}
local idx = 1
while idx<=#_sorted_factories and _sorted_factories[idx]<=metric_ do
if is_prefix(metric_,_sorted_factories[idx]) then
local fm = _sorted_factories[idx]
table.insert(metric_rps,{fm,_factories[fm]})
end
idx = idx + 1
end
local seqs = {}
for m in metric_hierarchy(metric_) do
for _,frp in ipairs(metric_rps) do
if is_prefix(m,frp[1]) then
for _,rp in ipairs(frp[2]) do
seqs[name(m,rp[1],rp[2])] = m
end
end
end
end
for n,m in pairs(seqs) do
coroutine.yield(n,m)
end
end)
end
local function update_rank(rank_timestamp_,rank_,timestamp_,value_,name_,step_)
local ts,rk,same_ts = update_rank_helper(rank_timestamp_,rank_,timestamp_,value_,step_)
return ts,rk
end
local function alert_check_stale(seq_,timestamp_)
local alert = _alerts[seq_.name()]
if not alert then
return nil
end
if alert._stale then
if seq_.latest_timestamp()+alert._stale<timestamp_ then
alert._state = "stale"
return true
end
alert._state = nil
end
return false
end
local function alert_check(sequence_,timestamp_)
local name = sequence_.name()
local alert = _alerts[name]
if not alert then
return nil
end
if alert_check_stale(sequence_,timestamp_) then
return alert
end
local average_sum = 0
local step = sequence_.step()
local period = sequence_.period()
local start = timestamp_-alert._period
for ts = start,timestamp_,step do
local idx,normalized_ts = calculate_idx(ts,step,period)
local slot = sequence_.slot(idx)
-- logd("alert_check",name,ts,start,slot._timestamp,slot._sum,step,average_sum)
if normalized_ts==slot._timestamp and slot._hits>0 then
if ts==start then
-- we need to take only the proportionate part of the first slot
average_sum = slot._sum*(slot._timestamp+step-start)/step
else
average_sum = average_sum + slot._sum
end
end
end
alert._sum = average_sum
if alert._critical_low and alert._warning_low and alert._critical_high and alert._warning_high then
alert._state = (alert._critical_low~=-1 and average_sum<alert._critical_low and "CRITICAL LOW") or
(alert._warning_low~=-1 and average_sum<alert._warning_low and "WARNING LOW") or
(alert._critical_high~=-1 and average_sum>alert._critical_high and "CRITICAL HIGH") or
(alert._warning_high~=-1 and average_sum>alert._warning_high and "WARNING HIGH") or
"NORMAL"
else
alert._state = "NORMAL"
end
return alert
end
local function flush_cache_of_sequence(name_,sparse_)
sparse_ = sparse_ or _updated_sequences[name_]
if not sparse_ then return nil end
local seq = sequence(_db,name_)
local now = time_now()
for j,sl in ipairs(sparse_.slots()) do
local adjusted_timestamp,sum = seq.update(sl._timestamp,sl._hits or 1,sl._sum,sl._type)
if adjusted_timestamp and sum then
_hints[name_] = _hints[name_] or {}
if not _hints[name_]._rank_ts then
_hints[name_]._rank = 0
_hints[name_]._rank_ts = 0
end
_hints[name_]._rank_ts,_hints[name_]._rank = update_rank(
_hints[name_]._rank_ts,_hints[name_]._rank,
adjusted_timestamp,sum,name_,seq.step())
end
alert_check(seq,now)
end
_updated_sequences[name_] = nil
end
local function flush_cache(max_,step_)
_flush_cache_logger()
-- we now update the real sequences
local num_processed = 0
local size,st,en = random_table_region(_updated_sequences,max_)
if size==0 then return false end
for n,s in iterate_table(_updated_sequences,st,en) do
flush_cache_of_sequence(n,s)
num_processed = num_processed + 1
end
if num_processed==0 then return false end
-- returns true if there are more items to process
return _updated_sequences and next(_updated_sequences)~=nil
end
local function gc(resource_,options_)
local garbage = {}
local str = strout("","\n")
local format = string.format
local col = collectionout(str,"[","]")
local timestamp = tonumber(options_.timestamp)
if not timestamp then
str.write('{"error": "timestamp must be provided"}');
else
col.head()
each_metric(_db,resource_,nil,
function(seq)
if seq.latest_timestamp()<timestamp then
col.elem(format("\"%s\": %d",seq.name(),seq.latest_timestamp()))
garbage[#garbage+1] = seq.name()
end
end)
col.tail()
if options_.force then
for _,name in ipairs(garbage) do
_db.out(name)
end
end
end
return wrap_json(str)
end
local function dump(resource_,options_)
local str = options_.to_str and strout("") or stdout("")
local serialize_opts = {all_slots=true,skip_empty=true,dont_cache=true} -- caching kills us when dumping large DBs
each_metric(_db,resource_,nil,
function(seq)
flush_cache_of_sequence(seq)
seq.serialize(serialize_opts,
function()
str.write(seq.name())
end,
function(sum,hits,timestamp)
str.write(" ",sum," ",hits," ",timestamp)
end)
str.write("\n")
end)
return str
end
local function output_anomalies(names_)
local str = strout("","\n")
local format = string.format
local col = collectionout(str,"{","}")
local now = time_now()
col.head()
for k,v in pairs(_anomalies) do
if not names_ or names_[k] then
col.elem(format("\"%s\": [%s]",k,table.concat(v,",")))
end
end
col.tail()
return str
end
local function output_alerts(names_,all_anomalies_)
local str = strout("","\n")
local format = string.format
local col = collectionout(str,"{","}")
local now = time_now()
local ans = not all_anomalies_ and {} or nil
col.head()
for _,n in ipairs(names_) do
local seq = sequence(db_,n)
local a,msg = alert_check(seq,now)
if a and a._critical_low and a._warning_low and a._warning_high and a._critical_high and a._period then
col.elem(format("\"%s\": [%d,%d,%d,%d,%d,%s,%d,\"%s\",%d,\"%s\"]",
n,a._critical_low,a._warning_low,a._warning_high,a._critical_high,
a._period,a._stale or "-1",a._sum,a._state,now,msg or ""))
end
if not all_anomalies_ then
ans[n] = true
end
end
col.elem(format("\"anomalies\": %s",output_anomalies(ans).get_string()))
col.tail()
return str
end
local function graph(resource_,options_)
local str = strout("")
options_ = options_ or {}
local timestamps = options_.timestamp and split(options_.timestamp,',') or nil
local format = string.format
local col = collectionout(str,"{","}")
local opts = { all_slots=not timestamps,
filter=options_.filter,
readable=is_true(options_.readable),
timestamps=timestamps,
sorted=is_true(options_.sorted),
stat=options_.stat,
factor=options_.factor,
skip_empty=true}
local sequences_generator = immediate_metrics
local alerts = is_true(options_.alerts)
local names = {}
local level = options_.level and tonumber(options_.level)
local insert = table.insert
local now = time_now()
local find = string.find
local in_memory = options_.in_memory and {}
col.head()
for m in split_helper(resource_,"/") do
if level then
local ranked_children = {}
local metric,rp = string.match(m,"^([^;]+)(;%w+:%w+)$")
metric = metric or m
for seq in sequences_for_prefix(db_,metric,rp,level) do
local name = seq.name()
local name_level = count_dots(name)
-- we call update_rank to get adjusted ranks (in case the previous update was
-- long ago). This is a readonly operation
local hint = _hints[seq.name()] or {}
local _,seq_rank = update_rank(
hint._rank_ts or 0 ,hint._rank or 0,
normalize_timestamp(now,seq.step(),seq.period()),0,seq.name(),seq.step())
insert(ranked_children,{seq,seq_rank,name_level})
end
table.sort(ranked_children,function(a,b) return a[3]<b[3] or (a[3]==b[3] and a[2]>b[2]) end)
sequences_generator = function()
return coroutine.wrap(
function()
for i=1,(math.min(#ranked_children,options_.count or DEFAULT_COUNT)) do
coroutine.yield(ranked_children[i][1])
end
end)
end
end
for seq in sequences_generator(db_,m,level) do
flush_cache_of_sequence(seq)
if in_memory then
local current = {}
seq.serialize(
opts,
function()
in_memory[seq.name()] = current
end,
function(sum,hits,timestamp)
insert(current,{sum,hits,timestamp})
end)
else
if alerts then
names[#names+1] = seq.name()
end
local col1 = collectionout(str,": [","]\n")
seq.serialize(
opts,
function()
col.elem(format("\"%s\"",seq.name()))
col1.head()
end,
function(sum,hits,timestamp)
col1.elem(format("[%d,%d,%s]",sum,hits,timestamp))
end)
col1.tail()
end
end
end
if in_memory then
return in_memory
end
if alerts then
col.elem(format("\"alerts\": %s",output_alerts(names).get_string()))
end
col.tail()
return wrap_json(str)
end
local function slot(resource_,options_)
local str = strout("")
local format = string.format
local opts = { timestamps={options_ and options_.timestamp},readable=is_true(options_.readable) }
local col = collectionout(str,"{","}")
col.head()
each_metric(db_,resource_,nil,
function(seq)
local col1 = collectionout(str,"[","]\n")
flush_cache_of_sequence(seq)
seq.serialize(opts,
function()
col.elem(format("\"%s\": ",seq.name()))
col1.head()
end,
function(sum,hits,timestamp)
col1.elem(format("[%d,%d,%s]",sum,hits,timestamp))
end
)
col1.tail()
end
)
col.tail()
return wrap_json(str)
end
local function latest(resource_,opts_)
opts_ = opts_ or {}
opts_.timestamp = "latest"
return slot(resource_,opts_)
end
local function key(resource_,options_)
local str = strout("")
local format = string.format
local find = string.find
local col = collectionout(str,"{","}")
local level = tonumber(options_.level) or 0
col.head()
if not resource_ or resource_=="" or resource_=="*" then
-- we take the factories as distinct prefixes
resource_ = table.concat(distinct_prefixes(keys(_factories)),"/")
level = level - 1
end
local selector = db_.matching_keys
-- we are abusing the level param to hold the substring to be search, to make the for loop easier
if options_.substring then
selector = db_.find_keys
level = options_.substring
end
logd("key - start traversing")
for prefix in split_helper(resource_ or "","/") do
for k in selector(prefix,level) do
local metric,_,_ = split_name(k)
if metric then
local hash = db_.has_sub_keys(metric) and "{\"children\": true}" or "{}"
col.elem(format("\"%s\": %s",k,hash))
end
end
end
logd("key - done traversing")
col.tail()
return wrap_json(str)
end
local function kvs_put(key_,value_)
return _db.put("kvs="..key_,value_)
end
local function kvs_get(key_)
return _db.get("kvs="..key_,true)
end
local function kvs_out(key_)
return _db.out("kvs="..key_,true)
end
local function save(skip_flushing_)
logi("save",table_size(_factories),table_size(_alerts),table_size(_hints))
_db.put("metadata=version",pp.pack(CURRENT_VERSION))
_db.put("metadata=factories",pp.pack(_factories))
_db.put("metadata=alerts",pp.pack(_alerts))
_db.put("metadata=hints",pp.pack({})) -- we don't save the hints but recalc them every time we start
logi("save - flushing uncommited data",skip_flushing_)
while not skip_flushing_ and flush_cache(UPDATE_AMOUNT) do
-- nop
end
end
local function reset(resource_,options_)
local timestamp = to_timestamp(options_.timestamp,time_now(),nil)
local level = tonumber(options_.level) or 0
local force = is_true(options_.force)
local str = strout("","\n")
local format = string.format
local col = collectionout(str,"[","]")
local timestamp = tonumber(options_.timestamp)
col.head()
if resource_=="" then
logw("reset - got empty key. bailing out");
else
for name in db_.matching_keys(resource_,level) do
if force then
logi("reset",name)
_updated_sequences[name] = nil
_db.out(name)
col.elem(format("\"%s\"",name))
elseif timestamp then
flush_cache_of_sequence(name)
local seq = sequence(db_,name)
logi("reset to timestamp",name,timestamp)
if seq.reset_to_timestamp(timestamp) then
col.elem(format("\"%s\"",name))
end
end
end
end
col.tail()
return wrap_json(str)
end
local function alert_set(resource_,options_)
if not resource_ or #resource_==0 then
return nil
end
local metric,step,period = split_name(resource_)
local new_alert = {
_critical_low = tonumber(options_.critical_low),
_warning_low = tonumber(options_.warning_low),
_warning_high = tonumber(options_.warning_high),
_critical_high = tonumber(options_.critical_high),
_period = parse_time_unit(options_.period),
_stale = parse_time_unit(options_.stale),
_sum = 0,
_state = ""
}
local function compare_with_existing()
if not _alerts[resource_] then
return false
end
local fields = {
"_critical_low",
"_warning_low",
"_warning_high",
"_critical_high",
"_period",
"_stale"
}
local existing = _alerts[resource_]
for _,f in ipairs(fields) do
if new_alert[f]~=existing[f] then
return false
end
end
return true
end
if not (metric and step and period and
new_alert._critical_low and new_alert._warning_low and
new_alert._critical_high and new_alert._warning_high and
new_alert._period) then
logw("alert_set threshold ill defined",resource_,t2s(options_),t2s(new_alert))
return nil
end
-- idempotent is king
if compare_with_existing() then
return ""
end
_alerts[resource_] = new_alert
-- we now force a check to fill in the current state
local seq = sequence(_db,resource_)
alert_check(seq,time_now())
logi("set alert",resource_,t2s(_alerts[resource_]))
save(true)
return ""
end
local function alert_remove(resource_)
if not _alerts[resource_] then
logw("alert not found",resource_)
return nil
end
_alerts[resource_] = nil
logi("remove alert",resource_)
save()
return ""
end
local function alert(resource_)
local as = #resource_>0 and split(resource_,"/") or keys(_alerts)
return wrap_json(output_alerts(as,#resource_==0))
end
local function merge_lines(sorted_file_,step_,period_,now_)
local last_metric,seq
local str = stdout("")
local format = string.format
local period = parse_time_unit(period_)
local function output_sequence(metric_,seq_)
for _,s in ipairs(seq_.slots()) do
str.write(metric_," ",s._sum," ",s._timestamp," ",s._hits,"\n")
end
end
function helper(f)
for l in f:lines() do
local items,t = parse_input_line(l)
if t=="command" then
logw("sorted_line - command in input file. ignoring",l)
else
if items[1]~=last_metric then
if seq then
output_sequence(last_metric,seq)
end
last_metric = items[1]
seq = sparse_sequence(format("%s;%s:%s",last_metric,step_,period_))
end
local timestamp,hits,sum,_ = legit_input_line(items[1],items[2],items[3],items[4])
if not timestamp then
logw("merge_lines - bad params",l)
elseif timestamp>now_-period then
seq.update(timestamp,hits,sum)
end
end
end
if seq then
output_sequence(seq)
end
return true
end
with_file(sorted_file_,helper)
end
local function command(items_)
local func = items_[1]
local dispatch = {
graph = function()
return graph(items_[2],qs_params(items_[3]))
end,
key = function()
return key(items_[2],qs_params(items_[3]))
end,
alert = function()
return alert(items_[2])
end,
alert_remove = function()
return alert_remove(items_[2])
end,
alert_set= function()
return alert_set(items_[2],{
critical_low = items_[3],
warning_low = items_[4],
warning_high = items_[5],
critical_high = items_[6],
period = items_[7],
stale = items_[8],
})
end,
latest = function()
return latest(items_[2],qs_params(items_[3]))
end,
slot = function()
return slot(items_[2],qs_params(items_[3]))
end,
gc = function()
return gc(items_[2],qs_params(items_[3]))
end,
reset = function()
return reset(items_[2],qs_params(items_[3]))
end,
dump = function()
return dump(items_[2],qs_params(items_[3]))
end,
merge_lines = function()
return merge_lines(items_[2],items_[3],items_[4],items_[5])
end,
}
if dispatch[func] then
return dispatch[func]()
end
loge("unknown command",func)
end
local function configure(configuration_lines_)
for l in lines_without_comments(configuration_lines_) do
local items,t = parse_input_line(l)
if t then
logw("unexpexted type",type)
else
local metric = items[1]
table.remove(items,1)
add_factory(metric,items)
end
end
logi("configure",table_size(_factories))
save(true)
return table_size(_factories)
end
local function export_configuration()
local str = strout("")
local format = string.format
local col = collectionout(str,"{","}")
col.head()
for fm,rps in pairs(_factories) do
local col1 = collectionout(str,"[","]\n")
col.elem(format("\"%s\": ",fm))
col1.head()
for _,v in ipairs(rps) do
col1.elem(format("\"%s:%s\" ",secs_to_time_unit(v[1]),secs_to_time_unit(v[2])))
end
col1.tail()
end
col.tail()
logi("export_configuration",table_size(_factories))
return wrap_json(str)
end
local function factories_out(resource_,options_)
local str = strout("")
local format = string.format
local col = collectionout(str,"{","}")
local force = is_true(options_ and options_.force)
col.head()
for fm in split_helper(resource_,"/") do
local rps = _factories[fm]
if force then
_factories[fm] = nil
end
if rps then
local col1 = collectionout(str,"[","]\n")
col.elem(format("\"%s\": ",fm))
col1.head()
for _,v in ipairs(rps) do
col1.elem(format("\"%s:%s\" ",secs_to_time_unit(v[1]),secs_to_time_unit(v[2])))
end
col1.tail()
end
end
col.tail()
logi("factories_out",table_size(_factories))
uniq_factories()
return wrap_json(str)
end
local function load()
logi("load")
local function helper(key_,dont_cache_,default_)
local v = _db.get(key_,dont_cache_)
return v and pp.unpack(v) or default_
end
local version = helper("metadata=version",true,CURRENT_VERSION)
if not version==CURRENT_VERSION then
error("unknown version")
return nil
end
_factories = helper("metadata=factories",true,{})
-- there was a bug which caused factories to be non-uniq so we fix it
uniq_factories()
_alerts = helper("metadata=alerts",true,{})
_hints = {}
logi("load",table_size(_factories),table_size(_alerts),table_size(_hints))
end
local function update_line(metric_,sum_,timestamp_,hits_,now_)
local timestamp,hits,sum,typ = legit_input_line(metric_,sum_,timestamp_,hits_)
if not timestamp then
logw("update_line - bad params",metric_,sum_,timestamp_)
return
end
if sum==0 then -- don't bother to update
return
end
for n,m in get_sequences(metric_) do
local skip = false
local new_key = false
if now_ then
local metric,step,period = parse_name(n)
skip = timestamp_<now_-period
end
if not skip then
local seq = _updated_sequences[n]
if not seq then
-- this might be a new key and so we should add it to the DB as well. Kind of ugly, but we rely on the
-- DB (and not the caches) when looking for keys
seq = sparse_sequence(n)
new_key = true
end
local adjusted_timestamp,sum = seq.update(timestamp,hits,sum,typ)
-- it might happen that we try to update a too old timestamp. In such a case
-- the update function returns null
if adjusted_timestamp then
_updated_sequences[n] = seq
if new_key then
flush_cache_of_sequence(n,seq)
end
end
end
end
end
local function flush_all_caches(amount_,step_)
amount_ = amount_ or UPDATE_AMOUNT
local fc1 = flush_cache(amount_,step_)
local fc2 = _db.flush_cache(amount_/4,step_)
return fc1 or fc2
end
local function modify_factories(factories_modifications_)
-- the factories_modifications_ is a list of triples,
-- <pattern, original retention, new retention>
for _,f in ipairs(factories_modifications_) do
local factory = _factories[f[1]]
if factory then
local orig_step,orig_period = parse_time_pair(f[2])
local new_step,new_period = parse_time_pair(f[3])
for j,r in ipairs(factory) do
if r[1]==orig_step and r[2]==orig_period then
logd("found original factory:",f[1])
factory[j] = {new_step,new_period}
-- scan the metrics hierarchy. every matching sequence should be replaced with
-- a new retention
for seq in sequences_for_prefix(_db,f[1],f[2]) do
logd("found original sequence:",seq.name())
local new_name = name(seq.metric(),new_step,new_period)
sequence(db_,new_name).update_batch(seq.slots(),0,1,2)
_db.out(seq.name())
end
end
end
else
logw("pattern not found",f[1])
end
end
flush_all_caches()
end
local function process_line(metric_line_,no_commands_)
local function helper()
local items,t = parse_input_line(metric_line_)
if #items==0 then
if #metric_line_>0 then
logd("bad input",metric_line_)
end
return nil
end
if t=="command" then
return not no_commands_ and command(items)
end
-- there are 2 line formats:
-- 1) of the format metric sum timestamp
-- 2) of the format (without the brackets) name (sum hits timestamp)+
-- 1) standard update
if not string.find(items[1],";",1,true) then
return update_line(items[1],items[2],items[3],items[4])
end
-- 2) an entire sequence
local name = items[1]
table.remove(items,1)
-- here we DON'T use the sparse sequence as they aren't needed when reading an
-- entire sequence
-- TODO might be a corrupted line with ';' accidently in the line.
return sequence(_db,name).update_batch(items,2,1,0)
end
local success,rv = pcall(helper)
if success then
return rv
end
logw("process_line error",rv,metric_line_)
return nil
end
local function process(data_,dont_update_,no_commands_)
local lines_count = 0
local function spillover_protection()
-- we protect from _updated_sequences growing too large if the input data is large
lines_count = lines_count + 1
if lines_count==UPDATED_SEQUENCES_MAX then
logi("process - forcing an update",lines_count)
flush_cache(UPDATE_AMOUNT)
lines_count = lines_count - UPDATE_AMOUNT
end
end
-- strings are handled as file pointers if they exist or as a line
-- tables as arrays of lines
-- functions as iterators of lines
local function helper()
if type(data_)=="string" then
local file_exists = with_file(data_,
function(f)
for l in f:lines() do
process_line(l,no_commands_)
spillover_protection()
end
return true
end)
if file_exists then
return true
end
return process_line(data_)
end
if type(data_)=="table" then
local rv
for _,d in ipairs(data_) do
rv = process_line(d)
spillover_protection()
end
return rv
end
-- we assume it is a function
local rv
local count = 0
for d in data_ do
rv = process_line(d)
count = count + 1
spillover_protection()
end
logd("processed",count)
return rv
end
local rv = helper()
if not dont_update_ then
flush_all_caches()
end
return rv
end
local function matching_sequences(metric_)
local seqs = {}
each_metric(_db,metric_,nil,
function(seq)
table.insert(seqs,seq)
end)
return seqs
end
return {
configure = configure,
export_configuration = export_configuration,
factories_out = factories_out,
matching_sequences = matching_sequences,
get_factories = function() return _factories end,
reset = reset,
dump = dump,
graph = graph,
key = key,
gc = gc,
latest = latest,
slot = slot,
modify_factories = modify_factories,
process = process,
flush_cache = flush_all_caches,
save = save,
load = load,
alert_set = alert_set,
alert_remove = alert_remove,
alert = alert,
kvs_put = kvs_put,
kvs_get = kvs_get,
kvs_out = kvs_out,
}
end
| apache-2.0 |
jshackley/darkstar | scripts/globals/weaponskills/ascetics_fury.lua | 18 | 4499 | -----------------------------------
-- Ascetics Fury
-- Hand-to-Hand weapon skill
-- Skill Level: N/A
-- Chance of params.critical hit varies with TP. Glanzfaust: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Monk) quest.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: None
-- Modifiers: STR:50% ; VIT:50%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.1; params.crit200 = 0.3; params.crit300 = 0.5;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.atkmulti = 2.6;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if ((player:getEquipID(SLOT_MAIN) == 18992) and (player:getMainJob() == JOB_MNK)) then
if (damage > 0) then
-- AFTERMATH LEVEL 1
if ((player:getTP() >= 100) and (player:getTP() <= 110)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 1);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1);
-- AFTERMATH LEVEL 2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1);
-- AFTERMATH LEVEL 3
elseif ((player:getTP() == 300)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1);
end
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Markets/npcs/Harmodios.lua | 34 | 2101 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Harmodios
-- Standard Merchant NPC
-- @pos -79.928 -4.824 -135.114 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,10) == false) then
player:startEvent(0x01ae);
else
player:showText(npc,HARMODIOS_SHOP_DIALOG);
stock = {
0x43C3, 990,1, --Piccolo
0x43C0, 219,2, --Cornette
0x43C9, 43,2, --Maple Harp
0x13B1, 69120,2, --Scroll of Vital Etude
0x13B2, 66240,2, --Scroll of Swift Etude
0x13B3, 63360,2, --Scroll of Sage Etude
0x13B4, 56700,2, --Scroll of Logical Etude
0x13AF, 79560,2, --Scroll of Herculean Etude
0x13B0, 76500,2, --Scroll of Uncanny Etude
0x43C7, 4644,3, --Gemshorn
0x43C1, 43,3, --Flute
0x13B5, 54000,3 --Scroll of Bewitching Etude
}
showNationShop(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);
if (csid == 0x01ae) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",10,true);
end
end;
| gpl-3.0 |
drhelius/Gearboy | platforms/ios/dependencies/SDL-2.0.4-9174/premake/util/sdl_dependency_checkers.lua | 7 | 7874 | -- Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org>
--
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
--
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely.
--
-- Meta-build system using premake created and maintained by
-- Benjamin Henning <b.henning@digipen.edu>
--[[
sdl_dependency_checkers.lua
This script contains a bunch of functions which determine whether certain
dependencies exist on the current platform. These functions are able to use
any and all available utilities for trying to determine both whether the
dependency is available on this platform, and how to build to the dependency.
There are a few limitations with these functions, but many of the limitations
can be mitigated by using the dependency definition functions in the project
definition files.
Each function in this file, in order to be a valid dependency function, must
return a table with the following entries:
'found' = boolean value indicating whether the dependency was found
'incDirs' = table of include directory strings, or nil if none are needed
'libDirs' = table of library directory strings, or nil if none are needed
'libs' = table of libraries to link to, or nil if none are needed
All functions must be properly registered with the project definition system
in order to be properly referenced by projects.
]]
-- dependency functions must return the following:
-- table with an element found, incDirs, libDirs, and libs
function openGLDep()
print("Checking OpenGL dependencies...")
if SDL_getos() == "macosx" then
-- mac should always have support for OpenGL...
return { found = true, libs = { "OpenGL.framework" } }
elseif SDL_getos() == "ios" then
--...unless on iOS
print("Desktop OpenGL is not supported on iOS targets.")
return { found = false, libs = { "OpenGL.framework" } }
elseif SDL_getos() == "cygwin" then
print("OpenGL is not currently supported on Cygwin.")
return { found = false, libDirs = { }, libs = { "OpenGL32" } }
end
local libpath = nil
local libname = nil
if SDL_getos() == "windows" or SDL_getos() == "mingw" then
libpath = os.findlib("OpenGL32")
libname = "OpenGL32"
else -- *nix
libpath = os.findlib("libGL")
libname = "GL"
end
local foundLib = libpath ~= nil
-- another way to possibly find the dependency on windows
--if not foundLib then
-- foundLib, libpath = find_dependency_dir_windows(nil, "C:/Program Files (x86);C:/Program Files", "Microsoft SDKs", "Lib")
--end
if not foundLib then return { found = false } end
if SDL_getos() == "mingw" then
libpath = libpath:gsub("\\", "/"):gsub("//", "/")
end
return { found = foundLib, libDirs = { }, libs = { libname } }
end
function directXDep()
print("Checking DirectX dependencies...")
-- enable this for more correct searching, but it's much slower
local searchPath = nil --os.getenvpath("ProgramFiles", "ProgramFiles(x86)")
local foundInc, incpath = find_dependency_dir_windows("DXSDK_DIR", searchPath, "DirectX", "Include")
local foundLib, libpath = find_dependency_dir_windows("DXSDK_DIR", searchPath, "DirectX", "Lib/x86")
if not foundInc or not foundLib then return { found = false } end
-- XXX: hacked mingw check...
if foundInc and SDL_getos() == "mingw" then
incpath = incpath:gsub("%$%(DXSDK_DIR%)", os.getenv("DXSDK_DIR")):gsub("\\", "/"):gsub("//", "/")
libpath = libpath:gsub("%$%(DXSDK_DIR%)", os.getenv("DXSDK_DIR")):gsub("\\", "/"):gsub("//", "/")
end
if SDL_getos() == "mingw" then
print("DirectX is not currently supported on MinGW targets.")
return { found = false, incDirs = { incpath }, libDirs = { libpath } }
end
if SDL_getos() == "cygwin" then
print("DirectX is not currently supported on Cygwin targets.")
return { found = false, incDirs = { incpath }, libDirs = { libpath } }
end
return { found = true, incDirs = { incpath }, libDirs = { libpath } }
end
function dbusDep()
print("Checking for D-Bus support...")
if not check_include_directories("/usr/include/dbus-1.0", "/usr/lib/x86_64-linux-gnu/dbus-1.0/include") then
print("Warning: D-Bus unsupported!")
return { found = false }
end
return { found = true, incDirs = { "/usr/include/dbus-1.0", "/usr/lib/x86_64-linux-gnu/dbus-1.0/include" } }
end
function alsaDep()
print("Checking for ALSA support...")
if not check_include_files("alsa/asoundlib.h")
or os.findlib("asound") == nil
or not check_library_exists_lookup("asound", "snd_pcm_open", "alsa/asoundlib.h")
or not SDL_assertdepfunc("DLOpen") then
print("Warning: ALSA unsupported!")
return { found = false }
end
return { found = true }
end
function pulseAudioDep()
print("Checking for PulseAudio support...")
if os.findlib("libpulse-simple") == nil
or not SDL_assertdepfunc("DLOpen") then
print("Warning: PulseAudio unsupported!")
return { found = false }
end
return { found = true }
end
function esdDep()
print("Checking for ESD support...")
if os.findlib("esd") == nil
or not SDL_assertdepfunc("DLOpen") then
print("Warning: ESD unsupported!")
return { found = false }
end
return { found = true }
end
function nasDep()
print("Checking for NAS support...")
if not check_include_file("audio/audiolib.h")
or not SDL_assertdepfunc("DLOpen") then
print("Warning: NAS unsupported!")
return { found = false }
end
return { found = true }
end
function ossDep()
print("Checking for OSS support...")
if not check_cxx_source_compiles([[
#include <sys/soundcard.h>
int main() { int arg = SNDCTL_DSP_SETFRAGMENT; return 0; }]])
and not check_cxx_source_compiles([[
#include <soundcard.h>
int main() { int arg = SNDCTL_DSP_SETFRAGMENT; return 0; }]]) then
print("Warning: OSS unsupported!")
return { found = false }
end
return { found = true }
end
function dlOpenDep()
print("Checking for DLOpen support...")
if not check_library_exists_multiple("dlopen", "dlfcn.h", "dl", "tdl") then
print("Warning: DLOpen unsupported!")
return { found = false }
end
return { found = true, libs = { "dl" } }
end
function x11Dep()
print("Checking for X11 support...")
for _, v in ipairs { "X11", "Xext", "Xcursor", "Xinerama", "Xi", "Xrandr", "Xrender", "Xss", "Xxf86vm" } do
if os.findlib(v) == nil then
print("Warning: X11 unsupported!")
return { found = false }
end
end
if not check_include_files("X11/Xcursor/Xcursor.h", "X11/extensions/Xinerama.h",
"X11/extensions/XInput2.h", "X11/extensions/Xrandr.h", "X11/extensions/Xrender.h",
"X11/extensions/scrnsaver.h", "X11/extensions/shape.h", "X11/Xlib.h",
"X11/extensions/xf86vmode.h") then
print("Warning: X11 unsupported!")
return { found = false }
end
if not SDL_assertdepfunc("DLOpen") then
print("Warning: X11 unsupported!")
return { found = false }
end
-- XXX: shared memory check...
-- there's a LOT more to check to properly configure X11...
return { found = true, libs = { "X11" } }
end
-- register all of these dependency functions with the definition system
SDL_registerDependencyChecker("OpenGL", openGLDep)
SDL_registerDependencyChecker("DirectX", directXDep)
SDL_registerDependencyChecker("DBus", dbusDep)
SDL_registerDependencyChecker("ALSA", alsaDep)
SDL_registerDependencyChecker("PulseAudio", pulseAudioDep)
SDL_registerDependencyChecker("ESD", esdDep)
SDL_registerDependencyChecker("NAS", nasDep)
SDL_registerDependencyChecker("OSS", ossDep)
SDL_registerDependencyChecker("DLOpen", dlOpenDep)
SDL_registerDependencyChecker("X11", x11Dep)
| gpl-3.0 |
Ombridride/minetest-minetestforfun-server | mods/plantlife_modpack/woodsoils/generating.lua | 9 | 4536 | -- generating of forest soils
local RaDiuS = {
-- WE1 NS1 WE2 NS2 WE3 NS3
{-1,-2, -2,-2, -2,-3},
{ 0,-2, -3,-1, -3,-2},
{ 1,-2, -3, 0, -4,-1},
{-2,-1, -3, 1, -4, 0},
{-1,-1, -2, 2, -4, 1},
{ 0,-1, -1, 3, -3, 2},
{ 1,-1, 0, 3, -2, 3},
{ 2,-1, 1, 3, -1, 4},
{-2, 0, 2, 2, 0, 4},
{-1, 0, 3, 1, 1, 4},
{ 0, 0, 3, 0, 2, 3},
{ 1, 0, 3,-1, 3, 2},
{ 2, 0, 2,-2, 4, 1},
{-2, 1, 1,-3, 4, 0},
{-1, 1, 0,-3, 4,-1},
{ 0, 1, -1,-3, 3,-2},
{ 1, 1, 0, 0, 2,-3},
{ 2, 1, 0, 0, 1,-4},
{-1, 2, 0, 0, 0,-4},
{ 0, 2, 0, 0, -1,-4},
{ 1, 2, 0, 0, 0, 0},
}
-- e = + , n = +
abstract_woodsoils.place_soil = function(pos)
if minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y-1,z=pos.z}).name, "soil") > 0
or minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y-2,z=pos.z}).name, "soil") > 0 then
for i in pairs(RaDiuS) do
local WE1 = RaDiuS[i][1]
local NS1 = RaDiuS[i][2]
local WE2 = RaDiuS[i][3]
local NS2 = RaDiuS[i][4]
local WE3 = RaDiuS[i][5]
local NS3 = RaDiuS[i][6]
local radius_1a = {x=pos.x+WE1,y=pos.y-1,z=pos.z+NS1}
local radius_1b = {x=pos.x+WE1,y=pos.y-2,z=pos.z+NS1}
local radius_2a = {x=pos.x+WE2,y=pos.y-1,z=pos.z+NS2}
local radius_2b = {x=pos.x+WE2,y=pos.y-2,z=pos.z+NS2}
local radius_3a = {x=pos.x+WE3,y=pos.y-1,z=pos.z+NS3}
local radius_3b = {x=pos.x+WE3,y=pos.y-2,z=pos.z+NS3}
--local node_1a = minetest.get_node(radius_1a)
--local node_1b = minetest.get_node(radius_1b)
local node_2a = minetest.get_node(radius_2a)
local node_2b = minetest.get_node(radius_2b)
local node_3a = minetest.get_node(radius_3a)
local node_3b = minetest.get_node(radius_3b)
-- Dirt with Leaves 1
if minetest.get_item_group(minetest.get_node(radius_1a).name, "soil") > 0 then
minetest.set_node(radius_1a, {name="woodsoils:dirt_with_leaves_1"})
end
if minetest.get_item_group(minetest.get_node(radius_1b).name, "soil") > 0 then
minetest.set_node(radius_1b, {name="woodsoils:dirt_with_leaves_1"})
end
-- Grass with Leaves 2
if string.find(node_2a.name, "dirt_with_grass") then
minetest.set_node(radius_2a, {name="woodsoils:grass_with_leaves_2"})
end
if string.find(node_2b.name, "dirt_with_grass") then
minetest.set_node(radius_2b, {name="woodsoils:grass_with_leaves_2"})
end
-- Grass with Leaves 1
if string.find(node_3a.name, "dirt_with_grass") then
minetest.set_node(radius_3a, {name="woodsoils:grass_with_leaves_1"})
end
if string.find(node_3b.name, "dirt_with_grass") then
minetest.set_node(radius_3b, {name="woodsoils:grass_with_leaves_1"})
end
end
end
end
biome_lib:register_generate_plant({
surface = {
"group:tree",
"ferns:fern_03",
"ferns:fern_02",
"ferns:fern_01"
},
max_count = 1000,
rarity = 1,
min_elevation = 1,
max_elevation = 40,
near_nodes = {"group:tree","ferns:fern_03","ferns:fern_02","ferns:fern_01"},
near_nodes_size = 5,
near_nodes_vertical = 1,
near_nodes_count = 4,
plantlife_limit = -1,
check_air = false,
},
"abstract_woodsoils.place_soil"
)
biome_lib:register_generate_plant({
surface = {
"moretrees:apple_tree_sapling_ongen",
"moretrees:beech_sapling_ongen",
"moretrees:birch_sapling_ongen",
"moretrees:fir_sapling_ongen",
"moretrees:jungletree_sapling_ongen",
"moretrees:oak_sapling_ongen",
"moretrees:palm_sapling_ongen",
"moretrees:rubber_tree_sapling_ongen",
"moretrees:sequoia_sapling_ongen",
"moretrees:spruce_sapling_ongen",
"moretrees:willow_sapling_ongen"
},
max_count = 1000,
rarity = 2,
min_elevation = 1,
max_elevation = 40,
plantlife_limit = -0.9,
check_air = false,
},
"abstract_woodsoils.place_soil"
)
minetest.register_abm({
nodenames = {"default:papyrus"},
neighbors = {
"woodsoils:dirt_with_leaves_1",
"woodsoils:dirt_with_leaves_2",
"woodsoils:grass_with_leaves_1",
"woodsoils:grass_with_leaves_2"
},
interval = 50,
chance = 20,
action = function(pos, node)
pos.y = pos.y-1
local name = minetest.get_node(pos).name
if string.find(name, "_with_leaves_") then
if minetest.find_node_near(pos, 3, {"group:water"}) == nil then
return
end
pos.y = pos.y+1
local height = 0
while minetest.get_node(pos).name == "default:papyrus" and height < 4 do
height = height+1
pos.y = pos.y+1
end
if height < 4 then
if minetest.get_node(pos).name == "air" then
minetest.set_node(pos, {name="default:papyrus"})
end
end
end
end,
})
| unlicense |
10sa/Advanced-Nutscript | nutscript/entities/weapons/nut_fists.lua | 1 | 6044 | AddCSLuaFile()
if (CLIENT) then
SWEP.PrintName = "주먹"
SWEP.Slot = 1
SWEP.SlotPos = 1
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = false
end
SWEP.Author = "Chessnut"
SWEP.Instructions = "왼쪽 클릭: [R 꾹 눌러 들기] 주먹질\n오른쪽 클릭: 문 두드리기/물건 들기"
SWEP.Purpose = "무언가를 들고 치거나 문을 두드릴 수 있습니다."
SWEP.Drop = false
SWEP.ViewModelFOV = 45
SWEP.ViewModelFlip = false
SWEP.AnimPrefix = "rpg"
SWEP.ViewTranslation = 4
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = ""
SWEP.Primary.Damage = 5
SWEP.Primary.Delay = 0.75
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = 0
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = ""
SWEP.ViewModel = Model("models/weapons/c_arms_cstrike.mdl")
SWEP.WorldModel = ""
SWEP.UseHands = false
SWEP.LowerAngles = Angle(0, 5, -22)
SWEP.FireWhenLowered = true
SWEP.HoldType = "normal"
function SWEP:PreDrawViewModel(viewModel, weapon, client)
local hands = player_manager.RunClass(client, "GetHandsModel")
if (hands and hands.model) then
viewModel:SetModel(hands.model)
viewModel:SetSkin(hands.skin)
viewModel:SetBodyGroups(hands.body)
end
end
ACT_VM_FISTS_DRAW = 3
ACT_VM_FISTS_HOLSTER = 2
function SWEP:Deploy()
if (!IsValid(self.Owner)) then
return
end
local viewModel = self.Owner:GetViewModel()
if (IsValid(viewModel)) then
viewModel:SetPlaybackRate(1)
viewModel:ResetSequence(ACT_VM_FISTS_DRAW)
end
return true
end
function SWEP:Holster()
if (!IsValid(self.Owner)) then
return
end
local viewModel = self.Owner:GetViewModel()
if (IsValid(viewModel)) then
viewModel:SetPlaybackRate(1)
viewModel:ResetSequence(ACT_VM_FISTS_HOLSTER)
end
return true
end
function SWEP:Think()
local viewModel = self.Owner:GetViewModel()
if (IsValid(viewModel)) then
viewModel:SetPlaybackRate(1)
end
end
function SWEP:Precache()
util.PrecacheSound("npc/vort/claw_swing1.wav")
util.PrecacheSound("npc/vort/claw_swing2.wav")
util.PrecacheSound("physics/plastic/plastic_box_impact_hard1.wav")
util.PrecacheSound("physics/plastic/plastic_box_impact_hard2.wav")
util.PrecacheSound("physics/plastic/plastic_box_impact_hard3.wav")
util.PrecacheSound("physics/plastic/plastic_box_impact_hard4.wav")
end
function SWEP:Initialize()
self:SetWeaponHoldType(self.HoldType)
self.LastHand = 0
end
function SWEP:DoPunchAnimation()
self.LastHand = math.abs(1 - self.LastHand)
local sequence = 4 + self.LastHand
local viewModel = self.Owner:GetViewModel()
if (IsValid(viewModel)) then
viewModel:SetPlaybackRate(0.5)
viewModel:SetSequence(sequence)
end
end
function SWEP:PrimaryAttack()
if (!IsFirstTimePredicted()) then
return
end
if (!self.Owner.character) then
return
end
self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
local stamina = math.Clamp(self.Owner.character:GetVar("stamina", 100) - 10, 0, 100)
if (!self.Owner:WepRaised() or stamina <= 0) then
return
end
self:EmitSound("npc/vort/claw_swing"..math.random(1, 2)..".wav")
local damage = self.Primary.Damage
self:DoPunchAnimation()
self.Owner.character:SetVar("stamina", stamina)
self.Owner:SetAnimation(PLAYER_ATTACK1)
self.Owner:ViewPunch(Angle(self.LastHand + 2, self.LastHand + 5, 0.125))
timer.Simple(0.055, function()
if (IsValid(self) and IsValid(self.Owner)) then
local damage = self.Primary.Damage
local result = AdvNut.hook.Run("PlayerGetFistDamage", self.Owner, damage)
if (result != nil) then
damage = result
end
local data = {}
data.start = self.Owner:GetShootPos()
data.endpos = data.start + self.Owner:GetAimVector()*96
data.filter = self.Owner
local trace = util.TraceLine(data)
if (SERVER and trace.Hit) then
local entity = trace.Entity
if (IsValid(entity)) then
local damageInfo = DamageInfo()
damageInfo:SetAttacker(self.Owner)
damageInfo:SetInflictor(self)
damageInfo:SetDamage(damage)
damageInfo:SetDamageType(DMG_SLASH)
damageInfo:SetDamagePosition(trace.HitPos)
damageInfo:SetDamageForce(self.Owner:GetAimVector()*10000)
entity:DispatchTraceAttack(damageInfo, data.start, data.endpos)
self.Owner:EmitSound("physics/body/body_medium_impact_hard"..math.random(1, 6)..".wav", 80)
end
end
AdvNut.hook.Run("PlayerThrowPunch", self.Owner, trace.Hit)
end
end)
end
function SWEP:CanCarry(entity)
local physicsObject = entity:GetPhysicsObject()
if (!IsValid(physicsObject)) then
return false
end
if (physicsObject:GetMass() > 100 or !physicsObject:IsMoveable()) then
return false
end
if (IsValid(entity.carrier)) then
return false
end
return true
end
function SWEP:DoPickup(entity)
if (entity:IsPlayerHolding()) then
return
end
timer.Simple(FrameTime() * 10, function()
if (!IsValid(entity) or entity:IsPlayerHolding()) then
return
end
self.Owner:PickupObject(entity)
self.Owner:EmitSound("physics/body/body_medium_impact_soft"..math.random(1, 3)..".wav", 75)
end)
self:SetNextSecondaryFire(CurTime() + 1)
end
function SWEP:SecondaryAttack()
if (!IsFirstTimePredicted()) then
return
end
local trace = self.Owner:GetEyeTraceNoCursor()
local entity = trace.Entity
if (SERVER and IsValid(entity)) then
local distance = self.Owner:EyePos():Distance(trace.HitPos)
if (distance > 72) then
return
end
if (string.find(entity:GetClass(), "door")) then
if (AdvNut.hook.Run("PlayerCanKnock", self.Owner, entity) == false) then
return
end
self.Owner:ViewPunch(Angle(-1.3, 1.8, 0))
self.Owner:EmitSound("physics/plastic/plastic_box_impact_hard"..math.random(1, 4)..".wav")
self.Owner:SetAnimation(PLAYER_ATTACK1)
self:DoPunchAnimation()
self:SetNextSecondaryFire(CurTime() + 0.4)
self:SetNextPrimaryFire(CurTime() + 1)
elseif (!entity:IsPlayer() and !entity:IsNPC() and self:CanCarry(entity)) then
local physObj = entity:GetPhysicsObject()
physObj:Wake()
self:DoPickup(entity)
end
end
end
| mit |
Keithenneu/Dota2-FullOverwrite | hero_think.lua | 2 | 12234 | -------------------------------------------------------------------------------
--- AUTHOR: Nostrademous
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
-------------------------------------------------------------------------------
_G._savedEnv = getfenv()
module( "hero_think", package.seeall )
-------------------------------------------------------------------------------
require( GetScriptDirectory().."/constants" )
require( GetScriptDirectory().."/item_usage" )
local gHeroVar = require( GetScriptDirectory().."/global_hero_data" )
local utils = require( GetScriptDirectory().."/utility" )
local function setHeroVar(var, value)
gHeroVar.SetVar(GetBot():GetPlayerID(), var, value)
end
local function getHeroVar(var)
return gHeroVar.GetVar(GetBot():GetPlayerID(), var)
end
local specialFile = nil
local specialFileName = nil
function tryHeroSpecialMode()
specialFile = dofile(specialFileName)
end
-- Consider incoming projectiles or nearby AOE and if we can evade.
-- This is of highest importance b/c if we are stunned/disabled we
-- cannot do any of the other actions we might be asked to perform.
function ConsiderEvading(bot)
if bot.evasionMode ~= nil then
return bot.evasionMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/evasion_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.evasionMode = specialFile
return bot.evasionMode:Desire(bot)
else
specialFileName = nil
bot.evasionMode = dofile( GetScriptDirectory().."/modes/evasion" )
return bot.evasionMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- Fight orchestration is done at a global Team level.
-- This just checks if we are given a fight target and a specific
-- action queue to execute as part of the fight.
function ConsiderAttacking(bot)
if bot.fightMode ~= nil then
return bot.fightMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/fight_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.fightMode = specialFile
return bot.fightMode:Desire(bot)
else
specialFileName = nil
bot.fightMode = dofile( GetScriptDirectory().."/modes/fight" )
return bot.fightMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- Which Heroes should be present for Shrine heal is made at Team level.
-- This just tells us if we should be part of this event.
function ConsiderShrine(bot, playerAssignment)
if bot:IsIllusion() then return BOT_MODE_DESIRE_NONE end
if bot.shrineMode ~= nil then
return bot.shrineMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/shrine_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.shrineMode = specialFile
return bot.shrineMode:Desire(bot)
else
specialFileName = nil
bot.shrineMode = dofile( GetScriptDirectory().."/modes/shrine" )
return bot.shrineMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- Determine if we should retreat. Team Fight Assignements can
-- over-rule our desire though. It might be more important for us to die
-- in a fight but win the over-all battle. If no Team Fight Assignment,
-- then it is up to the Hero to manage their safety from global and
-- tower/creep damage.
function ConsiderRetreating(bot)
if bot.retreatMode ~= nil then
return bot.retreatMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/retreat_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.retreatMode = specialFile
return bot.retreatMode:Desire(bot)
else
specialFileName = nil
bot.retreatMode = dofile( GetScriptDirectory().."/modes/retreat" )
return bot.retreatMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- Courier usage is done at Team wide level. We can do our own
-- shopping at secret/side shop if we are informed that the courier
-- will be unavailable to use for a certain period of time.
function ConsiderSecretAndSideShop(bot)
if bot.shopMode ~= nil then
return bot.shopMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/shop_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.shopMode = specialFile
return bot.shopMode:Desire(bot)
else
specialFileName = nil
bot.shopMode = dofile( GetScriptDirectory().."/modes/shop" )
return bot.shopMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- The decision is made at Team level.
-- This just checks if the Hero is part of the push, and if so,
-- what lane.
function ConsiderPushingLane(bot)
if bot.pushlaneMode ~= nil then
return bot.pushlaneMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/pushlane_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.pushlaneMode = specialFile
return bot.pushlaneMode:Desire(bot)
else
specialFileName = nil
bot.pushlaneMode = dofile( GetScriptDirectory().."/modes/pushlane" )
return bot.pushlaneMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- The decision is made at Team level.
-- This just checks if the Hero is part of the defense, and
-- where to go to defend if so.
function ConsiderDefendingLane(bot)
if bot.defendLane ~= nil then
return bot.defendLane:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/defendlane_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.defendLane = specialFile
return bot.defendLane:Desire(bot)
else
specialFileName = nil
bot.defendLane = dofile( GetScriptDirectory().."/modes/defendlane" )
return bot.defendLane:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- This is a localized lane decision. An ally defense can turn into an
-- orchestrated Team level fight, but that will be determined at the
-- Team level. If not a fight, then this is just a "buy my retreating
-- friend some time to go heal up / retreat".
function ConsiderDefendingAlly(bot)
if bot.defendAlly ~= nil then
return bot.defendAlly:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/defendally_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.defendAlly = specialFile
return bot.defendAlly:Desire(bot)
else
specialFileName = nil
bot.defendAlly = dofile( GetScriptDirectory().."/modes/defendally" )
return bot.defendAlly:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- Roaming decision are made at the Team level to keep all relevant
-- heroes informed of the upcoming kill opportunity.
-- This just checks if this Hero is part of the Gank.
function ConsiderRoam(bot)
if bot.roam ~= nil then
return bot.roam:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/roam_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.roam = specialFile
return bot.roam:Desire(bot)
else
specialFileName = nil
bot.roam = dofile( GetScriptDirectory().."/modes/roam" )
return bot.roam:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- The decision if and who should get Rune is made Team wide.
-- This just checks if this Hero should get it.
function ConsiderRune(bot, playerAssignment)
if GetGameState() ~= GAME_STATE_GAME_IN_PROGRESS then return BOT_MODE_DESIRE_NONE end
local playerRuneAssignment = playerAssignment[bot:GetPlayerID()].GetRune
if playerRuneAssignment ~= nil then
if playerRuneAssignment[1] == nil or GetRuneStatus(playerRuneAssignment[1]) == RUNE_STATUS_MISSING or
GetUnitToLocationDistance(bot, playerRuneAssignment[2]) > 3600 then
playerAssignment[bot:GetPlayerID()].GetRune = nil
setHeroVar("RuneTarget", nil)
setHeroVar("RuneLoc", nil)
return BOT_MODE_DESIRE_NONE
else
setHeroVar("RuneTarget", playerRuneAssignment[1])
setHeroVar("RuneLoc", playerRuneAssignment[2])
return BOT_MODE_DESIRE_HIGH
end
end
return BOT_MODE_DESIRE_NONE
end
-- The decision to Roshan is done in TeamThink().
-- This just checks if this Hero should be part of the effort.
function ConsiderRoshan(bot)
if bot.roshanMode ~= nil then
return bot.roshanMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/roshan_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.roshanMode = specialFile
return bot.roshanMode:Desire(bot)
else
specialFileName = nil
bot.roshanMode = dofile( GetScriptDirectory().."/modes/roshan" )
return bot.roshanMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- Farming assignments are made Team Wide.
-- This just tells the Hero where he should Jungle.
function ConsiderJungle(bot, playerAssignment)
if bot.junglingMode ~= nil then
return bot.junglingMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/jungling_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.junglingMode = specialFile
return bot.junglingMode:Desire(bot)
else
specialFileName = nil
bot.junglingMode = dofile( GetScriptDirectory().."/modes/jungling" )
return bot.junglingMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- Laning assignments are made Team Wide for Pushing & Defending.
-- Laning assignments are initially determined at start of game/hero-selection.
-- This just tells the Hero which Lane he is supposed to be in.
function ConsiderLaning(bot, playerAssignment)
if playerAssignment[bot:GetPlayerID()].Lane ~= nil then
setHeroVar("CurLane", playerAssignment[bot:GetPlayerID()].Lane)
end
if bot.laningMode ~= nil then
return bot.laningMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/laning_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.laningMode = specialFile
return bot.laningMode:Desire(bot)
else
specialFileName = nil
bot.laningMode = dofile( GetScriptDirectory().."/modes/laning" )
return bot.laningMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
-- Warding is done on a per-lane basis. This evaluates if this Hero
-- should ward, and where. (might be a team wide thing later)
function ConsiderWarding(bot, playerAssignment)
if bot.wardMode ~= nil then
return bot.wardMode:Desire(bot)
else
specialFileName = GetScriptDirectory().."/modes/ward_"..utils.GetHeroName(bot)
if pcall(tryHeroSpecialMode) then
specialFileName = nil
bot.wardMode = specialFile
return bot.wardMode:Desire(bot)
else
specialFileName = nil
bot.wardMode = dofile( GetScriptDirectory().."/modes/ward" )
return bot.wardMode:Desire(bot)
end
end
return BOT_MODE_DESIRE_NONE
end
for k,v in pairs( hero_think ) do _G._savedEnv[k] = v end
| gpl-3.0 |
knipferrc/dotfiles | nvim/lua/user/toggleterm.lua | 4 | 1682 | local status_ok, toggleterm = pcall(require, "toggleterm")
if not status_ok then
return
end
toggleterm.setup({
size = 20,
open_mapping = [[<c-\>]],
hide_numbers = true,
shade_filetypes = {},
shade_terminals = true,
shading_factor = 2,
start_in_insert = true,
insert_mappings = true,
persist_size = true,
direction = "float",
close_on_exit = true,
shell = vim.o.shell,
float_opts = {
border = "curved",
winblend = 0,
highlights = {
border = "Normal",
background = "Normal",
},
},
})
function _G.set_terminal_keymaps()
local opts = {noremap = true}
vim.api.nvim_buf_set_keymap(0, 't', '<esc>', [[<C-\><C-n>]], opts)
vim.api.nvim_buf_set_keymap(0, 't', 'jk', [[<C-\><C-n>]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-h>', [[<C-\><C-n><C-W>h]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-j>', [[<C-\><C-n><C-W>j]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-k>', [[<C-\><C-n><C-W>k]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-l>', [[<C-\><C-n><C-W>l]], opts)
end
vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()')
local Terminal = require("toggleterm.terminal").Terminal
local lazygit = Terminal:new({ cmd = "lazygit", hidden = true })
function _LAZYGIT_TOGGLE()
lazygit:toggle()
end
local node = Terminal:new({ cmd = "node", hidden = true })
function _NODE_TOGGLE()
node:toggle()
end
local ncdu = Terminal:new({ cmd = "ncdu", hidden = true })
function _NCDU_TOGGLE()
ncdu:toggle()
end
local htop = Terminal:new({ cmd = "htop", hidden = true })
function _HTOP_TOGGLE()
htop:toggle()
end
local python = Terminal:new({ cmd = "python", hidden = true })
function _PYTHON_TOGGLE()
python:toggle()
end
| mit |
accelleon/LuaASM | encoder.lua | 1 | 14881 | -- AccelASM encoder
-- The encoder works in 2 stages:
-- Stage 1 doesn't actually output any bytecode
-- instead it calculates offsets of labels
-- Stage 2 outputs the bytecode and parses
-- any non-constant expressions (i.e. expressions
-- that require labels
-- Table of ModR/M encodings
-- { Encoding:string, Mod:number, RM:number}
-- 16-bit addressing
ASM.ModRM16 = {
["BX SI"] = {0,0},
["BX DI"] = {0,1},
["BP SI"] = {0,2},
["BP DI"] = {0,3},
["SI"] = {0,4},
["DI"] = {0,5},
["D16"] = {0,6},
["BX"] = {0,7},
["BX SI D8"] = {1,0},
["BX DI D8"] = {1,1},
["BP SI D8"] = {1,2},
["BP DI D8"] = {1,3},
["SI D8"] = {1,4},
["DI D8"] = {1,5},
["BP D8"] = {1,6},
["BX D8"] = {1,7},
["BX SI D16"] = {2,0},
["BX DI D16"] = {2,1},
["BP SI D16"] = {2,2},
["BP DI D16"] = {2,3},
["SI D16"] = {2,4},
["DI D16"] = {2,5},
["BP D16"] = {2,6},
["BX D16"] = {2,7} }
-- 32/64-bit addressing
ASM.ModRM32 = {
["AX"] = {0,0},
["CX"] = {0,1},
["DX"] = {0,2},
["BX"] = {0,3},
["SIB"] = {0,4},
["EIP D32"] = {0,5},
["RIP D32"] = {0,5},
["SI"] = {0,6},
["DI"] = {0,7},
["AX D8"] = {1,0},
["CX D8"] = {1,1},
["DX D8"] = {1,2},
["BX D8"] = {1,3},
["SIB D8"] = {1,4},
["BP D8"] = {1,5},
["SI D8"] = {1,6},
["DI D8"] = {1,7},
["AX D32"] = {2,0},
["CX D32"] = {2,1},
["DX D32"] = {2,2},
["BX D32"] = {2,3},
["SIB D32"] = {2,4},
["BP D32"] = {2,5},
["SI D32"] = {2,6},
["DI D32"] = {2,7} }
-- Since all registers can be represented above,
-- only 1 name has been used. This maps registers
-- with the same index to the 16-bit name
ASM.INDREG = {
["EAX"] = "AX", ["EBX"] = "BX", ["ECX"] = "CX", ["EDX"] = "DX",
["EBP"] = "BP", ["ESI"] = "SI", ["EDI"] = "DI", ["ESP"] = "SP",
["AL"] = "AX", ["BL"] = "BX", ["CL"] = "CX", ["DL"] = "DX",
["AH"] = "SP", ["BH"] = "DI", ["CH"] = "BP", ["DH"] = "SI" }
-- Returns mod and r/m for a certain encoding
function ASM:GetModRM(base,index,dispSz,addrSz)
local str = ""
if base ~= nil then
str = str .. base:upper()
end
if index ~= nil then
if base ~= nil then
str = str .. " "
end
str = str .. index:upper()
end
if dispSz ~= nil and dispSz ~= 0 then
if base ~= nil or index ~= nil then
str = str .. " "
end
str = str .. "D" .. tostring(dispSz)
end
local modrm
if addrSz == 16 then
modrm = self.ModRM16[str]
else
modrm = self.ModRM32[str]
end
if not modrm then
modrm = self:GetModRM(index,base,dispSz,addrSz)
end
if modrm ~= nil then
return table.unpack(modrm)
end
end
function SplitString(str,delim)
local ret = {}
local delim = delim or " "
local tmp = ""
for i=1, #str do
local ch = string.sub(str,i,i)
if not string.find(delim,ch) then
tmp = tmp .. ch
else
table.insert(ret,tmp)
tmp = ""
end
end
if tmp ~= "" then
table.insert(ret,tmp)
end
if #ret < 1 then
return nil
else
return ret
end
end
function ASM:GetLabel(ident)
return self.Labels[ident]
end
function ASM:SetLabel(ident, val)
print("Label " .. ident .. " equals: " .. val)
self.Labels[ident] = val
end
function ASM:EncodeModRM(mod,reg,rm)
mod = bit32.band(bit32.lshift(mod,6),0xC0)
reg = bit32.band(bit32.lshift(reg,3),0x38)
rm = bit32.band(rm,0x07)
return bit32.band(bit32.bor(mod,reg,rm),0xFF)
end
function ASM:EncodeSIB(scale,index,base,mod)
-- Adjust parameters to be correct
local needDisp
if not index then
index = self.REG_LOOKUP["SP"]
end
if not base then
if mod ~= 0 then
-- Invalid EA
error("I Quit!")
end
base = self.REG_LOOKUP["BP"]
needDisp = true
end
-- We need to fix scale
if scale == 1 then
scale = 0
elseif scale == 2 then
scale = 1
elseif scale == 4 then
scale = 2
elseif scale == 8 then
scale = 3
else
error("Wrong scale")
end
scale = bit32.band(bit32.lshift(scale,6),0xC0)
index = bit32.band(bit32.lshift(index,3),0x38)
base = bit32.band(base,0x07)
return bit32.band(bit32.bor(scale,index,base),0xFF), needDisp
end
-- Possible returns:
-- .Scale = scale of index register
-- .Base = base register
-- .Disp = displacement
-- .DispSz = displacement size
-- .Index = index register
-- .Segment = segment override
-- Format:
-- [segment : index*scale + base + disp]
function ASM:EvalEA(toks)
local pos = toks[1].Pos
local ea = {}
self.Tokens = toks
self.CurTok = 1
if self:MatchToken(self.TOKEN.SIZE) then
ea.DispSz = self.TokenData
end
local ev, hint = self:Eval()
if self:MatchToken(self.TOKEN.COLON) then
if not is_sreg(ev[1].Type) or #ev > 1 then
self:Error(25,pos.File,pos.Line)
end
if self:MatchToken(self.TOKEN.SIZE) then
ea.DispSz = self.TokenData
end
ev, hint = self:Eval()
end
for _,e in pairs(ev) do
-- Is it a register?
if e.Type == 0 then
break
end
if e.Type < ASM.EXPR.REGEND then
if e.Val == 1 then
-- It could be a base register
if ea.Base then
-- Seems we already have a base
-- Throw this to index
if ea.Ind then
self:Error(24, pos.File, pos.Line)
end
ea.Ind = e.Data
ea.Scale = e.Val
end
ea.Base = e.Data
else
-- Must be index
if ea.Ind then
self:Error(24, pos.File, pos.Line)
end
ea.Ind = e.Data
ea.Scale = e.Val
end
else
if e.Type == self.EXPR.SIMPLE then
if ea.Disp then
self:Error(24, pos.File, pos.Line)
end
ea.Disp = e.Val
end
end
end
return ea
end
-- Returns nBytes, modrm, sib, dispSz, disp, addrSz
function ASM:ProcessEA(toks, rfield)
-- First evaluate the effective address
-- We do this here instead of the parser
-- in case it has a label
local pos, ea, reg
if toks[1] ~= nil then
-- It's a table, assume its an EA
pos = toks[1].Pos
ea = self:EvalEA(toks)
elseif toks.Type ~= nil then
-- It's a single token, assume
pos = toks.Pos
reg = toks.Data
else
-- Hmm shouldn't be here
error()
end
if not tonumber(rfield) then
rfield = self.REG_LOOKUP[rfield]
if not rfield then
error("Wut")
end
end
if ea.Scale == 0 then
ea.Index = nil
end
if not ea.DispSz then
ea.DispSz = 0
ea.Disp = 0
end
if not ea.Base and not ea.Ind and not ea.Scale and not ea.Disp then
error("Error parsing ea")
end
if reg ~= nil then
-- Register
local regType = self.REG_TYPE[reg]
local addrSz
if regType == "reg8" or regType == "reg16" then
addrSz = 16
elseif regType == "reg32" then
addrSz = 32
else
addrSz = 64
end
return 1, self:EncodeModRM(3, rfield, self.REG_LOOKUP[reg]), nil, nil, nil, addrSz
end
if not ea.Base and not ea.Ind and not ea.Scale then
-- Pure offset
if self.BitSize == 64 then
if ea.DispSz == 16 then
-- We cannot address 16 bit displacements
-- in 64-bit addressing
self.Error(24, pos.File,pos.Line)
end
end
if self.BitSize == 64 then
-- 64-bit addressing
if self.AddrType == "off" then
-- Offset addressing, 32-bit displacement isn't available in
-- modr/m alone in long mode, encode ModRM: SIB and SIB: disp32
return 2, self:EncodeModRM(0, rfield, 4), self:EncodeModRM(0, 4, 5), 4, disp, 64
else
-- Relative addressing, encode EIP/RIP + disp
return 1, self:EncodeModRM(0, rfield, 5), nil, 4, ea.Disp, 64
end
else
-- 32/16 bit addressing
if ea.DispSz == 32 then
-- If more than 16-bits, encode disp32
return 1, self:EncodeModRM(0, rfield, 5), nil, 4, ea.Disp, 32
elseif ea.DispSz == 16 then
-- Less than 16-bits, encode default address size
if self.BitSize == 64 or self.BitSize == 32 then
return 1, self:EncodeModRM(0, rfield, 6), nil, 4, ea.Disp, 32
else
return 1, self:EncodeModRM(0, rfield, 6), nil, 4, ea.Disp, 16
end
end
end
else
local addrSz = 16
if ea.DispSz == 32 or ea.Disp > 65535 then
addrSz = 32
end
-- Size optimizations:
-- [eax*2] and no disp -> eax*1 + eax
if ea.Scale == 2 and not ea.Base and ea.DispSz == 0 then
ea.Scale = 1
ea.Base = ea.Ind
end
if not ea.Scale then
-- We can assume we won't need an SIB byte in normal conditions
local mod, rm = self:GetModRM(ea.Base, ea.Ind, ea.DispSz, addrSz)
return 1, self:EncodeModRM(mod, rfield, rm), ea.DispSz, ea.Disp
else
-- Encode the correct SIB modrm
-- Special optimization for no base
-- SIB with no base requires a 32-bit displacement
local mod, rm
if ea.Base then
mod, rm = self:GetModRM("SIB", nil, ea.DispSz, 32)
else
mod, rm = self:GetModRM("SIB", nil, nil, 32)
end
local modrm = self:EncodeModRM(mod, rfield, rm)
-- We absolutely need an SIB byte
local index = self.REG_LOOKUP[ea.Ind]
local base = self.REG_LOOKUP[ea.Base]
local sib, needDisp = self:EncodeSIB(ea.Scale, index, base, mod)
if needDisp then
if not ea.Disp then
ea.Disp = 0
end
ea.DispSz = 32
end
return 2, modrm, sib, ea.DispSz/8, ea.Disp
end
end
return 0
end
local _rmtab = {}
for i=0,7 do
_rmtab["/" .. tostring(i)] = i
end
function ASM:SizeInstx(code)
local Size = 0
local Encoding = SplitString(code.Bytecode)
local function emitByte(n)
if not n then
Size = Size + 1
else
Size = Size + n
end
end
for _,o in pairs(Encoding) do
if o == "o16" then
if self.BitSize ~= 16 then
emitByte()
end
elseif o == "o32" then
if self.BitSize == 16 then
emitByte()
end
elseif o == "o64" then
emitByte()
elseif o == "/r" then
-- Parse memory
local size, modrm, sib, dSize, disp
if OpEnc[curOp] == 'r' then
local reg = getOp().Data
size, modrm, sib, dSize, disp = self:ProcessEA(getOp().Data, reg)
elseif OpEnc[curOp] == 'm' then
size, modrm, sib, dSize, disp = self:ProcessEA(getOp().Data, getOp().Data())
end
if dSize then size = size + dSize end
emitByte(size)
elseif _rmtab[o] then
-- Parse memory
local rfield = string.sub(o,2,2)
rfield = tonumber(rfield)
local size, modrm, sib, dSize, disp = self:ProcessEA(getOp().Data, rfield)
if dSize then size = size + dSize end
emitByte(size)
elseif (o == "ib") or (o == "iw") or (o == "id") then
if o == "ib" then
emitByte()
elseif o == "iw" then
emitByte(2)
elseif o == "id" then
emitByte(4)
end
elseif (o == "db") or (o == "dw") or (o == "dd") then
if o == "db" then
emitByte()
elseif o == "dw" then
emitByte(2)
elseif o == "dd" then
emitByte(4)
end
elseif (o == "rb") or (o == "rw") or (o == "rd") then
elseif tonumber(o) then
emitByte()
end
end
return Size
end
-- Returns byte table
function ASM:EncodeInstx(code)
local OpEnc = {}
local Encoding
-- Split the string into characters
local opEncode = code.OpEncode
for i=1, code.nOperands do
table.insert(OpEnc,string.sub(opEncode,i,i))
opEncode = string.sub(opEncode,i)
end
if #OpEnc ~= code.nOperands then
-- Opcode table most likely corrupt
-- or incorrect
self:Error(7,nil,nil,2)
end
Encoding = SplitString(code.Bytecode)
local Bytecode = {}
local curOp = 1
local Ops = code.Operands
-- Here we remove Operands that map with '-' i.e.
-- operands that aren't encoded
for i,o in pairs(OpEnc) do
if o == '-' then
table.remove(Ops,i)
table.remove(OpEnc,i)
end
end
local emitWord
local emitDword
-- These functions assume little endian!
local function emitByte(b, sz)
if not b then return end
if sz == 2 then
emitWord(b)
return
elseif sz == 4 then
emitDword(b)
return
end
table.insert(Bytecode,bit32.band(b,0xFF))
end
emitWord = function(w)
emitByte(bit32.band(w,0xFF))
emitByte(bit32.band(bit32.rshift(w,8),0xFF))
end
emitDword = function(dw)
emitWord(bit32.band(dw,0xFFFF))
emitWord(bit32.band(bit32.rshift(dw,16),0xFFFF))
end
local function getOp()
r = Ops[curOp]
curOp = curOp + 1
return r
end
local function expectOpType(t)
if Ops[curOp].Type ~= t then
-- Incorrect operand type
-- We should never end up here since operand type handling
-- is done during parsing
self:Error(7, code.Pos.File, code.Pos.Line, 3)
end
end
for _,o in pairs(Encoding) do
if o == "o16" then
if self.BitSize ~= 16 then
-- Emit operand size prefix
-- when BITS is not 16
emitByte(0x66)
end
elseif o == "o32" then
if self.BitSize == 16 then
-- Emit operand size prefix
-- only when BITS is 16
emitByte(0x66)
end
elseif o == "/r" then
-- ModR/M byte in which both r/m and reg fields are used
local size, modrm, sib, dSize, disp
if OpEnc[curOp] == 'r' then
local reg = getOp().Data
size, modrm, sib, dSize, disp = self:ProcessEA(getOp().Data, reg)
elseif OpEnc[curOp] == 'm' then
size, modrm, sib, dSize, disp = self:ProcessEA(getOp().Data, getOp().Data())
end
emitByte(modrm)
if sib then emitByte(sib) end
if dSize > 0 then emitByte(disp,dSize) end
elseif _rmtab[o] then
-- ModR/M byte in which only mod and r/m fields are used
-- and the reg field indicates an extension to the opcode
local rfield = string.sub(o,2,2)
rfield = tonumber(rfield)
local size, modrm, sib, dSize, disp = self:ProcessEA(getOp().Data, rfield)
emitByte(modrm)
if sib then emitByte(sib) end
if disp then emitByte(disp,dSize) end
elseif (o == "ib") or (o == "iw") or (o == "id") then
-- Immediate operand
local val = self:Eval(getOp().Data)
val = reloc_value(val)
if o == "ib" then
emitByte(val)
elseif o == "iw" then
emitWord(val)
elseif o == "id" then
emitDword(val)
end
elseif (o == "db") or (o == "dw") or (o == "dd") then
-- Displacement value
local val = self:Eval(getOp().Data)
val = reloc_value(val)
if o == "db" then
emitByte(val)
elseif o == "dw" then
emitWord(val)
elseif o == "dd" then
emitDword(val)
end
elseif (o == "rb") or (o == "rw") or (o == "rd") then
-- Register value added to previous byte
local regInd = self.REG_LOOKUP[getOp().Data]
Bytecode[#Bytecode] = Bytecode[#Bytecode] + regInd
elseif tonumber(o,16) then
emitByte(tonumber(o,16))
else
self:Error(7,nil,nil,4)
end
end
printTable(Bytecode)
return #Bytecode, Bytecode
end
function ASM:Encode()
-- Phase 1 calculate offset and set labels
local offset = 0
for _,o in pairs(self.CodeList) do
if o.Type == self.OPTYPE.INSTX then
offset = offset + self:EncodeInstx(o)
--offset = offset + self:SizeInstx(o)
elseif o.Type == self.OPTYPE.DEFINE then
-- db, dw, dd, dq
elseif o.Type == self.OPTYPE.LABEL then
-- Set label to offset
self:SetLabel(o.Data,offset)
end
end
-- Phase 2 actually encode
local output = {}
for _,o in pairs(self.CodeList) do
if o.Type == self.OPTYPE.INSTX then
local _, bytecode = self:EncodeInstx(o)
for _,v in pairs(bytecode) do
table.insert(output,v)
end
end
end
-- output bytecode
print("Output:")
printTable(output)
local outfile = self.Output.Open(self.OutFname)
self.Output.Write(outfile,output)
self.Output.Close(outfile)
end | gpl-3.0 |
jshackley/darkstar | scripts/zones/Norg/npcs/Vuliaie.lua | 19 | 1257 | -----------------------------------
-- Area: Norg
-- NPC: Vuliaie
-- Type: Tenshodo Merchant
-- @pos -24.259 0.891 -19.556 252
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/keyitems");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then
if (player:sendGuild(60424,9,23,7)) then
player:showText(npc, VULIAIE_SHOP_DIALOG);
end
else
-- player:startEvent(0x0096);
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 |
jshackley/darkstar | scripts/zones/Quicksand_Caves/npcs/_5s8.lua | 17 | 1276 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -334 0 659 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(-326);
local difZ = player:getZPos()-(660);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if (Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
bsnsk/vroom-hammerspoon | Spoons/HSearch.spoon/hs_datamuse.lua | 4 | 3260 | local obj={}
obj.__index = obj
obj.name = "thesaurusDM"
obj.version = "1.0"
obj.author = "ashfinal <ashfinal@gmail.com>"
-- Internal function used to find our location, so we know where to load files from
local function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
obj.spoonPath = script_path()
-- Define the source's overview. A unique `keyword` key should exist, so this source can be found.
obj.overview = {text="Type s ⇥ to request English Thesaurus.", image=hs.image.imageFromPath(obj.spoonPath .. "/resources/thesaurus.png"), keyword="s"}
-- Define the notice when a long-time request is being executed. It could be `nil`.
obj.notice = nil
local function dmTips()
local chooser_data = {
{text="Datamuse Thesaurus", subText="Type something to get more words like it …", image=hs.image.imageFromPath(obj.spoonPath .. "/resources/thesaurus.png")}
}
return chooser_data
end
-- Define the function which will be called when the `keyword` triggers a new source. The returned value is a table. Read more: http://www.hammerspoon.org/docs/hs.chooser.html#choices
obj.init_func = dmTips
-- Insert a friendly tip at the head so users know what to do next.
-- As this source highly relys on queryChangedCallback, we'd better tip users in callback instead of here
obj.description = nil
-- As the user is typing, the callback function will be called for every keypress. The returned value is a table.
local function thesaurusRequest(querystr)
local datamuse_baseurl = 'http://api.datamuse.com'
if string.len(querystr) > 0 then
local encoded_query = hs.http.encodeForQuery(querystr)
local query_url = datamuse_baseurl .. '/words?ml=' .. encoded_query .. '&max=20'
hs.http.asyncGet(query_url, nil, function(status, data)
if status == 200 then
if pcall(function() hs.json.decode(data) end) then
local decoded_data = hs.json.decode(data)
if #decoded_data > 0 then
local chooser_data = hs.fnutils.imap(decoded_data, function(item)
return {text = item.word, image=hs.image.imageFromPath(obj.spoonPath .. "/resources/thesaurus.png"), output="keystrokes", arg=item.word}
end)
-- Because we don't know when asyncGet will return data, we have to refresh hs.chooser choices in this callback.
if spoon.HSearch then
-- Make sure HSearch spoon is running now
spoon.HSearch.chooser:choices(chooser_data)
spoon.HSearch.chooser:refreshChoicesCallback()
end
end
end
end
end)
else
local chooser_data = {
{text="Datamuse Thesaurus", subText="Type something to get more words like it …", image=hs.image.imageFromPath(obj.spoonPath .. "/resources/thesaurus.png")}
}
if spoon.HSearch then
spoon.HSearch.chooser:choices(chooser_data)
spoon.HSearch.chooser:refreshChoicesCallback()
end
end
end
obj.callback = thesaurusRequest
return obj
| mit |
jshackley/darkstar | scripts/globals/abilities/fight.lua | 18 | 1033 | -----------------------------------
-- Ability: Fight
-- Commands your pet to attack the target.
-- Obtained: Beastmaster Level 1
-- Recast Time: 10 seconds
-- Duration: N/A
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getPet() == nil) then
return MSGBASIC_REQUIRES_A_PET,0;
else
if (target:getID() == player:getPet():getID() or (target:getMaster() ~= nil and target:getMaster():isPC())) then
return MSGBASIC_CANNOT_ATTACK_TARGET,0;
else
return 0,0;
end
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local pet = player:getPet();
if (player:checkDistance(pet) <= 25) then
player:petAttack(target);
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/The_Shrouded_Maw/npcs/MementoCircle.lua | 17 | 1427 | -----------------------------------
-- Area: The_Shrouded_Maw
-- NPC: MementoCircle
-----------------------------------
package.loaded["scripts/zones/The_Shrouded_Maw/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/The_Shrouded_Maw/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;
else
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 |
SpRoXx/GTW-RPG | [resources]/GTWvehicleshop/vehicle_c.lua | 2 | 19419 | --[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.404rq.com/bug-reports/
Suggestions: http://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
--[[ Create global vehicle data storage for clients ]]--
currentVehID = nil
veh_data_list = {{ }}
row,col = nil,nil
--[[ Create vehicle management GUI ]]--
x,y = guiGetScreenSize()
window = guiCreateWindow((x-600)/2, (y-400)/2, 600, 400, "Vehicle manager", false)
btn_show = guiCreateButton(10, 350, 90, 30, "Show", false, window)
btn_hide = guiCreateButton(100, 350, 90, 30, "Hide", false, window)
btn_lock = guiCreateButton(200, 350, 90, 30, "Lock", false, window)
btn_engine = guiCreateButton(290, 350, 90, 30, "Engine", false, window)
btn_recover = guiCreateButton(380, 350, 90, 30, "Recover", false, window)
btn_sell = guiCreateButton(470, 350, 90, 30, "Sell", false, window)
guiSetVisible( window, false )
--[[ Create the vehicle grid list ]]--
vehicle_list = guiCreateGridList( 10, 23, 580, 325, false, window )
col1 = guiGridListAddColumn( vehicle_list, "Name", 0.25 )
col2 = guiGridListAddColumn( vehicle_list, "Health", 0.1 )
col3 = guiGridListAddColumn( vehicle_list, "Fuel", 0.1 )
col4 = guiGridListAddColumn( vehicle_list, "Locked", 0.1 )
col5 = guiGridListAddColumn( vehicle_list, "Engine", 0.1 )
col6 = guiGridListAddColumn( vehicle_list, "Location", 0.3 )
guiGridListSetSelectionMode( vehicle_list, 0 )
guiGridListSetSortingEnabled(vehicle_list, false)
--[[ Apply GTWgui style ]]--
exports.GTWgui:setDefaultFont(btn_show, 10)
exports.GTWgui:setDefaultFont(btn_hide, 10)
exports.GTWgui:setDefaultFont(btn_lock, 10)
exports.GTWgui:setDefaultFont(btn_engine, 10)
exports.GTWgui:setDefaultFont(btn_recover, 10)
exports.GTWgui:setDefaultFont(btn_sell, 10)
exports.GTWgui:setDefaultFont(vehicle_list, 10)
--[[ Create vehicle trunk GUI ]]--
window_trunk = guiCreateWindow((x-600)/2, (y-400)/2, 600, 400, "Vehicle inventory", false)
btn_withdraw = guiCreateButton(275, 73, 50, 40, "<", false, window_trunk)
btn_deposit = guiCreateButton(275, 115, 50, 40, ">", false, window_trunk)
btn_withdraw_all = guiCreateButton(275, 163, 50, 40, "<<", false, window_trunk)
btn_deposit_all = guiCreateButton(275, 205, 50, 40, ">>", false, window_trunk)
btn_close = guiCreateButton(500, 350, 90, 30, "Close", false, window_trunk)
guiSetVisible( window_trunk, false )
--[[ Create the trunk grid list ]]--
label_vehicle = guiCreateLabel( 10, 23, 250, 20, "Vehicle trunk", false, window_trunk )
label_player = guiCreateLabel( 302, 23, 250, 20, "Your pocket", false, window_trunk )
inventory_list = guiCreateGridList( 10, 43, 263, 305, false, window_trunk )
player_items_list = guiCreateGridList( 327, 43, 263, 305, false, window_trunk )
col7 = guiGridListAddColumn( inventory_list, "Item", 0.61 )
col8 = guiGridListAddColumn( inventory_list, "Amount", 0.31 )
col9 = guiGridListAddColumn( player_items_list, "Item", 0.61 )
col10 = guiGridListAddColumn( player_items_list, "Amount", 0.31 )
guiGridListSetSelectionMode( inventory_list, 0 )
guiGridListSetSelectionMode( player_items_list, 0 )
--[[ Apply GTWgui style (inventory GUI )]]--
exports.GTWgui:setDefaultFont(label_vehicle, 10)
exports.GTWgui:setDefaultFont(label_player, 10)
exports.GTWgui:setDefaultFont(inventory_list, 10)
exports.GTWgui:setDefaultFont(player_items_list, 10)
exports.GTWgui:setDefaultFont(btn_withdraw, 16)
exports.GTWgui:setDefaultFont(btn_deposit, 16)
exports.GTWgui:setDefaultFont(btn_withdraw_all, 16)
exports.GTWgui:setDefaultFont(btn_deposit_all, 16)
exports.GTWgui:setDefaultFont(btn_close, 10)
--[[ Create a function to handle toggling of vehicle GUI ]]--
function toggleGUI( source )
-- Show the vehicle GUI
if not guiGetVisible( window ) then
showCursor( true )
guiSetVisible( window, true )
guiSetInputEnabled( true )
triggerServerEvent( "GTWvehicleshop.onListVehicles", localPlayer )
else
showCursor( false )
guiSetVisible( window, false )
guiSetInputEnabled( false )
end
end
addCommandHandler( "vehicles", toggleGUI )
bindKey( "F2", "down", "vehicles" )
--[[ Create a function to handle toggling of vehicle inventory GUI ]]--
function toggleInventoryGUI( plr )
-- Show the vehicle inventory GUI
if not guiGetVisible( window_trunk ) and isElement(getElementData(localPlayer, "GTWvehicleshop.the_near_veh_trunk")) then
local browsing_player = getElementData(getElementData(
localPlayer, "GTWvehicleshop.the_near_veh_trunk"),
"GTWvehicleshop.the_near_player_trunk")
if getElementData(localPlayer, "GTWvehicleshop.the_near_veh_trunk") and
browsing_player and browsing_player == localPlayer then
showCursor( true )
guiSetVisible( window_trunk, true )
guiSetInputEnabled( true )
loadWeaponsToList()
else
if not browsing_player then return end
exports.GTWtopbar:dm(getPlayerName(browsing_player).." is currently browsing this trunk, please wait!", 255, 0, 0)
end
else
showCursor( false )
guiSetVisible( window_trunk, false )
guiSetInputEnabled( false )
if isElement(getElementData(localPlayer, "GTWvehicleshop.the_near_veh_trunk")) then
triggerServerEvent( "GTWvehicleshop.onCloseInventory", localPlayer )
end
end
end
addCommandHandler( "inventory", toggleInventoryGUI )
bindKey( "F9", "down", "inventory" )
function loadWeaponsToList()
if col7 and col8 and col9 and col10 then
local weapons = getPedWeapons(localPlayer)
guiGridListClear( player_items_list )
guiGridListClear( inventory_list )
for i,wep in pairs(getPedWeapons(localPlayer)) do
local row = guiGridListAddRow( player_items_list )
local slot = getSlotFromWeapon(wep)
if getPedTotalAmmo(localPlayer,slot) > 0 then
guiGridListSetItemText( player_items_list, row, col9, getWeaponNameFromID(wep), false, false )
guiGridListSetItemText( player_items_list, row, col10, getPedTotalAmmo(localPlayer,slot), false, false )
end
end
-- Load weapons from vehicle inventory
local veh_id = getElementData( getElementData(localPlayer, "GTWvehicleshop.the_near_veh_trunk"), "isOwnedVehicle")
if veh_id then triggerServerEvent( "GTWvehicleshop.onOpenInventory", localPlayer, veh_id ) end
end
end
function receiveVehicleData(data_table)
if col1 and col2 and col3 and col4 and col5 and col6 then
-- Clear and refresh
guiGridListClear( vehicle_list )
veh_data_list = data_table
-- Load vehicles to list
for id, veh in pairs(data_table) do
local row = guiGridListAddRow( vehicle_list )
guiGridListSetItemText( vehicle_list, row, col1, getVehicleNameFromModel(data_table[id][2]), false, false )
if currentVehID == tonumber(data_table[id][1]) then
guiGridListSetItemColor( vehicle_list, row, col1, 100, 100, 255 )
end
guiGridListSetItemText( vehicle_list, row, col2, data_table[id][3], false, false )
if data_table[id][3] > 70 then
guiGridListSetItemColor( vehicle_list, row, col2, 0, 255, 0 )
elseif data_table[id][3] > 30 then
guiGridListSetItemColor( vehicle_list, row, col2, 255, 200, 0 )
else
guiGridListSetItemColor( vehicle_list, row, col2, 255, 0, 0 )
end
guiGridListSetItemText( vehicle_list, row, col3, data_table[id][4], false, false )
if data_table[id][4] > 80 then
guiGridListSetItemColor( vehicle_list, row, col3, 0, 255, 0 )
elseif data_table[id][4] > 20 then
guiGridListSetItemColor( vehicle_list, row, col3, 255, 200, 0 )
else
guiGridListSetItemColor( vehicle_list, row, col3, 255, 0, 0 )
end
local locked = "Open"
if data_table[id][5] == 1 then
locked = "Yes"
end
guiGridListSetItemText( vehicle_list, row, col4, locked, false, false )
if data_table[id][5] == 1 then
guiGridListSetItemColor( vehicle_list, row, col4, 0, 255, 0 )
else
guiGridListSetItemColor( vehicle_list, row, col4, 255, 200, 0 )
end
local engine = "Off"
if data_table[id][6] == 1 then
engine = "On"
end
guiGridListSetItemText( vehicle_list, row, col5, engine, false, false )
if data_table[id][6] == 1 then
guiGridListSetItemColor( vehicle_list, row, col5, 0, 255, 0 )
else
guiGridListSetItemColor( vehicle_list, row, col5, 255, 0, 0 )
end
local x,y,z, rx,ry,rz = unpack( fromJSON( data_table[id][7] ))
local location = getZoneName(x,y,z)
local city = getZoneName(x,y,z,true)
guiGridListSetItemText( vehicle_list, row, col6, location.." ("..city..")", false, false )
local px,py,pz = getElementPosition(localPlayer)
local dist = getDistanceBetweenPoints3D( x,y,z, px,py,pz )
if dist < 180 then
guiGridListSetItemColor( vehicle_list, row, col6, 0, 255, 0 )
else
guiGridListSetItemColor( vehicle_list, row, col6, 255, 200, 0 )
end
end
end
end
addEvent( "GTWvehicleshop.onReceivePlayerVehicleData", true )
addEventHandler( "GTWvehicleshop.onReceivePlayerVehicleData", root, receiveVehicleData )
function receiveInventoryItems(item)
if col7 and col8 then
-- Clear and refresh
guiGridListClear( inventory_list )
-- Load vehicles to list
local data_table = fromJSON(item)
for k, v in pairs(data_table) do
local row = guiGridListAddRow( inventory_list )
guiGridListSetItemText( inventory_list, row, col7, k, false, false )
guiGridListSetItemText( inventory_list, row, col8, v, false, false )
end
end
end
addEvent( "GTWvehicleshop.onReceiveInventoryItems", true )
addEventHandler( "GTWvehicleshop.onReceiveInventoryItems", root, receiveInventoryItems )
--[[ Toggle vehicle visibility on click ]]--
addEventHandler("onClientGUIClick",vehicle_list,
function()
row,col = guiGridListGetSelectedItem( vehicle_list )
if row and col and veh_data_list[row+1] then
currentVehID = veh_data_list[row+1][1]
for w=0, #veh_data_list do
guiGridListSetItemColor( vehicle_list, w, col1, 255, 255, 255 )
end
guiGridListSetItemColor( vehicle_list, row, col1, 100, 100, 255 )
guiGridListSetSelectedItem( vehicle_list, 0, 0)
end
end)
--[[ Close the inventory GUI ]]--
addEventHandler("onClientGUIClick",btn_close,
function()
toggleInventoryGUI(localPlayer)
end)
--[[ Options in the button menu ]]--
addEventHandler( "onClientGUIClick", root,
function ( )
--if not currentVehID then exports.GTWtopbar:dm("Please select a vehicle from the list!", 255, 0, 0) return end
if source == btn_show and currentVehID then
triggerServerEvent( "GTWvehicleshop.onShowVehicles", localPlayer, currentVehID )
end
if source == btn_hide and currentVehID then
triggerServerEvent( "GTWvehicleshop.onHideVehicles", localPlayer, currentVehID )
end
if source == btn_lock and currentVehID then
-- Update vehiclelist and lock status
if guiGridListGetItemText( vehicle_list, row, col4 ) == "Yes" then
triggerServerEvent( "GTWvehicleshop.onLockVehicle", localPlayer, currentVehID, 0 )
guiGridListSetItemText( vehicle_list, row, col4, "Open", false, false )
guiGridListSetItemColor( vehicle_list, row, col4, 255, 200, 0 )
else
triggerServerEvent( "GTWvehicleshop.onLockVehicle", localPlayer, currentVehID, 1 )
guiGridListSetItemText( vehicle_list, row, col4, "Yes", false, false )
guiGridListSetItemColor( vehicle_list, row, col4, 0, 255, 0 )
end
end
if source == btn_engine and currentVehID then
-- Update vehiclelist and engine status
if guiGridListGetItemText( vehicle_list, row, col5 ) == "On" then
triggerServerEvent( "GTWvehicleshop.onVehicleEngineToggle", localPlayer, currentVehID, 0 )
guiGridListSetItemText( vehicle_list, row, col5, "Off", false, false )
guiGridListSetItemColor( vehicle_list, row, col5, 255, 0, 0 )
else
triggerServerEvent( "GTWvehicleshop.onVehicleEngineToggle", localPlayer, currentVehID, 1 )
guiGridListSetItemText( vehicle_list, row, col5, "On", false, false )
guiGridListSetItemColor( vehicle_list, row, col5, 0, 255, 0 )
end
end
if source == btn_recover and currentVehID then
triggerServerEvent( "GTWvehicleshop.onVehicleRespawn", localPlayer, currentVehID )
end
if source == btn_sell and currentVehID then
triggerServerEvent( "GTWvehicleshop.onVehicleSell", localPlayer, currentVehID, veh_data_list[row+1][2] )
guiGridListRemoveRow( vehicle_list, row )
currentVehID = nil
end
-- Vehicle inventory
if source == btn_withdraw then
vehicle_shop_withdraw()
end
if source == btn_deposit then
vehicle_shop_deposit()
end
if source == btn_withdraw_all then
vehicle_shop_withdraw(true)
end
if source == btn_deposit_all then
vehicle_shop_deposit(true)
end
end)
--[[ Withdraw weapon from inventory ]]--
function vehicle_shop_withdraw(withdraw_all)
if not withdraw_all then withdraw_all = false end
local row_pil, col_pil = guiGridListGetSelectedItem( player_items_list )
local veh_id = getElementData( getElementData(localPlayer, "GTWvehicleshop.the_near_veh_trunk"), "isOwnedVehicle")
-- Validate operation
if row_pil == -1 or col_pil == -1 or not veh_id then return end
-- Get current values
local object = guiGridListGetItemText( player_items_list, row_pil, col9 )
local pocket = guiGridListGetItemText( player_items_list, row_pil, col10 )
-- Get current data
local slot = getSlotFromWeapon( getWeaponIDFromName( object ))
local ammo = getPedAmmoInClip(localPlayer, slot)
if withdraw_all then
ammo = tonumber(guiGridListGetItemText(player_items_list, row_pil, col10))
end
local is_empty = false
-- Justify values
if ammo > tonumber(guiGridListGetItemText(player_items_list, row_pil, col10)) then
ammo = tonumber(guiGridListGetItemText(player_items_list, row_pil, col10))
end
-- Send to database
triggerServerEvent( "GTWvehicleshop.onVehicleWeaponWithdraw", localPlayer, veh_id, object, ammo)
-- Manage lists add new item
local ex_row = isElementInList(inventory_list, object, col7)
if not ex_row then
local tmp_row = guiGridListAddRow( inventory_list )
guiGridListSetItemText( inventory_list, tmp_row, col7, object, false, false )
guiGridListSetItemText( inventory_list, tmp_row, col8, ammo, false, false )
else
guiGridListSetItemText( inventory_list, ex_row, col8, tonumber(guiGridListGetItemText(inventory_list, ex_row, col8)) + ammo, false, false )
end
guiGridListSetItemText( player_items_list, row_pil, col10, tonumber(guiGridListGetItemText(player_items_list, row_pil, col10)) - ammo, false, false )
-- Remove if empty
if guiGridListGetItemText(player_items_list, row_pil, col10) == "0" then
guiGridListRemoveRow( player_items_list, row_pil )
is_empty = true
end
-- Reload data
--loadWeaponsToList()
-- Clear selection if empty, otherwise reselect
if not is_empty then
guiGridListSetSelectedItem(player_items_list, row_pil, col_pil)
guiGridListSetSelectedItem(inventory_list, -1, -1)
else
guiGridListSetSelectedItem(player_items_list, -1, -1)
guiGridListSetSelectedItem(inventory_list, -1, -1)
end
-- Restore GUI style !Important if using GTWgui
setTimer(resetGTWguistyle, 1000, 1)
end
--[[ Deposit weapon from inventory ]]--
function vehicle_shop_deposit(deposit_all)
if not deposit_all then deposit_all = false end
local row_il, col_il = guiGridListGetSelectedItem( inventory_list )
local veh_id = getElementData( getElementData(localPlayer, "GTWvehicleshop.the_near_veh_trunk"), "isOwnedVehicle")
-- Validate operation
if row_il == -1 or col_il == -1 or not veh_id then return end
-- Get current values
local object = guiGridListGetItemText( inventory_list, row_il, col7 )
local trunk = guiGridListGetItemText( inventory_list, row_il, col8 )
-- Get current data
local ammo = getWeaponProperty(object, "std", "maximum_clip_ammo")
if deposit_all then
ammo = tonumber(guiGridListGetItemText(inventory_list, row_il, col8))
end
local is_empty = false
-- Justify values
if ammo > tonumber(guiGridListGetItemText(inventory_list, row_il, col8)) then
ammo = tonumber(guiGridListGetItemText(inventory_list, row_il, col8))
end
-- Send to database
triggerServerEvent( "GTWvehicleshop.onVehicleWeaponDeposit", localPlayer, veh_id, object, ammo)
-- Manage lists add new item
local ex_row = isElementInList(player_items_list, object, col9)
if not ex_row then
local tmp_row = guiGridListAddRow( player_items_list )
guiGridListSetItemText( player_items_list, tmp_row, col9, object, false, false )
guiGridListSetItemText( player_items_list, tmp_row, col10, ammo, false, false )
else
guiGridListSetItemText( player_items_list, ex_row, col10, tonumber(guiGridListGetItemText(player_items_list, ex_row, col10)) + ammo, false, false )
end
guiGridListSetItemText( inventory_list, row_il, col8, tonumber(guiGridListGetItemText(inventory_list, row_il, col8)) - ammo, false, false )
-- Remove if empty
if guiGridListGetItemText(inventory_list, row_il, col8) == "0" then
guiGridListRemoveRow( inventory_list, row_il )
is_empty = true
end
-- Reload data
--loadWeaponsToList()
-- Clear selection if empty, otherwise reselect
if not is_empty then
guiGridListSetSelectedItem(player_items_list, -1, -1)
guiGridListSetSelectedItem(inventory_list, row_il, col_il)
else
guiGridListSetSelectedItem(player_items_list, -1, -1)
guiGridListSetSelectedItem(inventory_list, -1, -1)
end
-- Restore GUI style !Important if using GTWgui
setTimer(resetGTWguistyle, 1000, 1)
--[[local row_il, col_il = guiGridListGetSelectedItem( inventory_list )
local veh_id = getElementData( getElementData(localPlayer, "GTWvehicleshop.the_near_veh_trunk"), "isOwnedVehicle")
if row_il == -1 or col_il == -1 or not veh_id then return end
triggerServerEvent( "GTWonVehicleWeaponDeposit", localPlayer, veh_id,
guiGridListGetItemText( inventory_list, row_il, col7 ), guiGridListGetItemText( inventory_list, row_il, col8 ))
local tmp_row = guiGridListAddRow( player_items_list )
guiGridListSetItemText( player_items_list, tmp_row, col9, guiGridListGetItemText( inventory_list, row_il, col7 ), false, false )
guiGridListSetItemText( player_items_list, tmp_row, col10, guiGridListGetItemText( inventory_list, row_il, col8 ), false, false )
guiGridListRemoveRow( inventory_list, row_il )
-- Clear selection
guiGridListSetSelectedItem(player_items_list, -1, -1)
guiGridListSetSelectedItem(inventory_list, -1, -1)]]--
end
function resetGTWguistyle()
-- Apply GUI style again !Important if using GTWgui
exports.GTWgui:setDefaultFont(inventory_list, 10)
exports.GTWgui:setDefaultFont(player_items_list, 10)
end
--[[ Find element in list ]]--
function isElementInList(g_list, text, col)
local items_count = guiGridListGetRowCount(g_list)
for r=0, items_count do
--outputChatBox("R: "..r..", C: "..col.." "..guiGridListGetItemText(g_list, r, col).." = "..text)
if guiGridListGetItemText(g_list, r, col) == text then return r end
end
return false
end
function getPedWeapons(ped)
local playerWeapons = {}
if ped and isElement(ped) and getElementType(ped) == "ped" or getElementType(ped) == "player" then
for i=2,9 do
local wep = getPedWeapon(ped,i)
if wep and wep ~= 0 then
table.insert(playerWeapons,wep)
end
end
else
return false
end
return playerWeapons
end
| bsd-2-clause |
BeyondTeam/TeleBeyond | plugins/arabic_lock.lua | 234 | 1405 | antiarabic = {}-- An empty table for solving multiple kicking problem
do
local function run(msg, matches)
if is_momod(msg) then -- Ignore mods,owner,admins
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_arabic'] then
if data[tostring(msg.to.id)]['settings']['lock_arabic'] == 'yes' then
if is_whitelisted(msg.from.id) then
return
end
if antiarabic[msg.from.id] == true then
return
end
if msg.to.type == 'chat' then
local receiver = get_receiver(msg)
local username = msg.from.username
local name = msg.from.first_name
if username and is_super_group(msg) then
send_large_msg(receiver , "Arabic/Persian is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked/msg deleted")
else
send_large_msg(receiver , "Arabic/Persian is not allowed here\nName: "..name.."["..msg.from.id.."]\nStatus: User kicked/msg deleted")
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (arabic was locked) ")
local chat_id = msg.to.id
local user_id = msg.from.id
kick_user(user_id, chat_id)
end
antiarabic[msg.from.id] = true
end
end
return
end
local function cron()
antiarabic = {} -- Clear antiarabic table
end
return {
patterns = {
"([\216-\219][\128-\191])"
},
run = run,
cron = cron
}
end
| agpl-3.0 |
wjaede/ardupilot | Tools/CHDK-Scripts/Cannon SX260/3DR_EAI_SX260.lua | 182 | 29665 |
--[[
KAP UAV Exposure Control Script v3.1
-- Released under GPL by waterwingz and wayback/peabody
http://chdk.wikia.com/wiki/KAP_%26_UAV_Exposure_Control_Script
3DR EAI 1.0 is a fork of KAP 3.1 with settings specific to Canon cameras triggered off the Pixhawk autopilot.
Changelog:
-Modified Tv, Av, and ISO settings for the Canon SX260
-Added an option to turn the GPS on and off
-Added control of GPS settings in Main Loop
-Changed USB OneShot mode to listen for 100ms command pulse from Pixhawk
@title 3DR EAI 1.0 - Lets Map!
@param i Shot Interval (sec)
@default i 2
@range i 2 120
@param s Total Shots (0=infinite)
@default s 0
@range s 0 10000
@param j Power off when done?
@default j 0
@range j 0 1
@param e Exposure Comp (stops)
@default e 6
@values e -2.0 -1.66 -1.33 -1.0 -0.66 -0.33 0.0 0.33 0.66 1.00 1.33 1.66 2.00
@param d Start Delay Time (sec)
@default d 0
@range d 0 10000
@param y Tv Min (sec)
@default y 5
@values y None 1/60 1/100 1/200 1/400 1/640
@param t Target Tv (sec)
@default t 7
@values t 1/100 1/200 1/400 1/640 1/800 1/1000 1/1250 1/1600 1/2000
@param x Tv Max (sec)
@default x 4
@values x 1/1000 1/1250 1/1600 1/2000 1/3200 1/5000 1/10000
@param f Av Low(f-stop)
@default f 6
@values f 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param a Av Target (f-stop)
@default a 7
@values a 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param m Av Max (f-stop)
@default m 13
@values m 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param p ISO Min
@default p 0
@values p 80 100 200 400 800 1250 1600
@param q ISO Max1
@default q 1
@values q 100 200 400 800 1250 1600
@param r ISO Max2
@default r 3
@values r 100 200 400 800 1250 1600
@param n Allow use of ND filter?
@default n 0
@values n No Yes
@param z Zoom position
@default z 0
@values z Off 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
@param c Focus @ Infinity Mode
@default c 3
@values c None @Shot AFL MF
@param v Video Interleave (shots)
@default v 0
@values v Off 1 5 10 25 50 100
@param w Video Duration (sec)
@default w 10
@range w 5 300
@param u Trigger Type
@default u 2
@values u Interval Cont. USB PWM
@param g GPS On
@default g 1
@range g 0 1
@param b Backlight Off?
@default b 1
@range b 0 1
@param l Logging
@default l 3
@values l Off Screen SDCard Both
--]]
props=require("propcase")
capmode=require("capmode")
-- convert user parameter to usable variable names and values
tv_table = { -320, 576, 640, 736, 832, 896, 928, 960, 992, 1024, 1056, 1113, 1180, 1276}
tv96target = tv_table[t+3]
tv96max = tv_table[x+8]
tv96min = tv_table[y+1]
sv_table = { 381, 411, 507, 603, 699, 761, 795 }
sv96min = sv_table[p+1]
sv96max1 = sv_table[q+2]
sv96max2 = sv_table[r+2]
av_table = { 171, 192, 218, 265, 285, 322, 347, 384, 417, 446, 477, 510, 543, 576 }
av96target = av_table[a+1]
av96minimum = av_table[f+1]
av96max = av_table[m+1]
ec96adjust = (e - 6)*32
video_table = { 0, 1, 5, 10, 25, 50, 100 }
video_mode = video_table[v+1]
video_duration = w
interval = i*1000
max_shots = s
poff_if_done = j
start_delay = d
backlight = b
log_mode= l
focus_mode = c
usb_mode = u
gps = g
if ( z==0 ) then zoom_setpoint = nil else zoom_setpoint = (z-1)*10 end
-- initial configuration values
nd96offset=3*96 -- ND filter's number of equivalent f-stops (f * 96)
infx = 50000 -- focus lock distance in mm (approximately 55 yards)
shot_count = 0 -- shot counter
blite_timer = 300 -- backlight off delay in 100mSec increments
old_console_timeout = get_config_value( 297 )
shot_request = false -- pwm mode flag to request a shot be taken
-- check camera Av configuration ( variable aperture and/or ND filter )
if n==0 then -- use of nd filter allowed?
if get_nd_present()==1 then -- check for ND filter only
Av_mode = 0 -- 0 = ND disabled and no iris available
else
Av_mode = 1 -- 1 = ND disabled and iris available
end
else
Av_mode = get_nd_present()+1 -- 1 = iris only , 2=ND filter only, 3= both ND & iris
end
function printf(...)
if ( log_mode == 0) then return end
local str=string.format(...)
if (( log_mode == 1) or (log_mode == 3)) then print(str) end
if ( log_mode > 1 ) then
local logname="A/3DR_EAI_log.log"
log=io.open(logname,"a")
log:write(os.date("%Y%b%d %X ")..string.format(...),"\n")
log:close()
end
end
tv_ref = { -- note : tv_ref values set 1/2 way between shutter speed values
-608, -560, -528, -496, -464, -432, -400, -368, -336, -304,
-272, -240, -208, -176, -144, -112, -80, -48, -16, 16,
48, 80, 112, 144, 176, 208, 240, 272, 304, 336,
368, 400, 432, 464, 496, 528, 560, 592, 624, 656,
688, 720, 752, 784, 816, 848, 880, 912, 944, 976,
1008, 1040, 1072, 1096, 1129, 1169, 1192, 1225, 1265, 1376 }
tv_str = {
">64",
"64", "50", "40", "32", "25", "20", "16", "12", "10", "8.0",
"6.0", "5.0", "4.0", "3.2", "2.5", "2.0", "1.6", "1.3", "1.0", "0.8",
"0.6", "0.5", "0.4", "0.3", "1/4", "1/5", "1/6", "1/8", "1/10", "1/13",
"1/15", "1/20", "1/25", "1/30", "1/40", "1/50", "1/60", "1/80", "1/100", "1/125",
"1/160", "1/200", "1/250", "1/320", "1/400", "1/500", "1/640", "1/800", "1/1000","1/1250",
"1/1600","1/2000","1/2500","1/3200","1/4000","1/5000","1/6400","1/8000","1/10000","hi" }
function print_tv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #tv_ref) and (val > tv_ref[i]) do i=i+1 end
return tv_str[i]
end
av_ref = { 160, 176, 208, 243, 275, 304, 336, 368, 400, 432, 464, 480, 496, 512, 544, 592, 624, 656, 688, 720, 752, 784 }
av_str = {"n/a","1.8", "2.0","2.2","2.6","2.8","3.2","3.5","4.0","4.5","5.0","5.6","5.9","6.3","7.1","8.0","9.0","10.0","11.0","13.0","14.0","16.0","hi"}
function print_av(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #av_ref) and (val > av_ref[i]) do i=i+1 end
return av_str[i]
end
sv_ref = { 370, 397, 424, 456, 492, 523, 555, 588, 619, 651, 684, 731, 779, 843, 907 }
sv_str = {"n/a","80","100","120","160","200","250","320","400","500","640","800","1250","1600","3200","hi"}
function print_sv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #sv_ref) and (val > sv_ref[i]) do i=i+1 end
return sv_str[i]
end
function pline(message, line) -- print line function
fg = 258 bg=259
end
-- switch between shooting and playback modes
function switch_mode( m )
if ( m == 1 ) then
if ( get_mode() == false ) then
set_record(1) -- switch to shooting mode
while ( get_mode() == false ) do
sleep(100)
end
sleep(1000)
end
else
if ( get_mode() == true ) then
set_record(0) -- switch to playback mode
while ( get_mode() == true ) do
sleep(100)
end
sleep(1000)
end
end
end
-- focus lock and unlock
function lock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if ( focus_mode == 2 ) then -- method 1 : set_aflock() command enables MF
if (chdk_version==120) then
set_aflock(1)
set_prop(props.AF_LOCK,1)
else
set_aflock(1)
end
if (get_prop(props.AF_LOCK) == 1) then printf(" AFL enabled") else printf(" AFL failed ***") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOn") == -1 then
call_event_proc("PT_MFOn")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOn") == -1 then
call_event_proc("MFOn")
end
end
if (get_prop(props.FOCUS_MODE) == 0 ) then -- MF not set - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(1) == 0 ) then set_aflock(1) end -- as a fall back, try setting AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 1) then printf(" MF enabled") else printf(" MF enable failed ***") end
end
sleep(1000)
set_focus(infx)
sleep(1000)
end
end
function unlock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if (focus_mode == 2 ) then -- method 1 : AFL
if (chdk_version==120) then
set_aflock(0)
set_prop(props.AF_LOCK,0)
else
set_aflock(0)
end
if (get_prop(props.AF_LOCK) == 0) then printf(" AFL unlocked") else printf(" AFL unlock failed") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOff") == -1 then
call_event_proc("PT_MFOff")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOff") == -1 then
call_event_proc("MFOff")
end
end
if (get_prop(props.FOCUS_MODE) == 1 ) then -- MF not reset - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(0) == 0 ) then set_aflock(0) end -- fall back so reset AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 0) then printf(" MF disabled") else printf(" MF disable failed") end
end
sleep(100)
end
end
-- zoom position
function update_zoom(zpos)
local count = 0
if(zpos ~= nil) then
zstep=((get_zoom_steps()-1)*zpos)/100
printf("setting zoom to "..zpos.." percent step="..zstep)
sleep(200)
set_zoom(zstep)
sleep(2000)
press("shoot_half")
repeat
sleep(100)
count = count + 1
until (get_shooting() == true ) or (count > 40 )
release("shoot_half")
end
end
-- restore camera settings on shutdown
function restore()
set_config_value(121,0) -- USB remote disable
set_config_value(297,old_console_timeout) -- restore console timeout value
if (backlight==1) then set_lcd_display(1) end -- display on
unlock_focus()
if( zoom_setpoint ~= nil ) then update_zoom(0) end
if( shot_count >= max_shots) and ( max_shots > 1) then
if ( poff_if_done == 1 ) then -- did script ending because # of shots done ?
printf("power off - shot count at limit") -- complete power down
sleep(2000)
post_levent_to_ui('PressPowerButton')
else
set_record(0) end -- just retract lens
end
end
-- Video mode
function check_video(shot)
local capture_mode
if ((video_mode>0) and(shot>0) and (shot%video_mode == 0)) then
unlock_focus()
printf("Video mode started. Button:"..tostring(video_button))
if( video_button ) then
click "video"
else
capture_mode=capmode.get()
capmode.set('VIDEO_STD')
press("shoot_full")
sleep(300)
release("shoot_full")
end
local end_second = get_day_seconds() + video_duration
repeat
wait_click(500)
until (is_key("menu")) or (get_day_seconds() > end_second)
if( video_button ) then
click "video"
else
press("shoot_full")
sleep(300)
release("shoot_full")
capmode.set(capture_mode)
end
printf("Video mode finished.")
sleep(1000)
lock_focus()
return(true)
else
return(false)
end
end
-- PWM USB pulse functions
function ch1up()
printf(" * usb pulse = ch1up")
shot_request = true
end
function ch1mid()
printf(" * usb pulse = ch1mid")
if ( get_mode() == false ) then
switch_mode(1)
lock_focus()
end
end
function ch1down()
printf(" * usb pulse = ch1down")
switch_mode(0)
end
function ch2up()
printf(" * usb pulse = ch2up")
update_zoom(100)
end
function ch2mid()
printf(" * usb pulse = ch2mid")
if ( zoom_setpoint ~= nil ) then update_zoom(zoom_setpoint) else update_zoom(50) end
end
function ch2down()
printf(" * usb pulse = ch2down")
update_zoom(0)
end
function pwm_mode(pulse_width)
if pulse_width > 0 then
if pulse_width < 5 then ch1up()
elseif pulse_width < 8 then ch1mid()
elseif pulse_width < 11 then ch1down()
elseif pulse_width < 14 then ch2up()
elseif pulse_width < 17 then ch2mid()
elseif pulse_width < 20 then ch2down()
else printf(" * usb pulse width error") end
end
end
-- Basic exposure calculation using shutter speed and ISO only
-- called for Tv-only and ND-only cameras (cameras without an iris)
function basic_tv_calc()
tv96setpoint = tv96target
av96setpoint = nil
local min_av = get_prop(props.MIN_AV)
-- calculate required ISO setting
sv96setpoint = tv96setpoint + min_av - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max2 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max2 -- clamp at max2 ISO if so
tv96setpoint = math.max(bv96meter+sv96setpoint-min_av,tv96min) -- recalculate required shutter speed down to Tv min
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - min_av -- recalculate required shutter speed and hope for the best
end
end
-- Basic exposure calculation using shutter speed, iris and ISO
-- called for iris-only and "both" cameras (cameras with an iris & ND filter)
function basic_iris_calc()
tv96setpoint = tv96target
av96setpoint = av96target
-- calculate required ISO setting
sv96setpoint = tv96setpoint + av96setpoint - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max1 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max1 -- clamp at first ISO limit
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint < av96min ) then -- check if new setting is goes below lowest f-stop
av96setpoint = av96min -- clamp at lowest f-stop
sv96setpoint = tv96setpoint + av96setpoint - bv96meter -- recalculate ISO setting
if (sv96setpoint > sv96max2 ) then -- check if the result is above max2 ISO
sv96setpoint = sv96max2 -- clamp at highest ISO setting if so
tv96setpoint = math.max(bv96meter+sv96setpoint-av96setpoint,tv96min) -- recalculate required shutter speed down to tv minimum
end
end
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate required shutter speed
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
tv96setpoint = tv96max -- clamp at maximum shutter speed if so
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint > av96max ) then -- check if new setting is goes above highest f-stop
av96setpoint = av96max -- clamp at highest f-stop
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate shutter speed needed and hope for the best
end
end
end
end
-- calculate exposure for cams without adjustable iris or ND filter
function exposure_Tv_only()
insert_ND_filter = nil
basic_tv_calc()
end
-- calculate exposure for cams with ND filter only
function exposure_NDfilter()
insert_ND_filter = false
basic_tv_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_tv_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- calculate exposure for cams with adjustable iris only
function exposure_iris()
insert_ND_filter = nil
basic_iris_calc()
end
-- calculate exposure for cams with both adjustable iris and ND filter
function exposure_both()
insert_ND_filter = false -- NOTE : assume ND filter never used automatically by Canon firmware
basic_iris_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_iris_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- ========================== Main Program =================================
set_console_layout(1 ,1, 45, 14 )
--printf("KAP 3.1 started - press MENU to exit")
printf("3DR EAI 1.0 Canon SX260 - Lets Map!")
printf("Based On KAP 3.1")
printf("Press the shutter button to pause")
bi=get_buildinfo()
printf("%s %s-%s %s %s %s", bi.version, bi.build_number, bi.build_revision, bi.platform, bi.platsub, bi.build_date)
chdk_version= tonumber(string.sub(bi.build_number,1,1))*100 + tonumber(string.sub(bi.build_number,3,3))*10 + tonumber(string.sub(bi.build_number,5,5))
if ( tonumber(bi.build_revision) > 0 ) then
build = tonumber(bi.build_revision)
else
build = tonumber(string.match(bi.build_number,'-(%d+)$'))
end
if ((chdk_version<120) or ((chdk_version==120)and(build<3276)) or ((chdk_version==130)and(build<3383))) then
printf("CHDK 1.2.0 build 3276 or higher required")
else
if( props.CONTINUOUS_AF == nil ) then caf=-999 else caf = get_prop(props.CONTINUOUS_AF) end
if( props.SERVO_AF == nil ) then saf=-999 else saf = get_prop(props.SERVO_AF) end
cmode = capmode.get_name()
printf("Mode:%s,Continuous_AF:%d,Servo_AF:%d", cmode,caf,saf)
printf(" Tv:"..print_tv(tv96target).." max:"..print_tv(tv96max).." min:"..print_tv(tv96min).." ecomp:"..(ec96adjust/96).."."..(math.abs(ec96adjust*10/96)%10) )
printf(" Av:"..print_av(av96target).." minAv:"..print_av(av96minimum).." maxAv:"..print_av(av96max) )
printf(" ISOmin:"..print_sv(sv96min).." ISO1:"..print_sv(sv96max1).." ISO2:"..print_sv(sv96max2) )
printf(" MF mode:"..focus_mode.." Video:"..video_mode.." USB:"..usb_mode)
printf(" AvM:"..Av_mode.." int:"..(interval/1000).." Shts:"..max_shots.." Dly:"..start_delay.." B/L:"..backlight)
sleep(500)
if (start_delay > 0 ) then
printf("entering start delay of ".. start_delay.." seconds")
sleep( start_delay*1000 )
end
-- CAMERA CONFIGURATION -
-- FIND config table here http://subversion.assembla.com/svn/chdk/trunk/core/conf.c
set_config_value(2,0) --Save raw: off
if (gps==1) then
set_config_value(282,1) --turn GPS on
--set_config_value(278,1) --show GPS symbol
set_config_value(261,1) --wait for signal time
set_config_value(266,5) --battery shutdown percentage
end
-- enable USB remote in USB remote moded
if (usb_mode > 0 ) then
set_config_value(121,1) -- make sure USB remote is enabled
if (get_usb_power(1) == 0) then -- can we start ?
printf("waiting on USB signal")
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
--changed sleep from 1000 to 500
else sleep(500) end
printf("USB signal received")
end
-- switch to shooting mode
switch_mode(1)
-- set zoom position
update_zoom(zoom_setpoint)
-- lock focus at infinity
lock_focus()
-- disable flash and AF assist lamp
set_prop(props.FLASH_MODE, 2) -- flash off
set_prop(props.AF_ASSIST_BEAM,0) -- AF assist off if supported for this camera
set_config_value( 297, 60) -- set console timeout to 60 seconds
if (usb_mode > 2 ) then repeat until (get_usb_power(2) == 0 ) end -- flush pulse buffer
next_shot_time = get_tick_count()
script_exit = false
if( get_video_button() == 1) then video_button = true else video_button = false end
set_console_layout(2 ,0, 45, 4 )
repeat
--BB: Set get_usb_power(2) > 7 for a 70/100s pulse
--BB: Could consider a max threshold to prevent erroneous trigger events
--eg. get_usb_power(2) > 7 && get_usb_power(2) < 13
if( ( (usb_mode < 2 ) and ( next_shot_time <= get_tick_count() ) )
or ( (usb_mode == 2 ) and (get_usb_power(2) > 7 ) )
or ( (usb_mode == 3 ) and (shot_request == true ) ) ) then
-- time to insert a video sequence ?
if( check_video(shot_count) == true) then next_shot_time = get_tick_count() end
-- intervalometer timing
next_shot_time = next_shot_time + interval
-- set focus at infinity ? (maybe redundant for AFL & MF mode but makes sure its set right)
if (focus_mode > 0) then
set_focus(infx)
sleep(100)
end
-- check exposure
local count = 0
local timeout = false
press("shoot_half")
repeat
sleep(50)
count = count + 1
if (count > 40 ) then timeout = true end
until (get_shooting() == true ) or (timeout == true)
-- shoot in auto mode if meter reading invalid, else calculate new desired exposure
if ( timeout == true ) then
release("shoot_half")
repeat sleep(50) until get_shooting() == false
shoot() -- shoot in Canon auto mode if we don't have a valid meter reading
shot_count = shot_count + 1
printf(string.format('IMG_%04d.JPG',get_exp_count()).." : shot in auto mode, meter reading invalid")
else
-- get meter reading values (and add in exposure compensation)
bv96raw=get_bv96()
bv96meter=bv96raw-ec96adjust
tv96meter=get_tv96()
av96meter=get_av96()
sv96meter=get_sv96()
-- set minimum Av to larger of user input or current min for zoom setting
av96min= math.max(av96minimum,get_prop(props.MIN_AV))
if (av96target < av96min) then av96target = av96min end
-- calculate required setting for current ambient light conditions
if (Av_mode == 1) then exposure_iris()
elseif (Av_mode == 2) then exposure_NDfilter()
elseif (Av_mode == 3) then exposure_both()
else exposure_Tv_only()
end
-- set up all exposure overrides
set_tv96_direct(tv96setpoint)
set_sv96(sv96setpoint)
if( av96setpoint ~= nil) then set_av96_direct(av96setpoint) end
if(Av_mode > 1) and (insert_ND_filter == true) then -- ND filter available and needed?
set_nd_filter(1) -- activate the ND filter
nd_string="NDin"
else
set_nd_filter(2) -- make sure the ND filter does not activate
nd_string="NDout"
end
-- and finally shoot the image
press("shoot_full_only")
sleep(100)
release("shoot_full")
repeat sleep(50) until get_shooting() == false
shot_count = shot_count + 1
-- update shooting statistic and log as required
shot_focus=get_focus()
if(shot_focus ~= -1) and (shot_focus < 20000) then
focus_string=" foc:"..(shot_focus/1000).."."..(((shot_focus%1000)+50)/100).."m"
if(focus_mode>0) then
error_string=" **WARNING : focus not at infinity**"
end
else
focus_string=" foc:infinity"
error_string=nil
end
printf(string.format('%d) IMG_%04d.JPG',shot_count,get_exp_count()))
printf(" meter : Tv:".. print_tv(tv96meter) .." Av:".. print_av(av96meter) .." Sv:"..print_sv(sv96meter).." "..bv96raw ..":"..bv96meter)
printf(" actual: Tv:".. print_tv(tv96setpoint).." Av:".. print_av(av96setpoint).." Sv:"..print_sv(sv96setpoint))
printf(" AvMin:".. print_av(av96min).." NDF:"..nd_string..focus_string )
if ((max_shots>0) and (shot_count >= max_shots)) then script_exit = true end
shot_request = false -- reset shot request flag
end
collectgarbage()
end
-- check if USB remote enabled in intervalometer mode and USB power is off -> pause if so
if ((usb_mode == 1 ) and (get_usb_power(1) == 0)) then
printf("waiting on USB signal")
unlock_focus()
switch_mode(0)
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
switch_mode(1)
lock_focus()
if ( is_key("menu")) then script_exit = true end
printf("USB wait finished")
sleep(100)
end
if (usb_mode == 3 ) then pwm_mode(get_usb_power(2)) end
if (blite_timer > 0) then
blite_timer = blite_timer-1
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(0) end
end
if( error_string ~= nil) then
draw_string( 16, 144, string.sub(error_string.." ",0,42), 258, 259)
end
wait_click(100)
if( not( is_key("no_key"))) then
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(1) end
blite_timer=300
if ( is_key("menu") ) then script_exit = true end
end
until (script_exit==true)
printf("script halt requested")
restore()
end
--[[ end of file ]]--
| gpl-3.0 |
vasilish/torch-draw | main.lua | 1 | 5910 | -- local image = require('image')
require('image')
local optim = require('optim')
local nn = require('nn')
torch.setdefaulttensortype('torch.FloatTensor')
torch.manualSeed(1)
require('eve')
local utils = require('utils')
local opt_parser = require('opts')
local options = opt_parser.parse(arg)
local use_cuda = options.backend == 'cuda' or options.backend == 'cudnn'
print('====> Loading the data...')
print('====> Using ' .. options.dataset .. ' dataset...')
local dataloader = require('dataloaders/dataloader')
local dataset, input_size, img_size = dataloader.load_data(options, use_cuda)
print('====> Finished Loading the data..')
options.img_size = img_size
options.input_size = input_size
-- The number of steps for the recurrent model
local T = options.num_glimpses
local read_size = options.read_size
local write_size = options.write_size
local optimizer
if options.optimizer == 'eve' then
optimizer = eve
else
optimizer = optim[options.optimizer]
end
print('====> Creating the model...')
local model_creator = require('models/setup')
local model, criterion = model_creator.setup(options, use_cuda)
local theta, gradTheta = model:getParameters()
local canvas2Img = nn.Sequential():add(nn.Sigmoid())
if use_cuda then
canvas2Img = canvas2Img:cuda()
end
print('====> Finished creating the model...')
local batch
-- The logger object for the training loss
local loss_logger = optim.Logger(options.log_file)
loss_logger:setNames{'Loss'}
local batch_size = options.batch_size
local hidden_size = options.hidden_size
local img_size_tab = img_size:totable()
local latent_size = options.latent_size
local function feval(params)
if theta ~= params then
theta:copy(params)
end
gradTheta:zero()
local numBatchElements = batch:nElement()
local loss = 0
-- Forward Pass
local forward_output, _, _ = model:forward(batch)
local canvas = forward_output[1]
xHat = canvas2Img:forward(canvas[T])
-- Calculate Reconstruction loss
local lossX = criterion:forward(xHat + 1e-8, batch)
local mu = torch.cat(forward_output[#forward_output - 1])
-- local logvar = torch.cat(forward_output[#forward_output]):view(batch_size, T, -1)
local logvar = torch.cat(forward_output[#forward_output])
local var = torch.exp(logvar)
local lossZ = (0.5 / numBatchElements) * torch.sum(torch.pow(mu, 2) + var - logvar - 1)
-- Calculate the gradient of the reconstruction loss
gradLossX = criterion:backward(xHat, batch)
gradLossX = canvas2Img:backward(xHat, gradLossX)
-- Backward Pass
model:backward(batch, gradLossX, forward_output)
loss = lossX + lossZ
gradTheta:clamp(-options.grad_clip, options.grad_clip)
return loss, gradTheta
end
local optimState = {
momentum = options.momentum,
nesterov = true,
learningRate = options.lr,
learningRateDecay = options.lrDecay,
}
local use_attention = options.use_attention == 'true'
local img_folder = paths.concat(options.img_folder, use_attention and 'attention' or
'no_attention')
if not paths.dirp(img_folder) and not paths.mkdir(img_folder) then
error('Error: Unable to create image directory: ' .. img_folder '\n')
end
local seq_folder = paths.concat(img_folder, options.dataset)
if not paths.dirp(seq_folder) and not paths.mkdir(seq_folder) then
error('Error: Unable to create image directory: ' .. seq_folder '\n')
end
local model_folder = options.model_folder
if not paths.dirp(model_folder) and not paths.mkdir(model_folder) then
error('Error: Unable to create model directory: ' .. model_folder '\n')
end
local train_size = dataset.train.size
local img_per_row = options.img_per_row
local test_sample = dataset.train.data:narrow(1, 1, options.batch_size)
for e = 1, options.maxEpochs do
lossSum = 0
N = 0
-- Iterate over batches
for i = 1, train_size, batch_size do
-- Necessary check in case the batch size does not divide the
-- training set
local end_idx = math.min(batch_size, train_size - i)
if end_idx < batch_size then
break
end
-- Sample a minibatch
batch = dataset.train.data:narrow(1, i, end_idx)
__, loss = optimizer(feval, theta, optimState)
N = N + 1
lossSum = lossSum + loss[1]
end
-- TO DO: Finish model storage
if e % options.save_interval == 0 then
model:save_model(options)
end
print('Epoch ' .. e .. ' loss = ' .. lossSum / N)
loss_logger:add{lossSum / N}
if options.display or options.save_image then
local test_output, read_att_params, write_att_params =
model:forward(test_sample)
local canvas_seq = {}
for t = 1, T do
local current_canvas = canvas2Img:forward(test_output[1][t])
canvas_seq[t] = torch.Tensor(table.unpack(current_canvas:size():totable()))
canvas_seq[t]:copy(current_canvas)
end
local read_seq
if use_attention then
read_seq = utils.drawReadSeq(T, read_size, test_sample,
read_att_params, {0, 255, 0})
end
local write_seq
if use_attention then
write_seq = utils.drawWriteSeq(T, write_size, canvas_seq,
write_att_params, {255, 0, 0})
else
write_seq = canvas_seq
end
local img_seq = {}
for t = 1, T do
local read_img
if use_attention then
read_img = image.toDisplayTensor(read_seq[t], 2, img_per_row)
else
read_img = image.toDisplayTensor(test_sample, 2, img_per_row)
end
local write_img = image.toDisplayTensor(write_seq[t], 2, img_per_row)
local img = image.toDisplayTensor({read_img, write_img}, 5)
if options.display then
if window ~= nil then
window = image.display{image=img, win=window}
else
window = image.display(img)
end
sys.sleep(0.1)
end
img_seq[t] = img
end
if options.save_image then
utils.storeSeq(seq_folder, img_seq)
end
end
end
-- Store the final model
model:save_model(options)
| mit |
elbamos/nn | LookupTable.lua | 3 | 3381 | local THNN = require 'nn.THNN'
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 4
function LookupTable:__init(nIndex, nOutput, paddingValue)
parent.__init(self)
self.weight = torch.Tensor(nIndex, nOutput)
self.gradWeight = torch.Tensor(nIndex, nOutput):zero()
self.paddingValue = paddingValue or 0
self:reset()
end
function LookupTable:backCompatibility()
self._count = self._count or torch.IntTensor()
self._input = self._input or torch.LongTensor()
if not self.shouldScaleGradByFreq then
self.shouldScaleGradByFreq = false
end
end
function LookupTable:accUpdateOnly()
self.gradWeight = nil
return self
end
function LookupTable:setPadding(paddingValue)
self.paddingValue = paddingValue
return self
end
function LookupTable:scaleGradByFreq()
self.shouldScaleGradByFreq = true
return self
end
function LookupTable:reset(stdv)
stdv = stdv or 1
self.weight:normal(0, stdv)
end
function LookupTable:makeInputContiguous(input)
-- make sure input is a contiguous torch.LongTensor
if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._input) then
self.copiedInput = true
self._input:resize(input:size()):copy(input)
return self._input
end
self.copiedInput = false
return input
end
function LookupTable:updateOutput(input)
self:backCompatibility()
input = self:makeInputContiguous(input)
if input:dim() == 1 then
self.output:index(self.weight, 1, input)
elseif input:dim() == 2 then
self.output:index(self.weight, 1, input:view(-1))
self.output = self.output:view(input:size(1), input:size(2), self.weight:size(2))
else
error("input must be a vector or matrix")
end
return self.output
end
function LookupTable:accGradParameters(input, gradOutput, scale)
self:backCompatibility()
input = self.copiedInput and self._input or input
if input:dim() == 2 then
input = input:view(-1)
elseif input:dim() ~= 1 then
error("input must be a vector or matrix")
end
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
self.gradWeight.THNN.LookupTable_accGradParameters(
input:cdata(),
gradOutput:cdata(),
self.gradWeight:cdata(),
self._count:cdata(),
THNN.optionalTensor(self._sorted),
THNN.optionalTensor(self._indices),
self.shouldScaleGradByFreq or false,
self.paddingValue or 0,
scale or 1
)
end
function LookupTable:type(type, tensorCache)
parent.type(self, type, tensorCache)
if type == 'torch.CudaTensor' then
-- CUDA uses _sorted and _indices temporary tensors
self._sorted = self.weight.new()
self._indices = self.weight.new()
self._count = self.weight.new()
self._input = self.weight.new()
else
-- self._count and self._input should only be converted if using Cuda
self._count = torch.IntTensor()
self._input = torch.LongTensor()
end
return self
end
function LookupTable:clearState()
self._gradOutput = nil
return self
end
-- we do not need to accumulate parameters when sharing
LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
| bsd-3-clause |
jshackley/darkstar | scripts/zones/Metalworks/npcs/Takiyah.lua | 17 | 1292 | -----------------------------------
-- Area: Metalworks
-- NPC: Takiyah
-- Type: Regional Merchant
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (GetRegionOwner(QUFIMISLAND) ~= BASTOK) then
player:showText(npc,TAKIYAH_CLOSED_DIALOG);
else
player:showText(npc,TAKIYAH_OPEN_DIALOG);
stock = {0x03ba,4121} -- Magic Pot Shard
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 |
asmagill/hs._asm.luathread | luaskin/modules/keycodes/init.lua | 6 | 1622 | --- === hs.keycodes ===
---
--- Convert between key-strings and key-codes. Also provides funcionality for querying and changing keyboard layouts.
--- hs.keycodes.map = {...}
--- Constant
--- A mapping from string representation of a key to its keycode, and vice versa.
--- For example: keycodes[1] == "s", and keycodes["s"] == 1, and so on.
--- This is primarily used by the hs.eventtap and hs.hotkey extensions.
---
--- Valid strings are any single-character string, or any of the following strings:
---
--- f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15,
--- f16, f17, f18, f19, f20, pad, pad*, pad+, pad/, pad-, pad=,
--- pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7, pad8, pad9,
--- padclear, padenter, return, tab, space, delete, escape, help,
--- home, pageup, forwarddelete, end, pagedown, left, right, down, up
local keycodes = require "hs.keycodes.internal"
keycodes.map = keycodes._cachemap()
--- hs.keycodes.inputSourceChanged(fn())
--- Function
--- Sets the function to be called when your input source (i.e. qwerty, dvorak, colemac) changes.
--- You can use this to rebind your hotkeys or whatever.
--- Note: setting this will un-set functions previously registered by this function.
function keycodes.inputSourceChanged(fn)
if keycodes._callback then keycodes._callback:_stop() end
keycodes._callback = keycodes._newcallback(function()
keycodes.map = keycodes._cachemap()
if fn then
local ok, err = xpcall(fn, debug.traceback)
if not ok then hs.showError(err) end
end
end)
end
keycodes.inputSourceChanged()
return keycodes
| mit |
hockeychaos/Core-Scripts-1 | CoreScriptsRoot/Modules/VR/Dialog.lua | 2 | 5894 | --Dialog: 3D dialogs for ROBLOX in VR
--written by 0xBAADF00D
--6/30/2016
local CoreGui = game:GetService("CoreGui")
local RobloxGui = CoreGui:WaitForChild("RobloxGui")
local InputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Utility = require(RobloxGui.Modules.Settings.Utility)
local Panel3D = require(RobloxGui.Modules.VR.Panel3D)
local DIALOG_BG_COLOR = Color3.new(0.2, 0.2, 0.2)
local DIALOG_BG_TRANSPARENCY = 0.3
local DIALOG_TITLE_HEIGHT = 66
local DIALOG_COLOR_HEIGHT = 8
local DIALOG_TITLE_TEXT_SIZE = Enum.FontSize.Size36
local DIALOG_CONTENT_PADDING = 48
local TITLE_COLOR = Color3.new(1, 1, 1)
local PANEL_OFFSET_CF = CFrame.new(0, 0, -7) * CFrame.Angles(0, math.pi, 0)
local emptySelectionImage = Utility:Create "ImageLabel" {
Name = "EmptySelectionImage",
Image = "",
BackgroundTransparency = 1,
ImageTransparency = 1
}
local DialogPanel = Panel3D.Get("Dialog")
DialogPanel:SetType(Panel3D.Type.Fixed)
DialogPanel.localCF = PANEL_OFFSET_CF
DialogPanel:SetCanFade(true)
local dialogPanelAngle = 0
local opacityLookup = {}
local resetBaseAngle = false
local baseAngle = 0
local PANEL_FADE_ANGLE_0, PANEL_FADE_ANGLE_1 = math.rad(37.5), math.rad(44)
local PANEL_FADE_RANGE = PANEL_FADE_ANGLE_1 - PANEL_FADE_ANGLE_0
local PANEL_REAPPEAR_ANGLE = math.rad(90)
local function positionDialogPanel(desiredAngle)
dialogPanelAngle = desiredAngle
local headCF = InputService:GetUserCFrame(Enum.UserCFrame.Head)
local headPos = headCF.p
DialogPanel.localCF = CFrame.new(headPos) * CFrame.Angles(0, desiredAngle, 0) * PANEL_OFFSET_CF
end
function DialogPanel:CalculateTransparency()
local headCF = InputService:GetUserCFrame(Enum.UserCFrame.Head)
local headLook = headCF.lookVector * Vector3.new(1, 0, 1)
local vertAngle = math.asin(headCF.lookVector.Y)
local vectorToPanel = Vector3.new(math.cos(baseAngle + dialogPanelAngle + math.rad(90)), 0, -math.sin(baseAngle + dialogPanelAngle + math.rad(90)))
if math.abs(vertAngle) > PANEL_FADE_ANGLE_1 then
resetBaseAngle = true
end
local angleToPanel = math.acos(headLook:Dot(vectorToPanel))
return math.min(math.max(0, (angleToPanel - PANEL_FADE_ANGLE_0) / PANEL_FADE_RANGE), 1)
end
local function updatePanelPosition()
local headCF = InputService:GetUserCFrame(Enum.UserCFrame.Head)
local headLook = headCF.lookVector * Vector3.new(1, 0, 1)
local headAngle = (math.atan2(-headLook.Z, headLook.X) - math.rad(90)) % math.rad(360)
local newPanelAngle = baseAngle + math.floor((headAngle / PANEL_REAPPEAR_ANGLE) + 0.5) * PANEL_REAPPEAR_ANGLE
if resetBaseAngle then
resetBaseAngle = false
baseAngle = headAngle
end
positionDialogPanel(newPanelAngle)
end
-- RenderStep update function for the DialogPanel
function dialogPanelRenderUpdate()
if DialogPanel.transparency == 1 or resetBaseAngle then
updatePanelPosition()
end
--update the transparency of gui elements
local opacityMult = 1 - DialogPanel.transparency
for guiElement, baseOpacity in pairs(opacityLookup) do
local transparency = 1 - (baseOpacity * opacityMult)
if guiElement:IsA("TextLabel") or guiElement:IsA("TextButton") then
guiElement.TextTransparency = transparency
elseif guiElement:IsA("ImageLabel") or guiElement:IsA("ImageButton") then
guiElement.ImageTransparency = transparency
elseif guiElement:IsA("Frame") then
guiElement.BackgroundTransparency = transparency
end
end
end
local DialogQueue = {}
local currentDescendantConn = nil
local lastDialogShown = nil
local function updatePanel()
local currentDialog = DialogQueue[1]
if lastDialogShown and lastDialogShown.content then
lastDialogShown.content.Parent = nil
end
if not currentDialog or not currentDialog.content then
DialogPanel:SetVisible(false)
opacityLookup = {}
if currentDescendantConn then
currentDescendantConn:disconnect()
currentDescendantConn = nil
end
else
currentDialog.content.Parent = DialogPanel:GetGUI()
lastDialogShown = currentDialog
local contentSize = currentDialog.content.AbsoluteSize
DialogPanel:ResizePixels(contentSize.X, contentSize.Y, 100)
resetBaseAngle = true
updatePanelPosition()
DialogPanel:SetVisible(true)
opacityLookup = {}
local function search(parent)
if parent:IsA("ImageLabel") or parent:IsA("ImageButton") then
opacityLookup[parent] = 1 - parent.ImageTransparency
elseif parent:IsA("TextLabel") or parent:IsA("TextButton") then
opacityLookup[parent] = 1 - parent.TextTransparency
elseif parent:IsA("Frame") then
opacityLookup[parent] = 1 - parent.BackgroundTransparency
end
for i, v in pairs(parent:GetChildren()) do
search(v)
end
end
search(DialogPanel:GetGUI())
if currentDescendantConn then
currentDescendantConn:disconnect()
currentDescendantConn = nil
end
currentDescendantConn = DialogPanel:GetGUI().DescendantAdded:connect(function(descendant)
search(descendant)
end)
end
end
local Dialog = {}
Dialog.__index = Dialog
function Dialog.new(content)
local self = setmetatable({}, Dialog)
self.content = content
return self
end
function Dialog:SetContent(guiElement)
if not guiElement and self.content then
self.content.Parent = nil
end
self.content = guiElement
end
local renderFuncBound = false
function Dialog:Show(shouldTakeover)
if not renderFuncBound then
renderFuncBound = true
RunService:BindToRenderStep("DialogPanel", Enum.RenderPriority.First.Value, dialogPanelRenderUpdate)
end
if shouldTakeover then
table.insert(DialogQueue, 1, self)
else
table.insert(DialogQueue, self)
end
updatePanel()
end
function Dialog:Close()
for idx, dialog in pairs(DialogQueue) do
if dialog == self then
table.remove(DialogQueue, idx)
break
end
end
if renderFuncBound and #DialogQueue == 0 then
renderFuncBound = false
RunService:UnbindFromRenderStep("DialogPanel")
end
updatePanel()
end
return Dialog | apache-2.0 |
jshackley/darkstar | scripts/zones/AlTaieu/npcs/_0x1.lua | 17 | 2004 | -----------------------------------
-- Area: Al'Taieu
-- NPC: Rubious Crystal (South Tower)
-- @pos 0 -6.250 -736.912 33
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/AlTaieu/TextIDs");
require("scripts/zones/AlTaieu/mobIDs");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus") == 2 and player:getVar("[SEA][AlTieu]SouthTower") == 0 and player:getVar("[SEA][AlTieu]SouthTowerCS") == 0) then
player:messageSpecial(OMINOUS_SHADOW);
SpawnMob(SouthTowerAern,180):updateClaim(player);
SpawnMob(SouthTowerAern+1,180):updateClaim(player);
SpawnMob(SouthTowerAern+2,180):updateClaim(player);
elseif (player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus") == 2 and player:getVar("[SEA][AlTieu]SouthTower") == 1 and player:getVar("[SEA][AlTieu]SouthTowerCS") == 0) then
player:startEvent(0x00A1);
else
player:messageSpecial(NOTHING_OF_INTEREST);
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 == 0x00A1) then
player:setVar("[SEA][AlTieu]SouthTowerCS", 1);
player:setVar("[SEA][AlTieu]SouthTower", 0);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/PsoXja/npcs/_i94.lua | 17 | 1263 | -----------------------------------
-- Area: Pso'Xja
-- NPC: _i94 (Stone Gate)
-- Notes: Blue Bracelet Door
-- @pos -330.000 14.074 -261.600 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local Z=player:getZPos();
if (Z >= -261) then
if (player:hasKeyItem(595)==true) then -- Blue Bracelet
player:startEvent(0x003d);
else
player:messageSpecial(ARCH_GLOW_BLUE);
end
elseif (Z <= -262) then
player:messageSpecial(CANNOT_OPEN_SIDE);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/spells/enchanting_etude.lua | 18 | 1767 | -----------------------------------------
-- Spell: Enchanting Etude
-- Static CHR Boost, BRD 22
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 0;
if (sLvl+iLvl <= 181) then
power = 3;
elseif ((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then
power = 4;
elseif ((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then
power = 5;
elseif ((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then
power = 6;
elseif ((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then
power = 7;
elseif ((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then
power = 8;
elseif (sLvl+iLvl >= 450) then
power = 9;
end
local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_ETUDE,power,0,duration,caster:getID(), MOD_CHR, 1)) then
spell:setMsg(75);
end
return EFFECT_ETUDE;
end; | gpl-3.0 |
jshackley/darkstar | scripts/commands/promote.lua | 26 | 1214 | ---------------------------------------------------------------------------------------------------
-- func: promote
-- desc: Promotes the player to a new GM level.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "si"
};
function onTrigger(player, target, level)
if (level == nil) then
level = target;
target = player:getName();
end
if (target == nil) then
target = player:getName();
end
-- Validate the target..
local targ = GetPlayerByName( target );
if (targ == nil) then
player:PrintToPlayer( string.format( "Invalid player '%s' given.", target ) );
return;
end
-- Validate the level..
if (level < 0) then
level = 0;
end
if (targ:getGMLevel() < player:getGMLevel()) then
if (level < player:getGMLevel()) then
targ:setGMLevel(level);
else
player:PrintToPlayer( "Target's new level is too high." );
end
else
printf( "%s attempting to adjust higher GM: %s", player:getName(), targ:getName() );
end
end; | gpl-3.0 |
10sa/Advanced-Nutscript | nutscript/gamemode/libs/sh_bar.lua | 1 | 3696 | --[[
Purpose: A library to draw bars on the HUD and add bars to the list. This is used since
it will make it easier for bars to be organized in drawing, otherwise it would be random
each frame and would look like it is flickering. It can also be used for plugins to display
other stuff, such as the stamina plugin.
--]]
nut.bar = nut.bar or {}
if (CLIENT) then
nut.bar.buffer = {}
nut.bar.mainStart = nut.bar.mainStart or 0
nut.bar.mainFinish = nut.bar.mainFinish or 0
nut.bar.mainText = nut.bar.mainText or ""
nut.bar.mainAlpha = nut.bar.mainAlpha or 0
--[[
Purpose: Adds a bar to the list of bars to be drawn and defines an ID for it.
--]]
function nut.bar.Add(uniqueID, data)
data.id = table.Count(nut.bar.buffer) + 1
nut.bar.buffer[uniqueID] = data
end
--[[
Purpose: Removes a bar from the list of bars based on its ID.
--]]
function nut.bar.Remove(uniqueID)
if (nut.bar.buffer[uniqueID]) then
nut.bar.buffer[uniqueID] = nil
end
end
--[[
Purpose: Return the data for a specific bar based off the uniqueID provided.
--]]
function nut.bar.Get(uniqueID)
return nut.bar.buffer[uniqueID]
end
--[[
Purpose: Loops through the list of bars, sorted by their IDs, and draws them
using nut:PaintBar(). It returns the y of the next bar that is to be drawn.
--]]
function nut.bar.Paint(x, y, width, height)
for k, v in pairs(nut.bar.buffer) do
if (AdvNut.hook.Run("HUDShouldPaintBar", k) != false and v.getValue) then
local realValue = v.getValue()
v.deltaValue = math.Approach(v.deltaValue or 0, realValue, FrameTime() * 80)
local color = v.color
if (v.deltaValue != realValue) then
color = Color(200, 200, 200, 100)
v.fadeTime = CurTime() + 2
end
if ((v.fadeTime or 0) < CurTime()) then
continue
end
y = GAMEMODE:PaintBar(v.deltaValue, color, x, y, width, height)
end
end
return y
end
function nut.bar.SetMainBar(text, time, timePassed)
nut.bar.mainStart = CurTime() - (timePassed or 0)
nut.bar.mainFinish = nut.bar.mainStart + time
nut.bar.mainText = text
end
function nut.bar.KillMainBar()
nut.bar.mainStart = 0
nut.bar.mainFinish = 0
nut.bar.mainText = ""
end
function nut.bar.PaintMain()
local finish = nut.bar.mainFinish
local approach = 0
if (finish > CurTime()) then
approach = 255
end
nut.bar.mainAlpha = math.Approach(nut.bar.mainAlpha, approach, FrameTime() * 360)
local alpha = nut.bar.mainAlpha
if (alpha > 0) then
local fraction = 1 - math.TimeFraction(nut.bar.mainStart, finish, CurTime())
local scrW, scrH = ScrW(), ScrH()
local width, height = scrW * 0.4, scrH * 0.05
local x, y = scrW*0.5 - width*0.5, scrH * 0.5 + height*0.5
local border = 4
local color = nut.config.mainColor
color.a = alpha
surface.SetDrawColor(10, 10, 10, alpha * 0.25)
surface.DrawOutlinedRect(x, y, width, height)
surface.SetDrawColor(25, 25, 25, alpha * 0.78)
surface.DrawRect(x, y, width, height)
surface.SetDrawColor(color)
surface.DrawRect(x + border, y + border, math.Clamp(width*fraction - border*2, 0, width), height - border*2)
nut.util.DrawText(x + (width * 0.5), y + (height * 0.5), nut.bar.mainText, Color(255, 255, 255, alpha))
end
end
netstream.Hook("nut_MainBar", function(data)
local text = data[1]
local time = data[2]
local timePassed = data[3]
if (time == 0) then
nut.bar.KillMainBar()
else
nut.bar.SetMainBar(text, time, timePassed)
end
end)
else
local playerMeta = FindMetaTable("Player")
function playerMeta:SetMainBar(text, time, timePassed)
text = text or ""
time = time or 0
netstream.Start(self, "nut_MainBar", {text, time, timePassed})
end
end
| mit |
jshackley/darkstar | scripts/globals/weaponskills/raging_axe.lua | 30 | 1469 | -----------------------------------
-- Raging Axe
-- Axe weapon skill
-- Skill level: 5
-- Delivers a two-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- When stacked with Sneak Attack, both hits have a 100% chance of landing, though it is unclear if they both params.crit.
-- Aligned with the Breeze Gorget & Thunder Gorget.
-- Aligned with the Breeze Belt & Thunder Belt.
-- Element: None
-- Modifiers: STR:60%
-- 100%TP 200%TP 300%TP
-- 1.00 1.50 2.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 2;
params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
LWJGL-CI/bgfx | scripts/codegen.lua | 2 | 24783 | -- Copyright 2019 云风 https://github.com/cloudwu . All rights reserved.
-- License (the same with bgfx) : https://github.com/bkaradzic/bgfx/blob/master/LICENSE
local codegen = {}
local DEFAULT_NAME_ALIGN = 20
local DEFINE_NAME_ALIGN = 41
local function namealign(name, align)
align = align or DEFAULT_NAME_ALIGN
return string.rep(" ", align - #name)
end
local function camelcase_to_underscorecase(name)
local tmp = {}
for v in name:gmatch "[%u%d]+%l*" do
tmp[#tmp+1] = v:lower()
end
return table.concat(tmp, "_")
end
local function to_underscorecase(name)
local tmp = {}
for v in name:gmatch "[_%u][%l%d]*" do
if v:byte() == 95 then -- '_'
v = v:sub(2) -- remove _
end
tmp[#tmp+1] = v
end
return table.concat(tmp, "_")
end
local function underscorecase_to_camelcase(name)
local tmp = {}
for v in name:gmatch "[^_]+" do
tmp[#tmp+1] = v:sub(1,1):upper() .. v:sub(2)
end
return table.concat(tmp)
end
local function convert_funcname(name)
name = name:gsub("^%l", string.upper) -- Change to upper CamlCase
return camelcase_to_underscorecase(name)
end
local function convert_arg(all_types, arg, namespace)
local fulltype, array = arg.fulltype:match "(.-)%s*(%[%s*[%d%a_:]*%s*%])"
if array then
arg.fulltype = fulltype
arg.array = array
local enum, value = array:match "%[%s*([%a%d]+)::([%a%d]+)%]"
if enum then
local typedef = all_types[ enum .. "::Enum" ]
if typedef == nil then
error ("Unknown Enum " .. enum)
end
arg.carray = "[BGFX_" .. camelcase_to_underscorecase(enum):upper() .. "_" .. value:upper() .. "]"
end
end
local t, postfix = arg.fulltype:match "(%a[%a%d_:]*)%s*([*&]+)%s*$"
if t then
arg.type = t
if postfix == "&" then
arg.ref = true
end
else
local prefix, t = arg.fulltype:match "^%s*(%a+)%s+(%S+)"
if prefix then
arg.type = t
else
arg.type = arg.fulltype
end
end
local ctype
local substruct = namespace.substruct
if substruct then
ctype = substruct[arg.type]
end
if not ctype then
ctype = all_types[arg.type]
end
if not ctype then
error ("Undefined type " .. arg.fulltype .. " in " .. namespace.name)
end
arg.ctype = arg.fulltype:gsub(arg.type, ctype.cname):gsub("&", "*")
if ctype.cname ~= arg.type then
arg.cpptype = arg.fulltype:gsub(arg.type, "bgfx::"..arg.type)
else
arg.cpptype = arg.fulltype
end
if arg.ref then
arg.ptype = arg.cpptype:gsub("&", "*")
end
end
local function alternative_name(name)
if name:sub(1,1) == "_" then
return name:sub(2)
else
return name .. "_"
end
end
local function gen_arg_conversion(all_types, arg)
if arg.ctype == arg.fulltype then
-- do not need conversion
return
end
local ctype = all_types[arg.type]
if ctype.handle and arg.type == arg.fulltype then
local aname = alternative_name(arg.name)
arg.aname = aname .. ".cpp"
arg.aname_cpp2c = aname .. ".c"
arg.conversion = string.format(
"union { %s c; bgfx::%s cpp; } %s = { %s };" ,
ctype.cname, arg.type, aname, arg.name)
arg.conversion_back = string.format(
"union { bgfx::%s cpp; %s c; } %s = { %s };" ,
arg.type, ctype.cname, aname, arg.name)
elseif arg.ref then
if ctype.cname == arg.type then
arg.aname = "*" .. arg.name
arg.aname_cpp2c = "&" .. arg.name
elseif arg.out and ctype.enum then
local aname = alternative_name(arg.name)
local cpptype = arg.cpptype:match "(.-)%s*&" -- remove &
local c99type = arg.ctype:match "(.-)%s*%*" -- remove *
arg.aname = aname
arg.aname_cpp2c = "&" .. aname
arg.conversion = string.format("%s %s;", cpptype, aname)
arg.conversion_back = string.format("%s %s;", c99type, aname);
arg.out_conversion = string.format("*%s = (%s)%s;", arg.name, ctype.cname, aname)
arg.out_conversion_back = string.format("%s = (%s)%s;", arg.name, c99type, aname)
else
arg.aname = alternative_name(arg.name)
arg.aname_cpp2c = string.format("(%s)&%s" , arg.ctype , arg.name)
arg.conversion = string.format(
"%s %s = *(%s)%s;",
arg.cpptype, arg.aname, arg.ptype, arg.name)
end
else
local cpptype = arg.cpptype
local ctype = arg.ctype
if arg.array then
cpptype = cpptype .. "*"
ctype = ctype .. "*"
end
arg.aname = string.format(
"(%s)%s",
cpptype, arg.name)
arg.aname_cpp2c = string.format(
"(%s)%s",
ctype, arg.name)
end
end
local function gen_ret_conversion(all_types, func)
local postfix = { func.vararg and "va_end(argList);" }
local postfix_cpp2c = { postfix[1] }
func.ret_postfix = postfix
func.ret_postfix_cpp2c = postfix_cpp2c
for _, arg in ipairs(func.args) do
if arg.out_conversion then
postfix[#postfix+1] = arg.out_conversion
postfix_cpp2c[#postfix_cpp2c+1] = arg.out_conversion_back
end
end
local ctype = all_types[func.ret.type]
if ctype.handle then
func.ret_conversion = string.format(
"union { %s c; bgfx::%s cpp; } handle_ret;" ,
ctype.cname, ctype.name)
func.ret_conversion_cpp2c = string.format(
"union { bgfx::%s cpp; %s c; } handle_ret;" ,
ctype.name, ctype.cname)
func.ret_prefix = "handle_ret.cpp = "
func.ret_prefix_cpp2c = "handle_ret.c = "
postfix[#postfix+1] = "return handle_ret.c;"
postfix_cpp2c[#postfix_cpp2c+1] = "return handle_ret.cpp;"
elseif func.ret.fulltype ~= "void" then
local ctype_conversion = ""
local conversion_back = ""
if ctype.name ~= ctype.cname then
if func.ret.ref then
ctype_conversion = "(" .. func.ret.ctype .. ")&"
conversion_back = "*(" .. func.ret.ptype .. ")"
else
ctype_conversion = "(" .. func.ret.ctype .. ")"
conversion_back = "(" .. func.ret.cpptype .. ")"
end
end
if #postfix > 0 then
func.ret_prefix = string.format("%s retValue = %s", func.ret.ctype , ctype_conversion)
func.ret_prefix_cpp2c = string.format("%s retValue = %s", func.ret.cpptype , conversion_back)
local ret = "return retValue;"
postfix[#postfix+1] = ret
postfix_cpp2c[#postfix_cpp2c+1] = ret
else
func.ret_prefix = string.format("return %s", ctype_conversion)
func.ret_prefix_cpp2c = string.format("return %s", conversion_back)
end
end
end
local function convert_vararg(v)
if v.vararg then
local args = v.args
local vararg = {
name = "",
fulltype = "...",
type = "...",
ctype = "...",
aname = "argList",
conversion = string.format(
"va_list argList;\n\tva_start(argList, %s);",
args[#args].name),
}
args[#args + 1] = vararg
v.alter_name = v.vararg
end
end
local function calc_flag_values(flag)
local shift = flag.shift
local base = flag.base or 0
local cap = 1 << (flag.range or 0)
if flag.range then
if flag.range == 64 then
flag.mask = 0xffffffffffffffff
else
flag.mask = ((1 << flag.range) - 1) << shift
end
end
local values = {}
for index, item in ipairs(flag.flag) do
local value = item.value
if flag.const then
-- use value directly
elseif shift then
if value then
if value > 0 then
value = value - 1
end
else
value = index + base - 1
end
if value >= cap then
error (string.format("Out of range for %s.%s (%d/%d)", flag.name, item.name, value, cap))
end
value = value << shift
elseif #item == 0 then
if value then
if value > 0 then
value = 1 << (value - 1)
end
else
local s = index + base - 2
if s >= 0 then
value = 1 << s
else
value = 0
end
end
end
if not value then
-- It's a combine flags
value = 0
for _, name in ipairs(item) do
local v = values[name]
if v then
value = value | v
else
-- todo : it's a undefined flag
value = nil
break
end
end
end
item.value = value
values[item.name] = value
end
end
function codegen.nameconversion(all_types, all_funcs)
for _,v in ipairs(all_types) do
local name = v.name
local cname = v.cname
if cname == nil then
if name:match "^%u" then
cname = camelcase_to_underscorecase(name)
elseif not v.flag then
v.cname = name
end
end
if cname and not v.flag then
if v.namespace then
cname = camelcase_to_underscorecase(v.namespace) .. "_" .. cname
end
v.cname = "bgfx_".. cname .. "_t"
end
if v.enum then
v.typename = v.name
v.name = v.name .. "::Enum"
end
if v.flag then
calc_flag_values(v)
end
end
-- make index
for _,v in ipairs(all_types) do
if not v.namespace then
if all_types[v.name] then
error ("Duplicate type " .. v.name)
elseif not v.flag then
all_types[v.name] = v
end
end
end
-- make sub struct index
for _,v in ipairs(all_types) do
if v.namespace then
local super = all_types[v.namespace]
if not super then
error ("Define " .. v.namespace .. " first")
end
local substruct = super.substruct
if not substruct then
substruct = {}
super.substruct = substruct
end
if substruct[v.name] then
error ( "Duplicate sub struct " .. v.name .. " in " .. v.namespace)
end
v.parent_class = super
substruct[#substruct+1] = v
substruct[v.name] = v
end
end
for _,v in ipairs(all_types) do
if v.struct then
for _, item in ipairs(v.struct) do
convert_arg(all_types, item, v)
end
elseif v.args then
-- funcptr
for _, arg in ipairs(v.args) do
convert_arg(all_types, arg, v)
end
convert_vararg(v)
convert_arg(all_types, v.ret, v)
end
end
local funcs = {}
local funcs_conly = {}
local funcs_alter = {}
for _,v in ipairs(all_funcs) do
if v.cname == nil then
v.cname = convert_funcname(v.name)
end
if v.class then
v.cname = convert_funcname(v.class) .. "_" .. v.cname
local classtype = all_types[v.class]
if classtype then
local methods = classtype.methods
if not methods then
methods = {}
classtype.methods = methods
end
methods[#methods+1] = v
end
elseif not v.conly then
funcs[v.name] = v
end
if v.conly then
table.insert(funcs_conly, v)
end
for _, arg in ipairs(v.args) do
convert_arg(all_types, arg, v)
gen_arg_conversion(all_types, arg)
end
convert_vararg(v)
if v.alter_name then
funcs_alter[#funcs_alter+1] = v
end
convert_arg(all_types, v.ret, v)
gen_ret_conversion(all_types, v)
local namespace = v.class
if namespace then
local classname = namespace
if v.const then
classname = "const " .. classname
end
local classtype = { fulltype = classname .. "*" }
convert_arg(all_types, classtype, v)
v.this = classtype.ctype
v.this_type = classtype
v.this_conversion = string.format( "%s This = (%s)_this;", classtype.cpptype, classtype.cpptype)
v.this_to_c = string.format("(%s)this", classtype.ctype)
end
end
for _, v in ipairs(funcs_conly) do
local func = funcs[v.name]
if func then
func.multicfunc = func.multicfunc or { func.cname }
table.insert(func.multicfunc, v.cname)
end
end
for _, v in ipairs(funcs_alter) do
local func = funcs[v.alter_name]
v.alter_cname = func.cname
end
end
local function lines(tbl)
if not tbl or #tbl == 0 then
return "//EMPTYLINE"
else
return table.concat(tbl, "\n\t")
end
end
local function remove_emptylines(txt)
return (txt:gsub("\t//EMPTYLINE\n", ""))
end
local function codetemp(func)
local conversion = {}
local conversion_c2cpp = {}
local args = {}
local cargs = {}
local callargs_conversion = {}
local callargs_conversion_back = {}
local callargs = {}
local cppfunc
local classname
if func.class then
-- It's a member function
cargs[1] = func.this .. " _this"
conversion[1] = func.this_conversion
cppfunc = "This->" .. func.name
callargs[1] = "_this"
callargs_conversion_back[1] = func.this_to_c
classname = func.class .. "::"
else
cppfunc = "bgfx::" .. tostring(func.alter_name or func.name)
classname = ""
end
for _, arg in ipairs(func.args) do
conversion[#conversion+1] = arg.conversion
conversion_c2cpp[#conversion_c2cpp+1] = arg.conversion_back
local cname = arg.ctype .. " " .. arg.name
if arg.array then
cname = cname .. (arg.carray or arg.array)
end
local name = arg.fulltype .. " " .. arg.name
if arg.array then
name = name .. arg.array
end
if arg.default ~= nil then
name = name .. " = " .. tostring(arg.default)
end
cargs[#cargs+1] = cname
args[#args+1] = name
callargs_conversion[#callargs_conversion+1] = arg.aname or arg.name
callargs_conversion_back[#callargs_conversion_back+1] = arg.aname_cpp2c or arg.name
callargs[#callargs+1] = arg.name
end
conversion[#conversion+1] = func.ret_conversion
conversion_c2cpp[#conversion_c2cpp+1] = func.ret_conversion_cpp2c
local ARGS
local args_n = #args
if args_n == 0 then
ARGS = ""
elseif args_n == 1 then
ARGS = args[1]
else
ARGS = "\n\t " .. table.concat(args, "\n\t, ") .. "\n\t"
end
local preret_c2c
local postret_c2c = {}
local conversion_c2c = {}
local callfunc_c2c
if func.vararg then
postret_c2c[1] = "va_end(argList);"
local vararg = func.args[#func.args]
callargs[#callargs] = vararg.aname
callargs_conversion_back[#callargs_conversion_back] = vararg.aname
conversion_c2c[1] = vararg.conversion
conversion_c2cpp[1] = vararg.conversion
if func.ret.fulltype == "void" then
preret_c2c = ""
else
preret_c2c = func.ret.ctype .. " retValue = "
postret_c2c[#postret_c2c+1] = "return retValue;"
end
callfunc_c2c = func.alter_cname or func.cname
else
if func.ret.fulltype == "void" then
preret_c2c = ""
else
preret_c2c = "return "
end
callfunc_c2c = func.cname
end
outCargs = table.concat(cargs, ", ")
if outCargs == "" then
outCargs = "void"
end
return {
RET = func.ret.fulltype,
CRET = func.ret.ctype,
CFUNCNAME = func.cname,
CFUNCNAMEUPPER = func.cname:upper(),
CFUNCNAMECAML = underscorecase_to_camelcase(func.cname),
FUNCNAME = func.name,
CARGS = outCargs,
CPPARGS = table.concat(args, ", "),
ARGS = ARGS,
CONVERSION = lines(conversion),
CONVERSIONCTOC = lines(conversion_c2c),
CONVERSIONCTOCPP = lines(conversion_c2cpp),
PRERET = func.ret_prefix or "",
PRERETCPPTOC = func.ret_prefix_cpp2c or "",
CPPFUNC = cppfunc,
CALLFUNCCTOC = callfunc_c2c,
CALLARGSCTOCPP = table.concat(callargs_conversion, ", "),
CALLARGSCPPTOC = table.concat(callargs_conversion_back, ", "),
CALLARGS = table.concat(callargs, ", "),
POSTRET = lines(func.ret_postfix),
POSTRETCPPTOC = lines(func.ret_postfix_cpp2c),
PRERETCTOC = preret_c2c,
POSTRETCTOC = lines(postret_c2c),
CLASSNAME = classname,
CONST = func.const and " const" or "",
}
end
local function apply_template(func, temp)
func.codetemp = func.codetemp or codetemp(func)
return (temp:gsub("$(%u+)", func.codetemp))
end
function codegen.apply_functemp(func, temp)
return remove_emptylines(apply_template(func, temp))
end
function codegen.gen_funcptr(funcptr)
return apply_template(funcptr, "typedef $RET (*$FUNCNAME)($ARGS);")
end
function codegen.gen_cfuncptr(funcptr)
return apply_template(funcptr, "typedef $CRET (*$CFUNCNAME)($CARGS);")
end
local function doxygen_funcret(r, func, prefix)
if not func or func.ret.fulltype == "void" or func.ret.comment == nil then
return
end
r[#r+1] = prefix
r[#r+1] = string.format("%s @returns %s", prefix, func.ret.comment[1])
for i = 2,#func.ret.comment do
r[#r+1] = string.format("%s %s", prefix, func.ret.comment[i])
end
return r
end
local function doxygen_func(r, func, prefix)
if not func or not func.args or #func.args == 0 then
return
end
r[#r+1] = prefix
for _, arg in ipairs(func.args) do
local inout
if arg.out then
inout = "out"
elseif arg.inout then
inout = "inout"
else
inout = "in"
end
local comment = string.format("%s @param[%s] %s", prefix, inout, arg.name)
if arg.comment then
r[#r+1] = comment .. " " .. arg.comment[1]
for i = 2,#arg.comment do
r[#r+1] = string.format("%s %s", prefix, arg.comment[i])
end
else
r[#r+1] = comment
end
end
doxygen_funcret(r, func, prefix)
return r
end
function codegen.doxygen_type(doxygen, func, cname)
if doxygen == nil then
return
end
local result = {}
for _, line in ipairs(doxygen) do
result[#result+1] = "/// " .. line
end
doxygen_func(result, func, "///")
if cname then
result[#result+1] = "///"
if type(cname) == "string" then
result[#result+1] = string.format("/// @attention C99's equivalent binding is `%s`.", cname)
else
local names = {}
for _, v in ipairs(cname) do
names[#names+1] = "`" .. v .. "`"
end
result[#result+1] = string.format("/// @attention C99's equivalent bindings are %s.", table.concat(names, ","))
end
end
result[#result+1] = "///"
return table.concat(result, "\n")
end
function codegen.doxygen_ctype(doxygen, func)
if doxygen == nil then
return
end
local result = {
"/**",
}
for _, line in ipairs(doxygen) do
result[#result+1] = " * " .. line
end
doxygen_func(result, func, " *")
result[#result+1] = " *"
result[#result+1] = " */"
return table.concat(result, "\n")
end
local enum_temp = [[
struct $NAME
{
$COMMENT
enum Enum
{
$ITEMS
Count
};
};
]]
function codegen.gen_enum_define(enum)
assert(type(enum.enum) == "table", "Not an enum")
local items = {}
for _, item in ipairs(enum.enum) do
local text
if not item.comment then
text = item.name .. ","
else
local comment = table.concat(item.comment, " ")
text = string.format("%s,%s //!< %s",
item.name, namealign(item.name), comment)
end
items[#items+1] = text
end
local comment = ""
if enum.comment then
comment = "/// " .. enum.comment
end
local temp = {
NAME = enum.typename,
COMMENT = comment,
ITEMS = table.concat(items, "\n\t\t"),
}
return (enum_temp:gsub("$(%u+)", temp))
end
local cenum_temp = [[
typedef enum $NAME
{
$ITEMS
$COUNT
} $NAME_t;
]]
function codegen.gen_enum_cdefine(enum)
assert(type(enum.enum) == "table", "Not an enum")
local cname = enum.cname:match "(.-)_t$"
local uname = cname:upper()
local items = {}
for index , item in ipairs(enum.enum) do
local comment = ""
if item.comment then
comment = table.concat(item.comment, " ")
end
local ename = item.cname
if not ename then
if enum.underscore then
ename = camelcase_to_underscorecase(item.name)
else
ename = item.name
end
ename = ename:upper()
end
local name = uname .. "_" .. ename
items[#items+1] = string.format("%s,%s /** (%2d) %s%s */",
name,
namealign(name, 40),
index - 1,
comment,
namealign(comment, 30))
end
local temp = {
NAME = cname,
COUNT = uname .. "_COUNT",
ITEMS = table.concat(items, "\n\t"),
}
return (cenum_temp:gsub("$(%u+)", temp))
end
local function flag_format(flag)
if not flag.format then
flag.format = "%0" .. (flag.bits // 4) .. "x"
end
end
function codegen.gen_flag_cdefine(flag)
assert(type(flag.flag) == "table", "Not a flag")
flag_format(flag)
local cname = "BGFX_" .. (flag.cname or to_underscorecase(flag.name):upper())
local s = {}
local shift = flag.shift
for index, item in ipairs(flag.flag) do
local name
if item.cname then
name = cname .. "_" .. item.cname
else
name = cname .. "_" .. to_underscorecase(item.name):upper()
end
local value = item.value
-- combine flags
if #item > 0 then
if item.comment then
for _, c in ipairs(item.comment) do
s[#s+1] = "/// " .. c
end
end
local sets = { "" }
for _, v in ipairs(item) do
sets[#sets+1] = cname .. "_" .. to_underscorecase(v):upper()
end
s[#s+1] = string.format("#define %s (0%s \\\n\t)\n", name, table.concat(sets, " \\\n\t| "))
else
local comment = ""
if item.comment then
if #item.comment > 1 then
s[#s+1] = ""
for _, c in ipairs(item.comment) do
s[#s+1] = "/// " .. c
end
else
comment = " //!< " .. item.comment[1]
end
end
value = string.format(flag.format, value)
local code = string.format("#define %s %sUINT%d_C(0x%s)%s",
name, namealign(name, DEFINE_NAME_ALIGN), flag.bits, value, comment)
s[#s+1] = code
end
end
local mask
if flag.mask then
mask = string.format(flag.format, flag.mask)
mask = string.format("UINT%d_C(0x%s)", flag.bits, mask)
end
if shift then
local name = cname .. "_SHIFT"
local comment = flag.desc or ""
local shift_align = tostring(shift)
shift_align = shift_align .. namealign(shift_align, #mask)
local comment = ""
if flag.desc then
comment = string.format(" //!< %s bit shift", flag.desc)
end
local code = string.format("#define %s %s%s%s", name, namealign(name, DEFINE_NAME_ALIGN), shift_align, comment)
s[#s+1] = code
end
if flag.range then
local name = cname .. "_MASK"
local comment = ""
if flag.desc then
comment = string.format(" //!< %s bit mask", flag.desc)
end
local code = string.format("#define %s %s%s%s", name, namealign(name, DEFINE_NAME_ALIGN), mask, comment)
s[#s+1] = code
end
if flag.helper then
s[#s+1] = string.format(
"#define %s(v) ( ( (uint%d_t)(v)<<%s )&%s)",
cname,
flag.bits,
(cname .. "_SHIFT"),
(cname .. "_MASK"))
end
s[#s+1] = ""
return table.concat(s, "\n")
end
local function text_with_comments(items, item, cstyle, is_classmember)
local name = item.name
if item.array then
if cstyle then
name = name .. (item.carray or item.array)
else
name = name .. item.array
end
end
local typename
if cstyle then
typename = item.ctype
else
typename = item.fulltype
end
if is_classmember then
name = "m_" .. name
end
local text = string.format("%s%s %s;", typename, namealign(typename), name)
if item.comment then
if #item.comment > 1 then
table.insert(items, "")
if cstyle then
table.insert(items, "/**")
for _, c in ipairs(item.comment) do
table.insert(items, " * " .. c)
end
table.insert(items, " */")
else
for _, c in ipairs(item.comment) do
table.insert(items, "/// " .. c)
end
end
else
text = string.format(
cstyle and "%s %s/** %s%s */" or "%s %s//!< %s",
text, namealign(text, 40), item.comment[1], namealign(item.comment[1], 40))
end
end
items[#items+1] = text
end
local struct_temp = [[
struct $NAME
{
$METHODS
$SUBSTRUCTS
$ITEMS
};
]]
function codegen.gen_struct_define(struct, methods)
assert(type(struct.struct) == "table", "Not a struct")
local items = {}
for _, item in ipairs(struct.struct) do
text_with_comments(items, item, false, methods ~= nil and not struct.shortname)
end
local ctor = {}
if struct.ctor then
ctor[1] = struct.name .. "();"
ctor[2] = ""
end
if methods then
for _, m in ipairs(methods) do
if m:sub(-1) ~= "\n" then
m = m .. "\n"
end
for line in m:gmatch "(.-)\n" do
ctor[#ctor+1] = line
end
ctor[#ctor+1] = ""
end
end
local subs = {}
if struct.substruct then
for _, v in ipairs(struct.substruct) do
local s = codegen.gen_struct_define(v)
s = s:gsub("\n", "\n\t")
subs[#subs+1] = s
end
end
local temp = {
NAME = struct.name,
SUBSTRUCTS = lines(subs),
ITEMS = table.concat(items, "\n\t"),
METHODS = lines(ctor),
}
return remove_emptylines(struct_temp:gsub("$(%u+)", temp))
end
local cstruct_temp = [[
typedef struct $NAME_s
{
$ITEMS
} $NAME_t;
]]
local cstruct_empty_temp = [[
struct $NAME_s;
typedef struct $NAME_s $NAME_t;
]]
function codegen.gen_struct_cdefine(struct)
assert(type(struct.struct) == "table", "Not a struct")
local cname = struct.cname:match "(.-)_t$"
local items = {}
for _, item in ipairs(struct.struct) do
text_with_comments(items, item, true)
end
local temp = {
NAME = cname,
ITEMS = table.concat(items, "\n\t"),
}
local codetemp = #struct.struct == 0 and cstruct_empty_temp or cstruct_temp
return (codetemp:gsub("$(%u+)", temp))
end
local chandle_temp = [[
typedef struct $NAME_s { uint16_t idx; } $NAME_t;
]]
function codegen.gen_chandle(handle)
assert(handle.handle, "Not a handle")
return (chandle_temp:gsub("$(%u+)", { NAME = handle.cname:match "(.-)_t$" }))
end
local handle_temp = [[
struct $NAME { uint16_t idx; };
inline bool isValid($NAME _handle) { return bgfx::kInvalidHandle != _handle.idx; }
]]
function codegen.gen_handle(handle)
assert(handle.handle, "Not a handle")
return (handle_temp:gsub("$(%u+)", { NAME = handle.name }))
end
local idl = require "idl"
local doxygen = require "doxygen"
local conversion
local idlfile = {}
function codegen.load(filename)
assert(conversion == nil, "Don't call codegen.load() after codegen.idl()")
assert(idlfile[filename] == nil, "Duplicate load " .. filename)
local source = doxygen.load(filename)
local f = assert(load(source, filename , "t", idl))
f()
idlfile[filename] = true
end
function codegen.idl(filename)
if conversion == nil then
if filename and not idlfile[filename] then
codegen.load(filename)
end
assert(next(idlfile), "call codegen.load() first")
conversion = true
codegen.nameconversion(idl.types, idl.funcs)
end
return idl
end
return codegen
| bsd-2-clause |
jshackley/darkstar | scripts/globals/items/queens_crown.lua | 34 | 1570 | -----------------------------------------
-- ID: 6064
-- Item: queens_crown
-- Food Effect: 240 Min, All Races
-----------------------------------------
-- MP+6% (Upper limit 55)
-- INT+4
-- MND+3
-- CHR+2
-- STR-2
-- MAB+7
-----------------------------------------
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,14400,6064);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 6);
target:addMod(MOD_FOOD_MP_CAP, 55);
target:addMod(MOD_INT, 4);
target:addMod(MOD_MND, 3);
target:addMod(MOD_CHR, 2);
target:addMod(MOD_STR, -2);
target:addMod(MOD_MATT, 7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 6);
target:delMod(MOD_FOOD_MP_CAP, 55);
target:delMod(MOD_INT, 4);
target:delMod(MOD_MND, 3);
target:delMod(MOD_CHR, 2);
target:delMod(MOD_STR, -2);
target:delMod(MOD_MATT, 7);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Inner_Horutoto_Ruins/npcs/_5cr.lua | 17 | 2440 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: _5cr (Magical Gizmo) #3
-- Involved In Mission: The Horutoto Ruins Experiment
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- The Magical Gizmo Number, this number will be compared to the random
-- value created by the mission The Horutoto Ruins Experiment, when you
-- reach the Gizmo Door and have the cutscene
local magical_gizmo_no = 3; -- of the 6
-- Check if we are on Windurst Mission 1-1
if (player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 2) then
-- Check if we found the correct Magical Gizmo or not
if (player:getVar("MissionStatus_rv") == magical_gizmo_no) then
player:startEvent(0x0034);
else
if (player:getVar("MissionStatus_op3") == 2) then
-- We've already examined this
player:messageSpecial(EXAMINED_RECEPTACLE);
else
-- Opened the wrong one
player:startEvent(0x0035);
end
end
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
-- If we just finished the cutscene for Windurst Mission 1-1
-- The cutscene that we opened the correct Magical Gizmo
if (csid == 0x0034) then
player:setVar("MissionStatus",3);
player:setVar("MissionStatus_rv", 0);
player:addKeyItem(CRACKED_MANA_ORBS);
player:messageSpecial(KEYITEM_OBTAINED,CRACKED_MANA_ORBS);
elseif (csid == 0x0035) then
-- Opened the wrong one
player:setVar("MissionStatus_op3", 2);
-- Give the message that thsi orb is not broken
player:messageSpecial(NOT_BROKEN_ORB);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/MiliartTK.lua | 27 | 5069 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Miliart T.K
-- Type: Sigil NPC
-- @pos 107 1 -31 80
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/campaign");
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local notes = player:getCurrency("allied_notes");
local freelances = 99; -- Faking it for now
local unknown = 12; -- Faking it for now
local medalRank = getMedalRank(player);
local bonusEffects = 0; -- 1 = regen, 2 = refresh, 4 = meal duration, 8 = exp loss reduction, 15 = all
local timeStamp = 0; -- getSigilTimeStamp(player);
-- if ( medal_rank > 25 and nation controls Throne_Room_S ) then
-- medal_rank = 32;
-- this decides if allied ring is in the Allied Notes item list.
-- end
if (medal_rank == 0) then
player:startEvent(0x06F);
else
player:startEvent(0x06E, 0, notes, freelances, unknown, medalRank, bonusEffects, timeStamp, 0);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local itemid = 0;
local canEquip = 2; -- Faking it for now.
-- 0 = Wrong job, 1 = wrong level, 2 = Everything is in order, 3 or greater = menu exits...
if (csid == 0x06E and option >= 2 and option <= 2050) then
itemid = getSandOriaNotesItem(option);
player:updateEvent(0, 0, 0, 0, 0, 0, 0, canEquip); -- canEquip(player,itemid)); <- works for sanction NPC, wtf?
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local medalRank = getMedalRank(player);
if (csid == 0x06E) then
-- Note: the event itself already verifies the player has enough AN, so no check needed here.
if (option >= 2 and option <= 2050) then -- player bought item
-- currently only "ribbons" rank coded.
item, price = getSandOriaNotesItem(option)
if (player:getFreeSlotsCount() >= 1) then
player:delCurrency("allied_notes", price);
player:addItem(item);
player:messageSpecial(ITEM_OBTAINED, item);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, item);
end
-- Please, don't change this elseif without knowing ALL the option results first.
elseif (option == 1 or option == 4097 or option == 8193 or option == 12289 or option == 16385
or option == 20481 or option == 24577 or option == 28673 or option == 36865 or option == 40961
or option == 45057 or option == 49153 or option == 53249 or option == 57345 or option == 61441) then
local cost = 0;
local power = ( (option - 1) / 4096 );
local duration = 10800+((15*medalRank)*60); -- 3hrs +15 min per medal (minimum 3hr 15 min with 1st medal)
local subPower = 35; -- Sets % trigger for regen/refresh. Static at minimum value (35%) for now.
if (power == 1 or power == 2 or power == 4) then
-- 1: Regen, 2: Refresh, 4: Meal Duration
cost = 50;
elseif (power == 3 or power == 5 or power == 6 or power == 8 or power == 12) then
-- 3: Regen + Refresh, 5: Regen + Meal Duration, 6: Refresh + Meal Duration,
-- 8: Reduced EXP loss, 12: Meal Duration + Reduced EXP loss
cost = 100;
elseif (power == 7 or power == 9 or power == 10 or power == 11 or power == 13 or power == 14) then
-- 7: Regen + Refresh + Meal Duration, 9: Regen + Reduced EXP loss,
-- 10: Refresh + Reduced EXP loss, 11: Regen + Refresh + Reduced EXP loss,
-- 13: Regen + Meal Duration + Reduced EXP loss, 14: Refresh + Meal Duration + Reduced EXP loss
cost = 150;
elseif (power == 15) then
-- 15: Everything
cost = 200;
end
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGIL, power, 0, duration, 0, subPower, 0);
player:messageSpecial(ALLIED_SIGIL);
if (cost > 0) then
player:delCurrency("allied_notes", cost);
end
end
end
end; | gpl-3.0 |
ByteFun/Starbound_mods | smount/tech/mech/mount35/mount35.lua | 10 | 34323 | function checkCollision(position)
local boundBox = mcontroller.boundBox()
boundBox[1] = boundBox[1] - mcontroller.position()[1] + position[1]
boundBox[2] = boundBox[2] - mcontroller.position()[2] + position[2]
boundBox[3] = boundBox[3] - mcontroller.position()[1] + position[1]
boundBox[4] = boundBox[4] - mcontroller.position()[2] + position[2]
return not world.rectCollision(boundBox)
end
function randomProjectileLine(startPoint, endPoint, stepSize, projectile, chanceToSpawn)
local dist = math.distance(startPoint, endPoint)
local steps = math.floor(dist / stepSize)
local normX = (endPoint[1] - startPoint[1]) / dist
local normY = (endPoint[2] - startPoint[2]) / dist
for i = 0, steps do
local p1 = { normX * i * stepSize + startPoint[1], normY * i * stepSize + startPoint[2]}
local p2 = { normX * (i + 1) * stepSize + startPoint[1] + math.random(-1, 1), normY * (i + 1) * stepSize + startPoint[2] + math.random(-1, 1)}
if math.random() <= chanceToSpawn then
world.spawnProjectile(projectile, math.midPoint(p1, p2), entity.id(), {normX, normY}, false)
end
end
return endPoint
end
function blinkAdjust(position, doPathCheck, doCollisionCheck, doLiquidCheck, doStandCheck)
local blinkCollisionCheckDiameter = tech.parameter("blinkCollisionCheckDiameter")
local blinkVerticalGroundCheck = tech.parameter("blinkVerticalGroundCheck")
local blinkFootOffset = tech.parameter("blinkFootOffset")
if doPathCheck then
local collisionBlocks = world.collisionBlocksAlongLine(mcontroller.position(), position, true, 1)
if #collisionBlocks ~= 0 then
local diff = world.distance(position, mcontroller.position())
diff[1] = diff[1] / math.abs(diff[1])
diff[2] = diff[2] / math.abs(diff[2])
position = {collisionBlocks[1][1] - diff[1], collisionBlocks[1][2] - diff[2]}
end
end
if doCollisionCheck and not checkCollision(position) then
local spaceFound = false
for i = 1, blinkCollisionCheckDiameter * 2 do
if checkCollision({position[1] + i / 2, position[2] + i / 2}) then
position = {position[1] + i / 2, position[2] + i / 2}
spaceFound = true
break
end
if checkCollision({position[1] - i / 2, position[2] + i / 2}) then
position = {position[1] - i / 2, position[2] + i / 2}
spaceFound = true
break
end
if checkCollision({position[1] + i / 2, position[2] - i / 2}) then
position = {position[1] + i / 2, position[2] - i / 2}
spaceFound = true
break
end
if checkCollision({position[1] - i / 2, position[2] - i / 2}) then
position = {position[1] - i / 2, position[2] - i / 2}
spaceFound = true
break
end
end
if not spaceFound then
return nil
end
end
if doStandCheck then
local groundFound = false
for i = 1, blinkVerticalGroundCheck * 2 do
local checkPosition = {position[1], position[2] - i / 2}
if world.pointCollision(checkPosition, false) then
groundFound = true
position = {checkPosition[1], checkPosition[2] + 0.5 - blinkFootOffset}
break
end
end
if not groundFound then
return nil
end
end
if doLiquidCheck and (world.liquidAt(position) or world.liquidAt({position[1], position[2] + blinkFootOffset})) then
return nil
end
if doCollisionCheck and not checkCollision(position) then
return nil
end
return position
end
function findRandomBlinkLocation(doCollisionCheck, doLiquidCheck, doStandCheck)
local randomBlinkTries = tech.parameter("randomBlinkTries")
local randomBlinkDiameter = tech.parameter("randomBlinkDiameter")
for i=1,randomBlinkTries do
local position = mcontroller.position()
position[1] = position[1] + (math.random() * 2 - 1) * randomBlinkDiameter
position[2] = position[2] + (math.random() * 2 - 1) * randomBlinkDiameter
local position = blinkAdjust(position, false, doCollisionCheck, doLiquidCheck, doStandCheck)
if position then
return position
end
end
return nil
end
function init()
self.level = tech.parameter("mechLevel", 6)
self.mechState = "off"
self.mechStateTimer = 0
self.specialLast = false
self.active = false
self.fireTimer = 0
tech.setVisible(false)
tech.rotateGroup("guns", 0, true)
self.multiJumps = 0
self.lastJump = false
self.mode = "none"
self.timer = 0
self.targetPosition = nil
self.grabbed = false
self.holdingJump = false
self.ranOut = false
self.airDashing = false
self.dashTimer = 0
self.dashDirection = 0
self.dashLastInput = 0
self.dashTapLast = 0
self.dashTapTimer = 0
self.dashAttackfireTimer = 0
self.dashAttackTimer = 0
self.dashAttackDirection = 0
self.dashAttackLastInput = 0
self.dashAttackTapLast = 0
self.dashAttackTapTimer = 0
self.holdingUp = false
self.holdingDown = false
self.holdingLeft = false
self.holdingRight = false
self.speedMultiplier = 1.1
self.levitateActivated = false
self.mechTimer = 0
end
function uninit()
if self.active then
local mechTransformPositionChange = tech.parameter("mechTransformPositionChange")
mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]})
tech.setParentOffset({0, 0})
self.active = false
tech.setVisible(false)
tech.setParentState()
tech.setToolUsageSuppressed(false)
mcontroller.controlFace(nil)
end
end
function input(args)
if self.dashTimer > 0 then
return nil
end
local maximumDoubleTapTime = tech.parameter("maximumDoubleTapTime")
if self.dashTapTimer > 0 then
self.dashTapTimer = self.dashTapTimer - args.dt
end
if args.moves["right"] and self.active then
if self.dashLastInput ~= 1 then
if self.dashTapLast == 1 and self.dashTapTimer > 0 then
self.dashTapLast = 0
self.dashTapTimer = 0
return "dashRight"
else
self.dashTapLast = 1
self.dashTapTimer = maximumDoubleTapTime
end
end
self.dashLastInput = 1
elseif args.moves["left"] and self.active then
if self.dashLastInput ~= -1 then
if self.dashTapLast == -1 and self.dashTapTimer > 0 then
self.dashTapLast = 0
self.dashTapTimer = 0
return "dashLeft"
else
self.dashTapLast = -1
self.dashTapTimer = maximumDoubleTapTime
end
end
self.dashLastInput = -1
else
self.dashLastInput = 0
end
if args.moves["jump"] and mcontroller.jumping() then
self.holdingJump = true
elseif not args.moves["jump"] then
self.holdingJump = false
end
if args.moves["special"] == 1 then
if self.active then
return "mechDeactivate"
else
return "mechActivate"
end
elseif args.moves[""] == 2 and self.active then
return "blink"
elseif args.moves[""] and args.moves[""] and args.moves[""] and not self.levitateActivated and self.active then
return "grab"
elseif args.moves["down"] and args.moves["right"] and not self.levitateActivated and self.active then
return "dashAttackRight"
elseif args.moves["down"] and args.moves["left"] and not self.levitateActivated and self.active then
return "dashAttackLeft"
elseif args.moves["primaryFire"] and self.active then
return "mechFire"
elseif args.moves["altFire"] and self.active then
return "mechAltFire"
elseif args.moves[""] and args.moves[""] and self.active then
return "mechSecFire"
elseif args.moves[""] and not mcontroller.canJump() and not self.holdingJump and self.active then
return "jetpack"
elseif args.moves["jump"] and not mcontroller.jumping() and not mcontroller.canJump() and not self.lastJump then
self.lastJump = true
return "multiJump"
else
self.lastJump = args.moves["jump"]
end
self.specialLast = args.moves["special"] == 1
--RedOrb
-- if args.moves["left"] then
-- self.holdingLeft = true
-- elseif not args.moves["left"] then
-- self.holdingLeft = false
-- end
-- if args.moves["right"] then
-- self.holdingRight = true
-- elseif not args.moves["right"] then
-- self.holdingRight = false
-- end
-- if args.moves["up"] then
-- self.holdingUp = true
-- elseif not args.moves["up"] then
-- self.holdingUp = false
-- end
-- if args.moves["down"] then
-- self.holdingDown = true
-- elseif not args.moves["down"] then
-- self.holdingDown = false
-- end
-- if not args.moves["jump"] and not args.moves["left"]and not args.moves["right"]and not args.moves["up"]and not args.moves["down"] and not tech.canJump() and not self.holdingJump and self.levitateActivated then
-- return "levitatehover"
-- elseif args.moves["jump"] and not tech.canJump() and not self.holdingJump then
-- return "levitate"
-- elseif args.moves["left"] and args.moves["right"] and not tech.canJump() and self.levitateActivated then
-- return "levitatehover"
-- elseif args.moves["up"] and args.moves["down"] and not tech.canJump() and self.levitateActivated then
-- return "levitatehover"
-- elseif (args.moves["jump"] or args.moves["up"]) and args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleftup"
-- elseif (args.moves["jump"] or args.moves["up"]) and args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitaterightup"
-- elseif args.moves["down"] and args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleftdown"
-- elseif args.moves["down"] and args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitaterightdown"
-- elseif args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleft"
-- elseif args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitateright"
-- elseif args.moves["up"] and not tech.canJump() and not self.holdingDown and self.levitateActivated then
-- return "levitateup"
-- elseif args.moves["down"] and not tech.canJump() and not self.holdingUp and self.levitateActivated then
-- return "levitatedown"
-- else
-- return nil
-- end
--RedOrbEnd
end
function update(args)
if self.mechTimer > 0 then
self.mechTimer = self.mechTimer - args.dt
end
local dashControlForce = tech.parameter("dashControlForce")
local dashSpeed = tech.parameter("dashSpeed")
local dashDuration = tech.parameter("dashDuration")
local energyUsageDash = tech.parameter("energyUsageDash")
local usedEnergy = 0
if args.actions["dashRight"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then
self.dashTimer = dashDuration
self.dashDirection = 1
usedEnergy = energyUsageDash
self.airDashing = not mcontroller.onGround()
return tech.consumeTechEnergy(energyUsageDash)
elseif args.actions["dashLeft"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then
self.dashTimer = dashDuration
self.dashDirection = -1
usedEnergy = energyUsageDash
self.airDashing = not mcontroller.onGround()
return tech.consumeTechEnergy(energyUsageDash)
end
if self.dashTimer > 0 then
mcontroller.controlApproachXVelocity(dashSpeed * self.dashDirection, dashControlForce, true)
if self.airDashing then
mcontroller.controlParameters({gravityEnabled = false})
mcontroller.controlApproachYVelocity(0, dashControlForce, true)
end
if self.dashDirection == -1 then
mcontroller.controlFace(-1)
tech.setFlipped(true)
else
mcontroller.controlFace(1)
tech.setFlipped(false)
end
tech.setAnimationState("dashing", "on")
tech.setParticleEmitterActive("dashParticles", true)
self.dashTimer = self.dashTimer - args.dt
else
tech.setAnimationState("dashing", "off")
tech.setParticleEmitterActive("dashParticles", false)
end
local dashAttackControlForce = tech.parameter("dashAttackControlForce")
local dashAttackSpeed = tech.parameter("dashAttackSpeed")
local dashAttackDuration = tech.parameter("dashAttackDuration")
local energyUsageDashAttack = tech.parameter("energyUsageDashAttack")
local diffDash = world.distance(tech.aimPosition(), mcontroller.position())
local aimAngleDash = math.atan(diffDash[2], diffDash[1])
local mechDashFireCycle = tech.parameter("mechDashFireCycle")
local mechDashProjectile = tech.parameter("mechDashProjectile")
local mechDashProjectileConfig = tech.parameter("mechDashProjectileConfig")
local flipDash = aimAngleDash > math.pi / 2 or aimAngleDash < -math.pi / 2
if flipDash then
tech.setFlipped(false)
mcontroller.controlFace(-1)
self.dashAttackDirection = -1
else
tech.setFlipped(true)
mcontroller.controlFace(1)
self.dashAttackDirection = 1
end
if status.resource("energy") > energyUsageDashAttack and args.actions["dashAttackLeft"] or args.actions["dashAttackRight"] then
if self.dashAttackTimer <= 0 then
world.spawnProjectile(mechDashProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontDashGun", "firePoint")), entity.id(), {math.cos(0), math.sin(0)}, false, mechDashProjectileConfig)
self.dashAttackTimer = self.dashAttackTimer + mechDashFireCycle
else
self.dashAttackTimer = self.dashAttackTimer - args.dt
end
mcontroller.controlApproachXVelocity(dashAttackSpeed * self.dashAttackDirection, dashAttackControlForce, true)
tech.setAnimationState("dashingAttack", "on")
tech.setParticleEmitterActive("dashAttackParticles", true)
else
tech.setAnimationState("dashingAttack", "off")
tech.setParticleEmitterActive("dashAttackParticles", false)
end
local energyUsageBlink = tech.parameter("energyUsageBlink")
local blinkMode = tech.parameter("blinkMode")
local blinkOutTime = tech.parameter("blinkOutTime")
local blinkInTime = tech.parameter("blinkInTime")
if args.actions["blink"] and self.mode == "none" and status.resource("energy") > energyUsageBlink then
local blinkPosition = nil
if blinkMode == "random" then
local randomBlinkAvoidCollision = tech.parameter("randomBlinkAvoidCollision")
local randomBlinkAvoidMidair = tech.parameter("randomBlinkAvoidMidair")
local randomBlinkAvoidLiquid = tech.parameter("randomBlinkAvoidLiquid")
blinkPosition =
findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, randomBlinkAvoidLiquid) or
findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, false) or
findRandomBlinkLocation(randomBlinkAvoidCollision, false, false)
elseif blinkMode == "cursor" then
blinkPosition = blinkAdjust(tech.aimPosition(), true, true, false, false)
elseif blinkMode == "cursorPenetrate" then
blinkPosition = blinkAdjust(tech.aimPosition(), false, true, false, false)
end
if blinkPosition then
self.targetPosition = blinkPosition
self.mode = "start"
else
-- Make some kind of error noise
end
end
if self.mode == "start" then
mcontroller.setVelocity({0, 0})
self.mode = "out"
self.timer = 0
return tech.consumeTechEnergy(energyUsageBlink)
elseif self.mode == "out" then
tech.setParentDirectives("?multiply=00000000")
tech.setVisible(false)
tech.setAnimationState("blinking", "out")
mcontroller.setVelocity({0, 0})
self.timer = self.timer + args.dt
if self.timer > blinkOutTime then
mcontroller.setPosition(self.targetPosition)
self.mode = "in"
self.timer = 0
end
return 0
elseif self.mode == "in" then
tech.setParentDirectives()
tech.setVisible(true)
tech.setAnimationState("blinking", "in")
mcontroller.setVelocity({0, 0})
self.timer = self.timer + args.dt
if self.timer > blinkInTime then
self.mode = "none"
end
return 0
end
local energyUsageJump = tech.parameter("energyUsageJump")
local multiJumpCount = tech.parameter("multiJumpCount")
if args.actions["multiJump"] and self.multiJumps < multiJumpCount and status.resource("energy") > energyUsageJump then
mcontroller.controlJump(true)
self.multiJumps = self.multiJumps + 1
tech.burstParticleEmitter("multiJumpParticles")
tech.playSound("sound")
return tech.consumeTechEnergy(energyUsageJump)
else
if mcontroller.onGround() or mcontroller.liquidMovement() then
self.multiJumps = 0
end
end
local energyCostPerSecond = tech.parameter("energyCostPerSecond")
local energyCostPerSecondPrim = tech.parameter("energyCostPerSecondPrim")
local energyCostPerSecondSec = tech.parameter("energyCostPerSecondSec")
local energyCostPerSecondAlt = tech.parameter("energyCostPerSecondAlt")
local mechCustomMovementParameters = tech.parameter("mechCustomMovementParameters")
local mechTransformPositionChange = tech.parameter("mechTransformPositionChange")
local parentOffset = tech.parameter("parentOffset")
local mechCollisionTest = tech.parameter("mechCollisionTest")
local mechAimLimit = tech.parameter("mechAimLimit") * math.pi / 180
local mechFrontRotationPoint = tech.parameter("mechFrontRotationPoint")
local mechFrontFirePosition = tech.parameter("mechFrontFirePosition")
local mechBackRotationPoint = tech.parameter("mechBackRotationPoint")
local mechBackFirePosition = tech.parameter("mechBackFirePosition")
local mechFireCycle = tech.parameter("mechFireCycle")
local mechProjectile = tech.parameter("mechProjectile")
local mechProjectileConfig = tech.parameter("mechProjectileConfig")
local mechAltFireCycle = tech.parameter("mechAltFireCycle")
local mechAltProjectile = tech.parameter("mechAltProjectile")
local mechAltProjectileConfig = tech.parameter("mechAltProjectileConfig")
local mechSecFireCycle = tech.parameter("mechSecFireCycle")
local mechSecProjectile = tech.parameter("mechSecProjectile")
local mechSecProjectileConfig = tech.parameter("mechSecProjectileConfig")
local mechGunBeamMaxRange = tech.parameter("mechGunBeamMaxRange")
local mechGunBeamStep = tech.parameter("mechGunBeamStep")
local mechGunBeamSmokeProkectile = tech.parameter("mechGunBeamSmokeProkectile")
local mechGunBeamEndProjectile = tech.parameter("mechGunBeamEndProjectile")
local mechGunBeamUpdateTime = tech.parameter("mechGunBeamUpdateTime")
local mechTransform = tech.parameter("mechTransform")
local mechActiveSide = nil
if tech.setFlipped(true) then
mechActiveSide = "left"
elseif tech.setFlipped(false) then
mechActiveSide = "right"
end
local mechStartupTime = tech.parameter("mechStartupTime")
local mechShutdownTime = tech.parameter("mechShutdownTime")
if not self.active and args.actions["mechActivate"] and self.mechState == "off" then
mechCollisionTest[1] = mechCollisionTest[1] + mcontroller.position()[1]
mechCollisionTest[2] = mechCollisionTest[2] + mcontroller.position()[2]
mechCollisionTest[3] = mechCollisionTest[3] + mcontroller.position()[1]
mechCollisionTest[4] = mechCollisionTest[4] + mcontroller.position()[2]
if not world.rectCollision(mechCollisionTest) then
tech.burstParticleEmitter("mechActivateParticles")
mcontroller.translate(mechTransformPositionChange)
tech.setVisible(true)
tech.setAnimationState("transform", "in")
-- status.modifyResource("health", status.stat("maxHealth") / 20)
tech.setParentState("sit")
tech.setToolUsageSuppressed(true)
self.mechState = "turningOn"
self.mechStateTimer = mechStartupTime
self.active = true
else
-- Make some kind of error noise
end
elseif self.mechState == "turningOn" and self.mechStateTimer <= 0 then
tech.setParentState("sit")
self.mechState = "on"
self.mechStateTimer = 0
elseif (self.active and (args.actions["mechDeactivate"] and self.mechState == "on" or (energyCostPerSecond * args.dt > status.resource("energy")) and self.mechState == "on")) then
self.mechState = "turningOff"
tech.setAnimationState("transform", "out")
self.mechStateTimer = mechShutdownTime
elseif self.mechState == "turningOff" and self.mechStateTimer <= 0 then
tech.burstParticleEmitter("mechDeactivateParticles")
mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]})
tech.setVisible(false)
tech.setParentState()
tech.setToolUsageSuppressed(false)
tech.setParentOffset({0, 0})
self.mechState = "off"
self.mechStateTimer = 0
self.active = false
end
mcontroller.controlFace(nil)
if self.mechStateTimer > 0 then
self.mechStateTimer = self.mechStateTimer - args.dt
end
if self.active then
local diff = world.distance(tech.aimPosition(), mcontroller.position())
local aimAngle = math.atan(diff[2], diff[1])
local flip = aimAngle > math.pi / 2 or aimAngle < -math.pi / 2
mcontroller.controlParameters(mechCustomMovementParameters)
if flip then
tech.setFlipped(false)
local nudge = tech.transformedPosition({0, 0})
tech.setParentOffset({-parentOffset[1] - nudge[1], parentOffset[2] + nudge[2]})
mcontroller.controlFace(-1)
if aimAngle > 0 then
aimAngle = math.max(aimAngle, math.pi - mechAimLimit)
else
aimAngle = math.min(aimAngle, -math.pi + mechAimLimit)
end
tech.rotateGroup("guns", math.pi + aimAngle)
else
tech.setFlipped(true)
local nudge = tech.transformedPosition({0, 0})
tech.setParentOffset({parentOffset[1] + nudge[1], parentOffset[2] + nudge[2]})
mcontroller.controlFace(1)
if aimAngle > 0 then
aimAngle = math.min(aimAngle, mechAimLimit)
else
aimAngle = math.max(aimAngle, -mechAimLimit)
end
tech.rotateGroup("guns", -aimAngle)
end
if not mcontroller.onGround() then
if mcontroller.velocity()[2] > 0 then
if args.actions["mechFire"] then
tech.setAnimationState("movement", "jumpAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "jumpAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "jumpAttack")
else
tech.setAnimationState("movement", "jump")
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "fallAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "fallAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "fallAttack")
else
tech.setAnimationState("movement", "fall")
end
end
elseif mcontroller.walking() or mcontroller.running() then
if flip and mcontroller.movingDirection() == 1 or not flip and mcontroller.movingDirection() == -1 then
if args.actions["mechFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["dashAttackRight"] then
tech.setAnimationState("movement", "backWalkDash")
elseif args.actions["dashAttackLeft"] then
tech.setAnimationState("movement", "backWalkDash")
else
tech.setAnimationState("movement", "backWalk")
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["dashAttackRight"] then
tech.setAnimationState("movement", "walkDash")
elseif args.actions["dashAttackLeft"] then
tech.setAnimationState("movement", "walkDash")
else
tech.setAnimationState("movement", "walk")
end
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "idleAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "idleAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "idleAttack")
else
tech.setAnimationState("movement", "idle")
end
end
local telekinesisProjectile = tech.parameter("telekinesisProjectile")
local telekinesisProjectileConfig = tech.parameter("telekinesisProjectileConfig")
local telekinesisFireCycle = tech.parameter("telekinesisFireCycle")
local energyUsagePerSecondTelekinesis = tech.parameter("energyUsagePerSecondTelekinesis")
local energyUsageTelekinesis = energyUsagePerSecondTelekinesis * args.dt
if self.active and args.actions["grab"] and not self.grabbed then
local monsterIds = world.monsterQuery(tech.aimPosition(), 5)
for i,v in pairs(monsterIds) do
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 2, 1)
world.monsterQuery(tech.aimPosition(),5, { callScript = "lonesurvivor_grab", callScriptArgs = { tech.aimPosition() } })
break
end
self.grabbed = true
elseif self.grabbed and not args.actions["grab"] then
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 3, 1)
world.monsterQuery(tech.aimPosition(),30, { callScript = "lonesurvivor_release", callScriptArgs = { tech.aimPosition() } })
self.grabbed = false
elseif self.active and self.grabbed then
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 1, 1)
world.monsterQuery(tech.aimPosition(),15, { callScript = "lonesurvivor_move", callScriptArgs = { tech.aimPosition() } })
end
if args.actions["grab"] and status.resource("energy") > energyUsageTelekinesis then
if self.fireTimer <= 0 then
world.spawnProjectile(telekinesisProjectile, tech.aimPosition(), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, telekinesisProjectileConfig)
self.fireTimer = self.fireTimer + telekinesisFireCycle
tech.setAnimationState("telekinesis", "telekinesisOn")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > telekinesisFireCycle / 2 and self.fireTimer <= telekinesisFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyUsageTelekinesis)
end
if args.actions["mechFire"] and status.resource("energy") > energyCostPerSecondPrim then
if self.fireTimer <= 0 then
world.spawnProjectile(mechProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechProjectileConfig)
self.fireTimer = self.fireTimer + mechFireCycle
tech.setAnimationState("frontFiring", "fire")
--tech.setParticleEmitterActive("jetpackParticles3", true)
-- local startPoint = vec2.add(mcontroller.position(), tech.partPoint("frontGun", "firePoint"))
-- local endPoint = vec_add(mcontroller.position(), {tech.partPoint("frontDashGun", "firePoint")[1] + mechGunBeamMaxRange * math.cos(aimAngle), tech.partPoint("frontDashGun", "firePoint")[2] + mechGunBeamMaxRange * math.sin(aimAngle) })
-- local beamCollision = progressiveLineCollision(startPoint, endPoint, mechGunBeamStep)
-- randomProjectileLine(startPoint, beamCollision, mechGunBeamStep, mechGunBeamSmokeProkectile, 0.08)
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechFireCycle / 2 and self.fireTimer <= mechFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondPrim)
end
if not args.actions["mechFire"] then
--tech.setParticleEmitterActive("jetpackParticles3", false)
end
if args.actions["mechAltFire"] and status.resource("energy") > energyCostPerSecondAlt then
if self.fireTimer <= 0 then
world.spawnProjectile(mechAltProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontAltGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig)
self.fireTimer = self.fireTimer + mechAltFireCycle
tech.setAnimationState("frontAltFiring", "fireAlt")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechAltFireCycle / 2 and self.fireTimer <= mechAltFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondAlt)
end
if args.actions["mechSecFire"] and status.resource("energy") > energyCostPerSecondSec then
if self.fireTimer <= 0 then
world.spawnProjectile(mechSecProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontSecGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig)
self.fireTimer = self.fireTimer + mechSecFireCycle
tech.setAnimationState("frontSecFiring", "fireSec")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechSecFireCycle / 2 and self.fireTimer <= mechSecFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondSec)
end
local jetpackSpeed = tech.parameter("jetpackSpeed")
local jetpackControlForce = tech.parameter("jetpackControlForce")
local energyUsagePerSecond = tech.parameter("energyUsagePerSecond")
local energyUsage = energyUsagePerSecond * args.dt
if status.resource("energy") < energyUsage then
self.ranOut = true
elseif mcontroller.onGround() or mcontroller.liquidMovement() then
self.ranOut = false
end
if args.actions["jetpack"] and not self.ranOut then
tech.setAnimationState("jetpack", "on")
mcontroller.controlApproachYVelocity(jetpackSpeed, jetpackControlForce, true)
return tech.consumeTechEnergy(energyUsage)
else
tech.setAnimationState("jetpack", "off")
return 0
end
-- local levitateSpeed = tech.parameter("levitateSpeed")
-- local levitateControlForce = tech.parameter("levitateControlForce")
-- local energyUsagePerSecondLevitate = tech.parameter("energyUsagePerSecondLevitate")
-- local energyUsagelevitate = energyUsagePerSecondLevitate * args.dt
-- if args.availableEnergy < energyUsagelevitate then
-- self.ranOut = true
-- elseif mcontroller.onGround() or mcontroller.liquidMovement() then
-- self.ranOut = false
-- end
-- if args.actions["levitate"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- self.levitateActivated = true
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitatehover"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleft"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleftup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleftdown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateright"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitaterightup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitaterightdown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0,5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitatedown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- else
-- self.levitateActivated = false
-- tech.setAnimationState("levitate", "off")
-- return 0
-- end
--return energyCostPerSecond * args.dt
end
return 0
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Bastok_Mines/npcs/Detzo.lua | 17 | 2392 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Detzo
-- Starts & Finishes Quest: Rivals
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
Rivals = player:getQuestStatus(BASTOK,RIVALS);
if (Rivals == QUEST_ACCEPTED) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
count = trade:getItemCount();
MythrilSallet = trade:hasItemQty(12417,1);
if (MythrilSallet == true and count == 1) then
-- You retain the Mythril Sallet after trading it to Detzo
player:startEvent(0x005e);
end
else
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE, 13571);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Rivals = player:getQuestStatus(BASTOK,RIVALS);
if (player:getVar("theTalekeeperGiftCS") == 1) then
player:startEvent(0x00ab);
player:setVar("theTalekeeperGiftCS",2);
elseif (Rivals == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >= 3) then
player:startEvent(0x005d);
elseif (Rivals == QUEST_ACCEPTED) then
player:showText(npc,10311);
else
player:startEvent(0x001e);
end
end;
-- 0x0001 0x001e 0x005d 0x005e 0x00ab 0x03f2 0x00b0 0x00b4 0x00b8
-----------------------------------
-- 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 == 0x005d) then
player:addQuest(BASTOK,RIVALS);
elseif (csid == 0x005e) then
player:addTitle(CONTEST_RIGGER);
player:addItem(13571);
player:messageSpecial(ITEM_OBTAINED,13571);
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,RIVALS);
end
end; | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.