repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278 values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15 values |
|---|---|---|---|---|---|
jshackley/darkstar | scripts/zones/Bibiki_Bay/npcs/qm1.lua | 17 | 1388 | -----------------------------------
-- Area: Bibiki Bay
-- NPC: ??? (qm1)
-- Notes: Used to spawn Shen
-- @pos -115.108 0.300 -724.664 4
-----------------------------------
package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bibiki_Bay/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local Shen = 16793859;
-- Trade Shrimp Lantern
if (GetMobAction(Shen) == 0 and trade:hasItemQty(1823,1) and trade:getItemCount() == 1) then
player:tradeComplete();
SpawnMob(Shen,180):updateClaim(player);
SpawnMob(Shen+1,180):updateClaim(player);
SpawnMob(Shen+2,180):updateClaim(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 |
goksie/newfies-dialer | lua/newfies.lua | 4 | 3187 | --
-- 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>
--
package.path = package.path .. ";/usr/share/newfies-lua/?.lua";
package.path = package.path .. ";/usr/share/newfies-lua/libs/?.lua";
require "fsm_callflow"
require "debugger"
--Init debug and fs_env
local debug_mode = false
local fs_env = true
local OptionParser = require "pythonic.optparse" . OptionParser
local opt = OptionParser{usage="%prog [options] [gzip-file...]",
version="newfies-dialer-lua Version 1.0", add_help_option=false}
opt.add_option{
"-h", "--help", action="store_true", dest="help",
help="Newfies-Dialer voice application FSM"}
opt.add_option{
"-n", "--nofs", action="store_true", dest="nofs",
help="Select the environement to run the script, as command line, you might want to run this with --nofs"}
local options, args = opt.parse_args()
if options.help then opt.print_help(); os.exit(1) end
-- Set if the environment is FreeSWITCH
if options.nofs then
fs_env = false
end
local debugger = Debugger(fs_env)
if not fs_env then
require "session"
session = Session()
end
local callflow = FSMCall(session, debug_mode, debugger)
-- This function simply tells us what function are available in Session
-- It just prints a list of all functions. We may be able to find functions
-- that have not yet been documented but are useful. I did :)
-- function printSessionFunctions( session )
-- metatbl = getmetatable(session)
-- if not metatbl then return nil end
-- local f=metatbl['.fn'] -- gets the functions table
-- if not f then return nil end
-- print("\n***Session Functions***\n")
-- for k,v in pairs(f) do print(k,v) end
-- print("\n\n")
-- end
-- new_session = freeswitch.Session() -- create a blank session
-- printSessionFunctions(new_session)
function myHangupHook(s, status, arg)
--debug("NOTICE", "myHangupHook: status -> " .. status .. "\n")
local obCause = session:hangupCause()
-- debug("INFO", "session:hangupCause() = " .. obCause )
if not callflow.hangup_trigger then
-- End call
callflow:end_call()
end
error()
end
if session:ready() then
local res = callflow:init()
if res then
--Answer the call
session:answer()
session:setHangupHook("myHangupHook")
-- session:streamFile("/usr/share/newfies_ramdisk/tts/flite_520f6ec9707bfe353662697257068b5e.wav")
--Start the FSM
callflow:start_call()
local loop = 0
--While the session is ready and call is not ended loop
while session:ready() and not callflow.call_ended and loop < 1000 do
loop = loop + 1
-- Loop on the State Machine to find the next node to proceed
callflow:next_node()
end
end
-- End call
callflow:end_call()
end
error(_die)
| mpl-2.0 |
wolf9s/packages | net/smartsnmpd/files/mibs/system.lua | 158 | 6428 | --
-- This file is part of SmartSNMP
-- Copyright (C) 2014, Credo Semiconductor Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program; if not, write to the Free Software Foundation, Inc.,
-- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--
local mib = require "smartsnmp"
local uci = require "uci"
-- System config
local context = uci.cursor("/etc/config", "/tmp/.uci")
-- scalar index
local sysDesc = 1
local sysObjectID = 2
local sysUpTime = 3
local sysContact = 4
local sysName = 5
local sysLocation = 6
local sysServices = 7
local sysORLastChange = 8
-- table index
local sysORTable = 9
-- entry index
local sysOREntry = 1
-- list index
local sysORIndex = 1
local sysORID = 2
local sysORDesc = 3
local sysORUpTime = 4
local startup_time = 0
local or_last_changed_time = 0
local function mib_system_startup(time)
startup_time = time
or_last_changed_time = time
end
mib_system_startup(os.time())
local sysGroup = {}
local or_oid_cache = {}
local or_index_cache = {}
local or_table_cache = {}
local or_table_reg = function (oid, desc)
local row = {}
row['oid'] = {}
for i in string.gmatch(oid, "%d") do
table.insert(row['oid'], tonumber(i))
end
row['desc'] = desc
row['uptime'] = os.time()
table.insert(or_table_cache, row)
or_last_changed_time = os.time()
or_oid_cache[oid] = #or_table_cache
or_index_cache = {}
for i in ipairs(or_table_cache) do
table.insert(or_index_cache, i)
end
end
local or_table_unreg = function (oid)
local or_idx = or_oid_cache[oid]
if or_table_cache[or_idx] ~= nil then
table.remove(or_table_cache, or_idx)
or_last_changed_time = os.time()
or_index_cache = {}
for i in ipairs(or_table_cache) do
table.insert(or_index_cache, i)
end
end
end
local last_load_time = os.time()
local function need_to_reload()
if os.difftime(os.time(), last_load_time) < 3 then
return false
else
last_load_time = os.time()
return true
end
end
local function load_config()
if need_to_reload() == true then
context:load("smartsnmpd")
end
end
context:load("smartsnmpd")
local sysMethods = {
["or_table_reg"] = or_table_reg,
["or_table_unreg"] = or_table_unreg
}
mib.module_method_register(sysMethods)
sysGroup = {
rocommunity = 'public',
[sysDesc] = mib.ConstString(function () load_config() return mib.sh_call("uname -a") end),
[sysObjectID] = mib.ConstOid(function ()
load_config()
local oid
local objectid
context:foreach("smartsnmpd", "smartsnmpd", function (s)
objectid = s.objectid
end)
if objectid ~= nil then
oid = {}
for i in string.gmatch(objectid, "%d+") do
table.insert(oid, tonumber(i))
end
end
return oid
end),
[sysUpTime] = mib.ConstTimeticks(function () load_config() return os.difftime(os.time(), startup_time) * 100 end),
[sysContact] = mib.ConstString(function ()
load_config()
local contact
context:foreach("smartsnmpd", "smartsnmpd", function (s)
contact = s.contact
end)
return contact
end),
[sysName] = mib.ConstString(function () load_config() return mib.sh_call("uname -n") end),
[sysLocation] = mib.ConstString(function ()
load_config()
local location
context:foreach("smartsnmpd", "smartsnmpd", function (s)
location = s.location
end)
return location
end),
[sysServices] = mib.ConstInt(function ()
load_config()
local services
context:foreach("smartsnmpd", "smartsnmpd", function (s)
services = tonumber(s.services)
end)
return services
end),
[sysORLastChange] = mib.ConstTimeticks(function () load_config() return os.difftime(os.time(), or_last_changed_time) * 100 end),
[sysORTable] = {
[sysOREntry] = {
[sysORIndex] = mib.UnaIndex(function () load_config() return or_index_cache end),
[sysORID] = mib.ConstOid(function (i) load_config() return or_table_cache[i].oid end),
[sysORDesc] = mib.ConstString(function (i) load_config() return or_table_cache[i].desc end),
[sysORUpTime] = mib.ConstTimeticks(function (i) load_config() return os.difftime(os.time(), or_table_cache[i].uptime) * 100 end),
}
}
}
return sysGroup
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Norg/npcs/Washu.lua | 17 | 3574 | -----------------------------------
-- Area: Norg
-- NPC: Washu
-- Involved in Quest: Yomi Okuri
-- Starts and finishes Quest: Stop Your Whining
-- @pos 49 -6 15 252
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(OUTLANDS,YOMI_OKURI) == QUEST_ACCEPTED and player:getVar("yomiOkuriCS") == 2) then
-- Trade Giant Sheep Meat, Frost Turnip, Bastore Sardine, Hecteyes Eye
if (trade:hasItemQty(4372,1) and trade:hasItemQty(4382,1) and (trade:hasItemQty(4360,1) or trade:hasItemQty(5792,1)) and trade:hasItemQty(939,1) and trade:getItemCount() == 4) then
player:startEvent(0x0096);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Whining = player:getQuestStatus(OUTLANDS,STOP_YOUR_WHINING);
mLvl = player:getMainLvl();
if (player:getQuestStatus(OUTLANDS,YOMI_OKURI) == QUEST_ACCEPTED) then
if (player:getVar("yomiOkuriCS") == 1) then
player:startEvent(0x0094);
elseif (player:getVar("yomiOkuriCS") == 2) then
player:startEvent(0x0095);
elseif (player:getVar("yomiOkuriCS") >= 3) then
player:startEvent(0x0097);
end
elseif (Whining == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 4 and mLvl >= 10) then
player:startEvent(0x0015); --Start Quest
elseif (Whining == QUEST_ACCEPTED and player:hasKeyItem(EMPTY_BARREL) == true) then
player:startEvent(0x0016); --Reminder Dialogue
elseif (Whining == QUEST_ACCEPTED and player:hasKeyItem(BARREL_OF_OPOOPO_BREW) == true) then
player:startEvent(0x0017); --Finish Quest
elseif (Whining == QUEST_COMPLETED) then
player:startEvent(0x0018);
else
player:startEvent(0x0050);
end
end;
-- 0x0050 0x0015 0x0016 0x0017 0x0018 0x0094 0x0095 0x0096 0x0097 0x00d1 0x00d2 0x00dd 0x00de 0x00df
-----------------------------------
-- 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 == 0x0094) then
player:setVar("yomiOkuriCS",2);
elseif (csid == 0x0096) then
player:tradeComplete();
player:addKeyItem(WASHUS_TASTY_WURST);
player:messageSpecial(KEYITEM_OBTAINED,WASHUS_TASTY_WURST);
player:setVar("yomiOkuriCS",3);
elseif (csid == 0x0015 and option == 1) then
player:addKeyItem(EMPTY_BARREL); --Empty Barrel
player:addQuest(OUTLANDS,STOP_YOUR_WHINING);
player:messageSpecial(KEYITEM_OBTAINED,EMPTY_BARREL);
elseif (csid == 0x0017) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4952);
else
player:delKeyItem(BARREL_OF_OPOOPO_BREW); --Filled Barrel
player:addItem(4952); -- Scroll of Hojo: Ichi
player:messageSpecial(ITEM_OBTAINED,4952); -- Scroll of Hojo: Ichi
player:addFame(OUTLANDS,NORG_FAME*75);
player:addTitle(APPRENTICE_SOMMELIER);
player:completeQuest(OUTLANDS,STOP_YOUR_WHINING);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Markets/npcs/Matthias.lua | 37 | 1050 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Matthias
-- Standard Info NPC
-- Involved in Quest:
-----------------------------------
require("scripts/globals/quests");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01f3);
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 |
LiberatorUSA/GUCEF | tests/gucefWEB_TestApp/premake4.lua | 2 | 1980 | --------------------------------------------------------------------
-- 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: gucefCOM_TestApp
project( "gucefCOM_TestApp" )
configuration( {} )
location( os.getenv( "PM4OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM4TARGETDIR" ) )
configuration( {} )
language( "C++" )
configuration( { "WIN32" } )
configuration( { WIN32 } )
kind( "WindowedApp" )
configuration( { "NOT WIN32" } )
configuration( {} )
kind( "ConsoleApp" )
configuration( {} )
links( { "gucefCOM", "gucefCOMCORE", "gucefCORE", "gucefMT" } )
links( { "gucefCOM", "gucefCOMCORE", "gucefCORE", "gucefMT" } )
configuration( {} )
vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/TestCode_CHTTPClient.h",
"include/TestCode_CHTTPServer.h"
} )
configuration( {} )
vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/gucefCOM_TestApp_main.cpp",
"src/TestCode_CHTTPClient.cpp",
"src/TestCode_CHTTPServer.cpp"
} )
configuration( {} )
includedirs( { "../../common/include", "../../gucefCOM/include", "../../gucefCOMCORE/include", "../../gucefCORE/include", "../../gucefMT/include", "include" } )
configuration( { "ANDROID" } )
includedirs( { "../../gucefCORE/include/android" } )
configuration( { "LINUX" } )
includedirs( { "../../gucefCORE/include/linux" } )
configuration( { "WIN32" } )
includedirs( { "../../gucefCOMCORE/include/mswin", "../../gucefCORE/include/mswin" } )
configuration( { "WIN64" } )
includedirs( { "../../gucefCOMCORE/include/mswin", "../../gucefCORE/include/mswin" } )
| apache-2.0 |
jshackley/darkstar | scripts/zones/Phomiuna_Aqueducts/npcs/_0r5.lua | 17 | 1326 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: Ornate Gate
-- @pos -95 -24 60 27
-----------------------------------
package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Phomiuna_Aqueducts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == DISTANT_BELIEFS and player:getVar("PromathiaStatus") == 2) then
player:startEvent(0x0024);
else
player:messageSpecial(NOTHING_OUT_HERE);
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 == 0x0024) then
player:setVar("PromathiaStatus",3);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Markets_[S]/npcs/Jagaris.lua | 36 | 4452 | -----------------------------------
-- Area: Bastok Markets [S]
-- NPC: Jagaris
-- Armor Storage NPC
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/armorstorage");
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
Deposit = 0x0148;
Withdrawl = 0x0149;
ArraySize = table.getn(StorageArray);
G1 = 0;
G2 = 0;
G3 = 0;
G4 = 0;
G5 = 0;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
for SetId = 1,ArraySize,11 do
TradeCount = trade:getItemCount();
T1 = trade:hasItemQty(StorageArray[SetId + 5],1);
if (T1 == true) then
if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then
if (TradeCount == StorageArray[SetId + 3]) then
T2 = trade:hasItemQty(StorageArray[SetId + 4],1);
T3 = trade:hasItemQty(StorageArray[SetId + 6],1);
T4 = trade:hasItemQty(StorageArray[SetId + 7],1);
T5 = trade:hasItemQty(StorageArray[SetId + 8],1);
if (StorageArray[SetId + 4] == 0) then
T2 = true;
end;
if (StorageArray[SetId + 6] == 0) then
T3 = true;
end;
if (StorageArray[SetId + 7] == 0) then
T4 = true;
end;
if (StorageArray[SetId + 8] == 0) then
T5 = true;
end;
if (T2 == true and T3 == true and T4 == true and T5 == true) then
player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]);
player:addKeyItem(StorageArray[SetId + 10]);
player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]);
break;
end;
end;
end;
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CurrGil = player:getGil();
for KeyItem = 11,ArraySize,11 do
if player:hasKeyItem(StorageArray[KeyItem]) then
if StorageArray[KeyItem - 9] == 1 then
G1 = G1 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 2 then
G2 = G2 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 3 then
G3 = G3 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 4 then
G4 = G4 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 6 then
G5 = G5 + StorageArray[KeyItem - 8];
end;
end;
end;
player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
if (csid == Withdrawl) then
player:updateEvent(StorageArray[option * 11 - 6],
StorageArray[option * 11 - 5],
StorageArray[option * 11 - 4],
StorageArray[option * 11 - 3],
StorageArray[option * 11 - 2],
StorageArray[option * 11 - 1]);
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == Withdrawl) then
if (option > 0 and option <= StorageArray[ArraySize] - 10) then
if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:addItem(StorageArray[option * 11 - Item],1);
player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
player:delKeyItem(StorageArray[option * 11]);
player:setGil(player:getGil() - StorageArray[option * 11 - 1]);
else
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
end;
end;
end;
if (csid == Deposit) then
player:tradeComplete();
end;
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Walls/npcs/HomePoint#2.lua | 17 | 1255 | -----------------------------------
-- Area: Windurst Walls
-- NPC: HomePoint#2
-- @pos -212 0.001 -99 239
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Walls/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 20);
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 |
LiberatorUSA/GUCEF | plugins/CORE/codecspluginZLIB/premake5.lua | 11 | 2286 | --------------------------------------------------------------------
-- 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: codecspluginZLIB
project( "codecspluginZLIB" )
configuration( {} )
location( os.getenv( "PM5OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM5TARGETDIR" ) )
configuration( {} )
language( "C" )
configuration( {} )
kind( "SharedLib" )
configuration( {} )
links( { "gucefCORE", "gucefMT", "zlib" } )
configuration( {} )
defines( { "GUCEF_CODECPLUGIN_BUILD_MODULE" } )
links( { "z" } )
configuration( { LINUX32 } )
links( { "zlib" } )
links( { "zlib" } )
configuration( { LINUX64 } )
links( { "zlib" } )
links( { "zlib" } )
configuration( { WIN32 } )
links( { "zlib" } )
links( { "zlib" } )
configuration( { WIN64 } )
links( { "zlib" } )
links( { "zlib" } )
configuration( {} )
vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/codecspluginZLIB.h",
"include/codecspluginZLIB_config.h",
"include/codecspluginZLIB_macros.h"
} )
configuration( {} )
vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/codecspluginZLIB.c"
} )
configuration( {} )
includedirs( { "../../../common/include", "../../../platform/gucefCORE/include", "../../../platform/gucefMT/include", "include" } )
configuration( { "ANDROID" } )
includedirs( { "../../../platform/gucefCORE/include/android" } )
configuration( { "LINUX32" } )
includedirs( { "../../../dependencies/zlib", "../../../platform/gucefCORE/include/linux" } )
configuration( { "LINUX64" } )
includedirs( { "../../../dependencies/zlib", "../../../platform/gucefCORE/include/linux" } )
configuration( { "WIN32" } )
includedirs( { "../../../dependencies/zlib", "../../../platform/gucefCORE/include/mswin" } )
configuration( { "WIN64" } )
includedirs( { "../../../dependencies/zlib", "../../../platform/gucefCORE/include/mswin" } )
| apache-2.0 |
jshackley/darkstar | scripts/zones/Hall_of_the_Gods/npcs/Shimmering_Circle.lua | 17 | 1789 | -----------------------------------
-- Area: Hall of the Gods
-- NPC: Shimmering Circle
-- Lifts players up to the sky!
-- @pos 0 -20 147 251
-----------------------------------
package.loaded["scripts/zones/Hall_of_the_Gods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Hall_of_the_Gods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ZilartProgress = player:getCurrentMission(ZILART);
local ZVar = player:getVar("ZilartStatus");
if (player:getZPos() < 200) then
if (ZilartProgress == THE_GATE_OF_THE_GODS and ZVar == 0) then
player:startEvent(0x0003); -- First time.
elseif (ZilartProgress ~= 255 and ZilartProgress > THE_GATE_OF_THE_GODS or -- If player has not done any ZM, Progress == 255
(ZilartProgress == THE_GATE_OF_THE_GODS and ZVar > 0)) then
player:startEvent(0x000a);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
else
player:startEvent(0x000b);
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 == 0x0003) then
player:setVar("ZilartStatus",1);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/The_Shrine_of_RuAvitau/npcs/qm2.lua | 2 | 1600 | -----------------------------------
-- Area: The Shrine of Ru'Avitau
-- NPC: ??? (Spawn Kirin)
-- @pos -81 32 2 178
-----------------------------------
package.loaded["scripts/zones/The_Shrine_of_RuAvitau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Shrine_of_RuAvitau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Validate traded items are all needed seals and ensure Kirin is not alive
if (GetMobAction(17506670) == 0 and trade:hasItemQty(1404, 1) and trade:hasItemQty(1405, 1) and trade:hasItemQty(1406, 1) and trade:hasItemQty(1407, 1) and trade:getItemCount() == 4) then
-- Complete the trade..
player:tradeComplete();
-- Spawn Kirin..
local mob = SpawnMob(17506670, 180);
player:showText(npc, KIRIN_OFFSET);
mob:updateClaim(player);
npc:setStatus(STATUS_DISAPPEAR);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0064);
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/globals/abilities/wizards_roll.lua | 9 | 2874 | -----------------------------------
-- Ability: Wizard's Roll
-- Enhances magic attack for party members within area of effect
-- Optimal Job: Black Mage
-- Lucky Number: 5
-- Unlucky Number: 9
-- Level 58
--
-- Die Roll |No BLM |With BLM
-- -------- -------- -----------
-- 1 |+2 |+6
-- 2 |+3 |+6
-- 3 |+4 |+7
-- 4 |+4 |+7
-- 5 |+10 |+13
-- 6 |+5 |+8
-- 7 |+6 |+9
-- 8 |+7 |+9
-- 9 |+1 |+5
-- 10 |+7 |+10
-- 11 |+12 |+16
-- Bust |-4 |-4
--
-- If the Corsair is a lower level than the player receiving Wizard's Roll, the +MAB will be reduced
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = getCorsairRollEffect(ability:getID());
ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE));
if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
else
player:setLocalVar("BLM_roll_bonus", 0);
return 0,0;
end
end;
-----------------------------------
-- onUseAbilityRoll
-----------------------------------
function onUseAbilityRoll(caster,target,ability,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {2, 3, 4, 4, 10, 5, 6, 7, 1, 7, 12, 4};
local effectpower = effectpowers[total]
local jobBonus = caster:getLocalVar("BLM_roll_bonus");
if (total < 12) then -- see chaos_roll.lua for comments
if (jobBonus == 0) then
if (caster:hasPartyJob(JOB_BLM) or math.random(0, 99) < caster:getMod(MOD_JOB_BONUS_CHANCE)) then
jobBonus = 1;
else
jobBonus = 2;
end
end
if (jobBonus == 1) then
effectpower = effectpower + 3;
end
if (target:getID() == caster:getID()) then
caster:setLocalVar("BLM_roll_bonus", jobBonus);
end
end
if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_WIZARDS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_MATT) == false) then
ability:setMsg(423);
end
end; | gpl-3.0 |
VincentGong/chess | cocos2d-x/tests/lua-tests/src/TransitionsTest/TransitionsTest.lua | 5 | 10704 | require "src/TransitionsTest/TransitionsName"
local SceneIdx = -1
local CurSceneNo = 2
local TRANSITION_DURATION = 1.2
local s = cc.Director:getInstance():getWinSize()
local function switchSceneTypeNo()
if CurSceneNo == 1 then
CurSceneNo = 2
else
CurSceneNo = 1
end
end
local function backAction()
SceneIdx = SceneIdx - 1
if SceneIdx < 0 then
SceneIdx = SceneIdx + Transition_Table.MAX_LAYER
end
switchSceneTypeNo()
return generateTranScene()
end
local function restartAction()
return generateTranScene()
end
local function nextAction()
SceneIdx = SceneIdx + 1
SceneIdx = math.mod(SceneIdx, Transition_Table.MAX_LAYER)
switchSceneTypeNo()
return generateTranScene()
end
local function backCallback(sender)
local scene = backAction()
cc.Director:getInstance():replaceScene(scene)
end
local function restartCallback(sender)
local scene = restartAction()
cc.Director:getInstance():replaceScene(scene)
end
local function nextCallback(sender)
local scene = nextAction()
cc.Director:getInstance():replaceScene(scene)
end
-----------------------------
-- TestLayer1
-----------------------------
local function createLayer1()
local layer = cc.Layer:create()
local x, y = s.width, s.height
local bg1 = cc.Sprite:create(s_back1)
bg1:setPosition(cc.p(s.width / 2, s.height / 2))
layer:addChild(bg1, -1)
local titleLabel = cc.Label:createWithTTF(Transition_Name[SceneIdx], s_thonburiPath, 32)
layer:addChild(titleLabel)
titleLabel:setColor(cc.c3b(255,32,32))
titleLabel:setAnchorPoint(cc.p(0.5, 0.5))
titleLabel:setPosition(x / 2, y - 100)
local label = cc.Label:createWithTTF("SCENE 1", s_markerFeltFontPath, 38)
label:setColor(cc.c3b(16,16,255))
label:setAnchorPoint(cc.p(0.5, 0.5))
label:setPosition(x / 2, y / 2)
layer:addChild(label)
-- menu
local item1 = cc.MenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = cc.MenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = cc.MenuItemImage:create(s_pPathF1, s_pPathF2)
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
local menu = cc.Menu:create()
menu:addChild(item1)
menu:addChild(item2)
menu:addChild(item3)
menu:setPosition(cc.p(0, 0))
item1:setPosition(cc.p(s.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2))
item2:setPosition(cc.p(s.width / 2, item2:getContentSize().height / 2))
item3:setPosition(cc.p(s.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2))
layer:addChild(menu, 1)
return layer
end
-----------------------------
-- TestLayer2
-----------------------------
local function createLayer2()
local layer = cc.Layer:create()
local x, y = s.width, s.height
local bg1 = cc.Sprite:create(s_back2)
bg1:setPosition(cc.p(s.width / 2, s.height / 2))
layer:addChild(bg1, -1)
local titleLabel = cc.Label:createWithTTF(Transition_Name[SceneIdx], s_thonburiPath, 32 )
layer:addChild(titleLabel)
titleLabel:setAnchorPoint(cc.p(0.5, 0.5))
titleLabel:setColor(cc.c3b(255,32,32))
titleLabel:setPosition(x / 2, y - 100)
local label = cc.Label:createWithTTF("SCENE 2", s_markerFeltFontPath, 38)
label:setColor(cc.c3b(16,16,255))
label:setAnchorPoint(cc.p(0.5, 0.5))
label:setPosition(x / 2, y / 2)
layer:addChild(label)
-- menu
local item1 = cc.MenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = cc.MenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = cc.MenuItemImage:create(s_pPathF1, s_pPathF2)
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
local menu = cc.Menu:create()
menu:addChild(item1)
menu:addChild(item2)
menu:addChild(item3)
menu:setPosition(cc.p(0, 0))
item1:setPosition(cc.p(s.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2))
item2:setPosition(cc.p(s.width / 2, item2:getContentSize().height / 2))
item3:setPosition(cc.p(s.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2))
layer:addChild(menu, 1)
return layer
end
-----------------------------
-- Create Transition Test
-----------------------------
local function createTransition(index, t, scene)
cc.Director:getInstance():setDepthTest(false)
if firstEnter == true then
firstEnter = false
return scene
end
if index == Transition_Table.CCTransitionJumpZoom then
scene = cc.TransitionJumpZoom:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressRadialCCW then
scene = cc.TransitionProgressRadialCCW:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressRadialCW then
scene = cc.TransitionProgressRadialCW:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressHorizontal then
scene = cc.TransitionProgressHorizontal:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressVertical then
scene = cc.TransitionProgressVertical:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressInOut then
scene = cc.TransitionProgressInOut:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressOutIn then
scene = cc.TransitionProgressOutIn:create(t, scene)
elseif index == Transition_Table.CCTransitionCrossFade then
scene = cc.TransitionCrossFade:create(t, scene)
elseif index == Transition_Table.TransitionPageForward then
cc.Director:getInstance():setDepthTest(true)
scene = cc.TransitionPageTurn:create(t, scene, false)
elseif index == Transition_Table.TransitionPageBackward then
cc.Director:getInstance():setDepthTest(true)
scene = cc.TransitionPageTurn:create(t, scene, true)
elseif index == Transition_Table.CCTransitionFadeTR then
scene = cc.TransitionFadeTR:create(t, scene)
elseif index == Transition_Table.CCTransitionFadeBL then
scene = cc.TransitionFadeBL:create(t, scene)
elseif index == Transition_Table.CCTransitionFadeUp then
scene = cc.TransitionFadeUp:create(t, scene)
elseif index == Transition_Table.CCTransitionFadeDown then
scene = cc.TransitionFadeDown:create(t, scene)
elseif index == Transition_Table.CCTransitionTurnOffTiles then
scene = cc.TransitionTurnOffTiles:create(t, scene)
elseif index == Transition_Table.CCTransitionSplitRows then
scene = cc.TransitionSplitRows:create(t, scene)
elseif index == Transition_Table.CCTransitionSplitCols then
scene = cc.TransitionSplitCols:create(t, scene)
elseif index == Transition_Table.CCTransitionFade then
scene = cc.TransitionFade:create(t, scene)
elseif index == Transition_Table.FadeWhiteTransition then
scene = cc.TransitionFade:create(t, scene, cc.c3b(255, 255, 255))
elseif index == Transition_Table.FlipXLeftOver then
scene = cc.TransitionFlipX:create(t, scene, cc.TRANSITION_ORIENTATION_LEFT_OVER )
elseif index == Transition_Table.FlipXRightOver then
scene = cc.TransitionFlipX:create(t, scene, cc.TRANSITION_ORIENTATION_RIGHT_OVER )
elseif index == Transition_Table.FlipYUpOver then
scene = cc.TransitionFlipY:create(t, scene, cc.TRANSITION_ORIENTATION_UP_OVER)
elseif index == Transition_Table.FlipYDownOver then
scene = cc.TransitionFlipY:create(t, scene, cc.TRANSITION_ORIENTATION_DOWN_OVER )
elseif index == Transition_Table.FlipAngularLeftOver then
scene = cc.TransitionFlipAngular:create(t, scene, cc.TRANSITION_ORIENTATION_LEFT_OVER )
elseif index == Transition_Table.FlipAngularRightOver then
scene = cc.TransitionFlipAngular:create(t, scene, cc.TRANSITION_ORIENTATION_RIGHT_OVER )
elseif index == Transition_Table.ZoomFlipXLeftOver then
scene = cc.TransitionZoomFlipX:create(t, scene, cc.TRANSITION_ORIENTATION_LEFT_OVER )
elseif index == Transition_Table.ZoomFlipXRightOver then
scene = cc.TransitionZoomFlipX:create(t, scene, cc.TRANSITION_ORIENTATION_RIGHT_OVER )
elseif index == Transition_Table.ZoomFlipYUpOver then
scene = cc.TransitionZoomFlipY:create(t, scene, cc.TRANSITION_ORIENTATION_UP_OVER)
elseif index == Transition_Table.ZoomFlipYDownOver then
scene = cc.TransitionZoomFlipY:create(t, scene, cc.TRANSITION_ORIENTATION_DOWN_OVER )
elseif index == Transition_Table.ZoomFlipAngularLeftOver then
scene = cc.TransitionZoomFlipAngular:create(t, scene, cc.TRANSITION_ORIENTATION_LEFT_OVER )
elseif index == Transition_Table.ZoomFlipAngularRightOver then
scene = cc.TransitionZoomFlipAngular:create(t, scene, cc.TRANSITION_ORIENTATION_RIGHT_OVER )
elseif index == Transition_Table.CCTransitionShrinkGrow then
scene = cc.TransitionShrinkGrow:create(t, scene)
elseif index == Transition_Table.CCTransitionRotoZoom then
scene = cc.TransitionRotoZoom:create(t, scene)
elseif index == Transition_Table.CCTransitionMoveInL then
scene = cc.TransitionMoveInL:create(t, scene)
elseif index == Transition_Table.CCTransitionMoveInR then
scene = cc.TransitionMoveInR:create(t, scene)
elseif index == Transition_Table.CCTransitionMoveInT then
scene = cc.TransitionMoveInT:create(t, scene)
elseif index == Transition_Table.CCTransitionMoveInB then
scene = cc.TransitionMoveInB:create(t, scene)
elseif index == Transition_Table.CCTransitionSlideInL then
scene = cc.TransitionSlideInL:create(t, scene)
elseif index == Transition_Table.CCTransitionSlideInR then
scene = cc.TransitionSlideInR:create(t, scene)
elseif index == Transition_Table.CCTransitionSlideInT then
scene = cc.TransitionSlideInT:create(t, scene)
elseif index == Transition_Table.CCTransitionSlideInB then
scene = cc.TransitionSlideInB:create(t, scene)
end
return scene
end
function generateTranScene()
local scene = cc.Scene:create()
local layer = nil
if CurSceneNo == 1 then
layer = createLayer1()
elseif CurSceneNo == 2 then
layer = createLayer2()
end
scene:addChild(layer)
scene:addChild(CreateBackMenuItem())
return createTransition(SceneIdx, TRANSITION_DURATION, scene)
end
function TransitionsTest()
cclog("TransitionsTest")
local scene = cc.Scene:create()
SceneIdx = -1
CurSceneNo = 2
firstEnter = true
return nextAction()
end
| mit |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/LoadingBar.lua | 4 | 2688 |
--------------------------------
-- @module LoadingBar
-- @extend Widget
--------------------------------
-- @function [parent=#LoadingBar] setPercent
-- @param self
-- @param #float float
--------------------------------
-- @function [parent=#LoadingBar] loadTexture
-- @param self
-- @param #string str
-- @param #ccui.Widget::TextureResType texturerestype
--------------------------------
-- @function [parent=#LoadingBar] setDirection
-- @param self
-- @param #ccui.LoadingBar::Direction direction
--------------------------------
-- @function [parent=#LoadingBar] setScale9Enabled
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#LoadingBar] setCapInsets
-- @param self
-- @param #rect_table rect
--------------------------------
-- @function [parent=#LoadingBar] getDirection
-- @param self
-- @return LoadingBar::Direction#LoadingBar::Direction ret (return value: ccui.LoadingBar::Direction)
--------------------------------
-- @function [parent=#LoadingBar] getCapInsets
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)
--------------------------------
-- @function [parent=#LoadingBar] isScale9Enabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#LoadingBar] getPercent
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- overload function: create(string, float)
--
-- overload function: create()
--
-- @function [parent=#LoadingBar] create
-- @param self
-- @param #string str
-- @param #float float
-- @return LoadingBar#LoadingBar ret (retunr value: ccui.LoadingBar)
--------------------------------
-- @function [parent=#LoadingBar] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)
--------------------------------
-- @function [parent=#LoadingBar] getVirtualRenderer
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
-- @function [parent=#LoadingBar] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @function [parent=#LoadingBar] getVirtualRendererSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- @function [parent=#LoadingBar] ignoreContentAdaptWithSize
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#LoadingBar] LoadingBar
-- @param self
return nil
| mit |
jshackley/darkstar | scripts/globals/weaponskills/shining_blade.lua | 30 | 1336 | -----------------------------------
-- Shining Blade
-- Sword weapon skill
-- Skill Level: 100
-- Deals light elemental damage to enemy. Damage varies with TP.
-- Aligned with the Soil Gorget.
-- Aligned with the Soil Belt.
-- Element: Light
-- Modifiers: STR:40% ; MND:40%
-- 100%TP 200%TP 300%TP
-- 1.125 2.222 3.523
-----------------------------------
require("scripts/globals/magic");
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 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.2; params.chr_wsc = 0.0;
params.ele = ELE_LIGHT;
params.skill = SKILL_SWD;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.125; params.ftp200 = 2.222; params.ftp300 = 3.523;
params.str_wsc = 0.4; params.mnd_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/turbo | turbo/escape.lua | 8 | 7852 | --- Turbo.lua Escape module
--
-- Copyright John Abrahamsen 2011, 2012, 2013 < JhnAbrhmsn@gmail.com >
--
-- "Permission is hereby granted, free of charge, to any person obtaining a copy of
-- this software and associated documentation files (the "Software"), to deal in
-- the Software without restriction, including without limitation the rights to
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do
-- so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE."
local json = require('turbo.3rdparty.JSON')
local escape = {} -- escape namespace
--- JSON stringify a table.
-- @param t Value to JSON encode.
-- @note May raise a error if table could not be decoded.
function escape.json_encode(t)
return json:encode(t)
end
--- Decode a JSON string to table.
-- @param s (String) JSON enoded string to decode into
-- Lua primitives.
-- @return (Table)
function escape.json_decode(s)
return json:decode(s)
end
local function _unhex(hex) return string.char(tonumber(hex, 16)) end
--- Unescape a escaped hexadecimal representation string.
-- @param s (String) String to unescape.
function escape.unescape(s)
return string.gsub(s, "%%(%x%x)", _unhex)
end
local function _hex(c)
return string.format("%%%02x", string.byte(c))
end
--- Encodes a string into its escaped hexadecimal representation.
-- @param s (String) String to escape.
function escape.escape(s)
return string.gsub(s, "([^A-Za-z0-9_])", _hex)
end
--- Encodes the HTML entities in a string. Helpfull to avoid XSS.
-- @param s (String) String to escape.
function escape.html_escape(s)
assert("Expected string in argument #1.")
return (string.gsub(s, "[}{\">/<'&]", {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
["/"] = "/"
}))
end
-- Remove trailing and leading whitespace from string.
-- @param s String
function escape.trim(s)
-- from PiL2 20.4
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
-- Remove leading whitespace from string.
-- @param s String
function escape.ltrim(s)
return (s:gsub("^%s*", ""))
end
-- Remove trailing whitespace from string.
-- @param s String
function escape.rtrim(s)
local n = #s
while n > 0 and s:find("^%s", n) do n = n - 1 end
return s:sub(1, n)
end
----- Very Fast MIME BASE64 Encoding / Decoding Routines
--------------- authored by Jeff Solinsky
do
local ffi = require'ffi'
local bit = jit and require "bit" or require "bit32"
local rshift = bit.rshift
local lshift = bit.lshift
local bor = bit.bor
local band = bit.band
local floor = math.floor
local mime64chars = ffi.new("uint8_t[64]",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
local mime64lookup = ffi.new("uint8_t[256]")
ffi.fill(mime64lookup, 256, 0xFF)
for i=0,63 do
mime64lookup[mime64chars[i]]=i
end
local u8arr= ffi.typeof'uint8_t[?]'
local u8ptr=ffi.typeof'uint8_t*'
--- Base64 decode a string or a FFI char *.
-- @param str (String or char*) Bytearray to decode.
-- @param sz (Number) Length of string to decode, optional if str is a Lua string
-- @return (String) Decoded string.
function escape.base64_decode(str, sz)
if (type(str)=="string") and (sz == nil) then sz=#str end
local m64, b1 -- value 0 to 63, partial byte
local bin_arr=ffi.new(u8arr, floor(bit.rshift(sz*3,2)))
local mptr = ffi.cast(u8ptr,bin_arr) -- position in binary mime64 output array
local bptr = ffi.cast(u8ptr,str)
local i = 0
while true do
repeat
if i >= sz then goto done end
m64 = mime64lookup[bptr[i]]
i=i+1
until m64 ~= 0xFF -- skip non-mime characters like newlines
b1=lshift(m64, 2)
repeat
if i >= sz then goto done end
m64 = mime64lookup[bptr[i]]
i=i+1
until m64 ~= 0xFF -- skip non-mime characters like newlines
mptr[0] = bor(b1,rshift(m64, 4)); mptr=mptr+1
b1 = lshift(m64,4)
repeat
if i >= sz then goto done end
m64 = mime64lookup[bptr[i]]
i=i+1
until m64 ~= 0xFF -- skip non-mime characters like newlines
mptr[0] = bor(b1,rshift(m64, 2)); mptr=mptr+1
b1 = lshift(m64,6)
repeat
if i >= sz then goto done end
m64 = mime64lookup[bptr[i]]
i=i+1
until m64 ~= 0xFF -- skip non-mime characters like newlines
mptr[0] = bor(b1, m64); mptr=mptr+1
end
::done::
return ffi.string(bin_arr, (mptr-bin_arr))
end
local mime64shorts=ffi.new('uint16_t[4096]')
for i=0,63 do
for j=0,63 do
local v
if ffi.abi("le") then
v=mime64chars[j]*256+mime64chars[i]
else
v=mime64chars[i]*256+mime64chars[j]
end
mime64shorts[i*64+j]=v
end
end
local u16arr = ffi.typeof"uint16_t[?]"
local crlf16 = ffi.new("uint16_t[1]")
if ffi.abi("le") then
crlf16[0] = (0x0A*256)+0x0D
else
crlf16[0] = (0x0D*256)+0x0A
end
local eq=string.byte('=')
--- Base64 encode binary data of a string or a FFI char *.
-- @param str (String or char*) Bytearray to encode.
-- @param sz (Number) Length of string to encode, optional if str is a Lua string
-- @return (String) Encoded base64 string.
function escape.base64_encode(str, sz)
if (type(str)=="string") and (sz == nil) then sz=#str end
local outlen = floor(sz*2/3)
outlen = outlen + floor(outlen/19)+3
local m64arr=ffi.new(u16arr,outlen)
local l,p,v=0,0
local bptr = ffi.cast(u8ptr,str)
local c = 38 -- put a new line after every 76 characters
local i,k=0,0
::while_3bytes::
if i+3>sz then goto break3 end
v=bor(lshift(bptr[i],16),lshift(bptr[i+1],8),bptr[i+2])
i=i+3
::encode_last3::
if c==k then
m64arr[k]=crlf16[0]
k=k+1
c=k+38 -- 76 /2 = 38
end
m64arr[k]=mime64shorts[rshift(v,12)]
m64arr[k+1]=mime64shorts[band(v,4095)]
k=k+2
goto while_3bytes
::break3::
if l>0 then
-- Add trailing equal sign padding
if l==1 then
-- 1 byte encoded needs two trailing equal signs
m64arr[k-1]=bor(lshift(eq,8),eq)
else
-- 2 bytes encoded needs one trailing equal sign
(ffi.cast(u8ptr,m64arr))[lshift(k,1)-1]=eq
end
else
l=sz-i -- get remaining len (1 or 2 bytes)
if l>0 then
v=lshift(bptr[i],16)
if l==2 then v=bor(v,lshift(bptr[i+1],8)) end
goto encode_last3
end
end
return ffi.string(m64arr,lshift(k,1))
end
end
return escape
| apache-2.0 |
jshackley/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Qahzwin.lua | 34 | 1032 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Qahzwin
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00F4);
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/globals/items/cup_of_imperial_coffee_+1.lua | 35 | 1257 | -----------------------------------------
-- ID: 5593
-- Item: cup_of_imperial_coffee_+1
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health Regen While Healing 5
-- Magic Regen While Healing 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5593);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPHEAL, 5);
target:addMod(MOD_MPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPHEAL, 5);
target:delMod(MOD_MPHEAL, 5);
end;
| gpl-3.0 |
Th2Evil/SuperPlus | plugins/badword.lua | 7 | 3344 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ block word : منع كلمات ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "تـم ☑️ اضافه كلمه جديده الى قائمه المنع ❌👍\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = '❌✋🏻 قائمه المنع الكلمات المحظوره ❌👍 :\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'تـم ☑️ تـنـظـيـف قائمه الـمنـع 👍🙊'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' تم ☑️ الغاهها من قامه الـمـنـع 👍'
end
local function run(msg, matches)
if matches[2] == 'منع' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'قائمه المنع' then
return list_variablesbad(msg)
elseif matches[2] == 'تنظيف قائمه المنع' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'الغاء منع' or matches[2] == 'rw' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^()(rw) (.*)$",
"^()(منع) (.*)$",
"^()(الغاء منع) (.*)$",
"^()(قائمه المنع)$",
"^()(تنظيف قائمه المنع)$",
"^(.+)$",
},
run = run
}
| gpl-2.0 |
jshackley/darkstar | scripts/zones/LaLoff_Amphitheater/bcnms/ark_angels_5.lua | 17 | 3273 | -----------------------------------
-- Area: LaLoff Amphitheater
-- Name: Ark Angels 5 (Galka)
-----------------------------------
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,4,1); -- winning CS (allow player to skip)
else
player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,4,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_APATHY) and player:hasKeyItem(SHARD_OF_ARROGANCE)
and player:hasKeyItem(SHARD_OF_COWARDICE) and player:hasKeyItem(SHARD_OF_ENVY));
if (csid == 0x7d01) then
if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then
player:addKeyItem(SHARD_OF_RAGE);
player:messageSpecial(KEYITEM_OBTAINED,SHARD_OF_RAGE);
if (AAKeyitems == true) then
player:completeMission(ZILART,ARK_ANGELS);
player:addMission(ZILART,THE_SEALED_SHRINE);
player:setVar("ZilartStatus",0);
end
end
end
local AAKeyitems = (player:hasKeyItem(SHARD_OF_APATHY) and player:hasKeyItem(SHARD_OF_ARROGANCE)
and player:hasKeyItem(SHARD_OF_COWARDICE) and player:hasKeyItem(SHARD_OF_ENVY)
and player:hasKeyItem(SHARD_OF_RAGE));
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Markets/npcs/Salimah.lua | 17 | 2906 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Salimah
-- Notes: Start & Finishes Quest: Gourmet
-- @pos -31.687 -6.824 -73.282 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Bastok_Markets/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local Gourmet = player:getQuestStatus(BASTOK,GOURMET);
if (Gourmet ~= QUEST_AVAILABLE and player:needToZone() == false) then
local count = trade:getItemCount();
local hasSleepshroom = trade:hasItemQty(4374,1);
local hasTreantBulb = trade:hasItemQty(953,1);
local hasWildOnion = trade:hasItemQty(4387,1);
if (hasSleepshroom or hasTreantBulb or hasWildOnion) then
if (count == 1) then
local vanatime = VanadielHour();
local item = 0;
local event = 203;
if (hasSleepshroom) then
item = 4374;
if (vanatime>=18 or vanatime<6) then
event = 201;
end
elseif (hasTreantBulb) then
item = 953;
if (vanatime>=6 and vanatime<12) then
event = 201;
end
elseif (hasWildOnion) then
item = 4387;
if (vanatime>=12 and vanatime<18) then
event = 202;
end
end
player:startEvent(event,item);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(BASTOK,GOURMET) ~= QUEST_AVAILABLE and player:needToZone()) then
player:startEvent(0x0079);
else
player:startEvent(0x00c8);
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);
local Gourmet = player:getQuestStatus(BASTOK,GOURMET);
if (csid == 0x00c8) then
if (Gourmet == QUEST_AVAILABLE) then
player:addQuest(BASTOK,GOURMET);
end
elseif (csid ~= 0x0079) then
player:tradeComplete();
if (Gourmet == QUEST_ACCEPTED) then
player:completeQuest(BASTOK,GOURMET);
end
local gil=350;
local fame=120;
if (csid == 201) then
gil=200;
elseif (csid == 203) then
gil=100;
fame=60;
end
player:addGil(gil*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,gil*GIL_RATE);
player:addFame(BASTOK,BAS_FAME*fame);
player:addTitle(MOMMYS_HELPER);
player:needToZone(true);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Gennoue.lua | 29 | 1057 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Gennoue
-- Type: Weather Reporter
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01FD,0,0,0,0,0,0,0,VanadielTime());
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 |
CapsAdmin/unfinished | client/chat_cinematic.lua | 1 | 9780 | chatcinematic = chatcinematic or {}
chatcinematic.random_seed = ""
chatcinematic.ActiveHooks = chatcinematic.ActiveHooks or {}
for key, ply in pairs(player.GetAll()) do
ply.chat_cinematic = false
end
function chatcinematic.RandomSeed(min, max, seed)
seed = seed or chatcinematic.random_seed
max = max + 1
seed = seed .. tostring(max) .. tostring(min)
return min + (max - min) * (util.CRC(seed)/10000000000)
end
local function HOOK(name)
hook.Add(name, "chatcinematic_" .. name, chatcinematic[name])
chatcinematic.ActiveHooks[name] = "chatcinematic_" .. name
end
function chatcinematic.Stop()
chatcinematic.players = {}
chatcinematic.active_player = NULL
for key, val in pairs(chatcinematic.ActiveHooks) do
hook.Remove(key, val)
end
end
function chatcinematic.IsActive()
return chatcinematic.GetActivePlayer():IsPlayer()
end
do -- players
function chatcinematic.SetActivePlayer(ply)
chatcinematic.active_player = ply
end
function chatcinematic.GetActivePlayer()
return chatcinematic.active_player or NULL
end
function chatcinematic.CheckPlayer(a)
return a.chat_cinematic == true
end
function chatcinematic.AddPlayer(ply)
ply.chat_cinematic = true
end
function chatcinematic.RemovePlayer(ply)
ply.chat_cinematic = false
end
function chatcinematic.OnPlayerChat(ply, str)
if not chatcinematic.CheckPlayer(LocalPlayer()) then return end
chatcinematic.random_seed = str
if chatcinematic.CheckPlayer(ply) then
if (ply.last_active_chatcinematic or 0) < CurTime() and (chatcinematic.last_active_chatcinematic or 0) < CurTime() then
chatcinematic.ChooseRandomCameraPos(ply)
chatcinematic.SetActivePlayer(ply)
ply.last_active_chatcinematic = CurTime() + 3
chatcinematic.last_active_chatcinematic = CurTime() + 1.5
end
end
end
HOOK("OnPlayerChat")
end
do -- view
chatcinematic.cam_distance = 200
chatcinematic.smooth_speed = 2
chatcinematic.pos_smooth = vector_origin
chatcinematic.dir_smooth = vector_origin
chatcinematic.fov_smooth = 0
chatcinematic.pos_target = vector_origin
chatcinematic.dir_target = vector_origin
chatcinematic.fov_target = 75
chatcinematic.local_camera_pos = vector_origin
chatcinematic.angle_offset = Angle(0,0,0)
function chatcinematic.GetEyePos(ply)
ply = not ply:Alive() and ply:GetRagdollEntity() or ply
local pos, ang = ply:GetBonePosition(ply:LookupBone("ValveBiped.Bip01_Head1"))
return pos + ang:Forward() * 2
end
function chatcinematic.ChooseRandomCameraPos(ply)
local prev = chatcinematic.GetActivePlayer()
if prev ~= ply then
ply = ply or prev
if ply:IsPlayer() then
chatcinematic.local_camera_pos = Vector(chatcinematic.RandomSeed(-1,1)*0.2, chatcinematic.RandomSeed(-1,1)*0.2, chatcinematic.RandomSeed(-1,1)*0.3)
chatcinematic.angle_offset = Angle(chatcinematic.RandomSeed(-1,1)*2, chatcinematic.RandomSeed(-1,1)*8, chatcinematic.RandomSeed(-1,1))
chatcinematic.fov_target = chatcinematic.RandomSeed(10, 40)
chatcinematic.new_angle = true
chatcinematic.panning_dir = Angle(0,0,0)
chatcinematic.panning_vel = chatcinematic.RandomSeed(1,3) * chatcinematic.angle_offset.y > 0 and -1 or 1
chatcinematic.pos_target = nil
end
end
end
function chatcinematic.GetLocalCameraPos()
local ply = chatcinematic.GetActivePlayer()
if ply:IsPlayer() then
return (ply:GetAimVector() * Vector(1,1,0)) + chatcinematic.local_camera_pos
end
return vector_origin
end
function chatcinematic.GetWorldCameraPos()
local middle = vector_origin
local players = player.GetAll()
local i = 0
for _, ply in pairs(players) do
if chatcinematic.CheckPlayer(ply) then
middle = middle + chatcinematic.GetEyePos(ply)
i = i + 1
end
end
if middle ~= vector_origin then
middle = middle / i
end
local ply = chatcinematic.GetActivePlayer()
return LerpVector(0.2, chatcinematic.GetEyePos(ply) + (chatcinematic.GetLocalCameraPos() * (chatcinematic.cam_distance * 0.5)), middle)
end
function chatcinematic.CalcSmooth()
local delta = FrameTime()
chatcinematic.pos_smooth = chatcinematic.pos_smooth + ((chatcinematic.pos_target - chatcinematic.pos_smooth) * (delta * chatcinematic.smooth_speed))
chatcinematic.dir_smooth = chatcinematic.dir_smooth + ((chatcinematic.dir_target - chatcinematic.dir_smooth) * (delta * chatcinematic.smooth_speed))
chatcinematic.fov_smooth = chatcinematic.fov_smooth + ((chatcinematic.fov_target - chatcinematic.fov_smooth) * (delta * chatcinematic.smooth_speed))
end
chatcinematic.panning_dir = vector_origin
chatcinematic.panning_vel = 0
function chatcinematic.CalcPanning()
if math.abs(chatcinematic.panning_dir.y) < 5 then
chatcinematic.panning_dir = chatcinematic.panning_dir + (Angle(0, FrameTime()*chatcinematic.panning_vel, 0))
end
end
local params = {}
function chatcinematic.CalcView()
local ply = chatcinematic.GetActivePlayer()
if ply:IsPlayer() then
chatcinematic.pos_target = chatcinematic.pos_target or chatcinematic.GetWorldCameraPos()
chatcinematic.dir_target = chatcinematic.GetEyePos(ply) - chatcinematic.pos_target + chatcinematic.panning_dir
chatcinematic.CalcSmooth()
chatcinematic.CalcPanning()
if chatcinematic.new_angle then
chatcinematic.pos_smooth = chatcinematic.pos_target
chatcinematic.dir_smooth = chatcinematic.dir_target
chatcinematic.fov_smooth = chatcinematic.fov_target
chatcinematic.new_angle = false
end
params.origin = chatcinematic.pos_smooth
params.angles = chatcinematic.dir_smooth:Angle() + chatcinematic.angle_offset + chatcinematic.panning_dir
params.fov = chatcinematic.fov_smooth
return params
end
end
HOOK("CalcView")
function chatcinematic.ShouldDrawLocalPlayer()
local ply = chatcinematic.GetActivePlayer()
if ply:IsPlayer() then
return true
end
end
HOOK("ShouldDrawLocalPlayer")
surface.CreateFont("cachatcinematicri", 48, 500, true, false, "subtitle")
chatcinematic.letterbox_ratio = 2.39 / 1
chatcinematic.letterbox_color = Color(0, 0, 0, 255)
chatcinematic.letterbox_vignette = 2
chatcinematic.letterbox_message = "hi2"
chatcinematic.letterbox_fade = 255
function chatcinematic.PreChatSound(data)
chatcinematic.letterbox_message = data.key
chatcinematic.letterbox_fade = 255
end
HOOK("PreChatSound")
local grad_up = surface.GetTextureID("gui/gradient_up")
local grad_down = surface.GetTextureID("gui/gradient_down")
function chatcinematic.DrawLetterBox()
local width, height = surface.ScreenWidth(), surface.ScreenHeight()
local ratio = width / height
surface.SetDrawColor(chatcinematic.letterbox_color)
local vx, vy, vw, vh
if ratio < chatcinematic.letterbox_ratio then
vw = width
vh = width / chatcinematic.letterbox_ratio
vx = (width - vw) / 2
vy = (height - vh) / 2
surface.DrawRect(-1, -1, vw, vy)
surface.DrawRect(-1, vy + vh, vw, height - (vy + vh))
else
vw = height * chatcinematic.letterbox_ratio
vh = height
vx = (width - vw) / 2
vy = (height - vh) / 2
surface.DrawRect(0, 0, vx, vh)
surface.DrawRect(vx + vw, 0, width - (vx + vw), vh)
end
local c = chatcinematic.letterbox_color
surface.SetDrawColor(c.r, c.g, c.b, c.a*0.8)
surface.SetTexture(grad_up)
surface.DrawTexturedRect(vx, vy + vh - vh / chatcinematic.letterbox_vignette, vw, vh / chatcinematic.letterbox_vignette)
surface.SetTexture(grad_down)
surface.DrawTexturedRect(vx, vy, vw, vh / chatcinematic.letterbox_vignette)
end
function chatcinematic.DrawSubtitles()
surface.SetFont("subtitle")
local w, h = surface.GetTextSize(chatcinematic.letterbox_message)
surface.SetTextPos((ScrW() - w) / 2, (ScrH() - h) * 0.95)
surface.SetTextColor(Color(255, 255, 255, chatcinematic.letterbox_fade))
surface.DrawText(chatcinematic.letterbox_message)
chatcinematic.letterbox_fade = math.Clamp(chatcinematic.letterbox_fade - 1, 0, 255)
end
local mat = Material("particle/Particle_Glow_04_Additive")
local size = 400
function chatcinematic.RenderScreenspaceEffects()
if not chatcinematic.IsActive() then return end
DrawSharpen(1.5, 0.3)
DrawColorModify({
["$pp_colour_colour"] = 0.8,
["$pp_colour_brightness"] = -0.10,
["$pp_colour_contrast"] = 0.5,
})
DrawBloom( 0, 2, 0, 0, 0.15, 0.1, 1, 1, 1 )
cam.Start2D()
surface.SetMaterial(mat)
surface.SetDrawColor(150,150,150,5)
surface.DrawTexturedRect(-size, -size, ScrW()+size*2, ScrH()+size*2)
cam.End2D()
chatcinematic.DrawLetterBox()
chatcinematic.DrawSubtitles()
--cam.Start2D()
-- surface.SetDrawColor(120,110,150,10)
-- surface.DrawRect(0, 0, ScrW(), ScrH())
--cam.End2D()
end
HOOK("RenderScreenspaceEffects")
function chatcinematic.HUDShouldDraw(str)
if not chatcinematic.IsActive() then return end
if str ~= "CHudWeaponSelection" then
return false
end
end
HOOK("HUDShouldDraw")
local emitter = ParticleEmitter(EyePos())
emitter:SetNoDraw(true)
function chatcinematic.PostDrawOpaqueRenderables()
if not chatcinematic.IsActive() then return end
for i=1, 5 do
local particle = emitter:Add("particle/Particle_Glow_05", LocalPlayer():EyePos() + VectorRand() * 500)
if particle then
local col = HSVToColor(math.random()*30, 0.1, 1)
particle:SetColor(col.r, col.g, col.b, 266)
particle:SetVelocity(VectorRand() )
particle:SetDieTime((math.random()+4)*3)
particle:SetLifeTime(0)
local size = 1
particle:SetAngles(AngleRand())
particle:SetStartSize((math.random()+1)*2)
particle:SetEndSize(0)
particle:SetStartAlpha(0)
particle:SetEndAlpha(255)
--particle:SetRollDelta(math.Rand(-1,1)*20)
particle:SetAirResistance(500)
particle:SetGravity(VectorRand() * 10)
end
end
emitter:Draw()
end
HOOK("PostDrawOpaqueRenderables")
end | gpl-3.0 |
LiberatorUSA/GUCEF | projects/premake5/targets/GUCEF_exe_udp2kafka/premake5.lua | 1 | 1230 | --------------------------------------------------------------------
-- 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.
--------------------------------------------------------------------
--
workspace( "GUCEF_exe_udp2kafka" )
platforms( { "ALL" } )
location( "projects\premake5\targets" )
--
-- Includes for all modules in the solution:
--
filter "ALL"
include( "dependencies/json-builder" )
include( "dependencies/json-parser" )
include( "dependencies/libparsifal" )
include( "dependencies/librdkafka" )
include( "dependencies/zlib" )
include( "platform/gucefCOM" )
include( "platform/gucefCOMCORE" )
include( "platform/gucefCORE" )
include( "platform/gucefMT" )
include( "platform/gucefVFS" )
include( "platform/gucefWEB" )
include( "plugins/CORE/codecspluginZLIB" )
include( "plugins/CORE/dstorepluginJSONPARSER" )
include( "plugins/CORE/dstorepluginPARSIFALXML" )
include( "tools/udp2kafka" )
| apache-2.0 |
jshackley/darkstar | scripts/globals/items/meatloaf.lua | 39 | 1357 | -----------------------------------------
-- ID: 5689
-- Item: Meatloaf
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- Strength 6
-- Agility 2
-- Intelligence -3
-- Attack 20% Cap 75
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD)) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5689);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 6);
target:addMod(MOD_AGI, 2);
target:addMod(MOD_INT, -3);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 75);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 6);
target:delMod(MOD_AGI, 2);
target:delMod(MOD_INT, -3);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 75);
end;
| gpl-3.0 |
DarkRainX/ufoai | base/ufos/ui/statistics.campaignstat.lua | 2 | 1559 | --!usr/bin/lua
--[[
-- @file
-- @brief Campaign success statistics
--]]
--[[
Copyright (C) 2002-2020 UFO: Alien Invasion.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--]]
require("ufox.lua")
function build_campaignstats (rootNode)
if (rootNode == nil) then
return
end
if (rootNode:child("campaign_stats") ~= nil) then
rootNode:child("campaign_stats"):delete_node()
end
local nationChart = ufox.build({
name = "campaign_stats",
class = "panel",
pos = {0, 0},
size = {545, 150},
backgroundcolor = {0.5, 0.5, 0.5, 0.2},
{
name = "campaign_string",
class = "string",
text = "_Campaign",
pos = {0, 0},
size = {545, 20},
contentalign = ufo.ALIGN_CC,
backgroundcolor = {0.527, 0.6, 0.21, 0.2},
},
{
name = "campaign_stats",
class = "text",
dataid = ufo.TEXT_GENERIC,
pos = {0, 20},
size = {545, 130},
lineheight = 22,
tabwidth = 360,
},
}, rootNode)
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Al_Zahbi/npcs/Danaaba.lua | 38 | 1025 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Danaaba
-- Type: Standard NPC
-- @zone: 48
-- @pos -17.375 -6.999 59.161
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00f8);
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/globals/items/tricolored_carp.lua | 18 | 1325 | -----------------------------------------
-- ID: 4426
-- Item: tricolored_carp
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4426);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Bibiki_Bay/npcs/Noih_Tahparawh.lua | 19 | 3558 | -----------------------------------
-- Area: Bibiki Bay
-- NPC: Noih Tahparawh
-- Type: Manaclipper
-- @pos -392 -3 -385 4
-----------------------------------
package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil;
require("scripts/zones/Bibiki_Bay/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local schedule = 0;
local vHour = VanadielHour();
local vMin = VanadielMinute();
if ( vHour <= 7) then -- Schedule
--Do nothing. -- 0: A - 8:40 - Bibiki Bay (Sunset Docks)
elseif ( vHour == 8 and vMin <= 40) then -- 1: D - 9:20 - Bibiki Bay (Sunset Docks)
--Do nothing. -- 2: A - 20:40 - Bibiki Bay (Sunset Docks)
elseif ( vHour == 8) then -- 3: D - 21:20 - Bibiki Bay (Sunset Docks)
schedule = 1;
elseif ( vHour == 9 and vMin <= 20) then
schedule = 1;
elseif ( vHour <= 19) then
schedule = 2;
elseif ( vHour == 20 and vMin <= 40) then
schedule = 2;
elseif ( vHour == 20) then
schedule = 3;
elseif ( vHour == 21 and vMin <= 20) then
schedule = 3;
end
local arrive = 0;
local depart = 0;
local seconds = 0;
if ( schedule == 0) then -- Arrival, bound for Bibiki Bay (Sunset Docks)
arrive = 1;
if ( vHour == 21) then vHour = 11;
elseif ( vHour == 22) then vHour = 10;
elseif ( vHour == 23) then vHour = 9;
elseif ( vHour == 0) then vHour = 8;
elseif ( vHour == 1) then vHour = 7;
elseif ( vHour == 2) then vHour = 6;
elseif ( vHour == 3) then vHour = 5;
elseif ( vHour == 4) then vHour = 4;
elseif ( vHour == 5) then vHour = 3;
elseif ( vHour == 6) then vHour = 2;
elseif ( vHour == 7) then vHour = 1;
elseif ( vHour == 8) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 40));
elseif ( schedule == 1) then -- Departure to Bibiki Bay (Sunset Docks)
depart = 1;
if ( vHour == 8) then vHour = 1;
elseif ( vHour == 9) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 20));
elseif ( schedule == 2) then -- Arrival, bound for Bibiki Bay (Sunset Docks)
arrive = 1;
if ( vHour == 9) then vHour = 11;
elseif ( vHour == 10) then vHour = 10;
elseif ( vHour == 11) then vHour = 9;
elseif ( vHour == 12) then vHour = 8;
elseif ( vHour == 13) then vHour = 7;
elseif ( vHour == 14) then vHour = 6;
elseif ( vHour == 15) then vHour = 5;
elseif ( vHour == 16) then vHour = 4;
elseif ( vHour == 17) then vHour = 3;
elseif ( vHour == 18) then vHour = 2;
elseif ( vHour == 19) then vHour = 1;
elseif ( vHour == 20) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 40));
elseif ( schedule == 3) then -- Departure to Bibiki Bay (Sunset Docks)
depart = 1;
if ( vHour == 20) then vHour = 1;
elseif ( vHour == 21) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 20));
end
player:startEvent( 0x0013, seconds, depart, arrive, 3, 0, 0, 0, 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/Attohwa_Chasm/npcs/qm1.lua | 17 | 1612 | -----------------------------------
-- Area: Attohwa Chasm
-- NPC: ??? (qm1)
-- @pos -402.574 3.999 -202.750 7
-----------------------------------
package.loaded["scripts/zones/Attohwa_Chasm/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/Attohwa_Chasm/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
-- Antlion Trap: ID 1825
-- Alastor Antlion: ID 16806248
-- UPDATE `mob_spawn_points` SET `pos_x`='-402.574', `pos_y`='3.999', `pos_z`='-202.75', `pos_rot`='7' WHERE (`mobid`='16806242')
local feelerID =16806242;
local feelerAntlion = GetMobByID(feelerID);
local npcX = npc:getXPos();
local npcY = npc:getYPos();
local npcZ = npc:getZPos();
feelerAntlion:setSpawn(npcX-3,npcY-2,npcZ-1);
if (GetMobAction(feelerID) == 0 and trade:hasItemQty(1825,1) and trade:getItemCount() == 1) then
player:tradeComplete();
SpawnMob(feelerID,120):updateClaim(player);
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(OCCASIONAL_LUMPS);
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 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/modules/admin-full/luasrc/controller/admin/index.lua | 6 | 1287 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: index.lua 7789 2011-10-26 03:04:18Z jow $
]]--
module("luci.controller.admin.index", package.seeall)
function index()
local root = node()
if not root.target then
root.target = alias("admin")
root.index = true
end
local page = node("admin")
page.target = firstchild()
page.title = _("Administration")
page.order = 10
page.sysauth = "root"
page.sysauth_authenticator = "htmlauth"
page.ucidata = true
page.index = true
-- Empty services menu to be populated by addons
entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true
entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90)
end
function action_logout()
local dsp = require "luci.dispatcher"
local sauth = require "luci.sauth"
if dsp.context.authsession then
sauth.kill(dsp.context.authsession)
dsp.context.urltoken.stok = nil
end
luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url())
luci.http.redirect(luci.dispatcher.build_url())
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Lower_Jeuno/npcs/Vhana_Ehgaklywha.lua | 17 | 3186 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Vhana Ehgaklywha
-- Standard Info NPC
-- @pos -122.853 0.000 -195.605
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
require("scripts/zones/Lower_Jeuno/TextIDs");
package.loaded["scripts/globals/pathfind"] = nil;
require("scripts/globals/pathfind");
path = {
0.932, 0, 19.065,
-2.84, 0, 13.676,
-5, 0, 13,
-7.833, 0, 12.263,
-8.782, 0, 12.736, -- lamp 1, path 5
-9.938, 0, 10.595,
-18, 0, 14.855,
-25, 0, 3,
-19, 0, -0.644,
-17.24, 0, -2.052,
-18.11, 0, -4.691,
-18.83, 0, -4.346, -- lamp 2, path 12
-19.34, 0, -7.971,
-30.38, 0, -26.50,
-32.38, 0, -28.52,
-32.76, 0, -28.63,
-32.98, 0, -28.60, -- lamp 3, path 17
-31.93, 0, -38.83,
-34.78, 0, -43.10,
-45.12, 0, -47.10, -- lamp 4, path 20
-52.76, 0, -60.53, -- lamp 5, path 21
-41.77, 0, -48.81,
-41.14, 0, -48.66,
-40.34, 0, -48.79,
-39.83, 0, -49.20,
-39.92, 0, -49.83,
-45.65, 6, -62.83,
-49.97, 6, -70.32,
-57.87, 6, -75.37,
-60.87, 6, -74.87, -- lamp 6, path 30
-61.05, 6, -83.40,
-66.38, 6, -92.58,
-72.88, 6, -95.78, -- lamp 7, path 33
-75.42, 6, -112.4,
-77.24, 5.9, -115.7,
-82.75, 0.7, -125.1,
-84.13, 0, -127.1,
-85.94, 0, -126.2,
-81.08, 0, -110.5, -- lamp 8, path 39
-88.57, 0, -123.3, -- lamp 9, path 40
-88.20, 0, -134.2,
-88.31, 0, -134.9,
-92.52, 0, -142.7,
-100.4, 0, -144.3, -- lamp 10, path 44
-108.6, 0, -158.0, -- lamp 11, path 45
-116.7, 0, -171.8, -- lamp 12, path 46
-114.8, 0, -182.0,
-122.8, 0, -195.6, -- end
}
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, 7160);
end;
-----------------------------------
-- onPath
-----------------------------------
function onPath(npc)
local pathpoints = { 5, 12, 17, 20, 21, 30, 33, 39, 40, 44, 45, 46};
for _, v in pairs(pathpoints) do
-- local lampOffset = 17780881;
if (npc:atPoint(pathfind.get(path,v))) then
npc:setPos(npc:getXPos(), npc:getYPos(), npc:getZPos(), 150);
npc:wait(5300);
print("Waiting..");
--GetNPCByID(lampOffset):openDoor(3);
--printf("%s lamp reached | ID is: %i",GetNPCByID(lampOffset):getName(), lampOffset);
return;
else
if (npc:atPoint(pathfind.get(path,48))) then
npc:wait(1000);
npc:setStatus(2);
end
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
botmohammad12344888/bot-888338888 | plugins/googlesh.lua | 2 | 1035 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults="جستجو در گوگل:\n______________________________\n"
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searche in Google",
usage = "/src (item) : google search",
patterns = {
"^جستجو (.*)$"
},
run = run
}
| gpl-2.0 |
CriztianiX/luaws | luaws/services/factory.lua | 1 | 1113 | local class = require 'middleclass'
local Luaws_Services_CloudWatch = require 'luaws.services.cloud_watch'
local Luaws_Services_S3 = require 'luaws.services.s3'
local Luaws_Services_SNS = require 'luaws.services.sns'
local Luaws_Services_SQS = require 'luaws.services.sqs'
local Luaws_Services_SWF = require 'luaws.services.swf'
local Luaws_Services_Factory = class('Luaws_Services_Factory')
local services = {
CloudWatch = function()
return Luaws_Services_CloudWatch:new()
end,
S3 = function()
return Luaws_Services_S3:new()
end,
SNS = function()
return Luaws_Services_SNS:new()
end,
SQS = function()
return Luaws_Services_SQS:new()
end,
SWF = function()
return Luaws_Services_SWF:new()
end
}
function Luaws_Services_Factory.static.services()
local s = {}
local tinsert = table.insert
for service,_ in pairs(services) do
tinsert(s, service)
end
return s
end
function Luaws_Services_Factory.static.create(service, core)
local s = services[service]()
s:setCore(core)
return s
end
return Luaws_Services_Factory
| gpl-2.0 |
hockeychaos/Core-Scripts-1 | PlayerScripts/StarterPlayerScripts/CameraScript/TransparencyController.lua | 2 | 5353 | -- SolarCrane
local MAX_TWEEN_RATE = 2.8 -- per second
local function clamp(low, high, num)
return (num > high and high or num < low and low or num)
end
local math_floor = math.floor
local function Round(num, places)
local decimalPivot = 10^places
return math_floor(num * decimalPivot + 0.5) / decimalPivot
end
local function CreateTransparencyController()
local module = {}
local LastUpdate = tick()
local TransparencyDirty = false
local Enabled = false
local LastTransparency = nil
local DescendantAddedConn, DescendantRemovingConn = nil, nil
local ToolDescendantAddedConns = {}
local ToolDescendantRemovingConns = {}
local CachedParts = {}
local function HasToolAncestor(object)
if object.Parent == nil then return false end
return object.Parent:IsA('Tool') or HasToolAncestor(object.Parent)
end
local function IsValidPartToModify(part)
if part:IsA('BasePart') or part:IsA('Decal') then
return not HasToolAncestor(part)
end
return false
end
local function CachePartsRecursive(object)
if object then
if IsValidPartToModify(object) then
CachedParts[object] = true
TransparencyDirty = true
end
for _, child in pairs(object:GetChildren()) do
CachePartsRecursive(child)
end
end
end
local function TeardownTransparency()
for child, _ in pairs(CachedParts) do
child.LocalTransparencyModifier = 0
end
CachedParts = {}
TransparencyDirty = true
LastTransparency = nil
if DescendantAddedConn then
DescendantAddedConn:disconnect()
DescendantAddedConn = nil
end
if DescendantRemovingConn then
DescendantRemovingConn:disconnect()
DescendantRemovingConn = nil
end
for object, conn in pairs(ToolDescendantAddedConns) do
conn:disconnect()
ToolDescendantAddedConns[object] = nil
end
for object, conn in pairs(ToolDescendantRemovingConns) do
conn:disconnect()
ToolDescendantRemovingConns[object] = nil
end
end
local function SetupTransparency(character)
TeardownTransparency()
if DescendantAddedConn then DescendantAddedConn:disconnect() end
DescendantAddedConn = character.DescendantAdded:connect(function(object)
-- This is a part we want to invisify
if IsValidPartToModify(object) then
CachedParts[object] = true
TransparencyDirty = true
-- There is now a tool under the character
elseif object:IsA('Tool') then
if ToolDescendantAddedConns[object] then ToolDescendantAddedConns[object]:disconnect() end
ToolDescendantAddedConns[object] = object.DescendantAdded:connect(function(toolChild)
CachedParts[toolChild] = nil
if toolChild:IsA('BasePart') or toolChild:IsA('Decal') then
-- Reset the transparency
toolChild.LocalTransparencyModifier = 0
end
end)
if ToolDescendantRemovingConns[object] then ToolDescendantRemovingConns[object]:disconnect() end
ToolDescendantRemovingConns[object] = object.DescendantRemoving:connect(function(formerToolChild)
wait() -- wait for new parent
if character and formerToolChild and formerToolChild:IsDescendantOf(character) then
if IsValidPartToModify(formerToolChild) then
CachedParts[formerToolChild] = true
TransparencyDirty = true
end
end
end)
end
end)
if DescendantRemovingConn then DescendantRemovingConn:disconnect() end
DescendantRemovingConn = character.DescendantRemoving:connect(function(object)
if CachedParts[object] then
CachedParts[object] = nil
-- Reset the transparency
object.LocalTransparencyModifier = 0
end
end)
CachePartsRecursive(character)
end
function module:SetEnabled(newState)
if Enabled ~= newState then
Enabled = newState
self:Update()
end
end
function module:SetSubject(subject)
local character = nil
if subject and subject:IsA("Humanoid") then
character = subject.Parent
end
if subject and subject:IsA("VehicleSeat") and subject.Occupant then
character = subject.Occupant.Parent
end
if character then
SetupTransparency(character)
else
TeardownTransparency()
end
end
function module:Update()
local instant = false
local now = tick()
local currentCamera = workspace.CurrentCamera
if currentCamera then
local transparency = 0
if not Enabled then
instant = true
else
local distance = (currentCamera.Focus.p - currentCamera.CoordinateFrame.p).magnitude
transparency = (7 - distance) / 5
if transparency < 0.5 then
transparency = 0
end
if LastTransparency then
local deltaTransparency = transparency - LastTransparency
-- Don't tween transparency if it is instant or your character was fully invisible last frame
if not instant and transparency < 1 and LastTransparency < 0.95 then
local maxDelta = MAX_TWEEN_RATE * (now - LastUpdate)
deltaTransparency = clamp(-maxDelta, maxDelta, deltaTransparency)
end
transparency = LastTransparency + deltaTransparency
else
TransparencyDirty = true
end
transparency = clamp(0, 1, Round(transparency, 2))
end
if TransparencyDirty or LastTransparency ~= transparency then
for child, _ in pairs(CachedParts) do
child.LocalTransparencyModifier = transparency
end
TransparencyDirty = false
LastTransparency = transparency
end
end
LastUpdate = now
end
return module
end
return CreateTransparencyController
| apache-2.0 |
OptimusLime/lua-websockets | src/websocket/ev_common.lua | 5 | 4133 | local ev = require'ev'
local frame = require'websocket.frame'
local tinsert = table.insert
local tconcat = table.concat
local eps = 2^-40
local detach = function(f,loop)
if ev.Idle then
ev.Idle.new(function(loop,io)
io:stop(loop)
f()
end):start(loop)
else
ev.Timer.new(function(loop,io)
io:stop(loop)
f()
end,eps):start(loop)
end
end
local async_send = function(sock,loop)
assert(sock)
loop = loop or ev.Loop.default
local sock_send = sock.send
local buffer
local index
local callbacks = {}
local send = function(loop,write_io)
local len = #buffer
local sent,err,last = sock_send(sock,buffer,index)
if not sent and err ~= 'timeout' then
write_io:stop(loop)
if callbacks.on_err then
if write_io:is_active() then
callbacks.on_err(err)
else
detach(function()
callbacks.on_err(err)
end,loop)
end
end
elseif sent then
local copy = buffer
buffer = nil
index = nil
write_io:stop(loop)
if callbacks.on_sent then
-- detach calling callbacks.on_sent from current
-- exection if thiis call context is not
-- the send io to let send_async(_,on_sent,_) truely
-- behave async.
if write_io:is_active() then
callbacks.on_sent(copy)
else
-- on_sent is only defined when responding to "on message for close op"
-- so this can happen only once per lifetime of a websocket instance.
-- callbacks.on_sent may be overwritten by a new call to send_async
-- (e.g. due to calling ws:close(...) or ws:send(...))
local on_sent = callbacks.on_sent
detach(function()
on_sent(copy)
end,loop)
end
end
else
assert(last < len)
index = last + 1
end
end
local io = ev.IO.new(send,sock:getfd(),ev.WRITE)
local stop = function()
io:stop(loop)
buffer = nil
index = nil
end
local send_async = function(data,on_sent,on_err)
if buffer then
-- a write io is still running
buffer = buffer..data
return #buffer
else
buffer = data
end
callbacks.on_sent = on_sent
callbacks.on_err = on_err
if not io:is_active() then
send(loop,io)
if index ~= nil then
io:start(loop)
end
end
local buffered = (buffer and #buffer - (index or 0)) or 0
return buffered
end
return send_async,stop
end
local message_io = function(sock,loop,on_message,on_error)
assert(sock)
assert(loop)
assert(on_message)
assert(on_error)
local last
local frames = {}
local first_opcode
assert(sock:getfd() > -1)
local message_io
local dispatch = function(loop,io)
-- could be stopped meanwhile by on_message function
while message_io:is_active() do
local encoded,err,part = sock:receive(100000)
if err then
if err == 'timeout' and #part == 0 then
return
elseif #part == 0 then
if message_io then
message_io:stop(loop)
end
on_error(err,io,sock)
return
end
end
if last then
encoded = last..(encoded or part)
last = nil
else
encoded = encoded or part
end
repeat
local decoded,fin,opcode,rest = frame.decode(encoded)
if decoded then
if not first_opcode then
first_opcode = opcode
end
tinsert(frames,decoded)
encoded = rest
if fin == true then
on_message(tconcat(frames),first_opcode)
frames = {}
first_opcode = nil
end
end
until not decoded
if #encoded > 0 then
last = encoded
end
end
end
message_io = ev.IO.new(dispatch,sock:getfd(),ev.READ)
message_io:start(loop)
-- the might be already data waiting (which will not trigger the IO)
dispatch(loop,message_io)
return message_io
end
return {
async_send = async_send,
message_io = message_io
}
| mit |
jshackley/darkstar | scripts/zones/Upper_Jeuno/npcs/Champalpieu.lua | 36 | 1244 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Champalpieu
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
require("scripts/zones/Upper_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CHAMPALPIEU_SHOP_DIALOG);
stock = {0x110D,120, --Rolanberry
0x43A8,7, --Iron Arrow
0x43B8,5, --Crossbow Bolt
0x025D,180, --Pickaxe
0x13C8,567, --Wind Threnody
0x13CB,420} --Water Threnody
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
sajuptpm/contrail-controller | src/analytics/uvedelete.lua | 10 | 1755 | --
-- Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
--
local function sub_del(_values)
local lres = redis.call('hgetall',_values)
local iter = 1
while iter <= #lres do
local attr = lres[iter]
local val = lres[iter+1]
if string.byte(val,1) ~= 60 then
local descs = cjson.decode(val)
for k,desc in pairs(descs) do
if desc.href ~= nil then
redis.call('del',desc.href)
redis.log(redis.LOG_NOTICE,"Deleting for "..desc.href)
end
end
redis.call('hdel', _values, attr)
end
iter = iter + 2
end
end
local sm = ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[4]
local typ = ARGV[5]
local key = ARGV[6]
local db = tonumber(ARGV[7])
local is_alarm = tonumber(ARGV[8])
local _del = KEYS[1]
local _values = KEYS[2]
local _uves = KEYS[3]
local _origins = KEYS[4]
local _table = KEYS[5]
local _deleted = KEYS[6]
redis.call('select',db)
if is_alarm == 1 then
redis.log(redis.LOG_NOTICE,"DelAlarm on "..sm.." for "..key)
else
local part = redis.call('hget',"KEY2PART:"..sm..":"..typ, key)
if part == false then
part = "NULL"
else
redis.call('hdel', "KEY2PART:"..sm..":"..typ, key)
redis.call('srem', "PART2KEY:"..part, sm..":"..typ..":"..key)
redis.log(redis.LOG_NOTICE,"DelUVE on "..sm.." for "..key.." part "..part)
end
end
sub_del(_values)
redis.call('zrem', _uves, key)
redis.call('srem', _origins, sm..":"..typ)
redis.call('srem', _table, key..":"..sm..":"..typ)
local lttt = redis.call('exists', _values)
if lttt == 1 then
redis.call('rename', _values, _del)
redis.call('lpush',_deleted, _del)
end
return true
| apache-2.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/modules/admin-full/luasrc/model/cbi/admin_status/processes.lua | 12 | 1494 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: processes.lua 7025 2011-05-04 21:23:55Z jow $
]]--
f = SimpleForm("processes", translate("Processes"), translate("This list gives an overview over currently running system processes and their status."))
f.reset = false
f.submit = false
t = f:section(Table, luci.sys.process.list())
t:option(DummyValue, "PID", translate("PID"))
t:option(DummyValue, "USER", translate("Owner"))
t:option(DummyValue, "COMMAND", translate("Command"))
t:option(DummyValue, "%CPU", translate("CPU usage (%)"))
t:option(DummyValue, "%MEM", translate("Memory usage (%)"))
hup = t:option(Button, "_hup", translate("Hang Up"))
hup.inputstyle = "reload"
function hup.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 1)
end
term = t:option(Button, "_term", translate("Terminate"))
term.inputstyle = "remove"
function term.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 15)
end
kill = t:option(Button, "_kill", translate("Kill"))
kill.inputstyle = "reset"
function kill.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 9)
end
return f | gpl-2.0 |
jshackley/darkstar | scripts/globals/weaponskills/exenterator.lua | 18 | 2057 | -----------------------------------
-- Exenterator
-- Skill level: 357
-- Terpsichore: Aftermath effect varies with TP.
-- In order to obtain Exenterator, the quest Martial Mastery must be completed.
-- Description: Delivers a fourfold attack that lowers enemy's params.accuracy. Effect duration varies with TP.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Notes: Stacks with itself allowing continuous params.acc down
-- params.acc down isn't the same as the spell Blind or sources which are the same as blind allowing both to stack
-- Element: None
-- Modifiers: AGI:73~85%, depending on merit points upgrades.
-- 100%TP 200%TP 300%TP
-- 1.0 1.0 1.0
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 4;
params.ftp100 = 1.0; params.ftp200 = 1.0; params.ftp300 = 1.0;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.85 + (player:getMerit(MERIT_EXENTERATOR) / 100); 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.0;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.agi_wsc = 0.7 + (player:getMerit(MERIT_EXENTERATOR) / 100);
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if damage > 0 then
local tp = player:getTP();
local duration=(tp/100*30)+90;
if (target:hasStatusEffect(EFFECT_ACCURACY_DOWN) == false) then
target:addStatusEffect(EFFECT_ACCURACY_DOWN, 20, 0,duration);
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Ajen-Myoojen.lua | 56 | 1087 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Ajen-Myoojen
-- Type: Standard NPC
-- @pos -44.542 -5.999 238.996 94
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00C8);
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:setPos(320, -4, -46, 192, 95);
end
end; | gpl-3.0 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/TMXMapInfo.lua | 6 | 5752 |
--------------------------------
-- @module TMXMapInfo
--------------------------------
-- @function [parent=#TMXMapInfo] setObjectGroups
-- @param self
-- @param #array_table array
--------------------------------
-- @function [parent=#TMXMapInfo] setTileSize
-- @param self
-- @param #size_table size
--------------------------------
-- @function [parent=#TMXMapInfo] initWithTMXFile
-- @param self
-- @param #string str
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#TMXMapInfo] getOrientation
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#TMXMapInfo] isStoringCharacters
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#TMXMapInfo] setLayers
-- @param self
-- @param #array_table array
--------------------------------
-- @function [parent=#TMXMapInfo] parseXMLFile
-- @param self
-- @param #string str
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#TMXMapInfo] getParentElement
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#TMXMapInfo] setTMXFileName
-- @param self
-- @param #string str
--------------------------------
-- @function [parent=#TMXMapInfo] parseXMLString
-- @param self
-- @param #string str
-- @return bool#bool ret (return value: bool)
--------------------------------
-- overload function: getLayers()
--
-- overload function: getLayers()
--
-- @function [parent=#TMXMapInfo] getLayers
-- @param self
-- @return array_table#array_table ret (retunr value: array_table)
--------------------------------
-- overload function: getTilesets()
--
-- overload function: getTilesets()
--
-- @function [parent=#TMXMapInfo] getTilesets
-- @param self
-- @return array_table#array_table ret (retunr value: array_table)
--------------------------------
-- @function [parent=#TMXMapInfo] getParentGID
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#TMXMapInfo] setParentElement
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#TMXMapInfo] initWithXML
-- @param self
-- @param #string str
-- @param #string str
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#TMXMapInfo] setParentGID
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#TMXMapInfo] getLayerAttribs
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#TMXMapInfo] getTileSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- @function [parent=#TMXMapInfo] getTileProperties
-- @param self
-- @return map_table#map_table ret (return value: map_table)
--------------------------------
-- overload function: getObjectGroups()
--
-- overload function: getObjectGroups()
--
-- @function [parent=#TMXMapInfo] getObjectGroups
-- @param self
-- @return array_table#array_table ret (retunr value: array_table)
--------------------------------
-- @function [parent=#TMXMapInfo] getTMXFileName
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @function [parent=#TMXMapInfo] setCurrentString
-- @param self
-- @param #string str
--------------------------------
-- @function [parent=#TMXMapInfo] setProperties
-- @param self
-- @param #map_table map
--------------------------------
-- @function [parent=#TMXMapInfo] setOrientation
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#TMXMapInfo] setTileProperties
-- @param self
-- @param #map_table map
--------------------------------
-- @function [parent=#TMXMapInfo] setMapSize
-- @param self
-- @param #size_table size
--------------------------------
-- @function [parent=#TMXMapInfo] setStoringCharacters
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#TMXMapInfo] getMapSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- @function [parent=#TMXMapInfo] setTilesets
-- @param self
-- @param #array_table array
--------------------------------
-- overload function: getProperties()
--
-- overload function: getProperties()
--
-- @function [parent=#TMXMapInfo] getProperties
-- @param self
-- @return map_table#map_table ret (retunr value: map_table)
--------------------------------
-- @function [parent=#TMXMapInfo] getCurrentString
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @function [parent=#TMXMapInfo] setLayerAttribs
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#TMXMapInfo] create
-- @param self
-- @param #string str
-- @return TMXMapInfo#TMXMapInfo ret (return value: cc.TMXMapInfo)
--------------------------------
-- @function [parent=#TMXMapInfo] createWithXML
-- @param self
-- @param #string str
-- @param #string str
-- @return TMXMapInfo#TMXMapInfo ret (return value: cc.TMXMapInfo)
--------------------------------
-- @function [parent=#TMXMapInfo] TMXMapInfo
-- @param self
return nil
| mit |
jshackley/darkstar | scripts/zones/Norg/npcs/Keal.lua | 17 | 4233 | -----------------------------------
-- Area: Norg
-- NPC: Keal
-- Starts and Ends Quest: It's Not Your Vault
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Norg/TextIDs");
local path = {
-5.453587, 0.151494, -16.361458,
-5.997250, 0.229052, -15.475480,
-6.582538, 0.317294, -14.524694,
-7.573528, 0.365118, -12.941586,
-7.069273, 0.384884, -13.867216,
-6.565747, 0.311785, -14.741985,
-5.676943, 0.173223, -16.241194,
-5.162223, 0.020922, -17.108603,
-4.725273, -0.022554, -18.175083,
-4.882753, -0.041670, -19.252790,
-5.294413, 0.020847, -20.336269,
-5.632565, 0.112649, -21.417961,
-5.905818, 0.202903, -22.541668,
-5.657803, 0.116744, -21.445057,
-5.273734, 0.023316, -20.410303,
-4.831870, -0.049031, -19.478870,
-4.749702, -0.024804, -18.311924,
-5.152854, 0.002354, -17.248878,
-5.639069, 0.185855, -16.335281,
-6.158780, 0.247668, -15.445805,
-7.253261, 0.405026, -13.567613,
-7.803670, 0.348802, -12.626184,
-8.375298, 0.223101, -11.645775,
-8.895057, 0.076541, -10.770375,
-9.384287, 0.015579, -9.884774,
-9.939011, 0.143451, -8.935238,
-9.422630, -0.025280, -9.816562,
-8.589481, 0.151451, -11.248314,
-8.095008, 0.275576, -12.123538,
-7.561854, 0.373715, -13.045633,
-5.644930, 0.185392, -16.292952,
-5.058481, -0.014674, -17.285294,
-4.724863, -0.024709, -18.265087,
-4.923457, -0.042915, -19.378429,
-5.293544, 0.020505, -20.338196,
-5.606711, 0.104830, -21.323364,
-5.849701, 0.183865, -22.302536,
-5.586438, 0.097169, -21.222555,
-5.214560, 0.046522, -20.280220,
-4.779529, -0.048305, -19.351633,
-4.757209, -0.021693, -18.194023,
-5.138152, -0.000450, -17.254173,
-5.685457, 0.173866, -16.248564,
-6.275849, 0.266052, -15.243981,
-7.196375, 0.403362, -13.666089,
-7.766060, 0.352119, -12.689950,
-8.280642, 0.241637, -11.799251,
-8.828505, 0.098458, -10.895535,
-9.351592, 0.039748, -9.948843,
-9.856394, 0.036026, -9.068656
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
-- onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Vault = player:getQuestStatus(OUTLANDS,ITS_NOT_YOUR_VAULT);
mLvl = player:getMainLvl();
IronBox = player:hasKeyItem(SEALED_IRON_BOX);
if (Vault == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 3 and mLvl >= 5) then
player:startEvent(0x0024,SEALED_IRON_BOX); -- Start quest
elseif (Vault == QUEST_ACCEPTED) then
if (IronBox == true) then
player:startEvent(0x0026); -- Finish quest
else
player:startEvent(0x0025,MAP_OF_THE_SEA_SERPENT_GROTTO); -- Reminder/Directions Dialogue
end
elseif (Vault == QUEST_COMPLETED) then
player:startEvent(0x0027); -- New Standard Dialogue for everyone who has completed the quest
else
player:startEvent(0x0059); -- Standard Conversation
end
npc:wait(-1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0024 and option == 1) then
player:addQuest(OUTLANDS,ITS_NOT_YOUR_VAULT);
elseif (csid == 0x0026) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4961);
else
player:delKeyItem(SEALED_IRON_BOX);
player:addItem(4961); -- Scroll of Tonko: Ichi
player:messageSpecial(ITEM_OBTAINED, 4961);
player:addFame(OUTLANDS,NORG_FAME*50);
player:completeQuest(OUTLANDS,ITS_NOT_YOUR_VAULT);
end
end
npc:wait(0);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/mobskills/Wild_Rage.lua | 18 | 1137 | ---------------------------------------------
-- Wild Rage
--
-- Description: Deals physical damage to enemies within area of effect.
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: 15' radial
-- Notes: Has additional effect of Poison when used by King Vinegarroon.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2.1;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW);
target:delHP(dmg);
-- king vinegrroon
if (mob:getID() == 17289575) then
local typeEffect = EFFECT_POISON;
local power = 25;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, power, 3, 60);
end
return dmg;
end;
| gpl-3.0 |
men232/greencode-framework | lua/greencode/plugins/territory/plugins/ter_owning/sh_auto.lua | 1 | 24067 | --[[
© 2013 GmodLive private project do not share
without permission of its author (Andrew Mensky vk.com/men232).
--]]
local greenCode = greenCode;
local PLUGIN = PLUGIN or greenCode.plugin:Loader();
PLUGIN.class = {};
local TER_PLUGIN = greenCode.plugin:Get("territory");
greenCode.config:Add( "rent_time", 15, false, false, false );
function PLUGIN:TerritorySystemInitialized()
TERRITORY_PERMISSION_CLASS:New{ name = "owner", desc = "Permission for owning", default = false }:Register();
TERRITORY_PERMISSION_CLASS:New{ name = "coowner", desc = "Permission for co-owning", default = false }:Register();
TERRITORY_PERMISSION_CLASS:New{ name = "canowning", desc = "Permission allow owning", default = false }:Register();
end;
local playerMeta = FindMetaTable("Player");
function playerMeta:HoldingCount() return PLUGIN:HoldingCount( self ); end;
function PLUGIN:HoldingCount( player )
local nCount = 0;
for _, TERRITORY in pairs(TER_PLUGIN:GetStored()) do
if ( TERRITORY:GetOwnerLevel(player) > 0 ) then
nCount = nCount + 1;
end;
end;
return nCount;
end;
-- A function to register class.
function PLUGIN:RegisterPrice( sName, sDesc, funcAfford, funcAdd, cur )
self.class[ sName ] = { desc = sDesc, funcAfford = funcAfford, funcAdd = funcAdd, cur = cur };
end;
function PLUGIN:P_CanAfford( sName, player, nAmount )
if ( self.class[sName] ) then
return self.class[sName].funcAfford( player, nAmount );
end;
return false, "Incorrect price type.";
end;
function PLUGIN:P_AddMoney( sName, player, nAmount )
if ( self.class[sName] ) then
local bDone = self.class[sName].funcAdd(player, nAmount);
if ( bDone != nil ) then return bDone; end;
return true;
end;
return false, "Incorrect price type.";
end;
PLUGIN:RegisterPrice( "session", "Покупка на 1 игровой сеанс", playerMeta.CanAfford, playerMeta.AddMoney, "$" );
PLUGIN:RegisterPrice( "rent", "Аренда на "..greenCode.config:Get("rent_time"):Get(15).." мин", playerMeta.CanAfford, playerMeta.AddMoney, "$" );
PLUGIN:RegisterPrice( "perm", "Покупка на вечное владение", playerMeta.CanAfford, playerMeta.AddMoney, "$" );
---------------------
-- TERRITORY CLASS --
---------------------
function TERRITORY_CLASS:GetOwners() return self("owner", {}); end;
function TERRITORY_CLASS:GetCoOwners() return self("coowner", {}); end;
function TERRITORY_CLASS:IsOwned() return table.Count(self:GetOwners()) > 0 or table.Count(self:GetCoOwners()) > 0 end;
function TERRITORY_CLASS:GetPrice( sType )
local nPrice = self("price",{})[sType] or 0;
if ( sType == "session" or sType == "rent" ) then
return greenCode.plugin:Call( "GetPrice", nPrice ) or nPrice;
end;
return nPrice;
end;
function TERRITORY_CLASS:GetOnlineOwners( bCoOwn )
local tOwners = {};
for uid, _ in pairs( self:GetOwners() ) do
local player = _player.GetByUniqueID(tostring(uid));
if ( player ) then
table.insert( tOwners, player );
end;
end;
if ( bCoOwn ) then
for uid, _ in pairs( self:GetCoOwners() ) do
local player = _player.GetByUniqueID(tostring(uid));
if ( player ) then
table.insert( tOwners, player );
end;
end;
end;
return tOwners;
end;
function TERRITORY_CLASS:GetAllPrice()
local tPriceData = self("price",{});
tPriceData.session = greenCode.plugin:Call( "GetPrice", tPriceData.session or 0 ) or tPriceData.session or 0;
return tPriceData;
end;
-- A function to get all doors location in territory.
function TERRITORY_CLASS:GetDoors()
local tDoors = {};
for k, v in pairs(_ents.GetAll()) do
if ( greenCode.entity:IsDoor( v ) and self:IsInside( v:GetPos() ) ) then
table.insert( tDoors, v );
end;
end;
return tDoors;
end;
if SERVER then
function TERRITORY_CLASS:SetPrice( sType, nAmount )
if ( PLUGIN.class[sType] ) then
local tPriceData = self("price",{});
tPriceData[sType] = nAmount;
self:SetData( "price", tPriceData );
return true;
end;
return false, "Incorrect price type.";
end;
function TERRITORY_CLASS:RemoveAllOwners()
local tPermissionData = self:GetPerm().private;
if ( tPermissionData ) then
for uid, _ in pairs( tPermissionData ) do
self:SetPermission( "private", "coowner", uid, nil );
self:SetPermission( "private", "owner", uid, nil );
end;
end;
end;
function TERRITORY_CLASS:SetOwner( player )
if ( self:GetPermission( "canowning", player, false ) ) then
self:RemoveAllOwners();
return self:SetPermission( "private", "owner", player, true, os.time() );
else
return false, "Вы не можете владеть этим.";
end;
end;
function TERRITORY_CLASS:AddCoOwner( calling_ply, target_ply )
local parentUID = self("ownerSession");
if ( table.Count( self:GetOwners() ) > 0 and parentUID ) then
local bDone, sReason, SESSION = self:SetPermission( "private", "coowner", target_ply, true, os.time() );
if ( bDone ) then
greenCode.plugin:Call( "OnTerritoryAddCoOwner", self, calling_ply, target_ply, SESSION );
end;
return bDone, sReason, SESSION;
else
return false, "Нет основного владельца.";
end;
end;
function TERRITORY_CLASS:RemoveCoOwner( calling_ply, target_ply )
if ( self:GetOwnerLevel(target_ply) == 1 ) then
local bDone, sReason, SESSION = self:SetPermission( "private", "coowner", target_ply, nil );
if ( bDone ) then
greenCode.plugin:Call( "OnTerritoryRemoveCoOwner", self, calling_ply, target_ply, SESSION );
end;
return bDone, sReason, SESSION;
else
return false, "Нет прав."
end;
end;
function TERRITORY_CLASS:GetOwnerLevel( player )
if ( self:IsValid() ) then
if ( self:GetPermission( "owner", player, false ) ) then
return 2;
elseif ( self:GetPermission( "coowner", player, false ) ) then
return 1;
end;
end;
return 0;
end;
function TERRITORY_CLASS:Buy( player, sPriceType )
local bDone, sReason = greenCode.plugin:Call( "PlayerCanBuyTerritory", self, player, sPriceType );
if ( bDone != false ) then
bDone, sReason, SESSION = self:SetOwner( player );
if ( bDone ) then
PLUGIN:P_AddMoney( sPriceType, player, -self:GetPrice(sPriceType) );
self:SetData("lastBuyType", sPriceType);
greenCode.plugin:Call( "OnTerritoryBuy", self, player, sPriceType, SESSION );
end;
end;
return bDone, sReason;
end;
-- A function to sell territory.
function TERRITORY_CLASS:Sell( player )
local bCanSell, sMsg = greenCode.plugin:Call( "PlayerCanSellTerritory", self, player );
if ( bCanSell != false ) then
local nPriceType = self("lastBuyType", "session");
if ( !PLUGIN.class[nPriceType] ) then
nPriceType = PLUGIN.class[1];
end;
bCanSell, sMsg = PLUGIN:P_AddMoney( nPriceType, player, math.ceil(self:GetPrice(nPriceType)/2) );
if ( bCanSell ) then
self.data.ownerSession = -1; -- Clean owner session.
self:RemoveAllOwners();
greenCode.plugin:Call( "OnTerritorySell", self, player );
return true;
end;
end;
return bCanSell, sMsg;
end;
function TERRITORY_CLASS:UpdateDoorOwner( player, bAllow )
local nOwnerLevel = self:GetOwnerLevel( player );
for _, door in pairs( self:GetDoors() ) do
if ( door and IsValid(door) ) then
if ( bAllow and door:IsOwnable() ) then
if ( nOwnerLevel > 1 and !door:IsOwned() and !door:OwnedBy(player) ) then
door:RemoveAllowed(player);
door:Own(player);
continue;
elseif ( door:IsOwned() ) then
door:AddAllowed(player);
end;
door:Own(player);
else
door:RemoveAllowed(player);
door:UnOwn(player);
end;
end;
end;
end;
else
function TERRITORY_CLASS:GetOwnerLevel( player )
if ( self:IsValid() ) then
local uid = tonumber(player:UniqueID());
if ( self:GetOwners()[uid] ) then
return 2;
elseif ( self:GetCoOwners()[uid] ) then
return 1;
end;
end;
return 0;
end;
end;
--------------------
-- TERRITORY HOOK --
--------------------
if CLIENT then return end;
function PLUGIN:OnTerritoryGetPermission( TERRITORY, sPermissionName, player )
if ( sPermissionName == "spawnobject" and TERRITORY:GetOwnerLevel(player) > 0 ) then
return true, "Is owner!";
end;
end;
function PLUGIN:PlayerCharacterInitialized( player )
for _, TERRITORY in pairs(TER_PLUGIN:GetStored()) do
if ( TERRITORY:GetOwnerLevel(player) > 0 ) then
TERRITORY:UpdateDoorOwner(player, true);
end;
end;
end;
function PLUGIN:OnTerrytoryChangeOwners( TERRITORY, player, bValue )
if ( type(player) == "number" ) then
player = _player.GetByUniqueID(tostring(player));
end;
if ( player and type(player) == "Player" ) then
timer.Simple(1, function()
if ( IsValid(player) ) then
TERRITORY:UpdateDoorOwner(player, tobool(bValue));
end;
end);
end;
end;
function PLUGIN:PlayerCanBuyTerritory( TERRITORY, player, sPriceType )
local nPrice = TERRITORY:GetPrice( sPriceType );
if ( !self.class[sPriceType] ) then
return false, "Incorrect price type."
elseif ( TERRITORY:GetOwnerLevel(player) > 0 ) then
return false, "Вы уже владелец этой территорией.";
elseif ( TERRITORY:IsOwned() ) then
local tOwnerNames = {}
for uid, v in pairs( TERRITORY:GetOwners() ) do
table.insert( tOwnerNames, v.name )
end;
return false, "Эта территория уже занята: " .. table.concat( tOwnerNames, ", " )..".";
elseif ( nPrice <= 0 ) then
return false, "Эта территории бесценна =) Позовите админа, пусть исправит!";
elseif ( !self:P_CanAfford( sPriceType, player, nPrice ) ) then
return false, "Вам это не по корману!";
end;
end;
function PLUGIN:PlayerCanSellTerritory( TERRITORY, player )
if ( TERRITORY:GetOwnerLevel(player) < 2 ) then
return false, "Вы не можете продать эту территорию.";
end;
end;
function PLUGIN:OnTerritoryChangePermission( TERRITORY, sPermissionName, sCharterName, player, bValue )
if ( sPermissionName == "owner" or sPermissionName == "coowner" ) then
local uid, sid, sName = greenCode.session:GetPlayerData(player);
local tData = sPermissionName == "owner" and TERRITORY:GetOwners() or TERRITORY:GetCoOwners();
if ( bValue ) then
tData[uid] = { name = sName, sid = sid };
else
tData[uid] = nil;
end;
TERRITORY:SetData( sPermissionName, tData );
greenCode.plugin:Call( "OnTerrytoryChangeOwners", TERRITORY, player, bValue );
elseif ( sPermissionName == "canowning" and sCharterName == "public" ) then
TERRITORY:SetData( "forsale", bValue );
elseif ( sPermissionName == "spawnobject" and sCharterName == "private" ) then
local uid, _, sName = greenCode.session:GetPlayerData(player);
local tPropSpawnData = TERRITORY("propSpawn", {});
tPropSpawnData[uid] = bValue and sName or nil;
TERRITORY:SetData( "propSpawn", tPropSpawnData );
end;
end;
function PLUGIN:OnTerrytoryCreate( tTerritoryData )
tTerritoryData["owner"] = {};
tTerritoryData["coowner"] = {};
tTerritoryData["price"] = { session = 0 };
tTerritoryData["forsale"] = false;
tTerritoryData["propSpawn"] = {};
tTerritoryData["ownerSession"] = 0;
tTerritoryData["_rent"] = 0;
tTerritoryData["lastBuyType"] = "";
end;
-- Called when player try buy door.
function PLUGIN:PlayerBuyDoor( player, eDoor )
local TERRITORY = TER_PLUGIN:GetLocation( eDoor:GetPos() );
if ( TERRITORY and TERRITORY:IsValid() and !eDoor:AllowedToOwn( player ) and TERRITORY:GetOwnerLevel(player) < 2 ) then
GAMEMODE:Notify( player, 1, 4, "Дверь часть территории '" .. TERRITORY:GetName().. "'." );
return false;
end;
end;
-- Called when player try buy door.
function PLUGIN:PlayerSellDoor( player, eDoor )
local TERRITORY = TER_PLUGIN:GetLocation( eDoor:GetPos() );
if ( TERRITORY and TERRITORY:IsValid() and TERRITORY:UniqueID() != 0 ) then
GAMEMODE:Notify( player, 1, 4, "Дверь часть территории '" .. TERRITORY:GetName().. "'." );
return false;
end;
end;
function PLUGIN:OnTerritoryPrintInfo( player, TERRITORY )
ULib.console( player, "\t\tOwner Level = " .. TERRITORY:GetOwnerLevel(player) );
ULib.console( player, "\t\tFor sale = " .. tostring(TERRITORY("forsale",false)) );
ULib.console( player, "\t\tLast Buy = " .. tostring(TERRITORY("lastBuyType","none")) );
ULib.console( player, "\t\tPrice:" );
for sType, nAmount in pairs( TERRITORY:GetAllPrice() ) do
ULib.console( player, "\t\t\t"..sType.." = " .. nAmount );
end;
end;
-- Called when player buy some territory.
function PLUGIN:OnTerritoryBuy( TERRITORY, player, sPriceType, SESSION )
-- to session buy, parent session to player.
if ( sPriceType == "session" ) then
SESSION:SetParent( tonumber(player:UniqueID()) );
elseif ( sPriceType == "rent" ) then
SESSION:SetTimeOut( greenCode.config:Get("rent_time"):Get(15)*60 );
SESSION:SetParent(-1); -- Clean parent if before playey buy in seesion.
elseif ( sPriceType == "perm" ) then
SESSION:SetParent(-1); -- Clean parent if before playey buy in seesion or rent.
end;
TERRITORY:SetData("ownerSession", SESSION:UniqueID());
player:EmitSound( "greencode/mission_passed"..math.random(1,2)..".mp3" );
greenCode.hint:SendAll( player:Name().." купил территорию ["..TERRITORY:GetName().."] "..sPriceType..".", 5, Color( 100, 255, 100 ) );
player:ConCommand("cl_gc_custommenu_update 7920");
end;
-- This fix to shared.lua
GAMEMODE.DefaultTeam = TEAM_CITIZEN;
-- Called when player sell some territory.
function PLUGIN:OnTerritorySell( TERRITORY, player )
-- Set default team
if ( self:HoldingCount(player) < 1 ) then
player:ChangeTeam(GAMEMODE.DefaultTeam, true);
end;
-- Remove props.
local tRemovedProps = { "Territory "..TERRITORY:Name().." - "..TERRITORY:UniqueID().." sell removed props:" };
for k, v in pairs( _ents.GetAll() ) do
if ( v.FPPOwnerID and TER_PLUGIN:GetLocation( v:GetPos() ) == TERRITORY ) then
table.insert( tRemovedProps, "["..v.FPPOwnerID.."] ["..v:EntIndex().." ["..v:GetClass().."]" );
v:Remove();
end;
end;
if ( #tRemovedProps > 1 ) then
greenCode:Debug( table.concat(tRemovedProps, "\n\t\t") );
end;
-- Update info
greenCode.hint:SendAll( player:Name().." продал территорию ["..TERRITORY:GetName().."] "..".", 5, Color( 100, 255, 100 ) );
player:ConCommand("cl_gc_custommenu_update 7920");
end;
function PLUGIN:OnTerritorySendData( tTerritoryData )
tTerritoryData.ownerSession = nil;
end;
function PLUGIN:OnSessionChangeTimeOut( SESSION, nValue, nPrev )
local tData = SESSION("territoryData");
if ( tData and tData.permission == "owner" ) then
local TERRITORY = TER_PLUGIN:FindByID(tData.uid);
if ( TERRITORY and TERRITORY:IsValid() and TERRITORY("lastBuyType") == "rent" ) then
local curTime = CurTime();
local nEndTime = math.ceil( curTime + nValue );
local difference = math.abs(TERRITORY("_rent", 0) - nEndTime);
if ( difference > 1 ) then
TERRITORY:SetData("_rent", nEndTime);
end;
if ( nValue == 300 or nValue == 180 or nValue == 180 ) then
for _, player in pairs( TERRITORY:GetOnlineOwners() ) do
greenCode.hint:Send( player, "До продления аренды '"..TERRITORY:Name().."' осталось "..math.Round(nValue/60).." мин.", 5, Color( 255, 255, 100 ), nil, true );
end;
end;
end;
end;
end;
function PLUGIN:GroupPay( tGroup, nPrice )
local nGoodPrice = math.Round( nPrice / #tGroup );
for k, player in pairs( tGroup ) do
if ( !self:P_CanAfford( "rent", player, nGoodPrice ) and !player:DepositsCanAfford(nGoodPrice) ) then
local nNotHave = nGoodPrice - (player:getDarkRPVar("money") or 0);
player.gcGroupPay = player.gcGroupPay + (nGoodPrice - nNotHave);
tGroup[k] = nil;
return self:GroupPay( tGroup, nPrice - (nGoodPrice-nNotHave) );
else
player.gcGroupPay = player.gcGroupPay + nGoodPrice;
nPrice = nPrice - nGoodPrice;
end;
end;
return nPrice;
end;
function PLUGIN:PreSessionClose( SESSION, uid )
local tData = SESSION("territoryData");
if ( tData ) then
local TERRITORY = TER_PLUGIN:FindByID(tData.uid);
if ( TERRITORY and TERRITORY:IsValid() and TERRITORY("lastBuyType") == "rent" ) then
local nPrice = TERRITORY:GetPrice("rent");
local tOwners = TERRITORY:GetOnlineOwners();
local nGoodPrice = math.Round( nPrice / #tOwners );
for _, player in pairs( tOwners ) do
player.gcGroupPay = 0;
end;
local nCost = self:GroupPay( tOwners, nPrice );
if ( nCost <= 0 ) then
for _, player in pairs( tOwners ) do
local bShouldDeposit = false;
local DEPOSIT;
if ( self:P_CanAfford( "rent", player, player.gcGroupPay ) ) then
self:P_AddMoney( "rent", player, -player.gcGroupPay );
else
DEPOSIT = player:DepositsCanAfford(-player.gcGroupPay);
if ( DEPOSIT ) then
DEPOSIT:AddMoney(-player.gcGroupPay);
bShouldDeposit = true;
end;
end;
greenCode.hint:Send( player, "Автоматическое продление аренды '"..TERRITORY:Name().."' "..greenCode.kernel:FormatNumber(player.gcGroupPay).."$"..( bShouldDeposit and " Оплата со счета #"..DEPOSIT:UniqueID().." - "..DEPOSIT:Name().."." or "" ), 5, Color( 255, 255, 100 ), nil, true );
end;
SESSION:SetTimeOut( greenCode.config:Get("rent_time"):Get(15)*60 );
end;
end;
end;
end;
--------------------
-- PLUGIN COMMAND --
--------------------
greenCode.command:Add( "ter_buy", 0, function( player, command, args )
if ( #args < 2 ) then return; end;
local bDone, sReason;
local TERRITORY = TER_PLUGIN:FindByID(tonumber(args[1])) or TER_PLUGIN:FindByName(args[1]);
if ( TERRITORY and TERRITORY:IsValid() ) then
bDone, sReason = TERRITORY:Buy( player, args[2] );
else
bDone, sReason = false, "Territory not found.";
end;
if ( !bDone ) then
greenCode.hint:Send( player, sReason, 5, Color( 255, 100, 100 ), nil, true );
end
end);
greenCode.command:Add( "ter_sell", 0, function( player, command, args )
if ( #args < 1 ) then return; end;
local bDone, sReason;
local TERRITORY = TER_PLUGIN:FindByID(tonumber(args[1])) or TER_PLUGIN:FindByName(args[1]);
if ( TERRITORY and TERRITORY:IsValid() ) then
bDone, sReason = TERRITORY:Sell( player, args[2] );
else
bDone, sReason = false, "Territory not found.";
end;
if ( !bDone ) then
greenCode.hint:Send( player, sReason, 5, Color( 255, 100, 100 ), nil, true );
end
end);
greenCode.command:Add( "ter_allowcoown", 0, function( player, command, args )
if ( #args < 3 ) then return; end;
local bDone, sReason;
local TERRITORY = TER_PLUGIN:FindByID(tonumber(args[1])) or TER_PLUGIN:FindByName(args[1]);
local bValue = tobool(args[3]) or nil;
local TARGET_PLY_SESSION;
if ( TERRITORY and TERRITORY:IsValid() ) then
if ( TERRITORY:GetOwnerLevel(player) > 1 ) then
local target_ply_uid, calling_ply_uid = tonumber(args[2]), tonumber(player:UniqueID());
TARGET_PLY_SESSION = greenCode.session:FindByID(target_ply_uid or -1);
if ( target_ply_uid != calling_ply_uid and TARGET_PLY_SESSION and TARGET_PLY_SESSION:IsValid() and TARGET_PLY_SESSION("sid") ) then
local sessionName = "private_"..calling_ply_uid.."_owner_"..TERRITORY:UniqueID();
local sessionUID = tonumber(util.CRC(sessionName));
local OWN_SESSION = greenCode.session:FindByID(sessionUID);
if ( OWN_SESSION and OWN_SESSION:IsValid() and OWN_SESSION("territoryData") ) then
local bShould, sError, PERM_SESSION;
if ( bValue ) then
bShould, sError, PERM_SESSION = TERRITORY:AddCoOwner( player, target_ply_uid );
else
bShould, sError, PERM_SESSION = TERRITORY:RemoveCoOwner( player, target_ply_uid );
end;
if ( bShould ) then
PERM_SESSION:SetParent(OWN_SESSION:UniqueID()); -- Remove coowner when owner buy session in close.
player:ConCommand("cl_gc_custommenu_update 7920");
bDone, sReason = bValue, "Вы "..(bValue and "добавили в совладельци " or "удалили из совладельцев ")..TARGET_PLY_SESSION:Name().." на '"..TERRITORY:Name().."'.";
else
sReason = sError;
end;
else
bDone, sReason = false, "Inccorect owner session uid.";
end;
else
bDone, sReason = false, "Inccorect player uid.";
end;
else
bDone, sReason = false, "У вас нет прав.";
end;
else
bDone, sReason = false, "Territory not found.";
end;
if ( bDone ) then
greenCode.hint:SendAll( player:Name()..(bValue and "добавил в совладельци " or "удалил из совладельцев ")..TARGET_PLY_SESSION:Name().." на '"..TERRITORY:Name().."'.", 5, bValue and Color(100,255,100) or Color(255,100,100), nil, true );
else
greenCode.hint:Send( player, sReason, 5, Color(255,100,100), nil, true );
end;
end);
greenCode.command:Add( "ter_allowspawn", 0, function( player, command, args )
if ( #args < 3 ) then return; end;
local bDone, sReason;
local TERRITORY = TER_PLUGIN:FindByID(tonumber(args[1])) or TER_PLUGIN:FindByName(args[1]);
local bValue = tobool(args[3]) or nil;
local PLY_SESSION
if ( TERRITORY and TERRITORY:IsValid() ) then
local nOwnerLevel = TERRITORY:GetOwnerLevel(player);
if ( nOwnerLevel > 0 ) then
local target_ply_uid, calling_ply_uid = tonumber(args[2]), tonumber(player:UniqueID());
PLY_SESSION = greenCode.session:FindByID(target_ply_uid or -1);
if ( target_ply_uid != calling_ply_uid and PLY_SESSION and PLY_SESSION:IsValid() and PLY_SESSION("sid") ) then
local sessionName = "private_"..calling_ply_uid..( nOwnerLevel > 1 and "_owner_" or "_coowner_")..TERRITORY:UniqueID();
local sessionUID = tonumber(util.CRC(sessionName));
local OWN_SESSION = greenCode.session:FindByID(sessionUID);
if ( OWN_SESSION and OWN_SESSION:IsValid() and OWN_SESSION("territoryData") ) then
local bShould, sError, PERM_SESSION = TERRITORY:SetPermission( "private", "spawnobject", target_ply_uid, bValue, bValue and os.time() );
if ( bShould ) then
PERM_SESSION:SetParent(OWN_SESSION:UniqueID()); -- Remove propspawn when owner buy session in close.
player:ConCommand("cl_gc_custommenu_update 7920");
bDone, sReason = true, "Вы "..(bValue and "разрешили" or "запретили").." "..PLY_SESSION:Name().." spawn объектов на '"..TERRITORY:Name().."'.";
else
sReason = sError;
end;
else
bDone, sReason = false, "Inccorect owner session uid.";
end;
else
bDone, sReason = false, "Inccorect player uid.";
end;
else
bDone, sReason = false, "У вас нет прав.";
end;
else
bDone, sReason = false, "Territory not found.";
end;
if ( bDone ) then
greenCode.hint:Send( player, sReason, 5, bValue and Color(100,255,100) or Color(255,100,100), nil, true );
for _, v in pairs( TERRITORY:GetOnlineOwners(true) ) do
if ( player == v ) then
continue;
end;
greenCode.hint:Send( v, player:Name()..(bValue and " разрешили " or " запретили ")..PLY_SESSION:Name().." spawn объектов на '"..TERRITORY:Name().."'.", 5, bValue and Color(100,255,100) or Color(255,100,100), nil, true );
end;
else
greenCode.hint:Send( player, sReason, 5, Color(255,100,100), nil, true );
end;
end); | mit |
ByteFun/Starbound_mods | smount/tech/mech/mount30/mount30.lua | 1 | 35539 | 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")
local blinkHeadOffset = tech.parameter("blinkHeadOffset")
if doPathCheck then
local collisionBlocks = world.collisionBlocksAlongLine(mcontroller.position(), position, {"Null", "Block", "Dynamic"}, 1)
if #collisionBlocks ~= 0 then
local diff = world.distance(position, mcontroller.position())
diff[1] = diff[1] > 0 and 1 or -1
diff[2] = diff[2] > 0 and 1 or -1
position = {collisionBlocks[1][1] - math.min(diff[1], 0), collisionBlocks[1][2] - math.min(diff[2], 0)}
end
end
if doCollisionCheck then
local diff = world.distance(position, mcontroller.position())
local collisionPoly = mcontroller.collisionPoly()
--Add foot offset if there is ground
if diff[2] < 0 then
local groundBlocks = world.collisionBlocksAlongLine(position, {position[1], position[2] + blinkFootOffset}, {"Null", "Block", "Dynamic"}, 1)
if #groundBlocks > 0 then
position[2] = groundBlocks[1][2] + 1 - blinkFootOffset
end
end
--Add head offset if there is ceiling
if diff[2] > 0 then
local ceilingBlocks = world.collisionBlocksAlongLine(position, {position[1], position[2] + blinkHeadOffset}, {"Null", "Block", "Dynamic"}, 1)
if #ceilingBlocks > 0 then
position[2] = ceilingBlocks[1][2] - blinkHeadOffset
end
end
--Resolve position
position = world.resolvePolyCollision(collisionPoly, position, blinkCollisionCheckDiameter)
if not position or world.lineTileCollision(mcontroller.position(), position, {"Null", "Block", "Dynamic"}) 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.pointTileCollision(checkPosition, {"Null", "Block", "Dynamic", "Platform"}) 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
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.aoeLastInput = 0
self.aoeTapLast = 0
self.aoeTapTimer = 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[""] 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[""] 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
------------------------
local maximumDoubleTapTime2 = tech.parameter("maximumDoubleTapTime2")
if self.aoeTapTimer > 0 then
self.aoeTapTimer = self.aoeTapTimer - args.dt
end
if args.moves["down"] and self.active then
if self.aoeLastInput ~= 1 then
if self.aoeTapLast == 1 and self.aoeTapTimer > 0 then
self.aoeTapLast = 0
self.aoeTapTimer = 0
return "mechSecFire"
else
self.aoeTapLast = 1
self.aoeTapTimer = maximumDoubleTapTime2
end
end
self.aoeLastInput = 1
else
self.aoeLastInput = 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["special"] == 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)
tech.burstParticleEmitter("glowParticles")
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
world.spawnProjectile(mechSecProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontSecGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig)
tech.setAnimationState("frontSecFiring", "fireSec")
-- if self.fireSecTimer <= 0 then
-- world.spawnProjectile(mechSecProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontSecGun", "firePoint")), entity.id(), {math.cos(0), math.sin(0)}, false, mechAltProjectileConfig)
-- self.fireSecTimer = self.fireSecTimer + mechSecFireCycle
-- tech.setAnimationState("frontSecFiring", "fireSec")
-- else
-- local oldFireSecTimer = self.fireSecTimer
-- self.fireSecTimer = self.fireSecTimer - args.dt
-- if oldFireSecTimer > mechSecFireCycle / 2 and self.fireSecTimer <= 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/Windurst_Woods/npcs/Erpolant.lua | 38 | 1038 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Erpolant
-- Type: Standard NPC
-- @zone: 241
-- @pos -63.224 -0.749 -33.424
--
-- 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)
player:startEvent(0x01bc);
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/Abyssea-Misareaux/npcs/qm16.lua | 17 | 1539 | -----------------------------------
-- Zone: Abyssea-Misereaux
-- NPC: ???
-- Spawns: Ironclad Pulverizor
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(17662484) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(BLAZING_CLUSTER_SOUL) and player:hasKeyItem(SCALDING_IRONCLAD_SPIKE)) then
player:startEvent(1021, BLAZING_CLUSTER_SOUL, SCALDING_IRONCLAD_SPIKE); -- Ask if player wants to use KIs
else
player:startEvent(1020, BLAZING_CLUSTER_SOUL, SCALDING_IRONCLAD_SPIKE); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1021 and option == 1) then
SpawnMob(17662484):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(BLAZING_CLUSTER_SOUL);
player:delKeyItem(SCALDING_IRONCLAD_SPIKE);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/prime_seafood_stewpot.lua | 36 | 1861 | -----------------------------------------
-- ID: 5239
-- Item: Prime Seafood Stewpot
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10% Cap 75
-- MP +15
-- Dexterity 1
-- Vitality 1
-- Agility 1
-- Mind 1
-- HP Recovered while healing 7
-- MP Recovered while healing 2
-- Accuracy 6
-- Evasion 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5239);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 10);
target:addMod(MOD_FOOD_HP_CAP, 75);
target:addMod(MOD_MP, 15);
target:addMod(MOD_DEX, 1);
target:addMod(MOD_VIT, 1);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_MND, 1);
target:addMod(MOD_HPHEAL, 7);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_ACC, 6);
target:addMod(MOD_EVA, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 10);
target:delMod(MOD_FOOD_HP_CAP, 75);
target:delMod(MOD_MP, 15);
target:delMod(MOD_DEX, 1);
target:delMod(MOD_VIT, 1);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_MND, 1);
target:delMod(MOD_HPHEAL, 7);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_ACC, 6);
target:delMod(MOD_EVA, 6);
end;
| gpl-3.0 |
georgekang/jit-construct | dynasm/dasm_x86.lua | 116 | 58970 | ------------------------------------------------------------------------------
-- DynASM x86/x64 module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
local x64 = x64
-- Module information:
local _info = {
arch = x64 and "x64" or "x86",
description = "DynASM x86/x64 module",
version = "1.3.0",
vernum = 10300,
release = "2011-05-05",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub
local concat, sort = table.concat, table.sort
local bit = bit or require("bit")
local band, shl, shr = bit.band, bit.lshift, bit.rshift
-- Inherited tables and callbacks.
local g_opt, g_arch
local wline, werror, wfatal, wwarn
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
-- int arg, 1 buffer pos:
"DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB",
-- action arg (1 byte), int arg, 1 buffer pos (reg/num):
"VREG", "SPACE", -- !x64: VREG support NYI.
-- ptrdiff_t arg, 1 buffer pos (address): !x64
"SETLABEL", "REL_A",
-- action arg (1 byte) or int arg, 2 buffer pos (link, offset):
"REL_LG", "REL_PC",
-- action arg (1 byte) or int arg, 1 buffer pos (link):
"IMM_LG", "IMM_PC",
-- action arg (1 byte) or int arg, 1 buffer pos (offset):
"LABEL_LG", "LABEL_PC",
-- action arg (1 byte), 1 buffer pos (offset):
"ALIGN",
-- action args (2 bytes), no buffer pos.
"EXTERN",
-- action arg (1 byte), no buffer pos.
"ESC",
-- no action arg, no buffer pos.
"MARK",
-- action arg (1 byte), no buffer pos, terminal action:
"SECTION",
-- no args, no buffer pos, terminal action:
"STOP"
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number (dynamically generated below).
local map_action = {}
-- First action number. Everything below does not need to be escaped.
local actfirst = 256-#action_names
-- Action list buffer and string (only used to remove dupes).
local actlist = {}
local actstr = ""
-- Argument list for next dasm_put(). Start with offset 0 into action list.
local actargs = { 0 }
-- Current number of section buffer positions for dasm_put().
local secpos = 1
------------------------------------------------------------------------------
-- Compute action numbers for action names.
for n,name in ipairs(action_names) do
local num = actfirst + n - 1
map_action[name] = num
end
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
local last = actlist[nn] or 255
actlist[nn] = nil -- Remove last byte.
if nn == 0 then nn = 1 end
out:write("static const unsigned char ", name, "[", nn, "] = {\n")
local s = " "
for n,b in ipairs(actlist) do
s = s..b..","
if #s >= 75 then
assert(out:write(s, "\n"))
s = " "
end
end
out:write(s, last, "\n};\n\n") -- Add last byte back.
end
------------------------------------------------------------------------------
-- Add byte to action list.
local function wputxb(n)
assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, a, num)
wputxb(assert(map_action[action], "bad action name `"..action.."'"))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Add call to embedded DynASM C code.
local function wcall(func, args)
wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true)
end
-- Delete duplicate action list chunks. A tad slow, but so what.
local function dedupechunk(offset)
local al, as = actlist, actstr
local chunk = char(unpack(al, offset+1, #al))
local orig = find(as, chunk, 1, true)
if orig then
actargs[1] = orig-1 -- Replace with original offset.
for i=offset+1,#al do al[i] = nil end -- Kill dupe.
else
actstr = as..chunk
end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
local offset = actargs[1]
if #actlist == offset then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
dedupechunk(offset)
wcall("put", actargs) -- Add call to dasm_put().
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped byte.
local function wputb(n)
if n >= actfirst then waction("ESC") end -- Need to escape byte.
wputxb(n)
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 10
local map_global = setmetatable({}, { __index = function(t, name)
if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end
local n = next_global
if n > 246 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end})
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=10,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("enum {\n")
for i=10,next_global-1 do
out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=10,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern = -1
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n < -256 then werror("too many extern labels") end
next_extern = n - 1
t[name] = n
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
local t = {}
for name, n in pairs(map_extern) do t[-n] = name end
out:write("Extern labels:\n")
for i=1,-next_extern-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
local t = {}
for name, n in pairs(map_extern) do t[-n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=1,-next_extern-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
local map_archdef = {} -- Ext. register name -> int. name.
local map_reg_rev = {} -- Int. register name -> ext. name.
local map_reg_num = {} -- Int. register name -> register number.
local map_reg_opsize = {} -- Int. register name -> operand size.
local map_reg_valid_base = {} -- Int. register name -> valid base register?
local map_reg_valid_index = {} -- Int. register name -> valid index register?
local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex.
local reg_list = {} -- Canonical list of int. register names.
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for _PTx macros).
local addrsize = x64 and "q" or "d" -- Size for address operands.
-- Helper functions to fill register maps.
local function mkrmap(sz, cl, names)
local cname = format("@%s", sz)
reg_list[#reg_list+1] = cname
map_archdef[cl] = cname
map_reg_rev[cname] = cl
map_reg_num[cname] = -1
map_reg_opsize[cname] = sz
if sz == addrsize or sz == "d" then
map_reg_valid_base[cname] = true
map_reg_valid_index[cname] = true
end
if names then
for n,name in ipairs(names) do
local iname = format("@%s%x", sz, n-1)
reg_list[#reg_list+1] = iname
map_archdef[name] = iname
map_reg_rev[iname] = name
map_reg_num[iname] = n-1
map_reg_opsize[iname] = sz
if sz == "b" and n > 4 then map_reg_needrex[iname] = false end
if sz == addrsize or sz == "d" then
map_reg_valid_base[iname] = true
map_reg_valid_index[iname] = true
end
end
end
for i=0,(x64 and sz ~= "f") and 15 or 7 do
local needrex = sz == "b" and i > 3
local iname = format("@%s%x%s", sz, i, needrex and "R" or "")
if needrex then map_reg_needrex[iname] = true end
local name
if sz == "o" then name = format("xmm%d", i)
elseif sz == "f" then name = format("st%d", i)
else name = format("r%d%s", i, sz == addrsize and "" or sz) end
map_archdef[name] = iname
if not map_reg_rev[iname] then
reg_list[#reg_list+1] = iname
map_reg_rev[iname] = name
map_reg_num[iname] = i
map_reg_opsize[iname] = sz
if sz == addrsize or sz == "d" then
map_reg_valid_base[iname] = true
map_reg_valid_index[iname] = true
end
end
end
reg_list[#reg_list+1] = ""
end
-- Integer registers (qword, dword, word and byte sized).
if x64 then
mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"})
end
mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"})
mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"})
mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"})
map_reg_valid_index[map_archdef.esp] = false
if x64 then map_reg_valid_index[map_archdef.rsp] = false end
map_archdef["Ra"] = "@"..addrsize
-- FP registers (internally tword sized, but use "f" as operand size).
mkrmap("f", "Rf")
-- SSE registers (oword sized, but qword and dword accessible).
mkrmap("o", "xmm")
-- Operand size prefixes to codes.
local map_opsize = {
byte = "b", word = "w", dword = "d", qword = "q", oword = "o", tword = "t",
aword = addrsize,
}
-- Operand size code to number.
local map_opsizenum = {
b = 1, w = 2, d = 4, q = 8, o = 16, t = 10,
}
-- Operand size code to name.
local map_opsizename = {
b = "byte", w = "word", d = "dword", q = "qword", o = "oword", t = "tword",
f = "fpword",
}
-- Valid index register scale factors.
local map_xsc = {
["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3,
}
-- Condition codes.
local map_cc = {
o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7,
s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15,
c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7,
pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15,
}
-- Reverse defines for registers.
function _M.revdef(s)
return gsub(s, "@%w+", map_reg_rev)
end
-- Dump register names and numbers
local function dumpregs(out)
out:write("Register names, sizes and internal numbers:\n")
for _,reg in ipairs(reg_list) do
if reg == "" then
out:write("\n")
else
local name = map_reg_rev[reg]
local num = map_reg_num[reg]
local opsize = map_opsizename[map_reg_opsize[reg]]
out:write(format(" %-5s %-8s %s\n", name, opsize,
num < 0 and "(variable)" or num))
end
end
end
------------------------------------------------------------------------------
-- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC).
local function wputlabel(aprefix, imm, num)
if type(imm) == "number" then
if imm < 0 then
waction("EXTERN")
wputxb(aprefix == "IMM_" and 0 or 1)
imm = -imm-1
else
waction(aprefix.."LG", nil, num);
end
wputxb(imm)
else
waction(aprefix.."PC", imm, num)
end
end
-- Put signed byte or arg.
local function wputsbarg(n)
if type(n) == "number" then
if n < -128 or n > 127 then
werror("signed immediate byte out of range")
end
if n < 0 then n = n + 256 end
wputb(n)
else waction("IMM_S", n) end
end
-- Put unsigned byte or arg.
local function wputbarg(n)
if type(n) == "number" then
if n < 0 or n > 255 then
werror("unsigned immediate byte out of range")
end
wputb(n)
else waction("IMM_B", n) end
end
-- Put unsigned word or arg.
local function wputwarg(n)
if type(n) == "number" then
if shr(n, 16) ~= 0 then
werror("unsigned immediate word out of range")
end
wputb(band(n, 255)); wputb(shr(n, 8));
else waction("IMM_W", n) end
end
-- Put signed or unsigned dword or arg.
local function wputdarg(n)
local tn = type(n)
if tn == "number" then
wputb(band(n, 255))
wputb(band(shr(n, 8), 255))
wputb(band(shr(n, 16), 255))
wputb(shr(n, 24))
elseif tn == "table" then
wputlabel("IMM_", n[1], 1)
else
waction("IMM_D", n)
end
end
-- Put operand-size dependent number or arg (defaults to dword).
local function wputszarg(sz, n)
if not sz or sz == "d" or sz == "q" then wputdarg(n)
elseif sz == "w" then wputwarg(n)
elseif sz == "b" then wputbarg(n)
elseif sz == "s" then wputsbarg(n)
else werror("bad operand size") end
end
-- Put multi-byte opcode with operand-size dependent modifications.
local function wputop(sz, op, rex)
local r
if rex ~= 0 and not x64 then werror("bad operand size") end
if sz == "w" then wputb(102) end
-- Needs >32 bit numbers, but only for crc32 eax, word [ebx]
if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end
if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end
if op >= 65536 then
if rex ~= 0 then
local opc3 = band(op, 0xffff00)
if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then
wputb(64 + band(rex, 15)); rex = 0
end
end
wputb(shr(op, 16)); op = band(op, 0xffff)
end
if op >= 256 then
local b = shr(op, 8)
if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0 end
wputb(b)
op = band(op, 255)
end
if rex ~= 0 then wputb(64 + band(rex, 15)) end
if sz == "b" then op = op - 1 end
wputb(op)
end
-- Put ModRM or SIB formatted byte.
local function wputmodrm(m, s, rm, vs, vrm)
assert(m < 4 and s < 16 and rm < 16, "bad modrm operands")
wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7))
end
-- Put ModRM/SIB plus optional displacement.
local function wputmrmsib(t, imark, s, vsreg)
local vreg, vxreg
local reg, xreg = t.reg, t.xreg
if reg and reg < 0 then reg = 0; vreg = t.vreg end
if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end
if s < 0 then s = 0 end
-- Register mode.
if sub(t.mode, 1, 1) == "r" then
wputmodrm(3, s, reg)
if vsreg then waction("VREG", vsreg); wputxb(2) end
if vreg then waction("VREG", vreg); wputxb(0) end
return
end
local disp = t.disp
local tdisp = type(disp)
-- No base register?
if not reg then
local riprel = false
if xreg then
-- Indexed mode with index register only.
-- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp)
wputmodrm(0, s, 4)
if imark == "I" then waction("MARK") end
if vsreg then waction("VREG", vsreg); wputxb(2) end
wputmodrm(t.xsc, xreg, 5)
if vxreg then waction("VREG", vxreg); wputxb(3) end
else
-- Pure 32 bit displacement.
if x64 and tdisp ~= "table" then
wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp)
if imark == "I" then waction("MARK") end
wputmodrm(0, 4, 5)
else
riprel = x64
wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp)
if imark == "I" then waction("MARK") end
end
if vsreg then waction("VREG", vsreg); wputxb(2) end
end
if riprel then -- Emit rip-relative displacement.
if match("UWSiI", imark) then
werror("NYI: rip-relative displacement followed by immediate")
end
-- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f.
wputlabel("REL_", disp[1], 2)
else
wputdarg(disp)
end
return
end
local m
if tdisp == "number" then -- Check displacement size at assembly time.
if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too)
if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0]
elseif disp >= -128 and disp <= 127 then m = 1
else m = 2 end
elseif tdisp == "table" then
m = 2
end
-- Index register present or esp as base register: need SIB encoding.
if xreg or band(reg, 7) == 4 then
wputmodrm(m or 2, s, 4) -- ModRM.
if m == nil or imark == "I" then waction("MARK") end
if vsreg then waction("VREG", vsreg); wputxb(2) end
wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB.
if vxreg then waction("VREG", vxreg); wputxb(3) end
if vreg then waction("VREG", vreg); wputxb(1) end
else
wputmodrm(m or 2, s, reg) -- ModRM.
if (imark == "I" and (m == 1 or m == 2)) or
(m == nil and (vsreg or vreg)) then waction("MARK") end
if vsreg then waction("VREG", vsreg); wputxb(2) end
if vreg then waction("VREG", vreg); wputxb(1) end
end
-- Put displacement.
if m == 1 then wputsbarg(disp)
elseif m == 2 then wputdarg(disp)
elseif m == nil then waction("DISP", disp) end
end
------------------------------------------------------------------------------
-- Return human-readable operand mode string.
local function opmodestr(op, args)
local m = {}
for i=1,#args do
local a = args[i]
m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?")
end
return op.." "..concat(m, ",")
end
-- Convert number to valid integer or nil.
local function toint(expr)
local n = tonumber(expr)
if n then
if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then
werror("bad integer number `"..expr.."'")
end
return n
end
end
-- Parse immediate expression.
local function immexpr(expr)
-- &expr (pointer)
if sub(expr, 1, 1) == "&" then
return "iPJ", format("(ptrdiff_t)(%s)", sub(expr,2))
end
local prefix = sub(expr, 1, 2)
-- =>expr (pc label reference)
if prefix == "=>" then
return "iJ", sub(expr, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "iJ", map_global[sub(expr, 3)]
end
-- [<>][1-9] (local label reference)
local dir, lnum = match(expr, "^([<>])([1-9])$")
if dir then -- Fwd: 247-255, Bkwd: 1-9.
return "iJ", lnum + (dir == ">" and 246 or 0)
end
local extname = match(expr, "^extern%s+(%S+)$")
if extname then
return "iJ", map_extern[extname]
end
-- expr (interpreted as immediate)
return "iI", expr
end
-- Parse displacement expression: +-num, +-expr, +-opsize*num
local function dispexpr(expr)
local disp = expr == "" and 0 or toint(expr)
if disp then return disp end
local c, dispt = match(expr, "^([+-])%s*(.+)$")
if c == "+" then
expr = dispt
elseif not c then
werror("bad displacement expression `"..expr.."'")
end
local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$")
local ops, imm = map_opsize[opsize], toint(tailops)
if ops and imm then
if c == "-" then imm = -imm end
return imm*map_opsizenum[ops]
end
local mode, iexpr = immexpr(dispt)
if mode == "iJ" then
if c == "-" then werror("cannot invert label reference") end
return { iexpr }
end
return expr -- Need to return original signed expression.
end
-- Parse register or type expression.
local function rtexpr(expr)
if not expr then return end
local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
local rnum = map_reg_num[reg]
if not rnum then
werror("type `"..(tname or expr).."' needs a register override")
end
if not map_reg_valid_base[reg] then
werror("bad base register override `"..(map_reg_rev[reg] or reg).."'")
end
return reg, rnum, tp
end
return expr, map_reg_num[expr]
end
-- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }.
local function parseoperand(param)
local t = {}
local expr = param
local opsize, tailops = match(param, "^(%w+)%s*(.+)$")
if opsize then
t.opsize = map_opsize[opsize]
if t.opsize then expr = tailops end
end
local br = match(expr, "^%[%s*(.-)%s*%]$")
repeat
if br then
t.mode = "xm"
-- [disp]
t.disp = toint(br)
if t.disp then
t.mode = x64 and "xm" or "xmO"
break
end
-- [reg...]
local tp
local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$")
reg, t.reg, tp = rtexpr(reg)
if not t.reg then
-- [expr]
t.mode = x64 and "xm" or "xmO"
t.disp = dispexpr("+"..br)
break
end
if t.reg == -1 then
t.vreg, tailr = match(tailr, "^(%b())(.*)$")
if not t.vreg then werror("bad variable register expression") end
end
-- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr]
local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$")
if xsc then
if not map_reg_valid_index[reg] then
werror("bad index register `"..map_reg_rev[reg].."'")
end
t.xsc = map_xsc[xsc]
t.xreg = t.reg
t.vxreg = t.vreg
t.reg = nil
t.vreg = nil
t.disp = dispexpr(tailsc)
break
end
if not map_reg_valid_base[reg] then
werror("bad base register `"..map_reg_rev[reg].."'")
end
-- [reg] or [reg+-disp]
t.disp = toint(tailr) or (tailr == "" and 0)
if t.disp then break end
-- [reg+xreg...]
local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$")
xreg, t.xreg, tp = rtexpr(xreg)
if not t.xreg then
-- [reg+-expr]
t.disp = dispexpr(tailr)
break
end
if not map_reg_valid_index[xreg] then
werror("bad index register `"..map_reg_rev[xreg].."'")
end
if t.xreg == -1 then
t.vxreg, tailx = match(tailx, "^(%b())(.*)$")
if not t.vxreg then werror("bad variable register expression") end
end
-- [reg+xreg*xsc...]
local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$")
if xsc then
t.xsc = map_xsc[xsc]
tailx = tailsc
end
-- [...] or [...+-disp] or [...+-expr]
t.disp = dispexpr(tailx)
else
-- imm or opsize*imm
local imm = toint(expr)
if not imm and sub(expr, 1, 1) == "*" and t.opsize then
imm = toint(sub(expr, 2))
if imm then
imm = imm * map_opsizenum[t.opsize]
t.opsize = nil
end
end
if imm then
if t.opsize then werror("bad operand size override") end
local m = "i"
if imm == 1 then m = m.."1" end
if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end
if imm >= -128 and imm <= 127 then m = m.."S" end
t.imm = imm
t.mode = m
break
end
local tp
local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$")
reg, t.reg, tp = rtexpr(reg)
if t.reg then
if t.reg == -1 then
t.vreg, tailr = match(tailr, "^(%b())(.*)$")
if not t.vreg then werror("bad variable register expression") end
end
-- reg
if tailr == "" then
if t.opsize then werror("bad operand size override") end
t.opsize = map_reg_opsize[reg]
if t.opsize == "f" then
t.mode = t.reg == 0 and "fF" or "f"
else
if reg == "@w4" or (x64 and reg == "@d4") then
wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'"))
end
t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm")
end
t.needrex = map_reg_needrex[reg]
break
end
-- type[idx], type[idx].field, type->field -> [reg+offset_expr]
if not tp then werror("bad operand `"..param.."'") end
t.mode = "xm"
t.disp = format(tp.ctypefmt, tailr)
else
t.mode, t.imm = immexpr(expr)
if sub(t.mode, -1) == "J" then
if t.opsize and t.opsize ~= addrsize then
werror("bad operand size override")
end
t.opsize = addrsize
end
end
end
until true
return t
end
------------------------------------------------------------------------------
-- x86 Template String Description
-- ===============================
--
-- Each template string is a list of [match:]pattern pairs,
-- separated by "|". The first match wins. No match means a
-- bad or unsupported combination of operand modes or sizes.
--
-- The match part and the ":" is omitted if the operation has
-- no operands. Otherwise the first N characters are matched
-- against the mode strings of each of the N operands.
--
-- The mode string for each operand type is (see parseoperand()):
-- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl
-- FP register: "f", +"F" for st0
-- Index operand: "xm", +"O" for [disp] (pure offset)
-- Immediate: "i", +"S" for signed 8 bit, +"1" for 1,
-- +"I" for arg, +"P" for pointer
-- Any: +"J" for valid jump targets
--
-- So a match character "m" (mixed) matches both an integer register
-- and an index operand (to be encoded with the ModRM/SIB scheme).
-- But "r" matches only a register and "x" only an index operand
-- (e.g. for FP memory access operations).
--
-- The operand size match string starts right after the mode match
-- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty.
-- The effective data size of the operation is matched against this list.
--
-- If only the regular "b", "w", "d", "q", "t" operand sizes are
-- present, then all operands must be the same size. Unspecified sizes
-- are ignored, but at least one operand must have a size or the pattern
-- won't match (use the "byte", "word", "dword", "qword", "tword"
-- operand size overrides. E.g.: mov dword [eax], 1).
--
-- If the list has a "1" or "2" prefix, the operand size is taken
-- from the respective operand and any other operand sizes are ignored.
-- If the list contains only ".", all operand sizes are ignored.
-- If the list has a "/" prefix, the concatenated (mixed) operand sizes
-- are compared to the match.
--
-- E.g. "rrdw" matches for either two dword registers or two word
-- registers. "Fx2dq" matches an st0 operand plus an index operand
-- pointing to a dword (float) or qword (double).
--
-- Every character after the ":" is part of the pattern string:
-- Hex chars are accumulated to form the opcode (left to right).
-- "n" disables the standard opcode mods
-- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q")
-- "X" Force REX.W.
-- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode.
-- "m"/"M" generates ModRM/SIB from the 1st/2nd operand.
-- The spare 3 bits are either filled with the last hex digit or
-- the result from a previous "r"/"R". The opcode is restored.
--
-- All of the following characters force a flush of the opcode:
-- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand.
-- "S" stores a signed 8 bit immediate from the last operand.
-- "U" stores an unsigned 8 bit immediate from the last operand.
-- "W" stores an unsigned 16 bit immediate from the last operand.
-- "i" stores an operand sized immediate from the last operand.
-- "I" dito, but generates an action code to optionally modify
-- the opcode (+2) for a signed 8 bit immediate.
-- "J" generates one of the REL action codes from the last operand.
--
------------------------------------------------------------------------------
-- Template strings for x86 instructions. Ordered by first opcode byte.
-- Unimplemented opcodes (deliberate omissions) are marked with *.
local map_op = {
-- 00-05: add...
-- 06: *push es
-- 07: *pop es
-- 08-0D: or...
-- 0E: *push cs
-- 0F: two byte opcode prefix
-- 10-15: adc...
-- 16: *push ss
-- 17: *pop ss
-- 18-1D: sbb...
-- 1E: *push ds
-- 1F: *pop ds
-- 20-25: and...
es_0 = "26",
-- 27: *daa
-- 28-2D: sub...
cs_0 = "2E",
-- 2F: *das
-- 30-35: xor...
ss_0 = "36",
-- 37: *aaa
-- 38-3D: cmp...
ds_0 = "3E",
-- 3F: *aas
inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m",
dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m",
push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or
"rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i",
pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m",
-- 60: *pusha, *pushad, *pushaw
-- 61: *popa, *popad, *popaw
-- 62: *bound rdw,x
-- 63: x86: *arpl mw,rw
movsxd_2 = x64 and "rm/qd:63rM",
fs_0 = "64",
gs_0 = "65",
o16_0 = "66",
a16_0 = not x64 and "67" or nil,
a32_0 = x64 and "67",
-- 68: push idw
-- 69: imul rdw,mdw,idw
-- 6A: push ib
-- 6B: imul rdw,mdw,S
-- 6C: *insb
-- 6D: *insd, *insw
-- 6E: *outsb
-- 6F: *outsd, *outsw
-- 70-7F: jcc lb
-- 80: add... mb,i
-- 81: add... mdw,i
-- 82: *undefined
-- 83: add... mdw,S
test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi",
-- 86: xchg rb,mb
-- 87: xchg rdw,mdw
-- 88: mov mb,r
-- 89: mov mdw,r
-- 8A: mov r,mb
-- 8B: mov r,mdw
-- 8C: *mov mdw,seg
lea_2 = "rx1dq:8DrM",
-- 8E: *mov seg,mdw
-- 8F: pop mdw
nop_0 = "90",
xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm",
cbw_0 = "6698",
cwde_0 = "98",
cdqe_0 = "4898",
cwd_0 = "6699",
cdq_0 = "99",
cqo_0 = "4899",
-- 9A: *call iw:idw
wait_0 = "9B",
fwait_0 = "9B",
pushf_0 = "9C",
pushfd_0 = not x64 and "9C",
pushfq_0 = x64 and "9C",
popf_0 = "9D",
popfd_0 = not x64 and "9D",
popfq_0 = x64 and "9D",
sahf_0 = "9E",
lahf_0 = "9F",
mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi",
movsb_0 = "A4",
movsw_0 = "66A5",
movsd_0 = "A5",
cmpsb_0 = "A6",
cmpsw_0 = "66A7",
cmpsd_0 = "A7",
-- A8: test Rb,i
-- A9: test Rdw,i
stosb_0 = "AA",
stosw_0 = "66AB",
stosd_0 = "AB",
lodsb_0 = "AC",
lodsw_0 = "66AD",
lodsd_0 = "AD",
scasb_0 = "AE",
scasw_0 = "66AF",
scasd_0 = "AF",
-- B0-B7: mov rb,i
-- B8-BF: mov rdw,i
-- C0: rol... mb,i
-- C1: rol... mdw,i
ret_1 = "i.:nC2W",
ret_0 = "C3",
-- C4: *les rdw,mq
-- C5: *lds rdw,mq
-- C6: mov mb,i
-- C7: mov mdw,i
-- C8: *enter iw,ib
leave_0 = "C9",
-- CA: *retf iw
-- CB: *retf
int3_0 = "CC",
int_1 = "i.:nCDU",
into_0 = "CE",
-- CF: *iret
-- D0: rol... mb,1
-- D1: rol... mdw,1
-- D2: rol... mb,cl
-- D3: rol... mb,cl
-- D4: *aam ib
-- D5: *aad ib
-- D6: *salc
-- D7: *xlat
-- D8-DF: floating point ops
-- E0: *loopne
-- E1: *loope
-- E2: *loop
-- E3: *jcxz, *jecxz
-- E4: *in Rb,ib
-- E5: *in Rdw,ib
-- E6: *out ib,Rb
-- E7: *out ib,Rdw
call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J",
jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB
-- EA: *jmp iw:idw
-- EB: jmp ib
-- EC: *in Rb,dx
-- ED: *in Rdw,dx
-- EE: *out dx,Rb
-- EF: *out dx,Rdw
lock_0 = "F0",
int1_0 = "F1",
repne_0 = "F2",
repnz_0 = "F2",
rep_0 = "F3",
repe_0 = "F3",
repz_0 = "F3",
-- F4: *hlt
cmc_0 = "F5",
-- F6: test... mb,i; div... mb
-- F7: test... mdw,i; div... mdw
clc_0 = "F8",
stc_0 = "F9",
-- FA: *cli
cld_0 = "FC",
std_0 = "FD",
-- FE: inc... mb
-- FF: inc... mdw
-- misc ops
not_1 = "m:F72m",
neg_1 = "m:F73m",
mul_1 = "m:F74m",
imul_1 = "m:F75m",
div_1 = "m:F76m",
idiv_1 = "m:F77m",
imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi",
imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi",
movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:",
movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:",
bswap_1 = "rqd:0FC8r",
bsf_2 = "rmqdw:0FBCrM",
bsr_2 = "rmqdw:0FBDrM",
bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU",
btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU",
btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU",
bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU",
shld_3 = "mriqdw:0FA4RmU|mrCqdw:0FA5Rm",
shrd_3 = "mriqdw:0FACRmU|mrCqdw:0FADRm",
rdtsc_0 = "0F31", -- P1+
cpuid_0 = "0FA2", -- P1+
-- floating point ops
fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m",
fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m",
fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m",
fpop_0 = "DDD8", -- Alias for fstp st0.
fist_1 = "xw:nDF2m|xd:DB2m",
fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m",
fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m",
fxch_0 = "D9C9",
fxch_1 = "ff:D9C8r",
fxch_2 = "fFf:D9C8r|Fff:D9C8R",
fucom_1 = "ff:DDE0r",
fucom_2 = "Fff:DDE0R",
fucomp_1 = "ff:DDE8r",
fucomp_2 = "Fff:DDE8R",
fucomi_1 = "ff:DBE8r", -- P6+
fucomi_2 = "Fff:DBE8R", -- P6+
fucomip_1 = "ff:DFE8r", -- P6+
fucomip_2 = "Fff:DFE8R", -- P6+
fcomi_1 = "ff:DBF0r", -- P6+
fcomi_2 = "Fff:DBF0R", -- P6+
fcomip_1 = "ff:DFF0r", -- P6+
fcomip_2 = "Fff:DFF0R", -- P6+
fucompp_0 = "DAE9",
fcompp_0 = "DED9",
fldenv_1 = "x.:D94m",
fnstenv_1 = "x.:D96m",
fstenv_1 = "x.:9BD96m",
fldcw_1 = "xw:nD95m",
fstcw_1 = "xw:n9BD97m",
fnstcw_1 = "xw:nD97m",
fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m",
fnstsw_1 = "Rw:nDFE0|xw:nDD7m",
fclex_0 = "9BDBE2",
fnclex_0 = "DBE2",
fnop_0 = "D9D0",
-- D9D1-D9DF: unassigned
fchs_0 = "D9E0",
fabs_0 = "D9E1",
-- D9E2: unassigned
-- D9E3: unassigned
ftst_0 = "D9E4",
fxam_0 = "D9E5",
-- D9E6: unassigned
-- D9E7: unassigned
fld1_0 = "D9E8",
fldl2t_0 = "D9E9",
fldl2e_0 = "D9EA",
fldpi_0 = "D9EB",
fldlg2_0 = "D9EC",
fldln2_0 = "D9ED",
fldz_0 = "D9EE",
-- D9EF: unassigned
f2xm1_0 = "D9F0",
fyl2x_0 = "D9F1",
fptan_0 = "D9F2",
fpatan_0 = "D9F3",
fxtract_0 = "D9F4",
fprem1_0 = "D9F5",
fdecstp_0 = "D9F6",
fincstp_0 = "D9F7",
fprem_0 = "D9F8",
fyl2xp1_0 = "D9F9",
fsqrt_0 = "D9FA",
fsincos_0 = "D9FB",
frndint_0 = "D9FC",
fscale_0 = "D9FD",
fsin_0 = "D9FE",
fcos_0 = "D9FF",
-- SSE, SSE2
andnpd_2 = "rmo:660F55rM",
andnps_2 = "rmo:0F55rM",
andpd_2 = "rmo:660F54rM",
andps_2 = "rmo:0F54rM",
clflush_1 = "x.:0FAE7m",
cmppd_3 = "rmio:660FC2rMU",
cmpps_3 = "rmio:0FC2rMU",
cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:",
cmpss_3 = "rrio:F30FC2rMU|rxi/od:",
comisd_2 = "rro:660F2FrM|rx/oq:",
comiss_2 = "rro:0F2FrM|rx/od:",
cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:",
cvtdq2ps_2 = "rmo:0F5BrM",
cvtpd2dq_2 = "rmo:F20FE6rM",
cvtpd2ps_2 = "rmo:660F5ArM",
cvtpi2pd_2 = "rx/oq:660F2ArM",
cvtpi2ps_2 = "rx/oq:0F2ArM",
cvtps2dq_2 = "rmo:660F5BrM",
cvtps2pd_2 = "rro:0F5ArM|rx/oq:",
cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:",
cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:",
cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM",
cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM",
cvtss2sd_2 = "rro:F30F5ArM|rx/od:",
cvtss2si_2 = "rr/do:F20F2CrM|rr/qo:|rxd:|rx/qd:",
cvttpd2dq_2 = "rmo:660FE6rM",
cvttps2dq_2 = "rmo:F30F5BrM",
cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:",
cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:",
fxsave_1 = "x.:0FAE0m",
fxrstor_1 = "x.:0FAE1m",
ldmxcsr_1 = "xd:0FAE2m",
lfence_0 = "0FAEE8",
maskmovdqu_2 = "rro:660FF7rM",
mfence_0 = "0FAEF0",
movapd_2 = "rmo:660F28rM|mro:660F29Rm",
movaps_2 = "rmo:0F28rM|mro:0F29Rm",
movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:",
movdqa_2 = "rmo:660F6FrM|mro:660F7FRm",
movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm",
movhlps_2 = "rro:0F12rM",
movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm",
movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm",
movlhps_2 = "rro:0F16rM",
movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm",
movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm",
movmskpd_2 = "rr/do:660F50rM",
movmskps_2 = "rr/do:0F50rM",
movntdq_2 = "xro:660FE7Rm",
movnti_2 = "xrqd:0FC3Rm",
movntpd_2 = "xro:660F2BRm",
movntps_2 = "xro:0F2BRm",
movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm",
movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm",
movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm",
movupd_2 = "rmo:660F10rM|mro:660F11Rm",
movups_2 = "rmo:0F10rM|mro:0F11Rm",
orpd_2 = "rmo:660F56rM",
orps_2 = "rmo:0F56rM",
packssdw_2 = "rmo:660F6BrM",
packsswb_2 = "rmo:660F63rM",
packuswb_2 = "rmo:660F67rM",
paddb_2 = "rmo:660FFCrM",
paddd_2 = "rmo:660FFErM",
paddq_2 = "rmo:660FD4rM",
paddsb_2 = "rmo:660FECrM",
paddsw_2 = "rmo:660FEDrM",
paddusb_2 = "rmo:660FDCrM",
paddusw_2 = "rmo:660FDDrM",
paddw_2 = "rmo:660FFDrM",
pand_2 = "rmo:660FDBrM",
pandn_2 = "rmo:660FDFrM",
pause_0 = "F390",
pavgb_2 = "rmo:660FE0rM",
pavgw_2 = "rmo:660FE3rM",
pcmpeqb_2 = "rmo:660F74rM",
pcmpeqd_2 = "rmo:660F76rM",
pcmpeqw_2 = "rmo:660F75rM",
pcmpgtb_2 = "rmo:660F64rM",
pcmpgtd_2 = "rmo:660F66rM",
pcmpgtw_2 = "rmo:660F65rM",
pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nrMU", -- Mem op: SSE4.1 only.
pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:",
pmaddwd_2 = "rmo:660FF5rM",
pmaxsw_2 = "rmo:660FEErM",
pmaxub_2 = "rmo:660FDErM",
pminsw_2 = "rmo:660FEArM",
pminub_2 = "rmo:660FDArM",
pmovmskb_2 = "rr/do:660FD7rM",
pmulhuw_2 = "rmo:660FE4rM",
pmulhw_2 = "rmo:660FE5rM",
pmullw_2 = "rmo:660FD5rM",
pmuludq_2 = "rmo:660FF4rM",
por_2 = "rmo:660FEBrM",
prefetchnta_1 = "xb:n0F180m",
prefetcht0_1 = "xb:n0F181m",
prefetcht1_1 = "xb:n0F182m",
prefetcht2_1 = "xb:n0F183m",
psadbw_2 = "rmo:660FF6rM",
pshufd_3 = "rmio:660F70rMU",
pshufhw_3 = "rmio:F30F70rMU",
pshuflw_3 = "rmio:F20F70rMU",
pslld_2 = "rmo:660FF2rM|rio:660F726mU",
pslldq_2 = "rio:660F737mU",
psllq_2 = "rmo:660FF3rM|rio:660F736mU",
psllw_2 = "rmo:660FF1rM|rio:660F716mU",
psrad_2 = "rmo:660FE2rM|rio:660F724mU",
psraw_2 = "rmo:660FE1rM|rio:660F714mU",
psrld_2 = "rmo:660FD2rM|rio:660F722mU",
psrldq_2 = "rio:660F733mU",
psrlq_2 = "rmo:660FD3rM|rio:660F732mU",
psrlw_2 = "rmo:660FD1rM|rio:660F712mU",
psubb_2 = "rmo:660FF8rM",
psubd_2 = "rmo:660FFArM",
psubq_2 = "rmo:660FFBrM",
psubsb_2 = "rmo:660FE8rM",
psubsw_2 = "rmo:660FE9rM",
psubusb_2 = "rmo:660FD8rM",
psubusw_2 = "rmo:660FD9rM",
psubw_2 = "rmo:660FF9rM",
punpckhbw_2 = "rmo:660F68rM",
punpckhdq_2 = "rmo:660F6ArM",
punpckhqdq_2 = "rmo:660F6DrM",
punpckhwd_2 = "rmo:660F69rM",
punpcklbw_2 = "rmo:660F60rM",
punpckldq_2 = "rmo:660F62rM",
punpcklqdq_2 = "rmo:660F6CrM",
punpcklwd_2 = "rmo:660F61rM",
pxor_2 = "rmo:660FEFrM",
rcpps_2 = "rmo:0F53rM",
rcpss_2 = "rro:F30F53rM|rx/od:",
rsqrtps_2 = "rmo:0F52rM",
rsqrtss_2 = "rmo:F30F52rM",
sfence_0 = "0FAEF8",
shufpd_3 = "rmio:660FC6rMU",
shufps_3 = "rmio:0FC6rMU",
stmxcsr_1 = "xd:0FAE3m",
ucomisd_2 = "rro:660F2ErM|rx/oq:",
ucomiss_2 = "rro:0F2ErM|rx/od:",
unpckhpd_2 = "rmo:660F15rM",
unpckhps_2 = "rmo:0F15rM",
unpcklpd_2 = "rmo:660F14rM",
unpcklps_2 = "rmo:0F14rM",
xorpd_2 = "rmo:660F57rM",
xorps_2 = "rmo:0F57rM",
-- SSE3 ops
fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m",
addsubpd_2 = "rmo:660FD0rM",
addsubps_2 = "rmo:F20FD0rM",
haddpd_2 = "rmo:660F7CrM",
haddps_2 = "rmo:F20F7CrM",
hsubpd_2 = "rmo:660F7DrM",
hsubps_2 = "rmo:F20F7DrM",
lddqu_2 = "rxo:F20FF0rM",
movddup_2 = "rmo:F20F12rM",
movshdup_2 = "rmo:F30F16rM",
movsldup_2 = "rmo:F30F12rM",
-- SSSE3 ops
pabsb_2 = "rmo:660F381CrM",
pabsd_2 = "rmo:660F381ErM",
pabsw_2 = "rmo:660F381DrM",
palignr_3 = "rmio:660F3A0FrMU",
phaddd_2 = "rmo:660F3802rM",
phaddsw_2 = "rmo:660F3803rM",
phaddw_2 = "rmo:660F3801rM",
phsubd_2 = "rmo:660F3806rM",
phsubsw_2 = "rmo:660F3807rM",
phsubw_2 = "rmo:660F3805rM",
pmaddubsw_2 = "rmo:660F3804rM",
pmulhrsw_2 = "rmo:660F380BrM",
pshufb_2 = "rmo:660F3800rM",
psignb_2 = "rmo:660F3808rM",
psignd_2 = "rmo:660F380ArM",
psignw_2 = "rmo:660F3809rM",
-- SSE4.1 ops
blendpd_3 = "rmio:660F3A0DrMU",
blendps_3 = "rmio:660F3A0CrMU",
blendvpd_3 = "rmRo:660F3815rM",
blendvps_3 = "rmRo:660F3814rM",
dppd_3 = "rmio:660F3A41rMU",
dpps_3 = "rmio:660F3A40rMU",
extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU",
insertps_3 = "rrio:660F3A41rMU|rxi/od:",
movntdqa_2 = "rmo:660F382ArM",
mpsadbw_3 = "rmio:660F3A42rMU",
packusdw_2 = "rmo:660F382BrM",
pblendvb_3 = "rmRo:660F3810rM",
pblendw_3 = "rmio:660F3A0ErMU",
pcmpeqq_2 = "rmo:660F3829rM",
pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:",
pextrd_3 = "mri/do:660F3A16RmU",
pextrq_3 = "mri/qo:660F3A16RmU",
-- pextrw is SSE2, mem operand is SSE4.1 only
phminposuw_2 = "rmo:660F3841rM",
pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:",
pinsrd_3 = "rmi/od:660F3A22rMU",
pinsrq_3 = "rmi/oq:660F3A22rXMU",
pmaxsb_2 = "rmo:660F383CrM",
pmaxsd_2 = "rmo:660F383DrM",
pmaxud_2 = "rmo:660F383FrM",
pmaxuw_2 = "rmo:660F383ErM",
pminsb_2 = "rmo:660F3838rM",
pminsd_2 = "rmo:660F3839rM",
pminud_2 = "rmo:660F383BrM",
pminuw_2 = "rmo:660F383ArM",
pmovsxbd_2 = "rro:660F3821rM|rx/od:",
pmovsxbq_2 = "rro:660F3822rM|rx/ow:",
pmovsxbw_2 = "rro:660F3820rM|rx/oq:",
pmovsxdq_2 = "rro:660F3825rM|rx/oq:",
pmovsxwd_2 = "rro:660F3823rM|rx/oq:",
pmovsxwq_2 = "rro:660F3824rM|rx/od:",
pmovzxbd_2 = "rro:660F3831rM|rx/od:",
pmovzxbq_2 = "rro:660F3832rM|rx/ow:",
pmovzxbw_2 = "rro:660F3830rM|rx/oq:",
pmovzxdq_2 = "rro:660F3835rM|rx/oq:",
pmovzxwd_2 = "rro:660F3833rM|rx/oq:",
pmovzxwq_2 = "rro:660F3834rM|rx/od:",
pmuldq_2 = "rmo:660F3828rM",
pmulld_2 = "rmo:660F3840rM",
ptest_2 = "rmo:660F3817rM",
roundpd_3 = "rmio:660F3A09rMU",
roundps_3 = "rmio:660F3A08rMU",
roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:",
roundss_3 = "rrio:660F3A0ArMU|rxi/od:",
-- SSE4.2 ops
crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:",
pcmpestri_3 = "rmio:660F3A61rMU",
pcmpestrm_3 = "rmio:660F3A60rMU",
pcmpgtq_2 = "rmo:660F3837rM",
pcmpistri_3 = "rmio:660F3A63rMU",
pcmpistrm_3 = "rmio:660F3A62rMU",
popcnt_2 = "rmqdw:F30FB8rM",
-- SSE4a
extrq_2 = "rro:660F79rM",
extrq_3 = "riio:660F780mUU",
insertq_2 = "rro:F20F79rM",
insertq_4 = "rriio:F20F78rMUU",
lzcnt_2 = "rmqdw:F30FBDrM",
movntsd_2 = "xr/qo:nF20F2BRm",
movntss_2 = "xr/do:F30F2BRm",
-- popcnt is also in SSE4.2
}
------------------------------------------------------------------------------
-- Arithmetic ops.
for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3,
["and"] = 4, sub = 5, xor = 6, cmp = 7 } do
local n8 = shl(n, 3)
map_op[name.."_2"] = format(
"mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi",
1+n8, 3+n8, n, n, 5+n8, n)
end
-- Shift ops.
for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3,
shl = 4, shr = 5, sar = 7, sal = 4 } do
map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n)
end
-- Conditional ops.
for cc,n in pairs(map_cc) do
map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X
map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n)
map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+
end
-- FP arithmetic ops.
for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3,
sub = 4, subr = 5, div = 6, divr = 7 } do
local nc = 0xc0 + shl(n, 3)
local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8))
local fn = "f"..name
map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n)
if n == 2 or n == 3 then
map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n)
else
map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n)
map_op[fn.."p_1"] = format("ff:DE%02Xr", nr)
map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr)
end
map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n)
end
-- FP conditional moves.
for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do
local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6)
map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+
map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+
end
-- SSE FP arithmetic ops.
for name,n in pairs{ sqrt = 1, add = 8, mul = 9,
sub = 12, min = 13, div = 14, max = 15 } do
map_op[name.."ps_2"] = format("rmo:0F5%XrM", n)
map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n)
map_op[name.."pd_2"] = format("rmo:660F5%XrM", n)
map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n)
end
------------------------------------------------------------------------------
-- Process pattern string.
local function dopattern(pat, args, sz, op, needrex)
local digit, addin
local opcode = 0
local szov = sz
local narg = 1
local rex = 0
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 5 positions.
if secpos+5 > maxsecpos then wflush() end
-- Process each character.
for c in gmatch(pat.."|", ".") do
if match(c, "%x") then -- Hex digit.
digit = byte(c) - 48
if digit > 48 then digit = digit - 39
elseif digit > 16 then digit = digit - 7 end
opcode = opcode*16 + digit
addin = nil
elseif c == "n" then -- Disable operand size mods for opcode.
szov = nil
elseif c == "X" then -- Force REX.W.
rex = 8
elseif c == "r" then -- Merge 1st operand regno. into opcode.
addin = args[1]; opcode = opcode + (addin.reg % 8)
if narg < 2 then narg = 2 end
elseif c == "R" then -- Merge 2nd operand regno. into opcode.
addin = args[2]; opcode = opcode + (addin.reg % 8)
narg = 3
elseif c == "m" or c == "M" then -- Encode ModRM/SIB.
local s
if addin then
s = addin.reg
opcode = opcode - band(s, 7) -- Undo regno opcode merge.
else
s = band(opcode, 15) -- Undo last digit.
opcode = shr(opcode, 4)
end
local nn = c == "m" and 1 or 2
local t = args[nn]
if narg <= nn then narg = nn + 1 end
if szov == "q" and rex == 0 then rex = rex + 8 end
if t.reg and t.reg > 7 then rex = rex + 1 end
if t.xreg and t.xreg > 7 then rex = rex + 2 end
if s > 7 then rex = rex + 4 end
if needrex then rex = rex + 16 end
wputop(szov, opcode, rex); opcode = nil
local imark = sub(pat, -1) -- Force a mark (ugly).
-- Put ModRM/SIB with regno/last digit as spare.
wputmrmsib(t, imark, s, addin and addin.vreg)
addin = nil
else
if opcode then -- Flush opcode.
if szov == "q" and rex == 0 then rex = rex + 8 end
if needrex then rex = rex + 16 end
if addin and addin.reg == -1 then
wputop(szov, opcode - 7, rex)
waction("VREG", addin.vreg); wputxb(0)
else
if addin and addin.reg > 7 then rex = rex + 1 end
wputop(szov, opcode, rex)
end
opcode = nil
end
if c == "|" then break end
if c == "o" then -- Offset (pure 32 bit displacement).
wputdarg(args[1].disp); if narg < 2 then narg = 2 end
elseif c == "O" then
wputdarg(args[2].disp); narg = 3
else
-- Anything else is an immediate operand.
local a = args[narg]
narg = narg + 1
local mode, imm = a.mode, a.imm
if mode == "iJ" and not match("iIJ", c) then
werror("bad operand size for label")
end
if c == "S" then
wputsbarg(imm)
elseif c == "U" then
wputbarg(imm)
elseif c == "W" then
wputwarg(imm)
elseif c == "i" or c == "I" then
if mode == "iJ" then
wputlabel("IMM_", imm, 1)
elseif mode == "iI" and c == "I" then
waction(sz == "w" and "IMM_WB" or "IMM_DB", imm)
else
wputszarg(sz, imm)
end
elseif c == "J" then
if mode == "iPJ" then
waction("REL_A", imm) -- !x64 (secpos)
else
wputlabel("REL_", imm, 2)
end
else
werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'")
end
end
end
end
end
------------------------------------------------------------------------------
-- Mapping of operand modes to short names. Suppress output with '#'.
local map_modename = {
r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm",
f = "stx", F = "st0", J = "lbl", ["1"] = "1",
I = "#", S = "#", O = "#",
}
-- Return a table/string showing all possible operand modes.
local function templatehelp(template, nparams)
if nparams == 0 then return "" end
local t = {}
for tm in gmatch(template, "[^%|]+") do
local s = map_modename[sub(tm, 1, 1)]
s = s..gsub(sub(tm, 2, nparams), ".", function(c)
return ", "..map_modename[c]
end)
if not match(s, "#") then t[#t+1] = s end
end
return t
end
-- Match operand modes against mode match part of template.
local function matchtm(tm, args)
for i=1,#args do
if not match(args[i].mode, sub(tm, i, i)) then return end
end
return true
end
-- Handle opcodes defined with template strings.
map_op[".template__"] = function(params, template, nparams)
if not params then return templatehelp(template, nparams) end
local args = {}
-- Zero-operand opcodes have no match part.
if #params == 0 then
dopattern(template, args, "d", params.op, nil)
return
end
-- Determine common operand size (coerce undefined size) or flag as mixed.
local sz, szmix, needrex
for i,p in ipairs(params) do
args[i] = parseoperand(p)
local nsz = args[i].opsize
if nsz then
if sz and sz ~= nsz then szmix = true else sz = nsz end
end
local nrex = args[i].needrex
if nrex ~= nil then
if needrex == nil then
needrex = nrex
elseif needrex ~= nrex then
werror("bad mix of byte-addressable registers")
end
end
end
-- Try all match:pattern pairs (separated by '|').
local gotmatch, lastpat
for tm in gmatch(template, "[^%|]+") do
-- Split off size match (starts after mode match) and pattern string.
local szm, pat = match(tm, "^(.-):(.*)$", #args+1)
if pat == "" then pat = lastpat else lastpat = pat end
if matchtm(tm, args) then
local prefix = sub(szm, 1, 1)
if prefix == "/" then -- Match both operand sizes.
if args[1].opsize == sub(szm, 2, 2) and
args[2].opsize == sub(szm, 3, 3) then
dopattern(pat, args, sz, params.op, needrex) -- Process pattern.
return
end
else -- Match common operand size.
local szp = sz
if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes.
if prefix == "1" then szp = args[1].opsize; szmix = nil
elseif prefix == "2" then szp = args[2].opsize; szmix = nil end
if not szmix and (prefix == "." or match(szm, szp or "#")) then
dopattern(pat, args, szp, params.op, needrex) -- Process pattern.
return
end
end
gotmatch = true
end
end
local msg = "bad operand mode"
if gotmatch then
if szmix then
msg = "mixed operand size"
else
msg = sz and "bad operand size" or "missing operand size"
end
end
werror(msg.." in `"..opmodestr(params.op, args).."'")
end
------------------------------------------------------------------------------
-- x64-specific opcode for 64 bit immediates and displacements.
if x64 then
function map_op.mov64_2(params)
if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end
if secpos+2 > maxsecpos then wflush() end
local opcode, op64, sz, rex, vreg
local op64 = match(params[1], "^%[%s*(.-)%s*%]$")
if op64 then
local a = parseoperand(params[2])
if a.mode ~= "rmR" then werror("bad operand mode") end
sz = a.opsize
rex = sz == "q" and 8 or 0
opcode = 0xa3
else
op64 = match(params[2], "^%[%s*(.-)%s*%]$")
local a = parseoperand(params[1])
if op64 then
if a.mode ~= "rmR" then werror("bad operand mode") end
sz = a.opsize
rex = sz == "q" and 8 or 0
opcode = 0xa1
else
if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then
werror("bad operand mode")
end
op64 = params[2]
if a.reg == -1 then
vreg = a.vreg
opcode = 0xb8
else
opcode = 0xb8 + band(a.reg, 7)
end
rex = a.reg > 7 and 9 or 8
end
end
wputop(sz, opcode, rex)
if vreg then waction("VREG", vreg); wputxb(0) end
waction("IMM_D", format("(unsigned int)(%s)", op64))
waction("IMM_D", format("(unsigned int)((%s)>>32)", op64))
end
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
local function op_data(params)
if not params then return "imm..." end
local sz = sub(params.op, 2, 2)
if sz == "a" then sz = addrsize end
for _,p in ipairs(params) do
local a = parseoperand(p)
if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then
werror("bad mode or size in `"..p.."'")
end
if a.mode == "iJ" then
wputlabel("IMM_", a.imm, 1)
else
wputszarg(sz, a.imm)
end
if secpos+2 > maxsecpos then wflush() end
end
end
map_op[".byte_*"] = op_data
map_op[".sbyte_*"] = op_data
map_op[".word_*"] = op_data
map_op[".dword_*"] = op_data
map_op[".aword_*"] = op_data
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_2"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end
if secpos+2 > maxsecpos then wflush() end
local a = parseoperand(params[1])
local mode, imm = a.mode, a.imm
if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then
-- Local label (1: ... 9:) or global label (->global:).
waction("LABEL_LG", nil, 1)
wputxb(imm)
elseif mode == "iJ" then
-- PC label (=>pcexpr:).
waction("LABEL_PC", imm)
else
werror("bad label definition")
end
-- SETLABEL must immediately follow LABEL_LG/LABEL_PC.
local addr = params[2]
if addr then
local a = parseoperand(addr)
if a.mode == "iPJ" then
waction("SETLABEL", a.imm)
else
werror("bad label assignment")
end
end
end
map_op[".label_1"] = map_op[".label_2"]
------------------------------------------------------------------------------
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]]
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", nil, 1)
wputxb(align-1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
-- Spacing pseudo-opcode.
map_op[".space_2"] = function(params)
if not params then return "num [, filler]" end
if secpos+1 > maxsecpos then wflush() end
waction("SPACE", params[1])
local fill = params[2]
if fill then
fill = tonumber(fill)
if not fill or fill < 0 or fill > 255 then werror("bad filler") end
end
wputxb(fill or 0)
end
map_op[".space_1"] = map_op[".space_2"]
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
if reg and not map_reg_valid_base[reg] then
werror("bad base register `"..(map_reg_rev[reg] or reg).."'")
end
-- Add #type to defines. A bit unclean to put it in map_archdef.
map_archdef["#"..name] = "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
map_type[name] = {
ctype = ctype,
ctypefmt = format("Dt%X(%%s)", num),
reg = reg,
}
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg and map_reg_rev[tp.reg] or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION")
wputxb(num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpregs(out)
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = map_coreop })
setmetatable(map_def, { __index = map_archdef })
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| bsd-2-clause |
Shrike78/Shilke2D | Shilke2D/Utils/Math/Bezier.lua | 1 | 1851 | --[[---
Bezier curve implementation.
Source ported from http://paulbourke.net/geometry/bezier/index2.html
--]]
---Three control point Bezier interpolation
--@param mu range [0,1], interpolation point between start and end of the curve
--@param p list of 3 control points for bezier definition
function bezier3(mu,p)
local mu2 = mu * mu
local mum1 = 1 - mu
local mum12 = mum1 * mum1
local p = p[1] * mum12 + 2 * p[2] * mum1 * mu + p[3] * mu2
return p
end
---Four control point Bezier interpolation
--@param mu range [0,1], interpolation point between start and end of the curve
--@param p list of 4 control points for bezier definition
function bezier4(mu,p)
local mu3 = mu * mu * mu
local mum1 = 1 - mu
local mum13 = mum1 * mum1 * mum1
local p = mum13 * p[1] + 3 * mu * mum1 * mum1 * p[2] +
3 * mu * mu * mum1 * p[3] + mu3 * p[4]
return p
end
---n-control point Bezier interpolation
--@param mu range [0,1], interpolation point between start and end of the curve
--@param p list of n-control points for bezier definition, with n>4
function bezier(mu,p)
local n = #p
local k,kn,nn,nkn
local blend,muk,munk
--this set b to 0, where 0 can be scalar or vec2 ecc.
local b = p[1] - p[1]
local muk = 1
local munk = math.pow(1-mu,n)
for k=0,n-1,1 do
nn = n
kn = k
nkn = n - k
blend = muk * munk
muk = muk * mu
munk = munk / (1-mu)
while nn >= 1 do
blend = blend * nn
nn = nn - 1
if kn > 1 then
blend = blend / kn
kn = kn -1
end
if nkn > 1 then
blend = blend / nkn
nkn = nkn - 1
end
end
b = b + p[k+1] * blend
end
return b
end
| mit |
Keithenneu/Dota2-FullOverwrite | bot_legion_commander.lua | 1 | 4385 | -------------------------------------------------------------------------------
--- AUTHOR: Keithen
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
-------------------------------------------------------------------------------
require( GetScriptDirectory().."/constants" )
local utils = require( GetScriptDirectory().."/utility" )
local dt = require( GetScriptDirectory().."/decision" )
local gHeroVar = require( GetScriptDirectory().."/global_hero_data" )
local ability = require( GetScriptDirectory().."/abilityUse/abilityUse_legion_commander" )
function setHeroVar(var, value)
local bot = GetBot()
gHeroVar.SetVar(bot:GetPlayerID(), var, value)
end
function getHeroVar(var)
local bot = GetBot()
return gHeroVar.GetVar(bot:GetPlayerID(), var)
end
local SKILL_Q = "legion_commander_overwhelming_odds"
local SKILL_W = "legion_commander_press_the_attack"
local SKILL_E = "legion_commander_moment_of_courage"
local SKILL_R = "legion_commander_duel"
local ABILITY1 = "special_bonus_strength_7"
local ABILITY2 = "special_bonus_exp_boost_20"
local ABILITY3 = "special_bonus_attack_damage_30"
local ABILITY4 = "special_bonus_movement_speed_20"
local ABILITY5 = "special_bonus_armor_7"
local ABILITY6 = "special_bonus_respawn_reduction_20"
local ABILITY7 = "special_bonus_unique_legion_commander" -- +40 dmg duel bonus
local ABILITY8 = "special_bonus_unique_legion_commander_2" -- -8s Press the Attack
local AbilityPriority = {
SKILL_E, SKILL_W, SKILL_E, SKILL_W, SKILL_Q,
SKILL_R, SKILL_E, SKILL_W, SKILL_W, ABILITY2,
SKILL_Q, SKILL_R, SKILL_E, SKILL_Q, ABILITY4,
SKILL_Q, SKILL_R, ABILITY6, ABILITY8
}
local botLC = dt:new()
function botLC:new(o)
o = o or dt:new(o)
setmetatable(o, self)
self.__index = self
return o
end
local lcBot = botLC:new{abilityPriority = AbilityPriority}
function lcBot:ConsiderAbilityUse()
return ability.AbilityUsageThink(GetBot())
end
function lcBot:GetNukeDamage(bot, target)
return ability.nukeDamage( bot, target )
end
function lcBot:QueueNuke(bot, target, actionQueue, engageDist)
return ability.queueNuke( bot, target, actionQueue, engageDist )
end
function Think()
local bot = GetBot()
lcBot:Think(bot)
-- if we are initialized, do the rest
if lcBot.Init then
if (bot:GetLevel() >= 12 or utils.HaveItem(bot, "item_blink")) and
getHeroVar("Role") ~= constants.ROLE_HARDCARRY then
setHeroVar("Role", constants.ROLE_HARDCARRY)
setHeroVar("CurLane", LANE_BOT) --FIXME: don't hardcode this
end
end
end
function lcBot:GetMaxClearableCampLevel(bot)
if DotaTime() < 30 then
return constants.CAMP_EASY
end
local abilityE = bot:GetAbilityByName(SKILL_E)
if abilityE:GetLevel() >= 4 then
return constants.CAMP_ANCIENT
elseif utils.HaveItem(bot, "item_iron_talon") and abilityE:GetLevel() >= 2 then
return constants.CAMP_HARD
end
return constants.CAMP_MEDIUM
end
function lcBot:IsReadyToGank(bot)
local ult = bot:GetAbilityByName(SKILL_R)
return ult:IsFullyCastable()
end
function lcBot:DoCleanCamp(bot, neutrals, difficulty)
if #neutrals == 0 then return end
if #neutrals > 1 then
table.sort(neutrals, function(n1, n2) return n1:GetHealth() < n2:GetHealth() end) -- sort by health
end
local it = utils.IsItemAvailable("item_iron_talon")
if it and difficulty ~= constants.CAMP_ANCIENT then -- we have an iron talon and not fighting ancients
local it_target = neutrals[#neutrals] -- neutral with most health
if utils.ValidTarget(it_target) and it_target:GetHealth() > 0.5 * it_target:GetMaxHealth() then -- is it worth it? TODO: add a absolute minimum / use it on big guys only
gHeroVar.HeroUseAbilityOnEntity(bot, it, it_target)
return
end
end
for i, neutral in ipairs(neutrals) do
-- kill the Ghost first as they slow down our DPS tremendously by being around
if utils.ValidTarget(neutral) and string.find(neutral:GetUnitName(), "ghost") ~= nil then
gHeroVar.HeroAttackUnit(bot, neutral, true)
return
end
end
if utils.ValidTarget(neutrals[1]) then
gHeroVar.HeroAttackUnit(bot, neutrals[1], true)
return
end
end
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Waters/npcs/Pechiru-Mashiru.lua | 36 | 1776 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Pechiru-Mashiru
-- Involved in Quests: Hat in Hand
-- Working 100%
-- @zone = 238
-- @pos = 162 -2 159
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
hatstatus = player:getQuestStatus(WINDURST,HAT_IN_HAND);
if ((hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) and testflag(tonumber(player:getVar("QuestHatInHand_var")),64) == false) then
player:startEvent(0x0036); -- Show Off Hat
else
player:startEvent(0x01a5); -- Standard Conversation
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 == 0x0036) then -- Show Off Hat
player:setVar("QuestHatInHand_var",player:getVar("QuestHatInHand_var")+64);
player:setVar("QuestHatInHand_count",player:getVar("QuestHatInHand_count")+1);
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Abyssea-Attohwa/npcs/qm22.lua | 17 | 1898 | -----------------------------------
-- Zone: Abyssea-Attohwa
-- NPC: ???
-- Spawns: Titlacauan
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(17658279) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(BLOTCHED_DOOMED_TONGUE) and player:hasKeyItem(CRACKED_SKELETON_CLAVICLE)
and player:hasKeyItem(WRITHING_GHOST_FINGER) -- I broke it into 3 lines at the 'and' because it was so long.
and player:hasKeyItem(RUSTED_HOUND_COLLAR)) then
player:startEvent(1022, BLOTCHED_DOOMED_TONGUE, CRACKED_SKELETON_CLAVICLE, WRITHING_GHOST_FINGER, RUSTED_HOUND_COLLAR); -- Ask if player wants to use KIs
else
player:startEvent(1023, BLOTCHED_DOOMED_TONGUE, CRACKED_SKELETON_CLAVICLE, WRITHING_GHOST_FINGER, RUSTED_HOUND_COLLAR); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1022 and option == 1) then
SpawnMob(17658279):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(BLOTCHED_DOOMED_TONGUE);
player:delKeyItem(CRACKED_SKELETON_CLAVICLE);
player:delKeyItem(WRITHING_GHOST_FINGER);
player:delKeyItem(RUSTED_HOUND_COLLAR);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Yuhtunga_Jungle/npcs/Cermet_Headstone.lua | 17 | 3918 | -----------------------------------
-- Area: Yuhtunga Jungle
-- NPC: Cermet Headstone
-- Involved in Mission: ZM5 Headstone Pilgrimage (Fire Fragment)
-- @pos 491 20 301 123
-----------------------------------
package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/missions");
require("scripts/zones/Yuhtunga_Jungle/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(790,1) and trade:getItemCount() == 1) then
if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE and player:hasKeyItem(FIRE_FRAGMENT) and player:hasCompleteQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS) == false) then
player:addQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS);
player:startEvent(0x00CA,790);
elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE) and player:hasCompleteQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS) == false) then
player:addQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS);
player:startEvent(0x00CA,790);
else
player:messageSpecial(NOTHING_HAPPENS);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
printf("zilart: %i",player:getCurrentMission(ZILART));
if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then
-- if requirements are met and 15 mins have passed since mobs were last defeated, spawn them
if (player:hasKeyItem(FIRE_FRAGMENT) == false and GetServerVariable("[ZM4]Fire_Headstone_Active") < os.time()) then
player:startEvent(0x00C8,FIRE_FRAGMENT);
-- if 15 min window is open and requirements are met, recieve key item
elseif (player:hasKeyItem(FIRE_FRAGMENT) == false and GetServerVariable("[ZM4]Fire_Headstone_Active") > os.time()) then
player:addKeyItem(FIRE_FRAGMENT);
-- Check and see if all fragments have been found (no need to check fire and dark frag)
if (player:hasKeyItem(ICE_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,FIRE_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,FIRE_FRAGMENT);
end
else
player:messageSpecial(ALREADY_OBTAINED_FRAG,FIRE_FRAGMENT);
end
elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then
player:messageSpecial(ZILART_MONUMENT);
else
player:messageSpecial(CANNOT_REMOVE_FRAG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x00C8 and option == 1) then
SpawnMob(17281031,300):updateClaim(player); -- Carthi
SpawnMob(17281030,300):updateClaim(player); -- Tipha
SetServerVariable("[ZM4]Fire_Headstone_Active",0);
elseif (csid == 0x00CA) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13143);
else
player:tradeComplete();
player:addItem(13143);
player:messageSpecial(ITEM_OBTAINED,13143);
player:completeQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS);
player:addTitle(FRIEND_OF_THE_OPOOPOS);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/head_of_grauberg_lettuce.lua | 36 | 1155 | -----------------------------------------
-- ID: 5688
-- Item: Head of Grauberg Lettuce
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility 1
-- Vitality -3
-----------------------------------------
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,300,5688);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, -3);
end;
| gpl-3.0 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/script/AudioEngine.lua | 24 | 2860 | --Encapsulate SimpleAudioEngine to AudioEngine,Play music and sound effects.
local M = {}
function M.stopAllEffects()
cc.SimpleAudioEngine:getInstance():stopAllEffects()
end
function M.getMusicVolume()
return cc.SimpleAudioEngine:getInstance():getMusicVolume()
end
function M.isMusicPlaying()
return cc.SimpleAudioEngine:getInstance():isMusicPlaying()
end
function M.getEffectsVolume()
return cc.SimpleAudioEngine:getInstance():getEffectsVolume()
end
function M.setMusicVolume(volume)
cc.SimpleAudioEngine:getInstance():setMusicVolume(volume)
end
function M.stopEffect(handle)
cc.SimpleAudioEngine:getInstance():stopEffect(handle)
end
function M.stopMusic(isReleaseData)
local releaseDataValue = false
if nil ~= isReleaseData then
releaseDataValue = isReleaseData
end
cc.SimpleAudioEngine:getInstance():stopMusic(releaseDataValue)
end
function M.playMusic(filename, isLoop)
local loopValue = false
if nil ~= isLoop then
loopValue = isLoop
end
cc.SimpleAudioEngine:getInstance():playMusic(filename, loopValue)
end
function M.pauseAllEffects()
cc.SimpleAudioEngine:getInstance():pauseAllEffects()
end
function M.preloadMusic(filename)
cc.SimpleAudioEngine:getInstance():preloadMusic(filename)
end
function M.resumeMusic()
cc.SimpleAudioEngine:getInstance():resumeMusic()
end
function M.playEffect(filename, isLoop)
local loopValue = false
if nil ~= isLoop then
loopValue = isLoop
end
return cc.SimpleAudioEngine:getInstance():playEffect(filename, loopValue)
end
function M.rewindMusic()
cc.SimpleAudioEngine:getInstance():rewindMusic()
end
function M.willPlayMusic()
return cc.SimpleAudioEngine:getInstance():willPlayMusic()
end
function M.unloadEffect(filename)
cc.SimpleAudioEngine:getInstance():unloadEffect(filename)
end
function M.preloadEffect(filename)
cc.SimpleAudioEngine:getInstance():preloadEffect(filename)
end
function M.setEffectsVolume(volume)
cc.SimpleAudioEngine:getInstance():setEffectsVolume(volume)
end
function M.pauseEffect(handle)
cc.SimpleAudioEngine:getInstance():pauseEffect(handle)
end
function M.resumeAllEffects(handle)
cc.SimpleAudioEngine:getInstance():resumeAllEffects()
end
function M.pauseMusic()
cc.SimpleAudioEngine:getInstance():pauseMusic()
end
function M.resumeEffect(handle)
cc.SimpleAudioEngine:getInstance():resumeEffect(handle)
end
function M.getInstance()
return cc.SimpleAudioEngine:getInstance()
end
function M.destroyInstance()
return cc.SimpleAudioEngine:destroyInstance()
end
local modename = "AudioEngine"
local proxy = {}
local mt = {
__index = M,
__newindex = function (t ,k ,v)
print("attemp to update a read-only table")
end
}
setmetatable(proxy,mt)
_G[modename] = proxy
package.loaded[modename] = proxy
| mit |
jshackley/darkstar | scripts/zones/Cloister_of_Gales/mobs/Ogmios.lua | 1 | 1323 | -----------------------------------
-- Area: Cloister of Gales
-- MOB: Ogmios
-- Involved in Quest: Carbuncle Debacle
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
-----------------------------------
-- OnMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- OnMobDeath Action
-----------------------------------
function onMobDeath(mob,killer,ally)
ally:setVar("BCNM_Killed",1);
record = 300;
partyMembers = 6;
pZone = ally:getZoneID();
ally:startEvent(0x7d01,0,record,0,(os.time() - ally:getVar("BCNM_Timer")),partyMembers,0,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
if (csid == 0x7d01) then
player:delStatusEffect(EFFECT_BATTLEFIELD);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
if (csid == 0x7d01) then
player:delKeyItem(DAZEBREAKER_CHARM);
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Silver_Sea_route_to_Al_Zahbi/Zone.lua | 17 | 1448 | -----------------------------------
--
-- Zone: Silver_Sea_route_to_Al_Zahbi
--
-----------------------------------
package.loaded["scripts/zones/Silver_Sea_route_to_Al_Zahbi/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Silver_Sea_route_to_Al_Zahbi/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
player:startEvent(0x0401);
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 == 0x0401) then
player:setPos(0,0,0,0,50);
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/items/goldsmiths_belt.lua | 30 | 1215 | -----------------------------------------
-- ID: 15446
-- Item: Goldsmith's Belt
-- Enchantment: Synthesis image support
-- 2Min, All Races
-----------------------------------------
-- Enchantment: Synthesis image support
-- Duration: 2Min
-- Goldsmithing Skill +3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_GOLDSMITHING_IMAGERY) == true) then
result = 238;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_GOLDSMITHING_IMAGERY,3,0,120);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_SKILL_GLD, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_SKILL_GLD, 1);
end; | gpl-3.0 |
spamn/awesome-config | themes/sky/theme.lua | 8 | 4941 | -------------------------------
-- "Sky" awesome theme --
-- By Andrei "Garoth" Thorp --
-------------------------------
-- If you want SVGs and extras, get them from garoth.com/awesome/sky-theme
local theme_assets = require("beautiful.theme_assets")
local xresources = require("beautiful.xresources")
local dpi = xresources.apply_dpi
local themes_path = require("gears.filesystem").get_themes_dir()
-- BASICS
local theme = {}
theme.font = "sans 8"
theme.bg_focus = "#e2eeea"
theme.bg_normal = "#729fcf"
theme.bg_urgent = "#fce94f"
theme.bg_minimize = "#0067ce"
theme.bg_systray = theme.bg_normal
theme.fg_normal = "#2e3436"
theme.fg_focus = "#2e3436"
theme.fg_urgent = "#2e3436"
theme.fg_minimize = "#2e3436"
theme.useless_gap = dpi(0)
theme.border_width = dpi(2)
theme.border_normal = "#dae3e0"
theme.border_focus = "#729fcf"
theme.border_marked = "#eeeeec"
-- IMAGES
theme.layout_fairh = themes_path .. "sky/layouts/fairh.png"
theme.layout_fairv = themes_path .. "sky/layouts/fairv.png"
theme.layout_floating = themes_path .. "sky/layouts/floating.png"
theme.layout_magnifier = themes_path .. "sky/layouts/magnifier.png"
theme.layout_max = themes_path .. "sky/layouts/max.png"
theme.layout_fullscreen = themes_path .. "sky/layouts/fullscreen.png"
theme.layout_tilebottom = themes_path .. "sky/layouts/tilebottom.png"
theme.layout_tileleft = themes_path .. "sky/layouts/tileleft.png"
theme.layout_tile = themes_path .. "sky/layouts/tile.png"
theme.layout_tiletop = themes_path .. "sky/layouts/tiletop.png"
theme.layout_spiral = themes_path .. "sky/layouts/spiral.png"
theme.layout_dwindle = themes_path .. "sky/layouts/dwindle.png"
theme.layout_cornernw = themes_path .. "sky/layouts/cornernw.png"
theme.layout_cornerne = themes_path .. "sky/layouts/cornerne.png"
theme.layout_cornersw = themes_path .. "sky/layouts/cornersw.png"
theme.layout_cornerse = themes_path .. "sky/layouts/cornerse.png"
theme.awesome_icon = themes_path .. "sky/awesome-icon.png"
-- from default for now...
theme.menu_submenu_icon = themes_path .. "default/submenu.png"
-- Generate taglist squares:
local taglist_square_size = dpi(4)
theme.taglist_squares_sel = theme_assets.taglist_squares_sel(
taglist_square_size, theme.fg_normal
)
theme.taglist_squares_unsel = theme_assets.taglist_squares_unsel(
taglist_square_size, theme.fg_normal
)
-- MISC
theme.wallpaper = themes_path .. "sky/sky-background.png"
theme.taglist_squares = "true"
theme.titlebar_close_button = "true"
theme.menu_height = dpi(15)
theme.menu_width = dpi(100)
-- Define the image to load
theme.titlebar_close_button_normal = themes_path .. "default/titlebar/close_normal.png"
theme.titlebar_close_button_focus = themes_path .. "default/titlebar/close_focus.png"
theme.titlebar_minimize_button_normal = themes_path .. "default/titlebar/minimize_normal.png"
theme.titlebar_minimize_button_focus = themes_path .. "default/titlebar/minimize_focus.png"
theme.titlebar_ontop_button_normal_inactive = themes_path .. "default/titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive = themes_path .. "default/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active = themes_path .. "default/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active = themes_path .. "default/titlebar/ontop_focus_active.png"
theme.titlebar_sticky_button_normal_inactive = themes_path .. "default/titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive = themes_path .. "default/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active = themes_path .. "default/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active = themes_path .. "default/titlebar/sticky_focus_active.png"
theme.titlebar_floating_button_normal_inactive = themes_path .. "default/titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive = themes_path .. "default/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active = themes_path .. "default/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active = themes_path .. "default/titlebar/floating_focus_active.png"
theme.titlebar_maximized_button_normal_inactive = themes_path .. "default/titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive = themes_path .. "default/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active = themes_path .. "default/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active = themes_path .. "default/titlebar/maximized_focus_active.png"
return theme
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Norg/npcs/Heizo.lua | 17 | 3116 | -----------------------------------
-- Area: Norg
-- NPC: Heizo
-- Starts and Ends Quest: Like Shining Leggings
-- @pos -1 -5 25 252
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
ShiningLeggings = player:getQuestStatus(OUTLANDS,LIKE_A_SHINING_LEGGINGS);
Legging = trade:getItemQty(14117);
if (Legging > 0 and Legging == trade:getItemCount()) then
TurnedInVar = player:getVar("shiningLeggings_nb");
if (ShiningLeggings == QUEST_ACCEPTED and TurnedInVar + Legging >= 10) then -- complete quest
player:startEvent(0x0081);
elseif (ShiningLeggings == QUEST_ACCEPTED and TurnedInVar <= 9) then -- turning in less than the amount needed to finish the quest
TotalLeggings = Legging + TurnedInVar
player:tradeComplete();
player:setVar("shiningLeggings_nb",TotalLeggings);
player:startEvent(0x0080,TotalLeggings); -- Update player on number of leggings turned in
end
else
if (ShiningLeggings == QUEST_ACCEPTED) then
player:startEvent(0x0080,TotalLeggings); -- Update player on number of leggings turned in, but doesn't accept anything other than leggings
else
player:startEvent(0x007e); -- Give standard conversation if items are traded but no quest is accepted
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
ShiningLeggings = player:getQuestStatus(OUTLANDS,LIKE_A_SHINING_LEGGINGS);
if (ShiningLeggings == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 3) then
player:startEvent(0x007f); -- Start Like Shining Leggings
elseif (ShiningLeggings == QUEST_ACCEPTED) then
player:startEvent(0x0080,player:getVar("shiningSubligar_nb")); -- Update player on number of Leggings turned in
else
player:startEvent(0x007e); -- Standard Conversation
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 == 0x007f) then
player:addQuest(OUTLANDS,LIKE_A_SHINING_LEGGINGS);
elseif (csid == 0x0081) then
player:tradeComplete();
player:addItem(4958); -- Scroll of Dokumori: Ichi
player:messageSpecial(ITEM_OBTAINED, 4958); -- Scroll of Dokumori: Ichi
player:addFame(OUTLANDS,NORG_FAME*100);
player:addTitle(LOOKS_GOOD_IN_LEGGINGS);
player:setVar("shiningLeggings_nb",0);
player:completeQuest(OUTLANDS,LIKE_A_SHINING_LEGGINGS);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/mobskills/Rock_Smash.lua | 13 | 1215 | ---------------------------------------------
-- Rock Smash
--
-- Description: Damages a single target. Additional effect: Petrification
-- Type: Physical
-- Utsusemi/Blink absorb: 1 shadow
-- Range: Melee
-- Notes:
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 91) then
local mobSkin = mob:getModelId();
if (mobSkin == 1680) then
return 0;
else
return 1;
end
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 2;
local dmgmod = 3;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded);
local typeEffect = EFFECT_PETRIFICATION;
local power = math.random(25, 40) + mob:getMainLvl()/3;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, power);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
golden-tech-native/gd_facerecognize | facelib/openface/models/openface/vgg-face.small1.def.lua | 14 | 2626 | -- Model: vgg-face.small1.def.lua
-- Description: Modified VGG Face network. Smaller and with batch normalization.
-- !! In progress, may change.
-- Input size: 3x96x96
-- Number of Parameters from net:getParameters() with embSize=128: TODO
-- Components: Mostly `nn`
-- Devices: CPU and CUDA
--
-- Brandon Amos <http://bamos.github.io>
-- 2016-06-08
--
-- Copyright 2016 Carnegie Mellon University
--
-- 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.
imgDim = 96
local conv = nn.SpatialConvolutionMM
local sbn = nn.SpatialBatchNormalization
local relu = nn.ReLU
local mp = nn.SpatialMaxPooling
function createModel()
local net = nn.Sequential()
net:add(conv(3, 64, 3,3, 1,1, 1,1))
net:add(sbn(64))
net:add(relu(true))
net:add(conv(64, 64, 3,3, 1,1, 1,1))
net:add(sbn(64))
net:add(relu(true))
net:add(mp(2,2, 2,2))
net:add(conv(64, 128, 3,3, 1,1, 1,1))
net:add(sbn(128))
net:add(relu(true))
net:add(conv(128, 128, 3,3, 1,1, 1,1))
net:add(sbn(128))
net:add(relu(true))
net:add(mp(2,2, 2,2))
net:add(conv(128, 256, 3,3, 1,1, 1,1))
net:add(sbn(256))
net:add(relu(true))
net:add(conv(256, 256, 3,3, 1,1, 1,1))
net:add(sbn(256))
net:add(relu(true))
net:add(conv(256, 256, 3,3, 1,1, 1,1))
net:add(sbn(256))
net:add(relu(true))
net:add(mp(2,2, 2,2))
net:add(conv(256, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(mp(2,2, 2,2))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(mp(2,2, 2,2))
-- Validate shape with:
net:add(nn.Reshape(4608))
net:add(nn.View(4608))
net:add(nn.Linear(4608, 1024))
net:add(relu(true))
net:add(nn.Linear(1024, opt.embSize))
net:add(nn.Normalize(2))
return net
end
| mit |
DougFirErickson/lcm | examples/lua/listener.lua | 9 | 1042 | local lcm = require('lcm')
-- this might be necessary depending on platform and LUA_PATH
package.path = './?/init.lua;' .. package.path
local exlcm = require('exlcm')
function array_to_str(array)
str = '{'
for i = 1, #array - 1 do
str = str .. array[i] .. ', '
end
return str .. array[#array] .. '}'
end
function my_handler(channel, data)
local msg = exlcm.example_t.decode(data)
print(string.format("Received message on channel \"%s\"", channel))
print(string.format(" timestamp = %d", msg.timestamp))
print(string.format(" position = %s", array_to_str(msg.position)))
print(string.format(" orientation = %s", array_to_str(msg.orientation)))
print(string.format(" ranges: %s", array_to_str(msg.ranges)))
print(string.format(" name = '%s'", msg.name))
print(string.format(" enabled = %s", tostring(msg.enabled)))
print("")
end
lc = lcm.lcm.new()
sub = lc:subscribe("EXAMPLE", my_handler)
while true do
lc:handle()
end
-- all subscriptions are unsubed at garbage collection
| lgpl-2.1 |
LiberatorUSA/GUCEF | dependencies/tolua/src/bin/lua/class.lua | 14 | 2836 | -- tolua: class class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: class.lua,v 1.3 2009/11/24 16:45:13 fabraham Exp $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Class class
-- Represents a class definition.
-- Stores the following fields:
-- name = class name
-- base = class base, if any (only single inheritance is supported)
-- {i} = list of members
classClass = {
classtype = 'class',
name = '',
base = '',
type = '',
btype = '',
ctype = '',
}
classClass.__index = classClass
setmetatable(classClass,classContainer)
-- register class
function classClass:register ()
push(self)
if _collect[self.type] then
output('#ifdef __cplusplus\n')
output(' tolua_cclass(tolua_S,"'..self.lname..'","'..self.type..'","'..self.btype..'",'.._collect[self.type]..');')
output('#else\n')
output(' tolua_cclass(tolua_S,"'..self.lname..'","'..self.type..'","'..self.btype..'",NULL);')
output('#endif\n')
else
output(' tolua_cclass(tolua_S,"'..self.lname..'","'..self.type..'","'..self.btype..'",NULL);')
end
output(' tolua_beginmodule(tolua_S,"'..self.lname..'");')
local i=1
while self[i] do
self[i]:register()
i = i+1
end
output(' tolua_endmodule(tolua_S);')
pop()
end
-- return collection requirement
function classClass:requirecollection (t)
push(self)
local r = false
local i=1
while self[i] do
r = self[i]:requirecollection(t) or r
i = i+1
end
pop()
-- only class that exports destructor can be appropriately collected
if self._delete then
t[self.type] = "tolua_collect_" .. gsub(self.type,"::","_")
r = true
end
return r
end
-- output tags
function classClass:decltype ()
push(self)
self.type = regtype(self.name)
self.btype = typevar(self.base)
self.ctype = 'const '..self.type
local i=1
while self[i] do
self[i]:decltype()
i = i+1
end
pop()
end
-- Print method
function classClass:print (ident,close)
print(ident.."Class{")
print(ident.." name = '"..self.name.."',")
print(ident.." base = '"..self.base.."';")
print(ident.." lname = '"..self.lname.."',")
print(ident.." type = '"..self.type.."',")
print(ident.." btype = '"..self.btype.."',")
print(ident.." ctype = '"..self.ctype.."',")
local i=1
while self[i] do
self[i]:print(ident.." ",",")
i = i+1
end
print(ident.."}"..close)
end
-- Internal constructor
function _Class (t)
setmetatable(t,classClass)
t:buildnames()
append(t)
return t
end
-- Constructor
-- Expects the name, the base and the body of the class.
function Class (n,p,b)
local c = _Class(_Container{name=n, base=p})
push(c)
c:parse(strsub(b,2,strlen(b)-1)) -- eliminate braces
pop()
end
| apache-2.0 |
bsmr-games/OpenRA | mods/cnc/maps/nod02b/nod02b.lua | 7 | 6482 | NodUnits = { "bggy", "e1", "e1", "e1", "e1", "e1", "bggy", "e1", "e1", "e1", "bggy" }
NodBaseBuildings = { "hand", "fact", "nuke" }
Grd2ActorTriggerActivator = { Refinery, Yard }
Atk4ActorTriggerActivator = { Guard1 }
Atk3ActorTriggerActivator = { Guard4 }
Atk6ActorTriggerActivator = { Guard2, Guard3 }
HuntActorTriggerActivator = { Refinery, Yard, Barracks, Plant, Silo1, Silo2 }
Atk8TriggerFunctionTime = DateTime.Minutes(1) + DateTime.Seconds(25)
Atk7TriggerFunctionTime = DateTime.Minutes(1) + DateTime.Seconds(20)
Gdi1Waypoints = { waypoint0, waypoint1, waypoint2, waypoint3 }
Gdi3Waypoints = { waypoint0, waypoint1, waypoint4, waypoint5, waypoint6, waypoint7, waypoint9 }
UnitToRebuild = 'e1'
GDIStartUnits = 0
Grd2TriggerFunction = function()
if not Grd2TriggerSwitch then
Grd2TriggerSwitch = true
MyActors = getActors(GDI, { ['e1'] = 5 })
Utils.Do(MyActors, function(actor)
Gdi5Movement(actor)
end)
end
end
Atk8TriggerFunction = function()
MyActors = getActors(GDI, { ['e1'] = 2 })
Utils.Do(MyActors, function(actor)
Gdi1Movement(actor)
end)
end
Atk7TriggerFunction = function()
MyActors = getActors(GDI, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Gdi3Movement(actor)
end)
end
Atk4TriggerFunction = function()
MyActors = getActors(GDI, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Gdi3Movement(actor)
end)
end
Atk3TriggerFunction = function()
MyActors = getActors(GDI, { ['e1'] = 2 })
Utils.Do(MyActors, function(actor)
Gdi1Movement(actor)
end)
end
Atk6TriggerFunction = function()
MyActors = getActors(GDI, { ['e1'] = 2 })
Utils.Do(MyActors, function(actor)
Gdi1Movement(actor)
end)
end
Atk5TriggerFunction = function()
if not Atk5TriggerSwitch then
Atk5TriggerSwitch = true
MyActors = getActors(GDI, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Gdi3Movement(actor)
end)
end
end
HuntTriggerFunction = function()
local list = GDI.GetGroundAttackers()
Utils.Do(list, function(unit)
IdleHunt(unit)
end)
end
Gdi5Movement = function(unit)
IdleHunt(unit)
end
Gdi1Movement = function(unit)
Utils.Do(Gdi1Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
Gdi3Movement = function(unit)
Utils.Do(Gdi3Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
WorldLoaded = function()
GDI = Player.GetPlayer("GDI")
Nod = Player.GetPlayer("Nod")
Trigger.OnObjectiveAdded(Nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(Nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(Nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(Nod, function()
Media.PlaySpeechNotification(Nod, "Win")
end)
Trigger.OnPlayerLost(Nod, function()
Media.PlaySpeechNotification(Nod, "Lose")
end)
GDIObjective = GDI.AddPrimaryObjective("Kill all enemies.")
NodObjective1 = Nod.AddPrimaryObjective("Build a base.")
NodObjective2 = Nod.AddPrimaryObjective("Destroy all GDI units.")
OnAnyDamaged(Grd2ActorTriggerActivator, Grd2TriggerFunction)
Trigger.AfterDelay(Atk8TriggerFunctionTime, Atk8TriggerFunction)
Trigger.AfterDelay(Atk7TriggerFunctionTime, Atk7TriggerFunction)
Trigger.OnAllRemovedFromWorld(Atk4ActorTriggerActivator, Atk4TriggerFunction)
Trigger.OnAllRemovedFromWorld(Atk3ActorTriggerActivator, Atk3TriggerFunction)
Trigger.OnDamaged(Harvester, Atk5TriggerFunction)
Trigger.OnAllRemovedFromWorld(HuntActorTriggerActivator, HuntTriggerFunction)
Trigger.AfterDelay(0, getStartUnits)
Harvester.FindResources()
InsertNodUnits()
end
Tick = function()
if Nod.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
GDI.MarkCompletedObjective(GDIObjective)
end
end
if GDI.HasNoRequiredUnits() then
Nod.MarkCompletedObjective(NodObjective2)
end
if DateTime.GameTime % DateTime.Seconds(1) == 0 and not Nod.IsObjectiveCompleted(NodObjective1) and CheckForBase(Nod, NodBaseBuildings) then
Nod.MarkCompletedObjective(NodObjective1)
end
if DateTime.GameTime % DateTime.Seconds(3) == 0 and Barracks.IsInWorld and Barracks.Owner == gdi then
checkProduction(GDI)
end
end
CheckForBase = function(player, buildings)
local checked = { }
local baseBuildings = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
if actor.Owner ~= Nod or Utils.Any(checked, function(bldng) return bldng.Type == actor.Type end) then
return false
end
local found = false
for i = 1, #buildings, 1 do
if actor.Type == buildings[i] then
found = true
checked[#checked + 1] = actor
end
end
return found
end)
return #baseBuildings >= 3
end
OnAnyDamaged = function(actors, func)
Utils.Do(actors, function(actor)
Trigger.OnDamaged(actor, func)
end)
end
getActors = function(owner, units)
local maxUnits = 0
local actors = { }
for type, count in pairs(units) do
local globalActors = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Owner == owner and actor.Type == type and not actor.IsDead
end)
if #globalActors < count then
maxUnits = #globalActors
else
maxUnits = count
end
for i = 1, maxUnits, 1 do
actors[#actors + 1] = globalActors[i]
end
end
return actors
end
checkProduction = function(player)
local Units = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Owner == player and actor.Type == UnitToRebuild
end)
if #Units < GDIStartUnits then
local unitsToProduce = GDIStartUnits - #Units
if Barracks.IsInWorld and unitsToProduce > 0 then
local UnitsType = { }
for i = 1, unitsToProduce, 1 do
UnitsType[i] = UnitToRebuild
end
Barracks.Build(UnitsType)
end
end
end
getStartUnits = function()
local Units = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Owner == GDI
end)
Utils.Do(Units, function(unit)
if unit.Type == UnitToRebuild then
GDIStartUnits = GDIStartUnits + 1
end
end)
end
InsertNodUnits = function()
Media.PlaySpeechNotification(Nod, "Reinforce")
Reinforcements.Reinforce(Nod, NodUnits, { UnitsEntry.Location, UnitsRally.Location }, 15)
Reinforcements.Reinforce(Nod, { "mcv" }, { McvEntry.Location, McvRally.Location })
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
| gpl-3.0 |
iofun/treehouse | luerl/529122331581c82c34d8284ac07c1636.lua | 1 | 2195 | -- Hive-tech air-to-air unit that requires a Greater Spire
-- to morph from a Mutalisk, through a Cocoon.
-- Our unit function table
local this_unit = {}
-- Where we are and fast we move
local x, y, dx, dy
-- Our name
local name = "Zerg_Devourer"
-- Our color
local color = "red"
-- Our BWAPI unit type
local type = 62
-- Our label
local label = "zerg_unit"
-- Our category
local category = "large_air"
-- Size of a clock tick msec
local tick
-- It's me, the unit structure
local me = unit.self()
-- The standard local variables
local armor = 2
local hitpoints,shield = 250,0
local ground_damage,air_damage = 0,25
local ground_cooldown,air_cooldown = 0,4.2
local ground_range,air_range = 0,6
local sight = 10
local speed = 3.720
local supply = 2
local cooldown = 50
local mineral = 250
local gas = 150
local holdkey = "d"
-- 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 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/WavesTiles3D.lua | 6 | 1251 |
--------------------------------
-- @module WavesTiles3D
-- @extend TiledGrid3DAction
--------------------------------
-- @function [parent=#WavesTiles3D] getAmplitudeRate
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- @function [parent=#WavesTiles3D] setAmplitude
-- @param self
-- @param #float float
--------------------------------
-- @function [parent=#WavesTiles3D] setAmplitudeRate
-- @param self
-- @param #float float
--------------------------------
-- @function [parent=#WavesTiles3D] getAmplitude
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- @function [parent=#WavesTiles3D] create
-- @param self
-- @param #float float
-- @param #size_table size
-- @param #unsigned int int
-- @param #float float
-- @return WavesTiles3D#WavesTiles3D ret (return value: cc.WavesTiles3D)
--------------------------------
-- @function [parent=#WavesTiles3D] clone
-- @param self
-- @return WavesTiles3D#WavesTiles3D ret (return value: cc.WavesTiles3D)
--------------------------------
-- @function [parent=#WavesTiles3D] update
-- @param self
-- @param #float float
return nil
| mit |
jshackley/darkstar | scripts/zones/Windurst_Woods/npcs/Nalta.lua | 38 | 1033 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Nalta
-- Type: Conquest Troupe
-- @zone: 241
-- @pos 19.140 1 -51.297
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0036);
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/Qufim_Island/npcs/HomePoint#1.lua | 2 | 1194 | -----------------------------------
-- Area: Qufim Island
-- NPC: HomePoint#1
-- @pos -212 -21 93 126
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Qufim_Island/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 115);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
PTPM/MTASA-legacy | ptpm_accounts/data.lua | 2 | 1644 | function setUserdata( username, column, data )
if column and column == "username" then return false end
local result = executeSQLQuery( "SELECT username FROM users WHERE username = '" .. escapeStr( username ) .. "'" )
if result then
if #result <= 0 then
outputDebugString( "setUserdata: No such username in database 'users': " .. username )
return false
end
end
local sData = tostring( data )
if sData == "true" then data = "1"
elseif sData == "false" then data = "0"
else data = sData
end
local result = executeSQLQuery( "UPDATE users SET " .. escapeStr( column ) .. " = '" .. escapeStr( data ) .. "' WHERE username = '" .. escapeStr( username ) .. "'" )
if result then
return true
else
return false
end
end
function getUserdata( username, column )
local result = executeSQLQuery( "SELECT username FROM users WHERE username = '" .. escapeStr( username ) .. "'" )
if result then
if #result <= 0 then
outputDebugString( "getUserdata: No such username in database 'users': " .. username )
return false
end
end
if type( column ) == "boolean" and column then -- return all
local result = executeSQLQuery( "SELECT * FROM users WHERE username = '" .. escapeStr( username ) .. "'" )
if result then
-- for i, v in pairs( result[1] ) do
-- outputChatBox( "Userdata '" .. tostring( i ) .. "' = '" .. tostring( v ) .. "'" )
-- end
return result[1]
end
return false
else
local result = executeSQLQuery( "SELECT " .. escapeStr( column ) .. " FROM users WHERE username = '" .. escapeStr( username ) .. "'" )
if result then
return result[1][column]
end
return false
end
end | mit |
jshackley/darkstar | scripts/globals/weaponskills/cross_reaper.lua | 29 | 1729 | -----------------------------------
-- Cross Reaper
-- Scythe weapon skill
-- Skill level: 225
-- Delivers a two-hit attack. Damage varies with TP.
-- Modifiers: STR:30% ; MND:30%
-- 100%TP 200%TP 300%TP
-- 2.0 2.25 2.5
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
------------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 2;
--ftp damage mods (for Damage Varies with TP; lines are calculated in the function
params.ftp100 = 2.0; params.ftp200 = 2.25; params.ftp300 = 2.5;
--wscs are in % so 0.2=20%
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.3; params.chr_wsc = 0.0;
--critical mods, again in % (ONLY USE FOR CRITICAL HIT VARIES WITH TP)
params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0;
params.canCrit = false;
--params.accuracy mods (ONLY USE FOR ACCURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0; params.acc200=0; params.acc300=0;
--attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 2.0; params.ftp200 = 4.0; params.ftp300 = 7.0;
params.str_wsc = 0.6; params.mnd_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 |
jshackley/darkstar | scripts/globals/spells/dragonfoe_mambo.lua | 18 | 1581 | -----------------------------------------
-- Spell: Dragonfoe Mambo
-- Grants evasion bonus to all members.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
-- Since nobody knows the evasion values for mambo, I'll just make shit up! (aka - same as madrigal)
local power = 9;
if (sLvl+iLvl > 130) then
power = power + math.floor((sLvl+iLvl-130) / 18);
end
if (power >= 30) then
power = 30;
end
local iBoost = caster:getMod(MOD_MAMBO_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
if (iBoost > 0) then
power = power + 1 + (iBoost-1)*4;
end
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_MAMBO,power,0,duration,caster:getID(), 0, 2)) then
spell:setMsg(75);
end
return EFFECT_MAMBO;
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/AlTaieu/npcs/Swirling_Vortex.lua | 17 | 1468 | -----------------------------------
-- Area: Al'Taieu
-- NPC: Swirling_Vortex
-- Type: Standard NPC
-- @zone 33
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/AlTaieu/TextIDs");
require("scripts/globals/limbus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getID() == 16912908) then
player:startEvent(0x009F);
else
player:startEvent(0x00A0);
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 == 0x00A0 and option == 1 ) then
ResetPlayerLimbusVariable(player);
LimbusEntrance(player,APPOLLYON_NW_SW);
elseif (csid == 0x009F and option == 1 ) then
ResetPlayerLimbusVariable(player);
LimbusEntrance(player,APPOLLYON_SE_NE);
end
end;
| gpl-3.0 |
SpRoXx/GTW-RPG | [misc]/scoreboard/dxscoreboard_clientsettings.lua | 2 | 55205 | settings = {
["useanimation"] = nil,
["toggleable"] = nil,
["showserverinfo"] = nil,
["showgamemodeinfo"] = nil,
["showteams"] = nil,
["usecolors"] = nil,
["drawspeed"] = nil,
["scale"] = nil,
["columnfont"] = nil,
["contentfont"] = nil,
["teamfont"] = nil,
["serverinfofont"] = nil,
["bg_color"] = {},
["selection_color"] = {},
["highlight_color"] = {},
["header_color"] = {},
["team_color"] = {},
["border_color"] = {},
["serverinfo_color"] = {},
["content_color"] = {}
}
defaultSettings = {
["useanimation"] = true,
["toggleable"] = false,
["showserverinfo"] = false,
["showgamemodeinfo"] = false,
["showteams"] = true,
["usecolors"] = true,
["drawspeed"] = 1.5,
["scale"] = 1.0,
["columnfont"] = "default-bold",
["contentfont"] = "default-bold",
["teamfont"] = "clear",
["serverinfofont"] = "default",
["bg_color"] = {
["r"] = 68,
["g"] = 68,
["b"] = 68,
["a"] = 170
},
["selection_color"] = {
["r"] = 82,
["g"] = 103,
["b"] = 188,
["a"] = 170
},
["highlight_color"] = {
["r"] = 255,
["g"] = 255,
["b"] = 255,
["a"] = 50
},
["header_color"] = {
["r"] = 100,
["g"] = 100,
["b"] = 100,
["a"] = 255
},
["team_color"] = {
["r"] = 100,
["g"] = 100,
["b"] = 100,
["a"] = 100
},
["border_color"] = {
["r"] = 100,
["g"] = 100,
["b"] = 100,
["a"] = 50
},
["serverinfo_color"] = {
["r"] = 150,
["g"] = 150,
["b"] = 150,
["a"] = 255
},
["content_color"] = {
["r"] = 255,
["g"] = 255,
["b"] = 255,
["a"] = 255
}
}
tempColors = {
["bg_color"] = {
["r"] = nil,
["g"] = nil,
["b"] = nil,
["a"] = nil
},
["selection_color"] = {
["r"] = nil,
["g"] = nil,
["b"] = nil,
["a"] = nil
},
["highlight_color"] = {
["r"] = nil,
["g"] = nil,
["b"] = nil,
["a"] = nil
},
["header_color"] = {
["r"] = nil,
["g"] = nil,
["b"] = nil,
["a"] = nil
},
["team_color"] = {
["r"] = nil,
["g"] = nil,
["b"] = nil,
["a"] = nil
},
["border_color"] = {
["r"] = nil,
["g"] = nil,
["b"] = nil,
["a"] = nil
},
["serverinfo_color"] = {
["r"] = nil,
["g"] = nil,
["b"] = nil,
["a"] = nil
},
["content_color"] = {
["r"] = nil,
["g"] = nil,
["b"] = nil,
["a"] = nil
}
}
MAX_DRAWSPEED = 4.0
MIN_DRAWSPEED = 0.5
MAX_SCALE = 2.5
MIN_SCALE = 0.5
fontIndexes = {
["column"] = 1,
["content"] = 1,
["team"] = 1,
["serverinfo"] = 1
}
fontNames = { "default", "default-bold", "clear", "arial", "sans","pricedown", "bankgothic", "diploma", "beckett" }
function readScoreboardSettings()
local settingsFile = xmlLoadFile( "settings.xml" )
if not settingsFile then
settingsFile = xmlCreateFile( "settings.xml", "settings" )
if not settingsFile then return false end
local useanimationTag = xmlCreateChild( settingsFile, "useanimation" )
xmlNodeSetValue( useanimationTag, tostring( defaultSettings.useanimation ) )
local toggleableTag = xmlCreateChild( settingsFile, "toggleable" )
xmlNodeSetValue( toggleableTag, tostring( defaultSettings.toggleable ) )
local showserverinfoTag = xmlCreateChild( settingsFile, "showserverinfo" )
xmlNodeSetValue( showserverinfoTag, tostring( defaultSettings.showserverinfo ) )
local showgamemodeinfoTag = xmlCreateChild( settingsFile, "showgamemodeinfo" )
xmlNodeSetValue( showgamemodeinfoTag, tostring( defaultSettings.showgamemodeinfo ) )
local showteamsTag = xmlCreateChild( settingsFile, "showteams" )
xmlNodeSetValue( showteamsTag, tostring( defaultSettings.showteams ) )
local usecolorsTag = xmlCreateChild( settingsFile, "usecolors" )
xmlNodeSetValue( usecolorsTag, tostring( defaultSettings.usecolors ) )
local drawspeedTag = xmlCreateChild( settingsFile, "drawspeed" )
xmlNodeSetValue( drawspeedTag, tostring( defaultSettings.drawspeed ) )
local scaleTag = xmlCreateChild( settingsFile, "scale" )
xmlNodeSetValue( scaleTag, tostring( defaultSettings.scale ) )
local columnfontTag = xmlCreateChild( settingsFile, "columnfont" )
xmlNodeSetValue( columnfontTag, tostring( defaultSettings.columnfont ) )
local contentfontTag = xmlCreateChild( settingsFile, "contentfont" )
xmlNodeSetValue( contentfontTag, tostring( defaultSettings.contentfont ) )
local teamfontTag = xmlCreateChild( settingsFile, "teamfont" )
xmlNodeSetValue( teamfontTag, tostring( defaultSettings.teamfont ) )
local serverinfofontTag = xmlCreateChild( settingsFile, "serverinfofont" )
xmlNodeSetValue( serverinfofontTag, tostring( defaultSettings.serverinfofont ) )
local bg_colorTag = xmlCreateChild( settingsFile, "bg_color" )
xmlNodeSetAttribute( bg_colorTag, "r", tostring( defaultSettings.bg_color.r ) )
xmlNodeSetAttribute( bg_colorTag, "g", tostring( defaultSettings.bg_color.g ) )
xmlNodeSetAttribute( bg_colorTag, "b", tostring( defaultSettings.bg_color.b ) )
xmlNodeSetAttribute( bg_colorTag, "a", tostring( defaultSettings.bg_color.a ) )
local selection_colorTag = xmlCreateChild( settingsFile, "selection_color" )
xmlNodeSetAttribute( selection_colorTag, "r", tostring( defaultSettings.selection_color.r ) )
xmlNodeSetAttribute( selection_colorTag, "g", tostring( defaultSettings.selection_color.g ) )
xmlNodeSetAttribute( selection_colorTag, "b", tostring( defaultSettings.selection_color.b ) )
xmlNodeSetAttribute( selection_colorTag, "a", tostring( defaultSettings.selection_color.a ) )
local highlight_colorTag = xmlCreateChild( settingsFile, "highlight_color" )
xmlNodeSetAttribute( highlight_colorTag, "r", tostring( defaultSettings.highlight_color.r ) )
xmlNodeSetAttribute( highlight_colorTag, "g", tostring( defaultSettings.highlight_color.g ) )
xmlNodeSetAttribute( highlight_colorTag, "b", tostring( defaultSettings.highlight_color.b ) )
xmlNodeSetAttribute( highlight_colorTag, "a", tostring( defaultSettings.highlight_color.a ) )
local header_colorTag = xmlCreateChild( settingsFile, "header_color" )
xmlNodeSetAttribute( header_colorTag, "r", tostring( defaultSettings.header_color.r ) )
xmlNodeSetAttribute( header_colorTag, "g", tostring( defaultSettings.header_color.g ) )
xmlNodeSetAttribute( header_colorTag, "b", tostring( defaultSettings.header_color.b ) )
xmlNodeSetAttribute( header_colorTag, "a", tostring( defaultSettings.header_color.a ) )
local team_colorTag = xmlCreateChild( settingsFile, "team_color" )
xmlNodeSetAttribute( team_colorTag, "r", tostring( defaultSettings.team_color.r ) )
xmlNodeSetAttribute( team_colorTag, "g", tostring( defaultSettings.team_color.g ) )
xmlNodeSetAttribute( team_colorTag, "b", tostring( defaultSettings.team_color.b ) )
xmlNodeSetAttribute( team_colorTag, "a", tostring( defaultSettings.team_color.a ) )
local border_colorTag = xmlCreateChild( settingsFile, "border_color" )
xmlNodeSetAttribute( border_colorTag, "r", tostring( defaultSettings.border_color.r ) )
xmlNodeSetAttribute( border_colorTag, "g", tostring( defaultSettings.border_color.g ) )
xmlNodeSetAttribute( border_colorTag, "b", tostring( defaultSettings.border_color.b ) )
xmlNodeSetAttribute( border_colorTag, "a", tostring( defaultSettings.border_color.a ) )
local serverinfo_colorTag = xmlCreateChild( settingsFile, "serverinfo_color" )
xmlNodeSetAttribute( serverinfo_colorTag, "r", tostring( defaultSettings.serverinfo_color.r ) )
xmlNodeSetAttribute( serverinfo_colorTag, "g", tostring( defaultSettings.serverinfo_color.g ) )
xmlNodeSetAttribute( serverinfo_colorTag, "b", tostring( defaultSettings.serverinfo_color.b ) )
xmlNodeSetAttribute( serverinfo_colorTag, "a", tostring( defaultSettings.serverinfo_color.a ) )
local content_colorTag = xmlCreateChild( settingsFile, "content_color" )
xmlNodeSetAttribute( content_colorTag, "r", tostring( defaultSettings.content_color.r ) )
xmlNodeSetAttribute( content_colorTag, "g", tostring( defaultSettings.content_color.g ) )
xmlNodeSetAttribute( content_colorTag, "b", tostring( defaultSettings.content_color.b ) )
xmlNodeSetAttribute( content_colorTag, "a", tostring( defaultSettings.content_color.a ) )
xmlSaveFile( settingsFile )
end
local useanimationTag = xmlFindChild( settingsFile, "useanimation", 0 )
if not useanimationTag then
useanimationTag = xmlCreateChild( settingsFile, "useanimation" )
xmlNodeSetValue( useanimationTag, tostring( defaultSettings.useanimation ) )
xmlSaveFile( settingsFile )
end
local toggleableTag = xmlFindChild( settingsFile, "toggleable", 0 )
if not toggleableTag then
toggleableTag = xmlCreateChild( settingsFile, "toggleable" )
xmlNodeSetValue( toggleableTag, tostring( defaultSettings.toggleable ) )
xmlSaveFile( settingsFile )
end
local showserverinfoTag = xmlFindChild( settingsFile, "showserverinfo", 0 )
if not showserverinfoTag then
showserverinfoTag = xmlCreateChild( settingsFile, "showserverinfo" )
xmlNodeSetValue( showserverinfoTag, tostring( defaultSettings.showserverinfo ) )
xmlSaveFile( settingsFile )
end
local showgamemodeinfoTag = xmlFindChild( settingsFile, "showgamemodeinfo", 0 )
if not showgamemodeinfoTag then
showgamemodeinfoTag = xmlCreateChild( settingsFile, "showgamemodeinfo" )
xmlNodeSetValue( showgamemodeinfoTag, tostring( defaultSettings.showgamemodeinfo ) )
xmlSaveFile( settingsFile )
end
local showteamsTag = xmlFindChild( settingsFile, "showteams", 0 )
if not showteamsTag then
showteamsTag = xmlCreateChild( settingsFile, "showteams" )
xmlNodeSetValue( showteamsTag, tostring( defaultSettings.showteams ) )
xmlSaveFile( settingsFile )
end
local usecolorsTag = xmlFindChild( settingsFile, "usecolors", 0 )
if not usecolorsTag then
usecolorsTag = xmlCreateChild( settingsFile, "usecolors" )
xmlNodeSetValue( usecolorsTag, tostring( defaultSettings.usecolors ) )
xmlSaveFile( settingsFile )
end
local drawspeedTag = xmlFindChild( settingsFile, "drawspeed", 0 )
if not drawspeedTag then
drawspeedTag = xmlCreateChild( settingsFile, "drawspeed" )
xmlNodeSetValue( drawspeedTag, tostring( defaultSettings.drawspeed ) )
xmlSaveFile( settingsFile )
end
local scaleTag = xmlFindChild( settingsFile, "scale", 0 )
if not scaleTag then
scaleTag = xmlCreateChild( settingsFile, "scale" )
xmlNodeSetValue( scaleTag, tostring( defaultSettings.scale ) )
xmlSaveFile( settingsFile )
end
local columnfontTag = xmlFindChild( settingsFile, "columnfont", 0 )
if not columnfontTag then
columnfontTag = xmlCreateChild( settingsFile, "columnfont" )
xmlNodeSetValue( columnfontTag, tostring( defaultSettings.columnfont ) )
xmlSaveFile( settingsFile )
end
local contentfontTag = xmlFindChild( settingsFile, "contentfont", 0 )
if not contentfontTag then
contentfontTag = xmlCreateChild( settingsFile, "contentfont" )
xmlNodeSetValue( contentfontTag, tostring( defaultSettings.contentfont ) )
xmlSaveFile( settingsFile )
end
local teamfontTag = xmlFindChild( settingsFile, "teamfont", 0 )
if not teamfontTag then
teamfontTag = xmlCreateChild( settingsFile, "teamfont" )
xmlNodeSetValue( teamfontTag, tostring( defaultSettings.teamfont ) )
xmlSaveFile( settingsFile )
end
local serverinfofontTag = xmlFindChild( settingsFile, "serverinfofont", 0 )
if not serverinfofontTag then
serverinfofontTag = xmlCreateChild( settingsFile, "serverinfofont" )
xmlNodeSetValue( serverinfofontTag, tostring( defaultSettings.serverinfofont ) )
xmlSaveFile( settingsFile )
end
local bg_colorTag = xmlFindChild( settingsFile, "bg_color", 0 )
if not bg_colorTag then
bg_colorTag = xmlCreateChild( settingsFile, "bg_color" )
xmlNodeSetAttribute( bg_colorTag, "r", tostring( defaultSettings.bg_color.r ) )
xmlNodeSetAttribute( bg_colorTag, "g", tostring( defaultSettings.bg_color.g ) )
xmlNodeSetAttribute( bg_colorTag, "b", tostring( defaultSettings.bg_color.b ) )
xmlNodeSetAttribute( bg_colorTag, "a", tostring( defaultSettings.bg_color.a ) )
xmlSaveFile( settingsFile )
end
local selection_colorTag = xmlFindChild( settingsFile, "selection_color", 0 )
if not selection_colorTag then
selection_colorTag = xmlCreateChild( settingsFile, "selection_color" )
xmlNodeSetAttribute( selection_colorTag, "r", tostring( defaultSettings.selection_color.r ) )
xmlNodeSetAttribute( selection_colorTag, "g", tostring( defaultSettings.selection_color.g ) )
xmlNodeSetAttribute( selection_colorTag, "b", tostring( defaultSettings.selection_color.b ) )
xmlNodeSetAttribute( selection_colorTag, "a", tostring( defaultSettings.selection_color.a ) )
xmlSaveFile( settingsFile )
end
local highlight_colorTag = xmlFindChild( settingsFile, "highlight_color", 0 )
if not highlight_colorTag then
highlight_colorTag = xmlCreateChild( settingsFile, "highlight_color" )
xmlNodeSetAttribute( highlight_colorTag, "r", tostring( defaultSettings.highlight_color.r ) )
xmlNodeSetAttribute( highlight_colorTag, "g", tostring( defaultSettings.highlight_color.g ) )
xmlNodeSetAttribute( highlight_colorTag, "b", tostring( defaultSettings.highlight_color.b ) )
xmlNodeSetAttribute( highlight_colorTag, "a", tostring( defaultSettings.highlight_color.a ) )
xmlSaveFile( settingsFile )
end
local header_colorTag = xmlFindChild( settingsFile, "header_color", 0 )
if not header_colorTag then
header_colorTag = xmlCreateChild( settingsFile, "header_color" )
xmlNodeSetAttribute( header_colorTag, "r", tostring( defaultSettings.header_color.r ) )
xmlNodeSetAttribute( header_colorTag, "g", tostring( defaultSettings.header_color.g ) )
xmlNodeSetAttribute( header_colorTag, "b", tostring( defaultSettings.header_color.b ) )
xmlNodeSetAttribute( header_colorTag, "a", tostring( defaultSettings.header_color.a ) )
xmlSaveFile( settingsFile )
end
local team_colorTag = xmlFindChild( settingsFile, "team_color", 0 )
if not team_colorTag then
team_colorTag = xmlCreateChild( settingsFile, "team_color" )
xmlNodeSetAttribute( team_colorTag, "r", tostring( defaultSettings.team_color.r ) )
xmlNodeSetAttribute( team_colorTag, "g", tostring( defaultSettings.team_color.g ) )
xmlNodeSetAttribute( team_colorTag, "b", tostring( defaultSettings.team_color.b ) )
xmlNodeSetAttribute( team_colorTag, "a", tostring( defaultSettings.team_color.a ) )
xmlSaveFile( settingsFile )
end
local border_colorTag = xmlFindChild( settingsFile, "border_color", 0 )
if not border_colorTag then
border_colorTag = xmlCreateChild( settingsFile, "border_color" )
xmlNodeSetAttribute( border_colorTag, "r", tostring( defaultSettings.border_color.r ) )
xmlNodeSetAttribute( border_colorTag, "g", tostring( defaultSettings.border_color.g ) )
xmlNodeSetAttribute( border_colorTag, "b", tostring( defaultSettings.border_color.b ) )
xmlNodeSetAttribute( border_colorTag, "a", tostring( defaultSettings.border_color.a ) )
xmlSaveFile( settingsFile )
end
local serverinfo_colorTag = xmlFindChild( settingsFile, "serverinfo_color", 0 )
if not serverinfo_colorTag then
serverinfo_colorTag = xmlCreateChild( settingsFile, "serverinfo_color" )
xmlNodeSetAttribute( serverinfo_colorTag, "r", tostring( defaultSettings.serverinfo_color.r ) )
xmlNodeSetAttribute( serverinfo_colorTag, "g", tostring( defaultSettings.serverinfo_color.g ) )
xmlNodeSetAttribute( serverinfo_colorTag, "b", tostring( defaultSettings.serverinfo_color.b ) )
xmlNodeSetAttribute( serverinfo_colorTag, "a", tostring( defaultSettings.serverinfo_color.a ) )
xmlSaveFile( settingsFile )
end
local content_colorTag = xmlFindChild( settingsFile, "content_color", 0 )
if not content_colorTag then
content_colorTag = xmlCreateChild( settingsFile, "content_color" )
xmlNodeSetAttribute( content_colorTag, "r", tostring( defaultSettings.content_color.r ) )
xmlNodeSetAttribute( content_colorTag, "g", tostring( defaultSettings.content_color.g ) )
xmlNodeSetAttribute( content_colorTag, "b", tostring( defaultSettings.content_color.b ) )
xmlNodeSetAttribute( content_colorTag, "a", tostring( defaultSettings.content_color.a ) )
xmlSaveFile( settingsFile )
end
settings.useanimation = xmlNodeGetValue( useanimationTag )
settings.useanimation = iif( settings.useanimation and tostring( settings.useanimation ) == "false", false, true )
settings.toggleable = xmlNodeGetValue( toggleableTag )
settings.toggleable = iif( settings.toggleable and tostring( settings.toggleable ) == "true", true, false )
settings.showserverinfo = xmlNodeGetValue( showserverinfoTag )
settings.showserverinfo = iif( settings.showserverinfo and tostring( settings.showserverinfo ) == "true", true, false )
settings.showgamemodeinfo = xmlNodeGetValue( showgamemodeinfoTag )
settings.showgamemodeinfo = iif( settings.showgamemodeinfo and tostring( settings.showgamemodeinfo ) == "true", true, false )
settings.showteams = xmlNodeGetValue( showteamsTag )
settings.showteams = iif( settings.showteams and tostring( settings.showteams ) == "false", false, true )
settings.usecolors = xmlNodeGetValue( usecolorsTag )
settings.usecolors = iif( settings.usecolors and tostring( settings.usecolors ) == "false", false, true )
settings.drawspeed = tonumber( xmlNodeGetValue( drawspeedTag ) )
settings.drawspeed = iif( type( settings.drawspeed ) == "number" and settings.drawspeed >= MIN_DRAWSPEED and settings.drawspeed <= MAX_DRAWSPEED, settings.drawspeed, defaultSettings.drawspeed )
settings.scale = tonumber( xmlNodeGetValue( scaleTag ) )
settings.scale = iif( type( settings.scale ) == "number" and settings.scale >= MIN_SCALE and settings.scale <= MAX_SCALE, settings.scale, defaultSettings.scale )
settings.columnfont = xmlNodeGetValue( columnfontTag )
settings.columnfont = iif( fontScale[settings.columnfont], settings.columnfont, defaultSettings.columnfont )
settings.contentfont = xmlNodeGetValue( contentfontTag )
settings.contentfont = iif( fontScale[settings.contentfont], settings.contentfont, defaultSettings.contentfont )
settings.teamfont = xmlNodeGetValue( teamfontTag )
settings.teamfont = iif( fontScale[settings.teamfont], settings.teamfont, defaultSettings.teamfont )
settings.serverinfofont = xmlNodeGetValue( serverinfofontTag )
settings.serverinfofont = iif( fontScale[settings.serverinfofont], settings.serverinfofont, defaultSettings.serverinfofont )
settings.bg_color.r = validateRange( tonumber( xmlNodeGetAttribute( bg_colorTag, "r" ) ) ) or defaultSettings.bg_color.r
settings.bg_color.g = validateRange( tonumber( xmlNodeGetAttribute( bg_colorTag, "g" ) ) ) or defaultSettings.bg_color.g
settings.bg_color.b = validateRange( tonumber( xmlNodeGetAttribute( bg_colorTag, "b" ) ) ) or defaultSettings.bg_color.b
settings.bg_color.a = validateRange( tonumber( xmlNodeGetAttribute( bg_colorTag, "a" ) ) ) or defaultSettings.bg_color.a
settings.selection_color.r = validateRange( tonumber( xmlNodeGetAttribute( selection_colorTag, "r" ) ) ) or defaultSettings.selection_color.r
settings.selection_color.g = validateRange( tonumber( xmlNodeGetAttribute( selection_colorTag, "g" ) ) ) or defaultSettings.selection_color.g
settings.selection_color.b = validateRange( tonumber( xmlNodeGetAttribute( selection_colorTag, "b" ) ) ) or defaultSettings.selection_color.b
settings.selection_color.a = validateRange( tonumber( xmlNodeGetAttribute( selection_colorTag, "a" ) ) ) or defaultSettings.selection_color.a
settings.highlight_color.r = validateRange( tonumber( xmlNodeGetAttribute( highlight_colorTag, "r" ) ) ) or defaultSettings.highlight_color.r
settings.highlight_color.g = validateRange( tonumber( xmlNodeGetAttribute( highlight_colorTag, "g" ) ) ) or defaultSettings.highlight_color.g
settings.highlight_color.b = validateRange( tonumber( xmlNodeGetAttribute( highlight_colorTag, "b" ) ) ) or defaultSettings.highlight_color.b
settings.highlight_color.a = validateRange( tonumber( xmlNodeGetAttribute( highlight_colorTag, "a" ) ) ) or defaultSettings.highlight_color.a
settings.header_color.r = validateRange( tonumber( xmlNodeGetAttribute( header_colorTag, "r" ) ) ) or defaultSettings.header_color.r
settings.header_color.g = validateRange( tonumber( xmlNodeGetAttribute( header_colorTag, "g" ) ) ) or defaultSettings.header_color.g
settings.header_color.b = validateRange( tonumber( xmlNodeGetAttribute( header_colorTag, "b" ) ) ) or defaultSettings.header_color.b
settings.header_color.a = validateRange( tonumber( xmlNodeGetAttribute( header_colorTag, "a" ) ) ) or defaultSettings.header_color.a
settings.team_color.r = validateRange( tonumber( xmlNodeGetAttribute( team_colorTag, "r" ) ) ) or defaultSettings.team_color.r
settings.team_color.g = validateRange( tonumber( xmlNodeGetAttribute( team_colorTag, "g" ) ) ) or defaultSettings.team_color.g
settings.team_color.b = validateRange( tonumber( xmlNodeGetAttribute( team_colorTag, "b" ) ) ) or defaultSettings.team_color.b
settings.team_color.a = validateRange( tonumber( xmlNodeGetAttribute( team_colorTag, "a" ) ) ) or defaultSettings.team_color.a
settings.border_color.r = validateRange( tonumber( xmlNodeGetAttribute( border_colorTag, "r" ) ) ) or defaultSettings.border_color.r
settings.border_color.g = validateRange( tonumber( xmlNodeGetAttribute( border_colorTag, "g" ) ) ) or defaultSettings.border_color.g
settings.border_color.b = validateRange( tonumber( xmlNodeGetAttribute( border_colorTag, "b" ) ) ) or defaultSettings.border_color.b
settings.border_color.a = validateRange( tonumber( xmlNodeGetAttribute( border_colorTag, "a" ) ) ) or defaultSettings.border_color.a
settings.serverinfo_color.r = validateRange( tonumber( xmlNodeGetAttribute( serverinfo_colorTag, "r" ) ) ) or defaultSettings.serverinfo_color.r
settings.serverinfo_color.g = validateRange( tonumber( xmlNodeGetAttribute( serverinfo_colorTag, "g" ) ) ) or defaultSettings.serverinfo_color.g
settings.serverinfo_color.b = validateRange( tonumber( xmlNodeGetAttribute( serverinfo_colorTag, "b" ) ) ) or defaultSettings.serverinfo_color.b
settings.serverinfo_color.a = validateRange( tonumber( xmlNodeGetAttribute( serverinfo_colorTag, "a" ) ) ) or defaultSettings.serverinfo_color.a
settings.content_color.r = validateRange( tonumber( xmlNodeGetAttribute( content_colorTag, "r" ) ) ) or defaultSettings.content_color.r
settings.content_color.g = validateRange( tonumber( xmlNodeGetAttribute( content_colorTag, "g" ) ) ) or defaultSettings.content_color.g
settings.content_color.b = validateRange( tonumber( xmlNodeGetAttribute( content_colorTag, "b" ) ) ) or defaultSettings.content_color.b
settings.content_color.a = validateRange( tonumber( xmlNodeGetAttribute( content_colorTag, "a" ) ) ) or defaultSettings.content_color.a
xmlUnloadFile( settingsFile )
useAnimation = false
scoreboardIsToggleable = false
showServerInfo = true
showGamemodeInfo = false
showTeams = true
useColors = true
drawSpeed = settings.drawspeed
scoreboardScale = 1
columnFont = customFont
contentFont = customFont
teamHeaderFont = customFont
serverInfoFont = customFont
local r,g,b = unpack(colorCode)
cScoreboardBackground = tocolor( 0,0,0,150 )
cSelection = tocolor( 255,255,0,100 )
cHighlight = tocolor( settings.highlight_color.r, settings.highlight_color.g, settings.highlight_color.b, settings.highlight_color.a )
cHeader = tocolor( r,g,b, settings.header_color.a )
cTeam = tocolor( 0,0,0,255 )
cBorder = tocolor( settings.border_color.r, settings.border_color.g, settings.border_color.b, settings.border_color.a )
cServerInfo = tocolor( r,g,b, 255 )
cContent = tocolor( settings.content_color.r, settings.content_color.g, settings.content_color.b, settings.content_color.a )
end
function createScoreboardSettingsWindow( posX, posY )
if not windowSettings then
windowSettings = guiCreateWindow( posX, posY, 323, 350, "Scoreboard settings", false )
guiSetText( windowSettings, "Scoreboard settings" )
guiWindowSetSizable( windowSettings, false )
labelUseAnimation = guiCreateLabel( 10, 26, 64, 15, "Use animation:", false, windowSettings )
guiSetFont( labelUseAnimation, "default-small" )
checkAnimationYes = guiCreateCheckBox( 101, 26, 42, 14, "yes", false, false, windowSettings )
checkAnimationNo = guiCreateCheckBox( 167, 26, 42, 14, "no", false, false, windowSettings )
labelMode = guiCreateLabel( 10, 43, 64, 15, "Mode:", false, windowSettings )
guiSetFont( labelMode, "default-small" )
checkModeHolding = guiCreateCheckBox( 101, 43, 64, 14, "holding", false, false, windowSettings )
checkModeToggled = guiCreateCheckBox( 167, 43, 64, 14, "toggled", false, false, windowSettings )
labelShowInfoOf = guiCreateLabel( 10, 60, 64, 15, "Show info of:", false, windowSettings )
guiSetFont( labelShowInfoOf, "default-small" )
checkServerInfoServer = guiCreateCheckBox( 101, 60, 64, 14, "server", false, false, windowSettings )
checkServerInfoGamemode = guiCreateCheckBox( 167, 60, 84, 14, "gamemode", false, false, windowSettings )
labelShowTeams = guiCreateLabel( 10, 77, 64, 15, "Show teams:", false, windowSettings )
guiSetFont( labelShowTeams, "default-small" )
checkShowTeamsYes = guiCreateCheckBox( 101, 77, 64, 14, "yes", false, false, windowSettings )
checkShowTeamsNo = guiCreateCheckBox( 167, 77, 84, 14, "no", false, false, windowSettings )
labelUseColors = guiCreateLabel( 10, 94, 64, 15, "Use colors:", false, windowSettings )
guiSetFont( labelUseColors, "default-small" )
checkUseColorsYes = guiCreateCheckBox( 101, 94, 64, 14, "yes", false, false, windowSettings )
checkUseColorsNo = guiCreateCheckBox( 167, 94, 84, 14, "no", false, false, windowSettings )
labelDrawSpeed = guiCreateLabel( 10, 111, 64, 15, "Draw speed:", false, windowSettings )
guiSetFont( labelDrawSpeed, "default-small" )
scrollDrawSpeed = guiCreateScrollBar( 101, 111, 172, 14, true, false, windowSettings )
labelScale = guiCreateLabel( 10, 128, 64, 15, "Scale:", false, windowSettings )
guiSetFont( labelScale, "default-small" )
scrollScale = guiCreateScrollBar( 101, 128, 172, 14, true, false, windowSettings )
labelFonts = guiCreateLabel( 10, 145, 64, 15, "Fonts:", false, windowSettings )
guiSetFont( labelFonts, "default-small" )
buttonColumnFont = guiCreateButton( 101, 145, 87, 14, " ", false, windowSettings )
buttonContentFont = guiCreateButton( 187, 145, 87, 14, " ", false, windowSettings )
buttonTeamFont = guiCreateButton( 101, 162, 87, 14, " ", false, windowSettings )
buttonServerInfoFont = guiCreateButton( 187, 162, 87, 14, " ", false, windowSettings )
labelBackgroundColor = guiCreateLabel( 10, 179, 74, 12, "Background color:", false, windowSettings)
guiSetFont( labelBackgroundColor, "default-small" )
buttonChangeBackgroundColor = guiCreateButton( 187, 179, 87, 14, "Change", false, windowSettings )
guiSetFont( buttonChangeBackgroundColor, "default-bold-small" )
labelSelectionColor = guiCreateLabel( 10, 196, 74, 12, "Local player color:", false, windowSettings )
guiSetFont( labelSelectionColor, "default-small" )
buttonChangeSelectionColor = guiCreateButton( 187, 196, 87, 14, "Change", false, windowSettings )
guiSetFont( buttonChangeSelectionColor, "default-bold-small" )
labelHighlightColor = guiCreateLabel( 10, 213, 64, 12, "Selection color:", false, windowSettings )
guiSetFont( labelHighlightColor, "default-small" )
buttonChangeHighlightColor = guiCreateButton( 187, 213, 87, 14, "Change", false, windowSettings )
guiSetFont( buttonChangeHighlightColor, "default-bold-small" )
labelColumnHeaderColor = guiCreateLabel( 10, 230, 87, 12, "Column header color:", false, windowSettings )
guiSetFont( labelColumnHeaderColor, "default-small" )
buttonChangeColumnHeaderColor = guiCreateButton( 187, 230, 87, 14, "Change", false, windowSettings )
guiSetFont( buttonChangeColumnHeaderColor, "default-bold-small" )
labelTeamHeaderColor = guiCreateLabel( 10, 247, 85, 12, "Team header color:", false, windowSettings )
guiSetFont( labelTeamHeaderColor, "default-small" )
buttonChangeTeamHeaderColor = guiCreateButton( 187, 247, 87, 14, "Change", false, windowSettings )
guiSetFont( buttonChangeTeamHeaderColor, "default-bold-small" )
labelBorderlineColor = guiCreateLabel( 10, 264, 86, 12, "Border line color:", false, windowSettings )
guiSetFont( labelBorderlineColor, "default-small" )
buttonChangeBorderlineColor = guiCreateButton( 187, 264, 87, 14, "Change", false, windowSettings )
guiSetFont( buttonChangeBorderlineColor, "default-bold-small" )
labelServerInfoColor = guiCreateLabel( 10, 281, 86, 12, "Server info color:", false, windowSettings )
guiSetFont( labelServerInfoColor, "default-small" )
buttonChangeServerInfoColor = guiCreateButton( 187, 281, 87, 14, "Change", false, windowSettings )
guiSetFont( buttonChangeServerInfoColor, "default-bold-small" )
labelContentColor = guiCreateLabel( 10, 298, 86, 12, "Content color:", false, windowSettings )
guiSetFont( labelContentColor, "default-small" )
buttonChangeContentColor = guiCreateButton( 187, 298, 87, 14, "Change", false, windowSettings )
guiSetFont( buttonChangeContentColor, "default-bold-small" )
buttonSaveChanges = guiCreateButton( 10, 322, 80, 15, "Save changes", false, windowSettings )
guiSetFont( buttonSaveChanges, "default-small" )
buttonRestoreDefaults = guiCreateButton( 95, 322, 80, 15, "Restore defaults", false, windowSettings )
guiSetFont( buttonRestoreDefaults, "default-small" )
buttonCancel = guiCreateButton( 200, 322, 120, 15, "Cancel", false, windowSettings )
guiSetFont( buttonCancel, "default-small" )
end
if type( settings.useanimation ) == "boolean" and not settings.useanimation then
guiCheckBoxSetSelected( checkAnimationNo, true )
guiCheckBoxSetSelected( checkAnimationYes, false )
else
guiCheckBoxSetSelected( checkAnimationNo, false )
guiCheckBoxSetSelected( checkAnimationYes, true )
end
if type( settings.toggleable ) == "boolean" and settings.toggleable then
guiCheckBoxSetSelected( checkModeToggled, true )
guiCheckBoxSetSelected( checkModeHolding, false )
else
guiCheckBoxSetSelected( checkModeToggled, false )
guiCheckBoxSetSelected( checkModeHolding, true )
end
if type( settings.showteams ) == "boolean" and not settings.showteams then
guiCheckBoxSetSelected( checkShowTeamsNo, true )
guiCheckBoxSetSelected( checkShowTeamsYes, false )
else
guiCheckBoxSetSelected( checkShowTeamsNo, false )
guiCheckBoxSetSelected( checkShowTeamsYes, true )
end
if type( settings.usecolors ) == "boolean" and not settings.usecolors then
guiCheckBoxSetSelected( checkUseColorsNo, true )
guiCheckBoxSetSelected( checkUseColorsYes, false )
else
guiCheckBoxSetSelected( checkUseColorsNo, false )
guiCheckBoxSetSelected( checkUseColorsYes, true )
end
guiCheckBoxSetSelected( checkServerInfoServer, settings.showserverinfo or defaultSettings.showserverinfo )
guiCheckBoxSetSelected( checkServerInfoGamemode, settings.showgamemodeinfo or defaultSettings.showgamemodeinfo )
guiScrollBarSetScrollPosition( scrollDrawSpeed, ((settings.drawspeed or defaultSettings.drawspeed)-MIN_DRAWSPEED)/(MAX_DRAWSPEED-MIN_DRAWSPEED)*100 )
guiScrollBarSetScrollPosition( scrollScale, ((settings.scale or defaultSettings.scale)-MIN_SCALE)/(MAX_SCALE-MIN_SCALE)*100 )
for k, v in ipairs( fontNames ) do
if settings.columnfont == v then fontIndexes.column = k end
if settings.contentfont == v then fontIndexes.content = k end
if settings.teamfont == v then fontIndexes.team = k end
if settings.serverinfofont == v then fontIndexes.serverinfo = k end
end
tempColors.bg_color.r = settings.bg_color.r or defaultSettings.bg_color.r
tempColors.bg_color.g = settings.bg_color.g or defaultSettings.bg_color.g
tempColors.bg_color.b = settings.bg_color.b or defaultSettings.bg_color.b
tempColors.bg_color.a = settings.bg_color.a or defaultSettings.bg_color.a
tempColors.selection_color.r = settings.selection_color.r or defaultSettings.selection_color.r
tempColors.selection_color.g = settings.selection_color.g or defaultSettings.selection_color.g
tempColors.selection_color.b = settings.selection_color.b or defaultSettings.selection_color.b
tempColors.selection_color.a = settings.selection_color.a or defaultSettings.selection_color.a
tempColors.highlight_color.r = settings.highlight_color.r or defaultSettings.highlight_color.r
tempColors.highlight_color.g = settings.highlight_color.g or defaultSettings.highlight_color.g
tempColors.highlight_color.b = settings.highlight_color.b or defaultSettings.highlight_color.b
tempColors.highlight_color.a = settings.highlight_color.a or defaultSettings.highlight_color.a
tempColors.header_color.r = settings.header_color.r or defaultSettings.header_color.r
tempColors.header_color.g = settings.header_color.g or defaultSettings.header_color.g
tempColors.header_color.b = settings.header_color.b or defaultSettings.header_color.b
tempColors.header_color.a = settings.header_color.a or defaultSettings.header_color.a
tempColors.team_color.r = settings.team_color.r or defaultSettings.team_color.r
tempColors.team_color.g = settings.team_color.g or defaultSettings.team_color.g
tempColors.team_color.b = settings.team_color.b or defaultSettings.team_color.b
tempColors.team_color.a = settings.team_color.a or defaultSettings.team_color.a
tempColors.border_color.r = settings.border_color.r or defaultSettings.border_color.r
tempColors.border_color.g = settings.border_color.g or defaultSettings.border_color.g
tempColors.border_color.b = settings.border_color.b or defaultSettings.border_color.b
tempColors.border_color.a = settings.border_color.a or defaultSettings.border_color.a
tempColors.serverinfo_color.r = settings.serverinfo_color.r or defaultSettings.serverinfo_color.r
tempColors.serverinfo_color.g = settings.serverinfo_color.g or defaultSettings.serverinfo_color.g
tempColors.serverinfo_color.b = settings.serverinfo_color.b or defaultSettings.serverinfo_color.b
tempColors.serverinfo_color.a = settings.serverinfo_color.a or defaultSettings.serverinfo_color.a
tempColors.content_color.r = settings.content_color.r or defaultSettings.content_color.r
tempColors.content_color.g = settings.content_color.g or defaultSettings.content_color.g
tempColors.content_color.b = settings.content_color.b or defaultSettings.content_color.b
tempColors.content_color.a = settings.content_color.a or defaultSettings.content_color.a
addEventHandler( "onClientGUIClick", windowSettings, settingsWindowClickHandler )
addEventHandler( "onClientRender", getRootElement(), drawSettingsWindowColors )
end
function destroyScoreboardSettingsWindow()
removeEventHandler( "onClientGUIClick", windowSettings, settingsWindowClickHandler )
removeEventHandler( "onClientRender", getRootElement(), drawSettingsWindowColors )
destroyElement( windowSettings )
if not getKeyState( "mouse2" ) then
showCursor( false )
end
colorPicker.closeSelect()
windowSettings = nil
end
function settingsWindowClickHandler( button, state )
if source == buttonSaveChanges then
saveSettingsFromSettingsWindow()
elseif source == buttonRestoreDefaults then
restoreDefaultSettings()
elseif source == buttonCancel then
destroyScoreboardSettingsWindow()
elseif source == buttonColumnFont then
if fontIndexes.column + 1 > #fontNames then
fontIndexes.column = 1
else
fontIndexes.column = fontIndexes.column + 1
end
elseif source == buttonContentFont then
if fontIndexes.content + 1 > #fontNames then
fontIndexes.content = 1
else
fontIndexes.content = fontIndexes.content + 1
end
elseif source == buttonTeamFont then
if fontIndexes.team + 1 > #fontNames then
fontIndexes.team = 1
else
fontIndexes.team = fontIndexes.team + 1
end
elseif source == buttonServerInfoFont then
if fontIndexes.serverinfo + 1 > #fontNames then
fontIndexes.serverinfo = 1
else
fontIndexes.serverinfo = fontIndexes.serverinfo + 1
end
elseif source == buttonChangeBackgroundColor then
colorPicker.openSelect( "bg_color" )
elseif source == buttonChangeSelectionColor then
colorPicker.openSelect( "selection_color" )
elseif source == buttonChangeHighlightColor then
colorPicker.openSelect( "highlight_color" )
elseif source == buttonChangeColumnHeaderColor then
colorPicker.openSelect( "header_color" )
elseif source == buttonChangeTeamHeaderColor then
colorPicker.openSelect( "team_color" )
elseif source == buttonChangeBorderlineColor then
colorPicker.openSelect( "border_color" )
elseif source == buttonChangeServerInfoColor then
colorPicker.openSelect( "serverinfo_color" )
elseif source == buttonChangeContentColor then
colorPicker.openSelect( "content_color" )
elseif source == checkAnimationNo or source == checkAnimationYes then
guiCheckBoxSetSelected( checkAnimationYes, false )
guiCheckBoxSetSelected( checkAnimationNo, false )
guiCheckBoxSetSelected( source, true )
elseif source == checkModeToggled or source == checkModeHolding then
guiCheckBoxSetSelected( checkModeToggled, false )
guiCheckBoxSetSelected( checkModeHolding, false )
guiCheckBoxSetSelected( source, true )
elseif source == checkShowTeamsNo or source == checkShowTeamsYes then
guiCheckBoxSetSelected( checkShowTeamsYes, false )
guiCheckBoxSetSelected( checkShowTeamsNo, false )
guiCheckBoxSetSelected( source, true )
elseif source == checkUseColorsNo or source == checkUseColorsYes then
guiCheckBoxSetSelected( checkUseColorsYes, false )
guiCheckBoxSetSelected( checkUseColorsNo, false )
guiCheckBoxSetSelected( source, true )
end
end
function drawSettingsWindowColors()
local x, y = guiGetPosition( windowSettings, false )
local drawSpeed = MIN_DRAWSPEED + ((guiScrollBarGetScrollPosition( scrollDrawSpeed )/100)*(MAX_DRAWSPEED-MIN_DRAWSPEED))
dxDrawText( string.format( "%.2f", drawSpeed ), x+280, y+111, x+280+33, y+111+16, cWhite, 1, "default", "left", "top", true, false, true )
local scale = MIN_SCALE + ((guiScrollBarGetScrollPosition( scrollScale )/100)*(MAX_SCALE-MIN_SCALE))
dxDrawText( string.format( "%.2f", scale ), x+280, y+128, x+280+33, y+128+16, cWhite, 1, "default", "left", "top", true, false, true )
dxDrawText( "Column", x+101, y+145, x+101+87, y+145+14, cWhite, fontscale( fontNames[fontIndexes.column], 1 ), fontNames[fontIndexes.column], "center", "center", true, false, true )
dxDrawText( "Content", x+187, y+145, x+187+87, y+145+14, cWhite, fontscale( fontNames[fontIndexes.content], 1 ), fontNames[fontIndexes.content], "center", "center", true, false, true )
dxDrawText( "Team", x+101, y+162, x+101+87, y+162+14, cWhite, fontscale( fontNames[fontIndexes.team], 1 ), fontNames[fontIndexes.team], "center", "center", true, false, true )
dxDrawText( "Server info", x+187, y+162, x+187+87, y+162+14, cWhite, fontscale( fontNames[fontIndexes.serverinfo], 1 ), fontNames[fontIndexes.serverinfo], "center", "center", true, false, true )
if tempColors.bg_color.r and tempColors.bg_color.g and tempColors.bg_color.b and tempColors.bg_color.a then
dxDrawRectangle( x+101, y+179, 84, 16, tocolor( tempColors.bg_color.r, tempColors.bg_color.g, tempColors.bg_color.b, tempColors.bg_color.a ), true )
end
if tempColors.selection_color.r and tempColors.selection_color.g and tempColors.selection_color.b and tempColors.selection_color.a then
dxDrawRectangle( x+101, y+196, 84, 16, tocolor( tempColors.selection_color.r, tempColors.selection_color.g, tempColors.selection_color.b, tempColors.selection_color.a ), true )
end
if tempColors.highlight_color.r and tempColors.highlight_color.g and tempColors.highlight_color.b and tempColors.highlight_color.a then
dxDrawRectangle( x+101, y+213, 84, 16, tocolor( tempColors.highlight_color.r, tempColors.highlight_color.g, tempColors.highlight_color.b, tempColors.highlight_color.a ), true )
end
if tempColors.header_color.r and tempColors.header_color.g and tempColors.header_color.b and tempColors.header_color.a then
dxDrawRectangle( x+101, y+230, 84, 16, tocolor( tempColors.header_color.r, tempColors.header_color.g, tempColors.header_color.b, tempColors.header_color.a ), true )
end
if tempColors.team_color.r and tempColors.team_color.g and tempColors.team_color.b and tempColors.team_color.a then
dxDrawRectangle( x+101, y+247, 84, 16, tocolor( tempColors.team_color.r, tempColors.team_color.g, tempColors.team_color.b, tempColors.team_color.a ), true )
end
if tempColors.border_color.r and tempColors.border_color.g and tempColors.border_color.b and tempColors.border_color.a then
dxDrawRectangle( x+101, y+264, 84, 16, tocolor( tempColors.border_color.r, tempColors.border_color.g, tempColors.border_color.b, tempColors.border_color.a ), true )
end
if tempColors.serverinfo_color.r and tempColors.serverinfo_color.g and tempColors.serverinfo_color.b and tempColors.serverinfo_color.a then
dxDrawRectangle( x+101, y+281, 84, 16, tocolor( tempColors.serverinfo_color.r, tempColors.serverinfo_color.g, tempColors.serverinfo_color.b, tempColors.serverinfo_color.a ), true )
end
if tempColors.content_color.r and tempColors.content_color.g and tempColors.content_color.b and tempColors.content_color.a then
dxDrawRectangle( x+101, y+298, 84, 16, tocolor( tempColors.content_color.r, tempColors.content_color.g, tempColors.content_color.b, tempColors.content_color.a ), true )
end
end
function saveSettingsFromSettingsWindow()
local userSettings = {
["useanimation"] = nil,
["toggleable"] = nil,
["showserverinfo"] = nil,
["showgamemodeinfo"] = nil,
["showteams"] = nil,
["usecolors"] = nil,
["drawspeed"] = nil,
["scale"] = nil,
["columnfont"] = nil,
["contentfont"] = nil,
["teamfont"] = nil,
["serverinfofont"] = nil,
["bg_color"] = {},
["selection_color"] = {},
["highlight_color"] = {},
["header_color"] = {},
["team_color"] = {},
["border_color"] = {},
["serverinfo_color"] = {},
["content_color"] = {}
}
userSettings.useanimation = iif( guiCheckBoxGetSelected( checkAnimationNo ), false, true )
userSettings.toggleable = iif( guiCheckBoxGetSelected( checkModeToggled ), true, false )
userSettings.showteams = iif( guiCheckBoxGetSelected( checkShowTeamsNo ), false, true )
userSettings.usecolors = iif( guiCheckBoxGetSelected( checkUseColorsNo ), false, true )
userSettings.showserverinfo = guiCheckBoxGetSelected( checkServerInfoServer )
userSettings.showgamemodeinfo = guiCheckBoxGetSelected( checkServerInfoGamemode )
userSettings.drawspeed = string.format( "%.2f", MIN_DRAWSPEED + ( (guiScrollBarGetScrollPosition( scrollDrawSpeed )/100)*(MAX_DRAWSPEED-MIN_DRAWSPEED) ) )
userSettings.drawspeed = tonumber( userSettings.drawspeed )
userSettings.scale = string.format( "%.2f", MIN_SCALE + ( (guiScrollBarGetScrollPosition( scrollScale )/100)*(MAX_SCALE-MIN_SCALE) ) )
userSettings.scale = tonumber( userSettings.scale )
userSettings.columnfont = fontNames[fontIndexes.column]
userSettings.contentfont = fontNames[fontIndexes.content]
userSettings.teamfont = fontNames[fontIndexes.team]
userSettings.serverinfofont = fontNames[fontIndexes.serverinfo]
userSettings.bg_color.r = tempColors.bg_color.r or defaultSettings.bg_color.r
userSettings.bg_color.g = tempColors.bg_color.g or defaultSettings.bg_color.g
userSettings.bg_color.b = tempColors.bg_color.b or defaultSettings.bg_color.b
userSettings.bg_color.a = tempColors.bg_color.a or defaultSettings.bg_color.a
userSettings.selection_color.r = tempColors.selection_color.r or defaultSettings.selection_color.r
userSettings.selection_color.g = tempColors.selection_color.g or defaultSettings.selection_color.g
userSettings.selection_color.b = tempColors.selection_color.b or defaultSettings.selection_color.b
userSettings.selection_color.a = tempColors.selection_color.a or defaultSettings.selection_color.a
userSettings.highlight_color.r = tempColors.highlight_color.r or defaultSettings.highlight_color.r
userSettings.highlight_color.g = tempColors.highlight_color.g or defaultSettings.highlight_color.g
userSettings.highlight_color.b = tempColors.highlight_color.b or defaultSettings.highlight_color.b
userSettings.highlight_color.a = tempColors.highlight_color.a or defaultSettings.highlight_color.a
userSettings.header_color.r = tempColors.header_color.r or defaultSettings.header_color.r
userSettings.header_color.g = tempColors.header_color.g or defaultSettings.header_color.g
userSettings.header_color.b = tempColors.header_color.b or defaultSettings.header_color.b
userSettings.header_color.a = tempColors.header_color.a or defaultSettings.header_color.a
userSettings.team_color.r = tempColors.team_color.r or defaultSettings.team_color.r
userSettings.team_color.g = tempColors.team_color.g or defaultSettings.team_color.g
userSettings.team_color.b = tempColors.team_color.b or defaultSettings.team_color.b
userSettings.team_color.a = tempColors.team_color.a or defaultSettings.team_color.a
userSettings.border_color.r = tempColors.border_color.r or defaultSettings.border_color.r
userSettings.border_color.g = tempColors.border_color.g or defaultSettings.border_color.g
userSettings.border_color.b = tempColors.border_color.b or defaultSettings.border_color.b
userSettings.border_color.a = tempColors.border_color.a or defaultSettings.border_color.a
userSettings.serverinfo_color.r = tempColors.serverinfo_color.r or defaultSettings.serverinfo_color.r
userSettings.serverinfo_color.g = tempColors.serverinfo_color.g or defaultSettings.serverinfo_color.g
userSettings.serverinfo_color.b = tempColors.serverinfo_color.b or defaultSettings.serverinfo_color.b
userSettings.serverinfo_color.a = tempColors.serverinfo_color.a or defaultSettings.serverinfo_color.a
userSettings.content_color.r = tempColors.content_color.r or defaultSettings.content_color.r
userSettings.content_color.g = tempColors.content_color.g or defaultSettings.content_color.g
userSettings.content_color.b = tempColors.content_color.b or defaultSettings.content_color.b
userSettings.content_color.a = tempColors.content_color.a or defaultSettings.content_color.a
saveSettings( userSettings )
end
function restoreDefaultSettings()
saveSettings( defaultSettings )
end
function saveSettings( settingsTable )
local settingsFile = xmlLoadFile( "settings.xml" )
if not settingsFile then
settingsFile = xmlCreateFile( "settings.xml", "settings" )
if not settingsFile then return false end
local useanimationTag = xmlCreateChild( settingsFile, "useanimation" )
local toggleableTag = xmlCreateChild( settingsFile, "toggleable" )
local showserverinfoTag = xmlCreateChild( settingsFile, "showserverinfo" )
local showgamemodeinfoTag = xmlCreateChild( settingsFile, "showgamemodeinfo" )
local showteamsTag = xmlCreateChild( settingsFile, "showteams" )
local usecolorsTag = xmlCreateChild( settingsFile, "usecolors" )
local drawspeedTag = xmlCreateChild( settingsFile, "drawspeed" )
local scaleTag = xmlCreateChild( settingsFile, "scale" )
local columnfontTag = xmlCreateChild( settingsFile, "columnfont" )
local contentfontTag = xmlCreateChild( settingsFile, "contentfont" )
local teamfontTag = xmlCreateChild( settingsFile, "teamfont" )
local serverinfofontTag = xmlCreateChild( settingsFile, "serverinfofont" )
local bg_colorTag = xmlCreateChild( settingsFile, "bg_color" )
local selection_colorTag = xmlCreateChild( settingsFile, "selection_color" )
local highlight_colorTag = xmlCreateChild( settingsFile, "highlight_color" )
local header_colorTag = xmlCreateChild( settingsFile, "header_color" )
local team_colorTag = xmlCreateChild( settingsFile, "team_color" )
local border_colorTag = xmlCreateChild( settingsFile, "border_color" )
local serverinfo_colorTag = xmlCreateChild( settingsFile, "serverinfo_color" )
local content_colorTag = xmlCreateChild( settingsFile, "content_color" )
end
local useanimationTag = xmlFindChild( settingsFile, "useanimation", 0 )
if not useanimationTag then
useanimationTag = xmlCreateChild( settingsFile, "useanimation" )
end
local toggleableTag = xmlFindChild( settingsFile, "toggleable", 0 )
if not toggleableTag then
toggleableTag = xmlCreateChild( settingsFile, "toggleable" )
end
local showserverinfoTag = xmlFindChild( settingsFile, "showserverinfo", 0 )
if not showserverinfoTag then
showserverinfoTag = xmlCreateChild( settingsFile, "showserverinfo" )
end
local showgamemodeinfoTag = xmlFindChild( settingsFile, "showgamemodeinfo", 0 )
if not showgamemodeinfoTag then
showgamemodeinfoTag = xmlCreateChild( settingsFile, "showgamemodeinfo" )
end
local showteamsTag = xmlFindChild( settingsFile, "showteams", 0 )
if not showteamsTag then
showteamsTag = xmlCreateChild( settingsFile, "showteams" )
end
local usecolorsTag = xmlFindChild( settingsFile, "usecolors", 0 )
if not usecolorsTag then
usecolorsTag = xmlCreateChild( settingsFile, "usecolors" )
end
local drawspeedTag = xmlFindChild( settingsFile, "drawspeed", 0 )
if not drawspeedTag then
drawspeedTag = xmlCreateChild( settingsFile, "drawspeed" )
end
local scaleTag = xmlFindChild( settingsFile, "scale", 0 )
if not scaleTag then
scaleTag = xmlCreateChild( settingsFile, "scale" )
end
local columnfontTag = xmlFindChild( settingsFile, "columnfont", 0 )
if not columnfontTag then
columnfontTag = xmlCreateChild( settingsFile, "columnfont" )
end
local contentfontTag = xmlFindChild( settingsFile, "contentfont", 0 )
if not contentfontTag then
contentfontTag = xmlCreateChild( settingsFile, "contentfont" )
end
local teamfontTag = xmlFindChild( settingsFile, "teamfont", 0 )
if not teamfontTag then
teamfontTag = xmlCreateChild( settingsFile, "teamfont" )
end
local serverinfofontTag = xmlFindChild( settingsFile, "serverinfofont", 0 )
if not serverinfofontTag then
serverinfofontTag = xmlCreateChild( settingsFile, "serverinfofont" )
end
local bg_colorTag = xmlFindChild( settingsFile, "bg_color", 0 )
if not bg_colorTag then
bg_colorTag = xmlCreateChild( settingsFile, "bg_color" )
end
local selection_colorTag = xmlFindChild( settingsFile, "selection_color", 0 )
if not selection_colorTag then
selection_colorTag = xmlCreateChild( settingsFile, "selection_color" )
end
local highlight_colorTag = xmlFindChild( settingsFile, "highlight_color", 0 )
if not highlight_colorTag then
highlight_colorTag = xmlCreateChild( settingsFile, "highlight_color" )
end
local header_colorTag = xmlFindChild( settingsFile, "header_color", 0 )
if not header_colorTag then
header_colorTag = xmlCreateChild( settingsFile, "header_color" )
end
local team_colorTag = xmlFindChild( settingsFile, "team_color", 0 )
if not team_colorTag then
team_colorTag = xmlCreateChild( settingsFile, "team_color" )
end
local border_colorTag = xmlFindChild( settingsFile, "border_color", 0 )
if not border_colorTag then
border_colorTag = xmlCreateChild( settingsFile, "border_color" )
end
local serverinfo_colorTag = xmlFindChild( settingsFile, "serverinfo_color", 0 )
if not serverinfo_colorTag then
serverinfo_colorTag = xmlCreateChild( settingsFile, "serverinfo_color" )
end
local content_colorTag = xmlFindChild( settingsFile, "content_color", 0 )
if not content_colorTag then
content_colorTag = xmlCreateChild( settingsFile, "content_color" )
end
xmlNodeSetValue( useanimationTag, tostring( settingsTable.useanimation ) )
xmlNodeSetValue( toggleableTag, tostring( settingsTable.toggleable ) )
xmlNodeSetValue( showserverinfoTag, tostring( settingsTable.showserverinfo ) )
xmlNodeSetValue( showgamemodeinfoTag, tostring( settingsTable.showgamemodeinfo ) )
xmlNodeSetValue( showteamsTag, tostring( settingsTable.showteams ) )
xmlNodeSetValue( usecolorsTag, tostring( settingsTable.usecolors ) )
xmlNodeSetValue( drawspeedTag, tostring( settingsTable.drawspeed ) )
xmlNodeSetValue( scaleTag, tostring( settingsTable.scale ) )
xmlNodeSetValue( columnfontTag, tostring( settingsTable.columnfont ) )
xmlNodeSetValue( contentfontTag, tostring( settingsTable.contentfont ) )
xmlNodeSetValue( teamfontTag, tostring( settingsTable.teamfont ) )
xmlNodeSetValue( serverinfofontTag, tostring( settingsTable.serverinfofont ) )
xmlNodeSetAttribute( bg_colorTag, "r", tostring( settingsTable.bg_color.r ) )
xmlNodeSetAttribute( bg_colorTag, "g", tostring( settingsTable.bg_color.g ) )
xmlNodeSetAttribute( bg_colorTag, "b", tostring( settingsTable.bg_color.b ) )
xmlNodeSetAttribute( bg_colorTag, "a", tostring( settingsTable.bg_color.a ) )
xmlNodeSetAttribute( selection_colorTag, "r", tostring( settingsTable.selection_color.r ) )
xmlNodeSetAttribute( selection_colorTag, "g", tostring( settingsTable.selection_color.g ) )
xmlNodeSetAttribute( selection_colorTag, "b", tostring( settingsTable.selection_color.b ) )
xmlNodeSetAttribute( selection_colorTag, "a", tostring( settingsTable.selection_color.a ) )
xmlNodeSetAttribute( highlight_colorTag, "r", tostring( settingsTable.highlight_color.r ) )
xmlNodeSetAttribute( highlight_colorTag, "g", tostring( settingsTable.highlight_color.g ) )
xmlNodeSetAttribute( highlight_colorTag, "b", tostring( settingsTable.highlight_color.b ) )
xmlNodeSetAttribute( highlight_colorTag, "a", tostring( settingsTable.highlight_color.a ) )
xmlNodeSetAttribute( header_colorTag, "r", tostring( settingsTable.header_color.r ) )
xmlNodeSetAttribute( header_colorTag, "g", tostring( settingsTable.header_color.g ) )
xmlNodeSetAttribute( header_colorTag, "b", tostring( settingsTable.header_color.b ) )
xmlNodeSetAttribute( header_colorTag, "a", tostring( settingsTable.header_color.a ) )
xmlNodeSetAttribute( team_colorTag, "r", tostring( settingsTable.team_color.r ) )
xmlNodeSetAttribute( team_colorTag, "g", tostring( settingsTable.team_color.g ) )
xmlNodeSetAttribute( team_colorTag, "b", tostring( settingsTable.team_color.b ) )
xmlNodeSetAttribute( team_colorTag, "a", tostring( settingsTable.team_color.a ) )
xmlNodeSetAttribute( border_colorTag, "r", tostring( settingsTable.border_color.r ) )
xmlNodeSetAttribute( border_colorTag, "g", tostring( settingsTable.border_color.g ) )
xmlNodeSetAttribute( border_colorTag, "b", tostring( settingsTable.border_color.b ) )
xmlNodeSetAttribute( border_colorTag, "a", tostring( settingsTable.border_color.a ) )
xmlNodeSetAttribute( serverinfo_colorTag, "r", tostring( settingsTable.serverinfo_color.r ) )
xmlNodeSetAttribute( serverinfo_colorTag, "g", tostring( settingsTable.serverinfo_color.g ) )
xmlNodeSetAttribute( serverinfo_colorTag, "b", tostring( settingsTable.serverinfo_color.b ) )
xmlNodeSetAttribute( serverinfo_colorTag, "a", tostring( settingsTable.serverinfo_color.a ) )
xmlNodeSetAttribute( content_colorTag, "r", tostring( settingsTable.content_color.r ) )
xmlNodeSetAttribute( content_colorTag, "g", tostring( settingsTable.content_color.g ) )
xmlNodeSetAttribute( content_colorTag, "b", tostring( settingsTable.content_color.b ) )
xmlNodeSetAttribute( content_colorTag, "a", tostring( settingsTable.content_color.a ) )
xmlSaveFile( settingsFile )
xmlUnloadFile( settingsFile )
destroyScoreboardSettingsWindow()
readScoreboardSettings()
end
function validateRange( number )
if type( number ) == "number" then
local isValid = number >= 0 and number <= 255
if isValid then
return number
end
end
return false
end
| bsd-2-clause |
Ombridride/minetest-minetestforfun-server | minetestforfun_game/mods/h2omes/init.lua | 7 | 13909 | h2omes = {}
h2omes.homes = {} -- table players home
h2omes.path = minetest.get_worldpath() .. "/h2omes/"
minetest.mkdir(h2omes.path)
h2omes.time_home = 2 * 60 --MFF 04/05/2016 2 minutes plus 20 minutes
h2omes.time_spawn = 5*60
h2omes.time_from_player = 5*60
h2omes.time_to_player = 5*60
local tmp_players = {}
local from_players = {}
h2omes.have_nether = false -- nether mod
if (minetest.get_modpath("nether") ~= nil) then
h2omes.have_nether = true
end
function h2omes.check(name)
if h2omes.homes[name] == nil then
h2omes.homes[name] = {["home"] = {}, ["pit"] = {}}
end
end
--function save_homes
function h2omes.save_homes(name)
local file = h2omes.path..name
local input, err = io.open(file, "w")
if input then
input:write(minetest.serialize(h2omes.homes[name]))
input:close()
else
minetest.log("error", "open(" .. file .. ", 'w') failed: " .. err)
end
end
--function load_homes
function h2omes.load_homes(name)
h2omes.check(name)
local file = h2omes.path..name
local input, err = io.open(file, "r")
if input then
local data = minetest.deserialize(input:read())
io.close(input)
if data and type(data) == "table" then
if data.home then
if data.home.real then
h2omes.homes[name].home.real = data.home.real
end
if data.home.nether then
h2omes.homes[name].home.nether = data.home.nether
end
end
if data.pit then
if data.pit.real then
h2omes.homes[name].pit.real = data.pit.real
end
if data.pit.nether then
h2omes.homes[name].pit.nether = data.pit.nether
end
end
end
end
end
-- disallowed tp real-->nether or nether-->real
function h2omes.can_teleport(from_pos, to_pos)
if not h2omes.have_nether then -- not nether mod, -19600 is real
return true
end
if from_pos.y < -19600 and to_pos.y < -19600 then
return true
elseif from_pos.y > -19600 and to_pos.y > -19600 then
return true
end
return false
end
--function set_homes
function h2omes.set_home(name, home_type, pos)
h2omes.check(name)
if not pos then
local player = minetest.get_player_by_name(name)
if not player then return end
pos = player:getpos()
end
if not pos then return false end
if pos.y < -19600 and h2omes.have_nether then
h2omes.homes[name][home_type].nether = pos
else
h2omes.homes[name][home_type].real = pos
end
minetest.chat_send_player(name, home_type.." set!")
minetest.sound_play("dingdong",{to_player=name, gain = 1.0})
h2omes.save_homes(name)
return true
end
--function get_homes
function h2omes.get_home(name, home_type)
h2omes.check(name)
local player = minetest.get_player_by_name(name)
if not player then return nil end
local pos = player:getpos()
if not pos then return nil end
local status = "real"
if pos.y < -19600 and h2omes.have_nether then
status = "nether"
end
if h2omes.homes[name][home_type][status] then
return h2omes.homes[name][home_type][status]
end
return nil
end
--function getspawn
function h2omes.getspawn(name)
local player = minetest.get_player_by_name(name)
if not player then return nil end
local pos = player:getpos()
if not pos then return nil end
local spawn_pos
if pos.y < -19600 and h2omes.have_nether then
spawn_pos = minetest.string_to_pos(minetest.setting_get("nether_static_spawnpoint") or "")
elseif minetest.setting_get_pos("static_spawnpoint") then
spawn_pos = minetest.setting_get_pos("static_spawnpoint")
end
return spawn_pos
end
--function to_spawn
function h2omes.to_spawn(name)
local player = minetest.get_player_by_name(name)
if not player then return false end
local spawn_pos = h2omes.getspawn(name)
if spawn_pos then
minetest.chat_send_player(name, "Teleporting to spawn...")
player:setpos(spawn_pos)
minetest.sound_play("teleport", {to_player=name, gain = 1.0})
minetest.log("action","Player ".. name .." respawned. Next allowed respawn in ".. h2omes.time_spawn .." seconds.")
return true
else
minetest.chat_send_player(name, "ERROR: No spawn point is set on this server!")
return false
end
end
--function to_homes
function h2omes.to_home(name, home_type)
h2omes.check(name)
local player = minetest.get_player_by_name(name)
if not player then return false end
local pos = player:getpos()
if not pos then return false end
local status = "real"
if pos.y < -19600 and h2omes.have_nether then
status = "nether"
end
if h2omes.homes[name][home_type][status] then
player:setpos(h2omes.homes[name][home_type][status])
minetest.chat_send_player(name, "Teleported to "..home_type.."!")
minetest.sound_play("teleport", {to_player=name, gain = 1.0})
return true
end
return false
end
--function to_player
function h2omes.to_player(name, to_pos, to_name)
local player = minetest.get_player_by_name(name)
if not player then return false end
local from_pos = player:getpos()
if to_pos then
if h2omes.can_teleport(from_pos, to_pos) then
minetest.chat_send_player(name, "Teleporting to player "..to_name)
player:setpos(to_pos)
minetest.sound_play("teleport", {to_player=name, gain = 1.0})
return true
else
minetest.chat_send_player(name, "Sorry, teleport between 2 worlds(real/nether) is not allowed!")
return false
end
else
minetest.chat_send_player(name, "ERROR: No position to player!")
return false
end
end
function h2omes.update_pos(name, pos, from_name)
from_players[name] = {name=from_name, pos=pos}
minetest.chat_send_player(name, from_name .." sent you their position to teleport")
minetest.sound_play("dingdong",{to_player=name, gain = 0.8})
return true
end
function h2omes.send_pos_to_player(name, pos, to_name)
local player = minetest.get_player_by_name(to_name)
if not player or not pos then return false end
if action_timers.wrapper(name, "send_pos_to_player", "from_player_" .. to_name, h2omes.time_from_player, h2omes.update_pos, {to_name, pos, name}) then
minetest.chat_send_player(name, "Your position has been sent to "..to_name)
return true
else
minetest.chat_send_player(name, "Error: "..to_name.." already received a request. please try again later.")
end
return false
end
function h2omes.show_formspec_home(name)
if tmp_players[name] == nil then
tmp_players[name] = {}
end
local player = minetest.get_player_by_name(name)
if not player then return false end
local formspec = {"size[8,9]label[3.15,0;Home Settings]"}
local pos = player:getpos()
--spawn
table.insert(formspec, "label[3.45,0.8;TO SPAWN]")
local spawn_pos = h2omes.getspawn(name)
if spawn_pos then
table.insert(formspec, string.format("label[2.9,1.3;x:%s, y:%s, z:%s]", math.floor(spawn_pos.x), math.floor(spawn_pos.y), math.floor(spawn_pos.z) ))
table.insert(formspec, "button_exit[6,1.1;1.5,1;to_spawn;To Spawn]")
else
table.insert(formspec, "label[3.3,1.3;No spawn set]")
end
--home
table.insert(formspec, "label[3.5,2.1;TO HOME]")
table.insert(formspec, "button[0.5,2.4;1.5,1;set_home;Set Home]")
local home_pos = h2omes.get_home(name, "home")
if home_pos then
table.insert(formspec, string.format("label[2.9,2.5;x:%s, y:%s, z:%s]", math.floor(home_pos.x), math.floor(home_pos.y), math.floor(home_pos.z) ))
table.insert(formspec, "button_exit[6,2.4;1.5,1;to_home;To Home]")
else
table.insert(formspec, "label[3.3,2.5;Home no set]")
end
--pit
table.insert(formspec, "label[3.55,3.4;TO PIT]")
table.insert(formspec, "button[0.5,3.7;1.5,1;set_pit;Set Pit]")
local pit_pos = h2omes.get_home(name, "pit")
if pit_pos then
table.insert(formspec, string.format("label[2.9,3.8;x:%s, y:%s, z:%s]", math.floor(pit_pos.x), math.floor(pit_pos.y), math.floor(pit_pos.z) ))
table.insert(formspec, "button_exit[6,3.7;1.5,1;to_pit;To Pit]")
else
table.insert(formspec, "label[3.3,3.8;Pit no set]")
end
--to player
table.insert(formspec, "label[3.35,4.7;TO PLAYER]")
local to_player = from_players[name]
if to_player and to_player.name and to_player.pos then
table.insert(formspec, string.format("label[0.5,5.1;To %s]", to_player.name))
table.insert(formspec,string.format("label[2.9,5.1;x:%s, y:%s, z:%s]", math.floor(to_player.pos.x),math.floor(to_player.pos.y),math.floor(to_player.pos.z)))
table.insert(formspec, "button_exit[6,5;1.5,1;to_player;To Player]")
else
table.insert(formspec, "label[2.7,5.1;No request from player]")
end
table.insert(formspec, "label[2.8,6;SEND MY POS TO PLAYER]")
if not tmp_players[name] or not tmp_players[name].players_list or #tmp_players[name].players_list < 1 or tmp_players[name].refresh then
tmp_players[name].refresh = nil
tmp_players[name].players_list = {}
tmp_players[name].selected_id = 0
for _,player in pairs(minetest.get_connected_players()) do
local player_name = player:get_player_name()
if player_name and player_name ~= "" and player_name ~= name then
table.insert(tmp_players[name].players_list, player_name)
end
end
tmp_players[name]["select_player"] = nil
end
if #tmp_players[name].players_list == 0 then
table.insert(formspec, "label[3,6.4;No player, try later]")
else
table.insert(formspec,"button[3.5,6.4;1.5,1;refresh;refresh]")
table.insert(formspec, "dropdown[0.5,6.5;3,1;select_player;"..table.concat(tmp_players[name].players_list, ",")..";"..tmp_players[name].selected_id.."]")
end
if tmp_players[name].selected_id and tmp_players[name].selected_id > 0 then
table.insert(formspec, "button_exit[6,6.4;1.5,1;send_to;Send To]")
end
table.insert(formspec, "button_exit[3.25,8.3;1.5,1;close;Close]")
minetest.show_formspec(name, "h2omes:formspec", table.concat(formspec))
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
local name = player:get_player_name()
if not name or name == "" then return end
if formname == "h2omes:formspec" then
if fields["set_home"] then
--h2omes.set_home(name, "home")
action_timers.wrapper(name, "sethome", "sethome_" .. name, h2omes.time_home, h2omes.set_home, {name, "home"})
elseif fields["set_pit"] then
--h2omes.set_home(name, "pit")
action_timers.wrapper(name, "setpit", "sethome_" .. name, h2omes.time_home, h2omes.set_home, {name, "pit"})
elseif fields["to_home"] then
--h2omes.to_home(name, "home")
action_timers.wrapper(name, "home", "tohome_" .. name, h2omes.time_home, h2omes.to_home, {name, "home"})
elseif fields["to_pit"] then
--h2omes.to_home(name, "pit")
action_timers.wrapper(name, "pit", "tohome_" .. name, h2omes.time_home, h2omes.to_home, {name, "pit"})
elseif fields["to_spawn"] then
action_timers.wrapper(name, "spawn", "tospawn_" .. name, h2omes.time_spawn, h2omes.to_spawn, {name})
elseif fields["to_player"] then
if not from_players[name] then return end
local to_name = from_players[name].name
local pos = from_players[name].pos
from_players[name] = nil
if not to_name or not pos then return end
h2omes.to_player(name, pos, to_name)
elseif fields["send_to"] then
local to_name = tmp_players[name]["select_player"]
if not to_name then return end
local pos = player:getpos()
action_timers.wrapper(name, "send_pos_to_player", "to_player_" .. name, h2omes.time_to_player, h2omes.send_pos_to_player, {name, pos, to_name})
tmp_players[name] = nil
elseif fields["refresh"] then
tmp_players[name].refresh = true
elseif fields["select_player"] then
for i, n in pairs(tmp_players[name].players_list) do
if n == fields["select_player"] then
tmp_players[name]["select_player"] = fields["select_player"]
tmp_players[name].selected_id = i
break
end
end
end
if not fields["quit"] then
h2omes.show_formspec_home(name)
end
end
end)
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
if not name or name == "" then return end
h2omes.load_homes(name)
end)
minetest.register_on_leaveplayer(function(player)
local name = player:get_player_name()
if not name or name == "" then return end
h2omes.homes[name] = nil
tmp_players[name] = nil
from_players[name] = nil
end)
minetest.register_privilege("home", "Can use /sethome, /home, /setpit and /pit")
minetest.register_chatcommand("spawn", {
description = "Teleport a player to the defined spawnpoint",
func = function(name)
local spawn_pos = h2omes.getspawn(name)
if spawn_pos then
action_timers.wrapper(name, "spawn", "tospawn_" .. name, h2omes.time_spawn, h2omes.to_spawn, {name})
else
minetest.chat_send_player(name, "ERROR: No spawn point is set on this server!")
return false
end
end
})
minetest.register_chatcommand("home", {
description = "Teleport you to your home point",
privs = {home=true},
func = function (name, params)
if not h2omes.get_home(name, "home") then
minetest.chat_send_player(name, "Set a home using /sethome")
return false
end
--h2omes.to_home(name, "home")
return action_timers.wrapper(name, "home", "tohome_" .. name, h2omes.time_home, h2omes.to_home, {name, "home"})
end,
})
minetest.register_chatcommand("sethome", {
description = "Set your home point",
privs = {home=true},
func = function (name, params)
--h2omes.set_home(name, "home")
return action_timers.wrapper(name, "sethome", "sethome_" .. name, h2omes.time_home, h2omes.set_home, {name, "home"})
end,
})
minetest.register_chatcommand("pit", {
description = "Teleport you to your pit point",
privs = {home=true},
func = function (name, params)
if not h2omes.get_home(name, "pit") then
minetest.chat_send_player(name, "Set a pit using /setpit")
return false
end
--h2omes.to_home(name, "pit")
return action_timers.wrapper(name, "pit", "tohome_" .. name, h2omes.time_home, h2omes.to_home, {name, "pit"})
end,
})
minetest.register_chatcommand("setpit", {
description = "Set your pit point",
privs = {home=true},
func = function (name, params)
--h2omes.set_home(name, "pit")
return action_timers.wrapper(name, "setpit", "sethome_" .. name, h2omes.time_home, h2omes.set_home, {name, "pit"})
end,
})
minetest.log("action","[h2omes] Loaded.")
| unlicense |
Ombridride/minetest-minetestforfun-server | mods/homedecor_modpack/homedecor/bathroom_furniture.lua | 13 | 3016 | local S = homedecor.gettext
local bathroom_tile_colors = {
{ "1", "white/grey", "#c0c0c0:200" },
{ "2", "white/dark grey", "#404040:150" },
{ "3", "white/black", "#000000:200" },
{ "4", "black/dark grey", "" },
{ "red", "white/red", "#d00000:150" },
{ "green", "white/green", "#00d000:150" },
{ "blue", "white/blue", "#0000d0:150" },
{ "yellow", "white/yellow", "#ffff00:150" },
{ "tan", "white/tan", "#ceaf42:150" }
}
for i in ipairs(bathroom_tile_colors) do
local color = bathroom_tile_colors[i][1]
local shade = bathroom_tile_colors[i][2]
local hue = bathroom_tile_colors[i][3]
local coloredtile = "homedecor_bathroom_tiles_bg.png^(homedecor_bathroom_tiles_fg.png^[colorize:"..hue..")"
if color == "4" then
coloredtile = "(homedecor_bathroom_tiles_bg.png^[colorize:#000000:75)"..
"^(homedecor_bathroom_tiles_fg.png^[colorize:#000000:200)"
end
minetest.register_node("homedecor:tiles_"..color, {
description = "Bathroom/kitchen tiles ("..shade..")",
tiles = {
coloredtile,
coloredtile,
coloredtile,
coloredtile,
"("..coloredtile..")^[transformR90",
"("..coloredtile..")^[transformR90"
},
groups = {cracky=3},
paramtype = "light",
sounds = default.node_sound_stone_defaults(),
})
end
local tr_cbox = {
type = "fixed",
fixed = { -0.375, -0.3125, 0.25, 0.375, 0.375, 0.5 }
}
homedecor.register("towel_rod", {
description = "Towel rod with towel",
mesh = "homedecor_towel_rod.obj",
tiles = {
"homedecor_generic_terrycloth.png",
"default_wood.png",
},
inventory_image = "homedecor_towel_rod_inv.png",
selection_box = tr_cbox,
walkable = false,
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3},
sounds = default.node_sound_defaults(),
})
homedecor.register("medicine_cabinet", {
description = S("Medicine Cabinet"),
mesh = "homedecor_medicine_cabinet.obj",
tiles = {
'default_wood.png',
'homedecor_medicine_cabinet_mirror.png'
},
inventory_image = "homedecor_medicine_cabinet_inv.png",
selection_box = {
type = "fixed",
fixed = {-0.3125, -0.1875, 0.3125, 0.3125, 0.5, 0.5}
},
walkable = false,
groups = { snappy = 3 },
sounds = default.node_sound_wood_defaults(),
on_punch = function(pos, node, puncher, pointed_thing)
node.name = "homedecor:medicine_cabinet_open"
minetest.swap_node(pos, node)
end,
infotext=S("Medicine cabinet"),
inventory = {
size=6,
},
})
homedecor.register("medicine_cabinet_open", {
mesh = "homedecor_medicine_cabinet_open.obj",
tiles = {
'default_wood.png',
'homedecor_medicine_cabinet_mirror.png',
'homedecor_medicine_cabinet_inside.png'
},
selection_box = {
type = "fixed",
fixed = {-0.3125, -0.1875, -0.25, 0.3125, 0.5, 0.5}
},
walkable = false,
groups = { snappy = 3, not_in_creative_inventory=1 },
drop = "homedecor:medicine_cabinet",
on_punch = function(pos, node, puncher, pointed_thing)
node.name = "homedecor:medicine_cabinet"
minetest.swap_node(pos, node)
end,
})
| unlicense |
jshackley/darkstar | scripts/zones/Quicksand_Caves/npcs/_5sb.lua | 17 | 1273 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -420 0 735 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()-(-420);
local difZ = player:getZPos()-(726);
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 |
LuaDist/lua-uri | test/file.lua | 1 | 5952 | require "uri-test"
local URI = require "uri"
local URIFile = require "uri.file"
local testcase = TestCase("Test uri.file")
function testcase:test_normalize ()
test_norm("file:///foo", "file://LocalHost/foo")
test_norm("file:///", "file://localhost/")
test_norm("file:///", "file://localhost")
test_norm("file:///", "file://")
test_norm("file:///", "file:/")
test_norm("file:///foo", "file:/foo")
test_norm("file://foo/", "file://foo")
end
function testcase:test_invalid ()
is_bad_uri("just scheme", "file:")
is_bad_uri("scheme with relative path", "file:foo/bar")
end
function testcase:test_set_host ()
local uri = assert(URI:new("file:///foo"))
is("", uri:host())
is("", uri:host("LocalHost"))
is("file:///foo", tostring(uri))
is("", uri:host("host.name"))
is("file://host.name/foo", tostring(uri))
is("host.name", uri:host(""))
is("file:///foo", tostring(uri))
end
function testcase:test_set_path ()
local uri = assert(URI:new("file:///foo"))
is("/foo", uri:path())
is("/foo", uri:path(nil))
is("file:///", tostring(uri))
is("/", uri:path(""))
is("file:///", tostring(uri))
is("/", uri:path("/bar/frob"))
is("file:///bar/frob", tostring(uri))
is("/bar/frob", uri:path("/"))
is("file:///", tostring(uri))
end
function testcase:test_bad_usage ()
local uri = assert(URI:new("file:///foo"))
assert_error("nil host", function () uri:host(nil) end)
assert_error("set userinfo", function () uri:userinfo("foo") end)
assert_error("set port", function () uri:userinfo(23) end)
assert_error("set relative path", function () uri:userinfo("foo/") end)
end
local function uri_to_fs (os, uristr, expected)
local uri = assert(URI:new(uristr))
is(expected, uri:filesystem_path(os))
end
local function fs_to_uri (os, path, expected)
is(expected, tostring(URIFile.make_file_uri(path, os)))
end
function testcase:test_uri_to_fs_unix ()
uri_to_fs("unix", "file:///", "/")
uri_to_fs("unix", "file:///c:", "/c:")
uri_to_fs("unix", "file:///C:/", "/C:/")
uri_to_fs("unix", "file:///C:/Program%20Files", "/C:/Program Files")
uri_to_fs("unix", "file:///C:/Program%20Files/", "/C:/Program Files/")
uri_to_fs("unix", "file:///Program%20Files/", "/Program Files/")
end
function testcase:test_uri_to_fs_unix_bad ()
-- On Unix platforms, there's no equivalent of UNC paths.
local uri = assert(URI:new("file://laptop/My%20Documents/FileSchemeURIs.doc"))
assert_error("Unix path with host name",
function () uri:filesystem_path("unix") end)
-- Unix paths can't contain null bytes or encoded slashes.
uri = assert(URI:new("file:///frob/foo%00bar/quux"))
assert_error("Unix path with null byte",
function () uri:filesystem_path("unix") end)
uri = assert(URI:new("file:///frob/foo%2Fbar/quux"))
assert_error("Unix path with encoded slash",
function () uri:filesystem_path("unix") end)
end
function testcase:test_fs_to_uri_unix ()
fs_to_uri("unix", "/", "file:///")
fs_to_uri("unix", "//", "file:///")
fs_to_uri("unix", "///", "file:///")
fs_to_uri("unix", "/foo/bar", "file:///foo/bar")
fs_to_uri("unix", "/foo/bar/", "file:///foo/bar/")
fs_to_uri("unix", "//foo///bar//", "file:///foo/bar/")
fs_to_uri("unix", "/foo bar/%2F", "file:///foo%20bar/%252F")
end
function testcase:test_fs_to_uri_unix_bad ()
-- Relative paths can't be converted to URIs, because URIs are inherently
-- absolute.
assert_error("relative Unix path",
function () FileURI.make_file_uri("foo/bar", "unix") end)
assert_error("relative empty Unix path",
function () FileURI.make_file_uri("", "unix") end)
end
function testcase:test_uri_to_fs_win32 ()
uri_to_fs("win32", "file:///", "\\")
uri_to_fs("win32", "file:///c:", "c:\\")
uri_to_fs("win32", "file:///C:/", "C:\\")
uri_to_fs("win32", "file:///C:/Program%20Files", "C:\\Program Files")
uri_to_fs("win32", "file:///C:/Program%20Files/", "C:\\Program Files\\")
uri_to_fs("win32", "file:///Program%20Files/", "\\Program Files\\")
-- http://blogs.msdn.com/ie/archive/2006/12/06/file-uris-in-windows.aspx
uri_to_fs("win32", "file://laptop/My%20Documents/FileSchemeURIs.doc",
"\\\\laptop\\My Documents\\FileSchemeURIs.doc")
uri_to_fs("win32",
"file:///C:/Documents%20and%20Settings/davris/FileSchemeURIs.doc",
"C:\\Documents and Settings\\davris\\FileSchemeURIs.doc")
-- For backwards compatibility with deprecated way of indicating drives.
uri_to_fs("win32", "file:///c%7C", "c:\\")
uri_to_fs("win32", "file:///c%7C/", "c:\\")
uri_to_fs("win32", "file:///C%7C/foo/", "C:\\foo\\")
end
function testcase:test_fs_to_uri_win32 ()
fs_to_uri("win32", "", "file:///")
fs_to_uri("win32", "\\", "file:///")
fs_to_uri("win32", "c:", "file:///c:/")
fs_to_uri("win32", "C:\\", "file:///C:/")
fs_to_uri("win32", "C:/", "file:///C:/")
fs_to_uri("win32", "C:\\Program Files", "file:///C:/Program%20Files")
fs_to_uri("win32", "C:\\Program Files\\", "file:///C:/Program%20Files/")
fs_to_uri("win32", "C:/Program Files/", "file:///C:/Program%20Files/")
fs_to_uri("win32", "\\Program Files\\", "file:///Program%20Files/")
fs_to_uri("win32", "\\\\laptop\\My Documents\\FileSchemeURIs.doc",
"file://laptop/My%20Documents/FileSchemeURIs.doc")
fs_to_uri("win32", "c:\\foo bar\\%2F", "file:///c:/foo%20bar/%252F")
end
function testcase:test_convert_on_unknown_os ()
local uri = assert(URI:new("file:///foo"))
assert_error("filesystem_path, unknown os",
function () uri:filesystem_path("NonExistent") end)
assert_error("make_file_uri, unknown os",
function () URIFile.make_file_uri("/foo", "NonExistent") end)
end
lunit.run()
-- vi:ts=4 sw=4 expandtab
| mit |
jshackley/darkstar | scripts/zones/Windurst_Woods/npcs/Cha_Lebagta.lua | 19 | 1938 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Cha Lebagta
-- Type: Standard NPC
-- @zone: 241
-- @pos 58.385 -6.249 216.670
-- Involved in Quests: As Thick as Thieves, Mihgo's Amigo
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
MihgosAmigo = player:getQuestStatus(WINDURST,MIHGO_S_AMIGO);
thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES);
thickAsThievesCS = player:getVar("thickAsThievesCS");
-- As Thick As Thieves (THF AF)
if (thickAsThieves == QUEST_ACCEPTED) then
player:startEvent(0x01FB,0,17474);
if (thickAsThievesCS == 1) then
player:setVar("thickAsThievesCS",3);
elseif (thickAsThievesCS == 2) then
player:setVar("thickAsThievesCS",4);
rand1 = math.random(2,7);
player:setVar("thickAsThievesGrapplingCS",rand1);
player:setVar("thickAsThievesGamblingCS",1);
end
-- Mihgo's Amigo
elseif (MihgosAmigo == QUEST_ACCEPTED) then
player:startEvent(0x0055,0,498); -- hint dialog
-- standard dialog
elseif (MihgosAmigo == QUEST_COMPLETED) then
player:startEvent(0x005B,0,498) -- new standard dialog after Mihgo's Amigo
else
player:startEvent(0x004e); -- normal dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Sacrarium/npcs/qm6.lua | 17 | 1739 | -----------------------------------
-- Area: Sacrarium
-- NPC: qm6 (???)
-- Notes: Used to spawn Old Prof. Mariselle
-- @pos 62.668 -3.111 -127.310 28
-----------------------------------
package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sacrarium/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OldProfessor = 16891970;
if (GetServerVariable("Old_Prof_Spawn_Location") == 6) then
if (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 3 and player:hasKeyItem(RELIQUIARIUM_KEY)==false and GetMobAction(OldProfessor) == 0) then
player:messageSpecial(EVIL_PRESENCE);
SpawnMob(OldProfessor,300):updateClaim(player);
GetMobByID(OldProfessor):setPos(npc:getXPos()+1, npc:getYPos(), npc:getZPos()+1); -- Set Prof. spawn x and z pos. +1 from NPC
else
player:messageSpecial(DRAWER_SHUT);
end
elseif (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 4 and player:hasKeyItem(RELIQUIARIUM_KEY)==false) then
player:addKeyItem(RELIQUIARIUM_KEY);
player:messageSpecial(KEYITEM_OBTAINED,RELIQUIARIUM_KEY);
else
player:messageSpecial(DRAWER_OPEN);
player:messageSpecial(DRAWER_EMPTY);
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
Shrike78/Shilke2D | Samples/BlendModes/blendDrawables.lua | 1 | 3135 | __DEBUG_CALLBACKS__ = true
--__USE_SIMULATION_COORDS__ = true
require("Shilke2D/include")
IO.setWorkingDir("Assets/BlendModes")
local WIDTH,HEIGHT = 1024,768
local FPS = 60
local blendModes = BlendMode.getRegisteredModes(true)
local blendModeIdx = 1
local infoTxt
local fgLayer
local QuadDrawObj = class(DrawableObj)
function QuadDrawObj:init(w,h,color)
DrawableObj.init(self)
self._w = w
self._h = h
self._c = color
end
function QuadDrawObj:getRect(resultRect)
local r = Rect() or resultRect
r:set(0,0,self._w, self._h)
return r
end
function QuadDrawObj:_innerDraw()
self:setPenColor(self._c)
Graphics.fillRect(0,0,self._w,self._h)
end
function createSample(bkgLayer, fgLayer, color, pma, description, pivotMode, posX, posY)
--scale objects
local s = .8
local qback = Quad(400,400, pivotMode)
qback:setColor(0,150,200)
qback:setPosition(posX, posY)
qback:setScale(s,s)
bkgLayer:addChild(qback)
local bkw, bkh = qback:getSize(bkgLayer)
local q = QuadDrawObj(200,200, color)
q:setScale(s,s)
fgLayer:addChild(q)
local qw, qh = q:getSize(fgLayer)
local px = posX == 0 and bkw/2 - qw/2 or WIDTH - bkw/2 - qw/2
local py = posY == 0 and bkh/2 - qh/2 or HEIGHT - bkh/2 - qh/2
q:setPosition(px, py)
q:setPremultipliedAlpha(pma)
local txt = TextField(300, 30, description, nil, 12, pivotMode)
px = posX == 0 and 0 or WIDTH
py = posY == 0 and bkh or HEIGHT - bkh
txt:setPosition(px, py)
txt:setHAlignment(TextField.CENTER_JUSTIFY)
bkgLayer:addChild(txt)
end
function setup()
Shilke2D.current:showStats(true)
stage = Shilke2D.current.stage
local bkgLayer = DisplayObjContainer()
fgLayer = DisplayObjContainer()
stage:addChild(bkgLayer)
stage:addChild(fgLayer)
createSample(bkgLayer, fgLayer, Color(255,255,255,128), false,
"straight white (a=128)", PivotMode.TOP_LEFT, 0, 0)
createSample(bkgLayer, fgLayer, Color(255,255,255,128), true,
"pma white (a=128)", PivotMode.TOP_RIGHT, WIDTH, 0)
createSample(bkgLayer, fgLayer, Color(0,0,0,128), false,
"straight black (a=128)", PivotMode.BOTTOM_LEFT, 0, HEIGHT)
createSample(bkgLayer, fgLayer, Color(0,0,0,128), true,
"pma black (a=128)", PivotMode.BOTTOM_RIGHT, WIDTH, HEIGHT)
infoTxt = TextField(500, 30, "Press A/Z to switch blend mode: " .. blendModes[blendModeIdx], nil, 20, PivotMode.CENTER)
infoTxt:setPosition(WIDTH/2, HEIGHT/2)
infoTxt:setAlignment(TextField.CENTER_JUSTIFY, TextField.CENTER_JUSTIFY)
stage:addChild(infoTxt)
end
function update()
end
function touched(touch)
end
function updateBlendMode()
local bmName = blendModes[blendModeIdx]
infoTxt:setText("Press A/Z to switch blend mode: " .. bmName)
for obj in children(fgLayer) do
obj:setBlendMode(bmName)
end
end
function onKeyboardEvent(key, down)
if down then
if key == KEY('z') or key == KEY('Z') then
blendModeIdx = blendModeIdx ~= 1 and (blendModeIdx - 1) or #blendModes
updateBlendMode()
elseif key == KEY('a') or key == KEY('A') then
blendModeIdx = (blendModeIdx ~= #blendModes) and (blendModeIdx + 1) or 1
updateBlendMode()
end
end
end
shilke2D = Shilke2D(WIDTH,HEIGHT,FPS)
shilke2D:start()
| mit |
jshackley/darkstar | scripts/globals/weaponskills/shark_bite.lua | 30 | 1459 | -----------------------------------
-- Shark Bite
-- Dagger weapon skill
-- Skill level: 225
-- Delivers a twofold attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Will stack with Trick Attack.
-- Aligned with the Breeze Gorget & Thunder Gorget.
-- Aligned with the Breeze Belt & Thunder Belt.
-- Element: None
-- Modifiers: DEX:40% AGI:40%
-- 100%TP 200%TP 300%TP
-- 2.00 4 5.75
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 2;
params.ftp100 = 2; params.ftp200 = 2.5; params.ftp300 = 3;
params.str_wsc = 0.0; params.dex_wsc = 0.5; 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.ftp200 = 4; params.ftp300 = 5.75;
params.dex_wsc = 0.4; params.agi_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
rmhartog/thrift | lib/lua/TProtocol.lua | 98 | 5119 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'Thrift'
TProtocolException = TException:new {
UNKNOWN = 0,
INVALID_DATA = 1,
NEGATIVE_SIZE = 2,
SIZE_LIMIT = 3,
BAD_VERSION = 4,
INVALID_PROTOCOL = 5,
DEPTH_LIMIT = 6,
errorCode = 0,
__type = 'TProtocolException'
}
function TProtocolException:__errorCodeToString()
if self.errorCode == self.INVALID_DATA then
return 'Invalid data'
elseif self.errorCode == self.NEGATIVE_SIZE then
return 'Negative size'
elseif self.errorCode == self.SIZE_LIMIT then
return 'Size limit'
elseif self.errorCode == self.BAD_VERSION then
return 'Bad version'
elseif self.errorCode == self.INVALID_PROTOCOL then
return 'Invalid protocol'
elseif self.errorCode == self.DEPTH_LIMIT then
return 'Exceeded size limit'
else
return 'Default (unknown)'
end
end
TProtocolBase = __TObject:new{
__type = 'TProtocolBase',
trans
}
function TProtocolBase:new(obj)
if ttype(obj) ~= 'table' then
error(ttype(self) .. 'must be initialized with a table')
end
-- Ensure a transport is provided
if not obj.trans then
error('You must provide ' .. ttype(self) .. ' with a trans')
end
return __TObject.new(self, obj)
end
function TProtocolBase:writeMessageBegin(name, ttype, seqid) end
function TProtocolBase:writeMessageEnd() end
function TProtocolBase:writeStructBegin(name) end
function TProtocolBase:writeStructEnd() end
function TProtocolBase:writeFieldBegin(name, ttype, id) end
function TProtocolBase:writeFieldEnd() end
function TProtocolBase:writeFieldStop() end
function TProtocolBase:writeMapBegin(ktype, vtype, size) end
function TProtocolBase:writeMapEnd() end
function TProtocolBase:writeListBegin(ttype, size) end
function TProtocolBase:writeListEnd() end
function TProtocolBase:writeSetBegin(ttype, size) end
function TProtocolBase:writeSetEnd() end
function TProtocolBase:writeBool(bool) end
function TProtocolBase:writeByte(byte) end
function TProtocolBase:writeI16(i16) end
function TProtocolBase:writeI32(i32) end
function TProtocolBase:writeI64(i64) end
function TProtocolBase:writeDouble(dub) end
function TProtocolBase:writeString(str) end
function TProtocolBase:readMessageBegin() end
function TProtocolBase:readMessageEnd() end
function TProtocolBase:readStructBegin() end
function TProtocolBase:readStructEnd() end
function TProtocolBase:readFieldBegin() end
function TProtocolBase:readFieldEnd() end
function TProtocolBase:readMapBegin() end
function TProtocolBase:readMapEnd() end
function TProtocolBase:readListBegin() end
function TProtocolBase:readListEnd() end
function TProtocolBase:readSetBegin() end
function TProtocolBase:readSetEnd() end
function TProtocolBase:readBool() end
function TProtocolBase:readByte() end
function TProtocolBase:readI16() end
function TProtocolBase:readI32() end
function TProtocolBase:readI64() end
function TProtocolBase:readDouble() end
function TProtocolBase:readString() end
function TProtocolBase:skip(ttype)
if type == TType.STOP then
return
elseif ttype == TType.BOOL then
self:readBool()
elseif ttype == TType.BYTE then
self:readByte()
elseif ttype == TType.I16 then
self:readI16()
elseif ttype == TType.I32 then
self:readI32()
elseif ttype == TType.I64 then
self:readI64()
elseif ttype == TType.DOUBLE then
self:readDouble()
elseif ttype == TType.STRING then
self:readString()
elseif ttype == TType.STRUCT then
local name = self:readStructBegin()
while true do
local name, ttype, id = self:readFieldBegin()
if ttype == TType.STOP then
break
end
self:skip(ttype)
self:readFieldEnd()
end
self:readStructEnd()
elseif ttype == TType.MAP then
local kttype, vttype, size = self:readMapBegin()
for i = 1, size, 1 do
self:skip(kttype)
self:skip(vttype)
end
self:readMapEnd()
elseif ttype == TType.SET then
local ettype, size = self:readSetBegin()
for i = 1, size, 1 do
self:skip(ettype)
end
self:readSetEnd()
elseif ttype == TType.LIST then
local ettype, size = self:readListBegin()
for i = 1, size, 1 do
self:skip(ettype)
end
self:readListEnd()
end
end
TProtocolFactory = __TObject:new{
__type = 'TProtocolFactory',
}
function TProtocolFactory:getProtocol(trans) end
| apache-2.0 |
jshackley/darkstar | scripts/zones/Den_of_Rancor/npcs/Grounds_Tome.lua | 34 | 1136 | -----------------------------------
-- Area: Den of Rancor
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_DEN_OF_RANCOR,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,796,797,798,799,800,801,802,803,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,796,797,798,799,800,801,802,803,0,0,GOV_MSG_DEN_OF_RANCOR);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/weaponskills/shining_strike.lua | 30 | 1314 | -----------------------------------
-- Shining Strike
-- Club weapon skill
-- Skill level: 5
-- Deals light elemental damage to enemy. Damage varies with TP.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: None
-- Modifiers: STR:40% ; MND:40%
-- 100%TP 200%TP 300%TP
-- 1.625 3 4.625
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 1; params.ftp200 = 1.75; params.ftp300 = 2.5;
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.2; params.chr_wsc = 0.0;
params.ele = ELE_LIGHT;
params.skill = SKILL_CLB;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.625; params.ftp200 = 3; params.ftp300 = 4.625;
params.str_wsc = 0.4; params.mnd_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
slanska/flexilite | src_lua/PropertyDef.lua | 1 | 46661 | ---
--- Created by slanska.
--- DateTime: 2017-10-31 3:18 PM
---
--[[
Property definition
Keeps name, id, reference to class definition
Provides API for property definition validation, type change etc
Notes:
======
* PropertyDef is the base class for family of inherited classes
* PropertyDef has ClassDef to refer to the class-owner
* Concrete property class is determined by rules.type attribute
* Property gets created a) from class definition and db row (already initialized and validated)
or b) from JSON parsed to Lua table
* After creation, initRefs is called to set correct metatables for name/class/prop references
* isValidDef is used for self check - whether property definition is correct and complete
* isValidData is used for data validation, according to property rules
* meta attribute is used as-is. This is user defined data
* applyDef calculates ctlv flags and calls resolve for name/class/prop references. This will lead
to finding classes/properties/creating names etc. applyDefs is called after changes to class/property
definition
* canChangeTo checks if property definition can be changed. Result is 'yes' (upgrade), 'no' and
'maybe' (existing data need to be validated)
* import loads data from Lua table
* export return Lua table without internal properties and metatables
Flow for create class/property:
* set property metatable based on type
* initMetadataRefs - set metatable to metadata refs
* isValidDef - check if referenced properties exist etc
* applyDef - sets ctlv, ctlvPlan, create names, enum classes, reversed props
* saveToDB - inserts/updates .name_props table etc.
Flow for alter class/property:
* set new property metatable based on type
* initMetadataRefs - set metatable to metadata refs
* isValidDef - check if referenced properties exist etc
* canChangeTo - for alter operations
* if 'maybe' for at least one property - scan data, check isValidData
* applyDef (if alteration is OK)
* saveToDB
* ClassDef.rebuildIndexes - if new ctlv ~= old ctlv
For resolve class:
* load from db, set new property metatable based on type
* initMetadataRefs - set metatable to metadata refs
* if all refs are resolved, class is marked as resolved
]]
require 'math'
local class = require 'pl.class'
local tablex = require 'pl.tablex'
local schema = require 'schema'
local bit = type(jit) == 'table' and require('bit') or require('bit32')
local name_ref = require 'NameRef'
local NameRef, ClassNameRef, PropNameRef = name_ref.NameRef, name_ref.ClassNameRef, name_ref.PropNameRef
local Constants = require 'Constants'
local AccessControl = require 'AccessControl'
local dbprops = require 'DBProperty'
local parseDateTimeToJulian = require('Util').parseDateTimeToJulian
local stringifyDateTimeInfo = require('Util').stringifyDateTimeInfo
local base64 = require 'base64'
local generateRelView = require('flexi_rel_vtable').generateView
local bit52 = require('Util').bit52
local tonumber = _G.tonumber
local string = _G.string
--[[
===============================================================================
PropertyDef
===============================================================================
]]
-- TODO Define classes to rules, enumDef, refDef etc.
---@class PropertyRules
---@field type string
---@field maxLength number
---@field maxOccurrences number
---@field minOccurrences number
---@field maxValue number
---@field minValue number
---@class PropertyEnumDef
---@field items table @comment EnumItemDef[]
---@class PropertyRefDef
---@field classRef ClassNameRef
---@field reverseProperty PropNameRef
---@field autoFetchLimit number
---@field autoFetchDepth number
---@field mixin boolean
---@field viewName string @comment optional name of view for many-to-many relationship
---@field viewColName string @comment optional name of corresponding column in many-to-many view
---@field reversedPropViewColName string @comment optional name of corresponding column in many-to-many view
---@class PropertyDefData
---@field rules PropertyRules
---@field enumDef PropertyEnumDef
---@field refDef PropertyRefDef
---@field accessRules table
---@field indexing string
---@field defaultValue any
---@class PropertyDefCtorParams
---@field ClassDef ClassDef
---@field newPropertyName string
---@field jsonData PropertyDefData
---@field dbrow table @comment [flexi_prop] structure
---@class PropertyDefCapabilities
---@field vtype string
---@field canBeUsedAsUDID boolean
---@field columnMappingSupported boolean
---@field supportsRangeIndexing boolean
---@field nativeType string
---@field supportedIndexTypes number
---@class PropertyDef
---@field ID number
---@field ClassDef ClassDef
---@field D PropertyDefData @comment parsed property definition JSON
---@field Name NameRef
---@field ctlv number
---@field ctlvPlan number
---@field Deleted boolean
---@field ColMap string
---@field NonNullCount number
---@field SearchHitCount number
local PropertyDef = class()
-- Factory method to create a property object based on rules.type in params.jsonData
---@param params PropertyDefCtorParams @comment 2 variants:
---for new property (not stored in DB) {ClassDef: ClassDef, newPropertyName:string, jsonData: table}
---for existing property (when loading from DB): {ClassDef: ClassDef, dbrow: table, jsonData: table}
function PropertyDef.CreateInstance(params)
local typeLowered = string.lower(params.jsonData.rules.type)
local propCtor = PropertyDef.PropertyTypes[typeLowered]
if not propCtor then
error(('Unknown type %s of property [%s]'):format(typeLowered, params.newPropertyName))
end
return propCtor(params)
end
-- PropertyDef constructor
---@param params PropertyDefCtorParams @comment 2 variants:
---for new property (not stored in DB) {ClassDef: ClassDef, newPropertyName:string, jsonData: table}
---for existing property (when loading from DB): {ClassDef: ClassDef, dbrow: table, jsonData: table}
function PropertyDef:_init(params)
assert(params.ClassDef)
assert(params.jsonData and params.jsonData.rules and params.jsonData.rules.type)
---@type ClassDef
self.ClassDef = params.ClassDef
self.D = params.jsonData
if params.newPropertyName then
-- New property, no row in database, no resolved name IDs
---@type NameRef
self.Name = NameRef(params.newPropertyName)
self:initMetadataRefs()
self.ctlvPlan = 0
else
assert(params.dbrow)
assert(params.jsonData)
self.Name = NameRef(params.dbrow.Property, params.dbrow.NameID)
-- Copy property attributes
---@type number
self.ID = params.dbrow.PropertyID
self.ctlv = params.dbrow.ctlv or 0
self.ctlvPlan = params.dbrow.ctlvPlan or 0
self.Deleted = params.dbrow.Deleted or false
self.ColMap = params.dbrow.ColMap
self.NonNullCount = params.dbrow.NonNullCount or 0
self.SearchHitCount = params.dbrow.SearchHitCount or 0
self.ClassDef.DBContext.ClassProps[self.ID] = self
end
end
function PropertyDef:initMetadataRefs()
-- Do nothing
end
function PropertyDef:ColumnMappingSupported()
return true
end
-- true if property value can be used as user defined ID (UID)
function PropertyDef:CanBeUsedAsUID()
return true
end
function PropertyDef:supportsRangeIndexing()
return false
end
-- Definite 'yes' is returned when a) propA.canChangeTo(propB) returned 'yes' and b) property types are compatible
-- and c) minOccurrences and maxOccurrences do not shrink
-- Definite 'no' is returned when propA does not support type change to propB or propA.canChangeTo(propB) returned 'no'
--- @param another PropertyDef
--- @return string
-- 'yes', 'no', 'maybe' (=existing data validation needed)
function PropertyDef:canAlterDefinition(newDef)
assert(newDef)
local result = 'yes'
-- compare minOccurrences and maxOccurences to get preliminary verdict
if self.D.rules.minOccurrences or 0 < newDef.D.rules.minOccurrences or 0 then
result = 'maybe'
elseif self.D.rules.maxOccurrences or 0 < newDef.D.rules.maxOccurrences or 0 then
result = 'maybe'
end
return result
end
---@return number @comment property ID
function PropertyDef:saveToDB()
assert(self.ClassDef and self.ClassDef.DBContext)
assert(self.Name and self.Name:isResolved(),
string.format('Name of property %s is not resolved', self:debugDesc()))
-- Set ctlv
self.ctlv = self:GetCTLV()
if self.ID and tonumber(self.ID) > 0 then
-- Update existing
self.ClassDef.DBContext:execStatement([[update [.class_props]
set NameID = :nameID, ctlv = :ctlv, ctlvPlan = :ctlvPlan, ColMap = :ColMap
where ID = :id]],
{
nameID = self.Name.id,
ctlv = self.ctlv,
ctlvPlan = self.ctlvPlan,
ColMap = self.ColMap,
id = self.ID
})
else
-- Insert new
self.ClassDef.DBContext:execStatement(
[[insert into [.class_props] (ClassID, NameID, ctlv, ctlvPlan, ColMap)
values (:ClassID, :NameID, :ctlv, :ctlvPlan, :ColMap);]], {
ClassID = self.ClassDef.ClassID,
NameID = self.Name.id,
ctlv = self.ctlv,
ctlvPlan = self.ctlvPlan,
ColMap = self.ColMap
})
self.ID = self.ClassDef.DBContext.db:last_insert_rowid()
-- As property ID is now known, register property in DBContext property collection
self.ClassDef.DBContext.ClassProps[self.ID] = self
end
return self.ID
end
--- @return table @comment User friendly JSON-ready table with all public properties.
-- Internal properties are not included
function PropertyDef:export()
return self.D
end
-- Returns native (SQLite) type, i.e. 'text', 'float', 'integer', 'blob'
--- @return string
function PropertyDef:getNativeType()
return ''
end
function PropertyDef:getCtlvIndexMask()
local idxType = string.lower(self.D.index or '')
if idxType == 'index' then
return Constants.CTLV_FLAGS.INDEX
elseif idxType == 'unique' then
return Constants.CTLV_FLAGS.UNIQUE
else
return 0
end
end
--[[
Returns mask for search in partial SQLite index
Depending on col mapping mode returns it for ctlv or ctlo.
Used for building SQL queries which perform search on Flexilite indexes
]]
---@return number
function PropertyDef:getIndexMask()
if self.ClassDef.ColMapActive and self.ColMap then
local idxType = string.lower(self.D.index or '')
local colIdx = self:ColMapIndex()
if idxType == 'index' then
return bit52.lshift(1, colIdx + Constants.CTLO_FLAGS.INDEX_SHIFT)
elseif idxType == 'unique' then
return bit52.lshift(1, colIdx + Constants.CTLO_FLAGS.UNIQUE_SHIFT)
else
return 0
end
end
return self:getCtlvIndexMask()
end
-- Builds bit flag value for [.ref-value].ctlv field
---@return number
function PropertyDef:GetCTLV()
local indexMask = self:getCtlvIndexMask()
local result = bit.bor(self:GetVType(), indexMask)
if self.D.noTrackChanges then
result = bit.bor(result, Constants.CTLV_FLAGS.NO_TRACK_CHANGES)
end
return result
end
--Applies property definition to the database. Called on property save
function PropertyDef:beforeSaveToDB()
self.ClassDef:assignColMappingForProperty(self)
-- resolve property name
self.Name:resolve(self.ClassDef)
self.ctlv = self:GetCTLV()
self.ctlvPlan = self.ctlv
end
--- Returns table representation of property definition as it will be used for class definition
--- serialization to JSON
---@return table
function PropertyDef:internalToJSON()
return tablex.deepcopy(self.D)
end
function PropertyDef:isReference()
return false
end
-- Returns SQLite raw value type
---@return number
function PropertyDef:GetVType()
return Constants.vtype.default
end
function PropertyDef:buildValueSchema(valueSchema)
local s = { valueSchema }
local maxOccurr = (self.D.rules and self.D.rules.maxOccurrences) or 1
if maxOccurr > 1 then
-- collection
s[2] = schema.Collection(valueSchema)
else
-- one item tuple
s[2] = schema.Tuple(valueSchema)
end
local minOccurr = (self.D.rules and self.D.rules.minOccurrences) or 0
if minOccurr == 0 then
s[3] = schema.Nil
end
return schema.OneOf(unpack(s))
end
---@param op string @comment 'C' or 'U'
function PropertyDef:GetValueSchema(op)
return schema.Any
end
function PropertyDef:GetSupportedIndexTypes()
return Constants.INDEX_TYPES.NON
end
-- Returns column expression to access property value (with PropIndex = 1)
-- Used to build dynamic SQL
---@param first boolean @comment if true, will preprend column expression with comma
---@return string
function PropertyDef:GetColumnExpression(first)
if self.ColMap then
return string.format(
'%s coalesce([%s], (select [Value] from [.ref-values] where ClassID=%d and PropertyID=%d and PropIndex=0 limit 1)) as [%s]',
first and ' ' or ',', self.ColMap, self.ClassDef.ClassID, self.ID, self.Name.text)
else
return string.format(
'%s (select [Value] from [.ref-values] where ClassID=%d and PropertyID=%d and PropIndex=0 limit 1) as [%s]',
first and '' or ',', self.ClassDef.ClassID, self.ID, self.Name.text)
end
end
-- Creates instance of DBProperty for DBObject
---@param object DBObject
function PropertyDef:CreateDBProperty(object)
local result = dbprops.DBProperty(object, self)
return result
end
-- Converts value from user format to internally used storage format
---@param dbv DBValue
---@return any
function PropertyDef:GetRawValue(dbv)
return dbv.Value
end
---@param dbv DBValue
---@param val any
function PropertyDef:SetRawValue(dbv, val)
dbv.Value = val
end
-- Sets dbv.Value from source data v, with possible conversion and/or validation
---@param dbv DBValue
---@param v any
---@return nil | function @comment If function is returned, it will be treated as pending action to be
---called at the second step of updates. Returning nil meand that dbv.Value was set successfully
function PropertyDef:ImportDBValue(dbv, v)
dbv.Value = v
end
-- Converts dbv.Value to the format, appropriate for JSON serialization
---@param dbo DBObject
---@param dbv DBValue
---@return any
function PropertyDef:ExportDBValue(dbo, dbv)
return dbv.Value
end
-- Binds Value parameter to insert/update .ref-values
---@param stmt userdata @comment sqlite3_statement
---@param param_no number
---@param dbv DBValue
function PropertyDef:BindValueParameter(stmt, param_no, dbv)
stmt:bind(param_no, dbv.Value)
end
-- Returns index of column mapped
---@return number | nil
function PropertyDef:ColMapIndex()
return self.ColMap ~= nil and string.lower(self.ColMap):byte() - string.byte('a') or nil
end
---@type PropertyDefCapabilities
local _propertyDefCapabilities = {
nativeType = '',
supportedIndexTypes = Constants.INDEX_TYPES.NON,
canBeUsedAsUDID = true,
columnMappingSupported = true,
vtype = Constants.vtype.default,
supportsRangeIndexing = false,
}
---@return PropertyDefCapabilities
function PropertyDef:getCapabilities()
return _propertyDefCapabilities
end
---@param includeId boolean
---@return string
function PropertyDef:debugDesc(includeId)
if includeId then
return ('%s.%s[%s]'):format(self.ClassDef.Name.text, self.Name.text, self.ID)
end
return ('%s.%s'):format(self.ClassDef.Name.text, self.Name.text)
end
--[[
===============================================================================
AnyPropertyDef
===============================================================================
]]
---@class AnyPropertyDef @parent PropertyDef
local AnyPropertyDef = class(PropertyDef)
function AnyPropertyDef:_init(params)
self:super(params)
end
-- TODO override methods, allow any data??
--[[
===============================================================================
NumberPropertyDef
===============================================================================
]]
-- Base property type for all range-able types
--- @class NumberPropertyDef @parent PropertyDef
local NumberPropertyDef = class(PropertyDef)
function NumberPropertyDef:_init(params)
self:super(params)
end
---@type PropertyDefCapabilities
local _numberPropertyDefCapabilities = tablex.deepcopy(_propertyDefCapabilities)
_numberPropertyDefCapabilities.nativeType = 'float'
_numberPropertyDefCapabilities.supportsRangeIndexing = true
_numberPropertyDefCapabilities.supportedIndexTypes = Constants.INDEX_TYPES.MUL + Constants.INDEX_TYPES.RNG + Constants.INDEX_TYPES.STD + Constants.INDEX_TYPES.UNQ
function NumberPropertyDef:getCapabilities()
return _numberPropertyDefCapabilities
end
function NumberPropertyDef:getNativeType()
return 'float'
end
--- @overload
function NumberPropertyDef:supportsRangeIndexing()
return true
end
---@param op string @comment 'C' or 'U'
function NumberPropertyDef:GetValueSchema(op)
local result = self:buildValueSchema(
schema.NumberFrom(self.D.rules.minValue or Constants.MIN_NUMBER,
self.D.rules.maxValue or Constants.MAX_NUMBER))
return result
end
function NumberPropertyDef:GetSupportedIndexTypes()
return Constants.INDEX_TYPES.MUL + Constants.INDEX_TYPES.RNG + Constants.INDEX_TYPES.STD + Constants.INDEX_TYPES.UNQ
end
---@param dbv DBValue
---@param v any
function NumberPropertyDef:ImportDBValue(dbv, v)
dbv.Value = tonumber(v)
end
--[[
===============================================================================
MoneyPropertyDef
===============================================================================
]]
--- @class MoneyPropertyDef @parent NumberPropertyDef
local MoneyPropertyDef = class(NumberPropertyDef)
-- Ctor is required
function MoneyPropertyDef:_init(params)
self:super(params)
end
local _moneyPropertyDefCapabilities = tablex.deepcopy(_numberPropertyDefCapabilities)
_moneyPropertyDefCapabilities.vtype = Constants.vtype.money
_moneyPropertyDefCapabilities.nativeType = 'integer'
function MoneyPropertyDef:getCapabilities()
return _moneyPropertyDefCapabilities
end
function MoneyPropertyDef:GetVType()
return Constants.vtype.money
end
function MoneyPropertyDef:getNativeType()
return 'integer'
end
---@param dbv DBValue
---@param v any
function MoneyPropertyDef:ImportDBValue(dbv, v)
local vv = tonumber(v) * 10000
local s = ('%.1f'):format(vv)
if s:byte(#s) ~= 48 then
-- Last character must be '0' (ASCII 48)
error(string.format('%s: %s is not valid value for money',
self:debugDesc(), v))
end
dbv.Value = tonumber(s:sub(1, #s - 2))
end
-- TODO GetValueSchema - check if value is number with up to 4 decimal places
--[[
===============================================================================
IntegerPropertyDef
===============================================================================
]]
--- @class IntegerPropertyDef @parent NumberPropertyDef
local IntegerPropertyDef = class(NumberPropertyDef)
function IntegerPropertyDef:_init(params)
self:super(params)
end
local _integerPropertyDefCapabilities = tablex.deepcopy(_numberPropertyDefCapabilities)
_integerPropertyDefCapabilities.nativeType = 'integer'
function IntegerPropertyDef:getCapabilities()
return _integerPropertyDefCapabilities
end
function IntegerPropertyDef:getNativeType()
return 'integer'
end
---@param op string @comment 'C' or 'U'
function IntegerPropertyDef:GetValueSchema(op)
local result = self:buildValueSchema(schema.AllOf(schema.NumberFrom(self.D.rules.minValue or Constants.MIN_INTEGER,
self.D.rules.maxValue or Constants.MAX_INTEGER), schema.Integer))
return result
end
--[[
===============================================================================
TextPropertyDef
===============================================================================
]]
--- @class TextPropertyDef @parent PropertyDef
local TextPropertyDef = class(PropertyDef)
function TextPropertyDef:_init(params)
self:super(params)
end
local _textPropertyDefCapabilities = tablex.deepcopy(_propertyDefCapabilities)
_textPropertyDefCapabilities.nativeType = 'text'
_textPropertyDefCapabilities.columnMappingSupported = true -- TODO
_textPropertyDefCapabilities.supportedIndexTypes = Constants.INDEX_TYPES.MUL + Constants.INDEX_TYPES.FTS + Constants.INDEX_TYPES.STD + Constants.INDEX_TYPES.UNQ
function TextPropertyDef:getNativeType()
return 'text'
end
function TextPropertyDef:ColumnMappingSupported()
return (self.D.rules.maxLength or 255) <= 255
end
---@param op string @comment 'C' or 'U'
function TextPropertyDef:GetValueSchema(op)
-- TODO Check regex and maxLength
local result = self:buildValueSchema(schema.String)
return result
end
function TextPropertyDef:GetSupportedIndexTypes()
return Constants.INDEX_TYPES.MUL + Constants.INDEX_TYPES.FTS + Constants.INDEX_TYPES.STD + Constants.INDEX_TYPES.UNQ
end
--[[
===============================================================================
SymNamePropertyDef
===============================================================================
]]
--- @class SymNamePropertyDef @parent TextPropertyDef
local SymNamePropertyDef = class(TextPropertyDef)
function SymNamePropertyDef:_init(params)
self:super(params)
end
function SymNamePropertyDef:ColumnMappingSupported()
return true
end
function SymNamePropertyDef:GetVType()
return Constants.vtype.symbol
end
---@param op string @comment 'C' or 'U'
function SymNamePropertyDef:GetValueSchema(op)
-- TODO Check if integer matches NamesID
local result = self:buildValueSchema(schema.OneOf(schema.String, schema.Integer))
return result
end
function SymNamePropertyDef:GetSupportedIndexTypes()
return Constants.INDEX_TYPES.MUL + Constants.INDEX_TYPES.STD + Constants.INDEX_TYPES.UNQ + Constants.INDEX_TYPES.FTS_SEARCH
end
--[[
===============================================================================
ReferencePropertyDef: base class for all referencing properties: enum, nested etc.
===============================================================================
]]
---@class ReferencePropertyDef : PropertyDef
---@field _viewGenerationPending boolean
local ReferencePropertyDef = class(PropertyDef)
-- Returns internal JSON representation of property
function ReferencePropertyDef:internalToJSON()
local result = PropertyDef.internalToJSON(self)
result.refDef = tablex.deepcopy(self.refDef)
return result
end
function ReferencePropertyDef:ColumnMappingSupported()
return false
end
-- true if property value can be used as user defined ID (UID)
function ReferencePropertyDef:CanBeUsedAsUID()
return false
end
-- Returns schema for property value as schema for nested/owned/mixin
-- Used for mixins, owned and nested objects for insert and update
function ReferencePropertyDef:getValueSchemaAsObject()
local result = self:buildValueSchema()
return result
end
-- Returns schema for property value as schema for query filter (to fetch list of referenced IDs)
-- Used for normal references (except mixins, nested and owned objects) for both insert and update.
function ReferencePropertyDef:getValueSchemaAsFilter()
end
---@param op string @comment 'C' or 'U'
function ReferencePropertyDef:GetValueSchema(op)
local result = self:buildValueSchema(schema.OneOf(schema.String, schema.Integer))
return result
end
-- Creates instance of DBProperty for DBObject
---@param object DBObject
function ReferencePropertyDef:CreateDBProperty(object)
local result = dbprops.ReferencePropertyDef(object, self)
return result
end
function ReferencePropertyDef:_init(params)
self:super(params)
end
function ReferencePropertyDef:initMetadataRefs()
PropertyDef.initMetadataRefs(self)
if self.D and self.D.refDef then
self.ClassDef.DBContext:InitMetadataRef(self.D.refDef, 'classRef', ClassNameRef)
self.ClassDef.DBContext:InitMetadataRef(self.D.refDef, 'reverseProperty', PropNameRef)
end
end
-- Private method to verify that relation view is created
function ReferencePropertyDef:_checkRegenerateRelView()
---@param refDef PropertyRefDef
---@return string
local function _get_view_col_name(refDef)
if refDef.viewColName then
return refDef.viewColName
end
-- check id prop
local idProp = self.ClassDef:getUdidProp()
if idProp then
return idProp.Name.text
end
-- assume self name - in most cases this would be incorrect though
local result = self.Name.text
return result
end
---@param refDef PropertyRefDef
---@return string
local function _get_reversed_view_col_name(refDef)
if refDef.reversedPropViewColName then
return refDef.reversedPropViewColName
end
-- check id column
if refDef.classRef then
local idProp = refDef.classRef:getUdidProp()
if idProp then
return idProp.Name.text
end
end
-- assume self name - in most cases this would be incorrect though
local result
if refDef.reverseProperty then
result = refDef.reverseProperty.text
elseif refDef.classRef then
result = refDef.classRef.text
else
error(string.format(
'%s: Reversed property or referenced class are required for relational view. Both refDef.classRef and refDef.reverseProperty',
self:debugDesc()))
end
return result
end
---@type PropertyRefDef
local refDef = self.D.refDef
if refDef and refDef.viewName then
-- Generate view for many-2-many relationship
local thatName = _get_reversed_view_col_name(refDef)
local thisName = _get_view_col_name(refDef)
generateRelView(
-- DBContext
self.ClassDef.DBContext,
-- tableName
refDef.viewName,
-- className
self.ClassDef.Name.text,
-- propName
self.Name.text,
-- col1Name
thisName,
-- col2Name
thatName)
end
self._viewGenerationPending = false
end
--- Override
---@return number @comment ID of saved property
function ReferencePropertyDef:saveToDB()
local result = PropertyDef.saveToDB(self)
if not self._viewGenerationPending then
self._viewGenerationPending = true
self.ClassDef.DBContext.ActionQueue:enqueue(function(self)
self:_checkRegenerateRelView()
end, self)
end
return result
end
-- TODO beforeApplyDef?
function ReferencePropertyDef:beforeSaveToDB()
PropertyDef.beforeSaveToDB(self)
---@type PropertyRefDef
local refDef = self.D.refDef
if refDef then
if refDef.classRef then
refDef.classRef:resolve(self.ClassDef)
end
if refDef.reverseProperty then
-- Check if reverse property exists. If no, create it
---@type ClassDef
local revClassDef = self.ClassDef.DBContext:getClassDef(refDef.classRef.text, true)
if not revClassDef:hasProperty(refDef.reverseProperty.text) then
-- Create new ref property
local propDef = {
rules = {
type = 'ref',
minOccurrences = 0,
maxOccurrences = Constants.MAX_INTEGER,
},
refDef = {
classRef = self.ClassDef.Name.text,
reverseProperty = self.Name.text,
}
}
local revPropDef = revClassDef:AddNewProperty(refDef.reverseProperty.text, propDef)
revPropDef:beforeSaveToDB()
--self.ClassDef.DBContext.ActionQueue:enqueue(function(params, dbContext)
-- params.revPropDef:beforeSaveToDB()
-- --local propID = params.revPropDef:saveToDB(nil, params.refDef.reverseProperty.text)
--end, {
-- revClassDef = revClassDef,
-- revPropDef = revPropDef,
-- refDef = refDef,
-- self = self
--})
end
--self.ClassDef.DBContext.ActionQueue:enqueue(function(params)
refDef.reverseProperty:resolve(revClassDef)
--end, { refDef = refDef, revClassDef = revClassDef})
end
end
end
function ReferencePropertyDef:isReference()
return true
end
-- Creates instance of DBProperty for DBObject
---@param object DBObject
function ReferencePropertyDef:CreateDBProperty(object)
local result = dbprops.LinkDBProperty(object, self)
return result
end
---@param dbv DBValue
---@param v any
function ReferencePropertyDef:ImportDBValue(dbv, v)
return self.ClassDef.DBContext.RefDataManager:importReferenceValue(self, dbv, v)
end
--[[
===============================================================================
EnumPropertyDef
Inherited from reference property and overrides ImportDBValue and
ExportDBValue
===============================================================================
]]
--- @class EnumPropertyDef : ReferencePropertyDef
local EnumPropertyDef = class(ReferencePropertyDef)
function EnumPropertyDef:_init(params)
self:super(params)
end
function EnumPropertyDef:beforeSaveToDB()
-- Note: calling PropertyDef, not ReferencePropertyDef
PropertyDef.beforeSaveToDB(self)
self.ClassDef.DBContext.ActionQueue:enqueue(function(self)
-- Resolve names
if self.D.enumDef then
if self.D.enumDef.classRef then
self.D.enumDef.classRef:resolve(self.ClassDef)
end
if self.D.enumDef.items then
for _, v in pairs(self.D.enumDef.items) do
v:resolve(self.ClassDef)
end
end
end
self.ClassDef.DBContext.RefDataManager:ApplyEnumPropertyDef(self)
end, self)
end
function EnumPropertyDef:internalToJSON()
local result = ReferencePropertyDef.internalToJSON(self)
result.refDef = tablex.deepcopy(self.enumDef)
return result
end
function EnumPropertyDef:initMetadataRefs()
ReferencePropertyDef.initMetadataRefs(self)
if self.D.enumDef then
self.ClassDef.DBContext:InitMetadataRef(self.D.enumDef, 'classRef', ClassNameRef)
if self.D.enumDef.items then
local newItems = {}
for i, v in pairs(self.D.enumDef.items) do
if v and v.text then
newItems[i] = NameRef(v.text, v.id)
end
end
self.D.enumDef.items = newItems
end
end
end
-- true if property value can be used as user defined ID (UID)
function EnumPropertyDef:CanBeUsedAsUID()
return false
end
function EnumPropertyDef:GetVType()
return Constants.vtype.enum
end
function EnumPropertyDef:GetSupportedIndexTypes()
return Constants.INDEX_TYPES.MUL + Constants.INDEX_TYPES.STD + Constants.INDEX_TYPES.UNQ
+ Constants.INDEX_TYPES.FTS_SEARCH
end
--[[ Applies enum value to the property
Postpones operation till all scalar data for all objects in the transaction are done.
This ensures that all inter-references are resolved properly
]]
---@param dbv DBValue
---@param v string | number | boolean
function EnumPropertyDef:ImportDBValue(dbv, v)
return self.ClassDef.DBContext.RefDataManager:importEnumValue(self, dbv, v)
end
-- Retrieves $uid value from referenced object
---@param dbo DBObject
---@param dbv DBValue
function EnumPropertyDef:ExportDBValue(dbo, dbv)
-- TODO
end
--function EnumPropertyDef:SetValue()
-- -- TODO
--end
--
-- Checks if all dependency classes exist. May create a new one. Noop by default
-- TODO needed?
--function EnumPropertyDef:beforeApplyDef()
-- PropertyDef.beforeApplyDef(self)
--
-- if self.D.enumDef then
-- self.ClassDef.DBContext.RefDataManager:ApplyEnumPropertyDef(self)
-- end
--end
--[[
===============================================================================
BoolPropertyDef
===============================================================================
]]
--- @class BoolPropertyDef @parent PropertyDef
local BoolPropertyDef = class(PropertyDef)
function BoolPropertyDef:_init(params)
self:super(params)
end
function BoolPropertyDef:getNativeType()
return 'integer'
end
-- true if property value can be used as user defined ID (UID)
function BoolPropertyDef:CanBeUsedAsUID()
return false
end
function BoolPropertyDef:GetSupportedIndexTypes()
return Constants.INDEX_TYPES.MUL
end
--[[
===============================================================================
BlobPropertyDef
===============================================================================
]]
--- @class BlobPropertyDef @parent PropertyDef
local BlobPropertyDef = class(PropertyDef)
function BlobPropertyDef:_init(params)
self:super(params)
end
function BlobPropertyDef:getNativeType()
return 'blob'
end
function BlobPropertyDef:ColumnMappingSupported()
return (self.D.rules.maxLength or Constants.MAX_BLOB_LENGTH) <= 255
end
-- true if property value can be used as user defined ID (UID)
function BlobPropertyDef:CanBeUsedAsUID()
return false
end
---@param dbv DBValue
function BlobPropertyDef:GetRawValue(dbv)
-- TODO base64.decode
return dbv.Value
end
-- Sets dbv.Value from source data v, with possible conversion and/or validation
---@param dbv DBValue
---@param v any
function BlobPropertyDef:ImportDBValue(dbv, v)
local vv = base64.decode(v)
if vv == nil and v ~= nil then
dbv.Value = v
else
dbv.Value = vv
end
end
---@param dbo DBObject
---@param dbv DBValue
---@return any
function BlobPropertyDef:ExportDBValue(dbo, dbv)
local result = base64.encode(dbv.Value)
return result
end
-- Binds Value parameter to insert/update .ref-values
---@param stmt userdata @comment sqlite3_statement
---@param param_no number
---@param dbv DBValue
function BlobPropertyDef:BindValueParameter(stmt, param_no, dbv)
stmt:bind_blob(param_no, dbv.Value)
end
--[[
===============================================================================
UuidPropertyDef
===============================================================================
]]
--- @class UuidPropertyDef @parent BlobPropertyDef
local UuidPropertyDef = class(BlobPropertyDef)
function UuidPropertyDef:_init(params)
self:super(params)
end
function UuidPropertyDef:GetSupportedIndexTypes()
return Constants.INDEX_TYPES.MUL + Constants.INDEX_TYPES.STD + Constants.INDEX_TYPES.UNQ
end
-- true if property value can be used as user defined ID (UID)
function UuidPropertyDef:CanBeUsedAsUID()
return true
end
--[[
===============================================================================
DateTimePropertyDef
===============================================================================
]]
--- @class DateTimePropertyDef @parent NumberPropertyDef
local DateTimePropertyDef = class(NumberPropertyDef)
function DateTimePropertyDef:_init(params)
self:super(params)
end
function DateTimePropertyDef:GetVType()
return Constants.vtype.datetime
end
function DateTimePropertyDef:validateValue(obj, path)
if path == nil then
return nil
end
if obj == nil then
return schema.Error('Null date value', path)
end
local v, err = self:toJulian(obj)
if err then
return schema.Error(err, path)
else
-- Check min/max
local lower = self.D.rules.minValue or Constants.MIN_NUMBER
local upper = self.D.rules.maxValue or Constants.MAX_NUMBER
if v >= lower and v <= upper then
return nil
else
return schema.Error(string.format("Invalid value: %s must be between %s and %s", path, lower, upper), path)
end
end
end
---@param op string @comment 'C' or 'U'
function DateTimePropertyDef:GetValueSchema(op)
local function ValidateDateTime(obj, path)
return self:validateValue(obj, path)
end
return self:buildValueSchema(ValidateDateTime)
end
-- Attempts to convert arbitrary value to number in Julian calendar (number of days starting from 0 AC)
---@param value any
---@param culture string | nil
---@return number, string @comment date/time in Julian (the same as SQLite) and error message (nil if OK)
function DateTimePropertyDef:toJulian(value)
if type(value) == 'string' then
return parseDateTimeToJulian(value)
elseif type(value) == 'number' then
return value, nil
elseif type(value) == 'table' then
local result = stringifyDateTimeInfo(value)
return result, nil
else
return 0, 'Unsupported value type for date/time'
end
end
function DateTimePropertyDef:beforeSaveToDB()
PropertyDef.beforeSaveToDB(self)
---@param cntnr table
---@param attrName string
local function convertDateTime(cntnr, attrName)
if cntnr and cntnr[attrName] then
local v, err = self:toJulian(cntnr[attrName])
if err then
-- TODO 'Default data is not in valid format'
error(err)
end
cntnr[attrName] = v
end
end
convertDateTime(self.D, 'defaultValue')
convertDateTime(self.D.rules, 'minValue')
convertDateTime(self.D.rules, 'maxValue')
end
---@param dbv DBValue
function DateTimePropertyDef:GetRawValue(dbv)
return self:toJulian(dbv.Value)
end
---@param dbv DBValue
---@param v any
function DateTimePropertyDef:ImportDBValue(dbv, v)
if type(v) == 'string' then
dbv.Value = parseDateTimeToJulian(v)
elseif type(v) == 'number' then
dbv.Value = tonumber(v)
else
error(string.format('Invalid value type of date property %s.%s: %s (%s)',
self.PropDef.ClassDef.Name.text, self.PropDef.Name.text, v, type(v)))
end
end
--[[
===============================================================================
TimeSpanPropertyDef
===============================================================================
]]
--- @class TimeSpanPropertyDef @parent DateTimePropertyDef
local TimeSpanPropertyDef = class(DateTimePropertyDef)
function TimeSpanPropertyDef:_init(params)
self:super(params)
end
function TimeSpanPropertyDef:GetVType()
return Constants.vtype.timespan
end
--[[
===============================================================================
ComputedPropertyDef
===============================================================================
]]
--- @class ComputedPropertyDef @parent PropertyDef
local ComputedPropertyDef = class(PropertyDef)
function ComputedPropertyDef:_init(params)
self:super(params)
end
function ComputedPropertyDef:ColumnMappingSupported()
return false
end
-- true if property value can be used as user defined ID (UID)
function ComputedPropertyDef:CanBeUsedAsUID()
return false
end
-- Class level list of available property types
-- map for property types
PropertyDef.PropertyTypes = {
['bool'] = BoolPropertyDef,
['boolean'] = BoolPropertyDef,
['integer'] = IntegerPropertyDef,
['int'] = IntegerPropertyDef,
['number'] = NumberPropertyDef,
['float'] = NumberPropertyDef,
['text'] = TextPropertyDef,
['string'] = TextPropertyDef,
['bytes'] = BlobPropertyDef,
['binary'] = BlobPropertyDef,
['blob'] = BlobPropertyDef,
['decimal'] = MoneyPropertyDef,
['money'] = MoneyPropertyDef,
['uuid'] = UuidPropertyDef,
['enum'] = EnumPropertyDef,
['fkey'] = EnumPropertyDef,
['foreignkey'] = EnumPropertyDef,
['reference'] = ReferencePropertyDef,
['link'] = ReferencePropertyDef,
['ref'] = ReferencePropertyDef,
['json'] = TextPropertyDef, -- TODO special prop class type???
['computed'] = ComputedPropertyDef,
['formula'] = ComputedPropertyDef,
['name'] = SymNamePropertyDef,
['symname'] = SymNamePropertyDef,
['symbol'] = SymNamePropertyDef,
['date'] = DateTimePropertyDef,
['datetime'] = DateTimePropertyDef,
['time'] = DateTimePropertyDef,
['timespan'] = TimeSpanPropertyDef,
['duration'] = TimeSpanPropertyDef,
['any'] = AnyPropertyDef,
}
-- All specific property classes
PropertyDef.Classes = {
BoolPropertyDef = BoolPropertyDef,
IntegerPropertyDef = IntegerPropertyDef,
NumberPropertyDef = NumberPropertyDef,
BlobPropertyDef = BlobPropertyDef,
MoneyPropertyDef = MoneyPropertyDef,
UuidPropertyDef = UuidPropertyDef,
EnumPropertyDef = EnumPropertyDef,
ReferencePropertyDef = ReferencePropertyDef,
TextPropertyDef = TextPropertyDef,
ComputedPropertyDef = ComputedPropertyDef,
SymNamePropertyDef = SymNamePropertyDef,
DateTimePropertyDef = DateTimePropertyDef,
TimeSpanPropertyDef = TimeSpanPropertyDef,
AnyPropertyDef = AnyPropertyDef,
}
local ClassRefSchema = schema.OneOf(schema.Nil, name_ref.IdentifierSchema, schema.Collection(name_ref.IdentifierSchema))
-- Schema validation rules for property JSON definition
local EnumDefSchemaDef = tablex.deepcopy(NameRef.SchemaDef)
EnumDefSchemaDef.items = schema.Optional(schema.Collection(schema.Record {
id = schema.OneOf(schema.String, schema.Integer),
text = schema.String,
icon = schema.Optional(schema.String),
imageUrl = schema.Optional(schema.String),
}))
EnumDefSchemaDef.refProperty = schema.Optional(name_ref.IdentifierSchema)
local EnumRefDefSchemaDef = {
classRef = tablex.deepcopy(ClassRefSchema),
mixin = schema.Optional(schema.Boolean),
}
local RefDefSchemaDef = {
classRef = tablex.deepcopy(ClassRefSchema),
--[[
Property name ID (in `classRef` class) used as reversed reference property for this one. Optional. If set,
Flexilite will ensure that referenced class does have this property (by creating if needed).
'reversed property' is treated as slave of master definition. It means the following:
1) reversed object ID is stored in [Value] field (master's object ID in [ObjectID] field)
2) when master property gets modified (switches to different class or reverse property) or deleted,
reverse property definition also gets deleted
]]
reverseProperty = schema.Optional(name_ref.IdentifierSchema),
--[[
Defines number of items fetched as a part of master object load. Applicable only > 0
]]
autoFetchLimit = schema.Optional(schema.AllOf(schema.Integer, schema.PositiveNumber)),
autoFetchDepth = schema.Optional(schema.AllOf(schema.Integer, schema.PositiveNumber)),
--[[
Optional relation rule when object gets deleted. If not specified, 'link' is assumed
]]
rule = schema.OneOf(schema.Nil,
--[[
Referenced object(s) are details (dependents).
They will be deleted when master is deleted. Equivalent of DELETE CASCADE
]]
'master',
--[[
Loose association between 2 objects. When object gets deleted, references are deleted too.
Equivalent of DELETE SET NULL
]]
'link',
--[[
Similar to master but referenced objects are treated as part of master object
]]
'inner',
--[[
Object cannot be deleted if there are references. Equivalent of DELETE RESTRICT
]]
'dependent'
),
mixin = schema.Optional(schema.Boolean),
viewName = schema.Optional(schema.String),
}
PropertyDef.Schema = schema.AllOf(schema.Record {
rules = schema.AllOf(
schema.Record {
type = schema.OneOf(unpack(tablex.keys(PropertyDef.PropertyTypes))),
subType = schema.OneOf(schema.Nil, 'text', 'email', 'ip', 'password', 'ip6v', 'url', 'image', 'html'), -- TODO list to be extended
minOccurrences = schema.Optional(schema.AllOf(schema.NonNegativeNumber, schema.Integer)),
maxOccurrences = schema.Optional(schema.AllOf(schema.Integer, schema.PositiveNumber)),
maxLength = schema.Optional(schema.AllOf(schema.Integer, schema.NumberFrom(-1, Constants.MAX_INTEGER))),
-- TODO integer, float or date/time, depending on property type
minValue = schema.Optional(schema.Number),
maxValue = schema.Optional(schema.Number),
regex = schema.Optional(schema.String),
},
schema.Test(function(rules)
return (rules.maxOccurrences or 1) >= (rules.minOccurrences or 0)
end, 'maxOccurrences must be greater or equal than minOccurrences')
,
schema.Test(function(rules)
-- TODO Check property type
return (rules.maxValue or Constants.MAX_NUMBER) >= (rules.minValue or Constants.MIN_NUMBER)
end, 'maxValue must be greater or equal than minValue')
),
index = schema.OneOf(schema.Nil, 'index', 'unique', 'range', 'fulltext'),
noTrackChanges = schema.Optional(schema.Boolean),
enumDef = schema.Case('rules.type',
{ schema.OneOf('enum', 'fkey', 'foreignkey'),
schema.Optional(schema.Record(EnumDefSchemaDef)) },
{ schema.Any, schema.Any }),
refDef = schema.Case('rules.type',
{ schema.OneOf('link', 'ref', 'reference'), schema.Record(RefDefSchemaDef) },
{ schema.OneOf('enum', 'fkey', 'foreignkey'), schema.Optional(schema.Record(EnumRefDefSchemaDef)) },
{ schema.Any, schema.Any }),
-- todo specific property value
defaultValue = schema.Any,
accessRules = schema.Optional(AccessControl.Schema),
}
,
schema.Test(
function(propDef)
-- Test enum definition
local t = string.lower(propDef.rules.type)
if t == 'enum' or t == 'fkey' or t == 'foreignkey' then
local def = propDef.enumDef and 1 or 0
def = def + (propDef.refDef and 2 or 0)
return def == 1 or def == 2
end
return true
end, 'Enum property requires either enumDef or refDef (but not both)'
)
)
return PropertyDef
| mpl-2.0 |
ByteFun/Starbound_mods | smount/tech/mech/mount36/mount36.lua | 7 | 34280 | 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[""] 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[""] 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[""] and self.active then
return "mechFire"
elseif args.moves[""] 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[""] 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 |
shagu/pfQuest | db/esES/professions.lua | 1 | 3340 | pfDB["professions"]["esES"] = {
[6] = "Escarcha",
[8] = "Fuego",
[26] = "Armas",
[38] = "Combate",
[39] = "Sutileza",
[40] = "Venenos",
[43] = "Espadas",
[44] = "Hachas",
[45] = "Arcos",
[46] = "Armas de fuego",
[50] = "Dominio de bestias",
[51] = "Supervivencia",
[54] = "Mazas",
[55] = "Espadas de dos manos",
[56] = "Sagrado",
[78] = "Magia sombría",
[95] = "Defensa",
[98] = "Lengua: común",
[101] = "Racial enano",
[109] = "Lengua: orco",
[111] = "Lengua: Enánico",
[113] = "Lengua: Darnassiano",
[115] = "Lengua: Taurahe",
[118] = "Empuñadura dual",
[124] = "Racial tauren",
[125] = "Racial orco",
[126] = "Racial elfo de la noche",
[129] = "Primeros auxilios",
[134] = "Combate feral",
[136] = "Bastones",
[137] = "Lengua: thalassiano",
[138] = "Lengua: dracónico",
[139] = "Lengua: demoníaco",
[140] = "Lengua: titánico",
[141] = "Lengua: lengua antigua",
[142] = "Supervivencia",
[148] = "Montar caballos",
[149] = "Montar lobos",
[150] = "Montar tigres",
[152] = "Montar carneros",
[155] = "Nadar",
[160] = "Mazas de dos manos",
[162] = "Sin armas",
[163] = "Puntería",
[164] = "Herrería",
[165] = "Marroquinería",
[171] = "Alquimia",
[172] = "Hachas de dos manos",
[173] = "Dagas",
[176] = "Armas arrojadizas",
[182] = "Botánica",
[183] = "COMÚN (DND)",
[184] = "Reprensión",
[185] = "Cocina",
[186] = "Minería",
[188] = "Mascota: diablillo",
[189] = "Mascota: Manáfago",
[197] = "Costura",
[202] = "Ingeniería",
[203] = "Mascota: araña",
[204] = "Mascota: abisario",
[205] = "Mascota: súcubo",
[206] = "Mascota: inferno",
[207] = "Mascota: guardia maldito",
[208] = "Mascota: lobo",
[209] = "Mascota: felino",
[210] = "Mascota: oso",
[211] = "Mascota: jabalí",
[212] = "Mascota: crocolisco",
[213] = "Mascota: carroñero",
[214] = "Mascota: cangrejo",
[215] = "Mascota: gorila",
[217] = "Mascota: raptor",
[218] = "Mascota: zancudo",
[220] = "Racial: no-muerto",
[226] = "Ballestas",
[228] = "Varitas",
[229] = "Armas de asta",
[236] = "Mascota: escórpido",
[237] = "Arcano",
[251] = "Mascota: tortuga",
[253] = "Asesinato",
[256] = "Furia",
[257] = "Protección",
[261] = "Entrenamiento de bestias",
[267] = "Protección",
[270] = "Mascota: miscelánea",
[293] = "Armadura de placas",
[313] = "Lengua: gnomótico",
[315] = "Lengua: trol",
[333] = "Encantamiento",
[354] = "Demonología",
[355] = "Aflicción",
[356] = "Pesca",
[373] = "Mejora",
[374] = "Recuperación",
[375] = "Combate elemental",
[393] = "Desollar",
[413] = "Mallas",
[414] = "Cuero",
[415] = "Tela",
[433] = "Escudo",
[473] = "Armas de puño",
[533] = "Montar raptor",
[553] = "Montar mecazancudos",
[554] = "Equitación para no-muertos",
[573] = "Recuperación",
[574] = "Equilibrio",
[593] = "Destrucción",
[594] = "Sagrado",
[613] = "Disciplina",
[633] = "Ganzúa",
[653] = "Mascota: murciélago",
[654] = "Mascota: hiena",
[655] = "Mascota: búho",
[656] = "Mascota: serpiente alada",
[673] = "Lengua: viscerálico",
[713] = "Montar kodos",
[733] = "Racial: trol",
[753] = "Racial: gnomo",
[754] = "Racial: humano",
[758] = "Mascota - Evento - Control remoto",
[762] = "Equitación",
}
| mit |
jshackley/darkstar | scripts/zones/LaLoff_Amphitheater/mobs/Ark_Angel_TT.lua | 8 | 1923 | -----------------------------------
-- Area: LaLoff Amphitheater
-- MOB: Ark Angel TT
-----------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:addMod(MOD_UFASTCAST, 30);
mob:setMobMod(MOBMOD_MAIN_2HOUR, 1);
mob:setMobMod(MOBMOD_SUB_2HOUR, 1);
end
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local mobid = mob:getID()
for member = mobid-5, mobid+2 do
if (GetMobAction(member) == 16) then
GetMobByID(member):updateEnmity(target);
end
end
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
if (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON) and bit.band(mob:getBehaviour(),BEHAVIOUR_STANDBACK) > 0) then
mob:setBehaviour(bit.band(mob:getBehaviour(), bit.bnot(BEHAVIOUR_STANDBACK)))
mob:setMobMod(MOBMOD_TELEPORT_TYPE,0);
mob:setMobMod(MOBMOD_SPAWN_LEASH,0);
mob:setSpellList(0);
end
if (not mob:hasStatusEffect(EFFECT_BLOOD_WEAPON) and bit.band(mob:getBehaviour(),BEHAVIOUR_STANDBACK) == 0) then
mob:setBehaviour(bit.bor(mob:getBehaviour(), BEHAVIOUR_STANDBACK))
mob:setMobMod(MOBMOD_TELEPORT_TYPE,1);
mob:setMobMod(MOBMOD_SPAWN_LEASH,22);
mob:setSpellList(39);
end
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob,killer,ally)
end;
| gpl-3.0 |
hockeychaos/Core-Scripts-1 | CoreScriptsRoot/Modules/Stats/StatsAggregatorManager.lua | 2 | 1937 |
--[[
Filename: StatsAggregatorManager.lua
Written by: dbanks
Description: Indexed array of stats aggregators, one for each stat.
--]]
--[[ Services ]]--
local CoreGuiService = game:GetService('CoreGui')
--[[ Modules ]]--
local StatsUtils = require(CoreGuiService.RobloxGui.Modules.Stats.StatsUtils)
local StatsAggregatorClass = require(CoreGuiService.RobloxGui.Modules.Stats.StatsAggregator)
--[[ Classes ]]--
local StatsAggregatorManagerClass = {}
StatsAggregatorManagerClass.__index = StatsAggregatorManagerClass
StatsAggregatorManagerClass.SecondsBetweenUpdate = 1.0
StatsAggregatorManagerClass.NumSamplesToKeep = 20
local statsAggregatorManagerSingleton = nil
function StatsAggregatorManagerClass.getSingleton()
if (statsAggregatorManagerSingleton == nil) then
statsAggregatorManagerSingleton = StatsAggregatorManagerClass.__new()
-- Start listening for updates in stats.
statsAggregatorManagerSingleton:StartListening()
end
return statsAggregatorManagerSingleton
end
function StatsAggregatorManagerClass.__new()
local self = {}
setmetatable(self, StatsAggregatorManagerClass)
self._statsAggregators = {}
for i, statType in ipairs(StatsUtils.AllStatTypes) do
local statsAggregator = StatsAggregatorClass.new(statType,
StatsAggregatorManagerClass.NumSamplesToKeep,
StatsAggregatorManagerClass.SecondsBetweenUpdate)
self._statsAggregators[statType] = statsAggregator
end
return self
end
function StatsAggregatorManagerClass:StartListening()
for i, statsAggregator in pairs(self._statsAggregators) do
statsAggregator:StartListening()
end
end
function StatsAggregatorManagerClass:StopListening()
for i, statsAggregator in pairs(self._statsAggregators) do
statsAggregator:StopListening()
end
end
function StatsAggregatorManagerClass:GetAggregator(statsType)
return self._statsAggregators[statsType]
end
return StatsAggregatorManagerClass | apache-2.0 |
fastmailops/pdns | modules/luabackend/test/powerdns-luabackend.lua | 12 | 3189 | --remember, this is just a test case to see that the minimal backend does work...
local logger = logger
local pairs = pairs
local type = type
local log_error = log_error
local dnspacket = dnspacket
local domains_id = {}
local domains_name = {}
local records = {}
domains_name["test.com"] = {domain_id = 11, name = "test.com", type = "NATIVE", soa = { hostmaster = "ahu.test.com", nameserver = "ns1.test.com", serial = 2005092501, refresh = 28800, retry = 7200, expire = 604800, default_ttl = 86400, ttl = 3600 } }
domains_id["11"] = domains_name["test.com"]
records["test.com"] = {
{domain_id = 11, name = "test.com", type = "NS", ttl = 120, content = "ns1.test.com"},
{domain_id = 11, name = "test.com", type = "NS", ttl = 120, content = "ns2.test.com"},
}
records["ns1.test.com"] = {
{domain_id = 11, name = "ns1.test.com", type = "A", ttl = 120, content = "10.11.12.14"},
{domain_id = 11, name = "ns1.test.com", type = "AAAA", ttl = 120, content = "1:2:3:4:5:6:7:9"}
}
records["ns2.test.com"] = {
{domain_id = 11, name = "ns2.test.com", type = "A", ttl = 120, content = "10.11.12.15"},
{domain_id = 11, name = "ns2.test.com", type = "AAAA", ttl = 120, content = "1:2:3:4:5:6:7:10"}
}
records["www.test.com"] = { {domain_id = 11, name = "www.test.com", type = "CNAME", ttl = 120, content = "host.test.com"} }
records["host.test.com"] = {
{domain_id = 11, name = "host.test.com", type = "A", ttl = 120, content = "10.11.12.13"},
{domain_id = 11, name = "host.test.com", type = "AAAA", ttl = 120, content = "1:2:3:4:5:6:7:8"}
}
function list(target, domain_id)
logger(log_error, "(l_list)", "target:", target, " domain_id:", domain_id )
return false
end
local size, c, r, n, nn, q_type, q_name, domainid
local remote_ip, remote_port, local_ip
function lookup(qtype, qname, domain_id)
-- logger(log_error, "(l_lookup)", "qtype:", qtype, " qname:", qname, " domain_id:", domain_id )
q_type = qtype
q_name = qname
domainid = domain_id
r = records[q_name]
c = 0
size = 0
remote_ip, remote_port, local_ip = dnspacket()
-- logger(log_error, "(l_lookup) dnspacket", "remote:", remote_ip, " port:", remote_port, " local:", local_ip)
if type(r) == "table" then
size = #r
end
-- logger(log_error, "(l_lookup)", "size:", size)
end
function get()
-- logger(log_error, "(l_get) BEGIN")
while c < size do
c = c + 1
if (q_type == "ANY" or q_type == r[c]["type"]) then
-- for kk,vv in pairs(r[c]) do
-- logger(log_error, kk, type(vv), vv)
-- end
return r[c]
end
end
-- logger(log_error, "(l_get) END")
return false
end
local k,v,kk,vv
function getsoa(name)
-- logger(log_error, "(l_getsoa) BEGIN", "name:", name)
r = domains_name[name]
if type(r) == "table" then
-- logger(log_error, type(r), type(r["soa"]))
return r["soa"]
end
-- logger(log_error, "(l_getsoa) END NOT FOUND")
end
logger(log_error, "powerdns-luabackend starting up!")
for k,v in pairs(QTypes) do
-- logger(log_error, k, v)
end
for k,v in pairs(records) do
for kk,vv in pairs(v) do
-- logger(log_error, kk, type(vv), vv["type"])
end
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Crawlers_Nest/npcs/_5h1.lua | 19 | 2611 | -----------------------------------
-- Area: Crawlers' Nest
-- NPC: Strange Apparatus
-- @pos: 214 0 -339 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
require("scripts/zones/Crawlers_Nest/TextIDs");
require("scripts/globals/strangeapparatus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local trade = tradeToStrApp(player, trade);
if (trade ~= nil) then
if ( trade == 1) then -- good trade
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
end
player:startEvent(0x0002, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0);
else -- wrong chip, spawn elemental nm
spawnElementalNM(player);
delStrAppDocStatus(player);
player:messageSpecial(SYS_OVERLOAD);
player:messageSpecial(YOU_LOST_THE, trade);
end
else -- Invalid trade, lose doctor status
delStrAppDocStatus(player);
player:messageSpecial(DEVICE_NOT_WORKING);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
else
player:setLocalVar( "strAppPass", 1);
end
player:startEvent(0x0000, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u", option);
if (csid == 0x0000) then
if (hasStrAppDocStatus(player) == false) then
local docStatus = 1; -- Assistant
if ( option == strAppPass(player)) then -- Good password
docStatus = 0; -- Doctor
giveStrAppDocStatus(player);
end
player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002) then
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
if (drop ~= 0) then
if ( dropQty == 0) then
dropQty = 1;
end
player:addItem(drop, dropQty);
player:setLocalVar("strAppDrop", 0);
player:setLocalVar("strAppDropQty", 0);
end
end
end; | gpl-3.0 |
yagop/telegram-bot | plugins/location.lua | 625 | 1564 | -- Implement a command !loc [area] which uses
-- the static map API to get a location image
-- Not sure if this is the proper way
-- Intent: get_latlong is in time.lua, we need it here
-- loadfile "time.lua"
-- Globals
-- If you have a google api key for the geocoding/timezone api
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Gets information about a location, maplink and overview",
usage = "!loc (location): Gets information about a location, maplink and overview",
patterns = {"^!loc (.*)$"},
run = run
}
end | gpl-2.0 |
BeyondTeam/TeleBeyond | libs/url.lua | 567 | 9183 | --[[
Copyright 2004-2007 Diego Nehab.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
]]
-----------------------------------------------------------------------------
-- URI parsing, composition and relative URL resolution
-- LuaSocket toolkit.
-- Author: Diego Nehab
-- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $
-----------------------------------------------------------------------------
-- updated for a module()-free world of 5.3 by slact
local string = require("string")
local base = _G
local table = require("table")
local Url={}
Url._VERSION = "URL 1.0.2"
function Url.escape(s)
return string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02x", string.byte(c))
end)
end
local function make_set(t)
local s = {}
for i,v in base.ipairs(t) do
s[t[i]] = 1
end
return s
end
local segment_set = make_set {
"-", "_", ".", "!", "~", "*", "'", "(",
")", ":", "@", "&", "=", "+", "$", ",",
}
local function protect_segment(s)
return string.gsub(s, "([^A-Za-z0-9_])", function (c)
if segment_set[c] then return c
else return string.format("%%%02x", string.byte(c)) end
end)
end
function Url.unescape(s)
return string.gsub(s, "%%(%x%x)", function(hex)
return string.char(base.tonumber(hex, 16))
end)
end
local function absolute_path(base_path, relative_path)
if string.sub(relative_path, 1, 1) == "/" then return relative_path end
local path = string.gsub(base_path, "[^/]*$", "")
path = path .. relative_path
path = string.gsub(path, "([^/]*%./)", function (s)
if s ~= "./" then return s else return "" end
end)
path = string.gsub(path, "/%.$", "/")
local reduced
while reduced ~= path do
reduced = path
path = string.gsub(reduced, "([^/]*/%.%./)", function (s)
if s ~= "../../" then return "" else return s end
end)
end
path = string.gsub(reduced, "([^/]*/%.%.)$", function (s)
if s ~= "../.." then return "" else return s end
end)
return path
end
-----------------------------------------------------------------------------
-- Parses a url and returns a table with all its parts according to RFC 2396
-- The following grammar describes the names given to the URL parts
-- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment>
-- <authority> ::= <userinfo>@<host>:<port>
-- <userinfo> ::= <user>[:<password>]
-- <path> :: = {<segment>/}<segment>
-- Input
-- url: uniform resource locator of request
-- default: table with default values for each field
-- Returns
-- table with the following fields, where RFC naming conventions have
-- been preserved:
-- scheme, authority, userinfo, user, password, host, port,
-- path, params, query, fragment
-- Obs:
-- the leading '/' in {/<path>} is considered part of <path>
-----------------------------------------------------------------------------
function Url.parse(url, default)
-- initialize default parameters
local parsed = {}
for i,v in base.pairs(default or parsed) do parsed[i] = v end
-- empty url is parsed to nil
if not url or url == "" then return nil, "invalid url" end
-- remove whitespace
-- url = string.gsub(url, "%s", "")
-- get fragment
url = string.gsub(url, "#(.*)$", function(f)
parsed.fragment = f
return ""
end)
-- get scheme
url = string.gsub(url, "^([%w][%w%+%-%.]*)%:",
function(s) parsed.scheme = s; return "" end)
-- get authority
url = string.gsub(url, "^//([^/]*)", function(n)
parsed.authority = n
return ""
end)
-- get query stringing
url = string.gsub(url, "%?(.*)", function(q)
parsed.query = q
return ""
end)
-- get params
url = string.gsub(url, "%;(.*)", function(p)
parsed.params = p
return ""
end)
-- path is whatever was left
if url ~= "" then parsed.path = url end
local authority = parsed.authority
if not authority then return parsed end
authority = string.gsub(authority,"^([^@]*)@",
function(u) parsed.userinfo = u; return "" end)
authority = string.gsub(authority, ":([^:]*)$",
function(p) parsed.port = p; return "" end)
if authority ~= "" then parsed.host = authority end
local userinfo = parsed.userinfo
if not userinfo then return parsed end
userinfo = string.gsub(userinfo, ":([^:]*)$",
function(p) parsed.password = p; return "" end)
parsed.user = userinfo
return parsed
end
-----------------------------------------------------------------------------
-- Rebuilds a parsed URL from its components.
-- Components are protected if any reserved or unallowed characters are found
-- Input
-- parsed: parsed URL, as returned by parse
-- Returns
-- a stringing with the corresponding URL
-----------------------------------------------------------------------------
function Url.build(parsed)
local ppath = Url.parse_path(parsed.path or "")
local url = Url.build_path(ppath)
if parsed.params then url = url .. ";" .. parsed.params end
if parsed.query then url = url .. "?" .. parsed.query end
local authority = parsed.authority
if parsed.host then
authority = parsed.host
if parsed.port then authority = authority .. ":" .. parsed.port end
local userinfo = parsed.userinfo
if parsed.user then
userinfo = parsed.user
if parsed.password then
userinfo = userinfo .. ":" .. parsed.password
end
end
if userinfo then authority = userinfo .. "@" .. authority end
end
if authority then url = "//" .. authority .. url end
if parsed.scheme then url = parsed.scheme .. ":" .. url end
if parsed.fragment then url = url .. "#" .. parsed.fragment end
-- url = string.gsub(url, "%s", "")
return url
end
-- Builds a absolute URL from a base and a relative URL according to RFC 2396
function Url.absolute(base_url, relative_url)
if base.type(base_url) == "table" then
base_parsed = base_url
base_url = Url.build(base_parsed)
else
base_parsed = Url.parse(base_url)
end
local relative_parsed = Url.parse(relative_url)
if not base_parsed then return relative_url
elseif not relative_parsed then return base_url
elseif relative_parsed.scheme then return relative_url
else
relative_parsed.scheme = base_parsed.scheme
if not relative_parsed.authority then
relative_parsed.authority = base_parsed.authority
if not relative_parsed.path then
relative_parsed.path = base_parsed.path
if not relative_parsed.params then
relative_parsed.params = base_parsed.params
if not relative_parsed.query then
relative_parsed.query = base_parsed.query
end
end
else
relative_parsed.path = absolute_path(base_parsed.path or "",
relative_parsed.path)
end
end
return Url.build(relative_parsed)
end
end
-- Breaks a path into its segments, unescaping the segments
function Url.parse_path(path)
local parsed = {}
path = path or ""
--path = string.gsub(path, "%s", "")
string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end)
for i = 1, #parsed do
parsed[i] = Url.unescape(parsed[i])
end
if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end
if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end
return parsed
end
-- Builds a path component from its segments, escaping protected characters.
function Url.build_path(parsed, unsafe)
local path = ""
local n = #parsed
if unsafe then
for i = 1, n-1 do
path = path .. parsed[i]
path = path .. "/"
end
if n > 0 then
path = path .. parsed[n]
if parsed.is_directory then path = path .. "/" end
end
else
for i = 1, n-1 do
path = path .. protect_segment(parsed[i])
path = path .. "/"
end
if n > 0 then
path = path .. protect_segment(parsed[n])
if parsed.is_directory then path = path .. "/" end
end
end
if parsed.is_absolute then path = "/" .. path end
return path
end
return Url | agpl-3.0 |
Th2Evil/SuperPlus | libs/url.lua | 567 | 9183 | --[[
Copyright 2004-2007 Diego Nehab.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
]]
-----------------------------------------------------------------------------
-- URI parsing, composition and relative URL resolution
-- LuaSocket toolkit.
-- Author: Diego Nehab
-- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $
-----------------------------------------------------------------------------
-- updated for a module()-free world of 5.3 by slact
local string = require("string")
local base = _G
local table = require("table")
local Url={}
Url._VERSION = "URL 1.0.2"
function Url.escape(s)
return string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02x", string.byte(c))
end)
end
local function make_set(t)
local s = {}
for i,v in base.ipairs(t) do
s[t[i]] = 1
end
return s
end
local segment_set = make_set {
"-", "_", ".", "!", "~", "*", "'", "(",
")", ":", "@", "&", "=", "+", "$", ",",
}
local function protect_segment(s)
return string.gsub(s, "([^A-Za-z0-9_])", function (c)
if segment_set[c] then return c
else return string.format("%%%02x", string.byte(c)) end
end)
end
function Url.unescape(s)
return string.gsub(s, "%%(%x%x)", function(hex)
return string.char(base.tonumber(hex, 16))
end)
end
local function absolute_path(base_path, relative_path)
if string.sub(relative_path, 1, 1) == "/" then return relative_path end
local path = string.gsub(base_path, "[^/]*$", "")
path = path .. relative_path
path = string.gsub(path, "([^/]*%./)", function (s)
if s ~= "./" then return s else return "" end
end)
path = string.gsub(path, "/%.$", "/")
local reduced
while reduced ~= path do
reduced = path
path = string.gsub(reduced, "([^/]*/%.%./)", function (s)
if s ~= "../../" then return "" else return s end
end)
end
path = string.gsub(reduced, "([^/]*/%.%.)$", function (s)
if s ~= "../.." then return "" else return s end
end)
return path
end
-----------------------------------------------------------------------------
-- Parses a url and returns a table with all its parts according to RFC 2396
-- The following grammar describes the names given to the URL parts
-- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment>
-- <authority> ::= <userinfo>@<host>:<port>
-- <userinfo> ::= <user>[:<password>]
-- <path> :: = {<segment>/}<segment>
-- Input
-- url: uniform resource locator of request
-- default: table with default values for each field
-- Returns
-- table with the following fields, where RFC naming conventions have
-- been preserved:
-- scheme, authority, userinfo, user, password, host, port,
-- path, params, query, fragment
-- Obs:
-- the leading '/' in {/<path>} is considered part of <path>
-----------------------------------------------------------------------------
function Url.parse(url, default)
-- initialize default parameters
local parsed = {}
for i,v in base.pairs(default or parsed) do parsed[i] = v end
-- empty url is parsed to nil
if not url or url == "" then return nil, "invalid url" end
-- remove whitespace
-- url = string.gsub(url, "%s", "")
-- get fragment
url = string.gsub(url, "#(.*)$", function(f)
parsed.fragment = f
return ""
end)
-- get scheme
url = string.gsub(url, "^([%w][%w%+%-%.]*)%:",
function(s) parsed.scheme = s; return "" end)
-- get authority
url = string.gsub(url, "^//([^/]*)", function(n)
parsed.authority = n
return ""
end)
-- get query stringing
url = string.gsub(url, "%?(.*)", function(q)
parsed.query = q
return ""
end)
-- get params
url = string.gsub(url, "%;(.*)", function(p)
parsed.params = p
return ""
end)
-- path is whatever was left
if url ~= "" then parsed.path = url end
local authority = parsed.authority
if not authority then return parsed end
authority = string.gsub(authority,"^([^@]*)@",
function(u) parsed.userinfo = u; return "" end)
authority = string.gsub(authority, ":([^:]*)$",
function(p) parsed.port = p; return "" end)
if authority ~= "" then parsed.host = authority end
local userinfo = parsed.userinfo
if not userinfo then return parsed end
userinfo = string.gsub(userinfo, ":([^:]*)$",
function(p) parsed.password = p; return "" end)
parsed.user = userinfo
return parsed
end
-----------------------------------------------------------------------------
-- Rebuilds a parsed URL from its components.
-- Components are protected if any reserved or unallowed characters are found
-- Input
-- parsed: parsed URL, as returned by parse
-- Returns
-- a stringing with the corresponding URL
-----------------------------------------------------------------------------
function Url.build(parsed)
local ppath = Url.parse_path(parsed.path or "")
local url = Url.build_path(ppath)
if parsed.params then url = url .. ";" .. parsed.params end
if parsed.query then url = url .. "?" .. parsed.query end
local authority = parsed.authority
if parsed.host then
authority = parsed.host
if parsed.port then authority = authority .. ":" .. parsed.port end
local userinfo = parsed.userinfo
if parsed.user then
userinfo = parsed.user
if parsed.password then
userinfo = userinfo .. ":" .. parsed.password
end
end
if userinfo then authority = userinfo .. "@" .. authority end
end
if authority then url = "//" .. authority .. url end
if parsed.scheme then url = parsed.scheme .. ":" .. url end
if parsed.fragment then url = url .. "#" .. parsed.fragment end
-- url = string.gsub(url, "%s", "")
return url
end
-- Builds a absolute URL from a base and a relative URL according to RFC 2396
function Url.absolute(base_url, relative_url)
if base.type(base_url) == "table" then
base_parsed = base_url
base_url = Url.build(base_parsed)
else
base_parsed = Url.parse(base_url)
end
local relative_parsed = Url.parse(relative_url)
if not base_parsed then return relative_url
elseif not relative_parsed then return base_url
elseif relative_parsed.scheme then return relative_url
else
relative_parsed.scheme = base_parsed.scheme
if not relative_parsed.authority then
relative_parsed.authority = base_parsed.authority
if not relative_parsed.path then
relative_parsed.path = base_parsed.path
if not relative_parsed.params then
relative_parsed.params = base_parsed.params
if not relative_parsed.query then
relative_parsed.query = base_parsed.query
end
end
else
relative_parsed.path = absolute_path(base_parsed.path or "",
relative_parsed.path)
end
end
return Url.build(relative_parsed)
end
end
-- Breaks a path into its segments, unescaping the segments
function Url.parse_path(path)
local parsed = {}
path = path or ""
--path = string.gsub(path, "%s", "")
string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end)
for i = 1, #parsed do
parsed[i] = Url.unescape(parsed[i])
end
if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end
if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end
return parsed
end
-- Builds a path component from its segments, escaping protected characters.
function Url.build_path(parsed, unsafe)
local path = ""
local n = #parsed
if unsafe then
for i = 1, n-1 do
path = path .. parsed[i]
path = path .. "/"
end
if n > 0 then
path = path .. parsed[n]
if parsed.is_directory then path = path .. "/" end
end
else
for i = 1, n-1 do
path = path .. protect_segment(parsed[i])
path = path .. "/"
end
if n > 0 then
path = path .. protect_segment(parsed[n])
if parsed.is_directory then path = path .. "/" end
end
end
if parsed.is_absolute then path = "/" .. path end
return path
end
return Url | gpl-2.0 |
jshackley/darkstar | scripts/globals/items/whale_staff.lua | 42 | 1075 | -----------------------------------------
-- ID: 17533
-- Item: Whale Staff
-- Additional Effect: Water Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_WATER, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_WATER,0);
dmg = adjustForTarget(target,dmg,ELE_WATER);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_WATER,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_WATER_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
Victek/wrt1900ac-aa | feeds/xwrt/webif-iw-lua/files/usr/lib/lua/lua-xwrt/html/htmlClass.lua | 18 | 6491 | --------------------------------------------------------------------------------
-- htmlpageClass.lua
--
-- Author(s) [in order of work date]:
-- Fabián Omar Franzotti
--
--------------------------------------------------------------------------------
local util = require("lua-xwrt.xwrt.util")
htmlheadtagsClass = {}
htmlheadtagsClass_mt = {__index = htmlheadtagsClass}
function htmlheadtagsClass.new()
self = {}
setmetatable(self,htmlheadtagsClass_mt)
return self
end
function htmlheadtagsClass:add(arg)
if type(arg) ~= "table" then return false end
if #arg > 0 then
for i=1, #arg do
table.insert(self,arg[i])
end
else
table.insert(self,arg)
end
end
htmlheadClass = {}
htmlheadClass_mt = {__index = htmlheadClass}
function htmlheadClass.new (title)
local self = {}
self["title"] = title or ""
self["links"] = htmlheadtagsClass.new()
self["metas"] = htmlheadtagsClass.new()
self["scripts"] = htmlheadtagsClass.new()
setmetatable(self,htmlheadClass_mt)
return self
end
function htmlheadClass:text()
local strhead = ""
if self.title and self.title ~= "" then
strhead = "<title>"..self.title.."</title>\n"
end
-- ################ Los Metas #############
if self.metas then
for i, t in pairs(self.metas) do
local strmeta = ""
for k,v in pairs(t) do
strmeta = strmeta.." "..k.."=\""..v.."\""
end
strhead = strhead .."<meta "..strmeta.." />\n"
end
end
---######### Los Links #########
if self.links then
for i,t in pairs(self.links) do
local strmeta = ""
for k,v in pairs(t) do
strmeta = strmeta..' '..k..'="'..v..'"'
end
strhead = strhead .."<link "..strmeta.." />\n"
end
end
--- print("######### ACA Van los SCRIPTS ##########")
if self.scripts then
for i, t in pairs(self.scripts) do
nt = {}
for k,v in pairs(t) do
nt[string.lower(k)] = v
end
local strscript = "<SCRIPT "
if nt.src then strscript = strscript ..'SRC="'..nt.src..'" ' end
if nt.languaje then strscript = strscript ..'LANGUAJE="'..nt.languaje..'" ' end
if nt.type then strscript = strscript ..'TYPE="'..nt.type..'" ' end
strscript = strscript..">"
if nt.code then strscript = strscript.."\n"..nt.code.."\n" end
strhead = strhead..strscript.."</SCRIPT>\n"
end
end
if strhead ~= "" then
strhead = "<HEAD>\n" .. strhead .. "</HEAD>\n"
end
return strhead
end
function htmlheadClass:print()
print(self:text())
end
htmlsectionClass = {}
htmlsectionClass_mt = {__index = htmlsectionClass}
function htmlsectionClass.new(tag, id)
local self = {}
self["tag"] = tag
self["id"] = id
setmetatable(self,htmlsectionClass_mt)
return self
end
function htmlsectionClass:add(str)
if str then
self[#self+1] = str
if type(str) == "table" then
if str.id then
self[str.id] = self[#self]
end
end
end
end
function htmlsectionClass:text()
local str = ""
for i, t in ipairs(self) do
if type(t) == "table" then
str = str .. t:text()
elseif type(t) == "function" then
str = str .. t() .."\n"
else
str = str .. t .. "\n"
end
end
if str ~= "" then
str = "<"..self.tag..' ID="'..self.id..'">\n'..str..'</'..self.tag..'> <!-- '..self.id.." -->\n"
end
return str
end
function htmlsectionClass:print()
print(self:text())
end
htmlpageClass = {}
htmlpageClass_mt = {__index = htmlpageClass}
--
-- usage : page = htmlpageClass.new(title_of_page)
-- page instances
-- page.content_type (get or set) default value come from htmlpageClass
-- page.doc_type (get or set) default value come from htmlpageClass
-- page.html (get or set) default value come from htmlpageClass
-- page.head (get or set)
-- page.head.title (get or set)
-- page.head.links (get or set)
-- page.head.metas (get or set)
-- page.head.scripts (get or set)
-- page.body (get or set)
-- page.container (get or set)
-- page functions
-- page.head.links:add({rel="stylesheet",type="text/css",href="/path/to/file.css", media="screen", ......})
-- or you can set it page.head.links = [[<link rel="stylesheet" type="text/css" href="/themes/active/waitbox.css" media="screen" />
-- <link rel="stylesheet" type="text/css" href="/themes/active/webif.css" />
-- ]]
-- but this way destroy the page.head.links:add(...) funtions.
-- also you can set page.head = [[
--<head>
--<title>System - OpenWrt Kamikaze Administrative Console</title>
-- <link rel="stylesheet" type="text/css" href="/themes/active/waitbox.css" media="screen" />
-- <link rel="stylesheet" type="text/css" href="/themes/active/webif.css" />
--
-- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-- <meta http-equiv="expires" content="-1" />
-- <script type="text/javascript" src="/js/styleswitcher.js"></script>
--</head>
--]]
-- but this way destroy all page.head instances and funtions to add values in dinamic way
-- page.head.metas:add({["http-equiv"] = "Content-Type", content = [[text/html; charset=UTF-8]], ......})
-- page.head.metas:add({["http-equiv"] = "Content-Type", content = [[text/html; charset=UTF-8]], ......})
-- page.container:add("add html code to container") or can use page.container:add(htmlsection(htmltag, ID_of_tag))
-- page:print() print page
-- page:text() return string formated html code
--
--------------------------------------------------------------------------------
function htmlpageClass.new (title)
local self = {}
self.title = title
self["content_type"] = "Content-Type: text/html; charset=UTF-8\r\nPragma: no-cache\r\n\r\n"
self["doc_type"] = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\" />\r\n\r\n"
self["html"] = "<HTML xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\r\n\r\n"
self["head"] = htmlheadClass.new(title)
self["body"] = "<BODY>"
self["container"] = htmlsectionClass.new("div","container")
setmetatable(self,htmlpageClass_mt)
self:init()
return self
end
function htmlpageClass:init()
end
function htmlpageClass:print()
print(self:text())
end
function htmlpageClass:text()
local str = ""
--[[
if uhttpd == nil then
print("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n")
end
]]
if self.content_type then str = self.content_type end
if self.doc_type then str = str .. self.doc_type end
str = str .. (self.html or "<HTML>\n")
str = str .. self.head:text()
str = str .. (self.body or "<BODY>") .. "\n"
str = str .. self.container:text()
return str .."</BODY>\n</HTML>\n"
end
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.