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
UnfortunateFruit/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/LaisavieXBerlends1.lua
36
1080
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Laisavie X Berlends -- @zone 80 -- @pos 26 2 6 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again! 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
Badboy30/badboy30
plugins/groupmanager.lua
166
11272
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin!" end local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.' end local function set_description(msg, data) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = deskripsi save_data(_config.moderation.data, data) return 'Set group description to:\n'..deskripsi end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function set_rules(msg, data) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules return rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ') save_data(_config.moderation.data, data) return 'Group name has been locked' end end local function unlock_group_name(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end -- show group settings local function show_group_settings(msg, data) if not is_momod(msg) then return "For moderators only!" end local settings = data[tostring(msg.to.id)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end function run(msg, matches) --vardump(msg) if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] return create_group(msg) end if not is_chat_msg(msg) then return "This is not a group chat." end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'setabout' and matches[2] then deskripsi = matches[2] return set_description(msg, data) end if matches[1] == 'about' then return get_description(msg, data) end if matches[1] == 'setrules' then rules = matches[2] return set_rules(msg, data) end if matches[1] == 'rules' then return get_rules(msg, data) end if matches[1] == 'group' and matches[2] == 'lock' then --group lock * if matches[3] == 'name' then return lock_group_name(msg, data) end if matches[3] == 'member' then return lock_group_member(msg, data) end if matches[3] == 'photo' then return lock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == 'unlock' then --group unlock * if matches[3] == 'name' then return unlock_group_name(msg, data) end if matches[3] == 'member' then return unlock_group_member(msg, data) end if matches[3] == 'photo' then return unlock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == 'settings' then return show_group_settings(msg, data) end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end end end return { description = "Plugin to manage group chat.", usage = { "!creategroup <group_name> : Create a new group (admin only)", "!setabout <description> : Set group description", "!about : Read group description", "!setrules <rules> : Set group rules", "!rules : Read group rules", "!setname <new_name> : Set group name", "!setphoto : Set group photo", "!group <lock|unlock> name : Lock/unlock group name", "!group <lock|unlock> photo : Lock/unlock group photo", "!group <lock|unlock> member : Lock/unlock group member", "!group settings : Show group settings" }, patterns = { "^!(creategroup) (.*)$", "^!(setabout) (.*)$", "^!(about)$", "^!(setrules) (.*)$", "^!(rules)$", "^!(setname) (.*)$", "^!(setphoto)$", "^!(group) (lock) (.*)$", "^!(group) (unlock) (.*)$", "^!(group) (settings)$", "^!!tgservice (.+)$", "%[(photo)%]", }, run = run, } end
gpl-2.0
nesstea/darkstar
scripts/zones/Northern_San_dOria/npcs/HomePoint#2.lua
27
1277
----------------------------------- -- Area: Northern San dOria -- NPC: HomePoint#2 -- @pos 10 -0.2 95 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 4); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Selbina/npcs/Dohdjuma.lua
34
1424
----------------------------------- -- Area: Selbina -- NPC: Dohdjuma -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,DOHDJUMA_SHOP_DIALOG); stock = {0x0263,36, --Rye Flour 0x1393,233, --Scroll of Sheepfoe Mambo 0x1036,2335, --Eye Drops 0x1034,284, --Antidote 0x119D,10, --Distilled Water 0x1010,819, --Potion 0x43F3,10, --Lugworm 0x111A,54, --Selbina Milk 0x118A,432, --Pickled Herring 0x11CF,4485, --Herb Quus 0x0b32,9200} --Selbina Waystone 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
NezzKryptic/Wire-Extras
lua/weapons/gmod_tool/stools/wire_magnet.lua
3
6892
TOOL.Category = "Wire Extras/Physics/Force" TOOL.Name = "Wire Magnet" TOOL.Command = nil TOOL.ConfigName = nil TOOL.Tab = "Wire" if ( CLIENT ) then language.Add( "Tool.wire_magnet.name", "Wired Magnet Tool" ) language.Add( "Tool.wire_magnet.desc", "Spawns a realistic magnet for use with the wire system." ) language.Add( "Tool.wire_magnet.0", "Primary: Create/Update Magnet Secondary: Grab model to use" ) language.Add( "WiremagnetTool_len", "Effect Length:" ) language.Add( "WiremagnetTool_stren", "Effect Strength:" ) language.Add( "WiremagnetTool_propfil", "Prop Filter:" ) language.Add( "WiremagnetTool_metal", "Attract Metal Only:" ) language.Add( "WiremagnetTool_starton", "Start On:" ) language.Add( "undone_wiremagnet", "Undone Wire Magnet" ) language.Add( "sboxlimit_wire_magnet", "You've hit wired magnets limit!" ) end if (SERVER) then CreateConVar('sbox_maxwire_magnets', 30) CreateConVar('sbox_wire_magnets_maxstrength', 10000) CreateConVar('sbox_wire_magnets_maxlen', 300) CreateConVar('sbox_wire_magnets_tickrate', 0.01) end TOOL.ClientConVar[ "leng" ] = "100" TOOL.ClientConVar[ "streng" ] = "2000" TOOL.ClientConVar[ "propfilter" ] = "" TOOL.ClientConVar[ "targetOnlyMetal" ] = 0 TOOL.ClientConVar[ "startOn" ] = 1 TOOL.ClientConVar[ "model" ] = "models/props_junk/PopCan01a.mdl" cleanup.Register( "wire_magnets" ) function TOOL:LeftClick( trace ) if ( trace.Entity && trace.Entity:IsPlayer() ) then return false end // If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end if (CLIENT) then return true end local ply = self:GetOwner() local leng = tonumber(self:GetClientNumber( "leng" )) local strength = tonumber(self:GetClientNumber("streng" )) local propfilter = string.lower( self:GetClientInfo( "propfilter" ) ) local targetmetal = tonumber(self:GetClientNumber( "targetOnlyMetal" ))==1 local starton = tonumber(self:GetClientNumber( "startOn" ))==1 //update if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_realmagnet") then trace.Entity:SetModel(self.ClientConVar[ "model" ]) trace.Entity:SetLength(leng) trace.Entity:SetStrength(strength) trace.Entity:SetPropFilter(propfilter) trace.Entity:SetTargetOnlyMetal(targetmetal) trace.Entity:ShowOutput() return true end if ( !self:GetSWEP():CheckLimit( "wire_magnets" ) ) then return false end local wire_ball = MakeWireMagnet( ply, trace.HitPos, leng, strength, targetmetal, self.ClientConVar[ "model" ],propfilter) wire_ball:SetOn(util.tobool(starton)) local const = WireLib.Weld(wire_ball, trace.Entity, trace.PhysicsBone, true) local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 wire_ball:SetAngles(Ang) local min = wire_ball:OBBMins() wire_ball:SetPos( trace.HitPos - trace.HitNormal * min.z ) undo.Create("WireMagnet") undo.AddEntity( wire_ball ) undo.AddEntity( const ) undo.SetPlayer( ply ) undo.Finish() ply:AddCleanup( "wire_magnets", wire_ball ) ply:AddCleanup( "wire_magnets", const ) return true end function TOOL:RightClick(trace) if trace.Entity==nil or not trace.Entity:IsValid() then return false end if trace.Entity:IsWorld() then return false end self.ClientConVar[ "model" ]=trace.Entity:GetModel() return true end if (SERVER) then function MakeWireMagnet( ply, Pos, leng, strength, targetOnlyMetal,model,propfilter, starton ) if ( !ply:CheckLimit( "wire_magnets" ) ) then return nil end local wire_ball = ents.Create( "gmod_wire_realmagnet" ) if (!wire_ball:IsValid()) then return false end wire_ball:SetPos( Pos ) wire_ball:PhysicsInit( SOLID_VPHYSICS ) wire_ball:SetMoveType( MOVETYPE_VPHYSICS ) wire_ball:SetSolid( SOLID_VPHYSICS ) wire_ball:SetStrength( strength ) wire_ball:SetLength( leng ) wire_ball:SetTargetOnlyMetal( targetOnlyMetal ) wire_ball:SetPropFilter( propfilter ) wire_ball:SetPlayer( ply ) wire_ball:SetModel(model) wire_ball:Spawn() wire_ball:SetOn(starton and tobool(starton)) ply:AddCount( "wire_magnets", wire_ball ) return wire_ball end duplicator.RegisterEntityClass("gmod_wire_realmagnet", MakeWireMagnet, "Pos", "Len", "Strength", "TargetOnlyMetal", "Model", "PropFilter", "On" ) end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool.wire_magnet.name", Description = "#Tool.wire_magnet.desc" }) panel:AddControl("ComboBox", { Label = "#Presets", MenuButton = "1", Folder = "wire_magnet", Options = { Default = { wire_magnet_len = "100", wire_magnet_strength = "2000", wire_magnet_targetOnlyMetal = "0", wire_magnet_starton = "1", wire_magnet_propfilter = "" } }, CVars = { [0] = "wire_magnet_len", [1] = "wire_magnet_strength", [2] = "wire_magnet_targetOnlyMetal", [3] = "wire_magnet_starton", [4] = "wire_magnet_propfilter" } }) panel:AddControl("Slider", { Label = "#WiremagnetTool_len", Type = "Float", Min = "1", Max = "100", Command = "wire_magnet_leng" }) panel:AddControl("Slider", { Label = "#WiremagnetTool_stren", Type = "Float", Min = "1", Max = "2000", Command = "wire_magnet_streng" }) panel:AddControl("CheckBox", { Label = "#WiremagnetTool_metal", Command = "wire_magnet_targetOnlyMetal" }) panel:AddControl("CheckBox", { Label = "#WiremagnetTool_starton", Command = "wire_magnet_starton" }) panel:AddControl("TextBox",{ Label="#WiremagnetTool_propfil", MaxLen=500, Text="", command="wire_magnet_propfilter" }) end function TOOL:UpdateGhostWireMagnet( ent, player ) if ( !ent || !ent:IsValid() ) then return end local tr = util.GetPlayerTrace( player, player:GetAimVector() ) local trace = util.TraceLine( tr ) if (!trace.Hit || trace.Entity:IsPlayer() ) then ent:SetNoDraw( true ) return end if (trace.Entity:GetClass()=="gmod_wire_realmagnet") then ent:SetNoDraw( true ) return end local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 local min = ent:OBBMins() ent:SetPos( trace.HitPos - trace.HitNormal * min.z ) ent:SetAngles( Ang ) ent:SetNoDraw( false ) end function TOOL:Think() if (!self.GhostEntity || !self.GhostEntity:IsValid() || string.lower(self.GhostEntity:GetModel()) != string.lower(self.ClientConVar[ "model" ])) then local _model = self.ClientConVar[ "model" ] if (!_model) then return end self:MakeGhostEntity( _model, Vector(0,0,0), Angle(0,0,0) ) end self:UpdateGhostWireMagnet( self.GhostEntity, self:GetOwner() ) end
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Northern_San_dOria/npcs/Morunaude.lua
36
1428
----------------------------------- -- Area: Northern San d'Oria -- NPC: Morunaude -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x027a); 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
Mashape/kong
kong/db/schema/entities/upstreams.lua
1
7354
local Schema = require "kong.db.schema" local typedefs = require "kong.db.schema.typedefs" local utils = require "kong.tools.utils" local null = ngx.null local validate_name = function(name) local p = utils.normalize_ip(name) if not p then return nil, "Invalid name; must be a valid hostname" end if p.type ~= "name" then return nil, "Invalid name; no ip addresses allowed" end if p.port then return nil, "Invalid name; no port allowed" end return true end local hash_on = Schema.define { type = "string", default = "none", one_of = { "none", "consumer", "ip", "header", "cookie" } } local http_statuses = Schema.define { type = "array", elements = { type = "integer", between = { 100, 999 }, }, } local seconds = Schema.define { type = "number", between = { 0, 65535 }, } local positive_int = Schema.define { type = "integer", between = { 1, 2 ^ 31 }, } local positive_int_or_zero = Schema.define { type = "integer", between = { 0, 2 ^ 31 }, } local check_type = Schema.define { type = "string", one_of = { "tcp", "http", "https", "grpc", "grpcs" }, default = "http", } local check_verify_certificate = Schema.define { type = "boolean", default = true, } local NO_DEFAULT = {} local healthchecks_config = { active = { type = "http", timeout = 1, concurrency = 10, http_path = "/", https_sni = NO_DEFAULT, https_verify_certificate = true, healthy = { interval = 0, -- 0 = probing disabled by default http_statuses = { 200, 302 }, successes = 0, -- 0 = disabled by default }, unhealthy = { interval = 0, -- 0 = probing disabled by default http_statuses = { 429, 404, 500, 501, 502, 503, 504, 505 }, tcp_failures = 0, -- 0 = disabled by default timeouts = 0, -- 0 = disabled by default http_failures = 0, -- 0 = disabled by default }, }, passive = { type = "http", healthy = { http_statuses = { 200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 300, 301, 302, 303, 304, 305, 306, 307, 308 }, successes = 0, }, unhealthy = { http_statuses = { 429, 500, 503 }, tcp_failures = 0, -- 0 = circuit-breaker disabled by default timeouts = 0, -- 0 = circuit-breaker disabled by default http_failures = 0, -- 0 = circuit-breaker disabled by default }, }, } local types = { type = check_type, timeout = seconds, concurrency = positive_int, interval = seconds, successes = positive_int_or_zero, tcp_failures = positive_int_or_zero, timeouts = positive_int_or_zero, http_failures = positive_int_or_zero, http_path = typedefs.path, http_statuses = http_statuses, https_sni = typedefs.sni, https_verify_certificate = check_verify_certificate, } local function gen_fields(tbl) local fields = {} local count = 0 for name, default in pairs(tbl) do local typ = types[name] local def, required if default == NO_DEFAULT then default = nil required = false tbl[name] = nil end if typ then def = typ{ default = default, required = required } else def = { type = "record", fields = gen_fields(default), default = default } end count = count + 1 fields[count] = { [name] = def } end return fields, tbl end local healthchecks_fields, healthchecks_defaults = gen_fields(healthchecks_config) local r = { name = "upstreams", primary_key = { "id" }, endpoint_key = "name", fields = { { id = typedefs.uuid, }, { created_at = typedefs.auto_timestamp_s }, { name = { type = "string", required = true, unique = true, custom_validator = validate_name }, }, { algorithm = { type = "string", default = "round-robin", one_of = { "consistent-hashing", "least-connections", "round-robin" }, }, }, { hash_on = hash_on }, { hash_fallback = hash_on }, { hash_on_header = typedefs.header_name, }, { hash_fallback_header = typedefs.header_name, }, { hash_on_cookie = { type = "string", custom_validator = utils.validate_cookie_name }, }, { hash_on_cookie_path = typedefs.path{ default = "/", }, }, { slots = { type = "integer", default = 10000, between = { 10, 2^16 }, }, }, { healthchecks = { type = "record", default = healthchecks_defaults, fields = healthchecks_fields, }, }, { tags = typedefs.tags }, { host_header = typedefs.host }, }, entity_checks = { -- hash_on_header must be present when hashing on header { conditional = { if_field = "hash_on", if_match = { match = "^header$" }, then_field = "hash_on_header", then_match = { required = true }, }, }, { conditional = { if_field = "hash_fallback", if_match = { match = "^header$" }, then_field = "hash_fallback_header", then_match = { required = true }, }, }, -- hash_on_cookie must be present when hashing on cookie { conditional = { if_field = "hash_on", if_match = { match = "^cookie$" }, then_field = "hash_on_cookie", then_match = { required = true }, }, }, { conditional = { if_field = "hash_fallback", if_match = { match = "^cookie$" }, then_field = "hash_on_cookie", then_match = { required = true }, }, }, -- hash_fallback must be "none" if hash_on is "none" { conditional = { if_field = "hash_on", if_match = { match = "^none$" }, then_field = "hash_fallback", then_match = { one_of = { "none" }, }, }, }, -- when hashing on cookies, hash_fallback is ignored { conditional = { if_field = "hash_on", if_match = { match = "^cookie$" }, then_field = "hash_fallback", then_match = { one_of = { "none" }, }, }, }, -- hash_fallback must not equal hash_on (headers are allowed) { conditional = { if_field = "hash_on", if_match = { match = "^consumer$" }, then_field = "hash_fallback", then_match = { one_of = { "none", "ip", "header", "cookie" }, }, }, }, { conditional = { if_field = "hash_on", if_match = { match = "^ip$" }, then_field = "hash_fallback", then_match = { one_of = { "none", "consumer", "header", "cookie" }, }, }, }, -- different headers { distinct = { "hash_on_header", "hash_fallback_header" }, }, }, -- This is a hack to preserve backwards compatibility with regard to the -- behavior of the hash_on field, and have it take place both in the Admin API -- and via declarative configuration. shorthands = { { algorithm = function(value) if value == "least-connections" then return { algorithm = value, hash_on = null, } else return { algorithm = value, } end end }, -- Then, if hash_on is set to some non-null value, adjust the algorithm -- field accordingly. { hash_on = function(value) if value == null then return { hash_on = "none" } elseif value == "none" then return { hash_on = value, algorithm = "round-robin", } else return { hash_on = value, algorithm = "consistent-hashing", } end end }, }, } return r
apache-2.0
Lordlotter/AdvanSource
plugins/all.lua
32
4484
do local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.\nUse /type in the group to set type.' end return group_type end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(msg,target,receiver) local data = load_data(_config.moderation.data) if not data[tostring(target)] then return end local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type if group_type == "Group" or group_type == "Realm" then local settings = show_group_settingsmod(msg,target) text = text.."\n\n"..settings elseif group_type == "SuperGroup" then local settings = show_supergroup_settingsmod(msg,target) text = text..'\n\n'..settings end local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local mutes_list = mutes_list(target) text = text.."\n\n"..mutes_list local muted_user_list = muted_user_list(target) text = text.."\n\n"..muted_user_list local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./system/chats/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./system/chats/all/"..target.."all.txt", ok_cb, false) return end local function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(msg,target,receiver) end if not is_owner(msg) or not is_vip(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) return all(msg,msg.to.id,receiver) end end return { patterns = { "^[#!/](all)$", "^[#!/](all) (%d+)$" }, run = run } end
gpl-2.0
UnfortunateFruit/darkstar
scripts/globals/items/noble_lady.lua
17
1392
----------------------------------------- -- ID: 4485 -- Item: noble_lady -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 3 -- Mind -5 -- Charisma 3 ----------------------------------------- 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,4485); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -5); target:addMod(MOD_CHR, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -5); target:delMod(MOD_CHR, 3); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Cloister_of_Flames/bcnms/sugar-coated_directive.lua
27
1824
---------------------------------------- -- Area: Cloister of Flames -- BCNM: Sugar Coated Directive (ASA-4) -- @pos -721 0 -598 207 ---------------------------------------- package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil; ---------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Cloister_of_Flames/TextIDs"); ---------------------------------------- -- 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:hasCompleteQuest(ASA,SUGAR_COATED_DIRECTIVE)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); 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); if (csid == 0x7d01) then player:addExp(400); player:setVar("ASA4_Scarlet","1"); end end;
gpl-3.0
microbang/luasocket
etc/qp.lua
59
1025
----------------------------------------------------------------------------- -- Little program to convert to and from Quoted-Printable -- LuaSocket sample files -- Author: Diego Nehab -- RCS ID: $Id: qp.lua,v 1.5 2004/06/17 21:46:22 diego Exp $ ----------------------------------------------------------------------------- local ltn12 = require("ltn12") local mime = require("mime") local convert arg = arg or {} local mode = arg and arg[1] or "-et" if mode == "-et" then local normalize = mime.normalize() local qp = mime.encode("quoted-printable") local wrap = mime.wrap("quoted-printable") convert = ltn12.filter.chain(normalize, qp, wrap) elseif mode == "-eb" then local qp = mime.encode("quoted-printable", "binary") local wrap = mime.wrap("quoted-printable") convert = ltn12.filter.chain(qp, wrap) else convert = mime.decode("quoted-printable") end local source = ltn12.source.chain(ltn12.source.file(io.stdin), convert) local sink = ltn12.sink.file(io.stdout) ltn12.pump.all(source, sink)
mit
malortie/gmod-addons
th_weapons/lua/weapons/weapon_th_chainsaw/shared.lua
1
24122
-- Only enable this addon if HL:S is mounted. if !IsHL1Mounted() then return end -- Define a global variable to ease calling base class methods. DEFINE_BASECLASS( 'weapon_th_base' ) SWEP.Base = 'weapon_th_base' SWEP.PrintName = 'Chainsaw (Cut)' SWEP.Author = 'Marc-Antoine (malortie) Lortie' SWEP.Contact = '' SWEP.Purpose = '' SWEP.Instructions = '' SWEP.Category = 'They Hunger' SWEP.Slot = 0 SWEP.SlotPos = 4 SWEP.ViewModelFOV = 90 SWEP.ViewModelFlip = false SWEP.ViewModel = 'models/th/v_chainsaw/v_chainsaw.mdl' SWEP.WorldModel = 'models/th/w_chainsaw/w_chainsaw.mdl' SWEP.PModel = 'models/th/p_chainsaw/p_chainsaw.mdl' SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = 100 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = AMMO_CLASS_TH_SAWGAS SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = true SWEP.Secondary.Ammo = 'none' SWEP.PullbackSound = 'weapon_th_chainsaw.pullback' SWEP.EngineStartSound = 'weapon_th_chainsaw.engine_start' SWEP.EngineRunSound = 'weapon_th_chainsaw.engine_run' SWEP.EngineShutdownSound = 'weapon_th_chainsaw.engine_shutdown' SWEP.AttackSound = 'weapon_th_chainsaw.attack' SWEP.SwingSound = 'weapon_th_chainsaw.swing' SWEP.SwingOffSound = 'weapon_th_chainsaw.swingoff' -- The rate at which to decrement gas when -- the chainsaw is on. SWEP.AmmoDrainRate = 0.8 -- The rate at which to inflict damage when -- the chainsaw is on. SWEP.AttackRate = 0.1 -- The minimum facing to inflict damage to a -- target (as a dot product result). SWEP.FacingDotMin = 0.5 -- The chainsaw trace length. SWEP.TraceDistance = 32 -- Minimum and maximum hull size to perform -- trace attack. SWEP.TraceHullMins = Vector( -16, -16, -16 ) SWEP.TraceHullMaxs = Vector( 16, 16, -16 ) ------------------------------------- -- Skill ConVars ------------------------------------- -- Represents the amount of damage casted. local chainsaw_damage_idle = GetConVar( 'sk_th_plr_dmg_chainsaw_idle' ) or CreateConVar( 'sk_th_plr_dmg_chainsaw_idle', '2' ) local chainsaw_damage_swing = GetConVar( 'sk_th_plr_dmg_chainsaw_swing' ) or CreateConVar( 'sk_th_plr_dmg_chainsaw_swing', '10' ) --[[--------------------------------------------------------- Setup networked variables. -----------------------------------------------------------]] function SWEP:SetupDataTables() BaseClass.SetupDataTables( self ) self.Weapon:NetworkVar( 'Float', 3, 'PowerupTime' ) self.Weapon:NetworkVar( 'Float', 4, 'NextAmmoDrainTime' ) self.Weapon:NetworkVar( 'Float', 5, 'NextAttackTime' ) self.Weapon:NetworkVar( 'Float', 6, 'LastFireTime' ) self.Weapon:NetworkVar( 'Float', 7, 'PullbackSoundTime' ) self.Weapon:NetworkVar( 'Float', 8, 'NextAttackSoundTime' ) self.Weapon:NetworkVar( 'Float', 9, 'NextEngineSoundTime' ) self.Weapon:NetworkVar( 'Float', 10, 'NextViewPunchTime' ) self.Weapon:NetworkVar( 'Float', 11, 'SwingAttackTime' ) self.Weapon:NetworkVar( 'Bool', 1, 'EngineOn' ) end --[[--------------------------------------------------------- Perform Client/Server initialization. -----------------------------------------------------------]] function SWEP:Initialize() BaseClass.Initialize( self ) self.Weapon:SetPowerupTime( 0 ) self.Weapon:SetNextAmmoDrainTime( 0 ) self.Weapon:SetNextAttackTime( 0 ) self.Weapon:SetLastFireTime( 0 ) self.Weapon:SetPullbackSoundTime( 0 ) self.Weapon:SetNextAttackSoundTime( 0 ) self.Weapon:SetNextEngineSoundTime( 0 ) self.Weapon:SetNextViewPunchTime( 0 ) self.Weapon:SetSwingAttackTime( 0 ) self.Weapon:SetEngineOn( false ) self:SetHoldType( "physgun" ) end --[[--------------------------------------------------------- Called when weapon tries to holster. @param wep The weapon we are trying switch to. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:Holster( wep ) if self:IsEngineOn() then self:ToggleEngine() end self:ResetAttackSwing() return BaseClass.Holster( self, wep ) end --[[--------------------------------------------------------- Called when player has just switched to this weapon. @return true to allow switching away from this weapon using lastinv command. -----------------------------------------------------------]] function SWEP:Deploy() return BaseClass.Deploy( self ) end --[[--------------------------------------------------------- Called when the reload key is pressed. -----------------------------------------------------------]] function SWEP:Reload() return true end --[[--------------------------------------------------------- Check if the weapon can do a primary attack. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:CanPrimaryAttack() return true end --[[--------------------------------------------------------- Primary weapon attack. -----------------------------------------------------------]] function SWEP:PrimaryAttack() if !self:CanPrimaryAttack() then return end self:AttackSwing( self:IsEngineOn() ) end --[[--------------------------------------------------------- Check if the weapon can do a secondary attack. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:CanSecondaryAttack() if self:Ammo1() <= 0 then return false end if self:IsStartingUp() then return true end return true end --[[--------------------------------------------------------- Secondary weapon attack. -----------------------------------------------------------]] function SWEP:SecondaryAttack() if !self:CanSecondaryAttack() then return end self:ToggleEngine() end --[[--------------------------------------------------------- Called every frame. -----------------------------------------------------------]] function SWEP:Think() local owner = self.Owner if !IsValid( owner ) then return end self:UpdateChainsaw( self:IsEngineOn() ) self:WeaponIdle() end --[[--------------------------------------------------------- Play weapon idle animation. -----------------------------------------------------------]] function SWEP:WeaponIdle() if !self:CanIdle() then return end local seq = self:LookupSequence( 'idle1' ) local vm = self.Owner:GetViewModel() vm:SendViewModelMatchingSequence( seq ) self.Weapon:SetNextIdle( CurTime() + self:ViewModelSequenceDuration() ) end --[[--------------------------------------------------------- Return engine state. @return true if the chainsaw engine is running. @return false otherwise. -----------------------------------------------------------]] function SWEP:IsEngineOn() return self.Weapon:GetEngineOn() end --[[--------------------------------------------------------- Return startup state. @return true if the chainsaw engine is starting up. @return false otherwise. -----------------------------------------------------------]] function SWEP:IsStartingUp() return self.Weapon:GetPowerupTime() != 0 end --[[--------------------------------------------------------- Return swing attack state. @return true if the owner is performing the swing attack. @return false otherwise. -----------------------------------------------------------]] function SWEP:IsInSwingAttack() return self.Weapon:GetInAttack() == 1 end --[[--------------------------------------------------------- Start pulling back the chainsaw handle. -----------------------------------------------------------]] function SWEP:Pullback() self:SendWeaponAnim( ACT_VM_PULLBACK ) self.Weapon:SetPowerupTime( CurTime() + self:ViewModelSequenceDuration() ) self.Weapon:SetPullbackSoundTime( CurTime() + 78.0 / 60.0 ) self.Weapon:SetEngineOn( false ) self.Weapon:SetNextPrimaryFire( self:GetPowerupTime() ) self.Weapon:SetNextSecondaryFire( self:GetPowerupTime() ) self.Weapon:SetNextIdle( self:GetPowerupTime() ) end --[[--------------------------------------------------------- Called when the startup is finished. -----------------------------------------------------------]] function SWEP:FinishStartup() self.Weapon:SetPowerupTime( 0 ) self.Weapon:SetPullbackSoundTime( 0 ) end --[[--------------------------------------------------------- Called every frame to update the startup. -----------------------------------------------------------]] function SWEP:UpdateStartup() -- Play pullback sound. if self.Weapon:GetPullbackSoundTime() != 0 && self.Weapon:GetPullbackSoundTime() <= CurTime() then self.Weapon:EmitSound( self.PullbackSound ) self.Weapon:SetPullbackSoundTime( 0 ) end if self:GetPowerupTime() > CurTime() then return end self:FinishStartup() self:StartEngine() end --[[--------------------------------------------------------- Start the chainsaw's engine. -----------------------------------------------------------]] function SWEP:StartEngine() self.Weapon:EmitSound( self.EngineStartSound ) self.Weapon:SetNextAttackTime( 0 ) self.Weapon:SetNextAmmoDrainTime( CurTime() ) -- Start using ammo as soon as possible. self.Weapon:SetEngineOn( true ) self:SetNextPrimaryFire( CurTime() + 0.25 ) self:SetNextSecondaryFire( CurTime() + 0.25 ) self.Weapon:SetNextIdle( CurTime() + RandomFloat( 10, 15 ) ) end --[[--------------------------------------------------------- Shutdown the chainsaw's engine. -----------------------------------------------------------]] function SWEP:ShutdownEngine() self:StopLoopingSounds() self.Weapon:EmitSound( self.EngineShutdownSound ) self.Weapon:SetNextAttackTime( 0 ) self.Weapon:SetNextAmmoDrainTime( 0 ) self.Weapon:SetLastFireTime( 0 ) self.Weapon:SetEngineOn( false ) self:SetNextPrimaryFire( CurTime() + 0.5 ) self:SetNextSecondaryFire( CurTime() + 0.5 ) self.Weapon:SetNextIdle( CurTime() ) end --[[--------------------------------------------------------- Either start or shutdown the chainsaw's engine. -----------------------------------------------------------]] function SWEP:ToggleEngine() if !self:IsEngineOn() then self:Pullback() else self:ShutdownEngine() end end --[[--------------------------------------------------------- Return the secondary attack activity. @return The activity to use for secondary attack. -----------------------------------------------------------]] function SWEP:GetPrimaryAttackActivity() return ACT_VM_SECONDARYATTACK end --[[--------------------------------------------------------- Perform the same task as @SendWeaponAnim, but only resets the animation if finished. @param activity Activity to play. -----------------------------------------------------------]] function SWEP:SendWeaponAnimRepeat( activity ) if self:GetActivity() != activity || self:IsViewModelSequenceFinished() then self:SendWeaponAnim( activity ) end end --[[--------------------------------------------------------- Obtain the tip position and angles, relative to the owner's shoot position. @param position Output resulting position. @param angles Output resulting angles. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:GetTipPositionAndAngles( position, angles ) local vm = self.Owner:GetViewModel() if !vm then return false end assert( isvector( position ) ) assert( isangle( angles ) ) --[[ Buggy!! --]] --local attach = vm:GetAttachment( 1 ) --if !attach then return false end --]] local pos = self.Owner:GetShootPos() local ang = self.Owner:EyeAngles() pos = pos + ang:Forward() * 32 + ang:Right() * 2 - ang:Up() * 6 angles.p = ang.p angles.y = ang.y angles.r = ang.r position.x = pos.x position.y = pos.y position.z = pos.z return true end --[[--------------------------------------------------------- Obtain the tip position and vectors, relative to the owner's shoot position. @param position Output resulting position. @param forward Output forward directional vector. @param right Output right directional vector. @param up Output up directional vector. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:GetTipPositionAndVectors( position, forward, right, up ) local angles = Angle() if !self:GetTipPositionAndAngles( position, angles ) then return false end local f, r, u = angles:Forward(), angles:Right(), angles:Up() forward.x = f.x; forward.y = f.y; forward.z = f.z; right.x = r.x; right.y = r.y; right.z = r.z; up.x = u.x; up.y = u.y; up.z = u.z; return true end --[[--------------------------------------------------------- Inflict damage to an entity. @param tr Trace result. @param victim Entity to apply damage to. @param damage Amount of damage to inflict. @param damageType Type of damage to inflict. -----------------------------------------------------------]] function SWEP:InflictDamage( tr, victim, damage, damageType ) local dmginfo = DamageInfo() dmginfo:SetInflictor( self ) dmginfo:SetAttacker( self.Owner ) dmginfo:SetDamage( damage ) dmginfo:SetDamagePosition( tr.HitPos ) dmginfo:SetDamageType( damageType ) victim:DispatchTraceAttack( dmginfo, tr ) end --[[--------------------------------------------------------- Start chainsaw swing attack. @param EngineOn Engine state, either true or false. -----------------------------------------------------------]] function SWEP:AttackSwing( EngineOn ) local owner = self.Owner if !IsValid( owner ) then return end self:SendWeaponAnim( self:GetPrimaryAttackActivity() ) if EngineOn then self.Weapon:EmitSound( self.SwingSound ) self.Weapon:SetInAttack( 1 ) self.Weapon:SetSwingAttackTime( CurTime() + self:ViewModelSequenceDuration() ) else self.Weapon:EmitSound( self.SwingOffSound ) end self.Weapon:SetNextPrimaryFire( CurTime() + self:ViewModelSequenceDuration() ) self.Weapon:SetNextSecondaryFire( CurTime() + self:ViewModelSequenceDuration() ) self.Weapon:SetNextIdle( CurTime() + self:ViewModelSequenceDuration() ) end --[[--------------------------------------------------------- Reset chainsaw swing variables. -----------------------------------------------------------]] function SWEP:ResetAttackSwing() self.Weapon:SetInAttack( 0 ) self.Weapon:SetSwingAttackTime( 0 ) self.Weapon:SetNextIdle( CurTime() ) end --[[--------------------------------------------------------- Called every frame to update the swing attack. PRECONDITION: The chainsaw engine must be on. -----------------------------------------------------------]] function SWEP:UpdateAttackSwing() assert( self:IsEngineOn() ) if self.Weapon:GetNextAttackTime() > CurTime() then return end self.Weapon:SetNextAttackTime( CurTime() + self.AttackRate ) local position, forward, right, up = Vector(), Vector(), Vector(), Vector() if !self:GetTipPositionAndVectors( position, forward, right, up ) then --print( Format( '%s:UpdateAttackSwing: Unable to get tip attachment. Returning...', self:GetClass() ) ) return end local pHurt = self:ChainsawTraceHullAttack( position, self.TraceDistance, Vector( -32, -32, -32 ), Vector( 32, 32, 32 ), chainsaw_damage_swing:GetFloat(), DMG_SLASH ) if IsValid( pHurt ) then end end --[[--------------------------------------------------------- Check if the owner is facing the entity. @param entity Entity to test dot product against with. @return true if entity is in view field. @return false if entity is not in view field. -----------------------------------------------------------]] function SWEP:IsOwnerFacingEntity( entity ) local eyeDir2D, entityDir2D eyeDir2D = self.Owner:EyeAngles():Forward() eyeDir2D.z = 0; eyeDir2D:Normalize() entityDir2D = entity:GetPos() - self.Owner:GetPos() entityDir2D.z = 0; entityDir2D:Normalize() local dot = eyeDir2D:Dot( entityDir2D ) return dot > self.FacingDotMin end --[[--------------------------------------------------------- Perform a trace attack and apply damage to any touched entity. @param vecSrc The position to trace from. @param distance The trace length. @param mins Minimum trace volume. @param mins Maximum trace volume. @param damage Amount of damage to apply. @param damageType Type of damage to apply. @return Entity that was hit. @return Trace result structure. -----------------------------------------------------------]] function SWEP:ChainsawTraceHullAttack( vecSrc, distance, mins, maxs, damage, damageType ) vecSrc = vecSrc or self.Owner:GetShootPos() distance = distance or 0 mins = mins or Vector( -2, -2, -1 ) maxs = maxs or Vector( 2, 2, 1 ) damage = damage or 0 damageType = damageType or DMG_SLASH local angles = self.Owner:EyeAngles() local forward = angles:Forward() local vecEnd = vecSrc + forward * distance local tr = util.TraceLine({ start = vecSrc, endpos = vecEnd, filter = {self, self.Owner}, mask = MASK_SHOT_HULL }) if tr.Fraction >= 1.0 then tr = util.TraceHull({ start = vecSrc, endpos = vecEnd, mins = mins, maxs = maxs, filter = {self, self.Owner}, mask = MASK_SHOT_HULL }) if tr.Fraction < 1.0 then -- Calculate the point of intersection of the line (or hull) and the object we hit -- This is and approximation of the "best" intersection if !tr.Hit || tr.HitWorld then tr = FindHullIntersection( vecSrc, tr, VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX, { self, self.Owner } ) end vecEnd = tr.HitPos -- This is the point on the actual surface (the hull could have hit space) end end if IsValid( tr.Entity ) && self:IsOwnerFacingEntity( tr.Entity ) then self:InflictDamage( tr, tr.Entity, damage, damageType ) end return tr.Entity, tr end --[[--------------------------------------------------------- Punch the player's angles. -----------------------------------------------------------]] function SWEP:AddViewKick() local owner = self.Owner if !IsValid( owner ) then return end owner:ViewPunch( Angle( RandomFloat( -2, 2 ), RandomFloat( -2, 2 ), 0 ) ) end --[[--------------------------------------------------------- Called when the chainsaw hit a non living entity. @param tr Trace result. -----------------------------------------------------------]] function SWEP:OnHitNonLiving( tr ) self:AddViewKick() UTIL_ImpactEffect( tr.HitPos, tr ) if self.Weapon:GetNextPrimaryFire() <= CurTime() && self.Weapon:GetNextSecondaryFire() <= CurTime() then self:SendWeaponAnimRepeat( ACT_VM_PRIMARYATTACK_1 ) end self.Weapon:SetNextIdle( CurTime() + RandomFloat( 10, 15 ) ) end --[[--------------------------------------------------------- Called when the chainsaw hit a living entity. @param tr Trace result. @param entity Hit entity. -----------------------------------------------------------]] function SWEP:OnHitLiving( tr, entity ) if self.Weapon:GetNextPrimaryFire() <= CurTime() && self.Weapon:GetNextSecondaryFire() <= CurTime() then self:SendWeaponAnimRepeat( ACT_VM_PRIMARYATTACK_2 ) end self.Weapon:SetNextIdle( CurTime() + RandomFloat( 10, 15 ) ) end --[[--------------------------------------------------------- Called every frame to make additional impact effect. @param materialName Name of the surface material. -----------------------------------------------------------]] function SWEP:DoSurfaceImpactEffect( materialName ) if surfaceName == 'metal' then UTIL_Sparks( tr.HitPos, tr ) end end --[[--------------------------------------------------------- Called every frame to update the viewpunch caused by the chainsaw engine. -----------------------------------------------------------]] function SWEP:UpdateIdleViewPunch() if self.Weapon:GetNextViewPunchTime() > CurTime() then return end self.Weapon:SetNextViewPunchTime( CurTime() + 0.1 ) local owner = self.Owner if !IsValid( owner ) then return end owner:ViewPunch( Angle( RandomFloat( -0.1, 0.1 ), RandomFloat( -0.1, 0.1 ), 0 ) ) end --[[--------------------------------------------------------- Called every frame to check if the chainsaw is hitting an entity. -----------------------------------------------------------]] function SWEP:IdleCastRadialDamage() if self.Weapon:GetNextAttackTime() > CurTime() then return end self.Weapon:SetNextAttackTime( CurTime() + self.AttackRate ) local position, forward, right, up = Vector(), Vector(), Vector(), Vector() if !self:GetTipPositionAndVectors( position, forward, right, up ) then --print( Format( '%s:UpdateAttackSwing: Unable to get tip attachment. Returning...', self:GetClass() ) ) return end local pHurt, tr = self:ChainsawTraceHullAttack( position, self.TraceDistance, self.TraceHullMins, self.TraceHullMaxs, chainsaw_damage_idle:GetFloat(), DMG_SLASH ) if tr.Hit then local surfaceName = util.GetSurfacePropName( tr.SurfaceProps ) self:DoSurfaceImpactEffect( surfaceName ) if pHurt:IsWorld() || IsProp( pHurt ) then self:OnHitNonLiving( tr ) else self:OnHitLiving( tr, pHurt ) end end end --[[--------------------------------------------------------- Called every frame to check the ammo consumption. -----------------------------------------------------------]] function SWEP:UpdateGasConsumption() if self.Weapon:GetNextAmmoDrainTime() > CurTime() then return end self.Weapon:SetNextAmmoDrainTime( CurTime() + self.AmmoDrainRate ) self:TakePrimaryAmmo( 1, self.Weapon:GetPrimaryAmmoType() ) end --[[--------------------------------------------------------- Check if the chainsaw can still be active. @return true to keep the chainsaw engine active. @return false to shutdown the chainsaw engine. -----------------------------------------------------------]] function SWEP:CheckChainsawCanRunAgain() if self:Ammo1() <= 0 then return false end return true end --[[--------------------------------------------------------- Called every frame to update the attack sound. -----------------------------------------------------------]] function SWEP:UpdateAttackSound() if self.Weapon:GetNextAttackSoundTime() > CurTime() then return end self.Weapon:SetNextAttackSoundTime( CurTime() + SoundDuration( self.AttackSound ) ) self.Weapon:EmitSound( self.AttackSound ) end --[[--------------------------------------------------------- Called every frame to update the engine sound. -----------------------------------------------------------]] function SWEP:UpdateEngineSound() if self.Weapon:GetNextEngineSoundTime() > CurTime() then return end self.Weapon:SetNextEngineSoundTime( CurTime() + SoundDuration( self.EngineRunSound ) ) self.Weapon:EmitSound( self.EngineRunSound ) end --[[--------------------------------------------------------- Stop all weapons sounds. -----------------------------------------------------------]] function SWEP:StopLoopingSounds() self.Weapon:StopSound( self.AttackSound ) self.Weapon:StopSound( self.EngineRunSound ) end --[[--------------------------------------------------------- Called every frame to update the chainsaw. @param EngineOn Engine state, either true or false. -----------------------------------------------------------]] function SWEP:UpdateChainsaw( EngineOn ) -- Play pullback sound. if self.Weapon:GetPullbackSoundTime() != 0 && self.Weapon:GetPullbackSoundTime() <= CurTime() then self.Weapon:EmitSound( self.PullbackSound ) self.Weapon:SetPullbackSoundTime( 0 ) end if EngineOn then local position, forward, right, up = Vector(), Vector(), Vector(), Vector() if !self:GetTipPositionAndVectors( position, forward, right, up ) then return end if !self:CheckChainsawCanRunAgain() then self:ToggleEngine() else if self:IsInSwingAttack() then if self.Weapon:GetSwingAttackTime() > CurTime() then self:UpdateAttackSwing() else self:ResetAttackSwing() end else self:UpdateIdleViewPunch() self:IdleCastRadialDamage() end self:UpdateGasConsumption() self:UpdateEngineSound() end elseif self:IsStartingUp() then self:UpdateStartup() end end
gpl-3.0
Mashape/kong
spec/02-integration/03-db/03-plugins_spec.lua
1
9140
local helpers = require "spec.helpers" assert:set_parameter("TableFormatLevel", 10) local UUID_PATTERN = "%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x" for _, strategy in helpers.each_strategy() do describe("kong.db [#" .. strategy .. "]", function() local db, bp, service, route local global_plugin lazy_setup(function() bp, db = helpers.get_db_utils(strategy, { "routes", "services", "plugins", }) global_plugin = db.plugins:insert({ name = "key-auth", protocols = { "http" }, }) assert.truthy(global_plugin) end) describe("Plugins #plugins", function() before_each(function() service = bp.services:insert() route = bp.routes:insert({ service = { id = service.id }, protocols = { "tcp" }, sources = { { ip = "127.0.0.1" } }, }) end) describe(":insert()", function() it("checks composite uniqueness", function() local route = bp.routes:insert({ methods = {"GET"} }) local plugin, err, err_t = db.plugins:insert({ name = "key-auth", route = { id = route.id }, }) assert.is_nil(err_t) assert.is_nil(err) assert.matches(UUID_PATTERN, plugin.id) assert.is_number(plugin.created_at) plugin.id = nil plugin.created_at = nil assert.same({ config = { hide_credentials = false, run_on_preflight = true, key_in_body = false, key_names = { "apikey" }, }, run_on = "first", protocols = { "grpc", "grpcs", "http", "https" }, enabled = true, name = "key-auth", route = { id = route.id, }, }, plugin) plugin, err, err_t = db.plugins:insert({ name = "key-auth", route = route, }) assert.falsy(plugin) assert.match("UNIQUE violation", err) assert.same("unique constraint violation", err_t.name) assert.same([[UNIQUE violation detected on '{service=null,]] .. [[name="key-auth",route={id="]] .. route.id .. [["},consumer=null}']], err_t.message) end) it("does not validate when associated to an incompatible route, or a service with only incompatible routes", function() local plugin, _, err_t = db.plugins:insert({ name = "key-auth", protocols = { "http" }, route = { id = route.id }, }) assert.is_nil(plugin) assert.equals(err_t.fields.protocols, "must match the associated route's protocols") local plugin, _, err_t = db.plugins:insert({ name = "key-auth", protocols = { "http" }, service = { id = service.id }, }) assert.is_nil(plugin) assert.equals(err_t.fields.protocols, "must match the protocols of at least one route pointing to this Plugin's service") end) it("validates when associated to a service with no routes", function() local service_with_no_routes = bp.services:insert() local plugin, _, err_t = db.plugins:insert({ name = "key-auth", protocols = { "http" }, service = { id = service_with_no_routes.id }, }) assert.truthy(plugin) assert.is_nil(err_t) end) end) describe(":update()", function() it("checks composite uniqueness", function() local route = bp.routes:insert({ methods = {"GET"} }) local plugin, err, err_t = db.plugins:insert({ name = "key-auth", route = { id = route.id }, }) assert.is_nil(err_t) assert.is_nil(err) assert.matches(UUID_PATTERN, plugin.id) assert.is_number(plugin.created_at) plugin.id = nil plugin.created_at = nil assert.same({ config = { hide_credentials = false, run_on_preflight = true, key_in_body = false, key_names = { "apikey" }, }, run_on = "first", protocols = { "grpc", "grpcs", "http", "https" }, enabled = true, name = "key-auth", route = { id = route.id, }, }, plugin) plugin, err, err_t = db.plugins:insert({ name = "key-auth", route = route, }) assert.falsy(plugin) assert.match("UNIQUE violation", err) assert.same("unique constraint violation", err_t.name) assert.same([[UNIQUE violation detected on '{service=null,]] .. [[name="key-auth",route={id="]] .. route.id .. [["},consumer=null}']], err_t.message) end) end) it("returns an error when updating mismatched plugins", function() local p, _, err_t = db.plugins:update({ id = global_plugin.id }, { route = { id = route.id } }) assert.is_nil(p) assert.equals(err_t.fields.protocols, "must match the associated route's protocols") local p, _, err_t = db.plugins:update({ id = global_plugin.id }, { service = { id = service.id } }) assert.is_nil(p) assert.equals(err_t.fields.protocols, "must match the protocols of at least one route pointing to this Plugin's service") end) end) describe(":upsert()", function() it("returns an error when upserting mismatched plugins", function() local p, _, err_t = db.plugins:upsert({ id = global_plugin.id }, { route = { id = route.id }, protocols = { "http" } }) assert.is_nil(p) assert.equals(err_t.fields.protocols, "must match the associated route's protocols") local p, _, err_t = db.plugins:upsert({ id = global_plugin.id }, { service = { id = service.id }, protocols = { "http" } }) assert.is_nil(p) assert.equals(err_t.fields.protocols, "must match the protocols of at least one route pointing to this Plugin's service") end) end) describe(":load_plugin_schemas()", function() it("loads custom entities with specialized methods", function() local ok, err = db.plugins:load_plugin_schemas({ ["plugin-with-custom-dao"] = true, }) assert.truthy(ok) assert.is_nil(err) assert.same("I was implemented for " .. strategy, db.custom_dao:custom_method()) end) it("reports failure with missing plugins", function() local ok, err = db.plugins:load_plugin_schemas({ ["missing"] = true, }) assert.falsy(ok) assert.match("missing plugin is enabled but not installed", err, 1, true) end) it("reports failure with bad plugins #4392", function() local ok, err = db.plugins:load_plugin_schemas({ ["legacy-plugin-bad"] = true, }) assert.falsy(ok) assert.match("failed converting legacy schema for legacy-plugin-bad", err, 1, true) end) it("succeeds with good plugins", function() local ok, err = db.plugins:load_plugin_schemas({ ["legacy-plugin-good"] = true, }) assert.truthy(ok) assert.is_nil(err) local foo = { required = false, type = "map", keys = { type = "string" }, values = { type = "string" }, default = { foo = "boo", bar = "bla", } } local config = { type = "record", required = true, fields = { { foo = foo }, foo = foo, } } local consumer = { type = "foreign", reference = "consumers", eq = ngx.null, schema = db.consumers.schema, } assert.same({ name = "legacy-plugin-good", fields = { { config = config }, { consumer = consumer }, config = config, consumer = consumer, } }, db.plugins.schema.subschemas["legacy-plugin-good"]) end) end) end) -- kong.db [strategy] end
apache-2.0
UnfortunateFruit/darkstar
scripts/globals/weaponskills/power_slash.lua
30
1662
----------------------------------- -- Power Slash -- Great Sword weapon skill -- Skill level: 30 -- Delivers a single-hit attack. params.crit varies with TP. -- Modifiers: STR:60% ; VIT:60% -- 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 = 1; --ftp damage mods (for Damage Varies with TP; lines are calculated in the function params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; --wscs are in % so 0.2=20% params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.2; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; --critical mods, again in % (ONLY USE FOR CRITICAL HIT VARIES WITH TP) params.crit100 = 0.2; params.crit200=0.4; params.crit300=0.6; params.canCrit = true; --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.str_wsc = 0.6; params.vit_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
DavisDev/OneInstaller
system/engine.lua
1
69299
--files.encrypt("system/libs/lib_wave.lua") --files.desencrypt("system/configs/hosting.ini") -- ## Recursos A Cargar ## icon = { -- ## Logos ## one = kernel.loadimage("system/theme/one_ico.png"), -- ## Barra Superior ## wifi = image.load("system/theme/wifi.png",14,11), ms = kernel.loadimage("system/theme/ms.png"), cats = { -- ## Categorias ## kernel.loadimage("system/theme/cats/1.png"), kernel.loadimage("system/theme/cats/2.png"), kernel.loadimage("system/theme/cats/3.png"), kernel.loadimage("system/theme/cats/4.png"), kernel.loadimage("system/theme/cats/5.png"), kernel.loadimage("system/theme/cats/6.png"), kernel.loadimage("system/theme/cats/7.png"), kernel.loadimage("system/theme/cats/8.png") }, stars = kernel.loadimage("system/theme/stars.png",105,20), flags = { -- ## Banderas Visor ## cats = kernel.loadimage("system/theme/flags/cats.png",27,12), model = kernel.loadimage("system/theme/flags/model.png",27,12), lang = kernel.loadimage("system/theme/flags/lang.png",21,12) }, -- ## Indicadores laterales Visor ## dl = kernel.loadimage("system/theme/dl.png"), wn = kernel.loadimage("system/theme/wn.png"), ss = kernel.loadimage("system/theme/ss.png"), -- ## Def Icon´s 0 ## prx = { kernel.loadimage("system/theme/icon0/prx_1.png"), kernel.loadimage("system/theme/icon0/prx_2.png"), kernel.loadimage("system/theme/icon0/prx_3.png"), kernel.loadimage("system/theme/icon0/prx_4.png"), }, hb = { kernel.loadimage("system/theme/icon0/hb_1.png"), kernel.loadimage("system/theme/icon0/hb_2.png"), kernel.loadimage("system/theme/icon0/hb_3.png"), kernel.loadimage("system/theme/icon0/hb_4.png"), }, ud = { kernel.loadimage("system/theme/icon0/update_1.png"), kernel.loadimage("system/theme/icon0/update_2.png"), kernel.loadimage("system/theme/icon0/update_3.png"), }, -- ## ## fb = kernel.loadimage("system/theme/fb.png"), fi = kernel.loadimage("system/theme/fi.png"), ur = kernel.loadimage("system/theme/unrar.png"), dup = kernel.loadimage("system/theme/dup.png"), myscreens = {} } -- ## Sonidos ## sound_scroll = kernel.loadsound("system/sounds/scroll.mp3") sound_go= kernel.loadsound("system/sounds/go.mp3") sound_ext = kernel.loadsound("system/sounds/ext.mp3") sound_back = kernel.loadsound("system/sounds/back.mp3") -- ## Configuraciones ## if not files.exists("ms0:/oneinstaller/") then files.mkdir("ms0:/oneinstaller/") end if not files.exists("ms0:/oneinstaller/notices/") then files.mkdir("ms0:/oneinstaller/notices/") end if not files.exists("ms0:/oneinstaller/tmp/") then files.mkdir("ms0:/oneinstaller/tmp/") end if not files.exists("ms0:/oneinstaller/lang/") then files.mkdir("ms0:/oneinstaller/lang/"); files.copy("system/langs/spa.lua","ms0:/oneinstaller/lang/spa.lua"); files.copy("system/langs/eng.lua","ms0:/oneinstaller/lang/eng.lua"); files.copy("system/langs/fre.lua","ms0:/oneinstaller/lang/fre.lua"); end pathini="ms0:/oneinstaller/config.ini" -- pendiente pues sera para dejarlo en una ruta absoluta function write_table(pathini, tb) local file = io.open(pathini, "w+") file:write("config = {\n") for s,t in pairs(tb) do if type(t) == "string" then file:write(string.format('"%s",\n', tostring(t))) else file:write(string.format('%s,\n', tostring(t))) end end file:write("}") file:close() end -- 1: col bar, 2: Root Wallpaper, pendiente: device work config = {7,""} if files.exists(pathini) then dofile(pathini) else write_table(pathini, config) end --background = kernel.loadimage(config[2]) -- Back Definido if not background then background = kernel.loadimage("system/theme/default.jpg") -- el fondo end lastnowversion = 210 lastupdateversion = 210 -- ## Librerias ## kernel.dofile("system/libs/utf8.lua")-- Manipulacion de Strings utf8 kernel.dofile("system/libs/lib_osc.lua")-- Funciones de osciladores osc.init(1,255,4) -- creamos un oscilador, minimo, maximo, salto kernel.dofile("system/libs/lib_grafics.lua") -- funciones patrones graficos kernel.dofile("system/libs/lib_wave.lua")-- Funcion Grafica de Ola WAVE.init("system/theme/wave.png") kernel.dofile("system/libs/http.lua") -- Funciones de peticion http box.init("system/theme/") -- inicia la libreria box mensajes! :D -- ## Modulos ## -- SE ESTA ELIMINANDO :D --[[ kernel.dofile("system/modules/comments.lua") kernel.dofile("system/modules/manager_plugins.lua")]] -- ## Colores Temas ## MyBarColors={ -- Colores disponibles de barras color.new(0,0,0,55), --1 BlackTrans color.new(139,0,0,135), --2 RedTrans color.new(0,255,0,95), --3 GreenTrnas color.new(255,255,0,95), --4 YellowTrans color.new(64,224,208,135), --5 TurquoiseTrans color.new(105,105,105,135), --6 GrayTrans color.new(255,255,255,100), --7 WhiteTrans color.new(55,72,251,105), --8 BlueTrans color.new(255,130,0,100) --9 orangeTrans } MyTxtColors = color.white -- color de texto blanca default MyTxtShadow = color.black -- sombra de texto negra "default" MyScrColor = color.new(0,72,251) --Brillo de seleccion MyLineColor = color.white --[[ -- Pendiente pues a mi no me interesan los usuarios go xDDDDD MyDevs = {"ms0:/","ef0:/"} -- Segun cual almacenamiento se trabaje if files.exist(MyDevs[1]) and config[2] == 1 then OverDev = MyDevs[1] else OverDev = MyDevs[2] end]] -- ## Algunas Funciones Graficas dedicadas a el ahorro de lineas ## function draw_back(mode,trans)-- Dibuja el Fondo y efecto if trans == nil then trans = 255 end -- no se declara entonces 255 if background then background:blit(0,0,trans) end -- existe? entonces dibujamos el fondo if mode == nil then WAVE.blit(2) end -- no se declara entonces dibujamos la ola end __refreshMs = true -- constante encargada del reload de la ms Batt = 0 function draw_topbar() draw.fillrect(5,5,470,20,barcolor) screen.print(10,8,lang.oi.." v2",0.7,MyTxtColors,MyTxtShadow) draw_batt(450,10) screen.print(400,10,Batt.."%",0.7,MyTxtColors,MyTxtShadow) draw.line(395,5,395,25,MyLineColor) local intensidad_wifi = wlan.strength() if wlan.isconnected() then if intensidad_wifi > 75 then frame = 3 elseif intensidad_wifi > 50 then frame = 2 elseif intensidad_wifi > 25 then frame = 1 else frame = 0 end icon.wifi:blitsprite(370,10,frame) screen.print(320,10,intensidad_wifi.."%",0.7,MyTxtColors,MyTxtShadow) else --icon.wifi[1]:blit(370,10) icon.wifi:blitsprite(370,10,0) screen.print(320,10,"0%",0.7,MyTxtColors,MyTxtShadow) end draw.line(318,5,318,25,MyLineColor) screen.print(243,8,os.getdate():sub(18),0.6,MyTxtColors,MyTxtShadow) draw.line(238,5,238,25,MyLineColor) icon.ms:blit(218,7) if __refreshMs then __refreshMs = false MS = os.infoms0() if MS.free then MS.txtfree = files.sizeformat(MS.free) end end screen.print(160,8,MS.txtfree,0.6,MyTxtColors,MyTxtShadow) draw.line(156,5,156,25,MyLineColor) end --Dibuja la bateria __refreshBatt = 110 -- constante encargada del reload de la battery function draw_batt(x,y) __refreshBatt = __refreshBatt + 1 if __refreshBatt > 100 then __refreshBatt = 0 if batt.exists () then Batt = batt.lifepercent() if Batt == "-" then draw.fillrect(x-3,y+2,3,5,color.new(255,255,255)) draw.fillrect(x,y,20,10,color.new(255,255,255)) Batt = "0" return end else draw.fillrect(x-3,y+2,3,5,color.white) draw.fillrect(x,y,20,10,color.white) return end end if Batt > 75 then thecolor = color.new(0,255,0) elseif Batt > 50 then thecolor = color.new(100,200,0) elseif Batt > 25 then thecolor = color.new(200,100,0) else thecolor = color.new(255,0,0) end draw.fillrect(x-3,y+2,3,5,color.white) draw.fillrect(x,y,20,10,color.white) draw.fillrect(x+1,y+1,18,8,thecolor) end -- ## Lenguajes ## OverLang = os.language() if OverLang == "ENGLISH" and files.exists("ms0:/oneinstaller/lang/eng.lua") then-- en kernel.dofile("ms0:/oneinstaller/lang/eng.lua") elseif OverLang == "FRENCH" and files.exists("ms0:/oneinstaller/lang/fre.lua") then-- fr kernel.dofile("ms0:/oneinstaller/lang/fre.lua") elseif OverLang == "SPANISH" and files.exists("ms0:/oneinstaller/lang/spa.lua") then-- esp kernel.dofile("ms0:/oneinstaller/lang/spa.lua") else--eng kernel.dofile("system/langs/eng.lua") end -- ## Set Scroll Menu ## scroll.set(1,lang.menu,4) -- ## Menu Principal ## -- ## Constantes: OverTop = false -- estamos sobre el top o en las opciones? PosTop = 0 -- numero de top donde estamos situados OverVita = false -- estamos en algo que tenga que ver con vita? OverCat = 1 -- Categoria sobre la que estamos -- ## Rutas de los configuradores de plugs ## plugs_path = {"ms0:/seplugins/vsh.txt","ms0:/seplugins/game.txt","ms0:/seplugins/pops.txt"} if os.cfw() == "eCFW ARK" then local sra = files.listdirs("ms0:/psp/savedata/") if sra then local i = 1 while i <= #sra do--for i=1, #sra do if files.exists(sra[i].path.."/FLASH0.ARK") then plugs_path[4] = sra[i].path.."/plugins.txt" -- ruta a el configurador de plug break end i = i + 1 end end end function show_menu() draw_back() -- Dibuja el fondo draw_topbar() -- dibuja la barra superior icon.one:blit(15,25) -- el logo :P grafics.multi_rect(4,5,111,165,35,5,barcolor) --Patron 4 rect opciones -- ## Impresion de Opciones ## local y,numpos,i = 121,1,scroll[1].ini while i <= scroll[1].lim do-- for i=scroll[1].ini,scroll[1].lim do if i==scroll[1].sel and not OverTop then draw.fillrect(5,71+40*numpos,165,35,color.new(0,72,251,osc.get())) end screen.print(87,y,lang.menu[i] or "",0.7,MyTxtColors,MyTxtShadow,512) -- centrado numpos,y,i = numpos + 1, y + 40,i+1 end -- ## Impresion Barra Lateral ## if scroll[1].maxim> 4 then local pos_height = math.max(155/scroll[1].maxim, 5) draw.fillrect(175, 111, 5, 155, barcolor) draw.fillrect(175, 111+((155-pos_height)/(scroll[1].maxim-1))*(scroll[1].sel-1), 5, pos_height, MyScrColor) end -- ## Mostramos Los Top Three ## trans = osc.get() if PosTop == 1 and Top_1 then --size(285,115) Top_1:blit(190,30,255) grafics.selectrect(190,30,285,115,color.new(0,72,251,trans)) elseif Top_1 then Top_1:blit(190,30,100) end if PosTop == 2 and Top_2 then --size(140,115) Top_2:blit(335,152,255) grafics.selectrect(335,152,140,115,color.new(0,72,251,trans)) elseif Top_2 then Top_2:blit(335,152,100) end if PosTop == 3 and Top_3 then Top_3:blit(190,152,255) grafics.selectrect(190,152,140,115,color.new(0,72,251,trans)) elseif Top_3 then Top_3:blit(190,152,100) end end function ctrls_menu() if OverTop then -- estamos sobre los top entonces nos dezplasamos sobre ellos if buttons.up and (PosTop == 2 or PosTop == 3) then sound_scroll:play() PosTop = 1 end if buttons.down and PosTop == 1 then sound_scroll:play() PosTop = math.random(2,3) end if buttons.right and PosTop == 3 then sound_scroll:play() PosTop = 2 end if buttons.left and (PosTop == 3 or PosTop == 1) then sound_scroll:play() PosTop = 0 OverTop = false end if buttons.left and PosTop == 2 then sound_scroll:play() PosTop = 3 end if buttons.cross then sound_go:play() OverCat = 9 -- categoria de los top scroll.set(3,Lista[OverCat],4) scroll[3].sel = PosTop scroll.set(4,Lista[OverCat][scroll[3].sel].description,8) Seccion = 4 end else -- estamos sobre las opciones if buttons.down or buttons.held.r then osc.defmax() sound_scroll:play() scroll.down(1) end if buttons.up or buttons.held.l then osc.defmax() sound_scroll:play() scroll.up(1) end if buttons.right then sound_scroll:play() PosTop = 1 OverTop = true end if buttons.cross then sound_go:play() if scroll[1].sel == 1 then -- PSP/VITA Seccion = 2 elseif scroll[1].sel == 2 then -- Explorer Files explorer.main() elseif scroll[1].sel == 3 then -- Manager Of Plugins box.new("Not Available","In this version, this option was not added") elseif scroll[1].sel == 4 then -- Send/Read Comments box.new("Not Available","In this version, this option was not added") --[[ local debugtab = "" for s,t in pairs(ContactList) do debugtab = debugtab.."key:"..s.." value:"..type(t).."{\n" for ys,xs in pairs(t) do debugtab = debugtab.."key:"..ys.." value:"..xs.."\n" end debugtab = debugtab.."}\n" end for s,t in pairs(ContactList[1] or {}) do debugtab = debugtab.."key:"..s.." value:"..t.."\n" end local y = 10 while true do buttons.read() if buttons.held.up then y = y + 4 elseif buttons.held.down then y = y - 4 end if buttons.start then break end screen.print(10,y,debugtab) screen.flip() end usb.mstick ( ) os.restart()]] --scroll.set("contact",ContactList,4) --ContactList[1].msg = wordwrap(ContactList[1].msg,214,0.7) --Seccion = 6 elseif scroll[1].sel == 5 then -- Configs Seccion = 8 elseif scroll[1].sel == 6 then -- History App local myscreenback = screen.buffertoimage() about({lang.aboutapp,lang.aboutteam,lang.aboutthks}) myscreenback:blit(0,0) elseif scroll[1].sel == 7 then -- EXIT kernel.exit() end end end end -- ## Set Scroll Categories ## scroll.set(2,lang.cats,4) -- ## Lista de Categorias ## function show_cats() draw_back() -- Dibuja el fondo draw_topbar() -- dibuja la barra superior icon.one:blit(15,25) -- el logo :P grafics.multi_rect(4,5,111,165,35,5,barcolor) --Patron 4 rect opciones -- ## Impresion De Categorias ## local y,numpos,i= 121,1,scroll[2].ini while i <= scroll[2].lim do-- for i=scroll[2].ini,scroll[2].lim do -- mayor rendimiento if i==scroll[2].sel then draw.fillrect(5,71+40*numpos,165,35,color.new(0,72,251,osc.get())) end --Brillo screen.print(87,y,lang.cats[i] or "",0.7,MyTxtColors,MyTxtShadow,512) numpos,y,i = numpos + 1, y + 40,i+1 end -- ## Impresion Barra Lateral ## if scroll[2].maxim> 4 then local pos_height = math.max(155/scroll[2].maxim, 5) draw.fillrect(175, 111, 5, 155, barcolor) draw.fillrect(175, 111+((155-pos_height)/(scroll[2].maxim-1))*(scroll[2].sel-1), 5, pos_height, MyScrColor) end -- ## Detalles Graficos ## draw.fillrect(190,30,285,235,barcolor)--Fondo de la barra lateral screen.print(337,55,"--"..lang.cats[scroll[2].sel].."--",0.7,MyTxtColors,MyTxtShadow,512) -- titulo de la categoria if scroll[2].sel < 8 then screen.print(337,75,lang.cnts..#Lista[scroll[2].sel],0.7,MyTxtColors,MyTxtShadow,512) end --contenidos de este reposito --#Lista[scroll[2].sel+large] icon.cats[scroll[2].sel]:blit(190+98,30+74) -- img correspondiente a la categoria screen.print(337,232,lang.lupr,0.6,MyTxtColors,MyTxtShadow,512) -- ultima vez actualizado del reposito screen.print(337,247,(lastupdaterepo or "unk"),0.6,MyTxtColors,MyTxtShadow,512) end function ctrls_cats() if buttons.down or buttons.held.r then osc.defmax() sound_scroll:play() scroll.down(2) end if buttons.up or buttons.held.l then osc.defmax() sound_scroll:play() scroll.up(2) end if buttons.circle then-- retorna al menu sound_back:play() Seccion = 1 end if buttons.cross and scroll[2].sel==8 then sound_go:play() search() -- la busqueda de un contenido elseif buttons.cross then sound_go:play() OverCat = scroll[2].sel scroll.set(3,Lista[OverCat],4) Seccion = 3 -- pasa a el recorredor de contenido end end function search() Lista[8] = {} -- limpiamos busquedas txt_to_search = osk.init(lang.find, "") if txt_to_search then for u=1,7 do for t=1,#Lista[u] do w,x = string.find(Lista[u][t].title:lower(), txt_to_search,1,true) if w then --Llenamos la tabla si se encuentra alguna coincidencia Lista[8][#Lista[8]+1] = Lista[u][t] end end end -- end if #Lista[8] > 0 then scroll.set(3,Lista[8],4) Seccion = 3 end end end -- ## Lista Contenidos ## --Pendiente en este beta no hay licencias XD --for i=1,#lang.lic do -- ajustamos licencias a el espacio --lang.lic[i] = wordwrap(lang.lic[i],155,0.7) --end listscroll = {200,200} function show_ltcnt() draw_back() -- Dibuja el fondo draw_topbar() -- dibuja la barra superior icon.one:blit(15,25) -- el logo :P grafics.multi_rect(4,190,30,280,55,5,barcolor) --Patron 4 rect opciones -- ## Impresion De Listado ## local y,numpos,i = 55,0,scroll[3].ini while i <= scroll[3].lim do --for i=scroll[3].ini,scroll[3].lim do -- Aunmento en un 75% de rendimiento al ser while if i==scroll[3].sel then -- Brillo, y scrolls draw.fillrect(190,30+60*numpos,280,55,color.new(0,72,251,osc.get())) listscroll[2] = screen.print(listscroll[2],y+5,(Lista[OverCat][i].description[1] or ""),0.7,MyTxtColors,MyTxtShadow,__SLEFT,260) else -- Normal screen.clip(200,y,260,25) screen.print(200,y+5,Lista[OverCat][i].description[1] or "",0.7,MyTxtColors,MyTxtShadow) screen.clip() end listscroll[1] = screen.print(listscroll[1],y-15,i..". "..Lista[OverCat][i].title or "",0.7,MyTxtColors,MyTxtShadow,__SLEFT,260) numpos,y, i = numpos + 1, y + 60, i+1 end -- ## Impresion Barra Lateral ## if scroll[3].maxim> 4 then local pos_height = math.max(235/scroll[3].maxim, 5) draw.fillrect(475, 30, 5, 235, barcolor) draw.fillrect(475, 30+((235-pos_height)/(scroll[3].maxim-1))*(scroll[3].sel-1), 5, pos_height, MyScrColor) end draw.fillrect(5,111,165,156,barcolor)--Pendiente en este beta no hay licencias XD --screen.print(8,103,lang.lic[scroll[2].sel],0.7,MyTxtColors,MyTxtShadow) -- licencia de categoria end function ctrls_ltcnt() if buttons.held.r or buttons.down then scroll.down(3) end if buttons.released.r or buttons.down then sound_scroll:play() end if buttons.held.l or buttons.up then scroll.up(3) end if buttons.released.l or buttons.up then sound_scroll:play() end if buttons.circle then sound_back:play() Seccion = 2 end if buttons.cross then sound_go:play() scroll.set(4,Lista[OverCat][scroll[3].sel].description,8) Seccion = 4 end end function cleanicon0() Lista[OverCat][scroll[3].sel].ico = nil collectgarbage() end --## Visor Contenidos ## function ctrls_vrcnt() if buttons.r then cleanicon0() scroll.down(3) scroll.set(4,Lista[OverCat][scroll[3].sel].description,8) sound_scroll:play() end if buttons.l then cleanicon0() scroll.up(3) scroll.set(4,Lista[OverCat][scroll[3].sel].description,8) sound_scroll:play() end if buttons.circle and OverCat == 9 then cleanicon0() sound_back:play() Seccion = 1 end--Entramos por una noticia de la pagina principal if buttons.circle and OverCat ~= 9 then cleanicon0() sound_back:play() Seccion = 3 end--Entramos por la lista de manera normal xD if buttons.cross then -- descargar sound_go:play() local state = false if Lista[OverCat][scroll[3].sel].outrep then --os.message(Lista[OverCat][scroll[3].sel].url) state = DownInstall(Lista[OverCat][scroll[3].sel].url,Lista[OverCat][scroll[3].sel].title) else --os.message(Servidor.."apps/"..Lista[OverCat][scroll[3].sel].id..".zip") state = DownInstall(Servidor.."apps/"..Lista[OverCat][scroll[3].sel].id..".zip",Lista[OverCat][scroll[3].sel].title) end if state then __refreshMs = true box.api(send_vote) -- Los obligamos a votar ya que fue un error haber hecho su eleccion xD else sound_back:play() end--Rewrite_NewPlugs()--respaldar_Plugs() end --[[if buttons.select then box.api(send_vote) end]] if buttons.held.down then scroll.down(4) elseif buttons.held.up then scroll.up(4) end if buttons.square then if Lista[OverCat][scroll[3].sel].captures > 0 then -- hay capturas? if downss() then -- pedimos si retorna true pues las obtuvimos y pasamos a mostrarlas scroll.set(5,icon.myscreens,3) Seccion = 5 else -- ya valio no obtuvimos nada box.new(lang.errors.titlescreens,lang.errors.serverlost) end end end end -- Entramos en el dialogo de La noticia o app myscroll = {title = 15,version = 15,author = 85} function show_vrcnt() draw_back() -- Dibuja el fondo draw_topbar() -- dibuja la barra superior draw.fillrect(5,30,330,237,barcolor) -- contenedor de la descripcion eh icono eh flags -- ## Title & Version & Author ## screen.print(15,45,lang.title,0.7,MyTxtColors,MyTxtShadow) myscroll["title"] = screen.print(myscroll["title"],60,Lista[OverCat][scroll[3].sel].title,0.7,MyTxtColors,MyTxtShadow,__SLEFT,160) screen.print(15,80,lang.version,0.7,MyTxtColors,MyTxtShadow) myscroll["version"] = screen.print(myscroll["version"],95,Lista[OverCat][scroll[3].sel].version,0.7,MyTxtColors,MyTxtShadow,__SLEFT,60) screen.print(85,80,lang.author,0.7,MyTxtColors,MyTxtShadow) myscroll["author"] = screen.print(myscroll["author"],95,Lista[OverCat][scroll[3].sel].author,0.7,MyTxtColors,MyTxtShadow,__SLEFT,90) -- ## ICON ## if not Lista[OverCat][scroll[3].sel].ico then if files.exists("ms0:/oneinstaller/notices/"..Lista[OverCat][scroll[3].sel].id..".png") then Lista[OverCat][scroll[3].sel].ico = image.load("ms0:/oneinstaller/notices/"..Lista[OverCat][scroll[3].sel].id..".png") else if OverCat == 5 or OverCat == 14 then local alternative = math.random(1,4) Lista[OverCat][scroll[3].sel].ico = image.copy(icon.prx[alternative]) elseif OverCat == 4 or OverCat == 13 then local alternative = math.random(1,3) Lista[OverCat][scroll[3].sel].ico = image.copy(icon.ud[alternative]) else local alternative = math.random(1,4) Lista[OverCat][scroll[3].sel].ico = image.copy(icon.hb[alternative]) end end end Lista[OverCat][scroll[3].sel].ico:blit(185,35) -- ## Flags ## if OverTop then icon.flags.cats:blitsprite(58,35,8) -- Categoria else icon.flags.cats:blitsprite(58,35,scroll[2].sel-1) -- Categoria end icon.flags.model:blitsprite(86,35,Lista[OverCat][scroll[3].sel].model) -- Modelo draw_lang_ico(icon.flags.lang,Lista[OverCat][scroll[3].sel].lang) -- ## Description ## screen.print(15,120,lang.descr,0.7,MyTxtColors,MyTxtShadow) local h,i = 135,scroll[4].ini while i <= scroll[4].lim do-- for i=scroll[4].ini,scroll[4].lim do screen.print(15,h,Lista[OverCat][scroll[3].sel].description[i] or "",0.7,MyTxtColors,MyTxtShadow) h,i = h + 15, i+1 end -- ## Impresion Barra Lateral Scroll ## if scroll[4].maxim > 8 then local pos_height = math.max(120/scroll[4].maxim, 8) draw.fillrect(320, 130, 5, 120, barcolor) draw.fillrect(320, 130+((120-pos_height)/(scroll[4].maxim-1))*(scroll[4].sel-1), 5, pos_height, MyScrColor) end -- ## Ranking Stars ## draw.fillrect(340,30,135,70,barcolor) screen.print(350,35,lang.rank,0.6,MyTxtColors,MyTxtShadow) if RankList[Lista[OverCat][scroll[3].sel].id] and RankList[Lista[OverCat][scroll[3].sel].id].votos > 0 then -- existe algo de ello? --RankList[Lista[OverCat][scroll[3].sel].id].media = math.floor(tonumber(RankList[Lista[OverCat][scroll[3].sel].id].puntos) / tonumber(RankList[Lista[OverCat][scroll[3].sel].id].votos)) icon.stars:blitsprite(350,50,RankList[Lista[OverCat][scroll[3].sel].id].media) screen.print(407,70,RankList[Lista[OverCat][scroll[3].sel].id].media.." - 5",0.6,MyTxtColors,MyTxtShadow,512) screen.print(407,85,lang.lrank[RankList[Lista[OverCat][scroll[3].sel].id].media+1],0.6,MyTxtColors,MyTxtShadow,512) else -- nada entonces 0 stars XD icon.stars:blitsprite(350,50,0) screen.print(407,70,lang.norank,0.6,MyTxtColors,MyTxtShadow,512) end -- # Downloads, Size & Rank # draw.fillrect(340,105,135,40,barcolor) icon.wn:blit(445,110) screen.print(345,110,lang.dls,0.6,MyTxtColors,MyTxtShadow) screen.print(345,125,Lista[OverCat][scroll[3].sel].fsize,0.7,MyTxtColors,MyTxtShadow) draw.fillrect(340,150,135,40,barcolor)--draw.fillrect(340,150,135,82,barcolor) icon.dl:blit(440,150) screen.print(345,155,lang.ins,0.6,MyTxtColors,MyTxtShadow) if RankList[Lista[OverCat][scroll[3].sel].id] then -- existe algo de ello? screen.print(390,170,RankList[Lista[OverCat][scroll[3].sel].id].down,0.7,MyTxtColors,MyTxtShadow,512) else screen.print(390,170,"0",0.7,MyTxtColors,MyTxtShadow) end -- ## ScreenShots ## draw.fillrect(340,195,135,40,barcolor) icon.ss:blit(430,195) screen.print(345,200,lang.ss,0.6,MyTxtColors,MyTxtShadow) screen.print(360,215,Lista[OverCat][scroll[3].sel].captures,0.7,MyTxtColors,MyTxtShadow) -- ## Download Button ## draw.fillrect(340,237,135,30,barcolor) draw.fillrect(340,237,135,30,color.new(0,72,255,osc.get())) screen.print(360,245,"X: "..lang.dl,0.6,MyTxtColors,MyTxtShadow) end function draw_lang_ico(img,index) if index < 1 then return end local frame1,frame2,frame3,num = index - 1,0,0,1 if index == 4 then frame1,frame2,num = 0,1,2 elseif index == 5 then frame1,frame2,num = 0,2,2 elseif index == 6 then frame1,frame2,num = 1,2,2 elseif index == 7 then frame1,frame2,frame3,num = 0,1,2,3 end if num > 0 then img:blitsprite(114,35,frame1) end if num > 1 then img:blitsprite(136,35,frame2) end if num > 2 then img:blitsprite(158,35,frame3) end end --## Visor ScreenShots ## function ctrls_shots() if buttons.down then scroll.down(5) elseif buttons.up then scroll.up(5) end if buttons.circle then Seccion = 4 end if buttons.cross then icon.myscreens[scroll[5].sel]:resize(480,272) visorimg(icon.myscreens[scroll[5].sel],Lista[OverCat][scroll[3].sel].title) icon.myscreens[scroll[5].sel]:center(0,0) end end function show_shots() draw_back() -- Dibuja el fondo draw_topbar() -- dibuja la barra superior draw.fillrect(336,26,144,246,barcolor) screen.print(168,35,Lista[OverCat][scroll[3].sel].title,0.7,MyTxtColors,MyTxtShadow,__ACENTER) local pos = 0 for i=1,scroll[5].maxim do icon.myscreens[i]:resize(144,82) icon.myscreens[i]:blit(336,(pos*82)+26) if i == scroll[5].sel then grafics.selectrect(336,(pos*82)+26,144,82,color.new(0,72,255,osc.get())) end icon.myscreens[scroll[5].sel]:resize(336,190) icon.myscreens[scroll[5].sel]:blit(0,56) pos = pos + 1 end end -- ## View Comments ## function show_viewcomments() draw_back() -- Dibuja el fondo draw_topbar() -- dibuja la barra superior draw.fillrect(5,30,230,232,barcolor)--Fondo de la barra lateral screen.print(13,45,ContactList[scroll["contact"].sel].name,0.6,MyTxtColors,MyTxtShadow) screen.print(237,35,ContactList[scroll["contact"].sel].date,0.6,MyTxtColors,MyTxtShadow,__ARIGHT) screen.print(13,55,ContactList[scroll["contact"].sel].msg,0.7,MyTxtColors,MyTxtShadow) --icon.one:blit(15,25) -- el logo :P grafics.multi_rect(4,240,30,230,55,5,barcolor) --Patron 4 rect opciones -- ## Impresion De Listado ## local y,numpos,i = 55,0,scroll["contact"].ini while i <= scroll["contact"].lim do --for i=scroll[3].ini,scroll[3].lim do -- Aunmento en un 75% de rendimiento al ser while if i==scroll["contact"].sel then -- Brillo, y scrolls draw.fillrect(240,30+60*numpos,230,55,color.new(0,72,251,osc.get())) end screen.clip(235,y-20,230,y+7) screen.print(243,y+5,ContactList[i].msg or "",0.7,MyTxtColors,MyTxtShadow) screen.print(243,y-15,i..". "..ContactList[i].name or "",0.7,MyTxtColors,MyTxtShadow,__SLEFT,260) screen.clip() numpos,y, i = numpos + 1, y + 60, i+1 end -- ## Impresion Barra Lateral ## if scroll["contact"].maxim> 4 then local pos_height = math.max(235/scroll["contact"].maxim, 5) draw.fillrect(475, 30, 5, 235, barcolor) draw.fillrect(475, 30+((235-pos_height)/(scroll["contact"].maxim-1))*(scroll["contact"].sel-1), 5, pos_height, MyScrColor) end end txt_reporter = "" -- texto del formulario function ctrls_viewcomments() if buttons.up then scroll.up("contact") ContactList[scroll["contact"].sel].msg = wordwrap(ContactList[scroll["contact"].sel].msg,214,0.7) elseif buttons.down then scroll.down("contact") ContactList[scroll["contact"].sel].msg = wordwrap(ContactList[scroll["contact"].sel].msg,214,0.7) end if buttons.circle then Seccion = 1 end -- retornamos al menu if buttons.cross then Seccion = 7 end -- nos pasamos al postform o enviador end -- ## Send Comments ## function ctrls_formcomments() if buttons.circle then Seccion = 6 end -- retornamos al visor comentarios if buttons.cross then -- enviamos if send_reporter(txt_reporter) == true then ContactList[#ContactList+1] = {name = os.nick(),date = os.getdate(),msg = txt_reporter} scroll.max("contact",ContactList) Seccion = 6 txt_reporter = "" else box.new("Error No send","Comentario o mensaje no enviado") Seccion = 6 txt_reporter = "" end end if buttons.square then --editamos txt local out_txt = osk.init("txt",txt_reporter) if out_txt then txt_reporter = wordwrap(out_txt,214,0.7)--quite el explode,"\n") end end end function show_formcomments() draw_back() -- Dibuja el fondo draw_topbar() -- dibuja la barra superior draw.fillrect(5,30,230,235,barcolor)--Fondo de la barra lateral screen.print(8,45,os.nick(),0.6,MyTxtColors,MyTxtShadow) screen.print(234,35,os.getdate(),0.6,MyTxtColors,MyTxtShadow,__ARIGHT) screen.print(8,55,txt_reporter,0.6,MyTxtColors,MyTxtShadow) draw.fillrect(240,30,235,235,barcolor)--Fondo de la barra lateral screen.print(243,45,ContactList[scroll["contact"].sel].name,0.7,MyTxtColors,MyTxtShadow) screen.print(271,35,ContactList[scroll["contact"].sel].date,0.6,MyTxtColors,MyTxtShadow,__ARIGHT) screen.print(243,55,ContactList[scroll["contact"].sel].msg,0.7,MyTxtColors,MyTxtShadow) end function send_reporter(tab) tab = string.explode(tab,"\n") local new_line = string.char(92,110) local form_send = table.concat(tab, new_line) local comilles = string.char(34) if string.len(form_send) > 0 then os.message(form_send) local result = http.post(Servidor.."contact.php?action=add","name="..os.nick().."&".."lang="..os.language().."&".."msg="..form_send) if result then return true end end return false end -- ## Configurador ## function show_configs() draw_back() -- Dibuja el fondo draw_topbar() -- dibuja la barra superior icon.one:blit(15,25) -- el logo :P draw.fillrect(5,100,150,167,barcolor) screen.print(20,110,lang.info.title,0.6,MyTxtColors,MyTxtShadow) screen.print(20,125,lang.info.firm..(os.cfw() or "Unk"),0.6,MyTxtColors,MyTxtShadow) screen.print(20,140,lang.info.model..(hw.getmodel() or "Unk"),0.6,MyTxtColors,MyTxtShadow) screen.print(20,155,lang.info.gen..hw.gen() or "",0.6,MyTxtColors,MyTxtShadow) screen.print(20,170,lang.info.region..hw.region() or "",0.6,MyTxtColors,MyTxtShadow) draw.fillrect(160,30,315,237,barcolor) screen.print(170,40,"Press R to change temp color theme",0.6,MyTxtColors,MyTxtShadow) --\nPress Select: Active TV\nPress Start Disable TV",0.6,MyTxtColors,MyTxtShadow) end function ctrls_configs() if buttons.r then config[1] = config[1] + 1 if config[1] > 9 then config[1] = 1 end end --if buttons.select then os.modetv(__8888) end --if buttons.start then os.modetv() end --if buttons.l then config[2] = config[2] + 1 if config[2] > 9 then config[2] = 1 end end if buttons.circle then -- salimos del configurador sound_scroll:play() Seccion = 1 end end -- ## Home Menu ## home_pos = 0 function api_homemenu(x1,y1,x2,y2) screen.print(x1,y1,"OneInstaller Menu",0.6,color.white,color.black,512) -- titulo draw.fillrect(x2,(home_pos*15)+y2,310,15,barcolor) if wlan.isconnected() then screen.print(x1,y2,lang.home.disconect,0.6,color.white,color.black,512) else screen.print(x1,y2,lang.home.conect,0.6,color.white,color.black,512) end y2 = y2 + 15 if usb.isactive() then screen.print(x1,y2,lang.home.disableusb,0.6,color.white,color.black,512) else screen.print(x1,y2,lang.home.enableusb,0.6,color.white,color.black,512) end y2 = y2 + 15 screen.print(x1,y2,lang.home.suspend,0.6,color.white,color.black,512) y2 = y2 + 15 screen.print(x1,y2,lang.home.off,0.6,color.white,color.black,512) y2 = y2 + 15 screen.print(x1,y2,lang.home.exit,0.6,color.white,color.black,512) y2 = y2 + 15 screen.print(x1,y2,lang.home.cancel,0.6,color.white,color.black,512) if buttons.up and home_pos > 0 then home_pos = home_pos - 1 elseif buttons.down and home_pos < 5 then home_pos = home_pos + 1 end if buttons.circle then box.close() home_pos = 0 end if buttons.cross then if home_pos == 0 then if wlan.isconnected() then wlan.disconnect ( ) else wlan.connect ( ) end elseif home_pos == 1 then if usb.isactive() then usb.stop ( ) else usb.mstick ( ) end elseif home_pos == 2 then kernel.fadeout() power.suspend() elseif home_pos == 3 then kernel.fadeout() power.off ( ) elseif home_pos == 4 then kernel.exit() end --game.add("eboot.pbp","ICON0.PNG",__ICON0) --game.add("eboot.pbp","SND0.AT3",__AT3) box.close() home_pos = 0 end end -- ## Funciones Net Oneinstaller ## -- ## Actualiza el System ## (todo) function Update_Sys() myback = screen.buffertoimage() box.ine(myback) tiempo:reset() tiempo:start() http.savefile(Servidor.."oneinstaller.rar","ms0:/oneinstaller/tmp/update.rar") tiempo:reset() tiempo:start() files.extract_w_bar("ms0:/oneinstaller/tmp/update.rar","ms0:/",CB_Up_Sys)--extrae con barra de accion completa files.delete("ms0:/oneinstaller/tmp/update.rar") myback:blit(0,0) box.back:blit(240,136) screen.print(240,84,lang.cupds,0.6,MyTxtColors,MyTxtShadow,512) screen.print(240,100,lang.oi.. " " ..lang.rupds,0.6,MyTxtColors,MyTxtShadow,512) screen.print(240,175,lang.ok,0.6,MyTxtColors,MyTxtShadow,512) screen.flip() buttons.waitforkey() box.out(myback) myback:blit(0,0) end -- ## Actualiza el Core (Files News) ## function Update_Core() onNetGetFile = CB_Dl_Core -- cambiamos el callback a el de install core progressupdate = 0 -- ## Reposito ## fileupdated = "Repository" http.savefile(Servidor.."repo.php?action=get&lang="..os.language(),"ms0:/oneinstaller/tmp/repository.lua") if files.exists("ms0:/oneinstaller/tmp/repository.lua") then --dofile("ms0:/oneinstaller/tmp/repository.lua") runok, str = pcall(dofile, "ms0:/oneinstaller/tmp/repository.lua")--Cargamos el script a prueba de errores -- Obtengo los distintos resultados de error if not runok then -- un error reintentaremos box.new(lang.errors.titlerepo,lang.errors.againrepo) http.savefile(Servidor.."repo.php?action=get&lang="..os.language(),"ms0:/oneinstaller/tmp/repository.lua") end else box.new(lang.errors.titlerepo,lang.errors.againrepo) if http.savefile(Servidor.."repo.php?action=get&lang="..os.language(),"ms0:/oneinstaller/tmp/repository.lua") then kernel.dofile("ms0:/oneinstaller/tmp/repository.lua") else os.exit() end end if lastupdateversion > lastnowversion then draw_back(true) local response = box.new(lang.tupds, {lang.mupds,lang.vaupds..lastnowversion,lang.vdupds..lastupdateversion},true) if response then Update_Sys() --en iso no puede reiniciar y de momentos pues asi dare el released os.exit()--os.restart() else os.exit() end end progressupdate = 20 -- ## Valoraciones y Descargas ## fileupdated = "Rankings" http.savefile(Servidor.."ranking.php?dl=1","ms0:/oneinstaller/tmp/ranking.lua") if files.exists("ms0:/oneinstaller/tmp/ranking.lua") then RankList = ini.load("ms0:/oneinstaller/tmp/ranking.lua") -- cargamos la tabla :D end progressupdate = 50 -- ## Comentarios ## --[[fileupdated = "Contacts" http.savefile(Servidor.."contact.php?action=get","ms0:/oneinstaller/tmp/contact.lua") if files.exists("ms0:/oneinstaller/tmp/contact.lua") then ContactList = ini.load("ms0:/oneinstaller/tmp/contact.lua") -- cargamos la tabla :D end progressupdate = 40]] -- ## Portadas ## fileupdated = "TOP 1" Top_1 = http.image(Servidor.."portada_1.jpg",1) progressupdate = 60 fileupdated = "TOP 2" Top_2 = http.image(Servidor.."portada_2.jpg",1) progressupdate = 70 fileupdated = "TOP 3" Top_3 = http.image(Servidor.."portada_3.jpg",1) progressupdate = 90 if not Top_1 then Top_1 = image.load("system/theme/top_1.png") end if not Top_2 then Top_2 = image.load("system/theme/top_2.png") end if not Top_3 then Top_3 = image.load("system/theme/top_2.png") end -- ## Login ## fileupdated = "Login" http.post(Servidor.."login.php","username="..os.nick().."&".."lang="..os.language().."&".."model="..(hw.getmodel() or "Unk").."&".."gen="..(hw.gen() or "Unk").."&".."reg="..(hw.region() or "Unk").."&".."fw="..(os.cfw() or "Unk")) progressupdate = 100 local myscreenback = screen.buffertoimage() box.ine(myscreenback) getmyicons = {} for __category=1 ,7 do -- Translate all repo to table & check icons or postsave zip & extract for __idxc=1,#Lista[__category] do if not files.exists("ms0:/oneinstaller/notices/"..Lista[__category][__idxc].id..".png") and Lista[__category][__idxc].defico == false then getmyicons[#getmyicons+1] = Lista[__category][__idxc].id end myscreenback:blit(0,0) box.back:blit(240,136) screen.print(240,84,"Check Repo",0.6,MyTxtColors,MyTxtShadow,512) screen.print(240,100,"ID: "..Lista[__category][__idxc].id,0.6,MyTxtColors,MyTxtShadow,512) screen.flip() Lista[__category][__idxc].description = string.explode(wordwrap(Lista[__category][__idxc].description or "",300,0.7) or "", "\n") or {""} end end for i=1,#Lista[9] do -- tops myscreenback:blit(0,0) box.back:blit(240,136) screen.print(240,84,"Check Repo",0.6,MyTxtColors,MyTxtShadow,512) screen.print(240,100,"ID: "..Lista[9][i].id,0.6,MyTxtColors,MyTxtShadow,512) screen.flip() Lista[9][i].description = string.explode(wordwrap(Lista[9][i].description or "",300,0.7) or "", "\n") or {""} end box.out(myscreenback) myscreenback:blit(0,0) --os.message(#getmyicons) if #getmyicons > 0 then getmyicons = string.implode(getmyicons,"#") draw_back(true) myback = screen.buffertoimage() box.ine(myback) tiempo:reset() tiempo:start() onNetGetFile = CB_Dl_Ico -- cambiamos el callback a el de install icons http.postsave(Servidor.."repo.php?action=icons","rest="..getmyicons,"ms0:/oneinstaller/tmp/mynewicons.zip") tiempo:reset() tiempo:start() files.extract_w_bar("ms0:/oneinstaller/tmp/mynewicons.zip","ms0:/oneinstaller/notices/",CB_Up_Ico)--extrae con barra de accion completa files.delete("ms0:/oneinstaller/tmp/mynewicons.zip") box.out(myback) myback:blit(0,0) end end -- Descarga las capturas function downss() onNetGetFile = CB_Dl_Screens __numdlscrsho = 1 local _id = Lista[OverCat][scroll[3].sel].id local _nss = Lista[OverCat][scroll[3].sel].captures myback = screen.buffertoimage() box.ine(myback) local tmpcaps = {} for i=1,_nss do tmpcaps[#tmpcaps+1] = http.image(Servidor.."apps/".._id.."_"..i..".jpg",1) __numdlscrsho = __numdlscrsho + 1 end if #tmpcaps > 0 then icon.myscreens = tmpcaps tmpcaps = nil collectgarbage("collect") box.out(myback) myback:blit(0,0) return true elseif #icon.myscreens > 0 then -- permite la entrada offline si habia caches tmpcaps = nil collectgarbage("collect") box.out(myback) myback:blit(0,0) return true end box.out(myback) myback:blit(0,0) return false end -- ## Descarga & Instala ## if not tiempo then tiempo = timer.new() end -- creamos un timer function DownInstall(url,title,preser) os.cpu(333) -- Temporalmente Forza Maxima CPU local capt = screen.buffertoimage() if wlan.isconnected() == false then wlan.connect() end -- No estamos Conectados? se conecta if wlan.isconnected() == false then box.new(lang.nowif, lang.dlab,true) return end if Lista[OverCat][scroll[3].sel].size > MS.free then box.new(lang.nospc,lang.dlab,true) return end file_installed = title or "" onNetGetFile = CB_Dl_Cont -- cambiamos el callback a el de install content tiempo:reset() tiempo:start() state = http.savefile(url,"ms0:/oneinstaller/tmp/install.zip")--wlan.getfile(url,"install.zip") if state then http.post(Servidor.."ranking.php","id="..Lista[OverCat][scroll[3].sel].id.."&".."down=1") if not RankList[Lista[OverCat][scroll[3].sel].id] then RankList[Lista[OverCat][scroll[3].sel].id] = {media = 0, puntos = 0, votos = 0,down = 0} end RankList[Lista[OverCat][scroll[3].sel].id].down = RankList[Lista[OverCat][scroll[3].sel].id].down + 1 ini.save("ms0:/oneinstaller/tmp/ranking.lua", RankList) end tiempo:stop() if state then local _rs = files.compress_size("ms0:/oneinstaller/tmp/install.zip") if _rs and _rs > MS.free then box.new(lang.nospc,lang.insab,true) return end local plugs = {} if OverCat == 5 then -- respalda plugs plugs.data = {} for i=1,#plugs_path do plugs.data[i] = files.read(plugs_path[i]) -- quitar el . al plugs.path end end files.extract_w_bar("ms0:/oneinstaller/tmp/install.zip","ms0:/",CB_Up_Cont)--extrae con barra de accion completa if OverCat == 5 then -- restaura plugs if #plugs.data > 0 then for i=1,#plugs_path do if plugs.data[i] then files.write(plugs_path[i],"\n"..plugs.data[i],"a+") end end end end if not preser then files.delete("ms0:/oneinstaller/tmp/install.zip") end -- pienso algunos querran guardar contenidos end os.cpu(222) -- volvemos a bajar la velocidad CPU capt:blit(0,0) return state end -- Callback Install & Download Content ## function CB_Dl_Cont(size,bytes) draw_back(true) -- Dibuja fondo sin Animacion. draw.fillrect(5,5,470,20,barcolor) screen.print(240,8,lang.oi,0.7,MyTxtColors,MyTxtShadow,512) -- ## Download ## draw.fillrect(5,30,470,115,barcolor) icon.fb:blit(10,35) screen.print(63,50,file_installed,0.7,MyTxtColors,MyTxtShadow) screen.print(63,70,files.sizeformat(size),0.7,MyTxtColors,MyTxtShadow) grafics.loadbar(10,100,460,21,math.floor(bytes*(456)/size),color.white,color.green) screen.print(240,105,files.sizeformat(bytes),0.7,MyTxtColors,MyTxtShadow,__ACENTER) screen.print(420,35,math.floor(bytes*(100)/size).." % ",0.7,MyTxtColors,MyTxtShadow) TiempoDescarga = (tiempo:time()/1000) VelocidadDescarga = (bytes/1024)/TiempoDescarga Tamano= size/1024 --icono.down:blit(30,123) screen.print(52,128,string.format("%.2f",VelocidadDescarga).."KB/s",0.7,MyTxtColors,MyTxtShadow) --icono.timer:blit(200,123) screen.print(360,128,string.format("%.2f",(Tamano/VelocidadDescarga)-TiempoDescarga).."s",0.7,MyTxtColors,MyTxtShadow) -- ## Un pack ## draw.fillrect(5,150,470,115,barcolor) icon.ur:blit(10,155) --draw.fillrect(340,30,135,235,barcolor) screen.flip() end function CB_Up_Cont(size,bytes,file) draw_back(true) -- Dibuja fondo sin Animacion. draw.fillrect(5,5,470,20,barcolor) screen.print(240,8,lang.oi,0.7,MyTxtColors,MyTxtShadow,512) draw.fillrect(5,30,470,115,barcolor) icon.fb:blit(10,35) screen.print(240,105,lang.complete,0.7,MyTxtColors,MyTxtShadow,__ACENTER) draw.fillrect(5,150,470,115,barcolor) icon.ur:blit(10,155) --Instalador real xD screen.print(63,160,file_installed,0.7,MyTxtColors,MyTxtShadow) screen.print(63,185,files.nopath(file),0.7,MyTxtColors,MyTxtShadow) TiempoExtract = tiempo:time()/1000 VelocidadExtract = (extract_total_write/1024)/TiempoExtract Tamano = extract_total_size/1024 --icono.down:blit(30,245) screen.print(52,248,string.format("%.2f",VelocidadExtract).."KB/s",0.7,MyTxtColors,MyTxtShadow) --icono.timer:blit(200,245) screen.print(360,248,string.format("%.2f",(Tamano/VelocidadExtract)-TiempoExtract).."s",0.7,MyTxtColors,MyTxtShadow) if file == fileant then extract_total_write = extract_total_write + bytes - antbytes else extract_total_write = extract_total_write + bytes end screen.print(420,155,math.floor(bytes*(100)/size).." % ",0.7,MyTxtColors,MyTxtShadow) grafics.loadbar(10,220,460,21,math.floor(extract_total_write*(456)/extract_total_size),color.white,color.green) --screen.print(285,235,extract_total_size,0.7,MyTxtColors,MyTxtShadow) screen.flip() antbytes = bytes fileant = file end -- ## Callback Down Updates ## function CB_Dl_Core(size,bytes) draw_back(true) -- Dibuja fondo sin Animacion. draw.fillrect(5,5,470,20,barcolor) screen.print(240,8,lang.oi,0.7,MyTxtColors,MyTxtShadow,512) draw.fillrect(5,30,470,237,barcolor) screen.print(35,40,lang.tupcore,0.8,MyTxtColors,MyTxtShadow) icon.dup:blit(271,9) icon.fb:blit(25,85) screen.print(80,105,fileupdated,0.8,MyTxtColors,MyTxtShadow) screen.print(80,125,files.sizeformat(size),0.8,MyTxtColors,MyTxtShadow) grafics.loadbar(25,170,264,21,math.floor(bytes*(260)/size),color.white,color.green) screen.print(157,175,files.sizeformat(bytes),0.7,MyTxtColors,MyTxtShadow,__ACENTER) screen.print(260,150,math.floor(bytes*(100)/size).." % ",0.7,MyTxtColors,MyTxtShadow) grafics.loadbar(25,228,430,21,math.floor(progressupdate*(4.30)),color.white,color.green) screen.print(240,208,progressupdate.." % ",0.7,MyTxtColors,MyTxtShadow) screen.flip() end -- ## Callback Down ScreenShots ## function CB_Dl_Screens(size,bytes) if myback then myback:blit(0,0) -- Dibuja fondo sin Animacion. end box.back:blit(240,136) screen.print(240,84,lang.dupds,0.6,MyTxtColors,MyTxtShadow,512) screen.print(240,100,"Screen Shots",0.6,MyTxtColors,MyTxtShadow,512) icon.fi:blit(90,98) screen.print(145,115,__numdlscrsho.."/"..Lista[OverCat][scroll[3].sel].captures,0.6,MyTxtColors,MyTxtShadow) grafics.loadbar(89,164,303,21,math.floor(bytes*(300)/size),color.gray,color.green) screen.print(240,144,math.floor(bytes*(100)/size).." % ",0.7,MyTxtColors,MyTxtShadow,512) screen.flip() end -- ## Callback Install & Download System ## function CB_Dl_Sys(size,bytes) if myback then myback:blit(0,0) -- Dibuja fondo sin Animacion. end box.back:blit(240,136) screen.print(240,84,lang.hupds,0.6,MyTxtColors,MyTxtShadow,512) screen.print(240,100,lang.dupds,0.6,MyTxtColors,MyTxtShadow,512) --screen.print(80,125,files.sizeformat(size),0.8,MyTxtColors,MyTxtShadow) grafics.loadbar(89,140,303,21,math.floor(bytes*(300)/size),color.gray,color.green) screen.print(240,144,math.floor(bytes*(100)/size).." % ",0.7,MyTxtColors,MyTxtShadow,512) screen.print(240,165,files.sizeformat(bytes).."/"..files.sizeformat(size),0.7,MyTxtColors,MyTxtShadow,__ACENTER) TiempoDescarga = (tiempo:time()/1000) VelocidadDescarga = (bytes/1024)/TiempoDescarga Tamano= size/1024 screen.print(151,175,string.format("%.2f",VelocidadDescarga).."KB/s",0.6,color.new(255,255,255),color.new(0,0,0),512) screen.print(327,175,string.format("%.2f",(Tamano/VelocidadDescarga)-TiempoDescarga).."s",0.6,color.new(255,255,255),color.new(0,0,0),512) screen.flip() end function CB_Up_Sys(size,bytes,file) if myback then myback:blit(0,0) -- Dibuja fondo sin Animacion. end box.back:blit(240,136) screen.print(240,84,lang.hupds,0.6,MyTxtColors,MyTxtShadow,512) screen.print(240,100,lang.iupds,0.6,MyTxtColors,MyTxtShadow,512) --screen.print(80,125,files.sizeformat(size),0.8,MyTxtColors,MyTxtShadow) grafics.loadbar(89,140,303,21,math.floor(extract_total_write*(300)/extract_total_size),color.gray,color.green) screen.print(240,144,math.floor(extract_total_write*(100)/extract_total_size).." % ",0.7,MyTxtColors,MyTxtShadow,512) screen.print(240,165,files.sizeformat(extract_total_write).."/"..files.sizeformat(extract_total_size),0.7,MyTxtColors,MyTxtShadow,__ACENTER) TiempoExtract = tiempo:time()/1000 VelocidadExtract = (extract_total_write/1024)/TiempoExtract Tamano = extract_total_size/1024 screen.print(151,175,string.format("%.2f",VelocidadExtract).."KB/s",0.6,color.new(255,255,255),color.new(0,0,0),512) screen.print(327,175,string.format("%.2f",(Tamano/VelocidadExtract)-TiempoExtract).."s",0.6,color.new(255,255,255),color.new(0,0,0),512) screen.flip() if file == fileant then extract_total_write = extract_total_write + bytes - antbytes else extract_total_write = extract_total_write + bytes end antbytes = bytes fileant = file end -- ## Callback Install icons ## function CB_Dl_Ico(size,bytes) if myback then myback:blit(0,0) -- Dibuja fondo sin Animacion. end box.back:blit(240,136) screen.print(240,84,lang.hupds.." Icons",0.6,MyTxtColors,MyTxtShadow,512) screen.print(240,100,lang.dupds,0.6,MyTxtColors,MyTxtShadow,512) --screen.print(80,125,files.sizeformat(size),0.8,MyTxtColors,MyTxtShadow) grafics.loadbar(89,140,303,21,math.floor(bytes*(300)/size),color.gray,color.green) screen.print(240,144,math.floor(bytes*(100)/size).." % ",0.7,MyTxtColors,MyTxtShadow,512) screen.print(240,165,files.sizeformat(bytes).."/"..files.sizeformat(size),0.7,MyTxtColors,MyTxtShadow,__ACENTER) TiempoDescarga = (tiempo:time()/1000) VelocidadDescarga = (bytes/1024)/TiempoDescarga Tamano= size/1024 screen.print(151,175,string.format("%.2f",VelocidadDescarga).."KB/s",0.6,color.new(255,255,255),color.new(0,0,0),512) screen.print(327,175,string.format("%.2f",(Tamano/VelocidadDescarga)-TiempoDescarga).."s",0.6,color.new(255,255,255),color.new(0,0,0),512) screen.flip() end function CB_Up_Ico(size,bytes,file) if myback then myback:blit(0,0) -- Dibuja fondo sin Animacion. end box.back:blit(240,136) screen.print(240,84,lang.hupds.." Icons",0.6,MyTxtColors,MyTxtShadow,512) screen.print(240,100,lang.iupds,0.6,MyTxtColors,MyTxtShadow,512) --screen.print(80,125,files.sizeformat(size),0.8,MyTxtColors,MyTxtShadow) grafics.loadbar(89,140,303,21,math.floor(extract_total_write*(300)/extract_total_size),color.gray,color.green) screen.print(240,144,math.floor(extract_total_write*(100)/extract_total_size).." % ",0.7,MyTxtColors,MyTxtShadow,512) screen.print(240,165,files.sizeformat(extract_total_write).."/"..files.sizeformat(extract_total_size),0.7,MyTxtColors,MyTxtShadow,__ACENTER) TiempoExtract = tiempo:time()/1000 VelocidadExtract = (extract_total_write/1024)/TiempoExtract Tamano = extract_total_size/1024 screen.print(151,175,string.format("%.2f",VelocidadExtract).."KB/s",0.6,color.new(255,255,255),color.new(0,0,0),512) screen.print(327,175,string.format("%.2f",(Tamano/VelocidadExtract)-TiempoExtract).."s",0.6,color.new(255,255,255),color.new(0,0,0),512) screen.flip() if file == fileant then extract_total_write = extract_total_write + bytes - antbytes else extract_total_write = extract_total_write + bytes end antbytes = bytes fileant = file end -- ## Callback Nulo o Vacio ## function CB_Dl_Null() end -- ## Vote Content ## ScoreLevel = 5 function send_vote(x1,y1,x2,y2) screen.print(x1,y1,lang.trank,0.6,color.white,color.black,512) -- titulo screen.print(x1,100,lang.lrank[ScoreLevel+1],0.6,color.white,color.black,512) -- descripcion score icon.stars:blitsprite(188,120,ScoreLevel) -- sprite stars screen.print(x1,150,ScoreLevel.." - 5",0.6,color.white,color.black,512) -- comparacion score screen.print(151,175,"X: "..lang.srank,0.6,color.white,color.black,512) screen.print(327,175,"O: "..lang.crank,0.6,color.white,color.black,512) if (buttons.left or buttons.down) and ScoreLevel > 0 then ScoreLevel = ScoreLevel - 1 end if (buttons.right or buttons.up) and ScoreLevel < 5 then ScoreLevel = ScoreLevel + 1 end if buttons.circle then ScoreLevel = 5 box.close() end if buttons.cross then if wlan.isconnected() then onNetGetFile = CB_Dl_Null -- callback nulo para evitar errores graficos http.post(Servidor.."ranking.php","id="..Lista[OverCat][scroll[3].sel].id.."&".."vote="..ScoreLevel) if not RankList[Lista[OverCat][scroll[3].sel].id] then RankList[Lista[OverCat][scroll[3].sel].id] = {media = 0, puntos = 0, votos = 0,down = 0} end RankList[Lista[OverCat][scroll[3].sel].id].votos = RankList[Lista[OverCat][scroll[3].sel].id].votos + 1 RankList[Lista[OverCat][scroll[3].sel].id].puntos = RankList[Lista[OverCat][scroll[3].sel].id].puntos + ScoreLevel RankList[Lista[OverCat][scroll[3].sel].id].media = math.floor(RankList[Lista[OverCat][scroll[3].sel].id].puntos/RankList[Lista[OverCat][scroll[3].sel].id].votos) ini.save("ms0:/oneinstaller/tmp/ranking.lua", RankList) end ScoreLevel = 5 box.close() end end -- About efect function about(intxt) if not intxt then return end amg.init() -- iniciamos el 3D screen.bilinear(1) -- activamos el suavizado de imgs local recursos = { crono =0, angle = 0, ct = 0, tbpos1 = -6, tbpos2 = -18, fxa = 255 } --Ajustamos Textos local showtxt = "" for i=1,#intxt do if type(intxt[i]) == "string" then showtxt = showtxt..wordwrap(intxt[i],240,0.7) else for u=1,#intxt[i] do intxt[i][u] = wordwrap(intxt[i][u],240,0.7) end showtxt = showtxt..string.rep("\n",6)..string.implode(intxt[i], "\n") end end -- Cargamos Objetos recursos.pboard = model3d.load("system/theme/3d/pboard.obj")--PSP_Board recursos.tpboard = texture3d.load("system/theme/3d/pboard.png",__VRAM)--PSP_B texture3d.setmulti(recursos.pboard,1,1,recursos.tpboard)-- aplicamos la textura a el modelo model3d.lighting(recursos.pboard,1,0) -- indica que no afectara las luces a ese modelo recursos.env = model3d.load("system/theme/3d/penv.obj")--PSP_ENV texture3d.mapping(recursos.env,1,1,__ENV,2,3) -- ajusta la textura de ese obj a ambiental model3d.lighting(recursos.env,1,0)-- indica que no afectara las luces a ese modelo --Creamos & ajustamos una camara camera1 = cam3d.new() cam3d.position(camera1,{0,0,1}) -- set posicion cam3d.eye(camera1,{0,0,0}) -- set vista --Ajustamos algunos parametros del escenario amg.perspective(35.0) -- ajusta el campo de vista amg.typelight(1,__DIRECTIONAL) -- ajusta luces direccionales amg.colorlight(1,color.new(250,250,250),color.new(100,200,90),color.new(120,120,120)) --ajusta colores de luces amg.poslight(1,{1,1,1}) --ajusta posicion de las luces amg.perspective(45.0)-- ajusta el campo de vista themesound = sound.load("system/sounds/theme.mp3") themesound:play() y = 232 while true do--Inicia bucle principal de animacion buttons.read() --if buttons.start then err() end -- error ocacional if buttons.held.up then y = y - 6 end if buttons.held.down then y = y + 6 end amg.begin() screen.clear(color.new(255,255,255)) cam3d.set(camera1) if recursos.crono < 500 or (recursos.crono > 1000 and recursos.crono < 1500) then cam3d.position(camera1,{0,0,1}) cam3d.eye(camera1,{0,0,0}) end if recursos.crono == 500 or recursos.crono == 1000 or recursos.crono == 1500 or recursos.crono == 2000 then recursos.fxa = 255 end if (recursos.crono > 500 and recursos.crono < 1000) or recursos.crono > 1500 then cam3d.eye(camera1,{math.sin(recursos.ct),0,0}) end amg.fog(3,12,color.new(255,255,255)) amg.light(1,1); model3d.position(recursos.pboard,1,{0,0,recursos.tbpos1}) model3d.render(recursos.pboard); model3d.position(recursos.pboard,1,{0,0,recursos.tbpos2}) model3d.render(recursos.pboard); model3d.position(recursos.env,1,{0,0,recursos.tbpos1}) model3d.render(recursos.env); model3d.position(recursos.env,1,{0,0,recursos.tbpos2}) model3d.render(recursos.env); amg.light(1,0); amg.fog() amg.mode2d(1) --screen.print(10,10,"fps:"..screen.fps().."\n".."Y:"..y.."\nCrono:"..recursos.crono) screen.clip(110,20,260,232) screen.print(120,y,showtxt,0.7,color.new(250,250,250),color.new(25,25,25)) screen.clip() screen.print(200+(100*math.sin(recursos.angle/30)),6,"OneInstaller",0.7,color.new(250,250,250),color.new(25,25,25)) if y < -850 then --break screen.print(360,255,"O: Continue",0.7,color.new(250,250,250),color.new(25,25,25),__ACENTER) screen.print(120,255,"X: Continue",0.7,color.new(250,250,250),color.new(25,25,25),__ACENTER) end draw.fillrect(0,0,480,272,color.new(255,255,255,recursos.fxa)) amg.mode2d(0) amg.update() screen.flip() model3d.rotation(recursos.pboard,1,{0,0,recursos.angle/3}) model3d.rotation(recursos.env,1,{0,0,recursos.angle/3}) recursos.angle = recursos.angle - 1; texture3d.trans(recursos.pboard,1,1,recursos.ct,0) texture3d.envmap(recursos.env,1,1,0,0,recursos.angle/100) recursos.ct = recursos.ct + 0.008 recursos.fxa = recursos.fxa - 6 if recursos.tbpos1 > 8 then recursos.tbpos1 = -16 end if recursos.tbpos2 > 8 then recursos.tbpos2 = -16 end recursos.tbpos1 = recursos.tbpos1 + 0.02; recursos.tbpos2 = recursos.tbpos2 + 0.02; recursos.crono = recursos.crono + 1; y = y - 0.5 if buttons.cross or buttons.circle then break end end themesound:stop() showtxt = nil --libero el texto themesound = nil -- libero musica recursos = nil --libero todo lo demas. collectgarbage() screen.bilinear(0) -- Quita el filtro suavizado amg.finish() -- cierra el 3D end -- explorer -- strings = { -- ## Opciones del Menu Explorer ## back=" Return ", copyfile="Copying File : ", label="Waiting...\nLoading Image...", dir="<DIR>", copy = "Copy", delete = "Delete ", makedir = "MakeDir", rename = "Rename", extract = "Extract", cancel = "Cancel", extractto = "Extract To", paste = "Paste", move = "Move", pass="Use Pass ?", creatfolder="Create Folder", newfolder="New Folder", ospass="PASS", } -- ## Muestra Un texto mientras algo se carga 'LABEL' ## -- function label(txt) -- mensaje de loading resource local scrback = screen.buffertoimage() draw.fillrect(180,100,120,72,color.new(128,128,128,150)) draw.rect(180,100,120,72,color.black) screen.print(240,120,txt,0.6,color.white,color.black,512) screen.flip() scrback:blit(0,0) end -- ## Visor De imagenes ## -- function visorimg(path,title) -- Version simplificada del visor del shell local scrback = screen.buffertoimage() local tmp = nil local _vmod = 0 if type(path) == "string" then label(strings.label) tmp = image.load(path) _vmod = 1 else tmp = path end if tmp then local infoimg = {} if _vmod == 0 then infoimg.name = title or "" else infoimg.name = files.nopath(path) end infoimg.w,infoimg.h = image.getrealw(tmp),image.getrealh(tmp) local show_bar_upper = true tmp:center() for i=0,20,1 do tmp:blit(240,136) draw.fillrect(0,0,480,i,color.new(255,255,255,100)) screen.flip() end while true do buttons.read() tmp:blit(240,136) if show_bar_upper then draw.fillrect(0,0,480,20,color.new(255,255,255,100)) screen.print(10,3,infoimg.name,0.7,color.white,color.black) screen.print(420,3,"w:"..infoimg.w,0.7,color.white,color.black,__ARIGHT) screen.print(470,3,"h:"..infoimg.h,0.7,color.white,color.black,__ARIGHT) end screen.flip() if buttons.square then show_bar_upper = not show_bar_upper end if buttons.circle or buttons.cross then break end end if show_bar_upper then for i=20,0,-1 do tmp:blit(240,136) draw.fillrect(0,0,480,i,color.new(255,255,255,100)) screen.flip() end end tmp = nil collectgarbage("collect") end scrback:blit(0,0) end -- ## Sort Add List By Name ## function Sort_By(tab,tipo) -- pendiente este permitira varios ordenes end function files.listsort(path) local tmp1 = files.listdirs(path) if tmp1 then table.sort(tmp1,function(a,b) return string.lower(a.name)<string.lower(b.name) end) else tmp1 = {} end local tmp2 = files.listfiles(path) if tmp2 then table.sort(tmp2,function(a,b) return string.lower(a.name)<string.lower(b.name) end) for s,t in pairs(tmp2) do t.size = files.sizeformat(t.size) table.insert(tmp1,t)-- esto es por que son subtablas, realmente no puedo hacer un cont con tmp2 end end return tmp1 end -- ## Explorador ## -- explorer = {} -- All explorer functions -- index para scroll -- 6: Lista -- 7: Menu -- x para el plugman revisar -- -- ## Explorer Refresh ## -- function explorer.refresh() explorer.list = files.listsort(Root[Dev]) scroll.set(6,explorer.list,15) end icons={1,pbp=2,prx=2, png=3,gif=3,jpg=3,bmp=3, mp3=4,s3m=4,wav=4,at3=4, rar=5,zip=5, cso=6,iso=6 } -- ## Explorer Drawer List ## -- function explorer.listshow() local h=25 local i = scroll[6].ini while i <= scroll[6].lim do --for i=scroll[6].ini,scroll[6].lim do -- Aunmento en un 75% de rendimiento al ser while if i==scroll[6].sel then draw.fillrect(0,h,480,15,color.new(128,128,128,100)) end --if explorer.list[i].size then --if icons[explorer.list[i].ext] then mimes:blitsprite(5,h, icons[explorer.list[i].ext]) -- else mimes:blitsprite(5,h, 0) end --else -- mimes:blitsprite(5,h, 1) --end screen.print(25, h, explorer.list[i].name or "",0.6, isopened[explorer.list[i].ext] or color.white, color.black) screen.print(470, h, explorer.list[i].size or strings.dir, 0.6, color.white, color.black, __ARIGHT) h,i = h+15, i+1 end end -- ## Explorer Drawer Menu ## -- function explorer.menushow() local h = slide_y + 5 local i = scroll[7].ini while i <= scroll[7].lim do if i==scroll[7].sel then cc=color.new(255,130,0) else cc=color.white end screen.print(slide_x+45,h,slide_opts_txt[i],0.6,cc,color.black,512) h,i=h+15, i+1 end end isopened = { png = color.green, jpg = color.green, gif = color.green, iso = color.orange, pbp = color.orange, cso = color.orange,zip = color.orange, rar = color.orange } function refresh_opt() slide_open[2]=false end function copysrc() explorer.src = explorer.list[scroll[6].sel].path explorer.action = scroll[7].sel refresh_opt() scroll.set(7,slide_opts_txt,7) end function _refresh() explorer.refresh() refresh_opt() slide_opts_txt = {strings.copy,strings.move,strings.extract,strings.delete,strings.makedir,strings.rename,strings.cancel} scroll.set(7,slide_opts_txt,7) explorer.action = 0 explorer.src, explorer.dst = "","" end function explorer.main() local scrback = screen.buffertoimage() Root = {"ms0:/","ef0:/"} if string.find(files.cdir(),"ef0") then Dev=2 else Dev=1 end back={} slide_open = {false,false} -- open/direction slide_x,slide_y,slide_h = 340,130,0 slide_opts_txt = {strings.copy,strings.move,strings.extract,strings.delete,strings.makedir,strings.rename,strings.cancel} scroll.set(7,slide_opts_txt,7) explorer.refresh() explorer.src,explorer.dst = "","" explorer.action = 0 divsect = 1 while true do buttons.read() if background then background:blit(0,0) end if divsect == 1 then -- List show_explorer_list() -- regla siempre el draw ctrls_explorer_list() if buttons.triangle then BackExpl = screen.buffertoimage() divsect, slide_open = 2, {true,true} end elseif divsect == 2 then -- Menu if BackExpl then BackExpl:blit(0,0) end show_explorer_menu() -- correccion igual para el draw list if slide_h > 100 then ctrls_explorer_menu() end -- evita uso de controles si se esta abriendo o cerrando if buttons.triangle or buttons.circle then refresh_opt() end end screen.flip() if buttons.select and not slide_open[2] then -- Salimos del explorer explorer.list=nil break end end scrback:blit(0,0) end function ctrls_explorer_list() if buttons.circle then -- return directory Root[Dev]=files.nofile(Root[Dev]) explorer.refresh() if #back>0 then if scroll[6].maxim == back[#back].maxim then scroll[6]=back[#back] end back[#back] = nil end end if scroll[6].maxim > 0 then-- Is exists any? if buttons.up or buttons.held.l then scroll.up(6) end if buttons.down or buttons.held.r then scroll.down(6) end if buttons.cross then -- Avanzar o ejecutar local extension = explorer.list[scroll[6].sel].ext if extension == "png" or extension == "jpg" or extension == "gif" then visorimg(explorer.list[scroll[6].sel].path) elseif extension == "cso" or extension == "iso" or extension == "pbp" or extension == "bin" then if (extension == "cso" or extension == "iso") and os.cfw()~="VHBL" then game.launch(explorer.list[scroll[6].sel].path) end if (extension == "pbp") then game.launch(explorer.list[scroll[6].sel].path) end end if not explorer.list[scroll[6].sel].size then -- es un dir table.insert(back,scroll[6]) Root[Dev]=explorer.list[scroll[6].sel].path explorer.refresh() end end end if buttons.start and not slide_open[2] then -- Swicht device if Dev == 1 and files.exists("ef0:/") then Dev = 2 explorer.refresh() elseif Dev == 2 and files.exists("ms0:/") then Dev = 1 explorer.refresh() end end end function show_explorer_list() draw.fillrect(0,0,480,20,barcolor) draw.fillrect(0,252,480,20,barcolor) screen.print(5,5,Root[Dev],0.6,color.new(255,69,0),color.black) if scroll[6].maxim > 0 then if scroll[6].maxim> 15 then -- esto dibuja la barra de scroll :D local pos_height = math.max(225/scroll[6].maxim, 15) draw.fillrect(475, 25, 5, 225, color.new(255,255,255,100)) draw.fillrect(475, 25+((225-pos_height)/(scroll[6].maxim-1))*(scroll[6].sel-1), 5, pos_height, color.new(0,255,0)) end explorer.listshow() else screen.print(10,25,"...".."\n"..strings.back,0.7,color.white,color.black) end screen.print(240,240,explorer.src or "",0.5,color.white,color.black,512) screen.print(240,250,explorer.dst or "",0.5,color.white,color.black,512) end function show_explorer_menu() if slide_open[2] and slide_h < 110 then slide_h = slide_h + 8 end if not slide_open[2] and slide_h > 0 then slide_h = slide_h - 8 end if not slide_open[2] and slide_h < 2 then slide_open[1] = false end if not slide_open[1] and slide_h < 2 then divsect = 1 end draw.fillrect(slide_x,slide_y,90,slide_h,color.new(255,255,255,100)) if slide_h > 100 then explorer.menushow() end -- la pongo aqui pues de lo contrario no actuan los if´s end function ctrls_explorer_menu() if buttons.up or buttons.held.l then scroll.up(7) end if buttons.down or buttons.held.r then scroll.down(7) end if buttons.cross then local numerador = 0 if explorer.src == "" and scroll[7].sel <= 3 then if #explorer.list > 0 then if scroll[7].sel == 1 or scroll[7].sel == 2 then --Copy/Move slide_opts_txt = {strings.paste,strings.delete,strings.makedir,strings.rename,strings.cancel} copysrc() else --Extract if explorer.list[scroll[6].sel].ext and (files.ext(explorer.list[scroll[6].sel].path):upper()=="ZIP" or files.ext(explorer.list[scroll[6].sel].path):upper()=="RAR") then slide_opts_txt = {strings.extractto,strings.delete,strings.makedir,strings.rename,strings.cancel} copysrc() end end end elseif string.len(explorer.src) > 0 then if scroll[7].sel == 1 then explorer.dst = Root[Dev].."/"..files.nopath(explorer.src) if Root[Dev]:sub(#Root[Dev]) == "/" then explorer.dst = Root[Dev]..files.nopath(explorer.src) end local screenback = screen.buffertoimage() if explorer.action == 1 then --Paste from Copy files.copy(explorer.src,explorer.dst) screenback:blit(0,0) elseif explorer.action == 2 then --Paste from Move if hw.getmodel() == "Vita" then if files.copy(explorer.src,explorer.dst) == 1 and files.exists(explorer.dst) then files.delete(explorer.src) end screenback:blit(0,0) else files.move(explorer.src,explorer.dst) end elseif explorer.action == 3 then --Extract explorer.dst = files.nofile(explorer.dst)-- esto es por que añado el src al final, para move y copy if os.message(strings.pass,1) == 1 then local pass = osk.init(strings.ospass,"") if pass then files.extract_w_bar(explorer.src,explorer.dst,pass) end else files.extract_w_bar(explorer.src,explorer.dst) end screenback:blit(0,0) end _refresh() end numerador = 2 end -- end of string len if scroll[7].sel == (4 - numerador) and #explorer.list > 0 then --Delete if os.message(strings.delete..explorer.list[scroll[6].sel].name.."?",1) == 1 then files.delete(explorer.list[scroll[6].sel].path) _refresh() end end if scroll[7].sel == (5 - numerador) then --MakeDir local newfolder = osk.init(strings.creatfolder, strings.newfolder) if newfolder then local dest = Root[Dev].."/"..newfolder if Root[Dev]:sub(#Root[Dev]) == "/" then dest = Root[Dev]..newfolder end files.mkdir(dest) _refresh() end end if scroll[7].sel == (6 - numerador) and #explorer.list > 0 then --Rename local name = osk.init(strings.rename,files.nopath(explorer.list[scroll[6].sel].path)) if name then files.rename(explorer.list[scroll[6].sel].path, name) _refresh() end end if scroll[7].sel == (7-numerador) then --Cancel _refresh() end end--if buttons.cross end
cc0-1.0
mahdib9/9
plugins/inrealm.lua
14
25561
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^(creategroup) (.*)$", "^(createrealm) (.*)$", "^(setabout) (%d+) (.*)$", "^(setrules) (%d+) (.*)$", "^(setname) (.*)$", "^(setgpname) (%d+) (.*)$", "^(setname) (%d+) (.*)$", "^(lock) (%d+) (.*)$", "^(unlock) (%d+) (.*)$", "^(setting) (%d+)$", "^(wholist)$", "^(who)$", "^(type)$", "^(kill) (chat) (%d+)$", "^(kill) (realm) (%d+)$", "^(addadmin) (.*)$", -- sudoers only "^(removeadmin) (.*)$", -- sudoers only "^(list) (.*)$", "^(log)$", "^(help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
ruisebastiao/nodemcu-firmware
lua_modules/hdc1000/HDC1000.lua
79
2703
------------------------------------------------------- -- This library was written for the Texas Instruments -- HDC1000 temperature and humidity sensor. -- It should work for the HDC1008 too. -- Written by Francesco Truzzi (francesco@truzzi.me) -- Released under GNU GPL v2.0 license. ------------------------------------------------------- -------------- NON-DEFAULT CONFIG VALUES -------------- ------------- config() optional arguments ------------- -- HDC1000_HEAT_OFF 0x00 (heater) -- HDC1000_TEMP_11BIT 0x40 (resolution) -- HDC1000_HUMI_11BIT 0x01 (resolution) -- HDC1000_HUMI_8BIT 0x20 (resolution) ------------------------------------------------------- local modname = ... local M = {} _G[modname] = M local id = 0 local i2c = i2c local delay = 20000 local _drdyn_pin local HDC1000_ADDR = 0x40 local HDC1000_TEMP = 0x00 local HDC1000_HUMI = 0x01 local HDC1000_CONFIG = 0x02 local HDC1000_HEAT_ON = 0x20 local HDC1000_TEMP_HUMI_14BIT = 0x00 -- reads 16bits from the sensor local function read16() i2c.start(id) i2c.address(id, HDC1000_ADDR, i2c.RECEIVER) data_temp = i2c.read(0, 2) i2c.stop(id) data = bit.lshift(string.byte(data_temp, 1, 1), 8) + string.byte(data_temp, 2, 2) return data end -- sets the register to read next local function setReadRegister(register) i2c.start(id) i2c.address(id, HDC1000_ADDR, i2c.TRANSMITTER) i2c.write(id, register) i2c.stop(id) end -- writes the 2 configuration bytes local function writeConfig(config) i2c.start(id) i2c.address(id, HDC1000_ADDR, i2c.TRANSMITTER) i2c.write(id, HDC1000_CONFIG, config, 0x00) i2c.stop(id) end -- returns true if battery voltage is < 2.7V, false otherwise function M.batteryDead() setReadRegister(HDC1000_CONFIG) return(bit.isset(read16(), 11)) end -- initalize i2c function M.init(sda, scl, drdyn_pin) _drdyn_pin = drdyn_pin i2c.setup(id, sda, scl, i2c.SLOW) end function M.config(addr, resolution, heater) -- default values are set if the function is called with no arguments HDC1000_ADDR = addr or HDC1000_ADDR resolution = resolution or HDC1000_TEMP_HUMI_14BIT heater = heater or HDC1000_HEAT_ON writeConfig(bit.bor(resolution, heater)) end -- outputs temperature in Celsius degrees function M.getHumi() setReadRegister(HDC1000_HUMI) if(_drdyn_pin ~= false) then gpio.mode(_drdyn_pin, gpio.INPUT) while(gpio.read(_drdyn_pin)==1) do end else tmr.delay(delay) end return(read16()/65535.0*100) end -- outputs humidity in %RH function M.getTemp() setReadRegister(HDC1000_TEMP) if(_drdyn_pin ~= false) then gpio.mode(_drdyn_pin, gpio.INPUT) while(gpio.read(_drdyn_pin)==1) do end else tmr.delay(delay) end return(read16()/65535.0*165-40) end return M
mit
UnfortunateFruit/darkstar
scripts/zones/San_dOria-Jeuno_Airship/Zone.lua
28
1461
----------------------------------- -- -- Zone: San_dOria-Jeuno_Airship -- ----------------------------------- ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) or (player:getYPos() == 0) or (player:getZPos() == 0)) then player:setPos(math.random(-4, 4),1,math.random(-23,-12)); end return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) 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); if (csid == 0x0064) then local prevzone = player:getPreviousZone(); if (prevzone == 246) then player:setPos(0,0,0,0,232); elseif (prevzone == 232) then player:setPos(0,0,0,0,246); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Bastok_Markets/npcs/Rothais.lua
36
1061
----------------------------------- -- Area: Bastok Markets -- NPC: Rothais -- Involved in Quest: Gourmet ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) vanatime = VanadielHour(); if (vanatime>=18 or vanatime<6) then player:startEvent(0x00cc); elseif (vanatime>=6 and vanatime<12) then player:startEvent(0x00cd); else player:startEvent(0x00ce); 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
Mashape/kong
kong/plugins/basic-auth/daos.lua
1
1169
local typedefs = require "kong.db.schema.typedefs" local crypto = require "kong.plugins.basic-auth.crypto" return { basicauth_credentials = { name = "basicauth_credentials", primary_key = { "id" }, cache_key = { "username" }, endpoint_key = "username", -- Passwords are hashed, so the exported passwords would contain the hashes. -- Importing them back would require "plain" non-hashed passwords instead. db_export = false, admin_api_name = "basic-auths", admin_api_nested_name = "basic-auth", fields = { { id = typedefs.uuid }, { created_at = typedefs.auto_timestamp_s }, { consumer = { type = "foreign", reference = "consumers", required = true, on_delete = "cascade" }, }, { username = { type = "string", required = true, unique = true }, }, { password = { type = "string", required = true }, }, { tags = typedefs.tags }, }, transformations = { { input = { "password" }, needs = { "consumer.id" }, on_write = function(password, consumer_id) return { password = crypto.hash(consumer_id, password) } end, }, }, }, }
apache-2.0
bowlofstew/Macaroni
Main/App/Source/test/lua/Macaroni/Model/ContextTests.lua
2
3033
-------------------------------------------------------------------------------- -- Copyright 2011 Tim Simpson -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -------------------------------------------------------------------------------- local Context = require "Macaroni.Model.Context"; local Node = require "Macaroni.Model.Node"; Test.register( { name = "Context Tests", tests={ ["CreateRoot Test"] = function(this) this.context = Context.New("{ROOT}"); Test.assertEquals("{ROOT}", tostring(this.context.Root)); end, ["ToString returns a string of some kind."] = function(this) local lContext = Context.New("{ROOT}"); Test.assertEquals("Context[references:3,Root:{ROOT}]", tostring(lContext)); end, ["ParseComplexName will morph unknown Nodes into Namespaces."] = function(this) local context = Context.New("{ROOT}", "{WILDCARD}"); local d = context.Root:FindOrCreate("A::B::C::D"); Test.assertEquals("A::B::C::D", d.FullName); local d_c = d.Node; Test.assertEquals("A::B::C", d_c.FullName); local d_b = d_c.Node; Test.assertEquals("A::B", d_b.FullName); local d_a = d_b.Node; Test.assertEquals("A", d_a.FullName); Test.assertEquals(1, #(context.Root.Children)); -- Must reuse A, and morph it into an Namespace... -- I.. am.. morphing... local a = context.Root:FindOrCreate("A"); Test.assertEquals("A", a.FullName); Test.assertEquals(a, d_a); Test.assertEquals(1, #(context.Root.Children)); end, --[[ ["Existing namespace instances are used when adding to collection."] = function(this) local context = Context.New("{r}", "*"); Node. context.RootNamespace. doc:Read("namespace A::B::C::D { } "); doc:Read("namespace A{}"); Test.assertEquals(2, #(doc.Namespaces)); local a = doc.Namespaces[2]; local d = doc.Namespaces[1]; Test.assertEquals("A::B::C::D", d.FullName); Test.assertEquals("A", a.FullName); local c = d.Parent; local b = d.Parent.Parent; local aReference2 = d.Parent.Parent.Parent; Test.assertEquals(a, aReference2); end,]]-- ["Root and wildcard namespaces created properly"] = function(this) context = Context.New("{ROOT}"); root = context.Root; Test.assertEquals("{ROOT}", tostring(root)); end, } } -- End of Test table. ); -- End of register call
apache-2.0
nesstea/darkstar
scripts/zones/Gusgen_Mines/npcs/_5gd.lua
13
1343
----------------------------------- -- Area: Gusgen Mines -- NPC: _5gd (Lever F) -- @pos 44 -20.56 143.802 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --local nID = npc:getID(); --printf("id: %u", nID); local Lever = npc:getID(); npc:openDoor(2); -- Lever animation if (GetNPCByID(Lever-6):getAnimation() == 9) then GetNPCByID(Lever-6):setAnimation(8);--open door F GetNPCByID(Lever-5):setAnimation(9);--close door E GetNPCByID(Lever-4):setAnimation(9);--close door D 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
nesstea/darkstar
scripts/globals/abilities/wind_maneuver.lua
35
1604
----------------------------------- -- Ability: Wind Maneuver -- Enhances the effect of wind attachments. Must have animator equipped. -- Obtained: Puppetmaster level 1 -- Recast Time: 10 seconds (shared with all maneuvers) -- Duration: 1 minute ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getWeaponSubSkillType(SLOT_RANGED) == 10 and not player:hasStatusEffect(EFFECT_OVERLOAD)) then return 0,0; else return 71,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local burden = 15; if (target:getStat(MOD_AGI) < target:getPet():getStat(MOD_AGI)) then burden = 20; end local overload = target:addBurden(ELE_WIND-1, burden); if (overload ~= 0) then target:removeAllManeuvers(); target:addStatusEffect(EFFECT_OVERLOAD, 0, 0, overload); else local level; if (target:getMainJob() == JOB_PUP) then level = target:getMainLvl() else level = target:getSubLvl() end local bonus = 1 + (level/15) + target:getMod(MOD_MANEUVER_BONUS); if (target:getActiveManeuvers() == 3) then target:removeOldestManeuver(); end target:addStatusEffect(EFFECT_WIND_MANEUVER, bonus, 0, 60); end return EFFECT_WIND_MANEUVER; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/kohlrouladen.lua
35
1287
----------------------------------------- -- ID: 5760 -- Item: kohlrouladen -- Food Effect: 1hour?, All Races ----------------------------------------- -- Strength 3 -- Agility 3 -- Intelligence -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5760); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 3); target:addMod(MOD_AGI, 3); target:addMod(MOD_INT, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 3); target:delMod(MOD_AGI, 3); target:delMod(MOD_INT, -5); end;
gpl-3.0
malortie/gmod-addons
th_weapons/lua/weapons/weapon_th_base/shared.lua
1
22291
-- Only enable this addon if HL:S is mounted. if !IsHL1Mounted() then return end SWEP.PrintName = "They Hunger Base SWEP" SWEP.Author = "" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.ViewModelFOV = 90 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/weapons/v_pistol.mdl" SWEP.WorldModel = "models/weapons/w_357.mdl" SWEP.Spawnable = false SWEP.AdminOnly = false SWEP.Primary.ClipSize = 8 SWEP.Primary.DefaultClip = 32 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "Pistol" SWEP.Primary.FireRate = 0.5 SWEP.Secondary.ClipSize = 8 SWEP.Secondary.DefaultClip = 32 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "Pistol" SWEP.Secondary.FireRate = 0.5 SWEP.m_WeaponDeploySpeed = 1.0 SWEP:SetWeaponHoldType( 'pistol' ) -- Specify whether or not this weapon can perform -- primary attacks underwater. SWEP.FiresUnderwater = false -- Specify whether or not this weapon can perform -- secondary attacks underwater. SWEP.AltFiresUnderwater = false -- The sound to play when empty. SWEP.EmptySound = 'weapon_th_base.empty' --[[--------------------------------------------------------- Setup networked variables. -----------------------------------------------------------]] function SWEP:SetupDataTables() self.Weapon:NetworkVar( 'Float', 0, 'NextIdle' ) self.Weapon:NetworkVar( 'Float', 1, 'StartThrow' ) self.Weapon:NetworkVar( 'Float', 2, 'ReleaseThrow' ) self.Weapon:NetworkVar( 'Int', 0, 'InAttack' ) self.Weapon:NetworkVar( 'Int', 1, 'InSpecialReload' ) self.Weapon:NetworkVar( 'Int', 2, 'ChargeReady' ) self.Weapon:NetworkVar( 'Bool', 0, 'DrawMuzzleFlash' ) self.Weapon:NetworkVar( 'Float', 27, 'MuzzleFlashTime' ) self.Weapon:NetworkVar( 'Float', 28, 'MuzzleFlashScale' ) self.Weapon:NetworkVar( 'Int', 28, 'MuzzleFlashType' ) end --[[--------------------------------------------------------- Name: SWEP:Initialize( ) Desc: Called when the weapon is first loaded -----------------------------------------------------------]] function SWEP:Initialize() self.Weapon:SetNextIdle( 0 ) self.Weapon:SetStartThrow( 0 ) self.Weapon:SetReleaseThrow( 0 ) self.Weapon:SetNextIdle( 0 ) self.Weapon:SetInAttack( 0 ) self.Weapon:SetInSpecialReload( 0 ) self.Weapon:SetChargeReady( 0 ) self.Weapon:SetDrawMuzzleFlash( true ) -- self.Weapon:SetMuzzleFlashTime( 0 ) self.Weapon:SetMuzzleFlashType( MUZZLEFLASH_HL1_GLOCK ) self.Weapon:SetMuzzleFlashScale( 1 ) -- end --[[--------------------------------------------------------- Name: SWEP:PrimaryAttack( ) Desc: +attack1 has been pressed -----------------------------------------------------------]] function SWEP:PrimaryAttack() end --[[--------------------------------------------------------- Name: SWEP:SecondaryAttack( ) Desc: +attack2 has been pressed -----------------------------------------------------------]] function SWEP:SecondaryAttack() end function SWEP:CanReload() return true end --[[--------------------------------------------------------- Name: SWEP:Reload( ) Desc: Reload is being pressed -----------------------------------------------------------]] function SWEP:Reload() if !self:CanReload() then return end self.Weapon:DefaultReload( ACT_VM_RELOAD ); -- Update idle time. self.Weapon:SetNextIdle( CurTime() + self:ViewModelSequenceDuration() + 0.01 ) end --[[--------------------------------------------------------- Name: SWEP:Think( ) Desc: Called every frame -----------------------------------------------------------]] function SWEP:Think() self:UpdateMuzzleFlash() self:WeaponIdle() end --[[--------------------------------------------------------- Check if this weapon can be holstered. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:CanHolster() return true end --[[--------------------------------------------------------- Name: SWEP:Holster( weapon_to_swap_to ) Desc: Weapon wants to holster RetV: Return true to allow the weapon to holster -----------------------------------------------------------]] function SWEP:Holster( wep ) if !self:CanHolster() then return false end return true end --[[--------------------------------------------------------- Check if this weapon can be deployed. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:CanDeploy() return true end --[[--------------------------------------------------------- Name: SWEP:Deploy( ) Desc: Whip it out -----------------------------------------------------------]] function SWEP:Deploy() if !self:CanDeploy() then return false end -- Perform muzzle flash checking. self:CheckMuzzleFlash() self.Weapon:SetNextIdle( CurTime() + 5.0 ) self:ResetBodygroups() return true end --[[--------------------------------------------------------- Test if this weapon uses clips for ammo 1. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:UsesClipsForAmmo1() return self.Weapon:GetMaxClip1() != -1 end --[[--------------------------------------------------------- Test if this weapon uses clips for ammo 2. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:UsesClipsForAmmo2() return self.Weapon:GetMaxClip2() != -1 end --[[--------------------------------------------------------- Test if this weapon has primary ammo. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:HasPrimaryAmmo() -- If I use a clip, and have some ammo in it, then I have ammo if self:UsesClipsForAmmo1() then if self.Weapon:Clip1() > 0 then return true end end -- Otherwise, I have ammo if I have some in my ammo counts if IsValid( self.Owner ) then if self:Ammo1() > 0 then return true end else -- No owner, so return how much primary ammo I have along with me. if( self:HasAmmo() ) then return true end end return false end --[[--------------------------------------------------------- Test if this weapon has secondary ammo. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:HasSecondaryAmmo() -- If I use a clip, and have some ammo in it, then I have ammo if self:UsesClipsForAmmo2() then if self.Weapon:Clip2() > 0 then return true end end -- Otherwise, I have ammo if I have some in my ammo counts if IsValid( self.Owner ) then if self:Ammo2() > 0 then return true end else -- No owner, so return how much secondary ammo I have along with me. if( self:HasAmmo() ) then return true end end return false end --[[--------------------------------------------------------- Test if this weapon uses primary ammo. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:UsesPrimaryAmmo() if self:GetPrimaryAmmoType() < 0 then return false end return true end --[[--------------------------------------------------------- Test if this weapon uses secondary ammo. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:UsesSecondaryAmmo() if self:GetSecondaryAmmoType() < 0 then return false end return true end --[[--------------------------------------------------------- Name: SWEP:TakePrimaryAmmo( ) Desc: A convenience function to remove ammo -----------------------------------------------------------]] function SWEP:TakePrimaryAmmo( num ) -- Doesn't use clips if ( self.Weapon:Clip1() <= 0 ) then if ( self:Ammo1() <= 0 ) then return end self.Owner:RemoveAmmo( num, self.Weapon:GetPrimaryAmmoType() ) return end self.Weapon:SetClip1( self.Weapon:Clip1() - num ) end --[[--------------------------------------------------------- Name: SWEP:TakeSecondaryAmmo( ) Desc: A convenience function to remove ammo -----------------------------------------------------------]] function SWEP:TakeSecondaryAmmo( num ) -- Doesn't use clips if ( self.Weapon:Clip2() <= 0 ) then if ( self:Ammo2() <= 0 ) then return end self.Owner:RemoveAmmo( num, self.Weapon:GetSecondaryAmmoType() ) return end self.Weapon:SetClip2( self.Weapon:Clip2() - num ) end --[[--------------------------------------------------------- Name: SWEP:CanPrimaryAttack( ) Desc: Helper function for checking for no ammo -----------------------------------------------------------]] function SWEP:CanPrimaryAttack() if self.Weapon:GetInSpecialReload() != 0 then return false end if ( self:UsesClipsForAmmo1() && self.Weapon:Clip1() <= 0 ) or ( !self:UsesClipsForAmmo1() && self:Ammo1() <= 0 ) then self:PlayEmptySound() self:SetNextPrimaryFire( CurTime() + self.Primary.FireRate ) self:Reload() return false end if !self.FiresUnderwater && self.Owner:WaterLevel() == 3 then self:PlayEmptySound() self:SetNextPrimaryFire( CurTime() + self.Primary.FireRate ) return false end return true end --[[--------------------------------------------------------- Name: SWEP:CanSecondaryAttack( ) Desc: Helper function for checking for no ammo -----------------------------------------------------------]] function SWEP:CanSecondaryAttack() if self.Weapon:GetInSpecialReload() != 0 then return false end if ( self:UsesClipsForAmmo2() && self.Weapon:Clip2() <= 0 ) or ( !self:UsesClipsForAmmo2() && self:Ammo2() <= 0 ) then self:PlayEmptySound() self:SetNextSecondaryFire( CurTime() + self.Secondary.FireRate ) return false end if !self.AltFiresUnderwater && self.Owner:WaterLevel() == 3 then self:PlayEmptySound() self:SetNextSecondaryFire( CurTime() + self.Secondary.FireRate ) return false end return true end --[[--------------------------------------------------------- Name: OnRemove Desc: Called just before entity is deleted -----------------------------------------------------------]] function SWEP:OnRemove() end --[[--------------------------------------------------------- Name: OwnerChanged Desc: When weapon is dropped or picked up by a new player -----------------------------------------------------------]] function SWEP:OwnerChanged() end --[[--------------------------------------------------------- Name: Ammo1 Desc: Returns how much of ammo1 the player has -----------------------------------------------------------]] function SWEP:Ammo1() return self.Owner:GetAmmoCount( self.Weapon:GetPrimaryAmmoType() ) end --[[--------------------------------------------------------- Name: Ammo2 Desc: Returns how much of ammo2 the player has -----------------------------------------------------------]] function SWEP:Ammo2() return self.Owner:GetAmmoCount( self.Weapon:GetSecondaryAmmoType() ) end --[[--------------------------------------------------------- Name: SetDeploySpeed Desc: Sets the weapon deploy speed. This value needs to match on client and server. -----------------------------------------------------------]] function SWEP:SetDeploySpeed( speed ) self.m_WeaponDeploySpeed = tonumber( speed ) end --[[--------------------------------------------------------- Name: DoImpactEffect Desc: Callback so the weapon can override the impact effects it makes return true to not do the default thing - which is to call UTIL_ImpactTrace in c++ -----------------------------------------------------------]] function SWEP:DoImpactEffect( tr, nDamageType ) return false; end --[[--------------------------------------------------------- Test if this weapon can play idle activity. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:CanIdle() if self.Weapon:GetNextIdle() > CurTime() then return false end return true end --[[--------------------------------------------------------- Play weapon idle animation. -----------------------------------------------------------]] function SWEP:WeaponIdle() if !self:CanIdle() then return end local anim = ACT_VM_IDLE -- Sometimes, play a fidget activity. if RandomInt( 0, 3 ) == 1 then anim = ACT_VM_FIDGET end self:SendWeaponAnim( anim ) self.Weapon:SetNextIdle( CurTime() + RandomFloat( 10, 15 ) ) end --[[--------------------------------------------------------- Play empty weapon sound. -----------------------------------------------------------]] function SWEP:PlayEmptySound() self.Weapon:EmitSound( self.EmptySound ) end --[[--------------------------------------------------------- Remove this weapon from the player's inventory. -----------------------------------------------------------]] function SWEP:RetireWeapon() if ( SERVER ) then self.Owner:StripWeapon( self.Weapon:GetClass() ) end -- end ( SERVER ) end --[[--------------------------------------------------------- Return the sequence duration of the viewmodel at a specified index. @param index ViewModel index. (must be between 0 and 2) @return ViewModel sequence duration. -----------------------------------------------------------]] function SWEP:ViewModelSequenceDuration( index ) index = index or 0 assert( index >= 0 && index <= 2 ) local owner = self.Owner if !IsValid( owner ) then return false end return owner:GetViewModel(index):SequenceDuration() end --[[--------------------------------------------------------- Return the sequence duration of the viewmodel at a specified index. @param index ViewModel index. (must be between 0 and 2) @return true on if the ViewModel sequence is finished. @return false otherwise. -----------------------------------------------------------]] function SWEP:IsViewModelSequenceFinished( index ) index = index or 0 assert( index >= 0 && index <= 2 ) local owner = self.Owner if !IsValid( owner ) then return false end return owner:GetViewModel(index):GetCycle() >= 1 end --[[--------------------------------------------------------- Do a shell ejection effect. @param origin Spawn position of the shell. @param velocity Shell velocity. @param rotation Yaw angle at which to throw the shell. @param shellType Shell type. @param bounceSound bound sound. (unused) -----------------------------------------------------------]] function SWEP:EjectBrass( origin, velocity, rotation, shellType, bounceSound ) if ( SERVER ) then local effectName = 'ShellEject' if shellType == SHELL_PISTOL then effectName = 'ShellEject' elseif shellType == SHELL_RIFLE then effectName = 'RifleShellEject' elseif shellType == SHELL_SHOTGUN then effectName = 'ShotgunShellEject' end local angles = self.Owner:GetLocalAngles() angles.y = rotation local effectdata = EffectData() effectdata:SetOrigin( origin ) effectdata:SetNormal( angles:Forward() ) effectdata:SetAngles( ( angles:Up() + angles:Right() ):Angle() ) util.Effect( effectName, effectdata, true, true ) end -- end ( SERVER ) end --[[--------------------------------------------------------- This method returns the shell eject offset. @return A vector reprensenting the shell eject offset. -----------------------------------------------------------]] function SWEP:GetShellEjectOffset() return Vector( 32, 6, -12 ) end --[[--------------------------------------------------------- Retrieve appropriate values for shell position, velocity and direction. @param entity Used to determine if this is a player. @param origin Spawn position. @param velocity Entity velocity. @param ShellVelocity Result shell velocity. @param ShellOrigin Result shell origin. @param forward Forward direction. @param right Right direction. @param up Up direction. @param forwardScale The length along forward vector. @param rightScale The length along right vector. @param upScale The length along up vector. -----------------------------------------------------------]] local function GetDefaultShellInfo( entity, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, forwardScale, rightScale, upScale ) local view_ofs = Vector( 0, 0, 64 ) -- 28 if entity:IsPlayer() then if entity:Crouching() then view_ofs[3] = 28 -- 12 end end local fR = RandomFloat( 50, 70 ) local fU = RandomFloat( 100, 150 ) for i = 1, 3 do ShellVelocity[i] = velocity[i] + right[i] * fR + up[i] * fU + forward[i] * 25 ShellOrigin[i] = origin[i] + view_ofs[i] + up[i] * upScale + forward[i] * forwardScale + right[i] * rightScale end end --[[--------------------------------------------------------- Perform a default shell ejection effect. @param shellType Shell type. @param bounceSound bound sound. (unused) -----------------------------------------------------------]] function SWEP:DefaultShellEject( shellType, bounceSoundType ) shellType = shellType or SHELL_PISTOL bounceSoundType = bounceSoundType or TE_BOUNCE_SHELL local angles = self.Owner:EyeAngles() + self.Owner:GetViewPunchAngles() local forward, right, up = angles:Forward(), angles:Right(), angles:Up() local offset = self:GetShellEjectOffset() local shellOrigin, shellVelocity = Vector(), Vector() GetDefaultShellInfo( self.Owner, self:GetPos(), self.Owner:GetVelocity(), shellVelocity, shellOrigin, forward, right, up, offset.x, offset.y, offset.z ) self:EjectBrass( shellOrigin, shellVelocity, angles.y, shellType, bounceSoundType ) end local ConcreteShotDecals = { 'decals/concrete/shot1', 'decals/concrete/shot2', 'decals/concrete/shot3', 'decals/concrete/shot4', 'decals/concrete/shot5' } local MetalShotDecals = { 'decals/metal/shot1', 'decals/metal/shot2', 'decals/metal/shot3', 'decals/metal/shot4', 'decals/metal/shot5', } local WoodShotDecals = { 'decals/wood/shot1', 'decals/wood/shot2', 'decals/wood/shot3', 'decals/wood/shot4', 'decals/wood/shot5', } --[[--------------------------------------------------------- Given a surface id, return an appropriate impact decal material name. @param surfaceid Surface Id. @return A decal name. -----------------------------------------------------------]] function SWEP:GetIdealSurfaceDecalMaterialName( surfaceid ) if surfaceid == 'metal' then return MetalShotDecals[ RandomInt( 1, #MetalShotDecals ) ] elseif surfaceid == 'wood' then return WoodShotDecals[ RandomInt( 1, #WoodShotDecals ) ] else return ConcreteShotDecals[ RandomInt( 1, #ConcreteShotDecals ) ] end end --[[--------------------------------------------------------- Paint a decal on a surface, given a start and end position of the trace. @param traceStart Trace start position. @param traceStart Trace end position. -----------------------------------------------------------]] function SWEP:DoImpactDecal( traceStart, traceEnd ) --if ( SERVER ) then local tr = util.TraceLine({ start = traceStart, endpos = traceEnd, filter = { self, self.Owner }, mask = MASK_SHOT_HULL }) if !tr or !tr.Hit then return end local name = util.GetSurfacePropName( tr.SurfaceProps ) local data = EffectData() data:SetOrigin( tr.HitPos ) data:SetNormal( tr.HitNormal ) data:SetScale( 1 ) util.Effect( 'Impact', data ) util.Decal( self:GetIdealSurfaceDecalMaterialName( name ), traceStart, traceEnd ) --end -- end ( SERVER ) end --[[--------------------------------------------------------- Ensure that the weapon should be drawing a muzzle flash effect if it needs to -----------------------------------------------------------]] function SWEP:CheckMuzzleFlash() if self:ShouldDrawMuzzleFlash() then self:EnableMuzzleFlash( true ) else self:EnableMuzzleFlash( false ) end end --[[--------------------------------------------------------- Test if the muzzle flash should be drawn. @return true on success. @return false on failure. -----------------------------------------------------------]] function SWEP:ShouldDrawMuzzleFlash() return self.Weapon:GetDrawMuzzleFlash() end --[[--------------------------------------------------------- Either enable or disable muzzle flash drawing. @param state New muzzle flash state. Can be true or false. -----------------------------------------------------------]] function SWEP:EnableMuzzleFlash( state ) self.Weapon:SetDrawMuzzleFlash( state ) end function SWEP:MuzzleEffect( type, scale ) self.Weapon:SetMuzzleFlashTime( CurTime() ) if ( type != nil ) then self.Weapon:SetMuzzleFlashType( type ) end if ( scale != nil ) then self.Weapon:SetMuzzleFlashScale( scale ) end end function SWEP:GetMuzzleFlashMaterialIndex( muzzleFlashType ) local materialIndex = 1 if muzzleFlashType == MUZZLEFLASH_HL1_GLOCK then materialIndex = 1 elseif muzzleFlashType == MUZZLEFLASH_HL1_MP5 then materialIndex = 2 elseif muzzleFlashType == MUZZLEFLASH_HL1_357 then materialIndex = 3 elseif muzzleFlashType == MUZZLEFLASH_HL1_SHOTGUN_DOUBLE then materialIndex = 3 elseif muzzleFlashType == MUZZLEFLASH_TH_AP9 then materialIndex = 4 elseif muzzleFlashType == MUZZLEFLASH_TH_HKG36 then materialIndex = 4 elseif muzzleFlashType == MUZZLEFLASH_TH_CHAINGUN then materialIndex = 3 elseif muzzleFlashType == MUZZLEFLASH_TH_EINAR1 then materialIndex = 2 end return materialIndex end function SWEP:DoMuzzleFlash() if CLIENT then if self:IsCarriedByLocalPlayer() and !self.Owner:ShouldDrawLocalPlayer() then return end local data = EffectData() data:SetEntity( self ) data:SetMaterialIndex( self:GetMuzzleFlashMaterialIndex( self:GetMuzzleFlashType() or MUZZLEFLASH_HL1_GLOCK ) ) data:SetScale( self.Weapon:GetMuzzleFlashScale() ) util.Effect( "hl1_muzzleflash", data, true, true ) end self.Owner:MuzzleFlash() end function SWEP:UpdateMuzzleFlash() if self.Weapon:GetMuzzleFlashTime() != 0 and self.Weapon:GetMuzzleFlashTime() <= CurTime() then self.Weapon:SetMuzzleFlashTime( 0 ) self:DoMuzzleFlash() end end function SWEP:ResetBodygroups() local owner = self.Owner if !IsValid( owner ) then return false end local vm = owner:GetViewModel() if !vm then return false end vm:SetBodygroup( 0, 0 ) return true end
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Talwahn.lua
34
1032
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Talwahn -- 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(0x0290); 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
johnmccabe/dockercraft
world/Plugins/APIDump/APIDesc.lua
6
260530
-- APIDesc.lua -- Contains the API objects' descriptions g_APIDesc = { Classes = { --[[ -- What the APIDump plugin understands / how to document stuff: ExampleClassName = { Desc = "Description, exported as the first paragraph of the class page. Usually enclosed within double brackets." Functions = { FunctionName = { Params = "Parameter list", Return = "Return values list", Notes = "Notes" ), OverloadedFunctionName = -- When a function supports multiple parameter variants { { Params = "Parameter list 1", Return = "Return values list 1", Notes = "Notes 1" }, { Params = "Parameter list 2", Return = "Return values list 2", Notes = "Notes 2" }, } } , Constants = { ConstantName = { Notes = "Notes about the constant" }, } , ConstantGroups = { GroupName1 = -- GroupName1 is used as the HTML anchor name { Include = {"constant1", "constant2", "const_.*"}, -- Constants to include in this group, array of identifiers, accepts wildcards TextBefore = "This text will be written in front of the constant list", TextAfter = "This text will be written after the constant list", ShowInDescendants = false, -- If false, descendant classes won't list these constants } }, Variables = { VariableName = { Type = "string", Notes = "Notes about the variable" }, } , AdditionalInfo = -- Paragraphs to be exported after the function definitions table { { Header = "Header 1", Contents = "Contents of the additional section 1", }, { Header = "Header 2", Contents = "Contents of the additional section 2", } }, Inherits = "ParentClassName", -- Only present if the class inherits from another API class }, ]]-- cBlockArea = { Desc = [[ This class is used when multiple adjacent blocks are to be manipulated. Because of chunking and multithreading, manipulating single blocks using {{cWorld|cWorld:SetBlock}}() is a rather time-consuming operation (locks for exclusive access need to be obtained, chunk lookup is done for each block), so whenever you need to manipulate multiple adjacent blocks, it's better to wrap the operation into a cBlockArea access. cBlockArea is capable of reading / writing across chunk boundaries, has no chunk lookups for get and set operations and is not subject to multithreading locking (because it is not shared among threads).</p> <p> cBlockArea remembers its origin (MinX, MinY, MinZ coords in the Read() call) and therefore supports absolute as well as relative get / set operations. Despite that, the contents of a cBlockArea can be written back into the world at any coords.</p> <p> cBlockArea can hold any combination of the following datatypes:<ul> <li>block types</li> <li>block metas</li> <li>blocklight</li> <li>skylight</li> </ul> Read() and Write() functions have parameters that tell the class which datatypes to read / write. Note that a datatype that has not been read cannot be written (FIXME).</p> <p> Typical usage:<ul> <li>Create cBlockArea object</li> <li>Read an area from the world / load from file / create anew</li> <li>Modify blocks inside cBlockArea</li> <li>Write the area back to a world / save to file</li> </ul></p> ]], Functions = { constructor = { Params = "", Return = "cBlockArea", Notes = "Creates a new empty cBlockArea object" }, Clear = { Params = "", Return = "", Notes = "Clears the object, resets it to zero size" }, CopyFrom = { Params = "BlockAreaSrc", Return = "", Notes = "Copies contents from BlockAreaSrc into self" }, CopyTo = { Params = "BlockAreaDst", Return = "", Notes = "Copies contents from self into BlockAreaDst." }, CountNonAirBlocks = { Params = "", Return = "number", Notes = "Returns the count of blocks that are not air. Returns 0 if blocktypes not available. Block metas are ignored (if present, air with any meta is still considered air)." }, CountSpecificBlocks = { { Params = "BlockType", Return = "number", Notes = "Counts the number of occurences of the specified blocktype contained in the area." }, { Params = "BlockType, BlockMeta", Return = "number", Notes = "Counts the number of occurrences of the specified blocktype + blockmeta combination contained in the area." }, }, Create = { Params = "SizeX, SizeY, SizeZ, [DataTypes]", Return = "", Notes = "Initializes this BlockArea to an empty area of the specified size and origin of {0, 0, 0}. Any previous contents are lost." }, Crop = { Params = "AddMinX, SubMaxX, AddMinY, SubMaxY, AddMinZ, SubMaxZ", Return = "", Notes = "Crops the specified number of blocks from each border. Modifies the size of this blockarea object." }, DumpToRawFile = { Params = "FileName", Return = "", Notes = "Dumps the raw data into a file. For debugging purposes only." }, Expand = { Params = "SubMinX, AddMaxX, SubMinY, AddMaxY, SubMinZ, AddMaxZ", Return = "", Notes = "Expands the specified number of blocks from each border. Modifies the size of this blockarea object. New blocks created with this operation are filled with zeroes." }, Fill = { Params = "DataTypes, BlockType, [BlockMeta], [BlockLight], [BlockSkyLight]", Return = "", Notes = "Fills the entire block area with the same values, specified. Uses the DataTypes param to determine which content types are modified." }, FillRelCuboid = { { Params = "{{cCuboid|RelCuboid}}, DataTypes, BlockType, [BlockMeta], [BlockLight], [BlockSkyLight]", Return = "", Notes = "Fills the specified cuboid (in relative coords) with the same values (like Fill() )." }, { Params = "MinRelX, MaxRelX, MinRelY, MaxRelY, MinRelZ, MaxRelZ, DataTypes, BlockType, [BlockMeta], [BlockLight], [BlockSkyLight]", Return = "", Notes = "Fills the specified cuboid with the same values (like Fill() )." }, }, GetBlockLight = { Params = "BlockX, BlockY, BlockZ", Return = "NIBBLETYPE", Notes = "Returns the blocklight at the specified absolute coords" }, GetBlockMeta = { Params = "BlockX, BlockY, BlockZ", Return = "NIBBLETYPE", Notes = "Returns the block meta at the specified absolute coords" }, GetBlockSkyLight = { Params = "BlockX, BlockY, BlockZ", Return = "NIBBLETYPE", Notes = "Returns the skylight at the specified absolute coords" }, GetBlockType = { Params = "BlockX, BlockY, BlockZ", Return = "BLOCKTYPE", Notes = "Returns the block type at the specified absolute coords" }, GetBlockTypeMeta = { Params = "BlockX, BlockY, BlockZ", Return = "BLOCKTYPE, NIBBLETYPE", Notes = "Returns the block type and meta at the specified absolute coords" }, GetCoordRange = {Params = "", Return = "MaxX, MaxY, MaxZ", Notes = "Returns the maximum relative coords in all 3 axes. See also GetSize()." }, GetDataTypes = { Params = "", Return = "number", Notes = "Returns the mask of datatypes that the object is currently holding" }, GetOrigin = { Params = "", Return = "OriginX, OriginY, OriginZ", Notes = "Returns the origin coords of where the area was read from." }, GetOriginX = { Params = "", Return = "number", Notes = "Returns the origin x-coord" }, GetOriginY = { Params = "", Return = "number", Notes = "Returns the origin y-coord" }, GetOriginZ = { Params = "", Return = "number", Notes = "Returns the origin z-coord" }, GetNonAirCropRelCoords = { Params = "[IgnoreBlockType]", Return = "MinRelX, MinRelY, MinRelZ, MaxRelX, MaxRelY, MaxRelZ", Notes = "Returns the minimum and maximum coords in each direction for the first non-ignored block in each direction. If there are no non-ignored blocks within the area, or blocktypes are not present, the returned values are reverse-ranges (MinX <- m_RangeX, MaxX <- 0 etc.). IgnoreBlockType defaults to air." }, GetRelBlockLight = { Params = "RelBlockX, RelBlockY, RelBlockZ", Return = "NIBBLETYPE", Notes = "Returns the blocklight at the specified relative coords" }, GetRelBlockMeta = { Params = "RelBlockX, RelBlockY, RelBlockZ", Return = "NIBBLETYPE", Notes = "Returns the block meta at the specified relative coords" }, GetRelBlockSkyLight = { Params = "RelBlockX, RelBlockY, RelBlockZ", Return = "NIBBLETYPE", Notes = "Returns the skylight at the specified relative coords" }, GetRelBlockType = { Params = "RelBlockX, RelBlockY, RelBlockZ", Return = "BLOCKTYPE", Notes = "Returns the block type at the specified relative coords" }, GetRelBlockTypeMeta = { Params = "RelBlockX, RelBlockY, RelBlockZ", Return = "BLOCKTYPE, NIBBLETYPE", Notes = "Returns the block type and meta at the specified relative coords" }, GetSize = { Params = "", Return = "SizeX, SizeY, SizeZ", Notes = "Returns the size of the area in all 3 axes. See also GetCoordRange()." }, GetSizeX = { Params = "", Return = "number", Notes = "Returns the size of the held data in the x-axis" }, GetSizeY = { Params = "", Return = "number", Notes = "Returns the size of the held data in the y-axis" }, GetSizeZ = { Params = "", Return = "number", Notes = "Returns the size of the held data in the z-axis" }, GetVolume = { Params = "", Return = "number", Notes = "Returns the volume of the area - the total number of blocks stored within." }, GetWEOffset = { Params = "", Return = "{{Vector3i}}", Notes = "Returns the WE offset, a data value sometimes stored in the schematic files. Cuberite doesn't use this value, but provides access to it using this method. The default is {0, 0, 0}."}, HasBlockLights = { Params = "", Return = "bool", Notes = "Returns true if current datatypes include blocklight" }, HasBlockMetas = { Params = "", Return = "bool", Notes = "Returns true if current datatypes include block metas" }, HasBlockSkyLights = { Params = "", Return = "bool", Notes = "Returns true if current datatypes include skylight" }, HasBlockTypes = { Params = "", Return = "bool", Notes = "Returns true if current datatypes include block types" }, LoadFromSchematicFile = { Params = "FileName", Return = "", Notes = "Clears current content and loads new content from the specified schematic file. Returns true if successful. Returns false and logs error if unsuccessful, old content is preserved in such a case." }, LoadFromSchematicString = { Params = "SchematicData", Return = "", Notes = "Clears current content and loads new content from the specified string (assumed to contain .schematic data). Returns true if successful. Returns false and logs error if unsuccessful, old content is preserved in such a case." }, Merge = { { Params = "BlockAreaSrc, {{Vector3i|RelMinCoords}}, Strategy", Return = "", Notes = "Merges BlockAreaSrc into this object at the specified relative coords, using the specified strategy" }, { Params = "BlockAreaSrc, RelX, RelY, RelZ, Strategy", Return = "", Notes = "Merges BlockAreaSrc into this object at the specified relative coords, using the specified strategy" }, }, MirrorXY = { Params = "", Return = "", Notes = "Mirrors this block area around the XY plane. Modifies blocks' metas (if present) to match (i. e. furnaces facing the opposite direction)." }, MirrorXYNoMeta = { Params = "", Return = "", Notes = "Mirrors this block area around the XY plane. Doesn't modify blocks' metas." }, MirrorXZ = { Params = "", Return = "", Notes = "Mirrors this block area around the XZ plane. Modifies blocks' metas (if present)" }, MirrorXZNoMeta = { Params = "", Return = "", Notes = "Mirrors this block area around the XZ plane. Doesn't modify blocks' metas." }, MirrorYZ = { Params = "", Return = "", Notes = "Mirrors this block area around the YZ plane. Modifies blocks' metas (if present)" }, MirrorYZNoMeta = { Params = "", Return = "", Notes = "Mirrors this block area around the YZ plane. Doesn't modify blocks' metas." }, Read = { { Params = "World, {{cCuboid|Cuboid}}, DataTypes", Return = "bool", Notes = "Reads the area from World, returns true if successful" }, { Params = "World, {{Vector3i|Point1}}, {{Vector3i|Point2}}, DataTypes", Return = "bool", Notes = "Reads the area from World, returns true if successful" }, { Params = "World, X1, X2, Y1, Y2, Z1, Z2, DataTypes", Return = "bool", Notes = "Reads the area from World, returns true if successful" }, }, RelLine = { { Params = "{{Vector3i|RelPoint1}}, {{Vector3i|RelPoint2}}, DataTypes, BlockType, [BlockMeta], [BlockLight], [BlockSkyLight]", Return = "", Notes = "Draws a line between the two specified points. Sets only datatypes specified by DataTypes (baXXX constants)." }, { Params = "RelX1, RelY1, RelZ1, RelX2, RelY2, RelZ2, DataTypes, BlockType, [BlockMeta], [BlockLight], [BlockSkyLight]", Return = "", Notes = "Draws a line between the two specified points. Sets only datatypes specified by DataTypes (baXXX constants)." }, }, RotateCCW = { Params = "", Return = "", Notes = "Rotates the block area around the Y axis, counter-clockwise (east -> north). Modifies blocks' metas (if present) to match." }, RotateCCWNoMeta = { Params = "", Return = "", Notes = "Rotates the block area around the Y axis, counter-clockwise (east -> north). Doesn't modify blocks' metas." }, RotateCW = { Params = "", Return = "", Notes = "Rotates the block area around the Y axis, clockwise (north -> east). Modifies blocks' metas (if present) to match." }, RotateCWNoMeta = { Params = "", Return = "", Notes = "Rotates the block area around the Y axis, clockwise (north -> east). Doesn't modify blocks' metas." }, SaveToSchematicFile = { Params = "FileName", Return = "", Notes = "Saves the current contents to a schematic file. Returns true if successful." }, SaveToSchematicString = { Params = "", Return = "string", Notes = "Saves the current contents to a string (in a .schematic file format). Returns the data if successful, nil if failed." }, SetBlockLight = { Params = "BlockX, BlockY, BlockZ, BlockLight", Return = "", Notes = "Sets the blocklight at the specified absolute coords" }, SetBlockMeta = { Params = "BlockX, BlockY, BlockZ, BlockMeta", Return = "", Notes = "Sets the block meta at the specified absolute coords" }, SetBlockSkyLight = { Params = "BlockX, BlockY, BlockZ, SkyLight", Return = "", Notes = "Sets the skylight at the specified absolute coords" }, SetBlockType = { Params = "BlockX, BlockY, BlockZ, BlockType", Return = "", Notes = "Sets the block type at the specified absolute coords" }, SetBlockTypeMeta = { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta", Return = "", Notes = "Sets the block type and meta at the specified absolute coords" }, SetOrigin = { { Params = "{{Vector3i|Origin}}", Return = "", Notes = "Resets the origin for the absolute coords. Only affects how absolute coords are translated into relative coords." }, { Params = "OriginX, OriginY, OriginZ", Return = "", Notes = "Resets the origin for the absolute coords. Only affects how absolute coords are translated into relative coords." }, }, SetRelBlockLight = { Params = "RelBlockX, RelBlockY, RelBlockZ, BlockLight", Return = "", Notes = "Sets the blocklight at the specified relative coords" }, SetRelBlockMeta = { Params = "RelBlockX, RelBlockY, RelBlockZ, BlockMeta", Return = "", Notes = "Sets the block meta at the specified relative coords" }, SetRelBlockSkyLight = { Params = "RelBlockX, RelBlockY, RelBlockZ, SkyLight", Return = "", Notes = "Sets the skylight at the specified relative coords" }, SetRelBlockType = { Params = "RelBlockX, RelBlockY, RelBlockZ, BlockType", Return = "", Notes = "Sets the block type at the specified relative coords" }, SetRelBlockTypeMeta = { Params = "RelBlockX, RelBlockY, RelBlockZ, BlockType, BlockMeta", Return = "", Notes = "Sets the block type and meta at the specified relative coords" }, SetWEOffset = { { Params = "{{Vector3i|Offset}}", Return = "", Notes = "Sets the WE offset, a data value sometimes stored in the schematic files. Mostly used for WorldEdit. Cuberite doesn't use this value, but provides access to it using this method." }, { Params = "OffsetX, OffsetY, OffsetZ", Return = "", Notes = "Sets the WE offset, a data value sometimes stored in the schematic files. Mostly used for WorldEdit. Cuberite doesn't use this value, but provides access to it using this method." }, }, Write = { { Params = "World, {{Vector3i|MinPoint}}, DataTypes", Return = "bool", Notes = "Writes the area into World at the specified coords, returns true if successful" }, { Params = "World, MinX, MinY, MinZ, DataTypes", Return = "bool", Notes = "Writes the area into World at the specified coords, returns true if successful" }, }, }, Constants = { baTypes = { Notes = "Operation should work on block types" }, baMetas = { Notes = "Operations should work on block metas" }, baLight = { Notes = "Operations should work on block (emissive) light" }, baSkyLight = { Notes = "Operations should work on skylight" }, msDifference = { Notes = "Block becomes air if 'self' and src are the same. Otherwise it becomes the src block." }, msFillAir = { Notes = "'self' is overwritten by Src only where 'self' has air blocks" }, msImprint = { Notes = "Src overwrites 'self' anywhere where 'self' has non-air blocks" }, msLake = { Notes = "Special mode for merging lake images" }, msMask = { Notes = "The blocks that are exactly the same are kept in 'self', all differing blocks are replaced by air"}, msOverwrite = { Notes = "Src overwrites anything in 'self'" }, msSimpleCompare = { Notes = "The blocks that are exactly the same are replaced with air, all differing blocks are replaced by stone"}, msSpongePrint = { Notes = "Similar to msImprint, sponge block doesn't overwrite anything, all other blocks overwrite everything"}, }, ConstantGroups = { BATypes = { Include = "ba.*", TextBefore = [[ The following constants are used to signalize the datatype to read or write: ]], }, MergeStrategies = { Include = "ms.*", TextBefore = [[ The Merge() function can use different strategies to combine the source and destination blocks. The following constants are used: ]], TextAfter = "See below for a detailed explanation of the individual merge strategies.", }, }, AdditionalInfo = { { Header = "Merge strategies", Contents = [[ <p>The strategy parameter specifies how individual blocks are combined together, using the table below. </p> <table class="inline"> <tbody><tr> <th colspan="2">area block</th><th colspan="3">result</th> </tr> <tr> <th> this </th><th> Src </th><th> msOverwrite </th><th> msFillAir </th><th> msImprint </th> </tr> <tr> <td> air </td><td> air </td><td> air </td><td> air </td><td> air </td> </tr> <tr> <td> A </td><td> air </td><td> air </td><td> A </td><td> A </td> </tr> <tr> <td> air </td><td> B </td><td> B </td><td> B </td><td> B </td> </tr> <tr> <td> A </td><td> B </td><td> B </td><td> A </td><td> B </td> </tr> <tr> <td> A </td><td> A </td><td> A </td><td> A </td><td> A </td> </td> </tbody></table> <p> So to sum up: <ol> <li class="level1">msOverwrite completely overwrites all blocks with the Src's blocks</li> <li class="level1">msFillAir overwrites only those blocks that were air</li> <li class="level1">msImprint overwrites with only those blocks that are non-air</li> </ol> </p> <h3>Special strategies</h3> <p>For each strategy, evaluate the table rows from top downwards, the first match wins.</p> <p> <strong>msDifference</strong> - changes all the blocks which are the same to air. Otherwise the source block gets placed. </p> <table><tbody<tr> <th colspan="2"> area block </th><th> </th><th> Notes </th> </tr><tr> <td> * </td><td> B </td><td> B </td><td> The blocks are different so we use block B </td> </tr><tr> <td> B </td><td> B </td><td> Air </td><td> The blocks are the same so we get air. </td> </tr> </tbody></table> <p> <strong>msLake</strong> - used for merging areas with lava and water lakes, in the appropriate generator. </p> <table><tbody><tr> <th colspan="2"> area block </th><th> </th><th> Notes </th> </tr><tr> <th> self </th><th> Src </th><th> result </th><th> </th> </tr><tr> <td> A </td><td> sponge </td><td> A </td><td> Sponge is the NOP block </td> </tr><tr> <td> * </td><td> air </td><td> air </td><td> Air always gets hollowed out, even under the oceans </td> </tr><tr> <td> water </td><td> * </td><td> water </td><td> Water is never overwritten </td> </tr><tr> <td> lava </td><td> * </td><td> lava </td><td> Lava is never overwritten </td> </tr><tr> <td> * </td><td> water </td><td> water </td><td> Water always overwrites anything </td> </tr><tr> <td> * </td><td> lava </td><td> lava </td><td> Lava always overwrites anything </td> </tr><tr> <td> dirt </td><td> stone </td><td> stone </td><td> Stone overwrites dirt </td> </tr><tr> <td> grass </td><td> stone </td><td> stone </td><td> ... and grass </td> </tr><tr> <td> mycelium </td><td> stone </td><td> stone </td><td> ... and mycelium </td> </tr><tr> <td> A </td><td> stone </td><td> A </td><td> ... but nothing else </td> </tr><tr> <td> A </td><td> * </td><td> A </td><td> Everything else is left as it is </td> </tr> </tbody></table> <p> <strong>msSpongePrint</strong> - used for most prefab-generators to merge the prefabs. Similar to msImprint, but uses the sponge block as the NOP block instead, so that the prefabs may carve out air pockets, too. </p> <table><tbody><tr> <th colspan="2"> area block </th><th> </th><th> Notes </th> </tr><tr> <th> self </th><th> Src </th><th> result </th><th> </th> </tr><tr> <td> A </td><td> sponge </td><td> A </td><td> Sponge is the NOP block </td> </tr><tr> <td> * </td><td> B </td><td> B </td><td> Everything else overwrites anything </td> </tr> </tbody></table> <p> <strong>msMask</strong> - the blocks that are the same in the other area are kept, all the differing blocks are replaced with air. Meta is used in the comparison, too, two blocks of the same type but different meta are considered different and thus replaced with air. </p> <table><tbody><tr> <th colspan="2"> area block </th><th> </th><th> Notes </th> </tr><tr> <th> self </th><th> Src </th><th> result </th><th> </th> </tr><tr> <td> A </td><td> A </td><td> A </td><td> Same blocks are kept </td> </tr><tr> <td> A </td><td> non-A </td><td> air </td><td> Differing blocks are replaced with air </td> </tr> </tbody></table> <p> <strong>msDifference</strong> - the blocks that are the same in both areas are replaced with air, all the differing blocks are kept from the first area. Meta is used in the comparison, too, two blocks of the same type but different meta are considered different. </p> <table><tbody><tr> <th colspan="2"> area block </th><th> </th><th> Notes </th> </tr><tr> <th> self </th><th> Src </th><th> result </th><th> </th> </tr><tr> <td> A </td><td> A </td><td> air </td><td> Same blocks are replaced with air </td> </tr><tr> <td> A </td><td> non-A </td><td> A </td><td> Differing blocks are kept from 'self' </td> </tr> </tbody></table> <p> <strong>msSimpleCompare</strong> - the blocks that are the same in both areas are replaced with air, all the differing blocks are replaced with stone. Meta is used in the comparison, too, two blocks of the same type but different meta are considered different. </p> <table><tbody><tr> <th colspan="2"> area block </th><th> </th><th> Notes </th> </tr><tr> <th> self </th><th> Src </th><th> result </th><th> </th> </tr><tr> <td> A </td><td> A </td><td> air </td><td> Same blocks are replaced with air </td> </tr><tr> <td> A </td><td> non-A </td><td> stone </td><td> Differing blocks are replaced with stone </td> </tr> </tbody></table> ]], }, -- Merge strategies }, -- AdditionalInfo }, -- cBlockArea cBlockInfo = { Desc = [[ This class is used to query and register block properties. ]], Functions = { CanBeTerraformed = { Params = "Type", Return = "bool", Notes = "(STATIC) Returns true if the block is suitable to be changed by a generator" }, FullyOccupiesVoxel = { Params = "Type", Return = "bool", Notes = "(STATIC) Returns whether the specified block fully occupies its voxel." }, Get = { Params = "Type", Return = "{{cBlockInfo}}", Notes = "(STATIC) Returns the {{cBlockInfo}} structure for the specified type." }, GetLightValue = { Params = "Type", Return = "number", Notes = "(STATIC) Returns how much light the specified block emits on its own." }, GetPlaceSound = { Params = "Type", Return = "", Notes = "(STATIC) Returns the name of the sound that is played when placing the block." }, GetSpreadLightFalloff = { Params = "Type", Return = "number", Notes = "(STATIC) Returns how much light the specified block consumes." }, IsOneHitDig = { Params = "Type", Return = "bool", Notes = "(STATIC) Returns whether the specified block will be destroyed after a single hit." }, IsPistonBreakable = { Params = "Type", Return = "bool", Notes = "(STATIC) Returns whether a piston can break the specified block." }, IsSnowable = { Params = "Type", Return = "bool", Notes = "(STATIC) Returns whether the specified block can hold snow atop." }, IsSolid = { Params = "Type", Return = "bool", Notes = "(STATIC) Returns whether the specified block is solid." }, IsTransparent = { Params = "Type", Return = "bool", Notes = "(STATIC) Returns whether the specified block is transparent." }, RequiresSpecialTool = { Params = "Type", Return = "bool", Notes = "(STATIC) Returns whether the specified block requires a special tool to drop." }, }, Variables = { m_CanBeTerraformed = { Type = "bool", Notes = "Is this block suited to be terraformed?" }, m_FullyOccupiesVoxel = { Type = "bool", Notes = "Does this block fully occupy its voxel - is it a 'full' block?" }, m_IsSnowable = { Type = "bool", Notes = "Can this block hold snow atop?" }, m_IsSolid = { Type = "bool", Notes = "Is this block solid (player cannot walk through)?" }, m_LightValue = { Type = "number", Notes = "How much light do the blocks emit on their own?" }, m_OneHitDig = { Type = "bool", Notes = "Is a block destroyed after a single hit?" }, m_PistonBreakable = { Type = "bool", Notes = "Can a piston break this block?" }, m_PlaceSound = { Type = "string", Notes = "The name of the sound that is placed when a block is placed." }, m_RequiresSpecialTool = { Type = "bool", Notes = "Does this block require a tool to drop?" }, m_SpreadLightFalloff = { Type = "number", Notes = "How much light do the blocks consume?" }, m_Transparent = { Type = "bool", Notes = "Is a block completely transparent? (light doesn't get decreased(?))" }, }, }, -- cBlockInfo cChatColor = { Desc = [[ A wrapper class for constants representing colors or effects. ]], Functions = {}, Constants = { Black = { Notes = "" }, Blue = { Notes = "" }, Bold = { Notes = "" }, Color = { Notes = "The first character of the color-code-sequence, �" }, DarkPurple = { Notes = "" }, Delimiter = { Notes = "The first character of the color-code-sequence, �" }, Gold = { Notes = "" }, Gray = { Notes = "" }, Green = { Notes = "" }, Italic = { Notes = "" }, LightBlue = { Notes = "" }, LightGray = { Notes = "" }, LightGreen = { Notes = "" }, LightPurple = { Notes = "" }, Navy = { Notes = "" }, Plain = { Notes = "Resets all formatting to normal" }, Purple = { Notes = "" }, Random = { Notes = "Random letters and symbols animate instead of the text" }, Red = { Notes = "" }, Rose = { Notes = "" }, Strikethrough = { Notes = "" }, Underlined = { Notes = "" }, White = { Notes = "" }, Yellow = { Notes = "" }, }, }, cChunkDesc = { Desc = [[ The cChunkDesc class is a container for chunk data while the chunk is being generated. As such, it is only used as a parameter for the {{OnChunkGenerating|OnChunkGenerating}} and {{OnChunkGenerated|OnChunkGenerated}} hooks and cannot be constructed on its own. Plugins can use this class in both those hooks to manipulate generated chunks. ]], Functions = { FillBlocks = { Params = "BlockType, BlockMeta", Return = "", Notes = "Fills the entire chunk with the specified blocks" }, FillRelCuboid = { { Params = "{{cCuboid|RelCuboid}}, BlockType, BlockMeta", Return = "", Notes = "Fills the cuboid, specified in relative coords, by the specified block type and block meta. The cuboid may reach outside of the chunk, only the part intersecting with this chunk is filled." }, { Params = "MinRelX, MaxRelX, MinRelY, MaxRelY, MinRelZ, MaxRelZ, BlockType, BlockMeta", Return = "", Notes = "Fills the cuboid, specified in relative coords, by the specified block type and block meta. The cuboid may reach outside of the chunk, only the part intersecting with this chunk is filled." }, }, FloorRelCuboid = { { Params = "{{cCuboid|RelCuboid}}, BlockType, BlockMeta", Return = "", Notes = "Fills those blocks of the cuboid (specified in relative coords) that are considered non-floor (air, water) with the specified block type and meta. Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled." }, { Params = "MinRelX, MaxRelX, MinRelY, MaxRelY, MinRelZ, MaxRelZ, BlockType, BlockMeta", Return = "", Notes = "Fills those blocks of the cuboid (specified in relative coords) that are considered non-floor (air, water) with the specified block type and meta. Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled." }, }, GetBiome = { Params = "RelX, RelZ", Return = "EMCSBiome", Notes = "Returns the biome at the specified relative coords" }, GetBlockEntity = { Params = "RelX, RelY, RelZ", Return = "{{cBlockEntity}} descendant", Notes = "Returns the block entity for the block at the specified coords. Creates it if it doesn't exist. Returns nil if the block has no block entity capability." }, GetBlockMeta = { Params = "RelX, RelY, RelZ", Return = "NIBBLETYPE", Notes = "Returns the block meta at the specified relative coords" }, GetBlockType = { Params = "RelX, RelY, RelZ", Return = "BLOCKTYPE", Notes = "Returns the block type at the specified relative coords" }, GetBlockTypeMeta = { Params = "RelX, RelY, RelZ", Return = "BLOCKTYPE, NIBBLETYPE", Notes = "Returns the block type and meta at the specified relative coords" }, GetChunkX = { Params = "", Return = "number", Notes = "Returns the X coord of the chunk contained." }, GetChunkZ = { Params = "", Return = "number", Notes = "Returns the Z coord of the chunk contained." }, GetHeight = { Params = "RelX, RelZ", Return = "number", Notes = "Returns the height at the specified relative coords" }, GetMaxHeight = { Params = "", Return = "number", Notes = "Returns the maximum height contained in the heightmap." }, GetMinHeight = { Params = "", Return = "number", Notes = "Returns the minimum height value in the heightmap." }, IsUsingDefaultBiomes = { Params = "", Return = "bool", Notes = "Returns true if the chunk is set to use default biome generator" }, IsUsingDefaultComposition = { Params = "", Return = "bool", Notes = "Returns true if the chunk is set to use default composition generator" }, IsUsingDefaultFinish = { Params = "", Return = "bool", Notes = "Returns true if the chunk is set to use default finishers" }, IsUsingDefaultHeight = { Params = "", Return = "bool", Notes = "Returns true if the chunk is set to use default height generator" }, IsUsingDefaultStructures = { Params = "", Return = "bool", Notes = "Returns true if the chunk is set to use default structures" }, RandomFillRelCuboid = { { Params = "{{cCuboid|RelCuboid}}, BlockType, BlockMeta, RandomSeed, ChanceOutOf10k", Return = "", Notes = "Fills the specified relative cuboid with block type and meta in random locations. RandomSeed is used for the random number genertion (same seed produces same results); ChanceOutOf10k specifies the density (how many out of every 10000 blocks should be filled). Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled." }, { Params = "MinRelX, MaxRelX, MinRelY, MaxRelY, MinRelZ, MaxRelZ, BlockType, BlockMeta, RandomSeed, ChanceOutOf10k", Return = "", Notes = "Fills the specified relative cuboid with block type and meta in random locations. RandomSeed is used for the random number genertion (same seed produces same results); ChanceOutOf10k specifies the density (how many out of every 10000 blocks should be filled). Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled." }, }, ReadBlockArea = { Params = "{{cBlockArea|BlockArea}}, MinRelX, MaxRelX, MinRelY, MaxRelY, MinRelZ, MaxRelZ", Return = "", Notes = "Reads data from the chunk into the block area object. Block types and metas are processed." }, ReplaceRelCuboid = { { Params = "{{cCuboid|RelCuboid}}, SrcType, SrcMeta, DstType, DstMeta", Return = "", Notes = "Replaces all SrcType+SrcMeta blocks in the cuboid (specified in relative coords) with DstType+DstMeta blocks. Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled." }, { Params = "MinRelX, MaxRelX, MinRelY, MaxRelY, MinRelZ, MaxRelZ, SrcType, SrcMeta, DstType, DstMeta", Return = "", Notes = "Replaces all SrcType+SrcMeta blocks in the cuboid (specified in relative coords) with DstType+DstMeta blocks. Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled." }, }, SetBiome = { Params = "RelX, RelZ, EMCSBiome", Return = "", Notes = "Sets the biome at the specified relative coords" }, SetBlockMeta = { Params = "RelX, RelY, RelZ, BlockMeta", Return = "", Notes = "Sets the block meta at the specified relative coords" }, SetBlockType = { Params = "RelX, RelY, RelZ, BlockType", Return = "", Notes = "Sets the block type at the specified relative coords" }, SetBlockTypeMeta = { Params = "RelX, RelY, RelZ, BlockType, BlockMeta", Return = "", Notes = "Sets the block type and meta at the specified relative coords" }, SetHeight = { Params = "RelX, RelZ, Height", Return = "", Notes = "Sets the height at the specified relative coords" }, SetUseDefaultBiomes = { Params = "bool", Return = "", Notes = "Sets the chunk to use default biome generator or not" }, SetUseDefaultComposition = { Params = "bool", Return = "", Notes = "Sets the chunk to use default composition generator or not" }, SetUseDefaultFinish = { Params = "bool", Return = "", Notes = "Sets the chunk to use default finishers or not" }, SetUseDefaultHeight = { Params = "bool", Return = "", Notes = "Sets the chunk to use default height generator or not" }, SetUseDefaultStructures = { Params = "bool", Return = "", Notes = "Sets the chunk to use default structures or not" }, UpdateHeightmap = { Params = "", Return = "", Notes = "Updates the heightmap to match current contents. The plugins should do that if they modify the contents and don't modify the heightmap accordingly; Cuberite expects (and checks in Debug mode) that the heightmap matches the contents when the cChunkDesc is returned from a plugin." }, WriteBlockArea = { Params = "{{cBlockArea|BlockArea}}, MinRelX, MinRelY, MinRelZ", Return = "", Notes = "Writes data from the block area into the chunk" }, }, AdditionalInfo = { { Header = "Manipulating block entities", Contents = [[ To manipulate block entities while the chunk is generated, first use SetBlockTypeMeta() to set the correct block type and meta at the position. Then use the GetBlockEntity() to create and return the correct block entity instance. Finally, use {{tolua}}.cast() to cast to the proper type.</p> Note that you don't need to check if a block entity has previously existed at the place, because GetBlockEntity() will automatically re-create the correct type for you.</p> <p> The following code is taken from the Debuggers plugin, it creates a sign at each chunk's [0, 0] coords, with the text being the chunk coords: <pre class="prettyprint lang-lua"> function OnChunkGenerated(a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc) -- Get the topmost block coord: local Height = a_ChunkDesc:GetHeight(0, 0); -- Create a sign there: a_ChunkDesc:SetBlockTypeMeta(0, Height + 1, 0, E_BLOCK_SIGN_POST, 0); local BlockEntity = a_ChunkDesc:GetBlockEntity(0, Height + 1, 0); if (BlockEntity ~= nil) then LOG("Setting sign lines..."); local SignEntity = tolua.cast(BlockEntity, "cSignEntity"); SignEntity:SetLines("Chunk:", tonumber(a_ChunkX) .. ", " .. tonumber(a_ChunkZ), "", "(Debuggers)"); end -- Update the heightmap: a_ChunkDesc:SetHeight(0, 0, Height + 1); end </pre> ]], }, }, -- AdditionalInfo }, -- cChunkDesc cClientHandle = { Desc = [[ A cClientHandle represents the technical aspect of a connected player - their game client connection. Internally, it handles all the incoming and outgoing packets, the chunks that are to be sent to the client, ping times etc. ]], Functions = { GenerateOfflineUUID = { Params = "Username", Return = "string", Notes = "(STATIC) Generates an UUID based on the player name provided. This is used for the offline (non-auth) mode, when there's no UUID source. Each username generates a unique and constant UUID, so that when the player reconnects with the same name, their UUID is the same. Returns a 32-char UUID (no dashes)." }, GetClientBrand = { Params = "", Return = "string", Notes = "Returns the brand that the client has sent in their MC|Brand plugin message." }, GetIPString = { Params = "", Return = "string", Notes = "Returns the IP address of the connection, as a string. Only the address part is returned, without the port number." }, GetLocale = { Params = "", Return = "Locale", Notes = "Returns the locale string that the client sends as part of the protocol handshake. Can be used to provide localized strings." }, GetPing = { Params = "", Return = "number", Notes = "Returns the ping time, in ms" }, GetPlayer = { Params = "", Return = "{{cPlayer|cPlayer}}", Notes = "Returns the player object connected to this client. Note that this may be nil, for example if the player object is not yet spawned." }, GetProtocolVersion = { Params = "", Return = "number", Notes = "Returns the protocol version number of the protocol that the client is talking. Returns zero if the protocol version is not (yet) known." }, GetUniqueID = { Params = "", Return = "number", Notes = "Returns the UniqueID of the client used to identify the client in the server" }, GetUUID = { Params = "", Return = "string", Notes = "Returns the authentication-based UUID of the client. This UUID should be used to identify the player when persisting any player-related data. Returns a 32-char UUID (no dashes)" }, GetUsername = { Params = "", Return = "string", Notes = "Returns the username that the client has provided" }, GetViewDistance = { Params = "", Return = "number", Notes = "Returns the viewdistance (number of chunks loaded for the player in each direction)" }, GetRequestedViewDistance = { Params = "", Return = "number", Notes = "Returns the view distance that the player request, not the used view distance." }, HasPluginChannel = { Params = "ChannelName", Return = "bool", Notes = "Returns true if the client has registered to receive messages on the specified plugin channel." }, IsUUIDOnline = { Params = "UUID", Return = "bool", Notes = "(STATIC) Returns true if the UUID is generated by online auth, false if it is an offline-generated UUID. We use Version-3 UUIDs for offline UUIDs, online UUIDs are Version-4, thus we can tell them apart. Accepts both 32-char and 36-char UUIDs (with and without dashes). If the string given is not a valid UUID, returns false."}, Kick = { Params = "Reason", Return = "", Notes = "Kicks the user with the specified reason" }, SendPluginMessage = { Params = "Channel, Message", Return = "", Notes = "Sends the plugin message on the specified channel." }, SetClientBrand = { Params = "ClientBrand", Return = "", Notes = "Sets the value of the client's brand. Normally this value is received from the client by a MC|Brand plugin message, this function lets plugins overwrite the value." }, SetLocale = { Params = "Locale", Return = "", Notes = "Sets the locale that Cuberite keeps on record. Initially the locale is initialized in protocol handshake, this function allows plugins to override the stored value (but only server-side and only until the user disconnects)." }, SetUsername = { Params = "Name", Return = "", Notes = "Sets the username" }, SetViewDistance = { Params = "ViewDistance", Return = "", Notes = "Sets the viewdistance (number of chunks loaded for the player in each direction)" }, SendBlockChange = { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta", Return = "", Notes = "Sends a BlockChange packet to the client. This can be used to create fake blocks only for that player." }, SendEntityAnimation = { Params = "{{cEntity|Entity}}, AnimationNumber", Return = "", Notes = "Sends the specified animation of the specified entity to the client. The AnimationNumber is protocol-specific." }, SendSoundEffect = { Params = "SoundName, X, Y, Z, Volume, Pitch", Return = "", Notes = "Sends a sound effect request to the client. The sound is played at the specified coords, with the specified volume (a float, 1.0 is full volume, can be more) and pitch (0-255, 63 is 100%)" }, SendTimeUpdate = { Params = "WorldAge, TimeOfDay, DoDaylightCycle", Return = "", Notes = "Sends the specified time update to the client. WorldAge is the total age of the world, in ticks. TimeOfDay is the current day's time, in ticks (0 - 24000). DoDaylightCycle is a bool that specifies whether the client should automatically move the sun (true) or keep it in the same place (false)." }, }, Constants = { MAX_VIEW_DISTANCE = { Notes = "The maximum value of the view distance" }, MIN_VIEW_DISTANCE = { Notes = "The minimum value of the view distance" }, }, }, -- cClientHandle cCompositeChat = { Desc = [[ Encapsulates a chat message that can contain various formatting, URLs, commands executed on click and commands suggested on click. The chat message can be sent by the regular chat-sending functions, {{cPlayer}}:SendMessage(), {{cWorld}}:BroadcastChat() and {{cRoot}}:BroadcastChat().</p> <p> Note that most of the functions in this class are so-called chaining modifiers - they modify the object and then return the object itself, so that they can be chained one after another. See the Chaining example below for details.</p> <p> Each part of the composite chat message takes a "Style" parameter, this is a string that describes the formatting. It uses the following strings, concatenated together: <table> <tr><th>String</th><th>Style</th></tr> <tr><td>b</td><td>Bold text</td></tr> <tr><td>i</td><td>Italic text</td></tr> <tr><td>u</td><td>Underlined text</td></tr> <tr><td>s</td><td>Strikethrough text</td></tr> <tr><td>o</td><td>Obfuscated text</td></tr> <tr><td>@X</td><td>color X (X is 0 - 9 or a - f, same as dye meta</td></tr> </table> The following picture, taken from MineCraft Wiki, illustrates the color codes:</p> <img src="http://hydra-media.cursecdn.com/minecraft.gamepedia.com/4/4c/Colors.png?version=34a0f56789a95326e1f7d82047b12232" /> ]], Functions = { constructor = { { Params = "", Return = "", Notes = "Creates an empty chat message" }, { Params = "Text", Return = "", Notes = "Creates a chat message containing the specified text, parsed by the ParseText() function. This allows easy migration from old chat messages." }, }, AddRunCommandPart = { Params = "Text, Command, [Style]", Return = "self", Notes = "Adds a text which, when clicked, runs the specified command. Chaining." }, AddShowAchievementPart = { Params = "PlayerName, AchievementName, [Style]", Return = "", Notes = "Adds a text that represents the 'Achievement get' message." }, AddSuggestCommandPart = { Params = "Text, Command, [Style]", Return = "self", Notes = "Adds a text which, when clicked, puts the specified command into the player's chat input area. Chaining." }, AddTextPart = { Params = "Text, [Style]", Return = "self", Notes = "Adds a regular text. Chaining." }, AddUrlPart = { Params = "Text, Url, [Style]", Return = "self", Notes = "Adds a text which, when clicked, opens up a browser at the specified URL. Chaining." }, Clear = { Params = "", Return = "", Notes = "Removes all parts from this object" }, CreateJsonString = { Params = "[AddPrefixes]", Return = "string", Notes = "Returns the entire object serialized into JSON, as it would be sent to a client. AddPrefixes specifies whether the chat prefixes should be prepended to the message, true by default." }, ExtractText = { Params = "", Return = "string", Notes = "Returns the text from the parts that comprises the human-readable data. Used for older protocols that don't support composite chat and for console-logging." }, GetAdditionalMessageTypeData = { Params = "", Return = "string", Notes = "Returns the AdditionalData associated with the message, such as the sender's name for mtPrivateMessage" }, GetMessageType = { Params = "", Return = "MessageType", Notes = "Returns the MessageType (mtXXX constant) that is associated with this message. When sent to a player, the message will be formatted according to this message type and the player's settings (adding \"[INFO]\" prefix etc.)" }, ParseText = { Params = "Text", Return = "self", Notes = "Adds text, while recognizing http and https URLs and old-style formatting codes (\"@2\"). Chaining." }, SetMessageType = { Params = "MessageType, AdditionalData", Return = "self", Notes = "Sets the MessageType (mtXXX constant) that is associated with this message. Also sets the additional data (string) associated with the message, which is specific for the message type - such as the sender's name for mtPrivateMessage. When sent to a player, the message will be formatted according to this message type and the player's settings (adding \"[INFO]\" prefix etc.). Chaining." }, UnderlineUrls = { Params = "", Return = "self", Notes = "Makes all URL parts contained in the message underlined. Doesn't affect parts added in the future. Chaining." }, }, AdditionalInfo = { { Header = "Chaining example", Contents = [[ Sending a chat message that is composed of multiple different parts has been made easy thanks to chaining. Consider the following example that shows how a message containing all kinds of parts is sent (adapted from the Debuggers plugin): <pre class="prettyprint lang-lua"> function OnPlayerJoined(a_Player) -- Send an example composite chat message to the player: a_Player:SendMessage(cCompositeChat() :AddTextPart("Hello, ") :AddUrlPart(a_Player:GetName(), "http://www.mc-server.org", "u@2") -- Colored underlined link :AddSuggestCommandPart(", and welcome.", "/help", "u") -- Underlined suggest-command :AddRunCommandPart(" SetDay", "/time set 0") -- Regular text that will execute command when clicked :SetMessageType(mtJoin) -- It is a join-message ) end</pre> ]], }, }, -- AdditionalInfo }, -- cCompositeChat cCraftingGrid = { Desc = [[ cCraftingGrid represents the player's crafting grid. It is used in {{OnCraftingNoRecipe|OnCraftingNoRecipe}}, {{OnPostCrafting|OnPostCrafting}} and {{OnPreCrafting|OnPreCrafting}} hooks. Plugins may use it to inspect the items the player placed on their crafting grid.</p> <p> Also, an object of this type is used in {{cCraftingRecipe}}'s ConsumeIngredients() function for specifying the exact number of ingredients to consume in that recipe; plugins may use this to apply the crafting recipe.</p> ]], Functions = { constructor = { Params = "Width, Height", Return = "cCraftingGrid", Notes = "Creates a new CraftingGrid object. This new crafting grid is not related to any player, but may be needed for {{cCraftingRecipe}}'s ConsumeIngredients function." }, Clear = { Params = "", Return = "", Notes = "Clears the entire grid" }, ConsumeGrid = { Params = "{{cCraftingGrid|CraftingGrid}}", Return = "", Notes = "Consumes items specified in CraftingGrid from the current contents. Used internally by {{cCraftingRecipe}}'s ConsumeIngredients() function, but available to plugins, too." }, Dump = { Params = "", Return = "", Notes = "DEBUG build: Dumps the contents of the grid to the log. RELEASE build: no action" }, GetHeight = { Params = "", Return = "number", Notes = "Returns the height of the grid" }, GetItem = { Params = "x, y", Return = "{{cItem|cItem}}", Notes = "Returns the item at the specified coords" }, GetWidth = { Params = "", Return = "number", Notes = "Returns the width of the grid" }, SetItem = { { Params = "x, y, {{cItem|cItem}}", Return = "", Notes = "Sets the item at the specified coords" }, { Params = "x, y, ItemType, ItemCount, ItemDamage", Return = "", Notes = "Sets the item at the specified coords" }, }, }, }, -- cCraftingGrid cCraftingRecipe = { Desc = [[ This class is used to represent a crafting recipe, either a built-in one, or one created dynamically in a plugin. It is used only as a parameter for {{OnCraftingNoRecipe|OnCraftingNoRecipe}}, {{OnPostCrafting|OnPostCrafting}} and {{OnPreCrafting|OnPreCrafting}} hooks. Plugins may use it to inspect or modify a crafting recipe that a player views in their crafting window, either at a crafting table or the survival inventory screen. </p> <p>Internally, the class contains a {{cCraftingGrid}} for the ingredients and a {{cItem}} for the result. ]], Functions = { Clear = { Params = "", Return = "", Notes = "Clears the entire recipe, both ingredients and results" }, ConsumeIngredients = { Params = "CraftingGrid", Return = "", Notes = "Consumes ingredients specified in the given {{cCraftingGrid|cCraftingGrid}} class" }, Dump = { Params = "", Return = "", Notes = "DEBUG build: dumps ingredients and result into server log. RELEASE build: no action" }, GetIngredient = { Params = "x, y", Return = "{{cItem|cItem}}", Notes = "Returns the ingredient stored in the recipe at the specified coords" }, GetIngredientsHeight = { Params = "", Return = "number", Notes = "Returns the height of the ingredients' grid" }, GetIngredientsWidth = { Params = "", Return = "number", Notes = "Returns the width of the ingredients' grid" }, GetResult = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the result of the recipe" }, SetIngredient = { { Params = "x, y, {{cItem|cItem}}", Return = "", Notes = "Sets the ingredient at the specified coords" }, { Params = "x, y, ItemType, ItemCount, ItemDamage", Return = "", Notes = "Sets the ingredient at the specified coords" }, }, SetResult = { { Params = "{{cItem|cItem}}", Return = "", Notes = "Sets the result item" }, { Params = "ItemType, ItemCount, ItemDamage", Return = "", Notes = "Sets the result item" }, }, }, }, -- cCraftingRecipe cCryptoHash = { Desc = [[ Provides functions for generating cryptographic hashes.</p> <p> Note that all functions in this class are static, so they should be called in the dot convention: <pre class="prettyprint lang-lua"> local Hash = cCryptoHash.sha1HexString("DataToHash") </pre></p> <p>Each cryptographic hash has two variants, one returns the hash as a raw binary string, the other returns the hash as a hex-encoded string twice as long as the binary string. ]], Functions = { md5 = { Params = "Data", Return = "string", Notes = "(STATIC) Calculates the md5 hash of the data, returns it as a raw (binary) string of 16 characters." }, md5HexString = { Params = "Data", Return = "string", Notes = "(STATIC) Calculates the md5 hash of the data, returns it as a hex-encoded string of 32 characters." }, sha1 = { Params = "Data", Return = "string", Notes = "(STATIC) Calculates the sha1 hash of the data, returns it as a raw (binary) string of 20 characters." }, sha1HexString = { Params = "Data", Return = "string", Notes = "(STATIC) Calculates the sha1 hash of the data, returns it as a hex-encoded string of 40 characters." }, }, }, -- cCryptoHash cEnchantments = { Desc = [[ This class is the storage for enchantments for a single {{cItem|cItem}} object, through its m_Enchantments member variable. Although it is possible to create a standalone object of this class, it is not yet used in any API directly.</p> <p> Enchantments can be initialized either programmatically by calling the individual functions (SetLevel()), or by using a string description of the enchantment combination. This string description is in the form "id=lvl;id=lvl;...;id=lvl;", where id is either a numerical ID of the enchantment, or its textual representation from the table below, and lvl is the desired enchantment level. The class can also create its string description from its current contents; however that string description will only have the numerical IDs.</p> <p> See the {{cItem}} class for usage examples. ]], Functions = { constructor = { { Params = "", Return = "cEnchantments", Notes = "Creates a new empty cEnchantments object" }, { Params = "StringSpec", Return = "cEnchantments", Notes = "Creates a new cEnchantments object filled with enchantments based on the string description" }, }, operator_eq = { Params = "OtherEnchantments", Return = "bool", Notes = "Returns true if this enchantments object has the same enchantments as OtherEnchantments." }, AddFromString = { Params = "StringSpec", Return = "", Notes = "Adds the enchantments in the string description into the object. If a specified enchantment already existed, it is overwritten." }, Clear = { Params = "", Return = "", Notes = "Removes all enchantments" }, GetLevel = { Params = "EnchantmentNumID", Return = "number", Notes = "Returns the level of the specified enchantment stored in this object; 0 if not stored" }, IsEmpty = { Params = "", Return = "bool", Notes = "Returns true if the object stores no enchantments" }, SetLevel = { Params = "EnchantmentNumID, Level", Return = "", Notes = "Sets the level for the specified enchantment, adding it if not stored before or removing it if level < = 0" }, StringToEnchantmentID = { Params = "EnchantmentTextID", Return = "number", Notes = "(static) Returns the enchantment numerical ID, -1 if not understood. Case insensitive. Also understands plain numbers." }, ToString = { Params = "", Return = "string", Notes = "Returns the string description of all the enchantments stored in this object, in numerical-ID form" }, }, Constants = { -- Only list these enchantment IDs, as they don't really need any kind of documentation: enchAquaAffinity = { Notes = "" }, enchBaneOfArthropods = { Notes = "" }, enchBlastProtection = { Notes = "" }, enchEfficiency = { Notes = "" }, enchFeatherFalling = { Notes = "" }, enchFireAspect = { Notes = "" }, enchFireProtection = { Notes = "" }, enchFlame = { Notes = "" }, enchFortune = { Notes = "" }, enchInfinity = { Notes = "" }, enchKnockback = { Notes = "" }, enchLooting = { Notes = "" }, enchLuckOfTheSea = { Notes = "" }, enchLure = { Notes = "" }, enchPower = { Notes = "" }, enchProjectileProtection = { Notes = "" }, enchProtection = { Notes = "" }, enchPunch = { Notes = "" }, enchRespiration = { Notes = "" }, enchSharpness = { Notes = "" }, enchSilkTouch = { Notes = "" }, enchSmite = { Notes = "" }, enchThorns = { Notes = "" }, enchUnbreaking = { Notes = "" }, }, }, cEntity = { Desc = [[ A cEntity object represents an object in the world, it has a position and orientation. cEntity is an abstract class, and can not be instantiated directly, instead, all entities are implemented as subclasses. The cEntity class works as the common interface for the operations that all (most) entities support.</p> <p> All cEntity objects have an Entity Type so it can be determined what kind of entity it is efficiently. Entities also have a class inheritance awareness, they know their class name, their parent class' name and can decide if there is a class within their inheritance chain. Since these functions operate on strings, they are slightly slower than checking the entity type directly, on the other hand, they are more specific directly. To check if the entity is a spider, you need to call IsMob(), then cast the object to {{cMonster}} and finally compare {{cMonster}}:GetMonsterType() to mtSpider. GetClass(), on the other hand, returns "cSpider" directly.</p> <p> Note that you should not store a cEntity object between two hooks' calls, because Cuberite may despawn / remove that entity in between the calls. If you need to refer to an entity later, use its UniqueID and {{cWorld|cWorld}}'s entity manipulation functions DoWithEntityByID(), ForEachEntity() or ForEachEntityInChunk() to access the entity again.</p> ]], Functions = { AddPosition = { { Params = "OffsetX, OffsetY, OffsetZ", Return = "", Notes = "Moves the entity by the specified amount in each axis direction" }, { Params = "{{Vector3d|Offset}}", Return = "", Notes = "Moves the entity by the specified amount in each direction" }, }, AddPosX = { Params = "OffsetX", Return = "", Notes = "Moves the entity by the specified amount in the X axis direction" }, AddPosY = { Params = "OffsetY", Return = "", Notes = "Moves the entity by the specified amount in the Y axis direction" }, AddPosZ = { Params = "OffsetZ", Return = "", Notes = "Moves the entity by the specified amount in the Z axis direction" }, AddSpeed = { { Params = "AddX, AddY, AddZ", Return = "", Notes = "Adds the specified amount of speed in each axis direction." }, { Params = "{{Vector3d|Add}}", Return = "", Notes = "Adds the specified amount of speed in each axis direction." }, }, AddSpeedX = { Params = "AddX", Return = "", Notes = "Adds the specified amount of speed in the X axis direction." }, AddSpeedY = { Params = "AddY", Return = "", Notes = "Adds the specified amount of speed in the Y axis direction." }, AddSpeedZ = { Params = "AddZ", Return = "", Notes = "Adds the specified amount of speed in the Z axis direction." }, ArmorCoversAgainst = { Params = "{{cEntity|AttackerEntity}}, DamageType, RawDamage", Return = "number", Notes = "Returns the points out of a_RawDamage that the currently equipped armor would cover." }, Destroy = { Params = "", Return = "", Notes = "Schedules the entity to be destroyed" }, GetAirLevel = { Params = "", Return = "number", Notes = "Returns the air level (number of ticks of air left). Note, this function is only updated with mobs or players." }, GetArmorCoverAgainst = { Params = "AttackerEntity, DamageType, RawDamage", Return = "number", Notes = "Returns the number of hitpoints out of RawDamage that the currently equipped armor would cover. See {{TakeDamageInfo}} for more information on attack damage." }, GetChunkX = { Params = "", Return = "number", Notes = "Returns the X-coord of the chunk in which the entity is placed" }, GetChunkZ = { Params = "", Return = "number", Notes = "Returns the Z-coord of the chunk in which the entity is placed" }, GetClass = { Params = "", Return = "string", Notes = "Returns the classname of the entity, such as \"cSpider\" or \"cPickup\"" }, GetClassStatic = { Params = "", Return = "string", Notes = "Returns the entity classname that this class implements. Each descendant overrides this function. Is static" }, GetEntityType = { Params = "", Return = "{{cEntity#EntityType|EntityType}}", Notes = "Returns the type of the entity, one of the {{cEntity#EntityType|etXXX}} constants. Note that to check specific entity type, you should use one of the IsXXX functions instead of comparing the value returned by this call." }, GetEquippedBoots = { Params = "", Return = "{{cItem}}", Notes = "Returns the boots that the entity has equipped. Returns an empty cItem if no boots equipped or not applicable." }, GetEquippedChestplate = { Params = "", Return = "{{cItem}}", Notes = "Returns the chestplate that the entity has equipped. Returns an empty cItem if no chestplate equipped or not applicable." }, GetEquippedHelmet = { Params = "", Return = "{{cItem}}", Notes = "Returns the helmet that the entity has equipped. Returns an empty cItem if no helmet equipped or not applicable." }, GetEquippedLeggings = { Params = "", Return = "{{cItem}}", Notes = "Returns the leggings that the entity has equipped. Returns an empty cItem if no leggings equipped or not applicable." }, GetEquippedWeapon = { Params = "", Return = "{{cItem}}", Notes = "Returns the weapon that the entity has equipped. Returns an empty cItem if no weapon equipped or not applicable." }, GetGravity = { Params = "", Return = "number", Notes = "Returns the number that is used as the gravity for physics simulation. 1G (9.78) by default." }, GetHeadYaw = { Params = "", Return = "number", Notes = "Returns the pitch of the entity's head (FIXME: Rename to GetHeadPitch() )." }, GetHealth = { Params = "", Return = "number", Notes = "Returns the current health of the entity." }, GetHeight = { Params = "", Return = "number", Notes = "Returns the height (Y size) of the entity" }, GetInvulnerableTicks = { Params = "", Return = "number", Notes = "Returns the number of ticks that this entity will be invulnerable for. This is used for after-hit recovery - the entities are invulnerable for half a second after being hit." }, GetKnockbackAmountAgainst = { Params = "ReceiverEntity", Return = "number", Notes = "Returns the amount of knockback that the currently equipped items would cause when attacking the ReceiverEntity." }, GetLookVector = { Params = "", Return = "{{Vector3f}}", Notes = "Returns the vector that defines the direction in which the entity is looking" }, GetMass = { Params = "", Return = "number", Notes = "Returns the mass of the entity. Currently unused." }, GetMaxHealth = { Params = "", Return = "number", Notes = "Returns the maximum number of hitpoints this entity is allowed to have." }, GetParentClass = { Params = "", Return = "string", Notes = "Returns the name of the direct parent class for this entity" }, GetPitch = { Params = "", Return = "number", Notes = "Returns the pitch (nose-down rotation) of the entity. Measured in degrees, normal values range from -90 to +90. +90 means looking down, 0 means looking straight ahead, -90 means looking up." }, GetPosition = { Params = "", Return = "{{Vector3d}}", Notes = "Returns the entity's pivot position as a 3D vector" }, GetPosX = { Params = "", Return = "number", Notes = "Returns the X-coord of the entity's pivot" }, GetPosY = { Params = "", Return = "number", Notes = "Returns the Y-coord of the entity's pivot" }, GetPosZ = { Params = "", Return = "number", Notes = "Returns the Z-coord of the entity's pivot" }, GetRawDamageAgainst = { Params = "ReceiverEntity", Return = "number", Notes = "Returns the raw damage that this entity's equipment would cause when attacking the ReceiverEntity. This includes this entity's weapon {{cEnchantments|enchantments}}, but excludes the receiver's armor or potion effects. See {{TakeDamageInfo}} for more information on attack damage." }, GetRoll = { Params = "", Return = "number", Notes = "Returns the roll (sideways rotation) of the entity. Currently unused." }, GetRot = { Params = "", Return = "{{Vector3f}}", Notes = "(OBSOLETE) Returns the entire rotation vector (Yaw, Pitch, Roll)" }, GetSpeed = { Params = "", Return = "{{Vector3d}}", Notes = "Returns the complete speed vector of the entity" }, GetSpeedX = { Params = "", Return = "number", Notes = "Returns the X-part of the speed vector" }, GetSpeedY = { Params = "", Return = "number", Notes = "Returns the Y-part of the speed vector" }, GetSpeedZ = { Params = "", Return = "number", Notes = "Returns the Z-part of the speed vector" }, GetTicksAlive = { Params = "", Return = "number", Notes = "Returns the number of ticks that this entity has been alive for." }, GetUniqueID = { Params = "", Return = "number", Notes = "Returns the ID that uniquely identifies the entity within the running server. Note that this ID is not persisted to the data files." }, GetWidth = { Params = "", Return = "number", Notes = "Returns the width (X and Z size) of the entity." }, GetWorld = { Params = "", Return = "{{cWorld}}", Notes = "Returns the world where the entity resides" }, GetYaw = { Params = "", Return = "number", Notes = "Returns the yaw (direction) of the entity. Measured in degrees, values range from -180 to +180. 0 means ZP, 90 means XM, -180 means ZM, -90 means XP." }, HandleSpeedFromAttachee = { Params = "ForwardAmount, SidewaysAmount", Return = "", Notes = "Updates the entity's speed based on the attachee exerting the specified force forward and sideways. Used for entities being driven by other entities attached to them - usually players driving minecarts and boats." }, Heal = { Params = "Hitpoints", Return = "", Notes = "Heals the specified number of hitpoints. Hitpoints is expected to be a positive number." }, IsA = { Params = "ClassName", Return = "bool", Notes = "Returns true if the entity class is a descendant of the specified class name, or the specified class itself" }, IsBoat = { Params = "", Return = "bool", Notes = "Returns true if the entity is a {{cBoat|boat}}." }, IsCrouched = { Params = "", Return = "bool", Notes = "Returns true if the entity is crouched. Always false for entities that don't support crouching." }, IsDestroyed = { Params = "", Return = "bool", Notes = "Returns true if the entity has been destroyed and is awaiting removal from the internal structures." }, IsEnderCrystal = { Params = "", Return = "bool", Notes = "Returns true if the entity is an ender crystal." }, IsExpOrb = { Params = "", Return = "bool", Notes = "Returns true if the entity represents an experience orb" }, IsFallingBlock = { Params = "", Return = "bool", Notes = "Returns true if the entity represents a {{cFallingBlock}} entity." }, IsFireproof = { Params = "", Return = "bool", Notes = "Returns true if the entity takes no damage from being on fire." }, IsFloater = { Params = "", Return = "bool", Notes = "Returns true if the entity represents a fishing rod floater" }, IsInvisible = { Params = "", Return = "bool", Notes = "Returns true if the entity is invisible" }, IsItemFrame = { Params = "", Return = "bool", Notes = "Returns true if the entity is an item frame." }, IsMinecart = { Params = "", Return = "bool", Notes = "Returns true if the entity represents a {{cMinecart|minecart}}" }, IsMob = { Params = "", Return = "bool", Notes = "Returns true if the entity represents any {{cMonster|mob}}." }, IsOnFire = { Params = "", Return = "bool", Notes = "Returns true if the entity is on fire" }, IsOnGround = { Params = "", Return = "bool", Notes = "Returns true if the entity is on ground (not falling, not jumping, not flying)" }, IsPainting = { Params = "", Return = "bool", Notes = "Returns if this entity is a painting." }, IsPawn = { Params = "", Return = "bool", Notes = "Returns true if the entity is a {{cPawn}} descendant." }, IsPickup = { Params = "", Return = "bool", Notes = "Returns true if the entity represents a {{cPickup|pickup}}." }, IsPlayer = { Params = "", Return = "bool", Notes = "Returns true if the entity represents a {{cPlayer|player}}" }, IsProjectile = { Params = "", Return = "bool", Notes = "Returns true if the entity is a {{cProjectileEntity}} descendant." }, IsRclking = { Params = "", Return = "bool", Notes = "Currently unimplemented" }, IsRiding = { Params = "", Return = "bool", Notes = "Returns true if the entity is attached to (riding) another entity." }, IsSprinting = { Params = "", Return = "bool", Notes = "Returns true if the entity is sprinting. Entities that cannot sprint return always false" }, IsSubmerged = { Params = "", Return = "bool", Notes = "Returns true if the mob or player is submerged in water (head is in a water block). Note, this function is only updated with mobs or players." }, IsSwimming = { Params = "", Return = "bool", Notes = "Returns true if the mob or player is swimming in water (feet are in a water block). Note, this function is only updated with mobs or players." }, IsTNT = { Params = "", Return = "bool", Notes = "Returns true if the entity represents a {{cTNTEntity|TNT entity}}" }, Killed = { Params = "{{cEntity|Victim}}", Return = "", Notes = "This entity has killed another entity (the Victim). For players, adds the scoreboard statistics about the kill." }, KilledBy = { Notes = "FIXME: Remove this from API" }, MoveToWorld = { { Params = "{{cWorld|World}}, [ShouldSendRespawn]", Return = "bool", Notes = "Removes the entity from this world and starts moving it to the specified world. Note that to avoid deadlocks, the move is asynchronous - the entity is moved into a queue and will be moved from that queue into the destination world at some (unpredictable) time in the future. ShouldSendRespawn is used only for players, it specifies whether the player should be sent a Repawn packet upon leaving the world (The client handles respawns only between different dimensions)." }, { Params = "WorldName, [ShouldSendRespawn]", Return = "bool", Notes = "Removes the entity from this world and starts moving it to the specified world. Note that to avoid deadlocks, the move is asynchronous - the entity is moved into a queue and will be moved from that queue into the destination world at some (unpredictable) time in the future. ShouldSendRespawn is used only for players, it specifies whether the player should be sent a Repawn packet upon leaving the world (The client handles respawns only between different dimensions)." }, }, SetGravity = { Params = "Gravity", Return = "", Notes = "Sets the number that is used as the gravity for physics simulation. 1G (9.78) by default." }, SetHeadYaw = { Params = "HeadPitch", Return = "", Notes = "Sets the head pitch (FIXME: Rename to SetHeadPitch() )." }, SetHealth = { Params = "Hitpoints", Return = "", Notes = "Sets the entity's health to the specified amount of hitpoints. Doesn't broadcast any hurt animation. Doesn't kill the entity if health drops below zero. Use the TakeDamage() function instead for taking damage." }, SetHeight = { Params = "", Return = "", Notes = "FIXME: Remove this from API" }, SetInvulnerableTicks = { Params = "NumTicks", Return = "", Notes = "Sets the amount of ticks for which the entity will not receive any damage from other entities." }, SetIsFireproof = { Params = "IsFireproof", Return = "", Notes = "Sets whether the entity receives damage from being on fire." }, SetMass = { Params = "Mass", Return = "", Notes = "Sets the mass of the entity. Currently unused." }, SetMaxHealth = { Params = "MaxHitpoints", Return = "", Notes = "Sets the maximum hitpoints of the entity. If current health is above MaxHitpoints, it is capped to MaxHitpoints." }, SetPitch = { Params = "number", Return = "", Notes = "Sets the pitch (nose-down rotation) of the entity" }, SetPitchFromSpeed = { Params = "", Return = "", Notes = "Sets the entity pitch to match its speed (entity looking forwards as it moves)" }, SetPosition = { { Params = "PosX, PosY, PosZ", Return = "", Notes = "Sets all three coords of the entity's pivot" }, { Params = "{{Vector3d|Vector3d}}", Return = "", Notes = "Sets all three coords of the entity's pivot" }, }, SetPosX = { Params = "number", Return = "", Notes = "Sets the X-coord of the entity's pivot" }, SetPosY = { Params = "number", Return = "", Notes = "Sets the Y-coord of the entity's pivot" }, SetPosZ = { Params = "number", Return = "", Notes = "Sets the Z-coord of the entity's pivot" }, SetRoll = { Params = "number", Return = "", Notes = "Sets the roll (sideways rotation) of the entity. Currently unused." }, SetRot = { Params = "{{Vector3f|Rotation}}", Return = "", Notes = "Sets the entire rotation vector (Yaw, Pitch, Roll)" }, SetYawFromSpeed = { Params = "", Return = "", Notes = "Sets the entity's yaw to match its current speed (entity looking forwards as it moves)." }, SetSpeed = { { Params = "SpeedX, SpeedY, SpeedZ", Return = "", Notes = "Sets the current speed of the entity" }, { Params = "{{Vector3d|Speed}}", Return = "", Notes = "Sets the current speed of the entity" }, }, SetSpeedX = { Params = "SpeedX", Return = "", Notes = "Sets the X component of the entity speed" }, SetSpeedY = { Params = "SpeedY", Return = "", Notes = "Sets the Y component of the entity speed" }, SetSpeedZ = { Params = "SpeedZ", Return = "", Notes = "Sets the Z component of the entity speed" }, SetWidth = { Params = "", Return = "", Notes = "FIXME: Remove this from API" }, SetYaw = { Params = "number", Return = "", Notes = "Sets the yaw (direction) of the entity." }, StartBurning = { Params = "NumTicks", Return = "", Notes = "Sets the entity on fire for the specified number of ticks. If entity is on fire already, makes it burn for either NumTicks or the number of ticks left from the previous fire, whichever is larger." }, SteerVehicle = { Params = "ForwardAmount, SidewaysAmount", Return = "", Notes = "Applies the specified steering to the vehicle this entity is attached to. Ignored if not attached to any entity." }, StopBurning = { Params = "", Return = "", Notes = "Extinguishes the entity fire, cancels all fire timers." }, TakeDamage = { { Params = "AttackerEntity", Return = "", Notes = "Causes this entity to take damage that AttackerEntity would inflict. Includes their weapon and this entity's armor." }, { Params = "DamageType, AttackerEntity, RawDamage, KnockbackAmount", Return = "", Notes = "Causes this entity to take damage of the specified type, from the specified attacker (may be nil). The final damage is calculated from RawDamage using the currently equipped armor." }, { Params = "DamageType, ArrackerEntity, RawDamage, FinalDamage, KnockbackAmount", Return = "", Notes = "Causes this entity to take damage of the specified type, from the specified attacker (may be nil). The values are wrapped into a {{TakeDamageInfo}} structure and applied directly." }, }, TeleportToCoords = { Params = "PosX, PosY, PosZ", Return = "", Notes = "Teleports the entity to the specified coords. Asks plugins if the teleport is allowed." }, TeleportToEntity = { Params = "DestEntity", Return = "", Notes = "Teleports this entity to the specified destination entity. Asks plugins if the teleport is allowed." }, }, Constants = { etBoat = { Notes = "The entity is a {{cBoat}}" }, etEnderCrystal = { Notes = "" }, etEntity = { Notes = "No further specialization available" }, etExpOrb = { Notes = "The entity is a {{cExpOrb}}" }, etFallingBlock = { Notes = "The entity is a {{cFallingBlock}}" }, etFloater = { Notes = "The entity is a fishing rod floater" }, etItemFrame = { Notes = "" }, etMinecart = { Notes = "The entity is a {{cMinecart}} descendant" }, etMob = { Notes = "The entity is a {{cMonster}} descendant" }, etMonster = { Notes = "The entity is a {{cMonster}} descendant" }, etPainting = { Notes = "The entity is a {{cPainting}}" }, etPickup = { Notes = "The entity is a {{cPickup}}" }, etPlayer = { Notes = "The entity is a {{cPlayer}}" }, etProjectile = { Notes = "The entity is a {{cProjectileEntity}} descendant" }, etTNT = { Notes = "The entity is a {{cTNTEntity}}" }, }, ConstantGroups = { EntityType = { Include = "et.*", TextBefore = "The following constants are used to distinguish between different entity types:", }, }, }, cFile = { Desc = [[ Provides helper functions for manipulating and querying the filesystem. Most functions are static, so they should be called directly on the cFile class itself: <pre class="prettyprint lang-lua"> cFile:DeleteFile("/usr/bin/virus.exe"); </pre></p> ]], Functions = { ChangeFileExt = { Params = "FileName, NewExt", Return = "string", Notes = "(STATIC) Returns FileName with its extension changed to NewExt. NewExt may begin with a dot, but needn't, the result is the same in both cases (the first dot, if present, is ignored). FileName may contain path elements, extension is recognized as the last dot after the last path separator in the string." }, Copy = { Params = "SrcFileName, DstFileName", Return = "bool", Notes = "(STATIC) Copies a single file to a new destination. Returns true if successful. Fails if the destination already exists." }, CreateFolder = { Params = "FolderPath", Return = "bool", Notes = "(STATIC) Creates a new folder. Returns true if successful. Only a single level can be created at a time, use CreateFolderRecursive() to create multiple levels of folders at once." }, CreateFolderRecursive = { Params = "FolderPath", Return = "bool", Notes = "(STATIC) Creates a new folder, creating its parents if needed. Returns true if successful." }, Delete = { Params = "Path", Return = "bool", Notes = "(STATIC) Deletes the specified file or folder. Returns true if successful. Only deletes folders that are empty.<br/><b>NOTE</b>: If you already know if the object is a file or folder, use DeleteFile() or DeleteFolder() explicitly." }, DeleteFile = { Params = "FilePath", Return = "bool", Notes = "(STATIC) Deletes the specified file. Returns true if successful." }, DeleteFolder = { Params = "FolderPath", Return = "bool", Notes = "(STATIC) Deletes the specified file or folder. Returns true if successful. Only deletes folders that are empty." }, DeleteFolderContents = { Params = "FolderPath", Return = "bool", Notes = "(STATIC) Deletes everything from the specified folder, recursively. The specified folder stays intact. Returns true if successful." }, Exists = { Params = "Path", Return = "bool", Notes = "(STATIC) Returns true if the specified file or folder exists.<br/><b>OBSOLETE</b>, use IsFile() or IsFolder() instead" }, GetExecutableExt = { Params = "", Return = "string", Notes = "(STATIC) Returns the customary executable extension (including the dot) used by the current platform (\".exe\" on Windows, empty string on Linux). " }, GetFolderContents = { Params = "FolderName", Return = "array table of strings", Notes = "(STATIC) Returns the contents of the specified folder, as an array table of strings. Each filesystem object is listed. Use the IsFile() and IsFolder() functions to determine the object type." }, GetLastModificationTime = { Params = "Path", Return = "number", Notes = "(STATIC) Returns the last modification time (in current timezone) of the specified file or folder. Returns zero if file not found / not accessible. The returned value is in the same units as values returned by os.time()." }, GetPathSeparator = { Params = "", Return = "string", Notes = "(STATIC) Returns the primary path separator used by the current platform. Returns \"\\\" on Windows and \"/\" on Linux. Note that the platform or CRT may support additional path separators, those are not reported." }, GetSize = { Params = "FileName", Return = "number", Notes = "(STATIC) Returns the size of the file, or -1 on failure." }, IsFile = { Params = "Path", Return = "bool", Notes = "(STATIC) Returns true if the specified path points to an existing file." }, IsFolder = { Params = "Path", Return = "bool", Notes = "(STATIC) Returns true if the specified path points to an existing folder." }, ReadWholeFile = { Params = "FileName", Return = "string", Notes = "(STATIC) Returns the entire contents of the specified file. Returns an empty string if the file cannot be opened." }, Rename = { Params = "OrigPath, NewPath", Return = "bool", Notes = "(STATIC) Renames a file or a folder. Returns true if successful. Undefined result if NewPath already exists." }, }, }, -- cFile cFloater = { Desc = [[ When a player uses his/her fishing rod it creates a floater entity. This class manages it. ]], Functions = { CanPickup = { Params = "", Return = "bool", Notes = "Returns true if the floater gives an item when the player right clicks." }, GetAttachedMobID = { Params = "", Return = "EntityID", Notes = "A floater can get attached to an mob. When it is and this functions gets called it returns the mob ID. If it isn't attached to a mob it returns -1" }, GetOwnerID = { Params = "", Return = "EntityID", Notes = "Returns the EntityID of the player who owns the floater." }, }, Inherits = "cEntity", }, cIniFile = { Desc = [[ This class implements a simple name-value storage represented on disk by an INI file. These files are suitable for low-volume high-latency human-readable information storage, such as for configuration. Cuberite itself uses INI files for settings and options.</p> <p> The INI files follow this basic structure: <pre class="prettyprint lang-ini"> ; Header comment line [KeyName0] ; Key comment line 0 ValueName0=Value0 ValueName1=Value1 [KeyName1] ; Key comment line 0 ; Key comment line 1 ValueName0=SomeOtherValue </pre> The cIniFile object stores all the objects in numbered arrays and provides access to the information either based on names (KeyName, ValueName) or zero-based indices.</p> <p> The objects of this class are created empty. You need to either load a file using ReadFile(), or insert values by hand. Then you can store the object's contents to a disk file using WriteFile(), or just forget everything by destroying the object. Note that the file operations are quite slow.</p> <p> For storing high-volume low-latency data, use the {{sqlite3}} class. For storing hierarchically-structured data, use the XML format, using the LuaExpat parser in the {{lxp}} class. ]], Functions = { constructor = { Params = "", Return = "cIniFile", Notes = "Creates a new empty cIniFile object." }, AddHeaderComment = { Params = "Comment", Return = "", Notes = "Adds a comment to be stored in the file header." }, AddKeyComment = { { Params = "KeyID, Comment", Return = "", Notes = "Adds a comment to be stored in the file under the specified key" }, { Params = "KeyName, Comment", Return = "", Notes = "Adds a comment to be stored in the file under the specified key" }, }, AddKeyName = { Params = "KeyName", Returns = "number", Notes = "Adds a new key of the specified name. Returns the KeyID of the new key." }, AddValue = { Params = "KeyName, ValueName, Value", Return = "", Notes = "Adds a new value of the specified name to the specified key. If another value of the same name exists in the key, both are kept (nonstandard INI file)" }, AddValueB = { Params = "KeyName, ValueName, Value", Return = "", Notes = "Adds a new bool value of the specified name to the specified key. If another value of the same name exists in the key, both are kept (nonstandard INI file)" }, AddValueF = { Params = "KeyName, ValueName, Value", Return = "", Notes = "Adds a new float value of the specified name to the specified key. If another value of the same name exists in the key, both are kept (nonstandard INI file)" }, AddValueI = { Params = "KeyName, ValueName, Value", Return = "", Notes = "Adds a new integer value of the specified name to the specified key. If another value of the same name exists in the key, both are kept (nonstandard INI file)" }, CaseInsensitive = { Params = "", Return = "", Notes = "Sets key names' and value names' comparisons to case insensitive (default)." }, CaseSensitive = { Params = "", Return = "", Notes = "Sets key names and value names comparisons to case sensitive." }, Clear = { Params = "", Return = "", Notes = "Removes all the in-memory data. Note that , like all the other operations, this doesn't affect any file data." }, DeleteHeaderComment = { Params = "CommentID", Return = "bool" , Notes = "Deletes the specified header comment. Returns true if successful."}, DeleteHeaderComments = { Params = "", Return = "", Notes = "Deletes all headers comments." }, DeleteKey = { Params = "KeyName", Return = "bool", Notes = "Deletes the specified key, and all values in that key. Returns true if successful." }, DeleteKeyComment = { { Params = "KeyID, CommentID", Return = "bool", Notes = "Deletes the specified key comment. Returns true if successful." }, { Params = "KeyName, CommentID", Return = "bool", Notes = "Deletes the specified key comment. Returns true if successful." }, }, DeleteKeyComments = { { Params = "KeyID", Return = "bool", Notes = "Deletes all comments for the specified key. Returns true if successful." }, { Params = "KeyName", Return = "bool", Notes = "Deletes all comments for the specified key. Returns true if successful." }, }, DeleteValue = { Params = "KeyName, ValueName", Return = "bool", Notes = "Deletes the specified value. Returns true if successful." }, DeleteValueByID = { Params = "KeyID, ValueID", Return = "bool", Notes = "Deletes the specified value. Returns true if successful." }, FindKey = { Params = "KeyName", Return = "number", Notes = "Returns the KeyID for the specified key name, or the noID constant if the key doesn't exist." }, FindValue = { Params = "KeyID, ValueName", Return = "numebr", Notes = "Returns the ValueID for the specified value name, or the noID constant if the specified key doesn't contain a value of that name." }, GetHeaderComment = { Params = "CommentID", Return = "string", Notes = "Returns the specified header comment, or an empty string if such comment doesn't exist" }, GetKeyComment = { { Params = "KeyID, CommentID", Return = "string", Notes = "Returns the specified key comment, or an empty string if such a comment doesn't exist" }, { Params = "KeyName, CommentID", Return = "string", Notes = "Returns the specified key comment, or an empty string if such a comment doesn't exist" }, }, GetKeyName = { Params = "KeyID", Return = "string", Notes = "Returns the key name for the specified key ID. Inverse for FindKey()." }, GetNumHeaderComments = { Params = "", Return = "number", Notes = "Retuns the number of header comments." }, GetNumKeyComments = { { Params = "KeyID", Return = "number", Notes = "Returns the number of comments under the specified key" }, { Params = "KeyName", Return = "number", Notes = "Returns the number of comments under the specified key" }, }, GetNumKeys = { Params = "", Return = "number", Notes = "Returns the total number of keys. This is the range for the KeyID (0 .. GetNumKeys() - 1)" }, GetNumValues = { { Params = "KeyID", Return = "number", Notes = "Returns the number of values stored under the specified key." }, { Params = "KeyName", Return = "number", Notes = "Returns the number of values stored under the specified key." }, }, GetValue = { { Params = "KeyName, ValueName", Return = "string", Notes = "Returns the value of the specified name under the specified key. Returns an empty string if the value doesn't exist." }, { Params = "KeyID, ValueID", Return = "string", Notes = "Returns the value of the specified name under the specified key. Returns an empty string if the value doesn't exist." }, }, GetValueB = { Params = "KeyName, ValueName", Return = "bool", Notes = "Returns the value of the specified name under the specified key, as a bool. Returns false if the value doesn't exist." }, GetValueF = { Params = "KeyName, ValueName", Return = "number", Notes = "Returns the value of the specified name under the specified key, as a floating-point number. Returns zero if the value doesn't exist." }, GetValueI = { Params = "KeyName, ValueName", Return = "number", Notes = "Returns the value of the specified name under the specified key, as an integer. Returns zero if the value doesn't exist." }, GetValueName = { { Params = "KeyID, ValueID", Return = "string", Notes = "Returns the name of the specified value Inverse for FindValue()." }, { Params = "KeyName, ValueID", Return = "string", Notes = "Returns the name of the specified value Inverse for FindValue()." }, }, GetValueSet = { Params = "KeyName, ValueName, Default", Return = "string", Notes = "Returns the value of the specified name under the specified key. If the value doesn't exist, creates it with the specified default." }, GetValueSetB = { Params = "KeyName, ValueName, Default", Return = "bool", Notes = "Returns the value of the specified name under the specified key, as a bool. If the value doesn't exist, creates it with the specified default." }, GetValueSetF = { Params = "KeyName, ValueName, Default", Return = "number", Notes = "Returns the value of the specified name under the specified key, as a floating-point number. If the value doesn't exist, creates it with the specified default." }, GetValueSetI = { Params = "KeyName, ValueName, Default", Return = "number", Notes = "Returns the value of the specified name under the specified key, as an integer. If the value doesn't exist, creates it with the specified default." }, HasValue = { Params = "KeyName, ValueName", Return = "bool", Notes = "Returns true if the specified value is present." }, ReadFile = { Params = "FileName, [AllowExampleFallback]", Return = "bool", Notes = "Reads the values from the specified file. Previous in-memory contents are lost. If the file cannot be opened, and AllowExample is true, another file, \"filename.example.ini\", is loaded and then saved as \"filename.ini\". Returns true if successful, false if not." }, SetValue = { { Params = "KeyID, ValueID, NewValue", Return = "bool", Notes = "Overwrites the specified value with a new value. If the specified value doesn't exist, returns false (doesn't add)." }, { Params = "KeyName, ValueName, NewValue, [CreateIfNotExists]", Return = "bool", Notes = "Overwrites the specified value with a new value. If CreateIfNotExists is true (default) and the value doesn't exist, it is first created. Returns true if the value was successfully set, false if not (didn't exists, CreateIfNotExists false)." }, }, SetValueB = { Params = "KeyName, ValueName, NewValueBool, [CreateIfNotExists]", Return = "bool", Notes = "Overwrites the specified value with a new bool value. If CreateIfNotExists is true (default) and the value doesn't exist, it is first created. Returns true if the value was successfully set, false if not (didn't exists, CreateIfNotExists false)." }, SetValueF = { Params = "KeyName, ValueName, NewValueFloat, [CreateIfNotExists]", Return = "bool", Notes = "Overwrites the specified value with a new floating-point number value. If CreateIfNotExists is true (default) and the value doesn't exist, it is first created. Returns true if the value was successfully set, false if not (didn't exists, CreateIfNotExists false)." }, SetValueI = { Params = "KeyName, ValueName, NewValueInt, [CreateIfNotExists]", Return = "bool", Notes = "Overwrites the specified value with a new integer value. If CreateIfNotExists is true (default) and the value doesn't exist, it is first created. Returns true if the value was successfully set, false if not (didn't exists, CreateIfNotExists false)." }, WriteFile = { Params = "FileName", Return = "bool", Notes = "Writes the current in-memory data into the specified file. Returns true if successful, false if not." }, }, Constants = { noID = { Notes = "" }, }, AdditionalInfo = { { Header = "Code example: Reading a simple value", Contents = [[ cIniFile is very easy to use. For example, you can find out what port the server is supposed to use according to settings.ini by using this little snippet: <pre class="prettyprint lang-lua"> local IniFile = cIniFile(); if (IniFile:ReadFile("settings.ini")) then ServerPort = IniFile:GetValueI("Server", "Port"); end </pre> ]], }, { Header = "Code example: Enumerating all objects in a file", Contents = [[ To enumerate all keys in a file, you need to query the total number of keys, using GetNumKeys(), and then query each key's name using GetKeyName(). Similarly, to enumerate all values under a key, you need to query the total number of values using GetNumValues() and then query each value's name using GetValueName().</p> <p> The following code logs all keynames and their valuenames into the server log: <pre class="prettyprint lang-lua"> local IniFile = cIniFile(); IniFile:ReadFile("somefile.ini") local NumKeys = IniFile:GetNumKeys(); for k = 0, NumKeys do local NumValues = IniFile:GetNumValues(k); LOG("key \"" .. IniFile:GetKeyName(k) .. "\" has " .. NumValues .. " values:"); for v = 0, NumValues do LOG(" value \"" .. IniFile:GetValueName(k, v) .. "\"."); end end </pre> ]], }, }, -- AdditionalInfo }, -- cIniFile cInventory = { Desc = [[This object is used to store the items that a {{cPlayer|cPlayer}} has. It also keeps track of what item the player has currently selected in their hotbar. Internally, the class uses three {{cItemGrid|cItemGrid}} objects to store the contents: <li>Armor</li> <li>Inventory</li> <li>Hotbar</li> These ItemGrids are available in the API and can be manipulated by the plugins, too.</p> <p> When using the raw slot access functions, such as GetSlot() and SetSlot(), the slots are numbered consecutively, each ItemGrid has its offset and count. To future-proff your plugins, use the named constants instead of hard-coded numbers. ]], Functions = { AddItem = { Params = "{{cItem|cItem}}, [AllowNewStacks]", Return = "number", Notes = "Adds an item to the storage; if AllowNewStacks is true (default), will also create new stacks in empty slots. Returns the number of items added" }, AddItems = { Params = "{{cItems|cItems}}, [AllowNewStacks]", Return = "number", Notes = "Same as AddItem, but for several items at once" }, ChangeSlotCount = { Params = "SlotNum, AddToCount", Return = "number", Notes = "Adds AddToCount to the count of items in the specified slot. If the slot was empty, ignores the call. Returns the new count in the slot, or -1 if invalid SlotNum" }, Clear = { Params = "", Return = "", Notes = "Empties all slots" }, CopyToItems = { Params = "{{cItems|cItems}}", Return = "", Notes = "Copies all non-empty slots into the cItems object provided; original cItems contents are preserved" }, DamageEquippedItem = { Params = "[DamageAmount]", Return = "bool", Notes = "Adds the specified damage (1 by default) to the currently equipped it" }, DamageItem = { Params = "SlotNum, [DamageAmount]", Return = "bool", Notes = "Adds the specified damage (1 by default) to the specified item, returns true if the item reached its max damage and should be destroyed" }, GetArmorGrid = { Params = "", Return = "{{cItemGrid|cItemGrid}}", Notes = "Returns the ItemGrid representing the armor grid (1 x 4 slots)" }, GetArmorSlot = { Params = "ArmorSlotNum", Return = "{{cItem|cItem}}", Notes = "Returns the specified armor slot contents. Note that the returned item is read-only" }, GetEquippedBoots = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the item in the \"boots\" slot of the armor grid. Note that the returned item is read-only" }, GetEquippedChestplate = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the item in the \"chestplate\" slot of the armor grid. Note that the returned item is read-only" }, GetEquippedHelmet = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the item in the \"helmet\" slot of the armor grid. Note that the returned item is read-only" }, GetEquippedItem = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the currently selected item from the hotbar. Note that the returned item is read-only" }, GetEquippedLeggings = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the item in the \"leggings\" slot of the armor grid. Note that the returned item is read-only" }, GetEquippedSlotNum = { Params = "", Return = "number", Notes = "Returns the hotbar slot number for the currently selected item" }, GetHotbarGrid = { Params = "", Return = "{{cItemGrid|cItemGrid}}", Notes = "Returns the ItemGrid representing the hotbar grid (9 x 1 slots)" }, GetHotbarSlot = { Params = "HotBarSlotNum", Return = "{{cItem|cItem}}", Notes = "Returns the specified hotbar slot contents. Note that the returned item is read-only" }, GetInventoryGrid = { Params = "", Return = "{{cItemGrid|cItemGrid}}", Notes = "Returns the ItemGrid representing the main inventory (9 x 3 slots)" }, GetInventorySlot = { Params = "InventorySlotNum", Return = "{{cItem|cItem}}", Notes = "Returns the specified main inventory slot contents. Note that the returned item is read-only" }, GetOwner = { Params = "", Return = "{{cPlayer|cPlayer}}", Notes = "Returns the player whose inventory this object represents" }, GetSlot = { Params = "SlotNum", Return = "{{cItem|cItem}}", Notes = "Returns the contents of the specified slot. Note that the returned item is read-only" }, HasItems = { Params = "{{cItem|cItem}}", Return = "bool", Notes = "Returns true if there are at least as many items of the specified type as in the parameter" }, HowManyCanFit = { Params = "{{cItem|cItem}}", Return = "number", Notes = "Returns the number of the specified items that can fit in the storage, including empty slots" }, HowManyItems = { Params = "{{cItem|cItem}}", Return = "number", Notes = "Returns the number of the specified items that are currently stored" }, RemoveItem = { Params = "{{cItem}}", Return = "number", Notes = "Removes the specified item from the inventory, as many as possible, up to the item's m_ItemCount. Returns the number of items that were removed." }, RemoveOneEquippedItem = { Params = "", Return = "", Notes = "Removes one item from the hotbar's currently selected slot" }, SetArmorSlot = { Params = "ArmorSlotNum, {{cItem|cItem}}", Return = "", Notes = "Sets the specified armor slot contents" }, SetEquippedSlotNum = { Params = "EquippedSlotNum", Return = "", Notes = "Sets the currently selected hotbar slot number" }, SetHotbarSlot = { Params = "HotbarSlotNum, {{cItem|cItem}}", Return = "", Notes = "Sets the specified hotbar slot contents" }, SetInventorySlot = { Params = "InventorySlotNum, {{cItem|cItem}}", Return = "", Notes = "Sets the specified main inventory slot contents" }, SetSlot = { Params = "SlotNum, {{cItem|cItem}}", Return = "", Notes = "Sets the specified slot contents" }, }, Constants = { invArmorCount = { Notes = "Number of slots in the Armor part" }, invArmorOffset = { Notes = "Starting slot number of the Armor part" }, invInventoryCount = { Notes = "Number of slots in the main inventory part" }, invInventoryOffset = { Notes = "Starting slot number of the main inventory part" }, invHotbarCount = { Notes = "Number of slots in the Hotbar part" }, invHotbarOffset = { Notes = "Starting slot number of the Hotbar part" }, invNumSlots = { Notes = "Total number of slots in a cInventory" }, }, ConstantGroups = { SlotIndices = { Include = "inv.*", TextBefore = [[ Rather than hardcoding numbers, use the following constants for slot indices and counts: ]], }, }, }, -- cInventory cItem = { Desc = [[ cItem is what defines an item or stack of items in the game, it contains the item ID, damage, quantity and enchantments. Each slot in a {{cInventory}} class or a {{cItemGrid}} class is a cItem and each {{cPickup}} contains a cItem. The enchantments are contained in a separate {{cEnchantments}} class and are accessible through the m_Enchantments variable.</p> <p> To test if a cItem object represents an empty item, do not compare the item type nor the item count, but rather use the IsEmpty() function.</p> <p> To translate from a cItem to its string representation, use the {{Globals#functions|global function}} ItemToString(), ItemTypeToString() or ItemToFullString(). To translate from a string to a cItem, use the StringToItem() global function. ]], Functions = { constructor = { { Params = "", Return = "cItem", Notes = "Creates a new empty cItem object" }, { Params = "ItemType, Count, Damage, EnchantmentString, CustomName, Lore", Return = "cItem", Notes = "Creates a new cItem object of the specified type, count (1 by default), damage (0 by default), enchantments (non-enchanted by default), CustomName (empty by default) and Lore (string, empty by default)" }, { Params = "cItem", Return = "cItem", Notes = "Creates an exact copy of the cItem object in the parameter" }, } , AddCount = { Params = "AmountToAdd", Return = "cItem", Notes = "Adds the specified amount to the item count. Returns self (useful for chaining)." }, Clear = { Params = "", Return = "", Notes = "Resets the instance to an empty item" }, CopyOne = { Params = "", Return = "cItem", Notes = "Creates a copy of this object, with its count set to 1" }, DamageItem = { Params = "[Amount]", Return = "bool", Notes = "Adds the specified damage. Returns true when damage reaches max value and the item should be destroyed (but doesn't destroy the item)" }, Empty = { Params = "", Return = "", Notes = "Resets the instance to an empty item" }, GetMaxDamage = { Params = "", Return = "number", Notes = "Returns the maximum value for damage that this item can get before breaking; zero if damage is not accounted for for this item type" }, GetMaxStackSize = { Params = "", Return = "number", Notes = "Returns the maximum stack size for this item." }, IsDamageable = { Params = "", Return = "bool", Notes = "Returns true if this item does account for its damage" }, IsEmpty = { Params = "", Return = "bool", Notes = "Returns true if this object represents an empty item (zero count or invalid ID)" }, IsEqual = { Params = "cItem", Return = "bool", Notes = "Returns true if the item in the parameter is the same as the one stored in the object (type, damage, lore, name and enchantments)" }, IsFullStack = { Params = "", Return = "bool", Notes = "Returns true if the item is stacked up to its maximum stacking" }, IsSameType = { Params = "cItem", Return = "bool", Notes = "Returns true if the item in the parameter is of the same ItemType as the one stored in the object. This is true even if the two items have different enchantments" }, IsBothNameAndLoreEmpty = { Params = "", Return = "bool", Notes = "Returns if both the custom name and lore are not set." }, IsCustomNameEmpty = { Params = "", Return = "bool", Notes = "Returns if the custom name of the cItem is empty." }, IsLoreEmpty = { Params = "", Return = "", Notes = "Returns if the lore of the cItem is empty." }, GetEnchantability = { Params = "", Return = "number", Notes = "Returns the enchantability of the item. When the item hasn't a enchantability, it will returns 0" }, EnchantByXPLevels = { Params = "NumXPLevels", Return = "bool", Notes = "Enchants the item using the specified number of XP levels. Returns true if item enchanted, false if not." }, IsEnchantable = { Params = "ItemType, WithBook", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is enchantable. If WithBook is true, the function is used in the anvil inventory with book enchantments. So it checks the \"only book enchantments\" too. Example: You can only enchant a hoe with a book." }, }, Variables = { m_Enchantments = { Type = "{{cEnchantments}}", Notes = "The enchantments that this item has" }, m_ItemCount = { Type = "number", Notes = "Number of items in this stack" }, m_ItemDamage = { Type = "number", Notes = "The damage of the item. Zero means no damage. Maximum damage can be queried with GetMaxDamage()" }, m_ItemType = { Type = "number", Notes = "The item type. One of E_ITEM_ or E_BLOCK_ constants" }, m_CustomName = { Type = "string", Notes = "The custom name for an item." }, m_Lore = { Type = "string", Notes = "The lore for an item. Line breaks are represented by the ` character." }, m_RepairCost = { Type = "number", Notes = "The repair cost of the item. The anvil need this value" }, m_Enchantments = { Type = "{{cEnchantments|cEnchantments}}}", Notes = "The enchantments of the item." }, }, AdditionalInfo = { { Header = "Usage notes", Contents = [[ Note that the object contained in a cItem class is quite complex and quite often new Minecraft versions add more stuff. Therefore it is recommended to copy cItem objects using the copy-constructor ("local copy = cItem(original);"), this is the only way that guarantees that the object will be copied at full, even with future versions of Cuberite. ]], }, { Header = "Example code", Contents = [[ The following code shows how to create items in several different ways (adapted from the Debuggers plugin): <pre class="prettyprint lang-lua"> -- empty item: local Item1 = cItem(); -- enchanted sword, enchantment given as numeric string (bad style; see Item5): local Item2 = cItem(E_ITEM_DIAMOND_SWORD, 1, 0, "1=1"); -- 1 undamaged shovel, no enchantment: local Item3 = cItem(E_ITEM_DIAMOND_SHOVEL); -- Add the Unbreaking enchantment. Note that Vanilla's levelcap isn't enforced: Item3.m_Enchantments:SetLevel(cEnchantments.enchUnbreaking, 4); -- 1 undamaged pickaxe, no enchantment: local Item4 = cItem(E_ITEM_DIAMOND_PICKAXE); -- Add multiple enchantments: Item4.m_Enchantments:SetLevel(cEnchantments.enchUnbreaking, 5); Item4.m_Enchantments:SetLevel(cEnchantments.enchEfficiency, 3); -- enchanted chestplate, enchantment given as textual stringdesc (good style) local Item5 = cItem(E_ITEM_DIAMOND_CHESTPLATE, 1, 0, "thorns=1;unbreaking=3"); </pre> ]], }, }, }, -- cItem cObjective = { Desc = [[ This class represents a single scoreboard objective. ]], Functions = { AddScore = { Params = "string, number", Return = "Score", Notes = "Adds a value to the score of the specified player and returns the new value." }, GetDisplayName = { Params = "", Return = "string", Notes = "Returns the display name of the objective. This name will be shown to the connected players." }, GetName = { Params = "", Return = "string", Notes = "Returns the internal name of the objective." }, GetScore = { Params = "string", Return = "Score", Notes = "Returns the score of the specified player." }, GetType = { Params = "", Return = "eType", Notes = "Returns the type of the objective. (i.e what is being tracked)" }, Reset = { Params = "", Return = "", Notes = "Resets the scores of the tracked players." }, ResetScore = { Params = "string", Return = "", Notes = "Reset the score of the specified player." }, SetDisplayName = { Params = "string", Return = "", Notes = "Sets the display name of the objective." }, SetScore = { Params = "string, Score", Return = "", Notes = "Sets the score of the specified player." }, SubScore = { Params = "string, number", Return = "Score", Notes = "Subtracts a value from the score of the specified player and returns the new value." }, }, Constants = { otAchievement = { Notes = "" }, otDeathCount = { Notes = "" }, otDummy = { Notes = "" }, otHealth = { Notes = "" }, otPlayerKillCount = { Notes = "" }, otStat = { Notes = "" }, otStatBlockMine = { Notes = "" }, otStatEntityKill = { Notes = "" }, otStatEntityKilledBy = { Notes = "" }, otStatItemBreak = { Notes = "" }, otStatItemCraft = { Notes = "" }, otStatItemUse = { Notes = "" }, otTotalKillCount = { Notes = "" }, }, }, -- cObjective cPainting = { Desc = "This class represents a painting in the world. These paintings are special and different from Vanilla in that they can be critical-hit.", Functions = { GetDirection = { Params = "", Return = "number", Notes = "Returns the direction the painting faces. Directions: ZP - 0, ZM - 2, XM - 1, XP - 3. Note that these are not the BLOCK_FACE constants." }, GetName = { Params = "", Return = "string", Notes = "Returns the name of the painting" }, }, }, -- cPainting cItemGrid = { Desc = [[This class represents a 2D array of items. It is used as the underlying storage and API for all cases that use a grid of items: <li>{{cChestEntity|Chest}} contents</li> <li>(TODO) Chest minecart contents</li> <li>{{cDispenserEntity|Dispenser}} contents</li> <li>{{cDropperEntity|Dropper}} contents</li> <li>{{cFurnaceEntity|Furnace}} contents (?)</li> <li>{{cHopperEntity|Hopper}} contents</li> <li>(TODO) Hopper minecart contents</li> <li>{{cPlayer|Player}} Inventory areas</li> <li>(TODO) Trapped chest contents</li> </p> <p>The items contained in this object are accessed either by a pair of XY coords, or a slot number (x + Width * y). There are functions available for converting between the two formats. ]], Functions = { AddItem = { Params = "{{cItem|cItem}}, [AllowNewStacks]", Return = "number", Notes = "Adds an item to the storage; if AllowNewStacks is true (default), will also create new stacks in empty slots. Returns the number of items added" }, AddItems = { Params = "{{cItems|cItems}}, [AllowNewStacks]", Return = "number", Notes = "Same as AddItem, but for several items at once" }, ChangeSlotCount = { { Params = "SlotNum, AddToCount", Return = "number", Notes = "Adds AddToCount to the count of items in the specified slot. If the slot was empty, ignores the call. Returns the new count in the slot, or -1 if invalid SlotNum" }, { Params = "X, Y, AddToCount", Return = "number", Notes = "Adds AddToCount to the count of items in the specified slot. If the slot was empty, ignores the call. Returns the new count in the slot, or -1 if invalid slot coords" }, }, Clear = { Params = "", Return = "", Notes = "Empties all slots" }, CopyToItems = { Params = "{{cItems|cItems}}", Return = "", Notes = "Copies all non-empty slots into the cItems object provided; original cItems contents are preserved" }, DamageItem = { { Params = "SlotNum, [DamageAmount]", Return = "bool", Notes = "Adds the specified damage (1 by default) to the specified item, returns true if the item reached its max damage and should be destroyed" }, { Params = "X, Y, [DamageAmount]", Return = "bool", Notes = "Adds the specified damage (1 by default) to the specified item, returns true if the item reached its max damage and should be destroyed" }, }, EmptySlot = { { Params = "SlotNum", Return = "", Notes = "Destroys the item in the specified slot" }, { Params = "X, Y", Return = "", Notes = "Destroys the item in the specified slot" }, }, GetFirstEmptySlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the first empty slot, -1 if all slots are full" }, GetFirstUsedSlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the first non-empty slot, -1 if all slots are empty" }, GetHeight = { Params = "", Return = "number", Notes = "Returns the Y dimension of the grid" }, GetLastEmptySlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the last empty slot, -1 if all slots are full" }, GetLastUsedSlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the last non-empty slot, -1 if all slots are empty" }, GetNextEmptySlot = { Params = "StartFrom", Return = "number", Notes = "Returns the SlotNumber of the first empty slot following StartFrom, -1 if all the following slots are full" }, GetNextUsedSlot = { Params = "StartFrom", Return = "number", Notes = "Returns the SlotNumber of the first non-empty slot following StartFrom, -1 if all the following slots are full" }, GetNumSlots = { Params = "", Return = "number", Notes = "Returns the total number of slots in the grid (Width * Height)" }, GetSlot = { { Params = "SlotNumber", Return = "{{cItem|cItem}}", Notes = "Returns the item in the specified slot. Note that the item is read-only" }, { Params = "X, Y", Return = "{{cItem|cItem}}", Notes = "Returns the item in the specified slot. Note that the item is read-only" }, }, GetSlotCoords = { Params = "SlotNum", Return = "number, number", Notes = "Returns the X and Y coords for the specified SlotNumber. Returns \"-1, -1\" on invalid SlotNumber" }, GetSlotNum = { Params = "X, Y", Return = "number", Notes = "Returns the SlotNumber for the specified slot coords. Returns -1 on invalid coords" }, GetWidth = { Params = "", Return = "number", Notes = "Returns the X dimension of the grid" }, HasItems = { Params = "{{cItem|cItem}}", Return = "bool", Notes = "Returns true if there are at least as many items of the specified type as in the parameter" }, HowManyCanFit = { Params = "{{cItem|cItem}}", Return = "number", Notes = "Returns the number of the specified items that can fit in the storage, including empty slots" }, HowManyItems = { Params = "{{cItem|cItem}}", Return = "number", Notes = "Returns the number of the specified items that are currently stored" }, IsSlotEmpty = { { Params = "SlotNum", Return = "bool", Notes = "Returns true if the specified slot is empty, or an invalid slot is specified" }, { Params = "X, Y", Return = "bool", Notes = "Returns true if the specified slot is empty, or an invalid slot is specified" }, }, RemoveItem = { Params = "{{cItem}}", Return = "number", Notes = "Removes the specified item from the grid, as many as possible, up to the item's m_ItemCount. Returns the number of items that were removed." }, RemoveOneItem = { { Params = "SlotNum", Return = "{{cItem|cItem}}", Notes = "Removes one item from the stack in the specified slot and returns it as a single cItem. Empty slots are skipped and an empty item is returned" }, { Params = "X, Y", Return = "{{cItem|cItem}}", Notes = "Removes one item from the stack in the specified slot and returns it as a single cItem. Empty slots are skipped and an empty item is returned" }, }, SetSlot = { { Params = "SlotNum, {{cItem|cItem}}", Return = "", Notes = "Sets the specified slot to the specified item" }, { Params = "X, Y, {{cItem|cItem}}", Return = "", Notes = "Sets the specified slot to the specified item" }, }, }, AdditionalInfo = { { Header = "Code example: Add items to player inventory", Contents = [[ The following code tries to add 32 sticks to a player's main inventory: <pre class="prettyprint lang-lua"> local Items = cItem(E_ITEM_STICK, 32); local PlayerMainInventory = Player:GetInventorySlots(); -- PlayerMainInventory is of type cItemGrid local NumAdded = PlayerMainInventory:AddItem(Items); if (NumAdded == Items.m_ItemCount) then -- All the sticks did fit LOG("Added 32 sticks"); else -- Some (or all) of the sticks didn't fit LOG("Tried to add 32 sticks, but only " .. NumAdded .. " could fit"); end </pre> ]], }, { Header = "Code example: Damage an item", Contents = [[ The following code damages the helmet in the player's armor and destroys it if it reaches max damage: <pre class="prettyprint lang-lua"> local PlayerArmor = Player:GetArmorSlots(); -- PlayerArmor is of type cItemGrid if (PlayerArmor:DamageItem(0)) then -- Helmet is at SlotNum 0 -- The helmet has reached max damage, destroy it: PlayerArmor:EmptySlot(0); end </pre> ]], }, }, -- AdditionalInfo }, -- cItemGrid cItems = { Desc = [[ This class represents a numbered collection (array) of {{cItem}} objects. The array indices start at zero, each consecutive item gets a consecutive index. This class is used for spawning multiple pickups or for mass manipulating an inventory. ]], Functions = { constructor = { Params = "", Return = "cItems", Notes = "Creates a new cItems object" }, Add = { { Params = "{{cItem|cItem}}", Return = "", Notes = "Adds a new item to the end of the collection" }, { Params = "ItemType, ItemCount, ItemDamage", Return = "", Notes = "Adds a new item to the end of the collection" }, }, Clear = { Params = "", Return = "", Notes = "Removes all items from the collection" }, Delete = { Params = "Index", Return = "", Notes = "Deletes item at the specified index" }, Get = { Params = "Index", Return = "{{cItem|cItem}}", Notes = "Returns the item at the specified index" }, Set = { { Params = "Index, {{cItem|cItem}}", Return = "", Notes = "Sets the item at the specified index to the specified item" }, { Params = "Index, ItemType, ItemCount, ItemDamage", Return = "", Notes = "Sets the item at the specified index to the specified item" }, }, Size = { Params = "", Return = "number", Notes = "Returns the number of items in the collection" }, }, }, -- cItems cLuaWindow = { Desc = [[This class is used by plugins wishing to display a custom window to the player, unrelated to block entities or entities near the player. The window can be of any type and have any contents that the plugin defines. Callbacks for when the player modifies the window contents and when the player closes the window can be set. </p> <p>This class inherits from the {{cWindow|cWindow}} class, so all cWindow's functions and constants can be used, in addition to the cLuaWindow-specific functions listed below. </p> <p>The contents of this window are represented by a {{cWindow|cWindow}}:GetSlot() etc. or {{cPlayer|cPlayer}}:GetInventory() to access the player inventory. </p> <p>When creating a new cLuaWindow object, you need to specify both the window type and the contents' width and height. Note that Cuberite accepts any combination of these, but opening a window for a player may crash their client if the contents' dimensions don't match the client's expectations. </p> <p>To open the window for a player, call {{cPlayer|cPlayer}}:OpenWindow(). Multiple players can open window of the same cLuaWindow object. All players see the same items in the window's contents (like chest, unlike crafting table). ]], Functions = { constructor = { Params = "WindowType, ContentsWidth, ContentsHeight, Title", Return = "", Notes = "Creates a new object of this class" }, GetContents = { Params = "", Return = "{{cItemGrid|cItemGrid}}", Notes = "Returns the cItemGrid object representing the internal storage in this window" }, SetOnClosing = { Params = "OnClosingCallback", Return = "", Notes = "Sets the function that the window will call when it is about to be closed by a player" }, SetOnSlotChanged = { Params = "OnSlotChangedCallback", Return = "", Notes = "Sets the function that the window will call when a slot is changed by a player" }, }, AdditionalInfo = { { Header = "Callbacks", Contents = [[ The object calls the following functions at the appropriate time: ]], }, { Header = "OnClosing Callback", Contents = [[ This callback, settable via the SetOnClosing() function, will be called when the player tries to close the window, or the window is closed for any other reason (such as a player disconnecting).</p> <pre class="prettyprint lang-lua"> function OnWindowClosing(a_Window, a_Player, a_CanRefuse) </pre> <p> The a_Window parameter is the cLuaWindow object representing the window, a_Player is the player for whom the window is about to close. a_CanRefuse specifies whether the callback can refuse the closing. If the callback returns true and a_CanRefuse is true, the window is not closed (internally, the server sends a new OpenWindow packet to the client). ]], }, { Header = "OnSlotChanged Callback", Contents = [[ This callback, settable via the SetOnSlotChanged() function, will be called whenever the contents of any slot in the window's contents (i. e. NOT in the player inventory!) changes.</p> <pre class="prettyprint lang-lua"> function OnWindowSlotChanged(a_Window, a_SlotNum) </pre> <p>The a_Window parameter is the cLuaWindow object representing the window, a_SlotNum is the slot number. There is no reference to a {{cPlayer}}, because the slot change needn't originate from the player action. To get or set the slot, you'll need to retrieve a cPlayer object, for example by calling {{cWorld|cWorld}}:DoWithPlayer(). </p> <p>Any returned values are ignored. ]], }, { Header = "Example", Contents = [[ This example is taken from the Debuggers plugin, used to test the API functionality. It opens a window and refuse to close it 3 times. It also logs slot changes to the server console. <pre class="prettyprint lang-lua"> -- Callback that refuses to close the window twice, then allows: local Attempt = 1; local OnClosing = function(Window, Player, CanRefuse) Player:SendMessage("Window closing attempt #" .. Attempt .. "; CanRefuse = " .. tostring(CanRefuse)); Attempt = Attempt + 1; return CanRefuse and (Attempt <= 3); -- refuse twice, then allow, unless CanRefuse is set to true end -- Log the slot changes: local OnSlotChanged = function(Window, SlotNum) LOG("Window \"" .. Window:GetWindowTitle() .. "\" slot " .. SlotNum .. " changed."); end -- Set window contents: -- a_Player is a cPlayer object received from the outside of this code fragment local Window = cLuaWindow(cWindow.Hopper, 3, 3, "TestWnd"); Window:SetSlot(a_Player, 0, cItem(E_ITEM_DIAMOND, 64)); Window:SetOnClosing(OnClosing); Window:SetOnSlotChanged(OnSlotChanged); -- Open the window: a_Player:OpenWindow(Window); </pre> ]], }, }, -- AdditionalInfo Inherits = "cWindow", }, -- cLuaWindow cMap = { Desc = [[ This class encapsulates a single in-game colored map.</p> <p> The contents (i.e. pixel data) of a cMap are dynamically updated by each tracked {{cPlayer}} instance. Furthermore, a cMap maintains and periodically updates a list of map decorators, which are objects drawn on the map that can freely move (e.g. Player and item frame pointers). ]], Functions = { EraseData = { Params = "", Return = "", Notes = "Erases all pixel data." }, GetCenterX = { Params = "", Return = "number", Notes = "Returns the X coord of the map's center." }, GetCenterZ = { Params = "", Return = "number", Notes = "Returns the Y coord of the map's center." }, GetDimension = { Params = "", Return = "eDimension", Notes = "Returns the dimension of the associated world." }, GetHeight = { Params = "", Return = "number", Notes = "Returns the height of the map." }, GetID = { Params = "", Return = "number", Notes = "Returns the numerical ID of the map. (The item damage value)" }, GetName = { Params = "", Return = "string", Notes = "Returns the name of the map." }, GetNumPixels = { Params = "", Return = "number", Notes = "Returns the number of pixels in this map." }, GetPixel = { Params = "PixelX, PixelZ", Return = "ColorID", Notes = "Returns the color of the specified pixel." }, GetPixelWidth = { Params = "", Return = "number", Notes = "Returns the width of a single pixel in blocks." }, GetScale = { Params = "", Return = "number", Notes = "Returns the scale of the map. Range: [0,4]" }, GetWidth = { Params = "", Return = "number", Notes = "Returns the width of the map." }, GetWorld = { Params = "", Return = "cWorld", Notes = "Returns the associated world." }, Resize = { Params = "Width, Height", Return = "", Notes = "Resizes the map. WARNING: This will erase the pixel data." }, SetPixel = { Params = "PixelX, PixelZ, ColorID", Return = "bool", Notes = "Sets the color of the specified pixel. Returns false on error (Out of range)." }, SetPosition = { Params = "CenterX, CenterZ", Return = "", Notes = "Relocates the map. The pixel data will not be modified." }, SetScale = { Params = "number", Return = "", Notes = "Rescales the map. The pixel data will not be modified." }, }, Constants = { E_BASE_COLOR_BLUE = { Notes = "" }, E_BASE_COLOR_BROWN = { Notes = "" }, E_BASE_COLOR_DARK_BROWN = { Notes = "" }, E_BASE_COLOR_DARK_GRAY = { Notes = "" }, E_BASE_COLOR_DARK_GREEN = { Notes = "" }, E_BASE_COLOR_GRAY_1 = { Notes = "" }, E_BASE_COLOR_GRAY_2 = { Notes = "" }, E_BASE_COLOR_LIGHT_BROWN = { Notes = "" }, E_BASE_COLOR_LIGHT_GRAY = { Notes = "" }, E_BASE_COLOR_LIGHT_GREEN = { Notes = "" }, E_BASE_COLOR_PALE_BLUE = { Notes = "" }, E_BASE_COLOR_RED = { Notes = "" }, E_BASE_COLOR_TRANSPARENT = { Notes = "" }, E_BASE_COLOR_WHITE = { Notes = "" }, }, }, -- cMap cMapManager = { Desc = [[ This class is associated with a single {{cWorld}} instance and manages a list of maps. ]], Functions = { DoWithMap = { Params = "ID, CallbackFunction", Return = "bool", Notes = "If a map with the specified ID exists, calls the CallbackFunction for that map. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cMap|Map}})</pre> Returns true if the map was found and the callback called, false if map not found." }, GetNumMaps = { Params = "", Return = "number", Notes = "Returns the number of registered maps." }, }, }, -- cMapManager cMojangAPI = { Desc = [[ Provides interface to various API functions that Mojang provides through their servers. Note that some of these calls will wait for a response from the network, and so shouldn't be used while the server is fully running (or at least when there are players connected) to avoid percepted lag.</p> <p> All the functions are static, call them using the <code>cMojangAPI:Function()</code> convention.</p> <p> Mojang uses two formats for UUIDs, short and dashed. Cuberite works with short UUIDs internally, but will convert to dashed UUIDs where needed - in the protocol login for example. The MakeUUIDShort() and MakeUUIDDashed() functions are provided for plugins to use for conversion between the two formats.</p> <p> This class will cache values returned by the API service. The cache will hold the values for 7 days by default, after that, they will no longer be available. This is in order to not let the server get banned from using the API service, since they are rate-limited to 600 queries per 10 minutes. The cache contents also gets updated whenever a player successfully joins, since that makes the server contact the API service, too, and retrieve the relevant data.</p> ]], Functions = { AddPlayerNameToUUIDMapping = { Params = "PlayerName, UUID", Return = "", Notes = "(STATIC) Adds the specified PlayerName-to-UUID mapping into the cache, with current timestamp. Accepts both short or dashed UUIDs. " }, GetPlayerNameFromUUID = { Params = "UUID, [UseOnlyCached]", Return = "PlayerName", Notes = "(STATIC) Returns the playername that corresponds to the given UUID, or an empty string on error. If UseOnlyCached is false (the default), queries the Mojang servers if the UUID is not in the cache. The UUID can be either short or dashed. <br /><b>WARNING</b>: Do NOT use this function with UseOnlyCached set to false while the server is running. Only use it when the server is starting up (inside the Initialize() method), otherwise you will lag the server severely." }, GetUUIDFromPlayerName = { Params = "PlayerName, [UseOnlyCached]", Return = "UUID", Notes = "(STATIC) Returns the (short) UUID that corresponds to the given playername, or an empty string on error. If UseOnlyCached is false (the default), queries the Mojang servers if the playername is not in the cache. <br /><b>WARNING</b>: Do NOT use this function with UseOnlyCached set to false while the server is running. Only use it when the server is starting up (inside the Initialize() method), otherwise you will lag the server severely." }, GetUUIDsFromPlayerNames = { Params = "PlayerNames, [UseOnlyCached]", Return = "table", Notes = "(STATIC) Returns a table that contains the map, 'PlayerName' -> '(short) UUID', for all valid playernames in the input array-table. PlayerNames not recognized will not be set in the returned map. If UseOnlyCached is false (the default), queries the Mojang servers for the results that are not in the cache. <br /><b>WARNING</b>: Do NOT use this function with UseOnlyCached set to false while the server is running. Only use it when the server is starting up (inside the Initialize() method), otherwise you will lag the server severely." }, MakeUUIDDashed = { Params = "UUID", Return = "DashedUUID", Notes = "(STATIC) Converts the UUID to a dashed format (\"01234567-8901-2345-6789-012345678901\"). Accepts both dashed or short UUIDs. Logs a warning and returns an empty string if UUID format not recognized." }, MakeUUIDShort = { Params = "UUID", Return = "ShortUUID", Notes = "(STATIC) Converts the UUID to a short format (without dashes, \"01234567890123456789012345678901\"). Accepts both dashed or short UUIDs. Logs a warning and returns an empty string if UUID format not recognized." }, }, }, cMonster = { Desc = [[ This class is the base class for all computer-controlled mobs in the game.</p> <p> To spawn a mob in a world, use the {{cWorld}}:SpawnMob() function. ]], Functions = { HasCustomName = { Params = "", Return = "bool", Notes = "Returns true if the monster has a custom name." }, GetCustomName = { Params = "", Return = "string", Notes = "Gets the custom name of the monster. If no custom name is set, the function returns an empty string." }, SetCustomName = { Params = "string", Return = "", Notes = "Sets the custom name of the monster. You see the name over the monster. If you want to disable the custom name, simply set an empty string." }, IsCustomNameAlwaysVisible = { Params = "", Return = "bool", Notes = "Is the custom name of this monster always visible? If not, you only see the name when you sight the mob." }, SetCustomNameAlwaysVisible = { Params = "bool", Return = "", Notes = "Sets the custom name visiblity of this monster. If it's false, you only see the name when you sight the mob. If it's true, you always see the custom name." }, FamilyFromType = { Params = "{{Globals#MobType|MobType}}", Return = "{{cMonster#MobFamily|MobFamily}}", Notes = "(STATIC) Returns the mob family ({{cMonster#MobFamily|mfXXX}} constants) based on the mob type ({{Globals#MobType|mtXXX}} constants)" }, GetMobFamily = { Params = "", Return = "{{cMonster#MobFamily|MobFamily}}", Notes = "Returns this mob's family ({{cMonster#MobFamily|mfXXX}} constant)" }, GetMobType = { Params = "", Return = "{{Globals#MobType|MobType}}", Notes = "Returns the type of this mob ({{Globals#MobType|mtXXX}} constant)" }, GetSpawnDelay = { Params = "{{cMonster#MobFamily|MobFamily}}", Return = "number", Notes = "(STATIC) Returns the spawn delay - the number of game ticks between spawn attempts - for the specified mob family." }, MobTypeToString = { Params = "{{Globals#MobType|MobType}}", Return = "string", Notes = "(STATIC) Returns the string representing the given mob type ({{Globals#MobType|mtXXX}} constant), or empty string if unknown type." }, MobTypeToVanillaName = { Params = "{{Globals#MobType|MobType}}", Return = "string", Notes = "(STATIC) Returns the vanilla name of the given mob type, or empty string if unknown type." }, MoveToPosition = { Params = "Position", Return = "", Notes = "Moves mob to the specified position" }, StringToMobType = { Params = "string", Return = "{{Globals#MobType|MobType}}", Notes = "(STATIC) Returns the mob type ({{Globals#MobType|mtXXX}} constant) parsed from the string type (\"creeper\"), or mtInvalidType if unrecognized." }, GetRelativeWalkSpeed = { Params = "", Return = "number", Notes = "Returns the relative walk speed of this mob. Standard is 1.0" }, SetRelativeWalkSpeed = { Params = "number", Return = "", Notes = "Sets the relative walk speed of this mob. Standard is 1.0" }, SetAge = { Params = "number", Return = "", Notes = "Sets the age of the monster" }, GetAge = { Params = "", Return = "number", Notes = "Returns the age of the monster" }, IsBaby = { Params = "", Return = "bool", Notes = "Returns true if the monster is a baby" }, }, Constants = { mfAmbient = { Notes = "Family: ambient (bat)" }, mfHostile = { Notes = "Family: hostile (blaze, cavespider, creeper, enderdragon, enderman, ghast, giant, magmacube, silverfish, skeleton, slime, spider, witch, wither, zombie, zombiepigman)" }, mfMaxplusone = { Notes = "The maximum family value, plus one. Returned when monster family not recognized." }, mfPassive = { Notes = "Family: passive (chicken, cow, horse, irongolem, mooshroom, ocelot, pig, sheep, snowgolem, villager, wolf)" }, mfWater = { Notes = "Family: water (squid)" }, mtBat = { Notes = "" }, mtBlaze = { Notes = "" }, mtCaveSpider = { Notes = "" }, mtChicken = { Notes = "" }, mtCow = { Notes = "" }, mtCreeper = { Notes = "" }, mtEnderDragon = { Notes = "" }, mtEnderman = { Notes = "" }, mtGhast = { Notes = "" }, mtGiant = { Notes = "" }, mtHorse = { Notes = "" }, mtInvalidType = { Notes = "Invalid monster type. Returned when monster type not recognized" }, mtIronGolem = { Notes = "" }, mtMagmaCube = { Notes = "" }, mtMooshroom = { Notes = "" }, mtOcelot = { Notes = "" }, mtPig = { Notes = "" }, mtSheep = { Notes = "" }, mtSilverfish = { Notes = "" }, mtSkeleton = { Notes = "" }, mtSlime = { Notes = "" }, mtSnowGolem = { Notes = "" }, mtSpider = { Notes = "" }, mtSquid = { Notes = "" }, mtVillager = { Notes = "" }, mtWitch = { Notes = "" }, mtWither = { Notes = "" }, mtWolf = { Notes = "" }, mtZombie = { Notes = "" }, mtZombiePigman = { Notes = "" }, }, ConstantGroups = { MobFamily = { Include = "mf.*", TextBefore = [[ Mobs are divided into families. The following constants are used for individual family types: ]], }, }, Inherits = "cPawn", }, -- cMonster cPawn = { Desc = [[cPawn is a controllable pawn object, controlled by either AI or a player. cPawn inherits all functions and members of {{cEntity}} ]], Functions = { TeleportToEntity = { Return = "" }, TeleportTo = { Return = "" }, Heal = { Return = "" }, TakeDamage = { Return = "" }, KilledBy = { Return = "" }, GetHealth = { Return = "number" }, AddEntityEffect = { Params = "{{cEntityEffect|EffectType}}", Return = "", Notes = "Applies an entity effect" }, RemoveEntityEffect = { Params = "{{cEntityEffect|EffectType}}", Return = "", Notes = "Removes a currently applied entity effect" }, HasEntityEffect = { Return = "bool", Params = "{{cEntityEffect|EffectType}}", Notes = "Returns true, if the supplied entity effect type is currently applied" }, ClearEntityEffects = { Return = "", Notes = "Removes all currently applied entity effects" }, }, Inherits = "cEntity", }, -- cPawn cPickup = { Desc = [[ This class represents a pickup entity (an item that the player or mobs can pick up). It is also commonly known as "drops". With this class you could create your own "drop" or modify those created automatically. ]], Functions = { CollectedBy = { Params = "{{cPlayer}}", Return = "bool", Notes = "Tries to make the player collect the pickup. Returns true if the pickup was collected, at least partially." }, GetAge = { Params = "", Return = "number", Notes = "Returns the number of ticks that the pickup has existed." }, GetItem = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the item represented by this pickup" }, IsCollected = { Params = "", Return = "bool", Notes = "Returns true if this pickup has already been collected (is waiting to be destroyed)" }, IsPlayerCreated = { Params = "", Return = "bool", Notes = "Returns true if the pickup was created by a player" }, SetAge = { Params = "AgeTicks", Return = "", Notes = "Sets the pickup's age, in ticks." }, }, Inherits = "cEntity", }, -- cPickup cPlayer = { Desc = [[ This class describes a player in the server. cPlayer inherits all functions and members of {{cPawn|cPawn}}. It handles all the aspects of the gameplay, such as hunger, sprinting, inventory etc. ]], Functions = { AddFoodExhaustion = { Params = "Exhaustion", Return = "", Notes = "Adds the specified number to the food exhaustion. Only positive numbers expected." }, CalcLevelFromXp = { Params = "XPAmount", Return = "number", Notes = "(STATIC) Returns the level which is reached with the specified amount of XP. Inverse of XpForLevel()." }, CanFly = { Return = "bool", Notes = "Returns if the player is able to fly." }, CloseWindow = { Params = "[CanRefuse]", Return = "", Notes = "Closes the currently open UI window. If CanRefuse is true (default), the window may refuse the closing." }, CloseWindowIfID = { Params = "WindowID, [CanRefuse]", Return = "", Notes = "Closes the currently open UI window if its ID matches the given ID. If CanRefuse is true (default), the window may refuse the closing." }, DeltaExperience = { Params = "DeltaXP", Return = "", Notes = "Adds or removes XP from the current XP amount. Won't allow XP to go negative. Returns the new experience, -1 on error (XP overflow)." }, Feed = { Params = "AddFood, AddSaturation", Return = "bool", Notes = "Tries to add the specified amounts to food level and food saturation level (only positive amounts expected). Returns true if player was hungry and the food was consumed, false if too satiated." }, FoodPoison = { Params = "NumTicks", Return = "", Notes = "Starts the food poisoning for the specified amount of ticks; if already foodpoisoned, sets FoodPoisonedTicksRemaining to the larger of the two" }, ForceSetSpeed = { Params = "{{Vector3d|Direction}}", Notes = "Forces the player to move to the given direction." }, GetClientHandle = { Params = "", Return = "{{cClientHandle}}", Notes = "Returns the client handle representing the player's connection. May be nil (AI players)." }, GetColor = { Return = "string", Notes = "Returns the full color code to be used for this player's messages (based on their rank). Prefix player messages with this code." }, GetCurrentXp = { Params = "", Return = "number", Notes = "Returns the current amount of XP" }, GetCustomName = { Params = "", Return = "string", Notes = "Returns the custom name of this player. If the player hasn't a custom name, it will return an empty string." }, GetEffectiveGameMode = { Params = "", Return = "{{Globals#GameMode|GameMode}}", Notes = "(OBSOLETE) Returns the current resolved game mode of the player. If the player is set to inherit the world's gamemode, returns that instead. See also GetGameMode() and IsGameModeXXX() functions. Note that this function is the same as GetGameMode(), use that function instead." }, GetEquippedItem = { Params = "", Return = "{{cItem}}", Notes = "Returns the item that the player is currently holding; empty item if holding nothing." }, GetEyeHeight = { Return = "number", Notes = "Returns the height of the player's eyes, in absolute coords" }, GetEyePosition = { Return = "{{Vector3d|EyePositionVector}}", Notes = "Returns the position of the player's eyes, as a {{Vector3d}}" }, GetFloaterID = { Params = "", Return = "number", Notes = "Returns the Entity ID of the fishing hook floater that belongs to the player. Returns -1 if no floater is associated with the player. FIXME: Undefined behavior when the player has used multiple fishing rods simultanously." }, GetFlyingMaxSpeed = { Params = "", Return = "number", Notes = "Returns the maximum flying speed, relative to the default game flying speed. Defaults to 1, but plugins may modify it for faster or slower flying." }, GetFoodExhaustionLevel = { Params = "", Return = "number", Notes = "Returns the food exhaustion level" }, GetFoodLevel = { Params = "", Return = "number", Notes = "Returns the food level (number of half-drumsticks on-screen)" }, GetFoodPoisonedTicksRemaining = { Params = "", Return = "", Notes = "Returns the number of ticks left for the food posoning effect" }, GetFoodSaturationLevel = { Params = "", Return = "number", Notes = "Returns the food saturation (overcharge of the food level, is depleted before food level)" }, GetFoodTickTimer = { Params = "", Return = "", Notes = "Returns the number of ticks past the last food-based heal or damage action; when this timer reaches 80, a new heal / damage is applied." }, GetGameMode = { Return = "{{Globals#GameMode|GameMode}}", Notes = "Returns the player's gamemode. The player may have their gamemode unassigned, in which case they inherit the gamemode from the current {{cWorld|world}}.<br /> <b>NOTE:</b> Instead of comparing the value returned by this function to the gmXXX constants, use the IsGameModeXXX() functions. These functions handle the gamemode inheritance automatically."}, GetIP = { Return = "string", Notes = "Returns the IP address of the player, if available. Returns an empty string if there's no IP to report."}, GetInventory = { Return = "{{cInventory|Inventory}}", Notes = "Returns the player's inventory"}, GetLastBedPos = { Params = "", Return = "{{Vector3i}}", Notes = "Returns the position of the last bed the player has slept in, or the world's spawn if no such position was recorded." }, GetMaxSpeed = { Params = "", Return = "number", Notes = "Returns the player's current maximum speed, relative to the game default speed. Takes into account the sprinting / flying status." }, GetName = { Return = "string", Notes = "Returns the player's name" }, GetNormalMaxSpeed = { Params = "", Return = "number", Notes = "Returns the player's maximum walking speed, relative to the game default speed. Defaults to 1, but plugins may modify it for faster or slower walking." }, GetPermissions = { Params = "", Return = "array-table of strings", Notes = "Returns the list of all permissions that the player has assigned to them through their rank." }, GetPlayerListName = { Return = "string", Notes = "Returns the name that is used in the playerlist." }, GetResolvedPermissions = { Return = "array-table of string", Notes = "Returns all the player's permissions, as a table. The permissions are stored in the array part of the table, beginning with index 1." }, GetSprintingMaxSpeed = { Params = "", Return = "number", Notes = "Returns the player's maximum sprinting speed, relative to the game default speed. Defaults to 1.3, but plugins may modify it for faster or slower sprinting." }, GetStance = { Return = "number", Notes = "Returns the player's stance (Y-pos of player's eyes)" }, GetTeam = { Params = "", Return = "{{cTeam}}", Notes = "Returns the team that the player belongs to, or nil if none." }, GetThrowSpeed = { Params = "SpeedCoeff", Return = "{{Vector3d}}", Notes = "Returns the speed vector for an object thrown with the specified speed coeff. Basically returns the normalized look vector multiplied by the coeff, with a slight random variation." }, GetThrowStartPos = { Params = "", Return = "{{Vector3d}}", Notes = "Returns the position where the projectiles should start when thrown by this player." }, GetUUID = { Params = "", Return = "string", Notes = "Returns the (short) UUID that the player is using. Could be empty string for players that don't have a Mojang account assigned to them (in the future, bots for example)." }, GetWindow = { Params = "", Return = "{{cWindow}}", Notes = "Returns the currently open UI window. If the player doesn't have any UI window open, returns the inventory window." }, GetXpLevel = { Params = "", Return = "number", Notes = "Returns the current XP level (based on current XP amount)." }, GetXpLifetimeTotal = { Params = "", Return = "number", Notes = "Returns the amount of XP that has been accumulated throughout the player's lifetime." }, GetXpPercentage = { Params = "", Return = "number", Notes = "Returns the percentage of the experience bar - the amount of XP towards the next XP level. Between 0 and 1." }, HasCustomName = { Params = "", Return = "bool", Notes = "Returns true if the player has a custom name." }, HasPermission = { Params = "PermissionString", Return = "bool", Notes = "Returns true if the player has the specified permission" }, Heal = { Params = "HitPoints", Return = "", Notes = "Heals the player by the specified amount of HPs. Only positive amounts are expected. Sends a health update to the client." }, IsEating = { Params = "", Return = "bool", Notes = "Returns true if the player is currently eating the item in their hand." }, IsFishing = { Params = "", Return = "bool", Notes = "Returns true if the player is currently fishing" }, IsFlying = { Return = "bool", Notes = "Returns true if the player is flying." }, IsGameModeAdventure = { Params = "", Return = "bool", Notes = "Returns true if the player is in the gmAdventure gamemode, or has their gamemode unset and the world is a gmAdventure world." }, IsGameModeCreative = { Params = "", Return = "bool", Notes = "Returns true if the player is in the gmCreative gamemode, or has their gamemode unset and the world is a gmCreative world." }, IsGameModeSpectator = { Params = "", Return = "bool", Notes = "Returns true if the player is in the gmSpectator gamemode, or has their gamemode unset and the world is a gmSpectator world." }, IsGameModeSurvival = { Params = "", Return = "bool", Notes = "Returns true if the player is in the gmSurvival gamemode, or has their gamemode unset and the world is a gmSurvival world." }, IsInBed = { Params = "", Return = "bool", Notes = "Returns true if the player is currently lying in a bed." }, IsSatiated = { Params = "", Return = "bool", Notes = "Returns true if the player is satiated (cannot eat)." }, IsVisible = { Params = "", Return = "bool", Notes = "Returns true if the player is visible to other players" }, LoadRank = { Params = "", Return = "", Notes = "Reloads the player's rank, message visuals and permissions from the {{cRankManager}}, based on the player's current rank." }, MoveTo = { Params = "{{Vector3d|NewPosition}}", Return = "Tries to move the player into the specified position." }, MoveToWorld = { Params = "WorldName", Return = "bool", Return = "Moves the player to the specified world. Returns true if successful." }, OpenWindow = { Params = "{{cWindow|Window}}", Return = "", Notes = "Opens the specified UI window for the player." }, PermissionMatches = { Params = "Permission, Template", Return = "bool", Notes = "(STATIC) Returns true if the specified permission matches the specified template. The template may contain wildcards." }, PlaceBlock = { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta", Return = "bool", Notes = "Places a block while impersonating the player. The {{OnPlayerPlacingBlock|HOOK_PLAYER_PLACING_BLOCK}} hook is called before the placement, and if it succeeds, the block is placed and the {{OnPlayerPlacedBlock|HOOK_PLAYER_PLACED_BLOCK}} hook is called. Returns true iff the block is successfully placed. Assumes that the block is in a currently loaded chunk." }, Respawn = { Params = "", Return = "", Notes = "Restores the health, extinguishes fire, makes visible and sends the Respawn packet." }, SendBlocksAround = { Params = "BlockX, BlockY, BlockZ, [Range]", Return = "", Notes = "Sends all the world's blocks in Range from the specified coords to the player, as a BlockChange packet. Range defaults to 1 (only one block sent)." }, SendMessage = { Params = "Message", Return = "", Notes = "Sends the specified message to the player." }, SendMessageFailure = { Params = "Message", Return = "", Notes = "Prepends Rose [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. For a command that failed to run because of insufficient permissions, etc." }, SendMessageFatal = { Params = "Message", Return = "", Notes = "Prepends Red [FATAL] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. For something serious, such as a plugin crash, etc." }, SendMessageInfo = { Params = "Message", Return = "", Notes = "Prepends Yellow [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. Informational message, such as command usage, etc." }, SendMessagePrivateMsg = { Params = "Message, SenderName", Return = "", Notes = "Prepends Light Blue [MSG: *SenderName*] / prepends SenderName and colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. For private messaging." }, SendMessageSuccess = { Params = "Message", Return = "", Notes = "Prepends Green [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. Success notification." }, SendMessageWarning = { Params = "Message, Sender", Return = "", Notes = "Prepends Rose [WARN] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. Denotes that something concerning, such as plugin reload, is about to happen." }, SendAboveActionBarMessage = { Params = "Message", Return = "", Notes = "Sends the specified message to the player (shows above action bar, doesn't show for < 1.8 clients)." }, SendSystemMessage = { Params = "Message", Return = "", Notes = "Sends the specified message to the player (doesn't show for < 1.8 clients)." }, SendRotation = { Params = "YawDegrees, PitchDegrees", Return = "", Notes = "Sends the specified rotation to the player, forcing them to look that way" }, SetBedPos = { Params = "{{Vector3i|Position}}", Return = "", Notes = "Sets the internal representation of the last bed position the player has slept in. The player will respawn at this position if they die." }, SetCanFly = { Params = "CanFly", Notes = "Sets if the player can fly or not." }, SetCrouch = { Params = "IsCrouched", Return = "", Notes = "Sets the crouch state, broadcasts the change to other players." }, SetCurrentExperience = { Params = "XPAmount", Return = "", Notes = "Sets the current amount of experience (and indirectly, the XP level)." }, SetCustomName = { Params = "string", Return = "", Notes = "Sets the custom name of this player. If you want to disable the custom name, simply set an empty string. The custom name will be used in the tab-list, in the player nametag and in the tab-completion." }, SetFlying = { Params = "IsFlying", Notes = "Sets if the player is flying or not." }, SetFlyingMaxSpeed = { Params = "FlyingMaxSpeed", Return = "", Notes = "Sets the flying maximum speed, relative to the game default speed. The default value is 1. Sends the updated speed to the client." }, SetFoodExhaustionLevel = { Params = "ExhaustionLevel", Return = "", Notes = "Sets the food exhaustion to the specified level." }, SetFoodLevel = { Params = "FoodLevel", Return = "", Notes = "Sets the food level (number of half-drumsticks on-screen)" }, SetFoodPoisonedTicksRemaining = { Params = "FoodPoisonedTicksRemaining", Return = "", Notes = "Sets the number of ticks remaining for food poisoning. Doesn't send foodpoisoning effect to the client, use FoodPoison() for that." }, SetFoodSaturationLevel = { Params = "FoodSaturationLevel", Return = "", Notes = "Sets the food saturation (overcharge of the food level)." }, SetFoodTickTimer = { Params = "FoodTickTimer", Return = "", Notes = "Sets the number of ticks past the last food-based heal or damage action; when this timer reaches 80, a new heal / damage is applied." }, SetGameMode = { Params = "{{Globals#GameMode|NewGameMode}}", Return = "", Notes = "Sets the gamemode for the player. The new gamemode overrides the world's default gamemode, unless it is set to gmInherit." }, SetIsFishing = { Params = "IsFishing, [FloaterEntityID]", Return = "", Notes = "Sets the 'IsFishing' flag for the player. The floater entity ID is expected for the true variant, it can be omitted when IsFishing is false. FIXME: Undefined behavior when multiple fishing rods are used simultanously" }, SetName = { Params = "Name", Return = "", Notes = "Sets the player name. This rename will NOT be visible to any players already in the server who are close enough to see this player." }, SetNormalMaxSpeed = { Params = "NormalMaxSpeed", Return = "", Notes = "Sets the normal (walking) maximum speed, relative to the game default speed. The default value is 1. Sends the updated speed to the client, if appropriate." }, SetSprint = { Params = "IsSprinting", Return = "", Notes = "Sets whether the player is sprinting or not." }, SetSprintingMaxSpeed = { Params = "SprintingMaxSpeed", Return = "", Notes = "Sets the sprinting maximum speed, relative to the game default speed. The default value is 1.3. Sends the updated speed to the client, if appropriate." }, SetTeam = { Params = "{{cTeam|Team}}", Return = "", Notes = "Moves the player to the specified team." }, SetVisible = { Params = "IsVisible", Return = "", Notes = "Sets the player visibility to other players" }, TossEquippedItem = { Params = "[Amount]", Return = "", Notes = "Tosses the item that the player has selected in their hotbar. Amount defaults to 1." }, TossHeldItem = { Params = "[Amount]", Return = "", Notes = "Tosses the item held by the cursor, then the player is in a UI window. Amount defaults to 1." }, TossPickup = { Params = "{{cItem|Item}}", Return = "", Notes = "Tosses a pickup newly created from the specified item." }, XpForLevel = { Params = "XPLevel", Return = "number", Notes = "(STATIC) Returns the total amount of XP needed for the specified XP level. Inverse of CalcLevelFromXp()." }, }, Constants = { EATING_TICKS = { Notes = "Number of ticks required for consuming an item." }, MAX_FOOD_LEVEL = { Notes = "The maximum food level value. When the food level is at this value, the player cannot eat." }, MAX_HEALTH = { Notes = "The maximum health value" }, }, Inherits = "cPawn", }, -- cPlayer cRankManager = { Desc = [[ Manages the players' permissions. The players are assigned a single rank, which contains groups of permissions. The functions in this class query or modify these.</p> <p> All the functions are static, call them using the <code>cRankManager:Function()</code> convention.</p> <p> The players are identified by their UUID, to support player renaming.</p> <p> The rank also contains specific "mesage visuals" - bits that are used for formatting messages from the players. There's a message prefix, which is put in front of every message the player sends, and the message suffix that is appended to each message. There's also a PlayerNameColorCode, which holds the color that is used for the player's name in the messages.</p> <p> Each rank can contain any number of permission groups. These groups allow for an easier setup of the permissions - you can share groups among ranks, so the usual approach is to group similar permissions together and add that group to any rank that should use those permissions.</p> <p> Permissions are added to individual groups. Each group can support unlimited permissions. Note that adding a permission to a group will make the permission available to all the ranks that contain that permission group.</p> <p> One rank is reserved as the Default rank. All players that don't have an explicit rank assigned to them will behave as if assigned to this rank. The default rank can be changed to any other rank at any time. Note that the default rank cannot be removed from the RankManager - RemoveRank() will change the default rank to the replacement rank, if specified, and fail if no replacement rank is specified. Renaming the default rank using RenameRank() will change the default rank to the new name. ]], Functions = { AddGroup = { Params = "GroupName", Return = "", Notes = "Adds the group of the specified name. Logs a warning and does nothing if the group already exists." }, AddGroupToRank = { Params = "GroupName, RankName", Return = "bool", Notes = "Adds the specified group to the specified rank. Returns true on success, false on failure - if the group name or the rank name is not found." }, AddPermissionToGroup = { Params = "Permission, GroupName", Return = "bool", Notes = "Adds the specified permission to the specified group. Returns true on success, false on failure - if the group name is not found." }, AddRank = { Params = "RankName, MsgPrefix, MsgSuffix, MsgNameColorCode", Return = "", Notes = "Adds a new rank of the specified name and with the specified message visuals. Logs an info message and does nothing if the rank already exists." }, ClearPlayerRanks = { Params = "", Return = "", Notes = "Removes all player ranks from the database. Note that this doesn't change the cPlayer instances for the already connected players, you need to update all the instances manually." }, GetAllGroups = { Params = "", Return = "array-table of groups' names", Notes = "Returns an array-table containing the names of all the groups that are known to the manager." }, GetAllPermissions = { Params = "", Return = "array-table of permissions", Notes = "Returns an array-table containing all the permissions that are known to the manager." }, GetAllPlayerUUIDs = { Params = "", Return = "array-table of uuids", Notes = "Returns the short uuids of all players stored in the rank DB, sorted by the players' names (case insensitive)." }, GetAllRanks = { Params = "", Return = "array-table of ranks' names", Notes = "Returns an array-table containing the names of all the ranks that are known to the manager." }, GetDefaultRank = { Params = "", Return = "string", Notes = "Returns the name of the default rank. " }, GetGroupPermissions = { Params = "GroupName", Return = "array-table of permissions", Notes = "Returns an array-table containing the permissions that the specified group contains." }, GetPlayerGroups = { Params = "PlayerUUID", Return = "array-table of groups' names", Notes = "Returns an array-table of the names of the groups that are assigned to the specified player through their rank. Returns an empty table if the player is not known or has no rank or groups assigned to them." }, GetPlayerMsgVisuals = { Params = "PlayerUUID", Return = "MsgPrefix, MsgSuffix, MsgNameColorCode", Notes = "Returns the message visuals assigned to the player. If the player is not explicitly assigned a rank, the default rank's visuals are returned. If there is an error, no value is returned at all." }, GetPlayerPermissions = { Params = "PlayerUUID", Return = "array-table of permissions", Notes = "Returns the permissions that the specified player is assigned through their rank. Returns the default rank's permissions if the player has no explicit rank assigned to them. Returns an empty array on error." }, GetPlayerRankName = { Params = "PlayerUUID", Return = "RankName", Notes = "Returns the name of the rank that is assigned to the specified player. An empty string (NOT the default rank) is returned if the player has no rank assigned to them." }, GetPlayerName = { Params = "PlayerUUID", Return = "PlayerName", Notes = "Returns the last name that the specified player has, for a player in the ranks database. An empty string is returned if the player isn't in the database." }, GetRankGroups = { Params = "RankName", Return = "array-table of groups' names", Notes = "Returns an array-table of the names of all the groups that are assigned to the specified rank. Returns an empty table if there is no such rank." }, GetRankPermissions = { Params = "RankName", Return = "array-table of permissions", Notes = "Returns an array-table of all the permissions that are assigned to the specified rank through its groups. Returns an empty table if there is no such rank." }, GetRankVisuals = { Params = "RankName", Return = "MsgPrefix, MsgSuffix, MsgNameColorCode", Notes = "Returns the message visuals for the specified rank. Returns no value if the specified rank does not exist." }, GroupExists = { Params = "GroupName", Return = "bool", Notes = "Returns true iff the specified group exists." }, IsGroupInRank = { Params = "GroupName, RankName", Return = "bool", Notes = "Returns true iff the specified group is assigned to the specified rank." }, IsPermissionInGroup = { Params = "Permission, GroupName", Return = "bool", Notes = "Returns true iff the specified permission is assigned to the specified group." }, IsPlayerRankSet = { Params = "PlayerUUID", Return = "bool", Notes = "Returns true iff the specified player has a rank assigned to them." }, RankExists = { Params = "RankName", Return = "bool", Notes = "Returns true iff the specified rank exists." }, RemoveGroup = { Params = "GroupName", Return = "", Notes = "Removes the specified group completely. The group will be removed from all the ranks using it and then erased from the manager. Logs an info message and does nothing if the group doesn't exist." }, RemoveGroupFromRank = { Params = "GroupName, RankName", Return = "", Notes = "Removes the specified group from the specified rank. The group will still exist, even if it isn't assigned to any rank. Logs an info message and does nothing if the group or rank doesn't exist." }, RemovePermissionFromGroup = { Params = "Permission, GroupName", Return = "", Notes = "Removes the specified permission from the specified group. Logs an info message and does nothing if the group doesn't exist." }, RemovePlayerRank = { Params = "PlayerUUID", Return = "", Notes = "Removes the player's rank; the player's left without a rank. Note that this doesn't change the {{cPlayer}} instances for the already connected players, you need to update all the instances manually. No action if the player has no rank assigned to them already." }, RemoveRank = { Params = "RankName, [ReplacementRankName]", Return = "", Notes = "Removes the specified rank. If ReplacementRankName is given, the players that have RankName will get their rank set to ReplacementRankName. If it isn't given, or is an invalid rank, the players will be removed from the manager, their ranks will be unset completely. Logs an info message and does nothing if the rank is not found." }, RenameGroup = { Params = "OldName, NewName", Return = "", Notes = "Renames the specified group. Logs an info message and does nothing if the group is not found or the new name is already used." }, RenameRank = { Params = "OldName, NewName", Return = "", Notes = "Renames the specified rank. Logs an info message and does nothing if the rank is not found or the new name is already used." }, SetDefaultRank = { Params = "RankName", Return = "bool", Notes = "Sets the specified rank as the default rank. Returns true on success, false on failure (rank doesn't exist)." }, SetPlayerRank = { Params = "PlayerUUID, PlayerName, RankName", Return = "", Notes = "Updates the rank for the specified player. The player name is provided for reference, the UUID is used for identification. Logs a warning and does nothing if the rank is not found." }, SetRankVisuals = { Params = "RankName, MsgPrefix, MsgSuffix, MsgNameColorCode", Return = "", Notes = "Updates the rank's message visuals. Logs an info message and does nothing if rank not found." }, }, }, -- cRankManager cRoot = { Desc = [[ This class represents the root of Cuberite's object hierarchy. There is always only one cRoot object. It manages and allows querying all the other objects, such as {{cServer}}, {{cPluginManager}}, individual {{cWorld|worlds}} etc.</p> <p> To get the singleton instance of this object, you call the cRoot:Get() function. Then you can call the individual functions on this object. Note that some of the functions are static and don't need the instance, they are to be called directly on the cRoot class, such as cRoot:GetPhysicalRAMUsage() ]], Functions = { BroadcastChat = { { Params = "MessageText, MessageType", Return = "", Notes = "Broadcasts a message to all players, with its message type set to MessageType (default: mtCustom)." }, { Params = "{{cCompositeChat|CompositeChat}}", Return = "", Notes = "Broadcasts a {{cCompositeChat|composite chat message}} to all players." }, }, BroadcastChatDeath = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtDeath. Use for when a player has died." }, BroadcastChatFailure = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtFailure. Use for a command that failed to run because of insufficient permissions, etc." }, BroadcastChatFatal = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtFatal. Use for a plugin that crashed, or similar." }, BroadcastChatInfo = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtInfo. Use for informational messages, such as command usage." }, BroadcastChatJoin = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtJoin. Use for players joining the server." }, BroadcastChatLeave = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtLeave. Use for players leaving the server." }, BroadcastChatSuccess = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtSuccess. Use for success messages." }, BroadcastChatWarning = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtWarning. Use for concerning events, such as plugin reload etc." }, CreateAndInitializeWorld = { Params = "WorldName", Return = "{{cWorld|cWorld}}", Notes = "Creates a new world and initializes it. If there is a world whith the same name it returns nil.<br><br><b>NOTE:</b> This function is currently unsafe, do not use!" }, FindAndDoWithPlayer = { Params = "PlayerName, CallbackFunction", Return = "bool", Notes = "Calls the given callback function for the player with the name best matching the name string provided.<br>This function is case-insensitive and will match partial names.<br>Returns false if player not found or there is ambiguity, true otherwise. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre>" }, DoWithPlayerByUUID = { Params = "PlayerUUID, CallbackFunction", Return = "bool", Notes = "If there is the player with the uuid, calls the CallbackFunction with the {{cPlayer}} parameter representing the player. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre> The function returns false if the player was not found, or whatever bool value the callback returned if the player was found." }, ForEachPlayer = { Params = "CallbackFunction", Return = "", Notes = "Calls the given callback function for each player. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|cPlayer}})</pre>" }, ForEachWorld = { Params = "CallbackFunction", Return = "", Notes = "Calls the given callback function for each world. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cWorld|cWorld}})</pre>" }, Get = { Params = "", Return = "Root object", Notes = "(STATIC) This function returns the cRoot object." }, GetBrewingRecipe = { Params = "{{cItem|cItem}}, {{cItem|cItem}}", Return = "{{cItem|cItem}}", Notes = "(STATIC) Returns the result item, if a recipe has been found. If no recipe is found, returns no value." }, GetBuildCommitID = { Params = "", Return = "string", Notes = "(STATIC) For official builds (Travis CI / Jenkins) it returns the exact commit hash used for the build. For unofficial local builds, returns the approximate commit hash (since the true one cannot be determined), formatted as \"approx: &lt;CommitHash&gt;\"." }, GetBuildDateTime = { Params = "", Return = "string", Notes = "(STATIC) For official builds (Travic CI / Jenkins) it returns the date and time of the build. For unofficial local builds, returns the approximate datetime of the commit (since the true one cannot be determined), formatted as \"approx: &lt;DateTime-iso8601&gt;\"." }, GetBuildID = { Params = "", Return = "string", Notes = "(STATIC) For official builds (Travis CI / Jenkins) it returns the unique ID of the build, as recognized by the build system. For unofficial local builds, returns the string \"Unknown\"." }, GetBuildSeriesName = { Params = "", Return = "string", Notes = "(STATIC) For official builds (Travis CI / Jenkins) it returns the series name of the build (for example \"Cuberite Windows x64 Master\"). For unofficial local builds, returns the string \"local build\"." }, GetCraftingRecipes = { Params = "", Return = "{{cCraftingRecipe|cCraftingRecipe}}", Notes = "Returns the CraftingRecipes object" }, GetDefaultWorld = { Params = "", Return = "{{cWorld|cWorld}}", Notes = "Returns the world object from the default world." }, GetFurnaceFuelBurnTime = { Params = "{{cItem|Fuel}}", Return = "number", Notes = "(STATIC) Returns the number of ticks for how long the item would fuel a furnace. Returns zero if not a fuel." }, GetFurnaceRecipe = { Params = "{{cItem|InItem}}", Return = "{{cItem|OutItem}}, NumTicks, {{cItem|InItem}}", Notes = "(STATIC) Returns the furnace recipe for smelting the specified input. If a recipe is found, returns the smelted result, the number of ticks required for the smelting operation, and the input consumed (note that Cuberite supports smelting M items into N items and different smelting rates). If no recipe is found, returns no value." }, GetPhysicalRAMUsage = { Params = "", Return = "number", Notes = "Returns the amount of physical RAM that the entire Cuberite process is using, in KiB. Negative if the OS doesn't support this query." }, GetPluginManager = { Params = "", Return = "{{cPluginManager|cPluginManager}}", Notes = "Returns the cPluginManager object." }, GetPrimaryServerVersion = { Params = "", Return = "number", Notes = "Returns the servers primary server version." }, GetProtocolVersionTextFromInt = { Params = "Protocol Version", Return = "string", Notes = "Returns the Minecraft version from the given Protocol. If there is no version found, it returns 'Unknown protocol(Parameter)'" }, GetServer = { Params = "", Return = "{{cServer|cServer}}", Notes = "Returns the cServer object." }, GetServerUpTime = { Params = "", Return = "number", Notes = "Returns the uptime of the server in seconds." }, GetTotalChunkCount = { Params = "", Return = "number", Notes = "Returns the amount of loaded chunks." }, GetVirtualRAMUsage = { Params = "", Return = "number", Notes = "Returns the amount of virtual RAM that the entire Cuberite process is using, in KiB. Negative if the OS doesn't support this query." }, GetWebAdmin = { Params = "", Return = "{{cWebAdmin|cWebAdmin}}", Notes = "Returns the cWebAdmin object." }, GetWorld = { Params = "WorldName", Return = "{{cWorld|cWorld}}", Notes = "Returns the cWorld object of the given world. It returns nil if there is no world with the given name." }, QueueExecuteConsoleCommand = { Params = "Message", Return = "", Notes = "Queues a console command for execution through the cServer class. The command will be executed in the tick thread. The command's output will be sent to console." }, SaveAllChunks = { Params = "", Return = "", Notes = "Saves all the chunks in all the worlds. Note that the saving is queued on each world's tick thread and this functions returns before the chunks are actually saved." }, SetPrimaryServerVersion = { Params = "Protocol Version", Return = "", Notes = "Sets the servers PrimaryServerVersion to the given protocol number." } }, AdditionalInfo = { { Header = "Querying a furnace recipe", Contents = [[ To find the furnace recipe for an item, use the following code (adapted from the Debuggers plugin's /fr command): <pre class="prettyprint lang-lua"> local HeldItem = a_Player:GetEquippedItem(); local Out, NumTicks, In = cRoot:GetFurnaceRecipe(HeldItem); -- Note STATIC call - no need for a Get() if (Out ~= nil) then -- There is a recipe, list it: a_Player:SendMessage( "Furnace turns " .. ItemToFullString(In) .. " to " .. ItemToFullString(Out) .. " in " .. NumTicks .. " ticks (" .. tostring(NumTicks / 20) .. " seconds)." ); else -- No recipe found a_Player:SendMessage("There is no furnace recipe that would smelt " .. ItemToString(HeldItem)); end </pre> ]], }, }, }, -- cRoot cScoreboard = { Desc = [[ This class manages the objectives and teams of a single world. ]], Functions = { AddPlayerScore = { Params = "Name, Type, Value", Return = "", Notes = "Adds a value to all player scores of the specified objective type." }, ForEachObjective = { Params = "CallBackFunction", Return = "bool", Notes = "Calls the specified callback for each objective in the scoreboard. Returns true if all objectives have been processed (including when there are zero objectives), or false if the callback function has aborted the enumeration by returning true. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cObjective|Objective}})</pre> The callback should return false or no value to continue with the next objective, or true to abort the enumeration." }, ForEachTeam = { Params = "CallBackFunction", Return = "bool", Notes = "Calls the specified callback for each team in the scoreboard. Returns true if all teams have been processed (including when there are zero teams), or false if the callback function has aborted the enumeration by returning true. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cObjective|Objective}})</pre> The callback should return false or no value to continue with the next team, or true to abort the enumeration." }, GetNumObjectives = { Params = "", Return = "number", Notes = "Returns the nuber of registered objectives." }, GetNumTeams = { Params = "", Return = "number", Notes = "Returns the number of registered teams." }, GetObjective = { Params = "string", Return = "{{cObjective}}", Notes = "Returns the objective with the specified name." }, GetObjectiveIn = { Params = "DisplaySlot", Return = "{{cObjective}}", Notes = "Returns the objective in the specified display slot. Can be nil." }, GetTeam = { Params = "string", Return = "{{cTeam}}", Notes = "Returns the team with the specified name." }, RegisterObjective = { Params = "Name, DisplayName, Type", Return = "{{cObjective}}", Notes = "Registers a new scoreboard objective. Returns the {{cObjective}} instance, nil on error." }, RegisterTeam = { Params = "Name, DisplayName, Prefix, Suffix", Return = "{{cTeam}}", Notes = "Registers a new team. Returns the {{cTeam}} instance, nil on error." }, RemoveObjective = { Params = "string", Return = "bool", Notes = "Removes the objective with the specified name. Returns true if operation was successful." }, RemoveTeam = { Params = "string", Return = "bool", Notes = "Removes the team with the specified name. Returns true if operation was successful." }, SetDisplay = { Params = "Name, DisplaySlot", Return = "", Notes = "Updates the currently displayed objective." }, }, Constants = { dsCount = { Notes = "" }, dsList = { Notes = "" }, dsName = { Notes = "" }, dsSidebar = { Notes = "" }, }, }, -- cScoreboard cServer = { Desc = [[ This class manages all the client connections internally. In the API layer, it allows to get and set the general properties of the server, such as the description and max players.</p> <p> It used to support broadcasting chat messages to all players, this functionality has been moved to {{cRoot}}:BroadcastChat(). ]], Functions = { GetDescription = { Return = "string", Notes = "Returns the server description set in the settings.ini." }, GetMaxPlayers = { Return = "number", Notes = "Returns the max amount of players who can join the server." }, GetNumPlayers = { Return = "number", Notes = "Returns the amount of players online." }, GetServerID = { Return = "string", Notes = "Returns the ID of the server?" }, IsHardcore = { Params = "", Return = "bool", Notes = "Returns true if the server is hardcore (players get banned on death)." }, SetMaxPlayers = { Params = "number", Notes = "Sets the max amount of players who can join." }, ShouldAuthenticate = { Params = "", Return = "bool", Notes = "Returns true iff the server is set to authenticate players (\"online mode\")." }, }, }, -- cServer cStringCompression = { Desc = [[ Provides functions to compress or decompress string <p> All functions in this class are static, so they should be called in the dot convention: <pre class="prettyprint lang-lua"> local CompressedString = cStringCompression.CompressStringGZIP("DataToCompress") </pre> ]], Functions = { CompressStringGZIP = {Params = "string", Return = "string", Notes = "Compress a string using GZIP"}, CompressStringZLIB = {Params = "string, factor", Return = "string", Notes = "Compresses a string using ZLIB. Factor 0 is no compression and factor 9 is maximum compression"}, InflateString = {Params = "string", Return = "string", Notes = "Uncompresses a string using Inflate"}, UncompressStringGZIP = {Params = "string", Return = "string", Notes = "Uncompress a string using GZIP"}, UncompressStringZLIB = {Params = "string, uncompressed length", Return = "string", Notes = "Uncompresses a string using ZLIB"}, }, }, cTeam = { Desc = [[ This class manages a single player team. ]], Functions = { AddPlayer = { Params = "string", Returns = "bool", Notes = "Adds a player to this team. Returns true if the operation was successful." }, AllowsFriendlyFire = { Params = "", Return = "bool", Notes = "Returns whether team friendly fire is allowed." }, CanSeeFriendlyInvisible = { Params = "", Return = "bool", Notes = "Returns whether players can see invisible teammates." }, HasPlayer = { Params = "string", Returns = "bool", Notes = "Returns whether the specified player is a member of this team." }, GetDisplayName = { Params = "", Return = "string", Notes = "Returns the display name of the team." }, GetName = { Params = "", Return = "string", Notes = "Returns the internal name of the team." }, GetNumPlayers = { Params = "", Return = "number", Notes = "Returns the number of registered players." }, GetPrefix = { Params = "", Return = "string", Notes = "Returns the prefix prepended to the names of the members of this team." }, RemovePlayer = { Params = "string", Returns = "bool", Notes = "Removes the player with the specified name from this team. Returns true if the operation was successful." }, Reset = { Params = "", Returns = "", Notes = "Removes all players from this team." }, GetSuffix = { Params = "", Return = "string", Notes = "Returns the suffix appended to the names of the members of this team." }, SetCanSeeFriendlyInvisible = { Params = "bool", Return = "", Notes = "Set whether players can see invisible teammates." }, SetDisplayName = { Params = "string", Return = "", Notes = "Sets the display name of this team. (i.e. what will be shown to the players)" }, SetFriendlyFire = { Params = "bool", Return = "", Notes = "Sets whether team friendly fire is allowed." }, SetPrefix = { Params = "string", Return = "", Notes = "Sets the prefix prepended to the names of the members of this team." }, SetSuffix = { Params = "string", Return = "", Notes = "Sets the suffix appended to the names of the members of this team." }, }, }, -- cTeam cTNTEntity = { Desc = "This class manages a TNT entity.", Functions = { Explode = { Return = "", Notes = "Explode the tnt." }, GetFuseTicks = { Return = "number", Notes = "Returns the fuse ticks until the tnt will explode." }, SetFuseTicks = { Return = "number", Notes = "Set the fuse ticks until the tnt will explode." }, }, Inherits = "cEntity", }, cWebPlugin = { Desc = "", Functions = {}, }, -- cWebPlugin cWindow = { Desc = [[ This class is the common ancestor for all window classes used by Cuberite. It is inherited by the {{cLuaWindow|cLuaWindow}} class that plugins use for opening custom windows. It is planned to be used for window-related hooks in the future. It implements the basic functionality of any window.</p> <p> Note that one cWindow object can be used for multiple players at the same time, and therefore the slot contents are player-specific (e. g. crafting grid, or player inventory). Thus the GetSlot() and SetSlot() functions need to have the {{cPlayer|cPlayer}} parameter that specifies the player for whom the contents are to be queried.</p> <p> Windows also have numeric properties, these are used to set the progressbars for furnaces or the XP costs for enchantment tables. ]], Functions = { GetSlot = { Params = "{{cPlayer|Player}}, SlotNumber", Return = "{{cItem}}", Notes = "Returns the item at the specified slot for the specified player. Returns nil and logs to server console on error." }, GetWindowID = { Params = "", Return = "number", Notes = "Returns the ID of the window, as used by the network protocol" }, GetWindowTitle = { Params = "", Return = "string", Notes = "Returns the window title that will be displayed to the player" }, GetWindowType = { Params = "", Return = "number", Notes = "Returns the type of the window, one of the constants in the table above" }, IsSlotInPlayerHotbar = { Params = "SlotNum", Return = "bool", Notes = "Returns true if the specified slot number is in the player hotbar" }, IsSlotInPlayerInventory = { Params = "SlotNum", Return = "bool", Notes = "Returns true if the specified slot number is in the player's main inventory or in the hotbar. Note that this returns false for armor slots!" }, IsSlotInPlayerMainInventory = { Params = "SlotNum", Return = "bool", Notes = "Returns true if the specified slot number is in the player's main inventory" }, SetProperty = { Params = "PropertyID, PropartyValue, {{cPlayer|Player}}", Return = "", Notes = "Sends the UpdateWindowProperty (0x69) packet to the specified player; or to all players who are viewing this window if Player is not specified or nil." }, SetSlot = { Params = "{{cPlayer|Player}}, SlotNum, {{cItem|cItem}}", Return = "", Notes = "Sets the contents of the specified slot for the specified player. Ignored if the slot number is invalid" }, SetWindowTitle = { Params = "string", Return = "", Notes = "Sets the window title that will be displayed to the player" }, }, Constants = { wtInventory = { Notes = "An inventory window" }, wtChest = { Notes = "A {{cChestEntity|chest}} or doublechest window" }, wtWorkbench = { Notes = "A workbench (crafting table) window" }, wtFurnace = { Notes = "A {{cFurnaceEntity|furnace}} window" }, wtDropSpenser = { Notes = "A {{cDropperEntity|dropper}} or a {{cDispenserEntity|dispenser}} window" }, wtEnchantment = { Notes = "An enchantment table window" }, wtBrewery = { Notes = "A brewing stand window" }, wtNPCTrade = { Notes = "A villager trade window" }, wtBeacon = { Notes = "A beacon window" }, wtAnvil = { Notes = "An anvil window" }, wtHopper = { Notes = "A {{cHopperEntity|hopper}} window" }, wtAnimalChest = { Notes = "A horse or donkey window" }, }, }, -- cWindow cWorld = { Desc = [[ cWorld is the game world. It is the hub of all the information managed by individual classes, providing convenient access to them. Cuberite supports multiple worlds in any combination of world types. You can have two overworlds, three nethers etc. To enumerate all world the server provides, use the {{cRoot}}:ForEachWorld() function.</p> <p> The world data is held in individual chunks. Each chunk consists of 16 (x) * 16 (z) * 256 (y) blocks, each block is specified by its block type (8-bit) and block metadata (4-bit). Additionally, each block has two light values calculated - skylight (how much daylight it receives) and blocklight (how much light from light-emissive blocks it receives), both 4-bit.</p> <p> Each world runs several separate threads used for various housekeeping purposes, the most important of those is the Tick thread. This thread updates the game logic 20 times per second, and it is the thread where all the gameplay actions are evaluated. Liquid physics, entity interactions, player ovement etc., all are applied in this thread.</p> <p> Additional threads include the generation thread (generates new chunks as needed, storage thread (saves and loads chunk from the disk), lighting thread (updates block light values) and the chunksender thread (compresses chunks to send to the clients).</p> <p> The world provides access to all its {{cPlayer|players}}, {{cEntity|entities}} and {{cBlockEntity|block entities}}. Because of multithreading issues, individual objects cannot be retrieved for indefinite handling, but rather must be modified in callbacks, within which they are guaranteed to stay valid.</p> <p> Physics for individual blocks are handled by the simulators. These will fire in each tick for all blocks that have been scheduled for simulator update ("simulator wakeup"). The simulators include liquid physics, falling blocks, fire spreading and extinguishing and redstone.</p> <p> Game time is also handled by the world. It provides the time-of-day and the total world age. ]], Functions = { AreCommandBlocksEnabled = { Params = "", Return = "bool", Notes = "Returns whether command blocks are enabled on the (entire) server" }, BroadcastBlockAction = { Params = "BlockX, BlockY, BlockZ, ActionByte1, ActionByte2, BlockType, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Broadcasts the BlockAction packet to all clients who have the appropriate chunk loaded (except ExcludeClient). The contents of the packet are specified by the parameters for the call, the blocktype needn't match the actual block that is present in the world data at the specified location." }, BroadcastChat = { Params = "Message, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Sends the Message to all players in this world, except the optional ExcludeClient. No formatting is done by the server." }, BroadcastChatDeath = { Params = "Message, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Prepends Gray [DEATH] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For when a player dies." }, BroadcastChatFailure = { Params = "Message, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Prepends Rose [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For a command that failed to run because of insufficient permissions, etc." }, BroadcastChatFatal = { Params = "Message, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Prepends Red [FATAL] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For a plugin that crashed, or similar." }, BroadcastChatInfo = { Params = "Message, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Prepends Yellow [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For informational messages, such as command usage." }, BroadcastChatSuccess = { Params = "Message, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Prepends Green [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For success messages." }, BroadcastChatWarning = { Params = "Message, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Prepends Rose [WARN] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For concerning events, such as plugin reload etc." }, BroadcastEntityAnimation = { Params = "{{cEntity|TargetEntity}}, Animation, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Sends an animation of an entity to all clienthandles (except ExcludeClient if given)" }, BroadcastParticleEffect = { Params = "ParticleName, X, Y, Z, OffSetX, OffSetY, OffSetZ, ParticleData, ParticleAmmount, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Spawns the specified particles to all players in the world exept the optional ExeptClient. A list of available particles by thinkofdeath can be found {{https://gist.github.com/thinkofdeath/5110835|Here}}" }, BroadcastSoundEffect = { Params = "SoundName, X, Y, Z, Volume, Pitch, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Sends the specified sound effect to all players in this world, except the optional ExceptClient" }, BroadcastSoundParticleEffect = { Params = "EffectID, X, Y, Z, EffectData, [{{cClientHandle|ExcludeClient}}]", Return = "", Notes = "Sends the specified effect to all players in this world, except the optional ExceptClient" }, CastThunderbolt = { Params = "X, Y, Z", Return = "", Notes = "Creates a thunderbolt at the specified coords" }, ChangeWeather = { Params = "", Return = "", Notes = "Forces the weather to change in the next game tick. Weather is changed according to the normal rules: wSunny <-> wRain <-> wStorm" }, ChunkStay = { Params = "ChunkCoordTable, OnChunkAvailable, OnAllChunksAvailable", Return = "", Notes = "Queues the specified chunks to be loaded or generated and calls the specified callbacks once they are loaded. ChunkCoordTable is an arra-table of chunk coords, each coord being a table of 2 numbers: { {Chunk1x, Chunk1z}, {Chunk2x, Chunk2z}, ...}. When any of those chunks are made available (including being available at the start of this call), the OnChunkAvailable() callback is called. When all the chunks are available, the OnAllChunksAvailable() callback is called. The function signatures are: <pre class=\"prettyprint lang-lua\">function OnChunkAvailable(ChunkX, ChunkZ)\nfunction OnAllChunksAvailable()</pre> All return values from the callbacks are ignored." }, CreateProjectile = { Params = "X, Y, Z, {{cProjectileEntity|ProjectileKind}}, {{cEntity|Creator}}, {{cItem|Originating Item}}, [{{Vector3d|Speed}}]", Return = "", Notes = "Creates a new projectile of the specified kind at the specified coords. The projectile's creator is set to Creator (may be nil). The item that created the projectile entity, commonly the {{cPlayer|player}}'s currently equipped item, is used at present for fireworks to correctly set their entity metadata. It is not used for any other projectile. Optional speed indicates the initial speed for the projectile." }, DigBlock = { Params = "X, Y, Z", Return = "", Notes = "Replaces the specified block with air, without dropping the usual pickups for the block. Wakes up the simulators for the block and its neighbors." }, DoExplosionAt = { Params = "Force, X, Y, Z, CanCauseFire, Source, SourceData", Return = "", Notes = "Creates an explosion of the specified relative force in the specified position. If CanCauseFire is set, the explosion will set blocks on fire, too. The Source parameter specifies the source of the explosion, one of the esXXX constants. The SourceData parameter is specific to each source type, usually it provides more info about the source." }, DoWithBlockEntityAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a block entity at the specified coords, calls the CallbackFunction with the {{cBlockEntity}} parameter representing the block entity. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cBlockEntity|BlockEntity}})</pre> The function returns false if there is no block entity, or if there is, it returns the bool value that the callback has returned. Use {{tolua}}.cast() to cast the Callback's BlockEntity parameter to the correct {{cBlockEntity}} descendant." }, DoWithBrewingstandAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a brewingstand at the specified coords, calls the CallbackFunction with the {{cBrewingstandEntity}} parameter representing the brewingstand. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cBrewingstandEntity|cBrewingstandEntity}})</pre> The function returns false if there is no brewingstand, or if there is, it returns the bool value that the callback has returned." }, DoWithBeaconAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a beacon at the specified coords, calls the CallbackFunction with the {{cBeaconEntity}} parameter representing the beacon. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cBeaconEntity|BeaconEntity}})</pre> The function returns false if there is no beacon, or if there is, it returns the bool value that the callback has returned." }, DoWithChestAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a chest at the specified coords, calls the CallbackFunction with the {{cChestEntity}} parameter representing the chest. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cChestEntity|ChestEntity}})</pre> The function returns false if there is no chest, or if there is, it returns the bool value that the callback has returned." }, DoWithCommandBlockAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a command block at the specified coords, calls the CallbackFunction with the {{cCommandBlockEntity}} parameter representing the command block. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cCommandBlockEntity|CommandBlockEntity}})</pre> The function returns false if there is no command block, or if there is, it returns the bool value that the callback has returned." }, DoWithDispenserAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a dispenser at the specified coords, calls the CallbackFunction with the {{cDispenserEntity}} parameter representing the dispenser. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cDispenserEntity|DispenserEntity}})</pre> The function returns false if there is no dispenser, or if there is, it returns the bool value that the callback has returned." }, DoWithDropSpenserAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a dropper or a dispenser at the specified coords, calls the CallbackFunction with the {{cDropSpenserEntity}} parameter representing the dropper or dispenser. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cDropSpenserEntity|DropSpenserEntity}})</pre> Note that this can be used to access both dispensers and droppers in a similar way. The function returns false if there is neither dispenser nor dropper, or if there is, it returns the bool value that the callback has returned." }, DoWithDropperAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a dropper at the specified coords, calls the CallbackFunction with the {{cDropperEntity}} parameter representing the dropper. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cDropperEntity|DropperEntity}})</pre> The function returns false if there is no dropper, or if there is, it returns the bool value that the callback has returned." }, DoWithEntityByID = { Params = "EntityID, CallbackFunction", Return = "bool", Notes = "If an entity with the specified ID exists, calls the callback with the {{cEntity}} parameter representing the entity. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cEntity|Entity}})</pre> The function returns false if the entity was not found, and it returns the same bool value that the callback has returned if the entity was found." }, DoWithFlowerPotAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a flower pot at the specified coords, calls the CallbackFunction with the {{cFlowerPotEntity}} parameter representing the flower pot. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cFlowerPotEntity|FlowerPotEntity}})</pre> The function returns false if there is no flower pot, or if there is, it returns the bool value that the callback has returned." }, DoWithFurnaceAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a furnace at the specified coords, calls the CallbackFunction with the {{cFurnaceEntity}} parameter representing the furnace. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cFurnaceEntity|FurnaceEntity}})</pre> The function returns false if there is no furnace, or if there is, it returns the bool value that the callback has returned." }, DoWithMobHeadAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a mob head at the specified coords, calls the CallbackFunction with the {{cMobHeadEntity}} parameter representing the furnace. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cMobHeadEntity|MobHeadEntity}})</pre> The function returns false if there is no mob head, or if there is, it returns the bool value that the callback has returned." }, DoWithNoteBlockAt = { Params = "BlockX, BlockY, BlockZ, CallbackFunction", Return = "bool", Notes = "If there is a note block at the specified coords, calls the CallbackFunction with the {{cNoteEntity}} parameter representing the note block. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cNoteEntity|NoteEntity}})</pre> The function returns false if there is no note block, or if there is, it returns the bool value that the callback has returned." }, DoWithPlayer = { Params = "PlayerName, CallbackFunction", Return = "bool", Notes = "If there is a player of the specified name (exact match), calls the CallbackFunction with the {{cPlayer}} parameter representing the player. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre> The function returns false if the player was not found, or whatever bool value the callback returned if the player was found." }, DoWithPlayerByUUID = { Params = "PlayerUUID, CallbackFunction", Return = "bool", Notes = "If there is the player with the uuid, calls the CallbackFunction with the {{cPlayer}} parameter representing the player. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre> The function returns false if the player was not found, or whatever bool value the callback returned if the player was found." }, FastSetBlock = { { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta", Return = "", Notes = "Sets the block at the specified coords, without waking up the simulators or replacing the block entities for the previous block type. Do not use if the block being replaced has a block entity tied to it!" }, { Params = "{{Vector3i|BlockCoords}}, BlockType, BlockMeta", Return = "", Notes = "Sets the block at the specified coords, without waking up the simulators or replacing the block entities for the previous block type. Do not use if the block being replaced has a block entity tied to it!" }, }, FindAndDoWithPlayer = { Params = "PlayerName, CallbackFunction", Return = "bool", Notes = "Calls the given callback function for the player with the name best matching the name string provided.<br>This function is case-insensitive and will match partial names.<br>Returns false if player not found or there is ambiguity, true otherwise. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre>" }, ForEachBlockEntityInChunk = { Params = "ChunkX, ChunkZ, CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each block entity in the chunk. Returns true if all block entities in the chunk have been processed (including when there are zero block entities), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cBlockEntity|BlockEntity}})</pre> The callback should return false or no value to continue with the next block entity, or true to abort the enumeration. Use {{tolua}}.cast() to cast the Callback's BlockEntity parameter to the correct {{cBlockEntity}} descendant." }, ForEachBrewingstandInChunk = { Params = "ChunkX, ChunkZ, CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each brewingstand in the chunk. Returns true if all brewingstands in the chunk have been processed (including when there are zero brewingstands), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cBrewingstandEntity|cBrewingstandEntity}})</pre> The callback should return false or no value to continue with the next brewingstand, or true to abort the enumeration." }, ForEachChestInChunk = { Params = "ChunkX, ChunkZ, CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each chest in the chunk. Returns true if all chests in the chunk have been processed (including when there are zero chests), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cChestEntity|ChestEntity}})</pre> The callback should return false or no value to continue with the next chest, or true to abort the enumeration." }, ForEachEntity = { Params = "CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each entity in the loaded world. Returns true if all the entities have been processed (including when there are zero entities), or false if the callback function has aborted the enumeration by returning true. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cEntity|Entity}})</pre> The callback should return false or no value to continue with the next entity, or true to abort the enumeration." }, ForEachEntityInBox = { Params = "{{cBoundingBox|Box}}, CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each entity in the specified bounding box. Returns true if all the entities have been processed (including when there are zero entities), or false if the callback function has aborted the enumeration by returning true. If any chunk within the bounding box is not valid, it is silently skipped without any notification. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cEntity|Entity}})</pre> The callback should return false or no value to continue with the next entity, or true to abort the enumeration." }, ForEachEntityInChunk = { Params = "ChunkX, ChunkZ, CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each entity in the specified chunk. Returns true if all the entities have been processed (including when there are zero entities), or false if the chunk is not loaded or the callback function has aborted the enumeration by returning true. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cEntity|Entity}})</pre> The callback should return false or no value to continue with the next entity, or true to abort the enumeration." }, ForEachFurnaceInChunk = { Params = "ChunkX, ChunkZ, CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each furnace in the chunk. Returns true if all furnaces in the chunk have been processed (including when there are zero furnaces), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cFurnaceEntity|FurnaceEntity}})</pre> The callback should return false or no value to continue with the next furnace, or true to abort the enumeration." }, ForEachPlayer = { Params = "CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each player in the loaded world. Returns true if all the players have been processed (including when there are zero players), or false if the callback function has aborted the enumeration by returning true. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre> The callback should return false or no value to continue with the next player, or true to abort the enumeration." }, GenerateChunk = { Params = "ChunkX, ChunkZ", Return = "", Notes = "Queues the specified chunk in the chunk generator. Ignored if the chunk is already generated (use RegenerateChunk() to force chunk re-generation)." }, GetBiomeAt = { Params = "BlockX, BlockZ", Return = "eBiome", Notes = "Returns the biome at the specified coords. Reads the biome from the chunk, if it is loaded, otherwise it uses the chunk generator to provide the biome value." }, GetBlock = { { Params = "BlockX, BlockY, BlockZ", Return = "BLOCKTYPE", Notes = "Returns the block type of the block at the specified coords, or 0 if the appropriate chunk is not loaded." }, { Params = "{{Vector3i|BlockCoords}}", Return = "BLOCKTYPE", Notes = "Returns the block type of the block at the specified coords, or 0 if the appropriate chunk is not loaded." }, }, GetBlockBlockLight = { Params = "BlockX, BlockY, BlockZ", Return = "number", Notes = "Returns the amount of block light at the specified coords, or 0 if the appropriate chunk is not loaded." }, GetBlockInfo = { Params = "BlockX, BlockY, BlockZ", Return = "BlockValid, BlockType, BlockMeta, BlockSkyLight, BlockBlockLight", Notes = "Returns the complete block info for the block at the specified coords. The first value specifies if the block is in a valid loaded chunk, the other values are valid only if BlockValid is true." }, GetBlockMeta = { { Params = "BlockX, BlockY, BlockZ", Return = "number", Notes = "Returns the block metadata of the block at the specified coords, or 0 if the appropriate chunk is not loaded." }, { Params = "{{Vector3i|BlockCoords}}", Return = "number", Notes = "Returns the block metadata of the block at the specified coords, or 0 if the appropriate chunk is not loaded." }, }, GetBlockSkyLight = { Params = "BlockX, BlockY, BlockZ", Return = "number", Notes = "Returns the block skylight of the block at the specified coords, or 0 if the appropriate chunk is not loaded." }, GetBlockTypeMeta = { Params = "BlockX, BlockY, BlockZ", Return = "BlockValid, BlockType, BlockMeta", Notes = "Returns the block type and metadata for the block at the specified coords. The first value specifies if the block is in a valid loaded chunk, the other values are valid only if BlockValid is true." }, GetDefaultWeatherInterval = { Params = "eWeather", Return = "", Notes = "Returns the default weather interval for the specific weather type. Returns -1 for any unknown weather." }, GetDimension = { Params = "", Return = "eDimension", Notes = "Returns the dimension of the world - dimOverworld, dimNether or dimEnd." }, GetGameMode = { Params = "", Return = "eGameMode", Notes = "Returns the gamemode of the world - gmSurvival, gmCreative or gmAdventure." }, GetGeneratorQueueLength = { Params = "", Return = "number", Notes = "Returns the number of chunks that are queued in the chunk generator." }, GetHeight = { Params = "BlockX, BlockZ", Return = "number", Notes = "Returns the maximum height of the particula block column in the world. If the chunk is not loaded, it waits for it to load / generate. <b>WARNING</b>: Do not use, Use TryGetHeight() instead for a non-waiting version, otherwise you run the risk of a deadlock!" }, GetIniFileName = { Params = "", Return = "string", Notes = "Returns the name of the world.ini file that the world uses to store the information." }, GetLightingQueueLength = { Params = "", Return = "number", Notes = "Returns the number of chunks in the lighting thread's queue." }, GetLinkedEndWorldName = { Params = "", Return = "string", Notes = "Returns the name of the end world this world is linked to." }, GetLinkedNetherWorldName = { Params = "", Return = "string", Notes = "Returns the name of the Netherworld linked to this world." }, GetLinkedOverworldName = { Params = "", Return = "string", Notes = "Returns the name of the world this world is linked to." }, GetMapManager = { Params = "", Return = "{{cMapManager}}", Notes = "Returns the {{cMapManager|MapManager}} object used by this world." }, GetMaxCactusHeight = { Params = "", Return = "number", Notes = "Returns the configured maximum height to which cacti will grow naturally." }, GetMaxNetherPortalHeight = { Params = "", Return = "number", Notes = "Returns the maximum height for a nether portal" }, GetMaxNetherPortalWidth = { Params = "", Return = "number", Notes = "Returns the maximum width for a nether portal" }, GetMaxSugarcaneHeight = { Params = "", Return = "number", Notes = "Returns the configured maximum height to which sugarcane will grow naturally." }, GetMaxViewDistance = { Params = "", Return = "number", Notes = "Returns the maximum viewdistance that players can see in this world. The view distance is the amount of chunks around the player that the player can see." }, GetMinNetherPortalHeight = { Params = "", Return = "number", Notes = "Returns the minimum height for a nether portal" }, GetMinNetherPortalWidth = { Params = "", Return = "number", Notes = "Returns the minimum width for a nether portal" }, GetName = { Params = "", Return = "string", Notes = "Returns the name of the world, as specified in the settings.ini file." }, GetNumChunks = { Params = "", Return = "number", Notes = "Returns the number of chunks currently loaded." }, GetScoreBoard = { Params = "", Return = "{{cScoreBoard}}", Notes = "Returns the {{cScoreBoard|ScoreBoard}} object used by this world. " }, GetSignLines = { Params = "BlockX, BlockY, BlockZ", Return = "IsValid, [Line1, Line2, Line3, Line4]", Notes = "Returns true and the lines of a sign at the specified coords, or false if there is no sign at the coords." }, GetSpawnX = { Params = "", Return = "number", Notes = "Returns the X coord of the default spawn" }, GetSpawnY = { Params = "", Return = "number", Notes = "Returns the Y coord of the default spawn" }, GetSpawnZ = { Params = "", Return = "number", Notes = "Returns the Z coord of the default spawn" }, GetStorageLoadQueueLength = { Params = "", Return = "number", Notes = "Returns the number of chunks queued up for loading" }, GetStorageSaveQueueLength = { Params = "", Return = "number", Notes = "Returns the number of chunks queued up for saving" }, GetTicksUntilWeatherChange = { Params = "", Return = "number", Notes = "Returns the number of ticks that will pass before the weather is changed" }, GetTimeOfDay = { Params = "", Return = "number", Notes = "Returns the number of ticks that have passed from the sunrise, 0 .. 24000." }, GetTNTShrapnelLevel = { Params = "", Return = "{{Globals#ShrapnelLevel|ShrapnelLevel}}", Notes = "Returns the shrapnel level, representing the block types that are propelled outwards following an explosion. Based on this value and a random picker, blocks are selectively converted to physics entities (FallingSand) and flung outwards." }, GetWeather = { Params = "", Return = "eWeather", Notes = "Returns the current weather in the world (wSunny, wRain, wStorm). To check for weather, use IsWeatherXXX() functions instead." }, GetWorldAge = { Params = "", Return = "number", Notes = "Returns the total age of the world, in ticks. The age always grows, cannot be set by plugins and is unrelated to TimeOfDay." }, GrowCactus = { Params = "BlockX, BlockY, BlockZ, NumBlocksToGrow", Return = "", Notes = "Grows a cactus block at the specified coords, by up to the specified number of blocks. Adheres to the world's maximum cactus growth (GetMaxCactusHeight())." }, GrowMelonPumpkin = { Params = "BlockX, BlockY, BlockZ, StemType", Return = "", Notes = "Grows a melon or pumpkin, based on the stem type specified (assumed to be in the coords provided). Checks for normal melon / pumpkin growth conditions - stem not having another produce next to it and suitable ground below." }, GrowRipePlant = { Params = "BlockX, BlockY, BlockZ, IsByBonemeal", Return = "bool", Notes = "Grows the plant at the specified coords. If IsByBonemeal is true, checks first if the specified plant type is bonemealable in the settings. Returns true if the plant was grown, false if not." }, GrowSugarcane = { Params = "BlockX, BlockY, BlockZ, NumBlocksToGrow", Return = "", Notes = "Grows a sugarcane block at the specified coords, by up to the specified number of blocks. Adheres to the world's maximum sugarcane growth (GetMaxSugarcaneHeight())." }, GrowTree = { Params = "BlockX, BlockY, BlockZ", Return = "", Notes = "Grows a tree based at the specified coords. If there is a sapling there, grows the tree based on that sapling, otherwise chooses a tree image based on the biome." }, GrowTreeByBiome = { Params = "BlockX, BlockY, BlockZ", Return = "", Notes = "Grows a tree based at the specified coords. The tree type is picked from types available for the biome at those coords." }, GrowTreeFromSapling = { Params = "BlockX, BlockY, BlockZ, SaplingMeta", Return = "", Notes = "Grows a tree based at the specified coords. The tree type is determined from the sapling meta (the sapling itself needn't be present)." }, IsBlockDirectlyWatered = { Params = "BlockX, BlockY, BlockZ", Return = "bool", Notes = "Returns true if the specified block has a water block right next to it (on the X/Z axes)" }, IsDaylightCycleEnabled = { Params = "", Return = "bool", Notes = "Returns true if the daylight cycle is enabled." }, IsDeepSnowEnabled = { Params = "", Return = "bool", Notes = "Returns whether the configuration has DeepSnow enabled." }, IsGameModeAdventure = { Params = "", Return = "bool", Notes = "Returns true if the current gamemode is gmAdventure." }, IsGameModeCreative = { Params = "", Return = "bool", Notes = "Returns true if the current gamemode is gmCreative." }, IsGameModeSpectator = { Params = "", Return = "bool", Notes = "Returns true if the current gamemode is gmSpectator." }, IsGameModeSurvival = { Params = "", Return = "bool", Notes = "Returns true if the current gamemode is gmSurvival." }, IsPVPEnabled = { Params = "", Return = "bool", Notes = "Returns whether PVP is enabled in the world settings." }, IsTrapdoorOpen = { Params = "BlockX, BlockY, BlockZ", Return = "bool", Notes = "Returns false if there is no trapdoor there or if the block isn't a trapdoor or if the chunk wasn't loaded. Returns true if trapdoor is open." }, IsWeatherRain = { Params = "", Return = "bool", Notes = "Returns true if the current world is raining." }, IsWeatherRainAt = { Params = "BlockX, BlockZ", Return = "bool", Notes = "Returns true if the specified location is raining (takes into account biomes)." }, IsWeatherStorm = { Params = "", Return = "bool", Notes = "Returns true if the current world is stormy." }, IsWeatherStormAt = { Params = "BlockX, BlockZ", Return = "bool", Notes = "Returns true if the specified location is stormy (takes into account biomes)." }, IsWeatherSunny = { Params = "", Return = "bool", Notes = "Returns true if the current weather is sunny." }, IsWeatherSunnyAt = { Params = "BlockX, BlockZ", Return = "bool", Notes = "Returns true if the current weather is sunny at the specified location (takes into account biomes)." }, IsWeatherWet = { Params = "", Return = "bool", Notes = "Returns true if the current world has any precipitation (rain or storm)." }, IsWeatherWetAt = { Params = "BlockX, BlockZ", Return = "bool", Notes = "Returns true if the specified location has any precipitation (rain or storm) (takes into account biomes)." }, PrepareChunk = { Params = "ChunkX, ChunkZ, [Callback]", Return = "", Notes = "Queues the chunk for preparing - making sure that it's generated and lit. It is legal to call with no callback. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback(ChunkX, ChunkZ)</pre>" }, QueueBlockForTick = { Params = "BlockX, BlockY, BlockZ, TicksToWait", Return = "", Notes = "Queues the specified block to be ticked after the specified number of gameticks." }, QueueSaveAllChunks = { Params = "", Return = "", Notes = "Queues all chunks to be saved in the world storage thread" }, QueueSetBlock = { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta, TickDelay", Return = "", Notes = "Queues the block to be set to the specified blocktype and meta after the specified amount of game ticks. Uses SetBlock() for the actual setting, so simulators are woken up and block entities are handled correctly." }, QueueTask = { Params = "TaskFunction", Return = "", Notes = "Queues the specified function to be executed in the tick thread. This is the primary means of interaction with a cWorld from the WebAdmin page handlers (see {{WebWorldThreads}}). The function signature is <pre class=\"pretty-print lang-lua\">function()</pre>All return values from the function are ignored. Note that this function is actually called *after* the QueueTask() function returns. Note that it is unsafe to store references to Cuberite objects, such as entities, across from the caller to the task handler function; store the EntityID instead." }, QueueUnloadUnusedChunks = { Params = "", Return = "", Notes = "Queues a cTask that unloads chunks that are no longer needed and are saved." }, RegenerateChunk = { Params = "ChunkX, ChunkZ", Return = "", Notes = "Queues the specified chunk to be re-generated, overwriting the current data. To queue a chunk for generating only if it doesn't exist, use the GenerateChunk() instead." }, ScheduleTask = { Params = "DelayTicks, TaskFunction", Return = "", Notes = "Queues the specified function to be executed in the world's tick thread after a the specified number of ticks. This enables operations to be queued for execution in the future. The function signature is <pre class=\"pretty-print lang-lua\">function({{cWorld|World}})</pre>All return values from the function are ignored. Note that it is unsafe to store references to Cuberite objects, such as entities, across from the caller to the task handler function; store the EntityID instead." }, SendBlockTo = { Params = "BlockX, BlockY, BlockZ, {{cPlayer|Player}}", Return = "", Notes = "Sends the block at the specified coords to the specified player's client, as an UpdateBlock packet." }, SetAreaBiome = { { Params = "MinX, MaxX, MinZ, MaxZ, EMCSBiome", Return = "bool", Notes = "Sets the biome in the rectangular area specified. Returns true if successful, false if any of the chunks were unloaded." }, { Params = "{{cCuboid|Cuboid}}, EMCSBiome", Return = "bool", Notes = "Sets the biome in the cuboid specified. Returns true if successful, false if any of the chunks were unloaded. The cuboid needn't be sorted." }, }, SetBiomeAt = { Params = "BlockX, BlockZ, EMCSBiome", Return = "bool", Notes = "Sets the biome at the specified block coords. Returns true if successful, false otherwise." }, SetBlock = { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta", Return = "", Notes = "Sets the block at the specified coords, replaces the block entities for the previous block type, creates a new block entity for the new block, if appropriate, and wakes up the simulators. This is the preferred way to set blocks, as opposed to FastSetBlock(), which is only to be used under special circumstances." }, SetBlockMeta = { { Params = "BlockX, BlockY, BlockZ, BlockMeta", Return = "", Notes = "Sets the meta for the block at the specified coords." }, { Params = "{{Vector3i|BlockCoords}}, BlockMeta", Return = "", Notes = "Sets the meta for the block at the specified coords." }, }, SetChunkAlwaysTicked = { Params = "ChunkX, ChunkZ, IsAlwaysTicked", Return = "", Notes = "Sets the chunk to always be ticked even when it doesn't contain any clients. IsAlwaysTicked set to true turns forced ticking on, set to false turns it off. Every call with 'true' should be paired with a later call with 'false', otherwise the ticking won't stop. Multiple actions can request ticking independently, the ticking will continue until the last call with 'false'. Note that when the chunk unloads, it loses the value of this flag." }, SetNextBlockTick = { Params = "BlockX, BlockY, BlockZ", Return = "", Notes = "Sets the blockticking to start at the specified block in the next tick." }, SetCommandBlockCommand = { Params = "BlockX, BlockY, BlockZ, Command", Return = "bool", Notes = "Sets the command to be executed in a command block at the specified coordinates. Returns if command was changed." }, SetCommandBlocksEnabled = { Params = "IsEnabled (bool)", Return = "", Notes = "Sets whether command blocks should be enabled on the (entire) server." }, SetDaylightCycleEnabled = { Params = "bool", Return = "", Notes = "Starts or stops the daylight cycle." }, SetLinkedEndWorldName = { Params = "string", Return = "", Notes = "Sets the name of the world that the end portal should link to." }, SetLinkedNetherWorldName = { Params = "string", Return = "", Notes = "Sets the name of the world that the nether portal should link to." }, SetLinkedOverworldName = { Params = "string", Return = "", Notes = "Sets the name of the world that the nether portal should link to?" }, SetMaxViewDistance = { Params = "number", Return = "", Notes = "Sets the maximum viewdistance of the players in the world." }, SetMaxNetherPortalHeight = { Params = "number", Return = "", Notes = "Sets the maximum height for a nether portal" }, SetMaxNetherPortalWidth = { Params = "number", Return = "", Notes = "Sets the maximum width for a nether portal" }, SetMinNetherPortalHeight = { Params = "number", Return = "", Notes = "Sets the minimum height for a nether portal" }, SetMinNetherPortalWidth = { Params = "number", Return = "", Notes = "Sets the minimum width for a nether portal" }, SetShouldUseChatPrefixes = { Params = "", Return = "ShouldUse (bool)", Notes = "Sets whether coloured chat prefixes such as [INFO] is used with the SendMessageXXX() or BroadcastChatXXX(), or simply the entire message is coloured in the respective colour." }, SetSignLines = { Params = "X, Y, Z, Line1, Line2, Line3, Line4, [{{cPlayer|Player}}]", Return = "", Notes = "Sets the sign text at the specified coords. The sign-updating hooks are called for the change. The Player parameter is used to indicate the player from whom the change has come, it may be nil." }, SetTicksUntilWeatherChange = { Params = "NumTicks", Return = "", Notes = "Sets the number of ticks after which the weather will be changed." }, SetTimeOfDay = { Params = "TimeOfDayTicks", Return = "", Notes = "Sets the time of day, expressed as number of ticks past sunrise, in the range 0 .. 24000." }, SetTNTShrapnelLevel = { Params = "{{Globals#ShrapnelLevel|ShrapnelLevel}}", Return = "", Notes = "Sets the Shrampel level of the world." }, SetTrapdoorOpen = { Params = "BlockX, BlockY, BlockZ, bool", Return = "", Notes = "Opens or closes a trapdoor at the specific coordinates." }, SetWeather = { Params = "Weather", Return = "", Notes = "Sets the current weather (wSunny, wRain, wStorm) and resets the TicksUntilWeatherChange to the default value for the new weather. The normal weather-changing hooks are called for the change." }, ShouldBroadcastAchievementMessages = { Params = "", Return = "bool", Notes = "Returns true if the server should broadcast achievement messages in this world." }, ShouldBroadcastDeathMessages = { Params = "", Return = "bool", Notes = "Returns true if the server should broadcast death messages in this world." }, ShouldUseChatPrefixes = { Params = "", Return = "bool", Notes = "Returns whether coloured chat prefixes are prepended to chat messages or the entire message is simply coloured." }, ShouldLavaSpawnFire = { Params = "", Return = "bool", Notes = "Returns true if the world is configured to spawn fires near lava (world.ini: [Physics].ShouldLavaSpawnFire value)" }, SpawnItemPickups = { { Params = "{{cItems|Pickups}}, X, Y, Z, FlyAwaySpeed", Return = "", Notes = "Spawns the specified pickups at the position specified. The FlyAway speed is used to initialize the random speed in which the pickups fly away from the spawn position." }, { Params = "{{cItems|Pickups}}, X, Y, Z, SpeedX, SpeedY, SpeedZ", Return = "", Notes = "Spawns the specified pickups at the position specified. All the pickups fly away from the spawn position using the specified speed." }, }, SpawnMinecart = { Params = "X, Y, Z, MinecartType, Item, BlockHeight", Return = "number", Notes = "Spawns a minecart at the specific coordinates. MinecartType is the item type of the minecart. If the minecart is an empty minecart then the given item is the block inside the minecart, and blockheight is the distance of the block and the minecart." }, SpawnMob = { Params = "X, Y, Z, {{cMonster|MonsterType}}, [Baby]", Return = "EntityID", Notes = "Spawns the specified type of mob at the specified coords. If the Baby parameter is true, the mob will be a baby. Returns the EntityID of the creates entity, or -1 on failure. " }, SpawnFallingBlock = { Params = "X, Y, Z, BlockType, BlockMeta", Return = "EntityID", Notes = "Spawns an {{cFallingBlock|Falling Block}} entity at the specified coords with the given block type/meta" }, SpawnExperienceOrb = { Params = "X, Y, Z, Reward", Return = "EntityID", Notes = "Spawns an {{cExpOrb|experience orb}} at the specified coords, with the given reward" }, SpawnPrimedTNT = { Params = "X, Y, Z, FuseTicks, InitialVelocityCoeff", Return = "", Notes = "Spawns a {{cTNTEntity|primed TNT entity}} at the specified coords, with the given fuse ticks. The entity gets a random speed multiplied by the InitialVelocityCoeff, 1 being the default value." }, TryGetHeight = { Params = "BlockX, BlockZ", Return = "IsValid, Height", Notes = "Returns true and height of the highest non-air block if the chunk is loaded, or false otherwise." }, UpdateSign = { Params = "X, Y, Z, Line1, Line2, Line3, Line4, [{{cPlayer|Player}}]", Return = "", Notes = "(<b>DEPRECATED</b>) Please use SetSignLines()." }, UseBlockEntity = { Params = "{{cPlayer|Player}}, BlockX, BlockY, BlockZ", Return = "", Notes = "Makes the specified Player use the block entity at the specified coords (open chest UI, etc.) If the cords are in an unloaded chunk or there's no block entity, ignores the call." }, VillagersShouldHarvestCrops = { Params = "", Return = "", Notes = "Returns true if villagers can harvest crops." }, WakeUpSimulators = { Params = "BlockX, BlockY, BlockZ", Return = "", Notes = "Wakes up the simulators for the specified block." }, WakeUpSimulatorsInArea = { Params = "MinBlockX, MaxBlockX, MinBlockY, MaxBlockY, MinBlockZ, MaxBlockZ", Return = "", Notes = "Wakes up the simulators for all the blocks in the specified area (edges inclusive)." }, }, AdditionalInfo = { { Header = "Using callbacks", Contents = [[ To avoid problems with stale objects, the cWorld class will not let plugins get a direct pointer to an {{cEntity|entity}}, {{cBlockEntity|block entity}} or a {{cPlayer|player}}. Such an object could be modified or even destroyed by another thread while the plugin holds it, so it would be rather unsafe.</p> <p> Instead, the cWorld provides access to these objects using callbacks. The plugin provides a function that is called and receives the object as a parameter; cWorld guarantees that while the callback is executing, the object will stay valid. If a plugin needs to "remember" the object outside of the callback, it needs to store the entity ID, blockentity coords or player name.</p> <p> The following code examples show how to use the callbacks</p> <p> This code teleports player Player to another player named ToName in the same world: <pre class="prettyprint lang-lua"> -- Player is a cPlayer object -- ToName is a string -- World is a cWorld object World:ForEachPlayer( function (a_OtherPlayer) if (a_OtherPlayer:GetName() == ToName) then Player:TeleportToEntity(a_OtherPlayer); end ); </pre></p> <p> This code fills each furnace in the chunk with 64 coals: <pre class="prettyprint lang-lua"> -- Player is a cPlayer object -- World is a cWorld object World:ForEachFurnaceInChunk(Player:GetChunkX(), Player:GetChunkZ(), function (a_Furnace) a_Furnace:SetFuelSlot(cItem(E_ITEM_COAL, 64)); end ); </pre></p> <p> This code teleports all spiders up by 100 blocks: <pre class="prettyprint lang-lua"> -- World is a cWorld object World:ForEachEntity( function (a_Entity) if not(a_Entity:IsMob()) then return; end -- Get the cMonster out of cEntity, now that we know the entity represents one. local Monster = tolua.cast(a_Entity, "cMonster"); if (Monster:GetMobType() == mtSpider) then Monster:TeleportToCoords(Monster:GetPosX(), Monster:GetPosY() + 100, Monster:GetPosZ()); end end ); </pre></p> ]], }, }, -- AdditionalInfo }, -- cWorld ItemCategory = { Desc = [[ This class contains static functions for determining item categories. All of the functions are called directly on the class table, unlike most other object, which require an instance first. ]], Functions = { IsArmor = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of an armor." }, IsAxe = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of an axe." }, IsBoots = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of boots." }, IsChestPlate = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of a chestplate." }, IsHelmet = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of a helmet." }, IsHoe = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of a hoe." }, IsLeggings = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of a leggings." }, IsPickaxe = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of a pickaxe." }, IsShovel = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of a shovel." }, IsSword = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of a sword." }, IsTool = { Params = "ItemType", Return = "bool", Notes = "(STATIC) Returns true if the specified item type is any kind of a tool (axe, hoe, pickaxe, shovel or FIXME: sword)" }, }, AdditionalInfo = { { Header = "Code example", Contents = [[ The following code snippet checks if the player holds a shovel. <pre class="prettyprint lang-lua"> -- a_Player is a {{cPlayer}} object, possibly received as a hook param local HeldItem = a_Player:GetEquippedItem() if (ItemCategory.IsShovel(HeldItem.m_ItemType)) then -- It's a shovel end </pre> ]], } }, }, -- ItemCategory lxp = { Desc = [[ This class provides an interface to the XML parser, {{http://matthewwild.co.uk/projects/luaexpat/|LuaExpat}}. It provides a SAX interface with an incremental XML parser.</p> <p> With an event-based API like SAX the XML document can be fed to the parser in chunks, and the parsing begins as soon as the parser receives the first document chunk. LuaExpat reports parsing events (such as the start and end of elements) directly to the application through callbacks. The parsing of huge documents can benefit from this piecemeal operation.</p> <p> See the online {{http://matthewwild.co.uk/projects/luaexpat/manual.html#parser|LuaExpat documentation}} for details on how to work with this parser. The code examples below should provide some basic help, too. ]], Functions = { new = {Params = "CallbacksTable, [SeparatorChar]", Return = "XMLParser object", Notes = "Creates a new XML parser object, with the specified callbacks table and optional separator character."}, }, Constants = { _COPYRIGHT = { Notes = "" }, _DESCRIPTION = { Notes = "" }, _VERSION = { Notes = "" }, }, AdditionalInfo = { { Header = "Parser callbacks", Contents = [[ The callbacks table passed to the new() function specifies the Lua functions that the parser calls upon various events. The following table lists the most common functions used, for a complete list see the online {{http://matthewwild.co.uk/projects/luaexpat/manual.html#parser|LuaExpat documentation}}.</p> <table> <tr><th>Function name</th><th>Parameters</th><th>Notes</th></tr> <tr><td>CharacterData</td><td>Parser, string</td><td>Called when the parser recognizes a raw string inside the element</td></tr> <tr><td>EndElement</td><td>Parser, ElementName</td><td>Called when the parser detects the ending of an XML element</td></tr> <tr><td>StartElement</td><td>Parser, ElementName, AttributesTable</td><td>Called when the parser detects the start of an XML element. The AttributesTable is a Lua table containing all the element's attributes, both in the array section (in the order received) and in the dictionary section.</td></tr> </table> ]], }, { Header = "XMLParser object", Contents = [[ The XMLParser object returned by lxp.new provides the functions needed to parse the XML. The following list provides the most commonly used ones, for a complete list see the online {{http://matthewwild.co.uk/projects/luaexpat/manual.html#parser|LuaExpat documentation}}. <ul> <li>close() - closes the parser, freeing all memory used by it.</li> <li>getCallbacks() - returns the callbacks table for this parser.</li> <li>parse(string) - parses more document data. the string contains the next part (or possibly all) of the document. Returns non-nil for success or nil, msg, line, col, pos for error.</li> <li>stop() - aborts parsing (can be called from within the parser callbacks).</li> </ul> ]], }, { Header = "Code example", Contents = [[ The following code reads an entire XML file and outputs its logical structure into the console: <pre class="prettyprint lang-lua"> local Depth = 0; -- Define the callbacks: local Callbacks = { CharacterData = function(a_Parser, a_String) LOG(string.rep(" ", Depth) .. "* " .. a_String); end EndElement = function(a_Parser, a_ElementName) Depth = Depth - 1; LOG(string.rep(" ", Depth) .. "- " .. a_ElementName); end StartElement = function(a_Parser, a_ElementName, a_Attribs) LOG(string.rep(" ", Depth) .. "+ " .. a_ElementName); Depth = Depth + 1; end } -- Create the parser: local Parser = lxp.new(Callbacks); -- Parse the XML file: local f = io.open("file.xml", "rb"); while (true) do local block = f:read(128 * 1024); -- Use a 128KiB buffer for reading if (block == nil) then -- End of file break; end Parser:parse(block); end -- Signalize to the parser that no more data is coming Parser:parse(); -- Close the parser: Parser:close(); </pre> ]], }, }, -- AdditionalInfo }, -- lxp sqlite3 = { Desc = [[ ]], Functions = { complete = { Params = "string", Return = "bool", Notes = "Returns true if the string sql comprises one or more complete SQL statements and false otherwise." }, open = { Params = "FileName", Return = "DBClass", Notes = [[ Opens (or creates if it does not exist) an SQLite database with name filename and returns its handle as userdata (the returned object should be used for all further method calls in connection with this specific database, see {{http://lua.sqlite.org/index.cgi/doc/tip/doc/lsqlite3.wiki#database_methods|Database methods}}). Example: <pre class="prettyprint lang-lua"> -- open the database: myDB = sqlite3.open('MyDatabaseFile.sqlite3') -- do some database calls... -- Close the database: myDB:close() </pre> ]], }, open_memory = { Return = "DBClass", Notes = "Opens an SQLite database in memory and returns its handle as userdata. In case of an error, the function returns nil, an error code and an error message. (In-memory databases are volatile as they are never stored on disk.)" }, version = { Return = "string", Notes = "Returns a string with SQLite version information, in the form 'x.y[.z]'." }, }, }, TakeDamageInfo = { Desc = [[ This class contains the amount of damage, and the entity that caused the damage. It is used in the {{OnTakeDamage|HOOK_TAKE_DAMAGE}} hook and in the {{cEntity}}'s TakeDamage() function. ]], Variables = { Attacker = { Type = "{{cEntity}}", Notes = "The entity who is attacking. Only valid if dtAttack." }, DamageType = { Type = "eDamageType", Notes = "Source of the damage. One of the dtXXX constants." }, FinalDamage = { Type = "number", Notes = " The final amount of damage that will be applied to the Receiver. It is the RawDamage minus any Receiver's armor-protection " }, Knockback = { Type = "{{Vector3d}}", Notes = "Vector specifying the amount and direction of knockback that will be applied to the Receiver " }, RawDamage = { Type = "number", Notes = "Amount of damage that the attack produces on the Receiver, including the Attacker's equipped weapon, but excluding the Receiver's armor." }, }, AdditionalInfo = { { Header = "", Contents = [[ The TDI is passed as the second parameter in the HOOK_TAKE_DAMAGE hook, and can be used to modify the damage before it is applied to the receiver: <pre class="prettyprint lang-lua"> function OnTakeDamage(Receiver, TDI) LOG("Damage: Raw ".. TDI.RawDamage .. ", Final:" .. TDI.FinalDamage); -- If the attacker is a spider, make it deal 999 points of damage (insta-death spiders): if ((TDI.Attacker ~= nil) and TDI.Attacker:IsA("cSpider")) then TDI.FinalDamage = 999; end end </pre> ]], }, }, -- AdditionalInfo }, -- TakeDamageInfo tolua = { Desc = [[ This class represents the tolua bridge between the Lua API and Cuberite. It supports some low level operations and queries on the objects. See also the tolua++'s documentation at {{http://www.codenix.com/~tolua/tolua++.html#utilities}}. Normally you shouldn't use any of these functions except for type() ]], Functions = { cast = { Params = "Object, TypeStr", Return = "Object", Notes = "Casts the object to the specified type.<br/><b>Note:</b> This is a potentially unsafe operation and it could crash the server. There is normally no need to use this function at all, so don't use it unless you know exactly what you're doing." }, getpeer = { Params = "", Return = "", Notes = "" }, inherit = { Params = "", Return = "", Notes = "" }, releaseownership = { Params = "", Return = "", Notes = "" }, setpeer = { Params = "", Return = "", Notes = "" }, takeownership = { Params = "", Return = "", Notes = "" }, type = { Params = "Object", Return = "TypeStr", Notes = "Returns a string representing the type of the object. This works similar to Lua's built-in type() function, but recognizes the underlying C++ classes, too." }, }, }, -- tolua Globals = { Desc = [[ These functions are available directly, without a class instance. Any plugin can call them at any time. ]], Functions = { AddFaceDirection = {Params = "BlockX, BlockY, BlockZ, BlockFace, [IsInverse]", Return = "BlockX, BlockY, BlockZ", Notes = "Returns the coords of a block adjacent to the specified block through the specified {{Globals#BlockFaces|face}}"}, BlockFaceToString = {Params = "{{Globals#BlockFaces|eBlockFace}}", Return = "string", Notes = "Returns the string representation of the {{Globals#BlockFaces|eBlockFace}} constant. Uses the axis-direction-based names, such as BLOCK_FACE_XP." }, BlockStringToType = {Params = "BlockTypeString", Return = "BLOCKTYPE", Notes = "Returns the block type parsed from the given string"}, Clamp = {Params = "Number, Min, Max", Return = "number", Notes = "Clamp the number to the specified range."}, ClickActionToString = {Params = "{{Globals#ClickAction|ClickAction}}", Return = "string", Notes = "Returns a string description of the ClickAction enumerated value"}, DamageTypeToString = {Params = "{{Globals#DamageType|DamageType}}", Return = "string", Notes = "Converts the {{Globals#DamageType|DamageType}} enumerated value to a string representation "}, EscapeString = {Params = "string", Return = "string", Notes = "Returns a copy of the string with all quotes and backslashes escaped by a backslash"}, GetChar = {Params = "String, Pos", Return = "string", Notes = "Returns one character from the string, specified by position "}, GetIniItemSet = { Params = "IniFile, SectionName, KeyName, DefaultValue", Return = "{{cItem}}", Notes = "Returns the item that has been read from the specified INI file value. If the value is not present in the INI file, the DefaultValue is stored in the file and parsed as the result. Returns empty item if the value cannot be parsed. " }, GetTime = {Return = "number", Notes = "Returns the current OS time, as a unix time stamp (number of seconds since Jan 1, 1970)"}, IsBiomeNoDownfall = {Params = "Biome", Return = "bool", Notes = "Returns true if the biome is 'dry', that is, there is no precipitation during rains and storms." }, IsValidBlock = {Params = "BlockType", Return = "bool", Notes = "Returns true if BlockType is a known block type"}, IsValidItem = {Params = "ItemType", Return = "bool", Notes = "Returns true if ItemType is a known item type"}, ItemToFullString = {Params = "{{cItem|cItem}}", Return = "string", Notes = "Returns the string representation of the item, in the format 'ItemTypeText:ItemDamage * Count'"}, ItemToString = {Params = "{{cItem|cItem}}", Return = "string", Notes = "Returns the string representation of the item type"}, ItemTypeToString = {Params = "ItemType", Return = "string", Notes = "Returns the string representation of ItemType "}, LOG = { {Params = "string", Notes = "Logs a text into the server console using 'normal' severity (gray text)"}, {Params = "{{cCompositeChat|CompositeChat}}", Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console. The severity is converted from the CompositeChat's MessageType."}, }, LOGERROR = { {Params = "string", Notes = "Logs a text into the server console using 'error' severity (black text on red background)"}, {Params = "{{cCompositeChat|CompositeChat}}", Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console using 'error' severity (black text on red background)"}, }, LOGINFO = { {Params = "string", Notes = "Logs a text into the server console using 'info' severity (yellow text)"}, {Params = "{{cCompositeChat|CompositeChat}}", Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console using 'info' severity (yellow text)"}, }, LOGWARN = { {Params = "string", Notes = "Logs a text into the server console using 'warning' severity (red text); OBSOLETE, use LOGWARNING() instead"}, {Params = "{{cCompositeChat|CompositeChat}}", Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console using 'warning' severity (red text); OBSOLETE, use LOGWARNING() instead"}, }, LOGWARNING = { {Params = "string", Notes = "Logs a text into the server console using 'warning' severity (red text)"}, {Params = "{{cCompositeChat|CompositeChat}}", Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console using 'warning' severity (red text)"}, }, MirrorBlockFaceY = { Params = "{{Globals#BlockFaces|eBlockFace}}", Return = "{{Globals#BlockFaces|eBlockFace}}", Notes = "Returns the {{Globals#BlockFaces|eBlockFace}} that corresponds to the given {{Globals#BlockFaces|eBlockFace}} after mirroring it around the Y axis (or rotating 180 degrees around it)." }, NoCaseCompare = {Params = "string, string", Return = "number", Notes = "Case-insensitive string comparison; returns 0 if the strings are the same"}, NormalizeAngleDegrees = { Params = "AngleDegrees", Return = "AngleDegrees", Notes = "Returns the angle, wrapped into the [-180, +180) range." }, ReplaceString = {Params = "full-string, to-be-replaced-string, to-replace-string", Return = "string", Notes = "Replaces *each* occurence of to-be-replaced-string in full-string with to-replace-string"}, RotateBlockFaceCCW = { Params = "{{Globals#BlockFaces|eBlockFace}}", Return = "{{Globals#BlockFaces|eBlockFace}}", Notes = "Returns the {{Globals#BlockFaces|eBlockFace}} that corresponds to the given {{Globals#BlockFaces|eBlockFace}} after rotating it around the Y axis 90 degrees counter-clockwise." }, RotateBlockFaceCW = { Params = "{{Globals#BlockFaces|eBlockFace}}", Return = "{{Globals#BlockFaces|eBlockFace}}", Notes = "Returns the {{Globals#BlockFaces|eBlockFace}} that corresponds to the given {{Globals#BlockFaces|eBlockFace}} after rotating it around the Y axis 90 degrees clockwise." }, StringSplit = {Params = "string, SeperatorsString", Return = "array table of strings", Notes = "Seperates string into multiple by splitting every time any of the characters in SeperatorsString is encountered."}, StringSplitAndTrim = {Params = "string, SeperatorsString", Return = "array table of strings", Notes = "Seperates string into multiple by splitting every time any of the characters in SeperatorsString is encountered. Each of the separate strings is trimmed (whitespace removed from the beginning and end of the string)"}, StringSplitWithQuotes = {Params = "string, SeperatorsString", Return = "array table of strings", Notes = "Seperates string into multiple by splitting every time any of the characters in SeperatorsString is encountered. Whitespace wrapped with single or double quotes will be ignored"}, StringToBiome = {Params = "string", Return = "{{Globals#BiomeTypes|BiomeType}}", Notes = "Converts a string representation to a {{Globals#BiomeTypes|BiomeType}} enumerated value"}, StringToDamageType = {Params = "string", Return = "{{Globals#DamageType|DamageType}}", Notes = "Converts a string representation to a {{Globals#DamageType|DamageType}} enumerated value."}, StringToDimension = {Params = "string", Return = "{{Globals#WorldDimension|Dimension}}", Notes = "Converts a string representation to a {{Globals#WorldDimension|Dimension}} enumerated value"}, StringToItem = {Params = "string, {{cItem|cItem}}", Return = "bool", Notes = "Parses the given string and sets the item; returns true if successful"}, StringToMobType = {Params = "string", Return = "{{Globals#MobType|MobType}}", Notes = "<b>DEPRECATED!</b> Please use cMonster:StringToMobType(). Converts a string representation to a {{Globals#MobType|MobType}} enumerated value"}, StripColorCodes = {Params = "string", Return = "string", Notes = "Removes all control codes used by MC for colors and styles"}, TrimString = {Params = "string", Return = "string", Notes = "Trims whitespace at both ends of the string"}, md5 = {Params = "string", Return = "string", Notes = "<b>OBSOLETE</b>, use the {{cCryptoHash}} functions instead.<br>Converts a string to a raw binary md5 hash."}, }, ConstantGroups = { BlockTypes = { Include = "^E_BLOCK_.*", TextBefore = [[ These constants are used for block types. They correspond directly with MineCraft's data values for blocks. ]], }, ItemTypes = { Include = "^E_ITEM_.*", TextBefore = [[ These constants are used for item types. They correspond directly with MineCraft's data values for items. ]], }, MetaValues = { Include = "^E_META_.*", }, BiomeTypes = { Include = "^bi.*", TextBefore = [[ These constants represent the biomes that the server understands. Note that there is a global StringToBiome() function that can convert a string into one of these constants. ]], }, BlockFaces = { Include = "^BLOCK_FACE_.*", TextBefore = [[ These constants are used to describe individual faces of the block. They are used when the client is interacting with a block in the {{OnPlayerBreakingBlock|HOOK_PLAYER_BREAKING_BLOCK}}, {{OnPlayerBrokenBlock|HOOK_PLAYER_BROKEN_BLOCK}}, {{OnPlayerLeftClick|HOOK_PLAYER_LEFT_CLICK}}, {{OnPlayerPlacedBlock|HOOK_PLAYER_PLACED_BLOCK}}, {{OnPlayerPlacingBlock|HOOK_PLAYER_PLACING_BLOCK}}, {{OnPlayerRightClick|HOOK_PLAYER_RIGHT_CLICK}}, {{OnPlayerUsedBlock|HOOK_PLAYER_USED_BLOCK}}, {{OnPlayerUsedItem|HOOK_PLAYER_USED_ITEM}}, {{OnPlayerUsingBlock|HOOK_PLAYER_USING_BLOCK}}, and {{OnPlayerUsingItem|HOOK_PLAYER_USING_ITEM}} hooks, or when the {{cLineBlockTracer}} hits a block, etc. ]], }, ClickAction = { Include = "^ca.*", TextBefore = [[ These constants are used to signalize various interactions that the user can do with the {{cWindow|UI windows}}. The server translates the protocol events into these constants. Note that there is a global ClickActionToString() function that can translate these constants into their textual representation. ]], }, WorldDimension = { Include = "^dim.*", TextBefore = [[ These constants represent dimension of a world. In Cuberite, the dimension is only reflected in the world's overall tint - overworld gets sky-like colors and dark shades, the nether gets reddish haze and the end gets dark haze. World generator is not directly affected by the dimension, same as fluid simulators; those only default to the expected values if not set specifically otherwise in the world.ini file. ]], }, DamageType = { Include = "^dt.*", TextBefore = [[ These constants are used for specifying the cause of damage to entities. They are used in the {{TakeDamageInfo}} structure, as well as in {{cEntity}}'s damage-related API functions. ]], }, GameMode = { Include = { "^gm.*", "^eGameMode_.*" }, TextBefore = [[ The following constants are used for the gamemode - survival, creative or adventure. Use the gmXXX constants, the eGameMode_ constants are deprecated and will be removed from the API. ]], }, MobType = { Include = { "^mt.*" }, TextBefore = [[ The following constants are used for distinguishing between the individual mob types: ]], }, Weather = { Include = { "^eWeather_.*", "wSunny", "wRain", "wStorm", "wThunderstorm" }, TextBefore = [[ These constants represent the weather in the world. Note that unlike vanilla, Cuberite allows different weathers even in non-overworld {{Globals#WorldDimension|dimensions}}. ]], }, ExplosionSource = { Include = "^es.*", TextBefore = [[ These constants are used to differentiate the various sources of explosions. They are used in the {{OnExploded|HOOK_EXPLODED}} hook, {{OnExploding|HOOK_EXPLODING}} hook and in the {{cWorld}}:DoExplosionAt() function. These constants also dictate the type of the additional data provided with the explosions, such as the exploding {{cCreeper|creeper}} entity or the {{Vector3i|coords}} of the exploding bed. ]], }, SpreadSource = { Include = "^ss.*", TextBefore = [[ These constants are used to differentiate the various sources of spreads, such as grass growing. They are used in the {{OnBlockSpread|HOOK_BLOCK_SPREAD}} hook. ]], }, ShrapnelLevel = { Include = "^sl.*", TextBefore = [[ The following constants define the block types that are propelled outwards after an explosion. ]], }, }, }, -- Globals }, IgnoreClasses = { "^coroutine$", "^debug$", "^io$", "^math$", "^package$", "^os$", "^string$", "^table$", "^g_Stats$", "^g_TrackedPages$", }, IgnoreFunctions = { "Globals.assert", "Globals.collectgarbage", "Globals.xpcall", "Globals.decoda_output", -- When running under Decoda, this function gets added to the global namespace "sqlite3.__newindex", "%a+%.__%a+", -- AnyClass.__Anything "%a+%.%.collector", -- AnyClass..collector "%a+%.new", -- AnyClass.new "%a+%.new_local", -- AnyClass.new_local "%a+%.delete", -- AnyClass.delete -- Functions global in the APIDump plugin: "CreateAPITables", "DumpAPIHtml", "DumpAPITxt", "Initialize", "LinkifyString", "ListMissingPages", "ListUndocumentedObjects", "ListUnexportedObjects", "LoadAPIFiles", "ReadDescriptions", "ReadHooks", "WriteHtmlClass", "WriteHtmlHook", "WriteStats", }, IgnoreConstants = { "cChestEntity.__cBlockEntityWindowOwner__", "cDropSpenserEntity.__cBlockEntityWindowOwner__", "cFurnaceEntity.__cBlockEntityWindowOwner__", "cHopperEntity.__cBlockEntityWindowOwner__", "cLuaWindow.__cItemGrid__cListener__", "Globals._CuberiteInternal_.*", -- Ignore all internal Cuberite constants }, IgnoreVariables = { "__.*__", -- tolua exports multiple inheritance this way } , ExtraPages = { -- No sorting is provided for these, they will be output in the same order as defined here { FileName = "Writing-a-Cuberite-plugin.html", Title = "Writing a Cuberite plugin" }, { FileName = "InfoFile.html", Title = "Using the Info.lua file" }, { FileName = "SettingUpDecoda.html", Title = "Setting up the Decoda Lua IDE" }, { FileName = "SettingUpZeroBrane.html", Title = "Setting up the ZeroBrane Studio Lua IDE" }, { FileName = "UsingChunkStays.html", Title = "Using ChunkStays" }, { FileName = "WebWorldThreads.html", Title = "Webserver vs World threads" }, } } ;
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/Kazham/npcs/Roropp.lua
19
6177
----------------------------------- -- Area: Kazham -- NPC: Roropp -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); require("scripts/globals/pathfind"); local path = { 16.031977, -8.000000, -106.132980, 16.257568, -8.000000, -105.056381, 16.488544, -8.000000, -103.993233, 16.736769, -8.000000, -102.925789, 16.683693, -8.000000, -103.979767, 16.548674, -8.000000, -105.063362, 16.395681, -8.000000, -106.140511, 16.232897, -8.000000, -107.264717, 15.467215, -8.000000, -111.498398, 14.589552, -8.000000, -110.994324, 15.159187, -8.000000, -111.843941, 14.467873, -8.000000, -110.962730, 15.174071, -8.000000, -111.862633, 14.541949, -8.000000, -111.057007, 14.902087, -8.000000, -110.084839, 16.047390, -8.000000, -109.979256, 15.778022, -8.000000, -111.043304, 14.890110, -8.000000, -111.671753, 14.021555, -8.000000, -112.251015, 14.686207, -8.000000, -111.499725, 14.093862, -8.000000, -110.499420, 13.680259, -8.000000, -109.391823, 13.557489, -8.000000, -108.379669, 13.505498, -8.000000, -107.381012, 13.459559, -8.000000, -106.253922, 13.316416, -8.000000, -103.526192, 13.187886, -8.000000, -104.739197, 13.107801, -8.000000, -105.800117, 12.796517, -8.000000, -112.526253, 13.832601, -8.000000, -112.296143, 14.750398, -8.000000, -111.783379, 15.670343, -8.000000, -111.165863, 16.603874, -8.000000, -110.633209, 16.092684, -8.000000, -111.518547, 14.989306, -8.000000, -111.488846, 14.200422, -8.000000, -110.700859, 13.893030, -8.000000, -109.573753, 14.125311, -8.000000, -108.444000, 14.459513, -8.000000, -107.450630, 14.801712, -8.000000, -106.489639, 17.003086, -8.000000, -99.881256, 16.131863, -8.000000, -100.382454, 15.278582, -8.000000, -101.082420, 14.444073, -8.000000, -101.823395, 13.716499, -8.000000, -102.551468, 13.602413, -8.000000, -103.671387, 13.773719, -8.000000, -104.753410, 14.019071, -8.000000, -105.842079, 14.275101, -8.000000, -106.944748, 15.256051, -8.000000, -111.604820, 14.447664, -8.000000, -110.851128, 15.032362, -8.000000, -111.679832, 14.342421, -8.000000, -110.802597, 13.347830, -8.000000, -111.075569, 12.911378, -8.000000, -112.149437, 13.853123, -8.000000, -112.719269, 14.862821, -8.000000, -112.491272, 14.661202, -8.000000, -111.423317, 14.026034, -8.000000, -110.421486, 13.683197, -8.000000, -109.474442, 13.565609, -8.000000, -108.425598, 13.508922, -8.000000, -107.411247, 13.463074, -8.000000, -106.340248, 13.314778, -8.000000, -103.679779, 13.196125, -8.000000, -104.712784, 13.107168, -8.000000, -105.817261, 12.642462, -8.000000, -112.284569, 12.722448, -8.000000, -111.167519, 12.800394, -8.000000, -110.082321, 13.358773, -8.000000, -103.535522, 13.700077, -8.000000, -104.534401, 13.968060, -8.000000, -105.588699, 14.196942, -8.000000, -106.594994, 14.446990, -8.000000, -107.686691, 14.850841, -8.000000, -109.436707, 15.239276, -8.000000, -111.548279, 14.406080, -8.000000, -110.805321, 15.076430, -8.000000, -111.739746, 14.353576, -8.000000, -110.817177, 13.903994, -8.000000, -109.854828, 14.002557, -8.000000, -108.838097, 14.350549, -8.000000, -107.686317, 14.707720, -8.000000, -106.730751, 15.101375, -8.000000, -105.648056, 16.961918, -8.000000, -99.919090, 15.985752, -8.000000, -100.501892, 15.192271, -8.000000, -101.161407, 14.369474, -8.000000, -101.891479, 13.749530, -8.000000, -102.797821, 13.968772, -8.000000, -103.829323, 14.469959, -8.000000, -104.888268, 14.964800, -8.000000, -105.802879, 16.955986, -8.000000, -109.414169, 16.776617, -8.000000, -110.478836, 16.263479, -8.000000, -111.339577, 15.200941, -8.000000, -111.526329, 14.352178, -8.000000, -110.754326, 15.190737, -8.000000, -110.001801, 16.302240, -8.000000, -110.005722, 15.815475, -8.000000, -111.014900, 14.911292, -8.000000, -111.661888, 14.005045, -8.000000, -112.263855, 14.883535, -8.000000, -111.781982, 14.404255, -8.000000, -110.876640, 15.071056, -8.000000, -111.731522, 14.335340, -8.000000, -110.793587, 13.342915, -8.000000, -111.184967, 12.869198, -8.000000, -112.210732, 13.971279, -8.000000, -112.223083, 14.902745, -8.000000, -111.661880, 15.813969, -8.000000, -111.060051, 16.728361, -8.000000, -110.402679, 16.754343, -8.000000, -109.357780, 16.393435, -8.000000, -108.410202, 15.880263, -8.000000, -107.455299, 15.362660, -8.000000, -106.521095, 13.593607, -8.000000, -103.312202, 14.028812, -8.000000, -102.335686, 14.836555, -8.000000, -101.487602, 15.656289, -8.000000, -100.748199, 16.544455, -8.000000, -99.965248, 15.712431, -8.000000, -100.702980, 14.859239, -8.000000, -101.459091, 13.961225, -8.000000, -102.255051, 14.754376, -8.000000, -101.551842, 15.574628, -8.000000, -100.824944, 16.913191, -8.000000, -99.639374, 16.158613, -8.000000, -100.307716, 15.371163, -8.000000, -101.005310, 13.802610, -8.000000, -102.395645, 13.852294, -8.000000, -103.601982, 14.296268, -8.000000, -104.610878, 14.826925, -8.000000, -105.560638, 15.320851, -8.000000, -106.448463, 15.858366, -8.000000, -107.421883, 17.018456, -8.000000, -109.527451, 16.734596, -8.000000, -110.580498, 16.095715, -8.000000, -111.542282 }; 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) player:startEvent(0x00C8); 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); npc:wait(0); end;
gpl-3.0
Spartan322/finalfrontier
gamemode/sgui/doorcontrol.lua
3
2227
-- Copyright (c) 2014 James King [metapyziks@gmail.com] -- -- This file is part of Final Frontier. -- -- Final Frontier is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of -- the License, or (at your option) any later version. -- -- Final Frontier 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 Lesser General Public License -- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>. local BASE = "page" GUI.BaseName = BASE GUI._shipview = nil GUI._powerbar = nil function GUI:Enter() self.Super[BASE].Enter(self) self._shipview = sgui.Create(self, "shipview") self._shipview:SetCurrentShip(self:GetShip()) for _, door in pairs(self._shipview:GetDoorElements()) do door.Enabled = true door.NeedsPermission = false end for _, room in pairs(self._shipview:GetRoomElements()) do if room:GetCurrentRoom() == self:GetRoom() then room.CanClick = true if SERVER then function room.OnClick(room, x, y, btn) if btn == MOUSE1 then self:GetSystem():ToggleAllOpen() else self:GetSystem():ToggleAllLocked() end return true end end elseif CLIENT then function room.GetRoomColor(room) return Color(0, 0, 0, 255) end end end local margin = 16 local barheight = 48 self._powerbar = sgui.Create(self, "powerbar") self._powerbar:SetSize(self:GetWidth() - margin * 2, barheight) self._powerbar:SetOrigin(margin, self:GetHeight() - margin - barheight) self._shipview:SetBounds(Bounds( margin, margin * 0.5, self:GetWidth() - margin * 2, self:GetHeight() - margin * 2.5 - barheight )) end
lgpl-3.0
ShaTelTeam/MegaZs
plugins/idfrom.lua
3
1229
do local function get_message_callback_id(extra, success, result) vardump(result) if result.to.peer_type == 'channel' then local chat = 'channel#id'..result.to.peer_id send_large_msg(chat, result.from.peer_id) else return 'Use This in Your Groups' end end local function get_message_forward(extra, success, result) vardump(result) if result.to.peer_type == 'channel' then local channel = "channel#id"..result.to.peer_id send_large_msg(channel, result.fwd_from.peer_id) else return "User in Groups" end end local function run(msg, matches) if matches[1] == "id" then if msg.to.type == "user" then return "👤"..string.gsub(msg.from.print_name, '_', ' ').." @"..(msg.from.username or '[none]').." |"..msg.from.id.."|" end if type(msg.reply_id) ~= "nil" then id = get_message(msg.reply_id, get_message_callback_id, false) elseif matches[1] == "id" then return "👤"..msg.to.title.."\n|"..msg.to.id.."|" end end if matches[1] == "from" then if type(msg.reply_id)~= "nil" then id = get_message(msg.reply_id, get_message_forward, false) end end end return { patterns = { "^[/!#](id)$", "^[/!#]id (from)$" }, run = run } end
gpl-2.0
Atcold/torch7
random.lua
72
1364
local wrap = require 'cwrap' require 'torchcwrap' local interface = wrap.CInterface.new() interface:print( [[ #include "luaT.h" #include "TH.h" extern void torch_Generator_init(lua_State *L); extern void torch_Generator_new(lua_State *L); ]]) for _,name in ipairs({"seed", "initialSeed"}) do interface:wrap(name, string.format("THRandom_%s",name), {{name='Generator', default=true}, {name="long", creturned=true}}) end interface:wrap('manualSeed', 'THRandom_manualSeed', {{name='Generator', default=true}, {name="long"}}) interface:wrap('getRNGState', 'THByteTensor_getRNGState', {{name='Generator', default=true}, {name='ByteTensor',default=true,returned=true,method={default='nil'}} }) interface:wrap('setRNGState', 'THByteTensor_setRNGState', {{name='Generator', default=true}, {name='ByteTensor',default=true,returned=true,method={default='nil'}} }) interface:register("random__") interface:print( [[ void torch_random_init(lua_State *L) { torch_Generator_init(L); torch_Generator_new(L); lua_setfield(L, -2, "_gen"); luaT_setfuncs(L, random__, 0); } ]]) interface:tofile(arg[1])
bsd-3-clause
nesstea/darkstar
scripts/zones/Temple_of_Uggalepih/TextIDs.lua
13
2342
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6384; -- Obtained: <item> GIL_OBTAINED = 6385; -- Obtained <number> gil KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7204; -- You can't fish here BITS_OF_VEGETABLE = 7490; -- Bits of vegetable matter are strewn around. They appear to have been gnawed on by insects... -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7306; -- You unlock the chest! CHEST_FAIL = 7307; -- Fails to open the chest. CHEST_TRAP = 7308; -- The chest was trapped! CHEST_WEAK = 7309; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7310; -- The chest was a mimic! CHEST_MOOGLE = 7311; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7312; -- The chest was but an illusion... CHEST_LOCKED = 7313; -- The chest appears to be locked. -- Dialog Texts NO_REASON_TO_INVESTIGATE = 7314; -- There is no reason to investigate further. THE_BOX_IS_LOCKED = 7315; -- The box is locked. PAINTBRUSH_OFFSET = 7318; -- projects the deepest, darkest corner of your soul onto the blank canvas...only then will the doors to rancor open FALLS_FROM_THE_BOOK = 7328; -- falls from the book! THE_DOOR_IS_LOCKED = 7342; -- The door is locked. You might be able to open it with PROTECTED_BY_UNKNOWN_FORCE = 7343; -- The door is protected by some unknown force. YOUR_KEY_BREAKS = 7345; -- breaks! DOOR_LOCKED = 7363; -- The door is locked. SOME_SORT_OF_CEREMONY = 7435; -- Some sort of ceremony was performed here... NM_OFFSET = 7485; -- It looks like some sort of device. A thin thread leads down to the floor... IT_IS_A_BEEHIVE = 7489; -- It is a beehive... NOTHING_HAPPENS = 119; -- Nothing happens... NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here. -- Other HATE_RESET = 7416; -- The built-up hate has been cleansed...! DOOR_SHUT = 7418; -- The door is firmly shut. NO_HATE = 7419; -- You have no built-up hate to cleanse. -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results...
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/QuBia_Arena/mobs/Rojgnoj_s_Left_Hand.lua
10
1232
----------------------------------- -- Area: QuBia_Arena -- Mission 9-2 SANDO ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/missions"); require("scripts/zones/QuBia_Arena/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("2HGO",math.random(40,80)); end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) if(mob:getLocalVar("2HOUR") == 0)then if(mob:getHPP() < mob:getLocalVar("2HGO"))then mob:setLocalVar("2HOUR",1); mob:useMobAbility(435); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) mob:setLocalVar("2HOUR",0); mob:setLocalVar("2HGO",0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) printf("finishCSID: %u",csid); printf("RESULT: %u",option); end;
gpl-3.0
jj918160/cocos2d-x-samples
samples/KillBug/src/cocos/extension/ExtensionConstants.lua
62
2000
if nil == cc.Control then return end cc.CONTROL_STATE_NORMAL = 1 cc.CONTROL_STATE_HIGH_LIGHTED = 2 cc.CONTROL_STATE_DISABLED = 4 cc.CONTROL_STATE_SELECTED = 8 cc.CONTROL_STEPPER_PART_MINUS = 0 cc.CONTROL_STEPPER_PART_PLUS = 1 cc.CONTROL_STEPPER_PART_NONE = 2 cc.TABLEVIEW_FILL_TOPDOWN = 0 cc.TABLEVIEW_FILL_BOTTOMUP = 1 cc.SCROLLVIEW_SCRIPT_SCROLL = 0 cc.SCROLLVIEW_SCRIPT_ZOOM = 1 cc.TABLECELL_TOUCHED = 2 cc.TABLECELL_HIGH_LIGHT = 3 cc.TABLECELL_UNHIGH_LIGHT = 4 cc.TABLECELL_WILL_RECYCLE = 5 cc.TABLECELL_SIZE_FOR_INDEX = 6 cc.TABLECELL_SIZE_AT_INDEX = 7 cc.NUMBER_OF_CELLS_IN_TABLEVIEW = 8 cc.SCROLLVIEW_DIRECTION_NONE = -1 cc.SCROLLVIEW_DIRECTION_HORIZONTAL = 0 cc.SCROLLVIEW_DIRECTION_VERTICAL = 1 cc.SCROLLVIEW_DIRECTION_BOTH = 2 cc.CONTROL_EVENTTYPE_TOUCH_DOWN = 1 cc.CONTROL_EVENTTYPE_DRAG_INSIDE = 2 cc.CONTROL_EVENTTYPE_DRAG_OUTSIDE = 4 cc.CONTROL_EVENTTYPE_DRAG_ENTER = 8 cc.CONTROL_EVENTTYPE_DRAG_EXIT = 16 cc.CONTROL_EVENTTYPE_TOUCH_UP_INSIDE = 32 cc.CONTROL_EVENTTYPE_TOUCH_UP_OUTSIDE = 64 cc.CONTROL_EVENTTYPE_TOUCH_CANCEL = 128 cc.CONTROL_EVENTTYPE_VALUE_CHANGED = 256 cc.EDITBOX_INPUT_MODE_ANY = 0 cc.EDITBOX_INPUT_MODE_EMAILADDR = 1 cc.EDITBOX_INPUT_MODE_NUMERIC = 2 cc.EDITBOX_INPUT_MODE_PHONENUMBER = 3 cc.EDITBOX_INPUT_MODE_URL = 4 cc.EDITBOX_INPUT_MODE_DECIMAL = 5 cc.EDITBOX_INPUT_MODE_SINGLELINE = 6 cc.EDITBOX_INPUT_FLAG_PASSWORD = 0 cc.EDITBOX_INPUT_FLAG_SENSITIVE = 1 cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 2 cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3 cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4 cc.KEYBOARD_RETURNTYPE_DEFAULT = 0 cc.KEYBOARD_RETURNTYPE_DONE = 1 cc.KEYBOARD_RETURNTYPE_SEND = 2 cc.KEYBOARD_RETURNTYPE_SEARCH = 3 cc.KEYBOARD_RETURNTYPE_GO = 4 cc.ASSETSMANAGER_CREATE_FILE = 0 cc.ASSETSMANAGER_NETWORK = 1 cc.ASSETSMANAGER_NO_NEW_VERSION = 2 cc.ASSETSMANAGER_UNCOMPRESS = 3 cc.ASSETSMANAGER_PROTOCOL_PROGRESS = 0 cc.ASSETSMANAGER_PROTOCOL_SUCCESS = 1 cc.ASSETSMANAGER_PROTOCOL_ERROR = 2
mit
nesstea/darkstar
scripts/commands/changesjob.lua
2
1078
--------------------------------------------------------------------------------------------------- -- func: changesjob -- desc: Changes the players current subjob. --------------------------------------------------------------------------------------------------- require("scripts/globals/status"); cmdprops = { permission = 1, parameters = "ss" }; function onTrigger(player, job, level) job = tonumber(job) or _G[job]; level = tonumber(level) or level; if (job == nil) then player:PrintToPlayer("You must enter a job id or short-name."); return; end if job <= 0 or job > 22 then player:PrintToPlayer( string.format( "Invalid job '%s' given. Use enum or id. e.g. JOB_WAR", job ) ); return; end -- Change the players subjob.. player:changesJob(job); -- Attempt to set the players subjob level.. if (level ~= nil and level > 0 and level <= 99) then player:setsLevel(level); else player:PrintToPlayer( "Invalid level given. Level must be between 1 and 99!" ); end end
gpl-3.0
MuhammadWang/MCServer
MCServer/Plugins/InfoDump.lua
2
20705
#!/usr/bin/lua -- InfoDump.lua --[[ Loads plugins' Info.lua and dumps its g_PluginInfo into various text formats This is used for generating plugin documentation for the forum and for GitHub's INFO.md files This script can be used in two ways: Executing "lua InfoDump.lua" will go through all subfolders and dump each Info.lua file it can find Note that this mode of operation requires LuaRocks with LFS installed; instructions are printed when the prerequisites are not met. Executing "lua InfoDump.lua PluginName" will load the Info.lua file from PluginName's folder and dump only that one plugin's documentation. This mode of operation doesn't require LuaRocks --]] -- Check Lua version. We use 5.1-specific construct when loading the plugin info, 5.2 is not compatible! if (_VERSION ~= "Lua 5.1") then print("Unsupported Lua version. This script requires Lua version 5.1, this Lua is version " .. (_VERSION or "<nil>")); return; end --- Replaces generic formatting with forum-specific formatting -- Also removes the single line-ends local function ForumizeString(a_Str) assert(type(a_Str) == "string"); -- Remove the indentation, unless in the code tag: -- Only one code or /code tag per line is supported! local IsInCode = false; local function RemoveIndentIfNotInCode(s) if (IsInCode) then -- we're in code section, check if this line terminates it IsInCode = (s:find("{%%/code}") ~= nil); return s .. "\n"; else -- we're not in code section, check if this line starts it IsInCode = (s:find("{%%code}") ~= nil); return s:gsub("^%s*", "") .. "\n"; end end a_Str = a_Str:gsub("(.-)\n", RemoveIndentIfNotInCode); -- Replace multiple line ends with {%p} and single line ends with a space, -- so that manual word-wrap in the Info.lua file doesn't wrap in the forum. a_Str = a_Str:gsub("\n\n", "{%%p}"); a_Str = a_Str:gsub("\n", " "); -- Replace the generic formatting: a_Str = a_Str:gsub("{%%p}", "\n\n"); a_Str = a_Str:gsub("{%%b}", "[b]"):gsub("{%%/b}", "[/b]"); a_Str = a_Str:gsub("{%%i}", "[i]"):gsub("{%%/i}", "[/i]"); a_Str = a_Str:gsub("{%%list}", "[list]"):gsub("{%%/list}", "[/list]"); a_Str = a_Str:gsub("{%%li}", "[*]"):gsub("{%%/li}", ""); -- TODO: Other formatting return a_Str; end --- Replaces generic formatting with forum-specific formatting -- Also removes the single line-ends local function GithubizeString(a_Str) assert(type(a_Str) == "string"); -- Remove the indentation, unless in the code tag: -- Only one code or /code tag per line is supported! local IsInCode = false; local function RemoveIndentIfNotInCode(s) if (IsInCode) then -- we're in code section, check if this line terminates it IsInCode = (s:find("{%%/code}") ~= nil); return s .. "\n"; else -- we're not in code section, check if this line starts it IsInCode = (s:find("{%%code}") ~= nil); return s:gsub("^%s*", "") .. "\n"; end end a_Str = a_Str:gsub("(.-)\n", RemoveIndentIfNotInCode); -- Replace multiple line ends with {%p} and single line ends with a space, -- so that manual word-wrap in the Info.lua file doesn't wrap in the forum. a_Str = a_Str:gsub("\n\n", "{%%p}"); a_Str = a_Str:gsub("\n", " "); -- Replace the generic formatting: a_Str = a_Str:gsub("{%%p}", "\n\n"); a_Str = a_Str:gsub("{%%b}", "**"):gsub("{%%/b}", "**"); a_Str = a_Str:gsub("{%%i}", "*"):gsub("{%%/i}", "*"); a_Str = a_Str:gsub("{%%list}", ""):gsub("{%%/list}", ""); a_Str = a_Str:gsub("{%%li}", " - "):gsub("{%%/li}", ""); -- TODO: Other formatting return a_Str; end --- Builds an array of categories, each containing all the commands belonging to the category, -- and the category description, if available. -- Returns the array table, each item has the following format: -- { Name = "CategoryName", Description = "CategoryDescription", Commands = {{CommandString = "/cmd verb", Info = {...}}, ...}} local function BuildCategories(a_PluginInfo) -- The returned result -- This will contain both an array and a dict of the categories, to allow fast search local res = {}; -- For each command add a reference to it into all of its categories: local function AddCommands(a_CmdPrefix, a_Commands) for cmd, info in pairs(a_Commands) do local NewCmd = { CommandString = a_CmdPrefix .. cmd, Info = info, } if ((info.HelpString ~= nil) and (info.HelpString ~= "")) then -- Add to each specified category: local Category = info.Category; if (type(Category) == "string") then Category = {Category}; end for idx, cat in ipairs(Category or {""}) do local CatEntry = res[cat]; if (CatEntry == nil) then -- First time we came across this category, create it: local NewCat = {Name = cat, Description = "", Commands = {NewCmd}}; table.insert(res, NewCat); res[cat] = NewCat; else -- We already have this category, just add the command to its list of commands: table.insert(CatEntry.Commands, NewCmd); end end -- for idx, cat - Category[] end -- if (HelpString valid) -- Recurse all subcommands: if (info.Subcommands ~= nil) then AddCommands(a_CmdPrefix .. cmd .. " ", info.Subcommands); end end -- for cmd, info - a_Commands[] end -- AddCommands() AddCommands("", a_PluginInfo.Commands); -- Assign descriptions to categories: for name, desc in pairs(a_PluginInfo.Categories or {}) do local CatEntry = res[name]; if (CatEntry ~= nil) then -- The result has this category, add the description: CatEntry.Description = desc.Description; end end -- Alpha-sort each category's command list: for idx, cat in ipairs(res) do table.sort(cat.Commands, function (cmd1, cmd2) return (string.lower(cmd1.CommandString) < string.lower(cmd2.CommandString)); end ); end return res; end --- Returns a string specifying the command. -- If a_Command is a simple string, returns a_Command colorized to blue -- If a_Command is a table, expects members Name (full command name) and Params (command parameters), -- colorizes command name blue and params green local function GetCommandRefForum(a_Command) if (type(a_Command) == "string") then return "[color=blue]" .. a_Command .. "[/color]"; end return "[color=blue]" .. a_Command.Name .. "[/color] [color=green]" .. (a_Command.Params or "") .. "[/color]"; end --- Returns a string specifying the command. -- If a_CommandParams is nil, returns a_CommandName apostrophed -- If a_CommandParams is a string, apostrophes a_CommandName with a_CommandParams local function GetCommandRefGithub(a_CommandName, a_CommandParams) assert(type(a_CommandName) == "string"); if (a_CommandParams == nil) then return "`" .. a_CommandName .. "`"; end assert(type(a_CommandParams) == "table"); if ((a_CommandParams.Params == nil) or (a_CommandParams.Params == "")) then return "`" .. a_CommandName .. "`"; end assert(type(a_CommandParams.Params) == "string"); return "`" .. a_CommandName .. " " .. a_CommandParams.Params .. "`"; end --- Writes the specified command detailed help array to the output file, in the forum dump format local function WriteCommandParameterCombinationsForum(a_CmdString, a_ParameterCombinations, f) assert(type(a_CmdString) == "string"); assert(type(a_ParameterCombinations) == "table"); assert(f ~= nil); if (#a_ParameterCombinations == 0) then -- No explicit parameter combinations to write return; end f:write("The following parameter combinations are recognized:\n"); for idx, combination in ipairs(a_ParameterCombinations) do f:write("[color=blue]", a_CmdString, "[/color] [color=green]", combination.Params or "", "[/color]"); if (combination.Help ~= nil) then f:write(" - ", ForumizeString(combination.Help)); end if (combination.Permission ~= nil) then f:write(" (Requires permission '[color=red]", combination.Permission, "[/color]')"); end f:write("\n"); end end --- Writes the specified command detailed help array to the output file, in the forum dump format local function WriteCommandParameterCombinationsGithub(a_CmdString, a_ParameterCombinations, f) assert(type(a_CmdString) == "string"); assert(type(a_ParameterCombinations) == "table"); assert(f ~= nil); if (#a_ParameterCombinations == 0) then -- No explicit parameter combinations to write return; end f:write("The following parameter combinations are recognized:\n\n"); for idx, combination in ipairs(a_ParameterCombinations) do f:write(GetCommandRefGithub(a_CmdString, combination)); if (combination.Help ~= nil) then f:write(" - ", GithubizeString(combination.Help)); end if (combination.Permission ~= nil) then f:write(" (Requires permission '**", combination.Permission, "**')"); end f:write("\n"); end end --- Writes all commands in the specified category to the output file, in the forum dump format local function WriteCommandsCategoryForum(a_Category, f) -- Write category name: local CategoryName = a_Category.Name; if (CategoryName == "") then CategoryName = "General"; end f:write("\n[size=Large]", ForumizeString(a_Category.DisplayName or CategoryName), "[/size]\n"); -- Write description: if (a_Category.Description ~= "") then f:write(ForumizeString(a_Category.Description), "\n"); end -- Write commands: f:write("\n[list]"); for idx2, cmd in ipairs(a_Category.Commands) do f:write("\n[b]", cmd.CommandString, "[/b] - ", ForumizeString(cmd.Info.HelpString or "UNDOCUMENTED"), "\n"); if (cmd.Info.Permission ~= nil) then f:write("Permission required: [color=red]", cmd.Info.Permission, "[/color]\n"); end if (cmd.Info.DetailedDescription ~= nil) then f:write(ForumizeString(cmd.Info.DetailedDescription)); end if (cmd.Info.ParameterCombinations ~= nil) then WriteCommandParameterCombinationsForum(cmd.CommandString, cmd.Info.ParameterCombinations, f); end end f:write("[/list]\n\n") end --- Writes all commands in the specified category to the output file, in the Github dump format local function WriteCommandsCategoryGithub(a_Category, f) -- Write category name: local CategoryName = a_Category.Name; if (CategoryName == "") then CategoryName = "General"; end f:write("\n### ", GithubizeString(a_Category.DisplayName or CategoryName), "\n"); -- Write description: if (a_Category.Description ~= "") then f:write(GithubizeString(a_Category.Description), "\n\n"); end f:write("| Command | Permission | Description | \n") f:write("| ------- | ---------- | ----------- | \n") -- Write commands: for idx2, cmd in ipairs(a_Category.Commands) do f:write("|", cmd.CommandString, " | ", cmd.Info.Permission or "", " | ", GithubizeString(cmd.Info.HelpString or "UNDOCUMENTED"), "| \n") end f:write("\n\n") end local function DumpCommandsForum(a_PluginInfo, f) -- Copy all Categories from a dictionary into an array: local Categories = BuildCategories(a_PluginInfo); -- Sort the categories by name: table.sort(Categories, function(cat1, cat2) return (string.lower(cat1.Name) < string.lower(cat2.Name)); end ); if (#Categories == 0) then return; end f:write("\n[size=X-Large]Commands[/size]\n"); -- Dump per-category commands: for idx, cat in ipairs(Categories) do WriteCommandsCategoryForum(cat, f); end end local function DumpCommandsGithub(a_PluginInfo, f) -- Copy all Categories from a dictionary into an array: local Categories = BuildCategories(a_PluginInfo); -- Sort the categories by name: table.sort(Categories, function(cat1, cat2) return (string.lower(cat1.Name) < string.lower(cat2.Name)); end ); if (#Categories == 0) then return; end f:write("\n# Commands\n"); -- Dump per-category commands: for idx, cat in ipairs(Categories) do WriteCommandsCategoryGithub(cat, f); end end local function DumpAdditionalInfoForum(a_PluginInfo, f) local AInfo = a_PluginInfo.AdditionalInfo; if (type(AInfo) ~= "table") then -- There is no AdditionalInfo in a_PluginInfo return; end for idx, info in ipairs(a_PluginInfo.AdditionalInfo) do if ((info.Title ~= nil) and (info.Contents ~= nil)) then f:write("\n[size=X-Large]", ForumizeString(info.Title), "[/size]\n"); f:write(ForumizeString(info.Contents), "\n"); end end end local function DumpAdditionalInfoGithub(a_PluginInfo, f) local AInfo = a_PluginInfo.AdditionalInfo; if (type(AInfo) ~= "table") then -- There is no AdditionalInfo in a_PluginInfo return; end for idx, info in ipairs(a_PluginInfo.AdditionalInfo) do if ((info.Title ~= nil) and (info.Contents ~= nil)) then f:write("\n# ", GithubizeString(info.Title), "\n"); f:write(GithubizeString(info.Contents), "\n"); end end end --- Collects all permissions mentioned in the info, returns them as a sorted array -- Each array item is {Name = "PermissionName", Info = { PermissionInfo }} local function BuildPermissions(a_PluginInfo) -- Collect all used permissions from Commands, reference the commands that use the permission: local Permissions = a_PluginInfo.Permissions or {}; local function CollectPermissions(a_CmdPrefix, a_Commands) for cmd, info in pairs(a_Commands) do CommandString = a_CmdPrefix .. cmd; if ((info.Permission ~= nil) and (info.Permission ~= "")) then -- Add the permission to the list of permissions: local Permission = Permissions[info.Permission] or {}; Permissions[info.Permission] = Permission; -- Add the command to the list of commands using this permission: Permission.CommandsAffected = Permission.CommandsAffected or {}; table.insert(Permission.CommandsAffected, CommandString); end -- Process the command param combinations for permissions: local ParamCombinations = info.ParameterCombinations or {}; for idx, comb in ipairs(ParamCombinations) do if ((comb.Permission ~= nil) and (comb.Permission ~= "")) then -- Add the permission to the list of permissions: local Permission = Permissions[comb.Permission] or {}; Permissions[info.Permission] = Permission; -- Add the command to the list of commands using this permission: Permission.CommandsAffected = Permission.CommandsAffected or {}; table.insert(Permission.CommandsAffected, {Name = CommandString, Params = comb.Params}); end end -- Process subcommands: if (info.Subcommands ~= nil) then CollectPermissions(CommandString .. " ", info.Subcommands); end end end CollectPermissions("", a_PluginInfo.Commands); -- Copy the list of permissions to an array: local PermArray = {}; for name, perm in pairs(Permissions) do table.insert(PermArray, {Name = name, Info = perm}); end -- Sort the permissions array: table.sort(PermArray, function(p1, p2) return (p1.Name < p2.Name); end ); return PermArray; end local function DumpPermissionsForum(a_PluginInfo, f) -- Get the processed sorted array of permissions: local Permissions = BuildPermissions(a_PluginInfo); if ((Permissions == nil) or (#Permissions <= 0)) then return; end -- Dump the permissions: f:write("\n[size=X-Large]Permissions[/size]\n[list]\n"); for idx, perm in ipairs(Permissions) do f:write(" - [color=red]", perm.Name, "[/color] - "); f:write(ForumizeString(perm.Info.Description or "")); local CommandsAffected = perm.Info.CommandsAffected or {}; if (#CommandsAffected > 0) then f:write("\n[list] Commands affected:\n- "); local Affects = {}; for idx2, cmd in ipairs(CommandsAffected) do table.insert(Affects, GetCommandRefForum(cmd)); end f:write(table.concat(Affects, "\n - ")); f:write("\n[/list]"); end if (perm.Info.RecommendedGroups ~= nil) then f:write("\n[list] Recommended groups: ", perm.Info.RecommendedGroups, "[/list]"); end f:write("\n"); end f:write("[/list]"); end local function DumpPermissionsGithub(a_PluginInfo, f) -- Get the processed sorted array of permissions: local Permissions = BuildPermissions(a_PluginInfo); if ((Permissions == nil) or (#Permissions <= 0)) then return; end -- Dump the permissions: f:write("\n# Permissions\n"); f:write("| Permissions | Description | Commands | Recommended groups |\n") f:write("| ----------- | ----------- | -------- | ------------------ |\n") for idx, perm in ipairs(Permissions) do f:write(perm.Name, " | "); f:write(GithubizeString(perm.Info.Description or ""), " | "); local CommandsAffected = perm.Info.CommandsAffected or {}; if (#CommandsAffected > 0) then local Affects = {}; for idx2, cmd in ipairs(CommandsAffected) do if (type(cmd) == "string") then table.insert(Affects, GetCommandRefGithub(cmd)); else table.insert(Affects, GetCommandRefGithub(cmd.Name, cmd)); end end f:write(table.concat(Affects, ", "), " | "); end if (perm.Info.RecommendedGroups ~= nil) then f:write(perm.Info.RecommendedGroups, " |"); end f:write("\n"); end end local function DumpPluginInfoForum(a_PluginFolder, a_PluginInfo) -- Open the output file: local f, msg = io.open(a_PluginInfo.Name .. "_forum.txt", "w"); if (f == nil) then print("\tCannot dump forum info for plugin " .. a_PluginFolder .. ": " .. msg); return; end -- Write the description: f:write(ForumizeString(a_PluginInfo.Description), "\n"); DumpAdditionalInfoForum(a_PluginInfo, f); DumpCommandsForum(a_PluginInfo, f); DumpPermissionsForum(a_PluginInfo, f); if (a_PluginInfo.SourceLocation ~= nil) then f:write("[b][color=blue]Source:[/color] [url=", a_PluginInfo.SourceLocation, "]Link[/url][/b]"); end f:close(); end local function DumpPluginInfoGithub(a_PluginFolder, a_PluginInfo) -- Open the output file: local f, msg = io.open(a_PluginInfo.Name .. ".md", "w"); -- TODO: Save to a_PluginFolder .. "/Readme.md" instead if (f == nil) then print("\tCannot dump github info for plugin " .. a_PluginFolder .. ": " .. msg); return; end -- Write the description: f:write(GithubizeString(a_PluginInfo.Description), "\n"); DumpAdditionalInfoGithub(a_PluginInfo, f); DumpCommandsGithub(a_PluginInfo, f); DumpPermissionsGithub(a_PluginInfo, f); f:close(); end --- Tries to load the g_PluginInfo from the plugin's Info.lua file -- Returns the g_PluginInfo table on success, or nil and error message on failure local function LoadPluginInfo(a_FolderName) -- Load and compile the Info file: local cfg, err = loadfile(a_FolderName .. "/Info.lua"); if (cfg == nil) then return nil, "Cannot open 'Info.lua': " .. err; end -- Execute the loaded file in a sandbox: -- This is Lua-5.1-specific and won't work in Lua 5.2! local Sandbox = {}; setfenv(cfg, Sandbox); cfg(); if (Sandbox.g_PluginInfo == nil) then return nil, "Info.lua doesn't contain the g_PluginInfo declaration"; end return Sandbox.g_PluginInfo; end local function ProcessPluginFolder(a_FolderName) local PluginInfo, Msg = LoadPluginInfo(a_FolderName); if (PluginInfo == nil) then if (Msg ~= nil) then print("\t" .. Msg); end return; end DumpPluginInfoForum(a_FolderName, PluginInfo); DumpPluginInfoGithub(a_FolderName, PluginInfo); end --- Tries to load LFS through LuaRocks, returns the LFS instance, or nil on error local function LoadLFS() -- Try to load lfs, do not abort if not found ... local lfs, err = pcall( function() return require("lfs") end ); -- ... rather, print a nice message with instructions: if not(lfs) then print([[ Cannot load LuaFileSystem Install it through luarocks by executing the following command: luarocks install luafilesystem (Windows) sudo luarocks install luafilesystem (*nix) If you don't have luarocks installed, you need to install them using your OS's package manager, usually: sudo apt-get install luarocks (Ubuntu / Debian) On windows, a binary distribution can be downloaded from the LuaRocks homepage, http://luarocks.org/en/Download ]]); print("Original error text: ", err); return nil; end -- We now know that LFS is present, get it normally: return require("lfs"); end local Arg1 = ...; if ((Arg1 ~= nil) and (Arg1 ~= "")) then -- Called with a plugin folder name, export only that one ProcessPluginFolder(Arg1) else -- Called without any arguments, process all subfolders: local lfs = LoadLFS(); if (lfs == nil) then -- LFS not loaded, error has already been printed, just bail out return; end print("Processing plugin subfolders:"); for fnam in lfs.dir(".") do if ((fnam ~= ".") and (fnam ~= "..")) then local Attributes = lfs.attributes(fnam); if (Attributes ~= nil) then if (Attributes.mode == "directory") then print(fnam); ProcessPluginFolder(fnam); end end end end end print("Done.");
apache-2.0
nesstea/darkstar
scripts/globals/effects/sanction.lua
32
1714
----------------------------------- -- -- EFFECT_SANCTION -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local power = effect:getPower(); -- 1 = regen, 2 = refresh, 3 = food. local subPower = effect:getSubPower(); -- subPower sets % required to trigger regen/refresh. -- target:addLatent(LATENT_SANCTION_EXP, ?, MOD_EXP_BONUS, ?); -- Possibly handle exp bonus in core instead if (power == 1) then -- target:addLatent(LATENT_SANCTION_REGEN, subPower, MOD_REGEN, 1); elseif (power == 2) then -- target:addLatent(LATENT_SANCTION_REGEN, subPower, MOD_REGEN, 1); elseif (power == 3) then -- target:addMod(MOD_FOOD_DURATION), ???); -- food duration not implemented. end end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local power = effect:getPower(); -- 1 = regen, 2 = refresh, 3 = food. local subPower = effect:getSubPower(); -- subPower sets % required to trigger regen/refresh. -- target:delLatent(LATENT_SANCTION_EXP, ?, MOD_EXP_BONUS, ?); if (power == 1) then -- target:delLatent(LATENT_SANCTION_REGEN, subPower, MOD_REGEN, 1); elseif (power == 2) then -- target:delLatent(LATENT_SANCTION_REGEN, subPower, MOD_REGEN, 1); elseif (power == 3) then -- target:delMod(MOD_FOOD_DURATION), ???); -- food duration not implemented. end end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/death_scythe_+1.lua
41
1069
----------------------------------------- -- ID: 16791 -- Item: Death Scythe +1 -- Additional Effect: Drains HP ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local power = 10; local params = {}; params.bonusmab = 0; params.includemab = false; power = addBonusesAbility(player, ELE_DARK, target, power, params); power = power * applyResistanceAddEffect(player,target,ELE_DARK,0); power = adjustForTarget(target,power,ELE_DARK); power = finalMagicNonSpellAdjustments(player,target,ELE_DARK,power ); if (power < 0) then power = 0; else player:addHP(power) end return SUBEFFECT_HP_DRAIN, MSGBASIC_ADD_EFFECT_HP_DRAIN, power; end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Port_Windurst/npcs/Tohopka.lua
13
1047
----------------------------------- -- Area: Port Windurst -- NPC: Tohopka -- Type: Standard NPC -- @zone: 240 -- @pos -105.723 -10 83.813 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0166); 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
vonflynee/opencomputersserver
world/opencomputers/689b9f29-1d36-4106-bf0e-c06a2ebfb1ef/bin/lua.lua
13
4399
local component = require("component") local package = require("package") local term = require("term") local serialization = require("serialization") local shell = require("shell") local args, options = shell.parse(...) local env = setmetatable({}, {__index = _ENV}) if #args > 0 then local script, reason = loadfile(args[1], nil, env) if not script then io.stderr:write(tostring(reason) .. "\n") os.exit(false) end local result, reason = pcall(script, table.unpack(args, 2)) if not result then io.stderr:write(reason) os.exit(false) end end if #args == 0 or options.i then local function optrequire(...) local success, module = pcall(require, ...) if success then return module end end setmetatable(env, { __index = function(t, k) _ENV[k] = _ENV[k] or optrequire(k) return _ENV[k] end, __pairs = function(self) local t = self return function(_, key) local k, v = next(t, key) if not k and t == env then t = _ENV k, v = next(t) end if not k and t == _ENV then t = package.loaded k, v = next(t) end return k, v end end }) local history = {} local function findTable(t, path) if type(t) ~= "table" then return nil end if not path or #path == 0 then return t end local name = string.match(path, "[^.]+") for k, v in pairs(t) do if k == name then return findTable(v, string.sub(path, #name + 2)) end end local mt = getmetatable(t) if t == env then mt = {__index=_ENV} end if mt then return findTable(mt.__index, path) end return nil end local function findKeys(t, r, prefix, name) if type(t) ~= "table" then return end for k, v in pairs(t) do if string.match(k, "^"..name) then local postfix = "" if type(v) == "function" then postfix = "()" elseif type(v) == "table" and getmetatable(v) and getmetatable(v).__call then postfix = "()" elseif type(v) == "table" then postfix = "." end r[prefix..k..postfix] = true end end local mt = getmetatable(t) if t == env then mt = {__index=_ENV} end if mt then return findKeys(mt.__index, r, prefix, name) end end local function hint(line, index) line = (line or ""):sub(1, index - 1) local path = string.match(line, "[a-zA-Z_][a-zA-Z0-9_.]*$") if not path then return nil end local suffix = string.match(path, "[^.]+$") or "" local prefix = string.sub(path, 1, #path - #suffix) local t = findTable(env, prefix) if not t then return nil end local r1, r2 = {}, {} findKeys(t, r1, string.sub(line, 1, #line - #suffix), suffix) for k in pairs(r1) do table.insert(r2, k) end table.sort(r2) return r2 end component.gpu.setForeground(0xFFFFFF) term.write(_VERSION .. " Copyright (C) 1994-2015 Lua.org, PUC-Rio\n") component.gpu.setForeground(0xFFFF00) term.write("Enter a statement and hit enter to evaluate it.\n") term.write("Prefix an expression with '=' to show its value.\n") term.write("Press Ctrl+C to exit the interpreter.\n") component.gpu.setForeground(0xFFFFFF) while term.isAvailable() do local foreground = component.gpu.setForeground(0x00FF00) term.write(tostring(env._PROMPT or "lua> ")) component.gpu.setForeground(foreground) local command = term.read(history, nil, hint) if command == nil then -- eof return end while #history > 10 do table.remove(history, 1) end local code, reason if string.sub(command, 1, 1) == "=" then code, reason = load("return " .. string.sub(command, 2), "=stdin", "t", env) else code, reason = load(command, "=stdin", "t", env) end if code then local result = table.pack(xpcall(code, debug.traceback)) if not result[1] then if type(result[2]) == "table" and result[2].reason == "terminated" then os.exit(result[2].code) end io.stderr:write(tostring(result[2]) .. "\n") else for i = 2, result.n do term.write(serialization.serialize(result[i], true) .. "\t", true) end if term.getCursor() > 1 then term.write("\n") end end else io.stderr:write(tostring(reason) .. "\n") end end end
mit
UnfortunateFruit/darkstar
scripts/globals/spells/kurayami_ichi.lua
11
1059
----------------------------------------- -- Spell: Kurayami:Ichi ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- Base Stats local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration Calculation local duration = 180 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Kurayami base power is 20 and is not affected by resistaces. local power = 20; --Calculates resist chance from Reist Blind if(math.random(0,100) >= target:getMod(MOD_BLINDRES)) then if(duration >= 80) then if(target:addStatusEffect(EFFECT_BLINDNESS,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end else spell:setMsg(284); end return EFFECT_BLINDNESS; end;
gpl-3.0
p00ria/Signal
plugins/owners.lua
1467
12478
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
zuzuf/TA3D
src/ta3d/mods/ta3d/scripts/corgol.lua
2
6604
-- CORGOL createUnitScript("corgol") __this:piece( "base", "body", "turret1", "sleeve1", "barrel1", "firepoint1", "turret2", "sleeve2", "barrel2", "firepoint2", "tracks1", "tracks2", "tracks3", "wheels1", "wheels2", "wheels3", "wheels4", "wheels5", "wheels6" ) __this.moving = false __this.once = 0 __this.animCount = 0 -- Signal definitions local ANIM_SPEED = 0.05 local RESTORE_DELAY = 3.0 __this.SMOKEPIECE1 = __this.body __this.SMOKEPIECE2 = __this.turret1 #include "exptype.lh" #include "smokeunit.lh" #include "hitweap.lh" __this.RestoreAfterDelay = function(this, delay) this.restoreCount = this.restoreCount + 1 local ncall = this.restoreCount this:sleep( delay ) if ncall ~= this.restoreCount then return end this:turn( this.turret1, y_axis, 0, 45 ) this:turn( this.sleeve1, x_axis, 0, 15 ) this:turn( this.turret2, y_axis, 0, 120 ) this:turn( this.sleeve2, x_axis, 0, 90 ) end __this.AnimationControl = function(this) local current_track = 0 while true do if this.moving or this.once > 0 then if current_track == 0 then this:show( this.tracks1 ) this:hide( this.tracks3 ) current_track = 1 elseif current_track == 1 then this:show( this.tracks2 ) this:hide( this.tracks1 ) current_track = 2 elseif current_track == 2 then this:show( this.tracks3 ) this:hide( this.tracks2 ) current_track = 0 if this.once > 0 then this.once = this.once - 1 end end this.animCount = this.animCount + 1 end this:sleep( ANIM_SPEED ) end end __this.StartMoving = function(this) this.moving = true this.animCount = 0 this:spin( this.wheels1, x_axis, 360, 60 ) this:spin( this.wheels6, x_axis, 360, 60 ) this:spin( this.wheels2, x_axis, 480, 120 ) this:spin( this.wheels3, x_axis, 480, 120 ) this:spin( this.wheels4, x_axis, 480, 120 ) this:spin( this.wheels5, x_axis, 480, 120 ) end __this.StopMoving = function(this) this.moving = false -- I don't like insta braking. It's not perfect but works for most cases. -- Probably looks goofy when the unit is turtling around, i.e. does not get faster as time increases.. this.once = this.animCount * ANIM_SPEED / 1000 if this.once > 3 then this.once = 3 end this:stop_spin( this.wheels1, x_axis, 15 ) this:stop_spin( this.wheels6, x_axis, 15 ) this:stop_spin( this.wheels2, x_axis, 45 ) this:stop_spin( this.wheels3, x_axis, 45 ) this:stop_spin( this.wheels4, x_axis, 45 ) this:stop_spin( this.wheels5, x_axis, 45 ) end -- Weapons __this.AimFromPrimary = function(this) return this.turret1 end __this.QueryPrimary = function(this) return this.firepoint1 end __this.AimPrimary = function(this, heading, pitch) this:set_script_value("AimPrimary", false) heading = heading * TA2DEG pitch = pitch * TA2DEG this:turn( this.turret1, y_axis, heading, 90 ) this:turn( this.sleeve1, x_axis, -pitch, 45 ) if this.aiming1 then return end this.aiming1 = true while this:is_turning( this.turret1, y_axis ) or this:is_turning( this.sleeve1, x_axis ) do yield() end this.aiming1 = false this:start_script( this.RestoreAfterDelay, this, RESTORE_DELAY ) this:set_script_value("AimPrimary", true) end __this.FirePrimary = function(this) this:move_piece_now( this.barrel1, z_axis, -2.5 ) this:sleep( 0.125 ) this:move( this.barrel1, z_axis, 0, 5 ) end __this.AimFromSecondary = function(this) return this.turret2 end __this.QuerySecondary = function(this) return this.firepoint2 end __this.AimSecondary = function(this, heading, pitch) this:set_script_value("AimSecondary", false) heading = heading * TA2DEG pitch = pitch * TA2DEG this:turn( this.turret2, y_axis, heading, 360 ) this:turn( this.sleeve2, x_axis, -pitch, 180 ) if this.aiming2 then return end this.aiming2 = true while this:is_turning( this.turret2, y_axis ) or this:is_turning( this.sleeve2, x_axis ) do yield() end this.aiming2 = false this:start_script( this.RestoreAfterDelay, this, RESTORE_DELAY ) this:set_script_value("AimSecondary", true) end __this.FireSecondary = function(this) this:move_piece_now( this.barrel2, z_axis, -0.25 ) this:move( this.barrel2, z_axis, 0, 5 ) end __this.Killed = function(this, severity) if severity >= 0 and severity < 25 then this:explode( this.barrel1, BITMAPONLY + BITMAP ) this:explode( this.sleeve1, BITMAPONLY + BITMAP ) this:explode( this.barrel2, BITMAPONLY + BITMAP ) this:explode( this.turret1, BITMAPONLY + BITMAP ) this:explode( this.turret2, BITMAPONLY + BITMAP ) this:explode( this.body, BITMAPONLY + BITMAP ) return 1 elseif severity >= 25 and severity < 50 then this:explode( this.barrel1, FALL + BITMAP ) this:explode( this.barrel2, SHATTER + BITMAP ) this:explode( this.sleeve1, FALL + BITMAP ) this:explode( this.turret1, SHATTER + BITMAP ) this:explode( this.turret2, FALL + BITMAP ) this:explode( this.body, BITMAPONLY + BITMAP ) return 2 elseif severity >= 50 and severity < 100 then this:explode( this.barrel1, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.barrel2, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.sleeve1, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.turret1, SHATTER + BITMAP ) this:explode( this.turret2, SHATTER + BITMAP ) this:explode( this.body, BITMAPONLY + BITMAP ) return 3 -- D-Gunned/Self-D elseif severity >= 100 then this:explode( this.barrel1, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.barrel2, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.sleeve1, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.turret1, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.turret2, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.body, SHATTER + BITMAP ) return 3 end end __this.Create = function(this) this.moving = false this.restoreCount = 0 this.aiming1 = false this.aiming2 = false this:hide( this.tracks1 ) this:hide( this.tracks2 ) while this:get(BUILD_PERCENT_LEFT) > 0 do this:sleep( 0.25 ) end this:start_script( this.AnimationControl, this ) this:start_script( this.SmokeUnit, this ) end
gpl-2.0
nesstea/darkstar
scripts/zones/Empyreal_Paradox/mobs/Promathia_2.lua
8
2578
----------------------------------- -- Area: Empyreal Paradox -- MOB: Promathia (phase 2) ----------------------------------- package.loaded["scripts/zones/Empyreal_Paradox/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Empyreal_Paradox/TextIDs"); require("scripts/globals/status"); require("scripts/globals/titles"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 50); mob:addMod(MOD_UFASTCAST,50); end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob,target) local bcnmAllies = mob:getBattlefield():getAllies(); for i,v in pairs(bcnmAllies) do if (v:getName() == "Prishe") then if not v:getTarget() then v:entityAnimationPacket("prov"); v:showText(v, PRISHE_TEXT + 1); v:setLocalVar("ready", mob:getID()); end else v:addEnmity(mob,0,1); end end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) if (mob:AnimationSub() == 3 and not mob:hasStatusEffect(EFFECT_STUN)) then mob:AnimationSub(0); mob:stun(1500); elseif (mob:AnimationSub() == 2 and not mob:hasStatusEffect(EFFECT_MAGIC_SHIELD)) then mob:AnimationSub(0); elseif (mob:AnimationSub() == 1 and not mob:hasStatusEffect(EFFECT_PHYSICAL_SHIELD)) then mob:AnimationSub(0); end local bcnmAllies = mob:getBattlefield():getAllies(); for i,v in pairs(bcnmAllies) do if not v:getTarget() then v:addEnmity(mob,0,1); end end end; ------------------------------------ -- onSpellPrecast ------------------------------------ function onSpellPrecast(mob, spell) if (spell:getID() == 218) then spell:setAoE(SPELLAOE_RADIAL); spell:setFlag(SPELLFLAG_HIT_ALL); spell:setRadius(30); spell:setAnimation(280); spell:setMPCost(1); elseif (spell:getID() == 219) then spell:setMPCost(1); end end; ------------------------------------ -- onMagicCastingCheck ------------------------------------ function onMagicCastingCheck(mob, target, spell) if math.random() > 0.75 then return 219; else return 218; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) end;
gpl-3.0
akdor1154/awesome
lib/wibox/layout/mirror.lua
1
3648
--------------------------------------------------------------------------- -- @author dodo -- @copyright 2012 dodo -- @release @AWESOME_VERSION@ -- @classmod wibox.layout.mirror --------------------------------------------------------------------------- local type = type local error = error local pairs = pairs local ipairs = ipairs local setmetatable = setmetatable local base = require("wibox.widget.base") local matrix = require("gears.matrix") local mirror = { mt = {} } --- Layout this layout function mirror:layout(_, width, height) if not self.widget then return end local m = matrix.identity local t = { x = 0, y = 0 } -- translation local s = { x = 1, y = 1 } -- scale if self.horizontal then t.x = width s.x = -1 end if self.vertical then t.y = height s.y = -1 end m = m:translate(t.x, t.y) m = m:scale(s.x, s.y) return { base.place_widget_via_matrix(self.widget, m, width, height) } end --- Fit this layout into the given area function mirror:fit(context, ...) if not self.widget then return 0, 0 end return base.fit_widget(self, context, self.widget, ...) end --- Set the widget that this layout mirrors. -- @param widget The widget to mirror function mirror:set_widget(widget) if widget then base.check_widget(widget) end self.widget = widget self:emit_signal("widget::layout_changed") end --- Get the number of children element -- @treturn table The children function mirror:get_children() return {self.widget} end --- Replace the layout children -- This layout only accept one children, all others will be ignored -- @tparam table children A table composed of valid widgets function mirror:set_children(children) self:set_widget(children[1]) end --- Reset this layout. The widget will be removed and the axes reset. function mirror:reset() self.horizontal = false self.vertical = false self:set_widget(nil) end --- Set the reflection of this mirror layout. -- @param reflection a table which contains new values for horizontal and/or vertical (booleans) function mirror:set_reflection(reflection) if type(reflection) ~= 'table' then error("Invalid type of reflection for mirror layout: " .. type(reflection) .. " (should be a table)") end for _, ref in ipairs({"horizontal", "vertical"}) do if reflection[ref] ~= nil then self[ref] = reflection[ref] end end self:emit_signal("widget::layout_changed") end --- Get the reflection of this mirror layout. -- @return a table of booleans with the keys "horizontal", "vertical". function mirror:get_reflection() return { horizontal = self.horizontal, vertical = self.vertical } end --- Returns a new mirror layout. A mirror layout mirrors a given widget. Use -- :set_widget() to set the widget and -- :set_horizontal() and :set_vertical() for the direction. -- horizontal and vertical are by default false which doesn't change anything. -- @param[opt] widget The widget to display. -- @param[opt] reflection A table describing the reflection to apply. local function new(widget, reflection) local ret = base.make_widget() ret.horizontal = false ret.vertical = false for k, v in pairs(mirror) do if type(v) == "function" then ret[k] = v end end ret:set_widget(widget) ret:set_reflection(reflection or {}) return ret end function mirror.mt:__call(...) return new(...) end return setmetatable(mirror, mirror.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
nesstea/darkstar
scripts/zones/Batallia_Downs_[S]/mobs/Gnole.lua
13
1676
----------------------------------- -- Area: Batillia Downs S -- MOB: Gnole ----------------------------------- ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("transformTime", os.time()) end; ----------------------------------- -- onMobRoam Action ----------------------------------- function onMobRoam(mob) local changeTime = mob:getLocalVar("transformTime"); local roamChance = math.random(1,100); local roamMoonPhase = VanadielMoonPhase(); if (roamChance > 100-roamMoonPhase) then if (mob:AnimationSub() == 0 and os.time() - changeTime > 300) then mob:AnimationSub(1); mob:setLocalVar("transformTime", os.time()); elseif (mob:AnimationSub() == 1 and os.time() - changeTime > 300) then mob:AnimationSub(0); mob:setLocalVar("transformTime", os.time()); end end end; ----------------------------------- -- onMobEngaged -- Change forms every 60 seconds ----------------------------------- function onMobEngaged(mob,target) local changeTime = mob:getLocalVar("changeTime"); local chance = math.random(1,100); local moonPhase = VanadielMoonPhase(); if (chance > 100-moonPhase) then if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then mob:AnimationSub(1); mob:setLocalVar("changeTime", mob:getBattleTime()); elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then mob:AnimationSub(0); mob:setLocalVar("changeTime", mob:getBattleTime()); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/serving_of_flounder_meuniere_+1.lua
35
1657
----------------------------------------- -- ID: 4345 -- Item: serving_of_flounder_meuniere_+1 -- Food Effect: 240Min, All Races ----------------------------------------- -- Dexterity 6 -- Vitality 1 -- Mind -1 -- Ranged ACC 15 -- Ranged ATT % 14 -- Ranged ATT Cap 30 -- Enmity -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4345); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 6); target:addMod(MOD_VIT, 1); target:addMod(MOD_MND, -1); target:addMod(MOD_RACC, 15); target:addMod(MOD_FOOD_RATTP, 14); target:addMod(MOD_FOOD_RATT_CAP, 30); target:addMod(MOD_ENMITY, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 6); target:delMod(MOD_VIT, 1); target:delMod(MOD_MND, -1); target:delMod(MOD_RACC, 15); target:delMod(MOD_FOOD_RATTP, 14); target:delMod(MOD_FOOD_RATT_CAP, 30); target:delMod(MOD_ENMITY, -3); end;
gpl-3.0
garyjs/Newfiesautodialer
lua/libs/constant.lua
3
1634
-- -- 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-2013 Star2Billing S.L. -- -- The Initial Developer of the Original Code is -- Arezqui Belaid <info@star2billing.com> -- -- Constant Value SECTION_TYPE PLAY_MESSAGE = "1" MULTI_CHOICE = "2" RATING_SECTION = "3" CAPTURE_DIGITS = "4" RECORD_MSG = "5" CALL_TRANSFER = "6" HANGUP_SECTION = "7" CONFERENCE = "8" DNC = "9" SECTION_TYPE = {} SECTION_TYPE["1"] = "PLAY_MESSAGE" SECTION_TYPE["2"] = "MULTI_CHOICE" SECTION_TYPE["3"] = "RATING_SECTION" SECTION_TYPE["4"] = "CAPTURE_DIGITS" SECTION_TYPE["5"] = "RECORD_MSG" SECTION_TYPE["6"] = "CALL_TRANSFER" SECTION_TYPE["7"] = "HANGUP_SECTION" SECTION_TYPE["8"] = "CONFERENCE" SECTION_TYPE["9"] = "DNC" -- Constant Value SUBSCRIBER_STATUS SUBSCRIBER_PENDING = "1" SUBSCRIBER_PAUSE = "2" SUBSCRIBER_ABORT = "3" SUBSCRIBER_FAIL = "4" SUBSCRIBER_SENT = "5" SUBSCRIBER_IN_PROCESS = "6" SUBSCRIBER_NOT_AUTHORIZED = "7" SUBSCRIBER_COMPLETED = "8" ROOT_DIR = '/usr/share/newfies-lua/' TTS_DIR = ROOT_DIR..'tts/' UPLOAD_DIR = '/usr/share/newfies/usermedia/' AUDIODIR = '/usr/share/newfies/usermedia/tts/' AUDIO_WELCOME = AUDIODIR..'script_9805d01afeec350f36ff3fd908f0cbd5.wav' AUDIO_ENTERAGE = AUDIODIR..'script_4ee73b76b5b4c5d596ed1cb3257861f0.wav' AUDIO_PRESSDIGIT = AUDIODIR..'script_610e09c761c4b592aaa954259ce4ce1d.wav' FS_RECORDING_PATH = '/usr/share/newfies/usermedia/recording/' USE_CACHE = false
mpl-2.0
nesstea/darkstar
scripts/zones/Quicksand_Caves/npcs/qm4.lua
27
1185
----------------------------------- -- Area: Quicksand Caves -- NPC: ??? (qm4) -- Involved in Mission: Bastok 8.1 "The Chains That Bind Us" -- @pos ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Quicksand_Caves/TextIDs"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local missionStatus = player:getVar("MissionStatus"); if (player:getCurrentMission(player:getNation()) == THE_CHAINS_THAT_BIND_US) and (missionStatus == 2) then player:startEvent(0x0A) else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if (csid == 0x0A) then player:setVar("MissionStatus", 3); end end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/melon_pie.lua
17
1251
----------------------------------------- -- ID: 4421 -- Item: melon_pie -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic 25 -- Agility -1 -- Intelligence 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4421); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 25); target:addMod(MOD_AGI, -1); target:addMod(MOD_INT, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 25); target:delMod(MOD_AGI, -1); target:delMod(MOD_INT, 4); end;
gpl-3.0
kirangonella/torch7
CmdLine.lua
62
7104
local CmdLine = torch.class('torch.CmdLine') local function strip(str) return string.match(str, '%-*(.*)') end local function pad(str, sz) return str .. string.rep(' ', sz-#str) end function CmdLine:error(msg) print('') io.stderr:write(msg) print('') self:help() os.exit(1) end function CmdLine:__readArgument__(params, arg, i, nArgument) local argument = self.arguments[nArgument] local value = arg[i] if nArgument > #self.arguments then self:error('invalid argument: ' .. value) end if argument.type and type(value) ~= argument.type then self:error('invalid argument type for argument ' .. argument.key .. ' (should be ' .. argument.type .. ')') end params[strip(argument.key)] = value return 1 end function CmdLine:__readOption__(params, arg, i) local key = arg[i] local option = self.options[key] if not option then self:error('unknown option ' .. key) end if option.type and option.type == 'boolean' then params[strip(key)] = not option.default return 1 else local value = arg[i+1] if not value then self:error('missing argument for option ' .. key) end if not option.type or option.type == 'string' then elseif option.type == 'number' then value = tonumber(value) else self:error('unknown required option type ' .. option.type) end if not value then self:error('invalid type for option ' .. key .. ' (should be ' .. option.type .. ')') end params[strip(key)] = value return 2 end end function CmdLine:__init(argseparator_,keyseparator_) self.argseparator = argseparator_ or ',' self.keyseparator = keyseparator_ or '=' self.options = {} self.arguments = {} self.helplines = {} self.dateformat = nil self.silentio = false end function CmdLine:silent() self.silentio = true end function CmdLine:addTime(name, format) format = format or '%F %T' if type(format) ~= 'string' then error('Argument has to be string') end if name ~= nil then name = '[' .. name .. ']: ' else name = '' end self.dateformat = format .. name end function CmdLine:argument(key, help, _type_) table.insert(self.arguments, {key=key, help=help, type=_type_}) table.insert(self.helplines, self.arguments[#self.arguments]) end function CmdLine:option(key, default, help, _type_) if default == nil then error('option ' .. key .. ' has no default value') end _type_ = _type_ or type(default) if type(default) ~= _type_ then error('option ' .. key .. ' has wrong default type value') end self.options[key] = {key=key, default=default, help=help, type=_type_} table.insert(self.helplines, self.options[key]) end function CmdLine:default() local params = {} for option,v in pairs(self.options) do params[strip(option)] = v.default end return params end function CmdLine:parse(arg) local i = 1 local params = self:default() local nArgument = 0 while i <= #arg do if arg[i] == '-help' or arg[i] == '-h' or arg[i] == '--help' then self:help(arg) os.exit(0) end if self.options[arg[i]] then i = i + self:__readOption__(params, arg, i) else nArgument = nArgument + 1 i = i + self:__readArgument__(params, arg, i, nArgument) end end if nArgument ~= #self.arguments then self:error('not enough arguments') end return params end function CmdLine:string(prefix, params, ignore) local arguments = {} local options = {} prefix = prefix or '' for k,v in pairs(params) do if ignore[k] then print('-- ignore option ' .. k) elseif self.options['-' .. k] then if v ~= self.options['-' .. k].default or ignore[k] == false then if type(v) == 'boolean' then if v then v = 't' else v = 'f' end end table.insert(options, k .. self.keyseparator .. v) print(k,v,self.options['-' .. k].default) end else local narg for i=1,#self.arguments do if strip(self.arguments[i].key) == k then narg = i end end if narg then arguments[narg] = k .. self.keyseparator .. v else print('WARNING: unknown option/argument: ' .. k .. ' IGNORING for DIRECTORY NAME') end end end table.sort(options) local str = table.concat(arguments, self.argseparator) if str == '' then str = table.concat(options, self.argseparator) else str = str .. self.argseparator .. table.concat(options, self.argseparator) end if str == '' then return prefix else return prefix .. self.argseparator .. str end end local oprint = print function CmdLine:log(file, params) local f = io.open(file, 'w') function print(...) local n = select("#", ...) local arg = {...} if not self.silentio then oprint(...) end local str = {} if self.dateformat then table.insert(str, os.date(self.dateformat)) end for i=1,n do table.insert(str,tostring(arg[i])) end table.insert(str,'\n') f:write(table.concat(str,' ')) f:flush() end print('[program started on ' .. os.date() .. ']') print('[command line arguments]') if params then for k,v in pairs(params) do print(k,v) end end print('[----------------------]') end function CmdLine:text(txt) txt = txt or '' assert(type(txt) == 'string') table.insert(self.helplines, txt) end function CmdLine:help(arg) io.write('Usage: ') if arg then io.write(arg[0] .. ' ') end io.write('[options] ') for i=1,#self.arguments do io.write('<' .. strip(self.arguments[i].key) .. '>') end io.write('\n') -- first pass to compute max length local optsz = 0 for _,option in ipairs(self.helplines) do if type(option) == 'table' then if option.default ~= nil then -- it is an option if #option.key > optsz then optsz = #option.key end else -- it is an argument if #strip(option.key)+2 > optsz then optsz = #strip(option.key)+2 end end end end -- second pass to print for _,option in ipairs(self.helplines) do if type(option) == 'table' then io.write(' ') if option.default ~= nil then -- it is an option io.write(pad(option.key, optsz)) if option.help then io.write(' ' .. option.help) end io.write(' [' .. tostring(option.default) .. ']') else -- it is an argument io.write(pad('<' .. strip(option.key) .. '>', optsz)) if option.help then io.write(' ' .. option.help) end end else io.write(option) -- just some additional help end io.write('\n') end end
bsd-3-clause
nesstea/darkstar
scripts/zones/Metalworks/npcs/Ayame.lua
12
2954
----------------------------------- -- Area: Metalworks -- NPC: Ayame -- Involved in Missions -- Starts and Finishes Quest: True Strength -- @pos 133 -19 34 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,TRUE_STRENGTH) == QUEST_ACCEPTED) then if (trade:hasItemQty(1100,1) and trade:getItemCount() == 1) then -- Trade Xalmo Feather player:startEvent(0x02ed); -- Finish Quest "True Strength" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local trueStrength = player:getQuestStatus(BASTOK,TRUE_STRENGTH); local WildcatBastok = player:getVar("WildcatBastok"); if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,9) == false) then player:startEvent(0x03a7); elseif (player:getCurrentMission(BASTOK) == THE_CRYSTAL_LINE and player:hasKeyItem(C_L_REPORTS)) then player:startEvent(0x02c8); elseif (trueStrength == QUEST_AVAILABLE and player:getMainJob() == 2 and player:getMainLvl() >= 50) then player:startEvent(0x02ec); -- Start Quest "True Strength" else player:startEvent(0x02bd); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x02c8) then finishMissionTimeline(player,1,csid,option); elseif (csid == 0x02ec) then player:addQuest(BASTOK,TRUE_STRENGTH); elseif (csid == 0x02ed) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14215); -- Temple Hose else player:tradeComplete(); player:addTitle(PARAGON_OF_MONK_EXCELLENCE); player:addItem(14215); player:messageSpecial(ITEM_OBTAINED,14215); -- Temple Hose player:addFame(BASTOK,AF3_FAME); player:completeQuest(BASTOK,TRUE_STRENGTH); end elseif (csid == 0x03a7) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",9,true); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Port_San_dOria/npcs/Ceraulian.lua
11
5366
----------------------------------- -- Area: Port San d'Oria -- NPC: Ceraulian -- Involved in Quest: The Holy Crest -- @pos 0 -8 -122 232 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,CHASING_QUOTAS) == QUEST_ACCEPTED and player:getVar("ChasingQuotas_Progress") == 0 and trade:getItemCount() == 1 and trade:hasItemQty(12494,1) and trade:getGil() == 0) then -- Trading gold hairpin only player:tradeComplete(); player:startEvent(17); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Quotas_Status = player:getQuestStatus(SANDORIA,CHASING_QUOTAS); local Quotas_Progress = player:getVar("ChasingQuotas_Progress"); local Quotas_No = player:getVar("ChasingQuotas_No"); local Stalker_Status = player:getQuestStatus(SANDORIA,KNIGHT_STALKER); local Stalker_Progress = player:getVar("KnightStalker_Progress"); if (player:getMainLvl() >= ADVANCED_JOB_LEVEL and player:getQuestStatus(SANDORIA,THE_HOLY_CREST) == QUEST_AVAILABLE) then player:startEvent(0x0018); -- Chasing Quotas (DRG AF2) elseif (Quotas_Status == QUEST_AVAILABLE and player:getMainJob() == 14 and player:getMainLvl() >= AF1_QUEST_LEVEL and Quotas_No == 0) then player:startEvent(18); -- Long version of quest start elseif (Quotas_No == 1) then player:startEvent(14); -- Short version for those that said no. elseif (Quotas_Status == QUEST_ACCEPTED and Quotas_Progress == 0) then players:startEvent(13); -- Reminder to bring Gold Hairpin elseif (Quotas_Progress == 1) then if (player:getVar("ChasingQuotas_date") > os.time()) then player:startEvent(3); -- Fluff cutscene because you haven't waited a day else player:startEvent(7); -- Boss got mugged end elseif (Quotas_Progress == 2) then player:startEvent(8); -- Go investigate elseif (Quotas_Progress == 3) then player:startEvent(6); -- Earring is a clue, non-required CS elseif (Quotas_Progress == 4 or Quotas_Progress == 5) then player:startEvent(9); -- Fluff text until Ceraulian is necessary again elseif (Quotas_Progress == 6) then player:startEvent(15); -- End of AF2 elseif (Quotas_Status == QUEST_COMPLETED and Stalker_Status == QUEST_AVAILABLE) then player:startEvent(16); -- Fluff text until DRG AF3 -- Knight Stalker (DRG AF3) elseif (Stalker_Status == QUEST_ACCEPTED and Stalker_Progress == 0) then player:startEvent(19); -- Fetch the last Dragoon's helmet elseif (Stalker_Progress == 1) then if (player:hasKeyItem(CHALLENGE_TO_THE_ROYAL_KNIGHTS) == false) then player:startEvent(23); -- Reminder to get helmet else player:startEvent(20); -- Response if you try to turn in the challenge to Ceraulian end elseif (player:getVar("KnightStalker_Option1") == 1) then player:startEvent(22); elseif (Stalker_Status == QUEST_COMPLETED) then player:startEvent(21); else player:startEvent(0x024b); 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 == 0x0018) then player:setVar("TheHolyCrest_Event",1); -- Chasing Quotas (DRG AF2) elseif (csid == 18) then if option == 0 then player:setVar("ChasingQuotas_No",1); else player:addQuest(SANDORIA,CHASING_QUOTAS); end elseif (csid == 14 and option == 1) then player:setVar("ChasingQuotas_No",0); player:addQuest(SANDORIA,CHASING_QUOTAS); elseif (csid == 17) then player:setVar("ChasingQuotas_Progress",1); player:setVar("ChasingQuotas_date", getMidnight()); elseif (csid == 7) then player:setVar("ChasingQuotas_Progress",2); player:setVar("ChasingQuotas_date",0); elseif (csid == 15) then if (player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14227); else player:delKeyItem(RANCHURIOMES_LEGACY); player:addItem(14227); player:messageSpecial(ITEM_OBTAINED,14227); -- Drachen Brais player:addFame(SANDORIA,AF2_FAME); player:completeQuest(SANDORIA,CHASING_QUOTAS); player:setVar("ChasingQuotas_Progress",0); end -- Knight Stalker (DRG AF3) elseif (csid == 19) then player:setVar("KnightStalker_Progress",1); elseif (csid == 22) then player:setVar("KnightStalker_Option1",0); end end;
gpl-3.0
NezzKryptic/Wire-Extras
lua/entities/gmod_wire_hud_indicator_2/expressions/expr_stack.lua
3
1462
EXPR_Stack = {} function EXPR_Stack:new() local obj = {} setmetatable( obj, {__index = EXPR_Stack} ) obj.elements = {} return obj end function EXPR_Stack:push( element ) if( element ~= nil ) then table.insert( self.elements, element ) else --Silently die, for now! end end function EXPR_Stack:pop( _type ) if( table.maxn( self.elements ) == 0 ) then return nil end local value = table.remove( self.elements ) if( _type ~= nil and value.value ~= nil and type(value.value) ~= _type ) then self:push( value ) return nil end return value end function EXPR_Stack:size() return table.maxn( self.elements ) end function EXPR_Stack:collapse() local output = "" for key, tok in pairs(self.elements) do output = output .. tostring(tok.value) end return output end function EXPR_Stack:peek( depth ) local depth = depth or 0 local size = self:size() return self.elements[size+depth] end function EXPR_Stack:peekTop() local tok = self:pop() self:push( tok ) return tok end function EXPR_Stack:print( prefix ) local buffer = prefix or "STACK: " for key, value in pairs( self.elements) do if( type(value) == "table" and value.value ~= nil ) then buffer = buffer .. ",[" .. tostring(value.type) .. " " .. tostring(value.value) .. " " .. tostring(value.depth) .. "] " else buffer = buffer .. ",[" .. tostring(value) .. "] " end end print( buffer ) end function EXPR_Stack:clear() self.elements = {} end
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/spells/cure_vi.lua
13
3520
----------------------------------------- -- Spell: Cure VI -- Restores target's HP. -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local divisor = 0; local constant = 0; local basepower = 0; local power = 0; local basecure = 0; local final = 0; local minCure = 600; power = getCurePower(caster); if(power < 210) then divisor = 1.5; constant = 600; basepower = 90; elseif(power < 300) then divisor = 0.9; constant = 680; basepower = 210; elseif(power < 400) then divisor = 10/7; constant = 780; basepower = 300; elseif(power < 500) then divisor = 2.5; constant = 850; basepower = 400; elseif(power < 700) then divisor = 5/3; constant = 890; basepower = 500; else divisor = 999999; constant = 1010; basepower = 0; end if(target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then basecure = getBaseCure(power,divisor,constant,basepower); final = getCureFinal(caster,spell,basecure,minCure,false); if(caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then local solaceStoneskin = 0; local equippedBody = caster:getEquipID(SLOT_BODY); if(equippedBody == 11186) then solaceStoneskin = math.floor(final * 0.30); elseif(equippedBody == 11086) then solaceStoneskin = math.floor(final * 0.35); else solaceStoneskin = math.floor(final * 0.25); end target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25); end; final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; local diff = (target:getMaxHP() - target:getHP()); if(final > diff) then final = diff; end target:restoreHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); else if(target:isUndead()) then spell:setMsg(2); local dmg = calculateMagicDamage(minCure,1,caster,spell,target,HEALING_MAGIC_SKILL,MOD_MND,false)*0.5; local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),HEALING_MAGIC_SKILL,1.0); dmg = dmg*resist; dmg = addBonuses(caster,spell,target,dmg); dmg = adjustForTarget(target,dmg,spell:getElement()); dmg = finalMagicAdjustments(caster,target,spell,dmg); final = dmg; target:delHP(final); target:updateEnmityFromDamage(caster,final); elseif(caster:getObjType() == TYPE_PC) then spell:setMsg(75); else -- e.g. monsters healing themselves. if(USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); local diff = (target:getMaxHP() - target:getHP()); if(final > diff) then final = diff; end target:addHP(final); end end return final; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Baya_Hiramayuh.lua
24
1486
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Baya Hiramayuh -- 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) -- Based on scripts/zones/Mhaura/Dieh_Yamilsiah.lua local timer = 1152 - ((os.time() - 1009811376)%1152); local direction = 0; -- Arrive, 1 for depart local waiting = 195; -- Offset for Mhaura if (timer <= waiting) then direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart" else timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival end player:startEvent(232,timer,direction); 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
Mashape/kong
kong/plugins/jwt/handler.lua
1
7830
local constants = require "kong.constants" local jwt_decoder = require "kong.plugins.jwt.jwt_parser" local fmt = string.format local kong = kong local type = type local ipairs = ipairs local tostring = tostring local re_gmatch = ngx.re.gmatch local JwtHandler = {} JwtHandler.PRIORITY = 1005 JwtHandler.VERSION = "2.1.0" --- Retrieve a JWT in a request. -- Checks for the JWT in URI parameters, then in cookies, and finally -- in the configured header_names (defaults to `[Authorization]`). -- @param request ngx request object -- @param conf Plugin configuration -- @return token JWT token contained in request (can be a table) or nil -- @return err local function retrieve_token(conf) local args = kong.request.get_query() for _, v in ipairs(conf.uri_param_names) do if args[v] then return args[v] end end local var = ngx.var for _, v in ipairs(conf.cookie_names) do local cookie = var["cookie_" .. v] if cookie and cookie ~= "" then return cookie end end local request_headers = kong.request.get_headers() for _, v in ipairs(conf.header_names) do local token_header = request_headers[v] if token_header then if type(token_header) == "table" then token_header = token_header[1] end local iterator, iter_err = re_gmatch(token_header, "\\s*[Bb]earer\\s+(.+)") if not iterator then kong.log.err(iter_err) break end local m, err = iterator() if err then kong.log.err(err) break end if m and #m > 0 then return m[1] end end end end local function load_credential(jwt_secret_key) local row, err = kong.db.jwt_secrets:select_by_key(jwt_secret_key) if err then return nil, err end return row end local function set_consumer(consumer, credential, token) local set_header = kong.service.request.set_header local clear_header = kong.service.request.clear_header if consumer and consumer.id then set_header(constants.HEADERS.CONSUMER_ID, consumer.id) else clear_header(constants.HEADERS.CONSUMER_ID) end if consumer and consumer.custom_id then set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id) else clear_header(constants.HEADERS.CONSUMER_CUSTOM_ID) end if consumer and consumer.username then set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username) else clear_header(constants.HEADERS.CONSUMER_USERNAME) end kong.client.authenticate(consumer, credential) if credential then kong.ctx.shared.authenticated_jwt_token = token -- TODO: wrap in a PDK function? ngx.ctx.authenticated_jwt_token = token -- backward compatibility only if credential.username then set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username) else clear_header(constants.HEADERS.CREDENTIAL_USERNAME) end clear_header(constants.HEADERS.ANONYMOUS) else clear_header(constants.HEADERS.CREDENTIAL_USERNAME) set_header(constants.HEADERS.ANONYMOUS, true) end end local function do_authentication(conf) local token, err = retrieve_token(conf) if err then kong.log.err(err) return kong.response.exit(500, { message = "An unexpected error occurred" }) end local token_type = type(token) if token_type ~= "string" then if token_type == "nil" then return false, { status = 401, message = "Unauthorized" } elseif token_type == "table" then return false, { status = 401, message = "Multiple tokens provided" } else return false, { status = 401, message = "Unrecognizable token" } end end -- Decode token to find out who the consumer is local jwt, err = jwt_decoder:new(token) if err then return false, { status = 401, message = "Bad token; " .. tostring(err) } end local claims = jwt.claims local header = jwt.header local jwt_secret_key = claims[conf.key_claim_name] or header[conf.key_claim_name] if not jwt_secret_key then return false, { status = 401, message = "No mandatory '" .. conf.key_claim_name .. "' in claims" } elseif jwt_secret_key == "" then return false, { status = 401, message = "Invalid '" .. conf.key_claim_name .. "' in claims" } end -- Retrieve the secret local jwt_secret_cache_key = kong.db.jwt_secrets:cache_key(jwt_secret_key) local jwt_secret, err = kong.cache:get(jwt_secret_cache_key, nil, load_credential, jwt_secret_key) if err then kong.log.err(err) return kong.response.exit(500, { message = "An unexpected error occurred" }) end if not jwt_secret then return false, { status = 401, message = "No credentials found for given '" .. conf.key_claim_name .. "'" } end local algorithm = jwt_secret.algorithm or "HS256" -- Verify "alg" if jwt.header.alg ~= algorithm then return false, {status = 401, message = "Invalid algorithm"} end local jwt_secret_value = algorithm ~= nil and algorithm:sub(1, 2) == "HS" and jwt_secret.secret or jwt_secret.rsa_public_key if conf.secret_is_base64 then jwt_secret_value = jwt:base64_decode(jwt_secret_value) end if not jwt_secret_value then return false, { status = 401, message = "Invalid key/secret" } end -- Now verify the JWT signature if not jwt:verify_signature(jwt_secret_value) then return false, { status = 401, message = "Invalid signature" } end -- Verify the JWT registered claims local ok_claims, errors = jwt:verify_registered_claims(conf.claims_to_verify) if not ok_claims then return false, { status = 401, errors = errors } end -- Verify the JWT registered claims if conf.maximum_expiration ~= nil and conf.maximum_expiration > 0 then local ok, errors = jwt:check_maximum_expiration(conf.maximum_expiration) if not ok then return false, { status = 401, errors = errors } end end -- Retrieve the consumer local consumer_cache_key = kong.db.consumers:cache_key(jwt_secret.consumer.id) local consumer, err = kong.cache:get(consumer_cache_key, nil, kong.client.load_consumer, jwt_secret.consumer.id, true) if err then return kong.response.exit(500, { message = "An unexpected error occurred" }) end -- However this should not happen if not consumer then return false, { status = 401, message = fmt("Could not find consumer for '%s=%s'", conf.key_claim_name, jwt_secret_key) } end set_consumer(consumer, jwt_secret, token) return true end function JwtHandler:access(conf) -- check if preflight request and whether it should be authenticated if not conf.run_on_preflight and kong.request.get_method() == "OPTIONS" then return end if conf.anonymous and kong.client.get_credential() then -- we're already authenticated, and we're configured for using anonymous, -- hence we're in a logical OR between auth methods and we're already done. return end local ok, err = do_authentication(conf) if not ok then if conf.anonymous then -- get anonymous user local consumer_cache_key = kong.db.consumers:cache_key(conf.anonymous) local consumer, err = kong.cache:get(consumer_cache_key, nil, kong.client.load_consumer, conf.anonymous, true) if err then kong.log.err("failed to load anonymous consumer:", err) return kong.response.exit(500, { message = "An unexpected error occurred" }) end set_consumer(consumer, nil, nil) else return kong.response.exit(err.status, err.errors or { message = err.message }) end end end return JwtHandler
apache-2.0
johnmccabe/dockercraft
world/Plugins/APIDump/Classes/Plugins.lua
11
23137
return { cPlugin = { Desc = [[cPlugin describes a Lua plugin. This page is dedicated to new-style plugins and contain their functions. Each plugin has its own Plugin object. ]], Functions = { GetDirectory = { Return = "string", Notes = "<b>OBSOLETE</b>, use GetFolderName() instead!" }, GetFolderName = { Params = "", Return = "string", Notes = "Returns the name of the folder where the plugin's files are. (APIDump)" }, GetLoadError = { Params = "", Return = "string", Notes = "If the plugin failed to load, returns the error message for the failure." }, GetLocalDirectory = { Notes = "<b>OBSOLETE</b>, use GetLocalFolder instead." }, GetLocalFolder = { Return = "string", Notes = "Returns the path where the plugin's files are. (Plugins/APIDump)" }, GetName = { Return = "string", Notes = "Returns the name of the plugin." }, GetStatus = { Params = "", Return = "{{cPluginManager#PluginStatus|PluginStatus}}", Notes = "Returns the status of the plugin (loaded, disabled, unloaded, error, not found)" }, GetVersion = { Return = "number", Notes = "Returns the version of the plugin." }, IsLoaded = { Params = "", Return = "", Notes = "" }, SetName = { Params = "string", Notes = "Sets the name of the Plugin." }, SetVersion = { Params = "number", Notes = "Sets the version of the plugin." }, }, }, -- cPlugin cPluginLua = { Desc = "", Functions = { AddWebTab = { Params = "", Return = "", Notes = "Adds a new webadmin tab" }, }, Inherits = "cPlugin", }, -- cPluginLua cPluginManager = { Desc = [[ This class is used for generic plugin-related functionality. The plugin manager has a list of all plugins, can enable or disable plugins, manages hooks and in-game console commands.</p> <p> Plugins can be identified by either the PluginFolder or PluginName. Note that these two can differ, refer to <a href="http://forum.mc-server.org/showthread.php?tid=1877">the forum</a> for detailed discussion. <p> There is one instance of cPluginManager in Cuberite, to get it, call either {{cRoot|cRoot}}:Get():GetPluginManager() or cPluginManager:Get() function.</p> <p> Note that some functions are "static", that means that they are called using a dot operator instead of the colon operator. For example: <pre class="prettyprint lang-lua"> cPluginManager.AddHook(cPluginManager.HOOK_CHAT, OnChatMessage); </pre></p> ]], Functions = { AddHook = { { Params = "{{cPluginManager#Hooks|HookType}}, [HookFunction]", Return = "", Notes = "(STATIC) Informs the plugin manager that it should call the specified function when the specified hook event occurs. If a function is not specified, a default global function name is looked up, based on the hook type" }, { Params = "{{cPlugin|Plugin}}, {{cPluginManager#Hooks|HookType}}, [HookFunction]", Return = "", Notes = "(STATIC, <b>DEPRECATED</b>) Informs the plugin manager that it should call the specified function when the specified hook event occurs. If a function is not specified, a default function name is looked up, based on the hook type. NOTE: This format is deprecated and the server outputs a warning if it is used!" }, }, BindCommand = { { Params = "Command, Permission, Callback, HelpString", Return = "[bool]", Notes = "(STATIC) Binds an in-game command with the specified callback function, permission and help string. By common convention, providing an empty string for HelpString will hide the command from the /help display. Returns true if successful, logs to console and returns no value on error. The callback uses the following signature: <pre class=\"prettyprint lang-lua\">function(Split, {{cPlayer|Player}})</pre> The Split parameter contains an array-table of the words that the player has sent, Player is the {{cPlayer}} object representing the player who sent the command. If the callback returns true, the command is assumed to have executed successfully; in all other cases the server sends a warning to the player that the command is unknown (this is so that subcommands can be implemented)." }, { Params = "Command, Permission, Callback, HelpString", Return = "[bool]", Notes = "Binds an in-game command with the specified callback function, permission and help string. By common convention, providing an empty string for HelpString will hide the command from the /help display. Returns true if successful, logs to console and returns no value on error. The callback uses the following signature: <pre class=\"prettyprint lang-lua\">function(Split, {{cPlayer|Player}})</pre> The Split parameter contains an array-table of the words that the player has sent, Player is the {{cPlayer}} object representing the player who sent the command. If the callback returns true, the command is assumed to have executed successfully; in all other cases the server sends a warning to the player that the command is unknown (this is so that subcommands can be implemented)." }, }, BindConsoleCommand = { { Params = "Command, Callback, HelpString", Return = "[bool]", Notes = "(STATIC) Binds a console command with the specified callback function and help string. By common convention, providing an empty string for HelpString will hide the command from the \"help\" console command. Returns true if successful, logs to console and returns no value on error. The callback uses the following signature: <pre class=\"prettyprint lang-lua\">function(Split)</pre> The Split parameter contains an array-table of the words that the admin has typed. If the callback returns true, the command is assumed to have executed successfully; in all other cases the server issues a warning to the console that the command is unknown (this is so that subcommands can be implemented)." }, { Params = "Command, Callback, HelpString", Return = "[bool]", Notes = "Binds a console command with the specified callback function and help string. By common convention, providing an empty string for HelpString will hide the command from the \"help\" console command. Returns true if successful, logs to console and returns no value on error. The callback uses the following signature: <pre class=\"prettyprint lang-lua\">function(Split)</pre> The Split parameter contains an array-table of the words that the admin has typed. If the callback returns true, the command is assumed to have executed successfully; in all other cases the server issues a warning to the console that the command is unknown (this is so that subcommands can be implemented)." }, }, CallPlugin = { Params = "PluginName, FunctionName, [FunctionArgs...]", Return = "[FunctionRets]", Notes = "(STATIC) Calls the specified function in the specified plugin, passing all the given arguments to it. If it succeeds, it returns all the values returned by that function. If it fails, returns no value at all. Note that only strings, numbers, bools, nils and classes can be used for parameters and return values; tables and functions cannot be copied across plugins." }, DoWithPlugin = { Params = "PluginName, CallbackFn", Return = "bool", Notes = "(STATIC) Calls the CallbackFn for the specified plugin, if found. A plugin can be found even if it is currently unloaded, disabled or errored, the callback should check the plugin status. If the plugin is not found, this function returns false, otherwise it returns the bool value that the callback has returned. The CallbackFn has the following signature: <pre class=\"prettyprint lang-lua\">function ({{cPlugin|Plugin}})</pre>" }, ExecuteCommand = { Params = "{{cPlayer|Player}}, CommandStr", Return = "{{cPluginManager#CommandResult|CommandResult}}", Notes = "Executes the command as if given by the specified Player. Checks permissions." }, ExecuteConsoleCommand = { Params = "CommandStr", Return = "bool, string", Notes = "Executes the console command as if given by the admin on the console. If the command is successfully executed, returns true and the text that would be output to the console normally. On error it returns false and an error message." }, FindPlugins = { Params = "", Return = "", Notes = "<b>OBSOLETE</b>, use RefreshPluginList() instead"}, ForceExecuteCommand = { Params = "{{cPlayer|Player}}, CommandStr", Return = "{{cPluginManager#CommandResult|CommandResult}}", Notes = "Same as ExecuteCommand, but doesn't check permissions" }, ForEachCommand = { Params = "CallbackFn", Return = "bool", Notes = "Calls the CallbackFn function for each command that has been bound using BindCommand(). The CallbackFn has the following signature: <pre class=\"prettyprint lang-lua\">function(Command, Permission, HelpString)</pre> If the callback returns true, the enumeration is aborted and this API function returns false; if it returns false or no value, the enumeration continues with the next command, and the API function returns true." }, ForEachConsoleCommand = { Params = "CallbackFn", Return = "bool", Notes = "Calls the CallbackFn function for each command that has been bound using BindConsoleCommand(). The CallbackFn has the following signature: <pre class=\"prettyprint lang-lua\">function (Command, HelpString)</pre> If the callback returns true, the enumeration is aborted and this API function returns false; if it returns false or no value, the enumeration continues with the next command, and the API function returns true." }, ForEachPlugin = { Params = "CallbackFn", Return = "bool", Notes = "(STATIC) Calls the CallbackFn function for each plugin that is currently discovered by Cuberite (including disabled, unloaded and errrored plugins). The CallbackFn has the following signature: <pre class=\"prettyprint lang-lua\">function ({{cPlugin|Plugin}})</pre> If the callback returns true, the enumeration is aborted and this API function returns false; if it returns false or no value, the enumeration continues with the next command, and the API function returns true." }, Get = { Params = "", Return = "cPluginManager", Notes = "(STATIC) Returns the single instance of the plugin manager" }, GetAllPlugins = { Params = "", Return = "table", Notes = "Returns a table (dictionary) of all plugins, [name => value], where value is a valid {{cPlugin}} if the plugin is loaded, or the bool value false if the plugin is not loaded." }, GetCommandPermission = { Params = "Command", Return = "Permission", Notes = "Returns the permission needed for executing the specified command" }, GetCurrentPlugin = { Params = "", Return = "{{cPlugin}}", Notes = "Returns the {{cPlugin}} object for the calling plugin. This is the same object that the Initialize function receives as the argument." }, GetNumLoadedPlugins = { Params = "", Return = "number", Notes = "Returns the number of loaded plugins (psLoaded only)" }, GetNumPlugins = { Params = "", Return = "number", Notes = "Returns the number of plugins, including the disabled, errored, unloaded and not-found ones" }, GetPlugin = { Params = "PluginName", Return = "{{cPlugin}}", Notes = "(<b>DEPRECATED, UNSAFE</b>) Returns a plugin handle of the specified plugin, or nil if such plugin is not loaded. Note thatdue to multithreading the handle is not guaranteed to be safe for use when stored - a single-plugin reload may have been triggered in the mean time for the requested plugin." }, GetPluginsPath = { Params = "", Return = "string", Notes = "Returns the path where the individual plugin folders are located. Doesn't include the path separator at the end of the returned string." }, IsCommandBound = { Params = "Command", Return = "bool", Notes = "Returns true if in-game Command is already bound (by any plugin)" }, IsConsoleCommandBound = { Params = "Command", Return = "bool", Notes = "Returns true if console Command is already bound (by any plugin)" }, IsPluginLoaded = { Params = "PluginName", Return = "", Notes = "Returns true if the specified plugin is loaded." }, LoadPlugin = { Params = "PluginFolder", Return = "", Notes = "(<b>DEPRECATED</b>) Loads a plugin from the specified folder. NOTE: Loading plugins may be an unsafe operation and may result in a deadlock or a crash. This API is deprecated and might be removed." }, LogStackTrace = { Params = "", Return = "", Notes = "(STATIC) Logs a current stack trace of the Lua engine to the server console log. Same format as is used when the plugin fails." }, RefreshPluginList = { Params = "", Return = "", Notes = "Refreshes the list of plugins to include all folders inside the Plugins folder (potentially new disabled plugins)" }, ReloadPlugins = { Params = "", Return = "", Notes = "Reloads all active plugins" }, UnloadPlugin = { Params = "PluginName", Return = "", Notes = "Queues the specified plugin to be unloaded. To avoid deadlocks, the unloading happens in the main tick thread asynchronously." }, }, ConstantGroups= { CommandResult = { Include = "^cr.*", TextBefore = [[ Results that the (Force)ExecuteCommand return. This gives information if the command is executed or not and the reason. ]], }, }, Constants = { crBlocked = { Notes = "When a plugin stopped the command using the OnExecuteCommand hook" }, crError = { Notes = "When the command handler for the given command results in an error" }, crExecuted = { Notes = "When the command is successfully executed." }, crNoPermission = { Notes = "When the player doesn't have permission to execute the given command." }, crUnknownCommand = { Notes = "When the given command doesn't exist." }, HOOK_BLOCK_SPREAD = { Notes = "Called when a block spreads based on world conditions" }, HOOK_BLOCK_TO_PICKUPS = { Notes = "Called when a block has been dug and is being converted to pickups. The server has provided the default pickups and the plugins may modify them." }, HOOK_BREWING_COMPLETING = { "Called before a brewing stand completes a brewing process." }, HOOK_BREWING_COMPLETED = { "Called when a brewing stand completed a brewing process." }, HOOK_CHAT = { Notes = "Called when a client sends a chat message that is not a command. The plugin may modify the chat message" }, HOOK_CHUNK_AVAILABLE = { Notes = "Called when a chunk is loaded or generated and becomes available in the {{cWorld|world}}." }, HOOK_CHUNK_GENERATED = { Notes = "Called after a chunk is generated. A plugin may do last modifications on the generated chunk before it is handed of to the {{cWorld|world}}." }, HOOK_CHUNK_GENERATING = { Notes = "Called before a chunk is generated. A plugin may override some parts of the generation algorithm." }, HOOK_CHUNK_UNLOADED = { Notes = "Called after a chunk has been unloaded from a {{cWorld|world}}." }, HOOK_CHUNK_UNLOADING = { Notes = "Called before a chunk is unloaded from a {{cWorld|world}}. The chunk has already been saved." }, HOOK_COLLECTING_PICKUP = { Notes = "Called when a player is about to collect a pickup." }, HOOK_CRAFTING_NO_RECIPE = { Notes = "Called when a player has items in the crafting slots and the server cannot locate any recipe. Plugin may provide a recipe." }, HOOK_DISCONNECT = { Notes = "Called after the player has disconnected." }, HOOK_ENTITY_ADD_EFFECT = { Notes = "Called when an effect is being added to an {{cEntity|entity}}. Plugin may refuse the effect." }, HOOK_ENTITY_CHANGED_WORLD = { Notes = "Called after a entity has changed the world." }, HOOK_ENTITY_CHANGING_WORLD = { Notes = "Called before a entity has changed the world. Plugin may disallow a entity to change the world." }, HOOK_ENTITY_TELEPORT = { Notes = "Called when an {{cEntity|entity}} is being teleported. Plugin may refuse the teleportation." }, HOOK_EXECUTE_COMMAND = { Notes = "Called when a client sends a chat message that is recognized as a command, before handing that command to the regular command handler. A plugin may stop the command from being handled. This hook is called even when the player doesn't have permissions for the command." }, HOOK_EXPLODED = { Notes = "Called after an explosion has been processed in a {{cWorld|world}}." }, HOOK_EXPLODING = { Notes = "Called before an explosion is processed in a {{cWorld|world}}. A plugin may alter the explosion parameters or cancel the explosion altogether." }, HOOK_HANDSHAKE = { Notes = "Called when a Handshake packet is received from a client." }, HOOK_HOPPER_PULLING_ITEM = { Notes = "Called when a hopper is pulling an item from the container above it." }, HOOK_HOPPER_PUSHING_ITEM = { Notes = "Called when a hopper is pushing an item into the container it is aimed at." }, HOOK_KILLED = { Notes = "Called when an entity has been killed." }, HOOK_KILLING = { Notes = "Called when an entity has just been killed. A plugin may resurrect the entity by setting its health to above zero." }, HOOK_LOGIN = { Notes = "Called when a Login packet is sent to the client, before the client is queued for authentication." }, HOOK_PLAYER_ANIMATION = { Notes = "Called when a client send the Animation packet." }, HOOK_PLAYER_BREAKING_BLOCK = { Notes = "Called when a player is about to break a block. A plugin may cancel the event." }, HOOK_PLAYER_BROKEN_BLOCK = { Notes = "Called after a player has broken a block." }, HOOK_PLAYER_DESTROYED = { Notes = "Called when the {{cPlayer}} object is destroyed - a player has disconnected." }, HOOK_PLAYER_EATING = { Notes = "Called when the player starts eating a held item. Plugins may abort the eating." }, HOOK_PLAYER_FISHED = { Notes = "Called when the player reels the fishing rod back in, after the server decides the player's fishing reward." }, HOOK_PLAYER_FISHING = { Notes = "Called when the player reels the fishing rod back in, plugins may alter the fishing reward." }, HOOK_PLAYER_FOOD_LEVEL_CHANGE = { Notes = "Called when the player's food level is changing. Plugins may refuse the change." }, HOOK_PLAYER_JOINED = { Notes = "Called when the player entity has been created. It has not yet been fully initialized." }, HOOK_PLAYER_LEFT_CLICK = { Notes = "Called when the client sends the LeftClick packet." }, HOOK_PLAYER_MOVING = { Notes = "Called when the player has moved and the movement is now being applied." }, HOOK_PLAYER_PLACED_BLOCK = { Notes = "Called when the player has just placed a block" }, HOOK_PLAYER_PLACING_BLOCK = { Notes = "Called when the player is about to place a block. A plugin may cancel the event." }, HOOK_PLAYER_RIGHT_CLICK = { Notes = "Called when the client sends the RightClick packet." }, HOOK_PLAYER_RIGHT_CLICKING_ENTITY = { Notes = "Called when the client sends the UseEntity packet." }, HOOK_PLAYER_SHOOTING = { Notes = "Called when the player releases the mouse button to fire their bow." }, HOOK_PLAYER_SPAWNED = { Notes = "Called after the player entity has been created. The entity is fully initialized and is spawning in the {{cWorld|world}}." }, HOOK_PLAYER_TOSSING_ITEM = { Notes = "Called when the player is tossing the held item (keypress Q)" }, HOOK_PLAYER_USED_BLOCK = { Notes = "Called after the player has right-clicked a block" }, HOOK_PLAYER_USED_ITEM = { Notes = "Called after the player has right-clicked with a usable item in their hand." }, HOOK_PLAYER_USING_BLOCK = { Notes = "Called when the player is about to use (right-click) a block" }, HOOK_PLAYER_USING_ITEM = { Notes = "Called when the player is about to right-click with a usable item in their hand." }, HOOK_PLUGINS_LOADED = { Notes = "Called after all plugins have loaded." }, HOOK_PLUGIN_MESSAGE = { Notes = "Called when a PluginMessage packet is received from a client." }, HOOK_POST_CRAFTING = { Notes = "Called after a valid recipe has been chosen for the current contents of the crafting grid. Plugins may modify the recipe." }, HOOK_PRE_CRAFTING = { Notes = "Called before a recipe is searched for the current contents of the crafting grid. Plugins may provide a recipe and cancel the built-in search." }, HOOK_PROJECTILE_HIT_BLOCK = { Notes = "Called when a {{cProjectileEntity|projectile}} hits a block." }, HOOK_PROJECTILE_HIT_ENTITY = { Notes = "Called when a {{cProjectileEntity|projectile}} hits an {{cEntity|entity}}." }, HOOK_SERVER_PING = { Notes = "Called when a client pings the server from the server list. Plugins may change the favicon, server description, players online and maximum players values." }, HOOK_SPAWNED_ENTITY = { Notes = "Called after an entity is spawned in a {{cWorld|world}}. The entity is already part of the world." }, HOOK_SPAWNED_MONSTER = { Notes = "Called after a mob is spawned in a {{cWorld|world}}. The mob is already part of the world." }, HOOK_SPAWNING_ENTITY = { Notes = "Called just before an entity is spawned in a {{cWorld|world}}." }, HOOK_SPAWNING_MONSTER = { Notes = "Called just before a mob is spawned in a {{cWorld|world}}." }, HOOK_TAKE_DAMAGE = { Notes = "Called when an entity is taking any kind of damage. Plugins may modify the damage value, effects, source or cancel the damage." }, HOOK_TICK = { Notes = "Called when the main server thread ticks - 20 times a second." }, HOOK_UPDATED_SIGN = { Notes = "Called after a {{cSignEntity|sign}} text has been updated, either by a player or by any external means." }, HOOK_UPDATING_SIGN = { Notes = "Called before a {{cSignEntity|sign}} text is updated, either by a player or by any external means." }, HOOK_WEATHER_CHANGED = { Notes = "Called after the weather has changed." }, HOOK_WEATHER_CHANGING = { Notes = "Called just before the weather changes" }, HOOK_WORLD_STARTED = { Notes = "Called when a world has been started." }, HOOK_WORLD_TICK = { Notes = "Called in each world's tick thread when the game logic is about to tick (20 times a second)." }, psDisabled = { Notes = "The plugin is not enabled in settings.ini" }, psError = { Notes = "The plugin is enabled in settings.ini, but it has run into an error while loading. Use {{cPlugin}}:GetLoadError() to identify the error." }, psLoaded = { Notes = "The plugin is enabled and loaded." }, psNotFound = { Notes = "The plugin has been loaded, but is no longer present on disk." }, psUnloaded = { Notes = "The plugin is enabled in settings.ini, but it has been unloaded (by a command)." }, }, -- constants ConstantGroups = { Hooks = { Include = {"HOOK_.*"}, TextBefore = [[ These constants identify individual hooks. To register the plugin to receive notifications on hooks, use the cPluginManager:AddHook() function. For detailed description of each hook, see the <a href='index.html#hooks'> hooks reference</a>.]], }, PluginStatus = { Include = {"ps.*"}, TextBefore = [[ These constants are used to report status of individual plugins. Use {{cPlugin}}:GetStatus() to query the status of a plugin; use cPluginManager::ForEachPlugin() to iterate over plugins.]], }, CommandResult = { Include = {"cr.*"}, TextBefore = [[ These constants are returned by the ExecuteCommand() function to identify the exact outcome of the operation.]], }, }, }, -- cPluginManager }
apache-2.0
UnfortunateFruit/darkstar
scripts/globals/items/ear_of_grilled_corn.lua
35
1298
----------------------------------------- -- ID: 4334 -- Item: ear_of_grilled_corn -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 10 -- Vitality 4 -- Health Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4334); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_VIT, 4); target:addMod(MOD_HPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_VIT, 4); target:delMod(MOD_HPHEAL, 1); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Beaucedine_Glacier/mobs/Calcabrina.lua
7
1944
----------------------------------- -- Area: Beaucedine Glacier -- NM: Calcabrina ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) -- wiki just says "low proc rate". No actual data to go on - going with 15% for now. local chance = 15; local LV_diff = target:getMainLvl() - mob:getMainLvl(); if (target:getMainLvl() > mob:getMainLvl()) then chance = chance - 5 * LV_diff chance = utils.clamp(chance, 5, 95); end if (math.random(0,99) >= chance) then return 0,0,0; else local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT); if (INT_diff > 20) then INT_diff = 20 + (INT_diff - 20) / 2; end local drain = INT_diff+LV_diff+damage/2; local params = {}; params.bonusmab = 0; params.includemab = false; drain = addBonusesAbility(mob, ELE_DARK, target, drain, params); drain = drain * applyResistanceAddEffect(mob,target,ELE_DARK,0); drain = adjustForTarget(target,drain,ELE_DARK); drain = finalMagicNonSpellAdjustments(target,mob,ELE_DARK,drain); if (drain <= 0) then drain = 0; else mob:addHP(drain); end return SUBEFFECT_HP_DRAIN, MSGBASIC_ADD_EFFECT_HP_DRAIN, drain; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random(5400,6000)); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Horlais_Peak/npcs/Burning_Circle.lua
13
2033
----------------------------------- -- Area: Horlais Peak -- NPC: Burning Circle -- Horlais Peak Burning Circle -- @pos -509 158 -211 139 ------------------------------------- package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Horlais_Peak/TextIDs"); --- 0: The Rank 2 Final Mission --- 1: Tails of Woe --- 2: Dismemberment Brigade --- 3: The Secret Weapon (Sandy Mission 7-2) --- 4: Hostile Herbivores --- 5: Shattering Stars (WAR) --- 6: Shattering Stars (BLM) --- 7: Shattering Stars (RNG) --- 8: Carapace Combatants --- 9: Shooting Fish --- 10: Dropping like Flies --- 11: Horns of War --- 12: Under Observation --- 13: Eye of the Tiger --- 14: Shots in the Dark --- 15: Double Dragonian --- 16: Today's Horoscope --- 17: Contaminated Colosseum ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
nesstea/darkstar
scripts/zones/QuBia_Arena/mobs/Rojgnoj_s_Left_Hand.lua
7
1148
----------------------------------- -- Area: QuBia_Arena -- Mission 9-2 SANDO ----------------------------------- ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("2HGO",math.random(40,80)); end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) if (mob:getLocalVar("2HOUR") == 0) then if (mob:getHPP() < mob:getLocalVar("2HGO")) then mob:setLocalVar("2HOUR",1); mob:useMobAbility(691); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) mob:setLocalVar("2HOUR",0); mob:setLocalVar("2HGO",0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) printf("finishCSID: %u",csid); printf("RESULT: %u",option); end;
gpl-3.0
Mashape/kong
kong/cmd/stop.lua
6
1085
local nginx_signals = require "kong.cmd.utils.nginx_signals" local conf_loader = require "kong.conf_loader" local pl_path = require "pl.path" local log = require "kong.cmd.utils.log" local function execute(args, opts) opts = opts or {} log.disable() -- only to retrieve the default prefix or use given one local default_conf = assert(conf_loader(nil, { prefix = args.prefix })) log.enable() assert(pl_path.exists(default_conf.prefix), "no such prefix: " .. default_conf.prefix) if opts.quiet then log.disable() end -- load <PREFIX>/kong.conf containing running node's config local conf = assert(conf_loader(default_conf.kong_env)) assert(nginx_signals.stop(conf)) if opts.quiet then log.enable() end log("Kong stopped") end local lapp = [[ Usage: kong stop [OPTIONS] Stop a running Kong node (Nginx and other configured services) in given prefix directory. This command sends a SIGTERM signal to Nginx. Options: -p,--prefix (optional string) prefix Kong is running at ]] return { lapp = lapp, execute = execute }
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/Beadeaux/npcs/Treasure_Chest.lua
12
2555
----------------------------------- -- Area: Beadeaux -- NPC: Treasure Chest -- @zone 147 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/treasure"); require("scripts/zones/Beadeaux/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --trade:hasItemQty(1034,1); -- Treasure Key --trade:hasItemQty(1115,1); -- Skeleton Key --trade:hasItemQty(1023,1); -- Living Key --trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if((trade:hasItemQty(1034,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if(pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if(success ~= -2) then player:tradeComplete(); if(math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if(loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1034); 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
malortie/gmod-addons
th_weapons/lua/entities/ent_weapon_th_taurus/init.lua
1
1177
-- Only enable this addon if HL:S is mounted. if !IsHL1Mounted() then return end ------------------------------------- -- Weapon 357 spawning. ------------------------------------- AddCSLuaFile('cl_init.lua') AddCSLuaFile('shared.lua') include('shared.lua') -- Define a global variable to ease calling base class methods. DEFINE_BASECLASS( 'base_point' ) --[[--------------------------------------------------------- Called to spawn this entity. @param ply The player spawner. @param tr The trace result from player's eye to the spawn point. @param ClassName The entity's class name. @return true on success. @return false on failure. -----------------------------------------------------------]] function ENT:SpawnFunction( ply, tr, ClassName ) -- Do not spawn at an invalid position. if ( !tr.Hit ) then return end -- Spawn the entity at the hit position, -- facing toward the player. local SpawnPos = tr.HitPos + tr.HitNormal local SpawnAng = ply:EyeAngles() SpawnAng.p = 0 SpawnAng.y = SpawnAng.y + 180 local ent = ents.Create( 'weapon_th_taurus' ) ent:SetPos( SpawnPos ) ent:SetAngles( SpawnAng ) ent:Spawn() ent:Activate() return ent end
gpl-3.0
nesstea/darkstar
scripts/zones/RuLude_Gardens/npcs/Radeivepart.lua
26
2944
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Radeivepart -- Starts and Finishes Quest: Northward -- Involved in Quests: Save the Clock Tower -- @zone 243 -- @pos 5 9 -39 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(555,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then a = player:getVar("saveTheClockTowerNPCz1"); -- NPC Zone1 if (a == 0 or (a ~= 1 and a ~= 3 and a ~= 5 and a ~= 9 and a ~= 17 and a ~= 7 and a ~= 25 and a ~= 11 and a ~= 13 and a ~= 19 and a ~= 21 and a ~= 15 and a ~= 23 and a ~= 27 and a ~= 29 and a ~= 31)) then player:startEvent(0x00a0,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end elseif (player:getQuestStatus(JEUNO,NORTHWARD) == QUEST_ACCEPTED) then if (trade:hasItemQty(16522,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x003d); -- Finish quest "Northward" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getFameLevel(JEUNO) >= 4 and player:getQuestStatus(JEUNO,NORTHWARD) == QUEST_AVAILABLE) then player:startEvent(000); -- Start quest "Northward" CS NOT FOUND else player:startEvent(0x009f); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00a0) then player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1); player:setVar("saveTheClockTowerNPCz1",player:getVar("saveTheClockTowerNPCz1") + 1); elseif (csid == 000 and option == 0) then player:addQuest(JEUNO,NORTHWARD); elseif (csid == 0x003d) then player:completeQuest(JEUNO,NORTHWARD); player:addTitle(ENVOY_TO_THE_NORTH); if (player:hasKeyItem(MAP_OF_CASTLE_ZVAHL) == false) then player:addKeyItem(MAP_OF_CASTLE_ZVAHL); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_CASTLE_ZVAHL); end player:addFame(JEUNO, 30); player:tradeComplete(); end end;
gpl-3.0
ennis/autograph-pipelines
resources/scripts/pl/permute.lua
51
1574
--- Permutation operations. -- -- Dependencies: `pl.utils`, `pl.tablex` -- @module pl.permute local tablex = require 'pl.tablex' local utils = require 'pl.utils' local copy = tablex.deepcopy local append = table.insert local coroutine = coroutine local resume = coroutine.resume local assert_arg = utils.assert_arg local permute = {} -- PiL, 9.3 local permgen permgen = function (a, n, fn) if n == 0 then fn(a) else for i=1,n do -- put i-th element as the last one a[n], a[i] = a[i], a[n] -- generate all permutations of the other elements permgen(a, n - 1, fn) -- restore i-th element a[n], a[i] = a[i], a[n] end end end --- an iterator over all permutations of the elements of a list. -- Please note that the same list is returned each time, so do not keep references! -- @param a list-like table -- @return an iterator which provides the next permutation as a list function permute.iter (a) assert_arg(1,a,'table') local n = #a local co = coroutine.create(function () permgen(a, n, coroutine.yield) end) return function () -- iterator local code, res = resume(co) return res end end --- construct a table containing all the permutations of a list. -- @param a list-like table -- @return a table of tables -- @usage permute.table {1,2,3} --> {{2,3,1},{3,2,1},{3,1,2},{1,3,2},{2,1,3},{1,2,3}} function permute.table (a) assert_arg(1,a,'table') local res = {} local n = #a permgen(a,n,function(t) append(res,copy(t)) end) return res end return permute
mit
UnfortunateFruit/darkstar
scripts/globals/items/danceshroom.lua
35
1208
----------------------------------------- -- ID: 4375 -- Item: danceshroom -- Food Effect: 5Min, All Races ----------------------------------------- -- Strength -5 -- Dexterity 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4375); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -5); target:addMod(MOD_DEX, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -5); target:delMod(MOD_DEX, 3); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Windurst_Waters/npcs/Chamama.lua
23
5974
----------------------------------- -- Area: Windurst Waters -- NPC: Chamama -- Involved In Quest: Inspector's Gadget -- Starts Quest: In a Pickle ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) FakeMoustache = player:hasKeyItem(FAKE_MOUSTACHE); InvisibleManSticker = player:hasKeyItem(INVISIBLE_MAN_STICKER); InAPickle = player:getQuestStatus(WINDURST,IN_A_PICKLE); count = trade:getItemCount(); gil = trade:getGil(); if ((InAPickle == QUEST_ACCEPTED or InAPickle == QUEST_COMPLETED) and trade:hasItemQty(583,1) == true and count == 1 and gil == 0) then rand = math.random(1,4); if (rand <= 2) then if (InAPickle == QUEST_ACCEPTED) then player:startEvent(0x0293); -- IN A PICKLE: Quest Turn In (1st Time) elseif (InAPickle == QUEST_COMPLETED) then player:startEvent(0x0296,200); end elseif (rand == 3) then player:startEvent(0x0291); -- IN A PICKLE: Too Light player:tradeComplete(trade); elseif (rand == 4) then player:startEvent(0x0292); -- IN A PICKLE: Too Small player:tradeComplete(trade); end elseif (FakeMoustache == false) then InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET); if (InspectorsGadget == QUEST_ACCEPTED) then count = trade:getItemCount(); SarutaCotton = trade:hasItemQty(834,4); if (SarutaCotton == true and count == 4) then player:startEvent(0x0228); end end elseif (InvisibleManSticker == false) then ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE); if (ThePromise == QUEST_ACCEPTED) then count = trade:getItemCount(); ShoalWeed = trade:hasItemQty(1148,1); if (ShoalWeed == true and count == 1) then player:startEvent(0x031f,0,0,INVISIBLE_MAN_STICKER); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET); ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE); InAPickle = player:getQuestStatus(WINDURST,IN_A_PICKLE); NeedToZone = player:needToZone(); if (ThePromise == QUEST_ACCEPTED) then InvisibleManSticker = player:hasKeyItem(INVISIBLE_MAN_STICKER); if (InvisibleManSticker == true) then player:startEvent(0x0320); else ThePromiseVar = player:getVar("ThePromise"); if (ThePromiseVar == 1) then player:startEvent(0x031e,0,1148,INVISIBLE_MAN_STICKER); else player:startEvent(0x031d,0,1148,INVISIBLE_MAN_STICKER); end end elseif (InspectorsGadget == QUEST_ACCEPTED) then FakeMoustache = player:hasKeyItem(FAKE_MOUSTACHE); printf("mustach check"); if (FakeMoustache == true) then player:startEvent(0x0229); else player:startEvent(0x0227,0,FAKE_MOUSTACHE); end elseif (InAPickle == QUEST_AVAILABLE and NeedToZone == false) then rand = math.random(1,2); if (rand == 1) then player:startEvent(0x028e,0,4444); -- IN A PICKLE + RARAB TAIL: Quest Begin else player:startEvent(0x028b); -- Standard Conversation end elseif (InAPickle == QUEST_ACCEPTED or player:getVar("QuestInAPickle_var") == 1) then player:startEvent(0x028f,0,4444); -- IN A PICKLE + RARAB TAIL: Quest Objective Reminder elseif (InAPickle == QUEST_COMPLETED and NeedToZone) then player:startEvent(0x0294); -- IN A PICKLE: After Quest elseif (InAPickle == QUEST_COMPLETED and NeedToZone == false and player:getVar("QuestInAPickle_var") ~= 1) then rand = math.random(1,2) if (rand == 1) then player:startEvent(0x0295); -- IN A PICKLE: Repeatable Quest Begin else player:startEvent(0x028b); -- Standard Conversation end else player:startEvent(0x028b); -- Standard Conversation end -- player:delQuest(WINDURST,IN_A_PICKLE); [[[[[[[[[[[[[ FOR TESTING ONLY ]]]]]]]]]]]]] 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 == 0x0228) then player:tradeComplete(); player:addKeyItem(FAKE_MOUSTACHE); player:messageSpecial(KEYITEM_OBTAINED,FAKE_MOUSTACHE); elseif (csid == 0x031d) then player:setVar("ThePromise",1); elseif (csid == 0x031f) then player:tradeComplete(); player:addKeyItem(FAKE_MOUSTACHE); player:messageSpecial(KEYITEM_OBTAINED,FAKE_MOUSTACHE); elseif (csid == 0x028e and option == 1) then -- IN A PICKLE + RARAB TAIL: Quest Begin player:addQuest(WINDURST,IN_A_PICKLE); elseif (csid == 0x0293) then -- IN A PICKLE: Quest Turn In (1st Time) player:tradeComplete(trade); player:completeQuest(WINDURST,IN_A_PICKLE); player:needToZone(true); player:addItem(12505); player:messageSpecial(ITEM_OBTAINED,12505); player:addGil(GIL_RATE*200); player:messageSpecial(GIL_OBTAINED,GIL_RATE*200); player:addFame(WINDURST,WIN_FAME*75); elseif (csid == 0x0295 and option == 1) then player:setVar("QuestInAPickle_var",1) elseif (csid == 0x0296) then -- IN A PICKLE + 200 GIL: Repeatable Quest Turn In player:tradeComplete(trade); player:needToZone(true); player:addGil(GIL_RATE*200); player:addFame(WINDURST,WIN_FAME*8); player:setVar("QuestInAPickle_var",0) end end;
gpl-3.0
garyjs/Newfiesautodialer
lua/libs/dbh_light.lua
3
2647
-- -- 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-2013 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"; --It might worth to rename this to model.lua local oo = require "loop.simple" --local redis = require 'redis' --require "memcached" require "settings" --redis.commands.expire = redis.command('EXPIRE') --redis.commands.ttl = redis.command('TTL') DBH = oo.class{ dbh = nil, -- debugger = nil, results = {}, caching = false, } function DBH:__init(debug_mode, debugger) -- self is the class return oo.rawnew(self, { debug_mode = debug_mode, -- debugger = debugger, }) end function DBH:connect() -- connect to ODBC database ODBC_DBNAME = 'newfiesdialer' self.dbh = freeswitch.Dbh("odbc://"..ODBC_DBNAME..":"..DBUSER..":"..DBPASS) assert(self.dbh:connected()) end function DBH:disconnect() self.dbh:release() -- optional end function DBH:get_list(sqlquery) -- self.debugger:msg("DEBUG", "Load SQL : "..sqlquery) local list = {} self.dbh:query(sqlquery, function(row) --Let's transform empty value to False --We do this to have similar behavior to luasql --luasql doesn't return the empty/null fields for k, v in pairs(row) do if v == '' then row[k] = false end end list[tonumber(row.id)] = row --freeswitch.consoleLog(fslevel, string.format("%5s : %s\n", row.id, row.name)) end) return list end function DBH:get_cache_list(sqlquery, ttl) return self:get_list(sqlquery) end function DBH:get_object(sqlquery) -- self.debugger:msg("DEBUG", "Load SQL : "..sqlquery) local res_get_object self.dbh:query(sqlquery, function(row) res_get_object = row for k, v in pairs(res_get_object) do if v == '' then res_get_object[k] = false end end --freeswitch.consoleLog(fslevel, string.format("%5s : %s\n", row.id, row.name)) end) return res_get_object end function DBH:get_cache_object(sqlquery, ttl) return self:get_object(sqlquery) end function DBH:execute(sqlquery) local res = self.dbh:query(sqlquery) return res end
mpl-2.0
nesstea/darkstar
scripts/zones/Beaucedine_Glacier/npcs/Iron_Grate.lua
13
2805
----------------------------------- -- Area: Beaucedine Glacier -- NPC: Iron Grate -- Type: Door -- @pos 241.000 5.000 -20.000 111 : J-8 -- @pos 60.000 5.000 -359.000 111 : H-10 -- @pos 100.000 -15.000 159.000 111 : I-7 -- @pos -199.000 -35.000 -220.000 111 : G-9 -- @pos -20.000 -55.000 -41.000 111 : H-8 -- @pos -340.000 -95.000 159.000 111 : F-7 ----------------------------------- package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Beaucedine_Glacier/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Z = player:getZPos(); if (X < 247 and X > 241) then -- J-8 player:startEvent(0x00C8); elseif (Z < -353 and Z > -359) then -- H-10 player:startEvent(0x00C9); elseif ((X > 95 and X < 104) and (Z > 153 and Z < 159)) then -- I-7 player:startEvent(0x00CA); elseif (X < -193 and X > -199) then -- G-9 player:startEvent(0x00CB); elseif (Z > -47 and Z < -41) then -- H-8 player:startEvent(0x00CC); elseif ((X > -344 and X < -337) and (Z > 153 and Z < 159)) then -- F-7 player:startEvent(0x00CD); 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 LVLcap = 0; if (option == 1) then if (csid == 0x00C8) then -- 50 Cap Area LVLcap = 50; player:setPos(396,-8,-20,125,9); elseif (csid == 0x00C9) then -- 60 Cap Area LVLcap = 60; player:setPos(220,-8,-282,66,9); elseif (csid == 0x00CA) then -- No Cap Area player:setPos(180,-8,241,190,9); elseif (csid == 0x00CB) then -- No Cap Area player:setPos(-242,8,-259,126,9); elseif (csid == 0x00CC) then -- Cap 40 Area LVLcap = 40; player:setPos(-180,-8,-78,194,9); elseif (csid == 0x00CD) then -- No Cap Area player:setPos(-300,-8,203,191,9); end if (ENABLE_COP_ZONE_CAP == 1 ) then player:setVar("PSOXJA_RESTRICTION_LVL",LVLcap); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Tombstone_Prototype.lua
17
1245
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Tombstone Prototype ----------------------------------- package.loaded["scripts/zones/Dynamis-Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob,target) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- Time Bonus: 010 060 if(mobID == 17330531 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(30); mob:addInBattlefieldList(); elseif(mobID == 17330830 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(30); mob:addInBattlefieldList(); end end;
gpl-3.0
MuhammadWang/MCServer
MCServer/Plugins/APIDump/Hooks/OnExecuteCommand.lua
3
1440
return { HOOK_EXECUTE_COMMAND = { CalledWhen = "A player executes an in-game command, or the admin issues a console command. Note that built-in console commands are exempt to this hook - they are always performed and the hook is not called.", DefaultFnName = "OnExecuteCommand", -- also used as pagename Desc = [[ A plugin may implement a callback for this hook to intercept both in-game commands executed by the players and console commands executed by the server admin. The function is called for every in-game command sent from any player and for those server console commands that are not built in in the server.</p> <p> If the command is in-game, the first parameter to the hook function is the {{cPlayer|player}} who's executing the command. If the command comes from the server console, the first parameter is nil. ]], Params = { { Name = "Player", Type = "{{cPlayer}}", Notes = "For in-game commands, the player who has sent the message. For console commands, nil" }, { Name = "Command", Type = "table of strings", Notes = "The command and its parameters, broken into a table by spaces" }, }, Returns = [[ If the plugin returns true, the command will be blocked and none of the remaining hook handlers will be called. If the plugin returns false, MCServer calls all the remaining hook handlers and finally the command will be executed. ]], }, -- HOOK_EXECUTE_COMMAND }
apache-2.0
FailcoderAddons/supervillain-ui
SVUI_Skins/components/addons/Bugsack.lua
2
1449
--[[ ########################################################## S V U I By: Failcoder ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; local pairs = _G.pairs; local string = _G.string; --[[ STRING METHODS ]]-- local format = string.format; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = _G['SVUI']; local L = SV.L; local MOD = SV.Skins; local Schema = MOD.Schema; --[[ ########################################################## BUGSACK ########################################################## ]]-- local function StyleBugSack(event, addon) assert(BugSack, "AddOn Not Loaded") hooksecurefunc(BugSack, "OpenSack", function() if BugSackFrame.Panel then return end BugSackFrame:RemoveTextures() BugSackFrame:SetStyle("Frame", 'Transparent') SV.API:Set("Tab", BugSackTabAll) BugSackTabAll:SetPoint("TOPLEFT", BugSackFrame, "BOTTOMLEFT", 0, 1) SV.API:Set("Tab", BugSackTabSession) SV.API:Set("Tab", BugSackTabLast) BugSackNextButton:SetStyle("Button") BugSackSendButton:SetStyle("Button") BugSackPrevButton:SetStyle("Button") SV.API:Set("ScrollBar", BugSackScrollScrollBar) end) end MOD:SaveAddonStyle("Bugsack", StyleBugSack)
mit
smarttang/sosrp
app-security-worker/sec.security.waf/resty/redis.lua
3
9227
-- Copyright (C) Yichun Zhang (agentzh) local sub = string.sub local byte = string.byte local tcp = ngx.socket.tcp local null = ngx.null local type = type local pairs = pairs local unpack = unpack local setmetatable = setmetatable local tonumber = tonumber local tostring = tostring local rawget = rawget --local error = error local ok, new_tab = pcall(require, "table.new") if not ok or type(new_tab) ~= "function" then new_tab = function (narr, nrec) return {} end end local _M = new_tab(0, 54) _M._VERSION = '0.26' local common_cmds = { "get", "set", "mget", "mset", "del", "incr", "decr", -- Strings "llen", "lindex", "lpop", "lpush", "lrange", "linsert", -- Lists "hexists", "hget", "hset", "hmget", --[[ "hmset", ]] "hdel", -- Hashes "smembers", "sismember", "sadd", "srem", "sdiff", "sinter", "sunion", -- Sets "zrange", "zrangebyscore", "zrank", "zadd", "zrem", "zincrby", -- Sorted Sets "auth", "eval", "expire", "script", "sort" -- Others } local sub_commands = { "subscribe", "psubscribe" } local unsub_commands = { "unsubscribe", "punsubscribe" } local mt = { __index = _M } function _M.new(self) local sock, err = tcp() if not sock then return nil, err end return setmetatable({ _sock = sock, _subscribed = false }, mt) end function _M.set_timeout(self, timeout) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end return sock:settimeout(timeout) end function _M.connect(self, ...) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end self._subscribed = false return sock:connect(...) end function _M.set_keepalive(self, ...) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end if rawget(self, "_subscribed") then return nil, "subscribed state" end return sock:setkeepalive(...) end function _M.get_reused_times(self) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end return sock:getreusedtimes() end local function close(self) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end return sock:close() end _M.close = close local function _read_reply(self, sock) local line, err = sock:receive() if not line then if err == "timeout" and not rawget(self, "_subscribed") then sock:close() end return nil, err end local prefix = byte(line) if prefix == 36 then -- char '$' -- print("bulk reply") local size = tonumber(sub(line, 2)) if size < 0 then return null end local data, err = sock:receive(size) if not data then if err == "timeout" then sock:close() end return nil, err end local dummy, err = sock:receive(2) -- ignore CRLF if not dummy then return nil, err end return data elseif prefix == 43 then -- char '+' -- print("status reply") return sub(line, 2) elseif prefix == 42 then -- char '*' local n = tonumber(sub(line, 2)) -- print("multi-bulk reply: ", n) if n < 0 then return null end local vals = new_tab(n, 0) local nvals = 0 for i = 1, n do local res, err = _read_reply(self, sock) if res then nvals = nvals + 1 vals[nvals] = res elseif res == nil then return nil, err else -- be a valid redis error value nvals = nvals + 1 vals[nvals] = {false, err} end end return vals elseif prefix == 58 then -- char ':' -- print("integer reply") return tonumber(sub(line, 2)) elseif prefix == 45 then -- char '-' -- print("error reply: ", n) return false, sub(line, 2) else -- when `line` is an empty string, `prefix` will be equal to nil. return nil, "unkown prefix: \"" .. tostring(prefix) .. "\"" end end local function _gen_req(args) local nargs = #args local req = new_tab(nargs * 5 + 1, 0) req[1] = "*" .. nargs .. "\r\n" local nbits = 2 for i = 1, nargs do local arg = args[i] if type(arg) ~= "string" then arg = tostring(arg) end req[nbits] = "$" req[nbits + 1] = #arg req[nbits + 2] = "\r\n" req[nbits + 3] = arg req[nbits + 4] = "\r\n" nbits = nbits + 5 end -- it is much faster to do string concatenation on the C land -- in real world (large number of strings in the Lua VM) return req end local function _do_cmd(self, ...) local args = {...} local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end local req = _gen_req(args) local reqs = rawget(self, "_reqs") if reqs then reqs[#reqs + 1] = req return end -- print("request: ", table.concat(req)) local bytes, err = sock:send(req) if not bytes then return nil, err end return _read_reply(self, sock) end local function _check_subscribed(self, res) if type(res) == "table" and (res[1] == "unsubscribe" or res[1] == "punsubscribe") and res[3] == 0 then self._subscribed = false end end function _M.read_reply(self) local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end if not rawget(self, "_subscribed") then return nil, "not subscribed" end local res, err = _read_reply(self, sock) _check_subscribed(self, res) return res, err end for i = 1, #common_cmds do local cmd = common_cmds[i] _M[cmd] = function (self, ...) return _do_cmd(self, cmd, ...) end end for i = 1, #sub_commands do local cmd = sub_commands[i] _M[cmd] = function (self, ...) self._subscribed = true return _do_cmd(self, cmd, ...) end end for i = 1, #unsub_commands do local cmd = unsub_commands[i] _M[cmd] = function (self, ...) local res, err = _do_cmd(self, cmd, ...) _check_subscribed(self, res) return res, err end end function _M.hmset(self, hashname, ...) if select('#', ...) == 1 then local t = select(1, ...) local n = 0 for k, v in pairs(t) do n = n + 2 end local array = new_tab(n, 0) local i = 0 for k, v in pairs(t) do array[i + 1] = k array[i + 2] = v i = i + 2 end -- print("key", hashname) return _do_cmd(self, "hmset", hashname, unpack(array)) end -- backwards compatibility return _do_cmd(self, "hmset", hashname, ...) end function _M.init_pipeline(self, n) self._reqs = new_tab(n or 4, 0) end function _M.cancel_pipeline(self) self._reqs = nil end function _M.commit_pipeline(self) local reqs = rawget(self, "_reqs") if not reqs then return nil, "no pipeline" end self._reqs = nil local sock = rawget(self, "_sock") if not sock then return nil, "not initialized" end local bytes, err = sock:send(reqs) if not bytes then return nil, err end local nvals = 0 local nreqs = #reqs local vals = new_tab(nreqs, 0) for i = 1, nreqs do local res, err = _read_reply(self, sock) if res then nvals = nvals + 1 vals[nvals] = res elseif res == nil then if err == "timeout" then close(self) end return nil, err else -- be a valid redis error value nvals = nvals + 1 vals[nvals] = {false, err} end end return vals end function _M.array_to_hash(self, t) local n = #t -- print("n = ", n) local h = new_tab(0, n / 2) for i = 1, n, 2 do h[t[i]] = t[i + 1] end return h end -- this method is deperate since we already do lazy method generation. function _M.add_commands(...) local cmds = {...} for i = 1, #cmds do local cmd = cmds[i] _M[cmd] = function (self, ...) return _do_cmd(self, cmd, ...) end end end setmetatable(_M, {__index = function(self, cmd) local method = function (self, ...) return _do_cmd(self, cmd, ...) end -- cache the lazily generated method in our -- module table _M[cmd] = method return method end}) return _M
gpl-3.0
nesstea/darkstar
scripts/zones/Caedarva_Mire/npcs/Jazaraat_s_Headstone.lua
16
2063
----------------------------------- -- Area: Caedarva Mire -- NPC: Jazaraat's Headstone -- Involved in mission: The Lost Kingdom (TOAUM 13) -- @pos -389 6 -570 79 ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Caedarva_Mire/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(TOAU) == LOST_KINGDOM and player:hasKeyItem(VIAL_OF_SPECTRAL_SCENT) and player:getVar("AhtUrganStatus") == 0) then player:startEvent(8); elseif (player:getVar("AhtUrganStatus") == 1) then if (GetMobAction(17101146) == 0) then SpawnMob(17101146):updateEnmity(player); end elseif (player:getVar("AhtUrganStatus") == 2) then player:startEvent(9); elseif (player:getVar("AhtUrganStatus") == 3) then player:setVar("AhtUrganStatus", 0); player:addKeyItem(EPHRAMADIAN_GOLD_COIN); player:completeMission(TOAU,LOST_KINGDOM); player:addMission(TOAU,THE_DOLPHIN_CREST); player:messageSpecial(KEYITEM_OBTAINED,EPHRAMADIAN_GOLD_COIN); else player:messageSpecial(JAZARAATS_HEADSTONE); 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 == 8) then player:setVar("AhtUrganStatus", 1); elseif (csid == 9) then player:setVar("AhtUrganStatus", 3); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/PsoXja/npcs/_099.lua
8
1669
----------------------------------- -- Area: Pso'Xja -- NPC: _099 (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- @pos -330.000 14.074 -261.600 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local Z=player:getZPos(); if (npc:getAnimation() == 9) then if(Z <= -59)then if(GetMobAction(16814090) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED); SpawnMob(16814090,120):updateClaim(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS); -- 10% Chance the door will simply open without Gargoyle pop npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif(Z >= -58)then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if(csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
Irubataru/dotfiles
roles/neovim/config/lua/irubataru/lsp/servers/sumneko_lua.lua
1
2584
local path = vim.split(package.path, ";") table.insert(path, "lua/?.lua") table.insert(path, "lua/?/init.lua") local function setup_libraries() local library = {} local function add(lib) for _, p in pairs(vim.fn.expand(lib, false, true)) do p = vim.loop.fs_realpath(p) library[p] = true end end local homedir = vim.env.HOME local filedir = vim.fn.expand("%:p") local function dev_vim() return filedir:find("^" .. homedir .. "/.config/nvim") ~= nil or filedir:find("^" .. homedir .. "/.dotfiles/roles/neovim/config") ~= nil end local function dev_awesome() return filedir:find("^" .. homedir .. "/.config/awesome") ~= nil or filedir:find("^" .. homedir .. "/.dotfiles/roles/awesome/config") ~= nil end local function dev_awesome_custom() return filedir:find("^" .. homedir .. "/config/awesome") ~= nil end if dev_vim() then -- add runtime add("$VIMRUNTIME") -- add your config add("~/.config/nvim") -- add plugins -- if you're not using packer, then you might need to change the paths below add("~/.local/share/nvim/site/pack/packer/opt/*") add("~/.local/share/nvim/site/pack/packer/start/*") elseif dev_awesome() then add(homedir .. "/.dotfiles/roles/awesome/config") add(homedir .. "/.dotfiles/roles/awesome/config/*") add("/usr/share/awesome/lib") add("/usr/share/awesome/lib/*") elseif dev_awesome_custom() then add("$PWD") add("/usr/share/awesome/lib") add("/usr/share/awesome/lib/*") else add("$PWD") end return library end local M = {} M.config = { on_attach_post = function(client, _) client.config.settings.Lua.workspace.library = setup_libraries() end, settings = { Lua = { runtime = { -- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim) version = "LuaJIT", -- Setup your lua path path = path, }, completion = { callSnippet = "Both" }, diagnostics = { -- Get the language server to recognize the `vim` global globals = { -- neovim "vim", -- awesome "awesome", "client", "root", "screen", }, }, workspace = { -- Make the server aware of Neovim runtime files library = setup_libraries(), }, -- Do not send telemetry data containing a randomized but unique identifier telemetry = { enable = false }, }, }, filetypes = { "lua", "lua.luapad", "luapad" }, } return M
mit
UnfortunateFruit/darkstar
scripts/zones/La_Theine_Plateau/npcs/Equesobillot.lua
17
2303
----------------------------------- -- Area: La Theine Plateau -- NPC: Equesobillot -- Involved in Mission: The Rescue Drill -- @pos -287 9 284 102 ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(SANDORIA) == THE_RESCUE_DRILL) then local MissionStatus = player:getVar("MissionStatus"); if(MissionStatus == 2) then player:startEvent(0x0065); elseif(MissionStatus == 3) then player:showText(npc, RESCUE_DRILL + 3); elseif(MissionStatus == 8) then if(player:getVar("theRescueDrillRandomNPC") == 2) then player:startEvent(0x0070); else player:showText(npc, RESCUE_DRILL + 21); end elseif(MissionStatus == 9) then if(player:getVar("theRescueDrillRandomNPC") == 2) then player:showText(npc, RESCUE_DRILL + 25); else player:showText(npc, RESCUE_DRILL + 26); end elseif(MissionStatus >= 10) then player:showText(npc, RESCUE_DRILL + 30); else player:showText(npc, RESCUE_DRILL); end else player:showText(npc, RESCUE_DRILL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0065) then player:setVar("MissionStatus",3); elseif(csid == 0x0070) then if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16535); -- Bronze Sword else player:addItem(16535); player:messageSpecial(ITEM_OBTAINED, 16535); -- Bronze Sword player:setVar("MissionStatus",9); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Beaucedine_Glacier/TextIDs.lua
5
1124
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6553; -- You cannot obtain the item. Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6554; -- You cannot obtain the #. Try trading again after sorting your inventory. ITEM_OBTAINED = 6555; -- Obtained: <item>. GIL_OBTAINED = 6556; -- Obtained <number> gil. KEYITEM_OBTAINED = 6558; -- Obtained key item: <keyitem>. ITEMS_OBTAINED = 6564; -- You obtain BEASTMEN_BANNER = 81; -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7209; -- You can't fish here. -- Conquest CONQUEST = 7456; -- You've earned conquest points! -- Other dialog NOTHING_OUT_OF_ORDINARY = 6569; -- There is nothing out of the ordinary here. -- Dynamis dialogs YOU_CANNOT_ENTER_DYNAMIS = 7843; -- You cannot enter Dynamis PLAYERS_HAVE_NOT_REACHED_LEVEL = 7845; -- Players who have not reached levelare prohibited from entering Dynamis. UNUSUAL_ARRANGEMENT_OF_BRANCHES = 7855; -- There is an unusual arrangement of branches here. -- conquest Base CONQUEST_BASE = 0;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Windurst_Woods/npcs/Nanaa_Mihgo.lua
17
10399
----------------------------------- -- Area: Windurst Walls -- NPC: Nanaa Mihgo -- Starts and Finishes Quest: Mihgo's Amigo (R), The Tenshodo Showdown (start), Rock Racketeer (start, listed as ROCK_RACKETTER in quests.lua) -- Involved In Quest: Crying Over Onions -- Involved in Mission 2-1 -- @pos 62 -4 240 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(498,4) and trade:getItemCount() == 4) then -- Trade Yagudo Necklace x4 local MihgosAmigo = player:getQuestStatus(WINDURST,MIHGO_S_AMIGO); if(MihgosAmigo == QUEST_ACCEPTED) then player:startEvent(0x0058,GIL_RATE*200); elseif(MihgosAmigo == QUEST_COMPLETED) then player:startEvent(0x01ee,GIL_RATE*200); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Check for Missions first (priority?) local MissionStatus = player:getVar("MissionStatus"); if(player:getCurrentMission(WINDURST) == LOST_FOR_WORDS and MissionStatus > 0 and MissionStatus < 5) then if(MissionStatus == 1) then player:startEvent(0x00a5,0,LAPIS_CORAL,LAPIS_MONOCLE); elseif(MissionStatus == 2) then player:startEvent(0x00a6,0,LAPIS_CORAL,LAPIS_MONOCLE); elseif(MissionStatus == 3) then player:startEvent(0x00a9); else player:startEvent(0x00aa); end else local CryingOverOnionsVar = player:getVar("CryingOverOnions"); local MihgosAmigo = player:getQuestStatus(WINDURST,MIHGO_S_AMIGO); local theTenshodoShowdown = player:getQuestStatus(WINDURST,THE_TENSHODO_SHOWDOWN); -- THF af quest local theTenshodoShowdownCS = player:getVar("theTenshodoShowdownCS"); local RockRacketeer = player:getQuestStatus(WINDURST,ROCK_RACKETTER); local RRvar = player:getVar("rockracketeer_sold"); local thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES); -- THF af quest local thickAsThievesCS = player:getVar("thickAsThievesCS"); local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS"); local thickAsThievesGamblingCS = player:getVar("thickAsThievesGamblingCS"); local hittingTheMarquisate = player:getQuestStatus(WINDURST,HITTING_THE_MARQUISATE); -- THF af quest local hittingTheMarquisateYatnielCS = player:getVar("hittingTheMarquisateYatnielCS"); local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS"); local hittingTheMarquisateNanaaCS = player:getVar("hittingTheMarquisateNanaaCS"); local WildcatWindurst = player:getVar("WildcatWindurst"); local LvL = player:getMainLvl(); local Job = player:getMainJob(); -- Lure of the Wildcat (Windurst) if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,4) == false) then player:startEvent(0x02dc); -- Optional CS of the quest "Crying Over Onions" elseif(CryingOverOnionsVar == 1) then player:startEvent(0x0256); -- Quest "The Tenshodo Showdown" THF af elseif(Job == 6 and LvL >= 40 and theTenshodoShowdown == QUEST_AVAILABLE) then player:startEvent(0x01f0); -- Start Quest "The Tenshodo Showdown" elseif(theTenshodoShowdownCS == 1) then player:startEvent(0x01f1); -- During Quest "The Tenshodo Showdown" (before cs at tensho HQ) elseif(theTenshodoShowdownCS >= 2) then player:startEvent(0x01f2); -- During Quest "The Tenshodo Showdown" (after cs at tensho HQ) elseif(Job == 6 and LvL < 50 and theTenshodoShowdown == QUEST_COMPLETED) then player:startEvent(0x01f7); -- Standard dialog after "The Tenshodo Showdown" -- Quest "Thick as Thieves" THF af elseif(Job == 6 and LvL >= 50 and thickAsThieves == QUEST_AVAILABLE and theTenshodoShowdown == QUEST_COMPLETED) then player:startEvent(0x01f8); -- Start Quest "Thick as Thieves" elseif(thickAsThievesCS >= 1 and thickAsThievesCS <= 4 and thickAsThievesGamblingCS <= 7 and thickAsThievesGrapplingCS <= 7) then player:startEvent(0x01f9,0,GANG_WHEREABOUTS_NOTE); -- During Quest "Thick as Thieves" (before completing grappling+gambling sidequests) elseif(thickAsThievesGamblingCS == 8 and thickAsThievesGrapplingCS ==8) then player:startEvent(0x01fc); -- complete quest "as thick as thieves" -- Quest "Hitting The Marquisate" THF af elseif(Job == 6 and LvL >= 50 and thickAsThieves == QUEST_COMPLETED and hittingTheMarquisate == QUEST_AVAILABLE) then player:startEvent(0x0200); -- Start Quest "Hitting The Marquisate" elseif(hittingTheMarquisateYatnielCS == 3 and hittingTheMarquisateHagainCS == 9) then player:startEvent(0x0204); -- finish first part of "Hitting The Marquisate" elseif(hittingTheMarquisateNanaaCS == 1) then player:startEvent(0x0205); -- during second part of "Hitting The Marquisate" -- Standard dialog elseif(RockRacketeer == QUEST_COMPLETED) then player:startEvent(0x0063); -- new dialog after Rock Racketeer elseif(MihgosAmigo == QUEST_COMPLETED) then player:startEvent(0x0059); -- new dialog after Mihgo's Amigos -- Rock Racketeer (listed as ROCK_RACKETTER in quests.lua) elseif(MihgosAmigo == QUEST_COMPLETED and RockRacketeer == QUEST_AVAILABLE and player:getFameLevel (WINDURST) >= 3) then if(player:needToZone()) then player:startEvent(0x0059); -- Mihgos Amigo complete text else player:startEvent(0x005D); -- quest start end elseif(RockRacketeer == QUEST_ACCEPTED and RRvar == 2) then player:startEvent(0x005F); -- not sold reminder elseif(RockRacketeer == QUEST_ACCEPTED and RRvar == 1) then player:startEvent(0x0062); -- advance quest talk to Varun elseif(RockRacketeer == QUEST_ACCEPTED) then player:startEvent(0x005E); -- quest reminder -- Quest "Mihgo's Amigo" elseif(MihgosAmigo == QUEST_AVAILABLE) then local CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS); if(CryingOverOnions == QUEST_AVAILABLE) then player:startEvent(0x0051); -- Start Quest "Mihgo's Amigo" with quest "Crying Over Onions" Activated else player:startEvent(0x0050); -- Start Quest "Mihgo's Amigo" end elseif(MihgosAmigo == QUEST_ACCEPTED) then player:startEvent(0x0052); else player:startEvent(0x004c); -- standard dialog 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 == 0x0050 or csid == 0x0051) then player:addQuest(WINDURST,MIHGO_S_AMIGO); elseif(csid == 0x0058) then player:tradeComplete(); player:addGil(GIL_RATE*200); player:addTitle(CAT_BURGLAR_GROUPIE); player:needToZone(true); player:addFame(NORG,NORG_FAME*60); player:completeQuest(WINDURST,MIHGO_S_AMIGO); elseif(csid == 0x01ee) then player:tradeComplete(); player:addTitle(CAT_BURGLAR_GROUPIE); player:addGil(GIL_RATE*200); player:addFame(NORG,NORG_FAME*30); elseif(csid == 0x01f0) then player:addQuest(WINDURST,THE_TENSHODO_SHOWDOWN); player:setVar("theTenshodoShowdownCS",1); player:addKeyItem(LETTER_FROM_THE_TENSHODO); player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_THE_TENSHODO); elseif(csid == 0x01f8 and option == 1) then -- start quest "as thick as thieves" player:addQuest(WINDURST,AS_THICK_AS_THIEVES); player:setVar("thickAsThievesCS",1); player:addKeyItem(GANG_WHEREABOUTS_NOTE); player:addKeyItem(FIRST_FORGED_ENVELOPE); player:addKeyItem(SECOND_FORGED_ENVELOPE); player:messageSpecial(KEYITEM_OBTAINED,GANG_WHEREABOUTS_NOTE); player:messageSpecial(KEYITEM_OBTAINED,FIRST_FORGED_ENVELOPE); player:messageSpecial(KEYITEM_OBTAINED,SECOND_FORGED_ENVELOPE); elseif(csid == 0x01fc) then -- complete quest "as thick as thieves" if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12514); else player:addItem(12514); player:messageSpecial(ITEM_OBTAINED,12514); player:completeQuest(WINDURST,AS_THICK_AS_THIEVES); player:setVar("thickAsThievesCS",0); player:setVar("thickAsThievesGrapplingCS",0); player:setVar("thickAsThievesGamblingCS",0); player:delKeyItem(GANG_WHEREABOUTS_NOTE); player:delKeyItem(FIRST_SIGNED_FORGED_ENVELOPE); player:delKeyItem(SECOND_SIGNED_FORGED_ENVELOPE); end elseif(csid == 0x0200) then -- start quest "hitting The Marquisate " player:addQuest(WINDURST,HITTING_THE_MARQUISATE); player:setVar("hittingTheMarquisateYatnielCS",1); player:setVar("hittingTheMarquisateHagainCS",1); player:addKeyItem(CAT_BURGLARS_NOTE); player:messageSpecial(KEYITEM_OBTAINED,CAT_BURGLARS_NOTE); elseif(csid == 0x0204) then -- end first part of "hitting The Marquisate " player:setVar("hittingTheMarquisateNanaaCS",1); player:setVar("hittingTheMarquisateYatnielCS",0); player:setVar("hittingTheMarquisateHagainCS",0); elseif(csid == 0x00a5 and option == 1) then -- Windurst Mission 2-1 continuation -- Add the key item for the mission player:addKeyItem(LAPIS_MONOCLE); player:messageSpecial(KEYITEM_OBTAINED,LAPIS_MONOCLE); -- Mark the progress player:setVar("MissionStatus",2); elseif(csid == 0x00a9) then -- Windurst Mission 2-1 continuation player:setVar("MissionStatus",4); player:setVar("MissionStatus_randfoss",0); player:delKeyItem(LAPIS_MONOCLE); player:delKeyItem(LAPIS_CORAL); player:addKeyItem(HIDEOUT_KEY); player:messageSpecial(KEYITEM_OBTAINED,HIDEOUT_KEY); elseif (csid == 0x02dc) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",4,true); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/serving_of_black_pudding.lua
36
1520
----------------------------------------- -- ID: 5552 -- Item: Serving of Black Pudding -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +8 -- MP +5% Cap 25 -- Intelligence +4 -- HP Recovered while healing +1 -- MP Recovered while healing +1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5552); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 5); target:addMod(MOD_FOOD_MP_CAP, 25); target:addMod(MOD_HP, 8); target:addMod(MOD_INT, 4); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 5); target:delMod(MOD_FOOD_MP_CAP, 25); target:delMod(MOD_HP, 8); target:delMod(MOD_INT, 4); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
Samanj5/Assassin
bot/seedbot.lua
1
8709
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) -- mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban" sudo_users={@redteam_03_00},--sudo users disabled_channels = {}, realm = {data = 'data/moderation.json'},--Realms Id moderation = {data = 'data/moderation.json'} about_text = [[Teleseed v1 An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Admins @iwals [Founder] @imandaneshi [Developer] @Rondoozle [Developer] @syedan25 [Manager] Special thanks to awkward_potato Siyanew topkecleon Vamptacus Our channels @teleseedch [English] ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id return group id or user id !help !lock [member|name|bots] Locks [member|name|bots] !unlock [member|name|photo|bots] Unlocks [member|name|photo|bots] !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !newlink create/revoke your group link !link returns group link !owner returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] <text> Save <text> as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] returns user id "!res @username" !log will return group logs !banlist will return group ban list **U can use both "/" and "!" *Only owner and mods can add bots in group *Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
UnfortunateFruit/darkstar
scripts/globals/items/cotton_candy.lua
39
1205
----------------------------------------- -- ID: 5708 -- Item: Cotton Candy -- Food Effect: 5 Min, All Races ----------------------------------------- -- MP % 10 Cap 200 -- MP Healing 3 ----------------------------------------- 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,300,5708); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 10); target:addMod(MOD_FOOD_MP_CAP, 200); target:addMod(MOD_MPHEAL, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 10); target:delMod(MOD_FOOD_MP_CAP, 200); target:delMod(MOD_MPHEAL, 3); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Mamook/mobs/Colibri.lua
16
1620
----------------------------------- -- Area: Mamook -- MOB: Colibri ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local delay = mob:getLocalVar("delay"); local LastCast = mob:getLocalVar("LAST_CAST"); local spell = mob:getLocalVar("COPY_SPELL"); if (mob:AnimationSub() == 1) then if (mob:getBattleTime() - LastCast > 30) then mob:setLocalVar("COPY_SPELL", 0); mob:setLocalVar("delay", 0); mob:AnimationSub(0); end if (spell > 0 and mob:hasStatusEffect(EFFECT_SILENCE) == false) then if (delay >= 3) then mob:castSpell(spell); mob:setLocalVar("COPY_SPELL", 0); mob:setLocalVar("delay", 0); mob:AnimationSub(0); else mob:setLocalVar("delay", delay+1); end end end end; ----------------------------------- -- onMagicHit ----------------------------------- function onMagicHit(caster, target, spell) if (spell:tookEffect() and (caster:isPC() or caster:isPet()) and spell:getSpellGroup() ~= SPELLGROUP_BLUE ) then target:setLocalVar("COPY_SPELL", spell:getID()); target:setLocalVar("LAST_CAST", target:getBattleTime()); target:AnimationSub(1); end return 1; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Rakh_Mhappyoh.lua
38
1051
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Rakh Mhappyoh -- Type: Standard NPC -- @zone: 94 -- @pos -55.989 -4.5 48.365 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- 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(0x019b); 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
nesstea/darkstar
scripts/zones/Gusgen_Mines/npcs/Mining_Point.lua
13
1057
----------------------------------- -- Area: Gusgen Mines -- NPC: Mining Point ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ------------------------------------- require("scripts/globals/mining"); require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startMining(player,player:getZoneID(),npc,trade,0x000B); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MINING_IS_POSSIBLE_HERE,605); 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
nesstea/darkstar
scripts/zones/Apollyon/mobs/Troglodyte_Dhalmel.lua
7
1257
----------------------------------- -- Area: Apollyon NE -- NPC: Troglodyte Dhalmel ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if (IsMobDead(16933115)==true and IsMobDead(16933116)==true and IsMobDead(16933117)==true and IsMobDead(16933118)==true and IsMobDead(16933119)==true and IsMobDead(16933120)==true and IsMobDead(16933121)==true and IsMobDead(16933122)==true ) then -- item GetNPCByID(16932864+178):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+178):setStatus(STATUS_NORMAL); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Temenos/mobs/Kindred_Summoner.lua
7
1142
----------------------------------- -- Area: Temenos N T -- NPC: Kindred_Summoner. ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) GetMobByID(16928800):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) if (IsMobDead(16928797)==true and IsMobDead(16928798)==true and IsMobDead(16928799)==true ) then GetNPCByID(16928768+27):setPos(-120,-80,429); GetNPCByID(16928768+27):setStatus(STATUS_NORMAL); GetNPCByID(16928768+161):setPos(-123,-80,429); GetNPCByID(16928768+161):setStatus(STATUS_NORMAL); GetNPCByID(16928768+212):setPos(-117,-80,429); GetNPCByID(16928768+212):setStatus(STATUS_NORMAL); end end;
gpl-3.0
plajjan/snabbswitch
lib/ljsyscall/include/lfs-tests/test.lua
23
6377
#!/usr/bin/env luajit -- very slightly modified version of tests from https://github.com/keplerproject/luafilesystem --[[ Copyright © 2003 Kepler Project. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local tmp = "/tmp" local sep = string.match (package.config, "[^\n]+") local upper = ".." local lfs = require"syscall.lfs" print (lfs._VERSION) io.write(".") io.flush() function attrdir (path) for file in lfs.dir(path) do if file ~= "." and file ~= ".." then local f = path..sep..file print ("\t=> "..f.." <=") local attr = lfs.attributes (f) assert (type(attr) == "table") if attr.mode == "directory" then attrdir (f) else for name, value in pairs(attr) do print (name, value) end end end end end -- Checking changing directories local current = assert (lfs.currentdir()) local reldir = string.gsub (current, "^.*%"..sep.."([^"..sep.."])$", "%1") assert (lfs.chdir (upper), "could not change to upper directory") assert (lfs.chdir (reldir), "could not change back to current directory") assert (lfs.currentdir() == current, "error trying to change directories") assert (lfs.chdir ("this couldn't be an actual directory") == nil, "could change to a non-existent directory") io.write(".") io.flush() -- Changing creating and removing directories local tmpdir = current..sep.."lfs_tmp_dir" local tmpfile = tmpdir..sep.."tmp_file" -- Test for existence of a previous lfs_tmp_dir -- that may have resulted from an interrupted test execution and remove it if lfs.chdir (tmpdir) then assert (lfs.chdir (upper), "could not change to upper directory") assert (os.remove (tmpfile), "could not remove file from previous test") assert (lfs.rmdir (tmpdir), "could not remove directory from previous test") end io.write(".") io.flush() -- tries to create a directory assert (lfs.mkdir (tmpdir), "could not make a new directory") local attrib, errmsg = lfs.attributes (tmpdir) if not attrib then error ("could not get attributes of file `"..tmpdir.."':\n"..errmsg) end local f = io.open(tmpfile, "w") f:close() io.write(".") io.flush() -- Change access time local testdate = os.time({ year = 2007, day = 10, month = 2, hour=0}) assert (lfs.touch (tmpfile, testdate)) local new_att = assert (lfs.attributes (tmpfile)) assert (new_att.access == testdate, "could not set access time") assert (new_att.modification == testdate, "could not set modification time") io.write(".") io.flush() -- Change access and modification time local testdate1 = os.time({ year = 2007, day = 10, month = 2, hour=0}) local testdate2 = os.time({ year = 2007, day = 11, month = 2, hour=0}) assert (lfs.touch (tmpfile, testdate2, testdate1)) local new_att = assert (lfs.attributes (tmpfile)) assert (new_att.access == testdate2, "could not set access time") assert (new_att.modification == testdate1, "could not set modification time") io.write(".") io.flush() -- Checking link (does not work on Windows) if lfs.link (tmpfile, "_a_link_for_test_", true) then assert (lfs.attributes"_a_link_for_test_".mode == "file") assert (lfs.symlinkattributes"_a_link_for_test_".mode == "link") assert (lfs.link (tmpfile, "_a_hard_link_for_test_")) assert (lfs.attributes (tmpfile, "nlink") == 2) assert (os.remove"_a_link_for_test_") assert (os.remove"_a_hard_link_for_test_") end io.write(".") io.flush() -- Checking text/binary modes (only has an effect in Windows) local f = io.open(tmpfile, "w") local result, mode = lfs.setmode(f, "binary") assert(result) -- on non-Windows platforms, mode is always returned as "binary" result, mode = lfs.setmode(f, "text") assert(result and mode == "binary") f:close() io.write(".") io.flush() -- Restore access time to current value assert (lfs.touch (tmpfile, attrib.access, attrib.modification)) new_att = assert (lfs.attributes (tmpfile)) assert (new_att.access == attrib.access) assert (new_att.modification == attrib.modification) io.write(".") io.flush() -- Remove new file and directory assert (os.remove (tmpfile), "could not remove new file") assert (lfs.rmdir (tmpdir), "could not remove new directory") assert (lfs.mkdir (tmpdir..sep.."lfs_tmp_dir") == nil, "could create a directory inside a non-existent one") io.write(".") io.flush() -- Trying to get attributes of a non-existent file assert (lfs.attributes ("this couldn't be an actual file") == nil, "could get attributes of a non-existent file") assert (type(lfs.attributes (upper)) == "table", "couldn't get attributes of upper directory") io.write(".") io.flush() -- Stressing directory iterator count = 0 for i = 1, 4000 do for file in lfs.dir (tmp) do count = count + 1 end end io.write(".") io.flush() -- Stressing directory iterator, explicit version count = 0 for i = 1, 4000 do local iter, dir = lfs.dir(tmp) local file = dir:next() while file do count = count + 1 file = dir:next() end assert(not pcall(dir.next, dir)) end io.write(".") io.flush() -- directory explicit close local iter, dir = lfs.dir(tmp) dir:close() assert(not pcall(dir.next, dir)) print"Ok!"
apache-2.0
nesstea/darkstar
scripts/globals/mobskills/PW_Groundburst.lua
37
1035
--------------------------------------------- -- Groundburst -- -- Description: Expels a fireball on targets in an area of effect. -- Type: Physical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown radial -- Notes: Only used by notorious monsters, and from any Mamool Ja in besieged. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId(); if (mobSkin == 1863) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; 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,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
nesstea/darkstar
scripts/globals/mobskills/Dread_Dive.lua
33
1035
--------------------------------------------- -- Dread Dive -- -- Description: Dives into a single target. Additional effect: Knockback + Stun -- Type: Physical -- Utsusemi/Blink absorb: 1 shadow -- Range: Melee -- Notes: Used instead of Gliding Spike by certain notorious monsters. --------------------------------------------- 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.4; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local typeEffect = EFFECT_STUN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4); target:delHP(dmg); return dmg; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Tohka_Telposkha.lua
34
1040
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Tohka Telposkha -- 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(0x0297); 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
Mashape/kong
spec/03-plugins/14-request-termination/01-schema_spec.lua
2
2296
local schema_def = require "kong.plugins.request-termination.schema" local v = require("spec.helpers").validate_plugin_config_schema describe("Plugin: request-termination (schema)", function() it("should accept a valid status_code", function() assert(v({status_code = 404}, schema_def)) end) it("should accept a valid message", function() assert(v({message = "Not found"}, schema_def)) end) it("should accept a valid content_type", function() assert(v({content_type = "text/html",body = "<body><h1>Not found</h1>"}, schema_def)) end) it("should accept a valid body", function() assert(v({body = "<body><h1>Not found</h1>"}, schema_def)) end) describe("errors", function() it("status_code should only accept numbers", function() local ok, err = v({status_code = "abcd"}, schema_def) assert.falsy(ok) assert.same("expected an integer", err.config.status_code) end) it("status_code < 100", function() local ok, err = v({status_code = 99}, schema_def) assert.falsy(ok) assert.same("value should be between 100 and 599", err.config.status_code) end) it("status_code > 599", function() local ok,err = v({status_code = 600}, schema_def) assert.falsy(ok) assert.same("value should be between 100 and 599", err.config.status_code) end) it("#message with body", function() local ok, err = v({message = "error", body = "test"}, schema_def) assert.falsy(ok) assert.same("message cannot be used with content_type or body", err.config) end) it("message with body and content_type", function() local ok, err = v({message = "error", content_type="text/html", body = "test"}, schema_def) assert.falsy(ok) assert.same("message cannot be used with content_type or body", err.config) end) it("message with content_type", function() local ok, err = v({message = "error", content_type="text/html"}, schema_def) assert.falsy(ok) assert.same("message cannot be used with content_type or body", err.config) end) it("content_type without body", function() local ok, err = v({content_type="text/html"}, schema_def) assert.falsy(ok) assert.same("content_type requires a body", err.config) end) end) end)
apache-2.0
nesstea/darkstar
scripts/zones/Davoi/npcs/_45d.lua
13
1583
----------------------------------- -- Area: Davoi -- NPC: Wall of Banishing -- Used In Quest: Whence Blows the Wind -- @pos 181 0.1 -218 149 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then if (player:hasKeyItem(CRIMSON_ORB)) then player:startEvent(0x002a); else player:messageSpecial(CAVE_HAS_BEEN_SEALED_OFF); player:messageSpecial(MAY_BE_SOME_WAY_TO_BREAK); player:setVar("miniQuestForORB_CS",99); end end 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 == 0x002a and option == 0) then player:messageSpecial(POWER_OF_THE_ORB_ALLOW_PASS); npc:openDoor(12); -- needs retail timing end end;
gpl-3.0
nesstea/darkstar
scripts/zones/North_Gustaberg/MobIDs.lua
23
1385
----------------------------------- -- Area: North Gustaberg -- Comments: -- posX, posY, posZ --(Taken from 'mob_spawn_points' table) ----------------------------------- -- Stinging Sophie Stinging_Sophie=17211561; Stinging_Sophie_PH={ [17211532] = '1', -- 352.974, -40.359, 472.914 [17211534] = '1', -- 353.313, -40.347, 463.609 [17211535] = '1', -- 237.753, -40.500, 469.738 [17211533] = '1', -- 216.150, -41.182, 445.157 [17211536] = '1', -- 197.369, -40.612, 453.688 [17211531] = '1', -- 196.873, -40.415, 500.153 [17211556] = '1', -- 210.607, -40.478, 566.096 [17211557] = '1', -- 288.447, -40.842, 634.161 [17211558] = '1', -- 295.890, -41.593, 614.738 [17211560] = '1', -- 356.544, -40.528, 570.302 [17211559] = '1', -- 363.973, -40.774, 562.355 [17211581] = '1', -- 308.116, -60.352, 550.771 [17211582] = '1', -- 308.975, -61.082, 525.690 [17211580] = '1', -- 310.309, -60.634, 521.404 [17211583] = '1', -- 285.813, -60.784, 518.539 [17211579] = '1', -- 283.958, -60.926, 530.016 }; -- Maighdean Uaine Maighdean_Uaine=17211702; Maighdean_Uaine_PH={ [17211698] = '1', -- 121.242, -0.500, 654.504 [17211701] = '1', -- 176.458, -0.347, 722.666 [17211697] = '1', -- 164.140, 1.981, 740.020 [17211710] = '1', -- 239.992, -0.493, 788.037 [17211700] = '1', -- 203.606, -0.607, 721.541 [17211711] = '1', -- 289.709, -0.297, 750.252 };
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/ulbuconut.lua
36
1146
----------------------------------------- -- ID: 5966 -- Item: Ulbuconut -- Food Effect: 5 Min, All Races ----------------------------------------- -- Agility -3 -- Intelligence +1 ----------------------------------------- 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,5966); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -3); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
nesstea/darkstar
scripts/globals/spells/regen.lua
13
1625
----------------------------------------- -- Spell: Regen -- Gradually restores target's HP. ----------------------------------------- -- Cleric's Briault enhances the effect -- Scale down duration based on level -- Composure increases duration 3x ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local hp = 5; local meritBonus = caster:getMerit(MERIT_REGEN_EFFECT); --printf("Regen: Merit Bonus = Extra +%d", meritBonus); --TODO: put this into a mod? +1 hp PER TIER, would need a new mod local body = caster:getEquipID(SLOT_BODY); if (body == 15089 or body == 14502) then hp = hp+1; end hp = hp + caster:getMod(MOD_REGEN_EFFECT) + meritBonus; local duration = 75; duration = duration + caster:getMod(MOD_REGEN_DURATION); if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end duration = calculateDurationForLvl(duration, 21, target:getMainLvl()); if (target:hasStatusEffect(EFFECT_REGEN) and target:getStatusEffect(EFFECT_REGEN):getTier() == 1) then target:delStatusEffect(EFFECT_REGEN); end if (target:addStatusEffect(EFFECT_REGEN,hp,3,duration,0,0,0)) then spell:setMsg(230); else spell:setMsg(75); -- no effect end return EFFECT_REGEN; end;
gpl-3.0
nesstea/darkstar
scripts/globals/quests.lua
11
37448
require("scripts/globals/npc_util"); ----------------------------------- -- -- QUESTS ID -- ----------------------------------- QUEST_AVAILABLE = 0; QUEST_ACCEPTED = 1; QUEST_COMPLETED = 2; ----------------------------------- -- Areas ID ----------------------------------- SANDORIA = 0; BASTOK = 1; WINDURST = 2; JEUNO = 3; OTHER_AREAS = 4; OUTLANDS = 5; AHT_URHGAN = 6; CRYSTAL_WAR = 7; ABYSSEA = 8; ----------------------------------- -- San d'Oria - 0 ----------------------------------- A_SENTRY_S_PERIL = 0; -- ± -- WATER_OF_THE_CHEVAL = 1; -- ± -- ROSEL_THE_ARMORER = 2; -- ± -- THE_PICKPOCKET = 3; -- ± -- FATHER_AND_SON = 4; -- + -- THE_SEAMSTRESS = 5; -- + -- THE_DISMAYED_CUSTOMER = 6; -- + -- THE_TRADER_IN_THE_FOREST = 7; -- + -- THE_SWEETEST_THINGS = 8; -- + -- THE_VICASQUE_S_SERMON = 9; -- + -- A_SQUIRE_S_TEST = 10; -- + -- GRAVE_CONCERNS = 11; -- ± -- THE_BRUGAIRE_CONSORTIUM = 12; -- + -- LIZARD_SKINS = 15; -- + -- FLYERS_FOR_REGINE = 16; -- + -- GATES_TO_PARADISE = 18; -- + -- A_SQUIRE_S_TEST_II = 19; -- + -- TO_CURE_A_COUGH = 20; -- + -- TIGER_S_TEETH = 23; -- ± -- UNDYING_FLAMES = 26; -- + -- A_PURCHASE_OF_ARMS = 27; -- + -- A_KNIGHT_S_TEST = 29; -- + -- THE_MEDICINE_WOMAN = 30; -- + -- BLACK_TIGER_SKINS = 31; -- + -- GROWING_FLOWERS = 58; -- ± -- TRIAL_BY_ICE = 59; -- + -- THE_GENERAL_S_SECRET = 60; -- ± -- THE_RUMOR = 61; -- ± -- HER_MAJESTY_S_GARDEN = 62; -- + -- INTRODUCTION_TO_TEAMWORK = 63; INTERMEDIATE_TEAMWORK = 64; ADVANCED_TEAMWORK = 65; GRIMY_SIGNPOSTS = 66; -- + -- A_JOB_FOR_THE_CONSORTIUM = 67; TROUBLE_AT_THE_SLUICE = 68; -- + -- THE_MERCHANT_S_BIDDING = 69; -- ± -- UNEXPECTED_TREASURE = 70; BLACKMAIL = 71; -- + -- THE_SETTING_SUN = 72; -- + -- DISTANT_LOYALTIES = 74; THE_RIVALRY = 75; -- ± -- THE_COMPETITION = 76; -- ± -- STARTING_A_FLAME = 77; -- ± -- FEAR_OF_THE_DARK = 78; -- + -- WARDING_VAMPIRES = 79; -- + -- SLEEPLESS_NIGHTS = 80; -- ± -- LUFET_S_LAKE_SALT = 81; -- ± -- HEALING_THE_LAND = 82; -- ± -- SORCERY_OF_THE_NORTH = 83; -- ± -- THE_CRIMSON_TRIAL = 84; -- ± -- ENVELOPED_IN_DARKNESS = 85; -- ± -- PEACE_FOR_THE_SPIRIT = 86; -- ± -- MESSENGER_FROM_BEYOND = 87; -- ± -- PRELUDE_OF_BLACK_AND_WHITE = 88; -- ± -- PIEUJE_S_DECISION = 89; -- + -- SHARPENING_THE_SWORD = 90; -- ± -- A_BOY_S_DREAM = 91; -- ± -- UNDER_OATH = 92; THE_HOLY_CREST = 93; -- + -- A_CRAFTSMAN_S_WORK = 94; -- ± -- CHASING_QUOTAS = 95; -- + -- KNIGHT_STALKER = 96; -- + -- ECO_WARRIOR_SAN = 97; METHODS_CREATE_MADNESS = 98; SOULS_IN_SHADOW = 99; A_TASTE_FOR_MEAT = 100; -- ± -- EXIT_THE_GAMBLER = 101; -- ± -- OLD_WOUNDS = 102; ESCORT_FOR_HIRE_SAN_D_ORIA = 103; A_DISCERNING_EYE_SAN_D_ORIA = 104; A_TIMELY_VISIT = 105; FIT_FOR_A_PRINCE = 106; TRIAL_SIZE_TRIAL_BY_ICE = 107; -- + -- SIGNED_IN_BLOOD = 108; -- + -- TEA_WITH_A_TONBERRY = 109; SPICE_GALS = 110; OVER_THE_HILLS_AND_FAR_AWAY = 112; LURE_OF_THE_WILDCAT_SAN_D_ORIA = 113; -- ± -- ATELLOUNE_S_LAMENT = 114; THICK_SHELLS = 117; -- ± -- FOREST_FOR_THE_TREES = 118; ----------------------------------- -- Bastok - 1 ----------------------------------- THE_SIREN_S_TEAR = 0; -- ± -- BEAUTY_AND_THE_GALKA = 1; -- ± -- WELCOME_TO_BASTOK = 2; -- + -- GUEST_OF_HAUTEUR = 3; THE_QUADAV_S_CURSE = 4; -- ± -- OUT_OF_ONE_S_SHELL = 5; -- ± -- HEARTS_OF_MYTHRIL = 6; -- ± -- THE_ELEVENTH_S_HOUR = 7; -- ± -- SHADY_BUSINESS = 8; -- ± -- A_FOREMAN_S_BEST_FRIEND = 9; -- ± -- BREAKING_STONES = 10; -- + -- THE_COLD_LIGHT_OF_DAY = 11; -- + -- GOURMET = 12; -- ± -- THE_ELVAAN_GOLDSMITH = 13; -- ± -- A_FLASH_IN_THE_PAN = 14; -- ± -- SMOKE_ON_THE_MOUNTAIN = 15; -- ± -- STAMP_HUNT = 16; -- + -- FOREVER_TO_HOLD = 17; -- ± -- TILL_DEATH_DO_US_PART = 18; -- ± -- FALLEN_COMRADES = 19; -- ± -- RIVALS = 20; -- + -- MOM_THE_ADVENTURER = 21; -- + -- THE_SIGNPOST_MARKS_THE_SPOT = 22; -- + -- PAST_PERFECT = 23; -- ± -- STARDUST = 24; -- + -- MEAN_MACHINE = 25; -- ± -- CID_S_SECRET = 26; -- ± -- THE_USUAL = 27; -- ± -- BLADE_OF_DARKNESS = 28; -- ± -- FATHER_FIGURE = 29; -- ± -- THE_RETURN_OF_THE_ADVENTURER = 30; -- ± -- DRACHENFALL = 31; -- + -- VENGEFUL_WRATH = 32; -- ± -- BEADEAUX_SMOG = 33; -- + -- THE_CURSE_COLLECTOR = 34; -- + -- FEAR_OF_FLYING = 35; -- + -- THE_WISDOM_OF_ELDERS = 36; -- ± -- GROCERIES = 37; -- ± -- THE_BARE_BONES = 38; -- ± -- MINESWEEPER = 39; -- ± -- THE_DARKSMITH = 40; -- ± -- BUCKETS_OF_GOLD = 41; -- ± -- THE_STARS_OF_IFRIT = 42; -- ± -- LOVE_AND_ICE = 43; -- ± -- BRYGID_THE_STYLIST = 44; -- ± -- THE_GUSTABERG_TOUR = 45; BITE_THE_DUST = 46; -- ± -- BLADE_OF_DEATH = 47; -- + -- SILENCE_OF_THE_RAMS = 48; -- ± -- ALTANA_S_SORROW = 49; -- + -- A_LADY_S_HEART = 50; -- ± -- GHOSTS_OF_THE_PAST = 51; -- ± -- THE_FIRST_MEETING = 52; -- ± -- TRUE_STRENGTH = 53; -- ± -- THE_DOORMAN = 54; -- ± -- THE_TALEKEEPER_S_TRUTH = 55; -- ± -- THE_TALEKEEPER_S_GIFT = 56; -- ± -- DARK_LEGACY = 57; -- ± -- DARK_PUPPET = 58; -- ± -- BLADE_OF_EVIL = 59; -- ± -- AYAME_AND_KAEDE = 60; -- ± -- TRIAL_BY_EARTH = 61; -- ± -- A_TEST_OF_TRUE_LOVE = 62; -- ± -- LOVERS_IN_THE_DUSK = 63; -- ± -- WISH_UPON_A_STAR = 64; ECO_WARRIOR_BAS = 65; THE_WEIGHT_OF_YOUR_LIMITS = 66; SHOOT_FIRST_ASK_QUESTIONS_LATER = 67; INHERITANCE = 68; THE_WALLS_OF_YOUR_MIND = 69; ESCORT_FOR_HIRE_BASTOK = 70; A_DISCERNING_EYE_BASTOK = 71; TRIAL_SIZE_TRIAL_BY_EARTH = 72; -- + -- FADED_PROMISES = 73; BRYGID_THE_STYLIST_RETURNS = 74; -- ± -- OUT_OF_THE_DEPTHS = 75; ALL_BY_MYSELF = 76; A_QUESTION_OF_FAITH = 77; RETURN_OF_THE_DEPTHS = 78; TEAK_ME_TO_THE_STARS = 79; HYPER_ACTIVE = 80; THE_NAMING_GAME = 81; CHIPS = 82; BAIT_AND_SWITCH = 83; LURE_OF_THE_WILDCAT_BASTOK = 84; ACHIEVING_TRUE_POWER = 85; TOO_MANY_CHEFS = 86; A_PROPER_BURIAL = 87; FULLY_MENTAL_ALCHEMIST = 88; SYNERGUSTIC_PURSUITS = 89; THE_WONDROUS_WHATCHAMACALLIT = 90; ----------------------------------- -- Windurst - 2 ----------------------------------- HAT_IN_HAND = 0; -- + -- A_FEATHER_IN_ONE_S_CAP = 1; -- + -- A_CRISIS_IN_THE_MAKING = 2; -- + -- MAKING_AMENDS = 3; -- + -- MAKING_THE_GRADE = 4; -- + -- IN_A_PICKLE = 5; -- + -- WONDERING_MINSTREL = 6; -- + -- A_POSE_BY_ANY_OTHER_NAME = 7; -- + -- MAKING_AMENS = 8; -- + -- THE_MOONLIT_PATH = 9; -- + -- STAR_STRUCK = 10; -- ± -- BLAST_FROM_THE_PAST = 11; -- + -- A_SMUDGE_ON_ONE_S_RECORD = 12; -- ± -- CHASING_TALES = 13; -- + -- FOOD_FOR_THOUGHT = 14; -- + -- OVERNIGHT_DELIVERY = 15; -- + -- WATER_WAY_TO_GO = 16; -- + -- BLUE_RIBBON_BLUES = 17; -- + -- THE_ALL_NEW_C_3000 = 18; -- + -- THE_POSTMAN_ALWAYS_KO_S_TWICE = 19; -- + -- EARLY_BIRD_CATCHES_THE_BOOKWORM = 20; -- + -- CATCH_IT_IF_YOU_CAN = 21; -- + -- ALL_AT_SEA = 23; THE_ALL_NEW_C_2000 = 24; -- ± -- MIHGO_S_AMIGO = 25; -- + -- ROCK_RACKETTER = 26; -- + -- CHOCOBILIOUS = 27; -- + -- TEACHER_S_PET = 28; -- + -- REAP_WHAT_YOU_SOW = 29; -- + -- GLYPH_HANGER = 30; -- + -- THE_FANGED_ONE = 31; -- + -- CURSES_FOILED_AGAIN_1 = 32; -- + -- CURSES_FOILED_AGAIN_2 = 33; -- + -- MANDRAGORA_MAD = 34; -- + -- TO_BEE_OR_NOT_TO_BEE = 35; -- + -- TRUTH_JUSTICE_AND_THE_ONION_WAY = 36; -- + -- MAKING_HEADLINES = 37; -- + -- SCOOPED = 38; CREEPY_CRAWLIES = 39; -- + -- KNOW_ONE_S_ONIONS = 40; -- + -- INSPECTOR_S_GADGET = 41; -- + -- ONION_RINGS = 42; -- + -- A_GREETING_CARDIAN = 43; -- + -- LEGENDARY_PLAN_B = 44; -- + -- IN_A_STEW = 45; -- + -- LET_SLEEPING_DOGS_LIE = 46; CAN_CARDIANS_CRY = 47; -- + -- WONDER_WANDS = 48; -- + -- HEAVEN_CENT = 49; SAY_IT_WITH_FLOWERS = 50; -- + -- HOIST_THE_JELLY_ROGER = 51; -- + -- SOMETHING_FISHY = 52; -- + -- TO_CATCH_A_FALLIHG_STAR = 53; -- + -- PAYING_LIP_SERVICE = 60; -- + -- THE_AMAZIN_SCORPIO = 61; -- + -- TWINSTONE_BONDING = 62; -- + -- CURSES_FOILED_A_GOLEM = 63; -- + -- ACTING_IN_GOOD_FAITH = 64; -- ± -- FLOWER_CHILD = 65; -- ± -- THE_THREE_MAGI = 66; -- ± -- RECOLLECTIONS = 67; -- ± -- THE_ROOT_OF_THE_PROBLEM = 68; THE_TENSHODO_SHOWDOWN = 69; -- + -- AS_THICK_AS_THIEVES = 70; -- + -- HITTING_THE_MARQUISATE = 71; -- + -- SIN_HUNTING = 72; -- + -- FIRE_AND_BRIMSTONE = 73; -- + -- UNBRIDLED_PASSION = 74; -- + -- I_CAN_HEAR_A_RAINBOW = 75; -- + -- CRYING_OVER_ONIONS = 76; -- + -- WILD_CARD = 77; -- + -- THE_PROMISE = 78; -- + -- NOTHING_MATTERS = 79; TORAIMARAI_TURMOIL = 80; -- + -- THE_PUPPET_MASTER = 81; -- + -- CLASS_REUNION = 82; -- + -- CARBUNCLE_DEBACLE = 83; -- + -- ECO_WARRIOR_WIN = 84; -- + -- FROM_SAPLINGS_GROW = 85; ORASTERY_WOES = 86; BLOOD_AND_GLORY = 87; ESCORT_FOR_HIRE_WINDURST = 88; A_DISCERNING_EYE_WINDURST = 89; TUNING_IN = 90; TUNING_OUT = 91; ONE_GOOD_DEED = 92; WAKING_DREAMS = 93; -- + -- LURE_OF_THE_WILDCAT_WINDURST = 94; BABBAN_NY_MHEILLEA = 95; ----------------------------------- -- Jeuno - 3 ----------------------------------- CREST_OF_DAVOI = 0; -- + -- SAVE_MY_SISTER = 1; -- + -- A_CLOCK_MOST_DELICATE = 2; -- + -- SAVE_THE_CLOCK_TOWER = 3; -- + -- CHOCOBO_S_WOUNDS = 4; -- + -- SAVE_MY_SON = 5; -- + -- A_CANDLELIGHT_VIGIL = 6; -- + -- THE_WONDER_MAGIC_SET = 7; -- + -- THE_KIND_CARDIAN = 8; -- + -- YOUR_CRYSTAL_BALL = 9; -- + -- COLLECT_TARUT_CARDS = 10; -- + -- THE_OLD_MONUMENT = 11; -- + -- A_MINSTREL_IN_DESPAIR = 12; -- + -- RUBBISH_DAY = 13; -- + -- NEVER_TO_RETURN = 14; -- + -- COMMUNITY_SERVICE = 15; -- + -- COOK_S_PRIDE = 16; -- + -- TENSHODO_MEMBERSHIP = 17; -- + -- THE_LOST_CARDIAN = 18; -- + -- PATH_OF_THE_BEASTMASTER = 19; -- + -- PATH_OF_THE_BARD = 20; -- + -- THE_CLOCKMASTER = 21; -- + -- CANDLE_MAKING = 22; -- + -- CHILD_S_PLAY = 23; -- + -- NORTHWARD = 24; -- + -- THE_ANTIQUE_COLLECTOR = 25; -- + -- DEAL_WITH_TENSHODO = 26; -- + -- THE_GOBBIEBAG_PART_I = 27; -- + -- THE_GOBBIEBAG_PART_II = 28; -- + -- THE_GOBBIEBAG_PART_III = 29; -- + -- THE_GOBBIEBAG_PART_IV = 30; -- + -- MYSTERIES_OF_BEADEAUX_I = 31; -- + -- MYSTERIES_OF_BEADEAUX_II = 32; -- + -- MYSTERY_OF_FIRE = 33; MYSTERY_OF_WATER = 34; MYSTERY_OF_EARTH = 35; MYSTERY_OF_WIND = 36; MYSTERY_OF_ICE = 37; MYSTERY_OF_LIGHTNING = 38; MYSTERY_OF_LIGHT = 39; MYSTERY_OF_DARKNESS = 40; FISTFUL_OF_FURY = 41; -- + -- THE_GOBLIN_TAILOR = 42; -- + -- PRETTY_LITTLE_THINGS = 43; -- ± -- BORGHERTZ_S_WARRING_HANDS = 44; -- + -- BORGHERTZ_S_STRIKING_HANDS = 45; -- + -- BORGHERTZ_S_HEALING_HANDS = 46; -- + -- BORGHERTZ_S_SORCEROUS_HANDS = 47; -- + -- BORGHERTZ_S_VERMILLION_HANDS = 48; -- + -- BORGHERTZ_S_SNEAKY_HANDS = 49; -- + -- BORGHERTZ_S_STALWART_HANDS = 50; -- + -- BORGHERTZ_S_SHADOWY_HANDS = 51; -- + -- BORGHERTZ_S_WILD_HANDS = 52; -- + -- BORGHERTZ_S_HARMONIOUS_HANDS = 53; -- + -- BORGHERTZ_S_CHASING_HANDS = 54; -- + -- BORGHERTZ_S_LOYAL_HANDS = 55; -- + -- BORGHERTZ_S_LURKING_HANDS = 56; -- + -- BORGHERTZ_S_DRAGON_HANDS = 57; -- + -- BORGHERTZ_S_CALLING_HANDS = 58; -- + -- AXE_THE_COMPETITION = 59; WINGS_OF_GOLD = 60; -- ± -- SCATTERED_INTO_SHADOW = 61; -- ± -- A_NEW_DAWN = 62; PAINFUL_MEMORY = 63; -- + -- THE_REQUIEM = 64; -- + -- THE_CIRCLE_OF_TIME = 65; -- + -- SEARCHING_FOR_THE_RIGHT_WORDS = 66; BEAT_AROUND_THE_BUSHIN = 67; -- + -- DUCAL_HOSPITALITY = 68; IN_THE_MOOD_FOR_LOVE = 69; EMPTY_MEMORIES = 70; HOOK_LINE_AND_SINKER = 71; A_CHOCOBO_S_TALE = 72; A_REPUTATION_IN_RUINS = 73; THE_GOBBIEBAG_PART_V = 74; -- + -- THE_GOBBIEBAG_PART_VI = 75; -- + -- BEYOND_THE_SUN = 76; UNLISTED_QUALITIES = 77; GIRL_IN_THE_LOOKING_GLASS = 78; MIRROR_MIRROR = 79; -- + -- PAST_REFLECTIONS = 80; BLIGHTED_GLOOM = 81; BLESSED_RADIANCE = 82; MIRROR_IMAGES = 83; CHAMELEON_CAPERS = 84; REGAINING_TRUST = 85; STORMS_OF_FATE = 86; MIXED_SIGNALS = 87; SHADOWS_OF_THE_DEPARTED = 88; APOCALYPSE_NIGH = 89; LURE_OF_THE_WILDCAT_JEUNO = 90; -- ± -- THE_ROAD_TO_AHT_URHGAN = 91; -- + -- CHOCOBO_ON_THE_LOOSE = 92; THE_GOBBIEBAG_PART_VII = 93; -- + -- THE_GOBBIEBAG_PART_VIII = 94; -- + -- LAKESIDE_MINUET = 95; THE_UNFINISHED_WALTZ = 96; -- ± -- THE_ROAD_TO_DIVADOM = 97; COMEBACK_QUEEN = 98; A_FURIOUS_FINALE = 99; THE_MIRACULOUS_DALE = 100; CLASH_OF_THE_COMRADES = 101; UNLOCKING_A_MYTH_WARRIOR = 102; UNLOCKING_A_MYTH_MONK = 103; UNLOCKING_A_MYTH_WHITE_MAGE = 104; UNLOCKING_A_MYTH_BLACK_MAGE = 105; UNLOCKING_A_MYTH_RED_MAGE = 106; UNLOCKING_A_MYTH_THIEF = 107; UNLOCKING_A_MYTH_PALADIN = 108; UNLOCKING_A_MYTH_DARK_KNIGHT = 109; UNLOCKING_A_MYTH_BEASTMASTER = 110; UNLOCKING_A_MYTH_BARD = 111; UNLOCKING_A_MYTH_RANGER = 112; UNLOCKING_A_MYTH_SAMURAI = 113; UNLOCKING_A_MYTH_NINJA = 114; UNLOCKING_A_MYTH_DRAGOON = 115; UNLOCKING_A_MYTH_SUMMONER = 116; UNLOCKING_A_MYTH_BLUE_MAGE = 117; UNLOCKING_A_MYTH_CORSAIR = 118; UNLOCKING_A_MYTH_PUPPETMASTER = 119; UNLOCKING_A_MYTH_DANCER = 120; UNLOCKING_A_MYTH_SCHOLAR = 121; THE_GOBBIEBAG_PART_IX = 123; -- + -- THE_GOBBIEBAG_PART_X = 124; -- + -- IN_DEFIANT_CHALLENGE = 128; -- + -- ATOP_THE_HIGHEST_MOUNTAINS = 129; -- + -- WHENCE_BLOWS_THE_WIND = 130; -- + -- RIDING_ON_THE_CLOUDS = 131; -- + -- SHATTERING_STARS = 132; -- + -- NEW_WORLDS_AWAIT = 133; EXPANDING_HORIZONS = 134; BEYOND_THE_STARS = 135; DORMANT_POWERS_DISLODGED = 136; BEYOND_INFINITY = 137; A_TRIAL_IN_TANDEM = 160; A_TRIAL_IN_TANDEM_REDUX = 161; YET_ANOTHER_TRIAL_IN_TANDEM = 162; A_QUATERNARY_TRIAL_IN_TANDEM = 163; A_TRIAL_IN_TANDEM_REVISITED = 164; ALL_IN_THE_CARDS = 166; MARTIAL_MASTERY = 167; VW_OP_115_VALKURM_DUSTER = 168; VW_OP_118_BUBURIMU_SQUALL = 169; PRELUDE_TO_PUISSANCE = 170; ----------------------------------- -- Other Areas - 4 ----------------------------------- RYCHARDE_THE_CHEF = 0; -- + -- WAY_OF_THE_COOK = 1; -- + -- UNENDING_CHASE = 2; -- + -- HIS_NAME_IS_VALGEIR = 3; -- + -- EXPERTISE = 4; -- + -- THE_CLUE = 5; -- + -- THE_BASICS = 6; -- + -- ORLANDO_S_ANTIQUES = 7; -- + -- THE_SAND_CHARM = 8; -- + -- A_POTTER_S_PREFERENCE = 9; -- + -- THE_OLD_LADY = 10; -- + -- FISHERMAN_S_HEART = 11; DONATE_TO_RECYCLING = 16; -- + -- UNDER_THE_SEA = 17; -- + -- ONLY_THE_BEST = 18; -- + -- EN_EXPLORER_S_FOOTSTEPS = 19; -- + -- CARGO = 20; -- + -- THE_GIFT = 21; -- + -- THE_REAL_GIFT = 22; -- + -- THE_RESCUE = 23; -- + -- ELDER_MEMORIES = 24; -- + -- TEST_MY_METTLE = 25; INSIDE_THE_BELLY = 26; -- ± -- TRIAL_BY_LIGHTNING = 27; -- ± -- TRIAL_SIZE_TRIAL_BY_LIGHTNING = 28; -- + -- IT_S_RAINING_MANNEQUINS = 29; RECYCLING_RODS = 30; PICTURE_PERFECT = 31; WAKING_THE_BEAST = 32; SURVIVAL_OF_THE_WISEST = 33; A_HARD_DAY_S_KNIGHT = 64; X_MARKS_THE_SPOT = 65; A_BITTER_PAST = 66; THE_CALL_OF_THE_SEA = 67; PARADISE_SALVATION_AND_MAPS = 68; GO_GO_GOBMUFFIN = 69; THE_BIG_ONE = 70; FLY_HIGH = 71; UNFORGIVEN = 72; SECRETS_OF_OVENS_LOST = 73; PETALS_FOR_PARELBRIAUX = 74; ELDERLY_PURSUITS = 75; IN_THE_NAME_OF_SCIENCE = 76; BEHIND_THE_SMILE = 77; KNOCKING_ON_FORBIDDEN_DOORS = 78; CONFESSIONS_OF_A_BELLMAKER = 79; IN_SEARCH_OF_THE_TRUTH = 80; UNINVITED_GUESTS = 81; TANGO_WITH_A_TRACKER = 82; REQUIEM_OF_SIN = 83; VW_OP_026_TAVNAZIAN_TERRORS = 84; VW_OP_004_BIBIKI_BOMBARDMENT = 85; BOMBS_AWAY = 96; MITHRAN_DELICACIES = 97; GIVE_A_MOOGLE_A_BREAK = 100; THE_MOOGLE_PICNIC = 101; MOOGLE_IN_THE_WILD = 102; MISSIONARY_MOBLIN = 103; FOR_THE_BIRDS = 104; BETTER_THE_DEMON_YOU_KNOW = 105; AN_UNDERSTANDING_OVERLORD = 106; AN_AFFABLE_ADAMANTKING = 107; A_MORAL_MANIFEST = 108; A_GENEROUS_GENERAL = 109; RECORDS_OF_EMINENCE = 110; UNITY_CONCORD = 111; ----------------------------------- -- Outlands - 5 ----------------------------------- -- Kazham (1-15) THE_FIREBLOOM_TREE = 1; GREETINGS_TO_THE_GUARDIAN = 2; -- + -- A_QUESTION_OF_TASTE = 3; EVERYONES_GRUDGING = 4; YOU_CALL_THAT_A_KNIFE = 6; MISSIONARY_MAN = 7; -- ± -- GULLIBLES_TRAVELS = 8; -- + -- EVEN_MORE_GULLIBLES_TRAVELS = 9; -- + -- PERSONAL_HYGIENE = 10; -- + -- THE_OPO_OPO_AND_I = 11; -- + -- TRIAL_BY_FIRE = 12; -- ± -- CLOAK_AND_DAGGER = 13; A_DISCERNING_EYE_KAZHAM = 14; TRIAL_SIZE_TRIAL_BY_FIRE = 15; -- + -- -- Voidwatch (100-105) VOIDWATCH_OPS_BORDER_CROSSING = 100; VW_OP_054_ELSHIMO_LIST = 101; VW_OP_101_DETOUR_TO_ZEPWELL = 102; VW_OP_115_LI_TELOR_VARIANT = 103; SKYWARD_HO_VOIDWATCHER = 104; -- Norg (128-149) THE_SAHAGINS_KEY = 128; -- ± -- FORGE_YOUR_DESTINY = 129; -- ± -- BLACK_MARKET = 130; MAMA_MIA = 131; STOP_YOUR_WHINING = 132; -- + -- TRIAL_BY_WATER = 133; -- + -- EVERYONES_GRUDGE = 134; SECRET_OF_THE_DAMP_SCROLL = 135; -- ± -- THE_SAHAGINS_STASH = 136; -- + -- ITS_NOT_YOUR_VAULT = 137; -- + -- LIKE_A_SHINING_SUBLIGAR = 138; -- + -- LIKE_A_SHINING_LEGGINGS = 139; -- + -- THE_SACRED_KATANA = 140; -- ± -- YOMI_OKURI = 141; -- ± -- A_THIEF_IN_NORG = 142; -- ± -- TWENTY_IN_PIRATE_YEARS = 143; -- ± -- I_LL_TAKE_THE_BIG_BOX = 144; -- ± -- TRUE_WILL = 145; -- ± -- THE_POTENTIAL_WITHIN = 146; BUGI_SODEN = 147; TRIAL_SIZE_TRIAL_BY_WATER = 148; -- + -- AN_UNDYING_PLEDGE = 149; -- Misc (160-165) WRATH_OF_THE_OPO_OPOS = 160; WANDERING_SOULS = 161; SOUL_SEARCHING = 162; DIVINE_MIGHT = 163; -- ± -- DIVINE_MIGHT_REPEAT = 164; -- ± -- OPEN_SESAME = 165; -- Rabao (192-201) DONT_FORGET_THE_ANTIDOTE = 192; -- ± -- THE_MISSING_PIECE = 193; -- ± -- TRIAL_BY_WIND = 194; -- ± -- THE_KUFTAL_TOUR = 195; THE_IMMORTAL_LU_SHANG = 196; -- ± -- TRIAL_SIZE_TRIAL_BY_WIND = 197; -- ± -- CHASING_DREAMS = 199; -- CoP Quest THE_SEARCH_FOR_GOLDMANE = 200; -- CoP Quest INDOMITABLE_SPIRIT = 201; -- ± -- ----------------------------------- -- Aht Urhgan - 6 ----------------------------------- KEEPING_NOTES = 0; ARTS_AND_CRAFTS = 1; OLDUUM = 2; -- + -- GOT_IT_ALL = 3; -- + -- GET_THE_PICTURE = 4; AN_EMPTY_VESSEL = 5; -- + -- LUCK_OF_THE_DRAW = 6; -- ± -- NO_STRINGS_ATTACHED = 7; -- + -- FINDING_FAULTS = 8; GIVE_PEACE_A_CHANCE = 9; THE_ART_OF_WAR = 10; na = 11; A_TASTE_OF_HONEY = 12; SUCH_SWEET_SORROW = 13; FEAR_OF_THE_DARK_II = 14; -- + -- COOK_A_ROON = 15; THE_DIE_IS_CAST = 16; TWO_HORN_THE_SAVAGE = 17; TOTOROONS_TREASURE_HUNT = 18; WHAT_FRIENDS_ARE_FOR = 19; ROCK_BOTTOM = 20; BEGINNINGS = 21; OMENS = 22; TRANSFORMATIONS = 23; EQUIPED_FOR_ALL_OCCASIONS = 24; -- + -- NAVIGATING_THE_UNFRIENDLY_SEAS = 25; -- + -- AGAINST_ALL_ODDS = 26; THE_WAYWARD_AUTOMATION = 27; OPERATION_TEATIME = 28; PUPPETMASTER_BLUES = 29; MOMENT_OF_TRUTH = 30; THREE_MEN_AND_A_CLOSET = 31; -- + -- FIVE_SECONDS_OF_FAME = 32; DELIVERING_THE_GOODS = 61; -- + -- VANISHING_ACT = 62; -- + -- STRIKING_A_BALANCE = 63; NOT_MEANT_TO_BE = 64; -- + -- LED_ASTRAY = 65; RAT_RACE = 66; -- + -- THE_PRINCE_AND_THE_HOPPER = 67; VW_OP_050_AHT_URGAN_ASSAULT = 68; VW_OP_068_SUBTERRAINEAN_SKIRMISH= 69; AN_IMPERIAL_HEIST = 70; DUTIES_TASKS_AND_DEEDS = 71; FORGING_A_NEW_MYTH = 72; COMING_FULL_CIRCLE = 73; WAKING_THE_COLLOSSUS = 74; DIVINE_INTERFERANCE = 75; THE_RIDER_COMETH = 76; UNWAVERING_RESOLVE = 77; A_STYGIAN_PACT = 78; ----------------------------------- -- Crystal War - 7 ----------------------------------- LOST_IN_TRANSLOCATION = 0; MESSAGE_ON_THE_WINDS = 1; THE_WEEKLY_ADVENTURER = 2; HEALING_HERBS = 3; REDEEMING_ROCKS = 4; THE_DAWN_OF_DELECTABILITY = 5; A_LITTLE_KNOWLEDGE = 6; -- + -- THE_FIGHTING_FOURTH = 7; SNAKE_ON_THE_PLAINS = 8; -- + -- STEAMED_RAMS = 9; -- + -- SEEING_SPOTS = 10; -- + -- THE_FLIPSIDE_OF_THINGS = 11; BETTER_PART_OF_VALOR = 12; FIRES_OF_DISCONTENT = 13; HAMMERING_HEARTS = 14; GIFTS_OF_THE_GRIFFON = 15; CLAWS_OF_THE_GRIFFON = 16; THE_TIGRESS_STIRS = 17; -- + -- THE_TIGRESS_STRIKES = 18; LIGHT_IN_THE_DARKNESS = 19; BURDEN_OF_SUSPICION = 20; EVIL_AT_THE_INLET = 21; THE_FUMBLING_FRIAR = 22; REQUIEM_FOR_THE_DEPARTED = 23; BOY_AND_THE_BEAST = 24; WRATH_OF_THE_GRIFFON = 25; THE_LOST_BOOK = 26; KNOT_QUITE_THERE = 27; A_MANIFEST_PROBLEM = 28; BEANS_AHOY = 29; -- + -- BEAST_FROM_THE_EAST = 30; THE_SWARM = 31; ON_SABBATICAL = 32; DOWNWARD_HELIX = 33; SEEING_BLOOD_RED = 34; STORM_ON_THE_HORIZON = 35; FIRE_IN_THE_HOLE = 36; PERILS_OF_THE_GRIFFON = 37; IN_A_HAZE_OF_GLORY = 38; WHEN_ONE_MAN_IS_NOT_ENOUGH = 39; A_FEAST_FOR_GNATS = 40; SAY_IT_WITH_A_HANDBAG = 41; QUELLING_THE_STORM = 42; HONOR_UNDER_FIRE = 43; THE_PRICE_OF_VALOR = 44; BONDS_THAT_NEVER_DIE = 45; THE_LONG_MARCH_NORTH = 46; THE_FORBIDDEN_PATH = 47; A_JEWELERS_LAMENT = 48; BENEATH_THE_MASK = 49; WHAT_PRICE_LOYALTY = 50; SONGBIRDS_IN_A_SNOWSTORM = 51; BLOOD_OF_HEROES = 52; SINS_OF_THE_MOTHERS = 53; HOWL_FROM_THE_HEAVENS = 54; SUCCOR_TO_THE_SIDHE = 55; THE_YOUNG_AND_THE_THREADLESS = 56; SON_AND_FATHER = 57; THE_TRUTH_LIES_HID = 58; BONDS_OF_MYTHRIL = 59; CHASING_SHADOWS = 60; FACE_OF_THE_FUTURE = 61; MANIFEST_DESTINY = 62; AT_JOURNEYS_END = 63; HER_MEMORIES_HOMECOMING_QUEEN = 64; HER_MEMORIES_OLD_BEAN = 65; HER_MEMORIES_THE_FAUX_PAS = 66; HER_MEMORIES_THE_GRAVE_RESOLVE = 67; HER_MEMORIES_OPERATION_CUPID = 68; HER_MEMORIES_CARNELIAN_FOOTFALLS = 69; HER_MEMORIES_AZURE_FOOTFALLS = 70; HER_MEMORIES_VERDURE_FOOTFALLS = 71; HER_MEMORIES_OF_MALIGN_MALADIES = 72; GUARDIAN_OF_THE_VOID = 80; DRAFTED_BY_THE_DUCHY = 81; BATTLE_ON_A_NEW_FRONT = 82; VOIDWALKER_OP_126 = 83; A_CAIT_CALLS = 84; THE_TRUTH_IS_OUT_THERE = 85; REDRAFTED_BY_THE_DUCHY = 86; A_NEW_MENACE = 87; NO_REST_FOR_THE_WEARY = 88; A_WORLD_IN_FLUX = 89; BETWEEN_A_ROCK_AND_RIFT = 90; A_FAREWELL_TO_FELINES = 91; THIRD_TOUR_OF_DUCHY = 92; GLIMMER_OF_HOPE = 93; BRACE_FOR_THE_UNKNOWN = 94; PROVENANCE = 95; CRYSTAL_GUARDIAN = 96; ENDINGS_AND_BEGINNINGS = 97; AD_INFINITUM = 98; ----------------------------------- -- Abyssea - 8 ----------------------------------- -- For some reason these did not match dat file order, -- had to adjust IDs >120 after using @addquest CATERING_CAPERS = 0; GIFT_OF_LIGHT = 1; FEAR_OF_THE_DARK_III = 2; AN_EYE_FOR_REVENGE = 3; UNBREAK_HIS_HEART = 4; EXPLOSIVE_ENDEAVORS = 5; THE_ANGLING_ARMORER = 6; WATER_OF_LIFE = 7; OUT_OF_TOUCH = 8; LOST_MEMORIES = 9; HOPE_BLOOMS_ON_THE_BATTLEFIELD = 10; OF_MALNOURISHED_MARTELLOS = 11; ROSE_ON_THE_HEATH = 12; FULL_OF_HIMSELF_ALCHEMIST = 13; THE_WALKING_WOUNDED = 14; SHADY_BUSINESS_REDUX = 15; ADDLED_MIND_UNDYING_DREAMS = 16; THE_SOUL_OF_THE_MATTER = 17; SECRET_AGENT_MAN = 18; PLAYING_PAPARAZZI = 19; HIS_BOX_HIS_BELOVED = 20; WEAPONS_NOT_WORRIES = 21; CLEANSING_THE_CANYON = 22; SAVORY_SALVATION = 23; BRINGING_DOWN_THE_MOUNTAIN = 24; A_STERLING_SPECIMEN = 25; FOR_LOVE_OF_A_DAUGHTER = 26; SISTERS_IN_CRIME = 27; WHEN_GOOD_CARDIANS_GO_BAD = 28; TANGLING_WITH_TONGUE_TWISTERS = 29; A_WARD_TO_END_ALL_WARDS = 30; THE_BOXWATCHERS_BEHEST = 31; HIS_BRIDGE_HIS_BELOVED = 32; BAD_COMMUNICATION = 33; FAMILY_TIES = 34; AQUA_PURA = 35; AQUA_PURAGA = 36; WHITHER_THE_WHISKER = 37; SCATTERED_SHELLS_SCATTERED_MIND = 38; WAYWARD_WARES = 39; LOOKING_FOR_LOOKOUTS = 40; FLOWN_THE_COOP = 41; THREADBARE_TRIBULATIONS = 42; AN_OFFER_YOU_CANT_REFUSE = 43; SOMETHING_IN_THE_AIR = 44; AN_ACRIDIDAEN_ANODYNE = 45; HAZY_PROSPECTS = 46; FOR_WANT_OF_A_POT = 47; MISSING_IN_ACTION = 48; I_DREAM_OF_FLOWERS = 49; DESTINY_ODYSSEY = 50; UNIDENTIFIED_RESEARCH_OBJECT = 51; COOKBOOK_OF_HOPE_RESTORING = 52; SMOKE_OVER_THE_COAST = 53; SOIL_AND_GREEN = 54; DROPPING_THE_BOMB = 55; WANTED_MEDICAL_SUPPLIES = 56; VOICES_FROM_BEYOND = 57; BENEVOLENCE_LOST = 58; BRUGAIRES_AMBITION = 59; CHOCOBO_PANIC = 60; THE_EGG_ENTHUSIAST = 61; GETTING_LUCKY = 62; HER_FATHERS_LEGACY = 63; THE_MYSTERIOUS_HEAD_PATROL = 64; MASTER_MISSING_MASTER_MISSED = 65; THE_PERILS_OF_KORORO = 66; LET_THERE_BE_LIGHT = 67; LOOK_OUT_BELOW = 68; HOME_HOME_ON_THE_RANGE = 69; IMPERIAL_ESPIONAGE = 70; IMPERIAL_ESPIONAGE_II = 71; BOREAL_BLOSSOMS = 72; BROTHERS_IN_ARMS = 73; SCOUTS_ASTRAY = 74; FROZEN_FLAME_REDUX = 75; SLIP_SLIDIN_AWAY = 76; CLASSROOMS_WITHOUT_BORDERS = 77; THE_SECRET_INGREDIENT = 78; HELP_NOT_WANTED = 79; THE_TITUS_TOUCH = 80; SLACKING_SUBORDINATES = 81; MOTHERLY_LOVE = 82; LOOK_TO_THE_SKY = 83; THE_UNMARKED_TOMB = 84; PROOF_OF_THE_LION = 85; BRYGID_THE_STYLIST_STRIKES_BACK = 86; DOMINION_OP_01_ALTEPA = 87; DOMINION_OP_02_ALTEPA = 88; DOMINION_OP_03_ALTEPA = 89; DOMINION_OP_04_ALTEPA = 90; DOMINION_OP_05_ALTEPA = 91; DOMINION_OP_06_ALTEPA = 92; DOMINION_OP_07_ALTEPA = 93; DOMINION_OP_08_ALTEPA = 94; DOMINION_OP_09_ALTEPA = 95; DOMINION_OP_10_ALTEPA = 96; DOMINION_OP_11_ALTEPA = 97; DOMINION_OP_12_ALTEPA = 98; DOMINION_OP_13_ALTEPA = 99; DOMINION_OP_14_ALTEPA = 100; DOMINION_OP_01_ULEGUERAND = 101; DOMINION_OP_02_ULEGUERAND = 102; DOMINION_OP_03_ULEGUERAND = 103; DOMINION_OP_04_ULEGUERAND = 104; DOMINION_OP_05_ULEGUERAND = 105; DOMINION_OP_06_ULEGUERAND = 106; DOMINION_OP_07_ULEGUERAND = 107; DOMINION_OP_08_ULEGUERAND = 108; DOMINION_OP_09_ULEGUERAND = 109; DOMINION_OP_10_ULEGUERAND = 110; DOMINION_OP_11_ULEGUERAND = 111; DOMINION_OP_12_ULEGUERAND = 112; DOMINION_OP_13_ULEGUERAND = 113; DOMINION_OP_14_ULEGUERAND = 114; DOMINION_OP_01_GRAUBERG = 115; DOMINION_OP_02_GRAUBERG = 116; DOMINION_OP_03_GRAUBERG = 117; DOMINION_OP_04_GRAUBERG = 118; DOMINION_OP_05_GRAUBERG = 119; DOMINION_OP_06_GRAUBERG = 120; DOMINION_OP_07_GRAUBERG = 121; DOMINION_OP_08_GRAUBERG = 122; DOMINION_OP_09_GRAUBERG = 123; WARD_WARDEN_I_ATTOHWA = 124; WARD_WARDEN_I_MISAREAUX = 125; WARD_WARDEN_I_VUNKERL = 126; WARD_WARDEN_II_ATTOHWA = 127; WARD_WARDEN_II_MISAREAUX = 128; WARD_WARDEN_II_VUNKERL = 129; DESERT_RAIN_I_ATTOHWA = 130; DESERT_RAIN_I_MISAREAUX = 131; DESERT_RAIN_I_VUNKERL = 132; DESERT_RAIN_II_ATTOHWA = 133; DESERT_RAIN_II_MISAREAUX = 134; DESERT_RAIN_II_VUNKERL = 135; CRIMSON_CARPET_I_ATTOHWA = 136; CRIMSON_CARPET_I_MISAREAUX = 137; CRIMSON_CARPET_I_VUNKERL = 138; CRIMSON_CARPET_II_ATTOHWA = 139; CRIMSON_CARPET_II_MISAREAUX = 140; CRIMSON_CARPET_II_VUNKERL = 141; REFUEL_AND_REPLENISH_LA_THEINE = 142; REFUEL_AND_REPLENISH_KONSCHTAT = 143; REFUEL_AND_REPLENISH_TAHRONGI = 144; REFUEL_AND_REPLENISH_ATTOHWA = 145; REFUEL_AND_REPLENISH_MISAREAUX = 146; REFUEL_AND_REPLENISH_VUNKERL = 147; REFUEL_AND_REPLENISH_ALTEPA = 148; REFUEL_AND_REPLENISH_ULEGUERAND = 149; REFUEL_AND_REPLENISH_GRAUBERG = 150; A_MIGHTIER_MARTELLO_LA_THEINE = 151; A_MIGHTIER_MARTELLO_KONSCHTAT = 152; A_MIGHTIER_MARTELLO_TAHRONGI = 153; A_MIGHTIER_MARTELLO_ATTOHWA = 154; A_MIGHTIER_MARTELLO_MISAREAUX = 155; A_MIGHTIER_MARTELLO_VUNKERL = 156; A_MIGHTIER_MARTELLO_ALTEPA = 157; A_MIGHTIER_MARTELLO_ULEGUERAND = 158; A_MIGHTIER_MARTELLO_GRAUBERG = 159; A_JOURNEY_BEGINS = 160; -- + -- THE_TRUTH_BECKONS = 161; -- + -- DAWN_OF_DEATH = 162; A_GOLDSTRUCK_GIGAS = 163; TO_PASTE_A_PEISTE = 164; MEGADRILE_MENACE = 165; THE_FORBIDDEN_FRONTIER = 166; FIRST_CONTACT = 167; AN_OFFICER_AND_A_PIRATE = 168; HEART_OF_MADNESS = 169; TENUOUS_EXISTENCE = 170; CHAMPIONS_OF_ABYSSEA = 171; THE_BEAST_OF_BASTORE = 172; A_DELECTABLE_DEMON = 173; A_FLUTTERY_FIEND = 174; SCARS_OF_ABYSSEA = 175; A_BEAKED_BLUSTERER = 176; A_MAN_EATING_MITE = 177; AN_ULCEROUS_URAGNITE = 178; HEROES_OF_ABYSSEA = 179; A_SEA_DOGS_SUMMONS = 180; DEATH_AND_REBIRTH = 181; EMISSARIES_OF_GOD = 182; BENEATH_A_BLOOD_RED_SKY = 183; THE_WYRM_GOD = 184; MEANWHILE_BACK_ON_ABYSSEA = 185; A_MOONLIGHT_REQUITE = 186; DOMINION_OP_10_GRAUBERG = 187; DOMINION_OP_11_GRAUBERG = 188; DOMINION_OP_12_GRAUBERG = 189; DOMINION_OP_13_GRAUBERG = 190; DOMINION_OP_14_GRAUBERG = 191;
gpl-3.0
bocaaust/MindPiano
MindPiano/Libs/RuntimeResources.bundle/tween.lua
6
17270
-- tween.lua -- v1.0.1 (2012-02) -- Based on: -- Enrique García Cota - enrique.garcia.cota [AT] gmail [DOT] com -- tweening functions for lua -- inspired by jquery's animate function -- Modified for Codea by John Millard 2013-02 ----------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------- tween = {} -- private stuff local tweens = {} local function isCallable(f) local tf = type(f) if tf == 'function' then return true end if tf == 'table' then local mt = getmetatable(f) return (type(mt) == 'table' and type(mt.__call) == 'function') end return false end local function copyTables(destination, keysTable, valuesTable) valuesTable = valuesTable or keysTable for k,v in pairs(keysTable) do if type(v) == 'table' then destination[k] = copyTables({}, v, valuesTable[k]) else destination[k] = valuesTable[k] end end return destination end local function checkSubjectAndTargetRecursively(subject, target, path) path = path or {} local targetType, newPath for k,targetValue in pairs(target) do targetType, newPath = type(targetValue), copyTables({}, path) table.insert(newPath, tostring(k)) if targetType == 'number' then assert(type(subject[k]) == 'number', "Parameter '" .. table.concat(newPath,'/') .. "' is missing from subject or isn't a number") elseif targetType == 'userdata' then assert(type(subject[k]) == 'userdata', "Parameter '" .. table.concat(newPath,'/') .. "' is missing from subject or isn't a userdata") elseif targetType == 'table' then checkSubjectAndTargetRecursively(subject[k], targetValue, newPath) else assert(targetType == 'number', "Parameter '" .. table.concat(newPath,'/') .. "' must be a number or table of numbers") end end end local function getEasingFunction(easing) easing = easing or "linear" if type(easing) == 'table' then easing = easing['easing'] or "linear" end if type(easing) == 'string' then local name = easing easing = tween.easing[name] assert(type(easing) == 'function', "The easing function name '" .. name .. "' is invalid") end return easing end local function getloopFunction(loop) loop = loop or "once" if type(loop) == 'table' then loop = loop['loop'] or "once" if type(loop) == 'string' then local name = loop loop = tween.loop[name] assert(type(loop) == 'function', "The loop function name '" .. name .. "' is invalid") end else loop = tween.loop.once end return loop end local function checkStartParams(time, subject, target, options, callback) local easing = getEasingFunction(options) local loop = getloopFunction(options) assert(type(time) == 'number' and time > 0, "time must be a positive number. Was " .. tostring(time)) local tsubject = type(subject) assert(tsubject == 'table' or tsubject == 'userdata', "subject must be a table or userdata. Was " .. tostring(subject)) assert(type(target)== 'table', "target must be a table. Was " .. tostring(target)) assert(isCallable(easing), "easing must be a function or functable. Was " .. tostring(easing)) assert(isCallable(loop), "loop must be a function or functable. Was " .. tostring(loop)) assert(callback==nil or isCallable(callback), "callback must be nil, a function or functable. Was " .. tostring(time)) checkSubjectAndTargetRecursively(subject, target) end local function newTween(time, subject, target, options, callback, args) local self = { time = time, subject = subject, target = target, easing = getEasingFunction(options), loop = getloopFunction(options), callback = callback, args = args, initial = copyTables({}, target, subject), running = 0 } tweens[self] = self return self end local function easeWithTween(self, subject, target, initial) local t,b,c,d for k,v in pairs(target) do if type(v)=='table' then easeWithTween(self, subject[k], v, initial[k]) else t,b,c,d = self.running, initial[k], v - initial[k], self.time if self.loop then t = self.loop(t,d) end subject[k] = self.easing(t,b,c,d) end end end local function updateTween(self, dt) self.running = self.running + dt easeWithTween(self, self.subject, self.target, self.initial) end local function hasExpiredTween(self) if self.loop == tween.loop.once then return self.running >= self.time else return false end end local function finishTween(self) --copyTables(self.subject, self.target) self.running = self.time easeWithTween(self, self.subject, self.target, self.initial) if self.callback then self.callback(unpack(self.args)) end tween.stop(self) if self.next then self.next.initial = copyTables(self.next.initial, self.target, self.subject) tweens[self.next] = self.next end end local function resetTween(self) self.running = 0 easeWithTween(self, self.subject, self.target, self.initial) --copyTables(self.subject, self.initial) end -- paths local function pathFactory(subject, values) local len = #values assert(len >= 1, "Path length must be one or greater") local keys = {} for k,v in pairs(values[1]) do table.insert(keys,k) end local pathFunc = function(t,k) t = (1 + (t*(len-1))) local i2 = math.floor(t) local i1 = math.max(i2 - 1, 1) local i3 = math.min(i2 + 1, len) local i4 = math.min(i3 + 2, len) t = t - i2 local p1 = values[i1][k] local p2 = values[i2][k] local p3 = values[i3][k] local p4 = values[i4][k] local t2 = t*t local t3 = t*t*t return 0.5 * ( (2*p2) + (-p1+p3)*t + (2*p1 - 5*p2 + 4*p3 - p4)*t2 + (-p1 + 3*p2 - 3*p3 + p4)*t3) end local proxy = {} local mt = { __index = function(table,k) if k == 't' then return 0 end return rawget(table,k) end, __newindex = function(table,k,v) if k == 't' then for i,key in pairs(keys) do subject[key] = pathFunc(v,key) end else rawset(table,k,v) end end } setmetatable(proxy,mt) return proxy end -- easing -- Adapted from https://github.com/EmmanuelOga/easing. See LICENSE.txt for credits. -- For all easing functions: -- t = time == how much time has to pass for the tweening to complete -- b = begin == starting property value -- c = change == ending - beginning -- d = duration == running time. How much time has passed *right now* local pow = function(x, y) return x^y end local sin, cos, pi, sqrt, abs, asin = math.sin, math.cos, math.pi, math.sqrt, math.abs, math.asin -- linear local function linear(t, b, c, d) return c * t / d + b end -- quad local function inQuad(t, b, c, d) return c * pow(t / d, 2) + b end local function outQuad(t, b, c, d) t = t / d return -c * t * (t - 2) + b end local function inOutQuad(t, b, c, d) t = t / d * 2 if t < 1 then return c / 2 * pow(t, 2) + b end return -c / 2 * ((t - 1) * (t - 3) - 1) + b end local function outInQuad(t, b, c, d) if t < d / 2 then return outQuad(t * 2, b, c / 2, d) end return inQuad((t * 2) - d, b + c / 2, c / 2, d) end -- cubic local function inCubic (t, b, c, d) return c * pow(t / d, 3) + b end local function outCubic(t, b, c, d) return c * (pow(t / d - 1, 3) + 1) + b end local function inOutCubic(t, b, c, d) t = t / d * 2 if t < 1 then return c / 2 * t * t * t + b end t = t - 2 return c / 2 * (t * t * t + 2) + b end local function outInCubic(t, b, c, d) if t < d / 2 then return outCubic(t * 2, b, c / 2, d) end return inCubic((t * 2) - d, b + c / 2, c / 2, d) end -- quart local function inQuart(t, b, c, d) return c * pow(t / d, 4) + b end local function outQuart(t, b, c, d) return -c * (pow(t / d - 1, 4) - 1) + b end local function inOutQuart(t, b, c, d) t = t / d * 2 if t < 1 then return c / 2 * pow(t, 4) + b end return -c / 2 * (pow(t - 2, 4) - 2) + b end local function outInQuart(t, b, c, d) if t < d / 2 then return outQuart(t * 2, b, c / 2, d) end return inQuart((t * 2) - d, b + c / 2, c / 2, d) end -- quint local function inQuint(t, b, c, d) return c * pow(t / d, 5) + b end local function outQuint(t, b, c, d) return c * (pow(t / d - 1, 5) + 1) + b end local function inOutQuint(t, b, c, d) t = t / d * 2 if t < 1 then return c / 2 * pow(t, 5) + b end return c / 2 * (pow(t - 2, 5) + 2) + b end local function outInQuint(t, b, c, d) if t < d / 2 then return outQuint(t * 2, b, c / 2, d) end return inQuint((t * 2) - d, b + c / 2, c / 2, d) end -- sine local function inSine(t, b, c, d) return -c * cos(t / d * (pi / 2)) + c + b end local function outSine(t, b, c, d) return c * sin(t / d * (pi / 2)) + b end local function inOutSine(t, b, c, d) return -c / 2 * (cos(pi * t / d) - 1) + b end local function outInSine(t, b, c, d) if t < d / 2 then return outSine(t * 2, b, c / 2, d) end return inSine((t * 2) -d, b + c / 2, c / 2, d) end -- expo local function inExpo(t, b, c, d) if t == 0 then return b end return c * pow(2, 10 * (t / d - 1)) + b - c * 0.001 end local function outExpo(t, b, c, d) if t == d then return b + c end return c * 1.001 * (-pow(2, -10 * t / d) + 1) + b end local function inOutExpo(t, b, c, d) if t == 0 then return b end if t == d then return b + c end t = t / d * 2 if t < 1 then return c / 2 * pow(2, 10 * (t - 1)) + b - c * 0.0005 end return c / 2 * 1.0005 * (-pow(2, -10 * (t - 1)) + 2) + b end local function outInExpo(t, b, c, d) if t < d / 2 then return outExpo(t * 2, b, c / 2, d) end return inExpo((t * 2) - d, b + c / 2, c / 2, d) end -- circ local function inCirc(t, b, c, d) return(-c * (sqrt(1 - pow(t / d, 2)) - 1) + b) end local function outCirc(t, b, c, d) return(c * sqrt(1 - pow(t / d - 1, 2)) + b) end local function inOutCirc(t, b, c, d) t = t / d * 2 if t < 1 then return -c / 2 * (sqrt(1 - t * t) - 1) + b end t = t - 2 return c / 2 * (sqrt(1 - t * t) + 1) + b end local function outInCirc(t, b, c, d) if t < d / 2 then return outCirc(t * 2, b, c / 2, d) end return inCirc((t * 2) - d, b + c / 2, c / 2, d) end -- elastic local function calculatePAS(p,a,c,d) p, a = p or d * 0.3, a or 0 if a < abs(c) then return p, c, p / 4 end -- p, a, s return p, a, p / (2 * pi) * asin(c/a) -- p,a,s end local function inElastic(t, b, c, d, a, p) local s if t == 0 then return b end t = t / d if t == 1 then return b + c end p,a,s = calculatePAS(p,a,c,d) t = t - 1 return -(a * pow(2, 10 * t) * sin((t * d - s) * (2 * pi) / p)) + b end local function outElastic(t, b, c, d, a, p) local s if t == 0 then return b end t = t / d if t == 1 then return b + c end p,a,s = calculatePAS(p,a,c,d) return a * pow(2, -10 * t) * sin((t * d - s) * (2 * pi) / p) + c + b end local function inOutElastic(t, b, c, d, a, p) local s if t == 0 then return b end t = t / d * 2 if t == 2 then return b + c end p,a,s = calculatePAS(p,a,c,d) t = t - 1 if t < 0 then return -0.5 * (a * pow(2, 10 * t) * sin((t * d - s) * (2 * pi) / p)) + b end return a * pow(2, -10 * t) * sin((t * d - s) * (2 * pi) / p ) * 0.5 + c + b end local function outInElastic(t, b, c, d, a, p) if t < d / 2 then return outElastic(t * 2, b, c / 2, d, a, p) end return inElastic((t * 2) - d, b + c / 2, c / 2, d, a, p) end -- back local function inBack(t, b, c, d, s) s = s or 1.70158 t = t / d return c * t * t * ((s + 1) * t - s) + b end local function outBack(t, b, c, d, s) s = s or 1.70158 t = t / d - 1 return c * (t * t * ((s + 1) * t + s) + 1) + b end local function inOutBack(t, b, c, d, s) s = (s or 1.70158) * 1.525 t = t / d * 2 if t < 1 then return c / 2 * (t * t * ((s + 1) * t - s)) + b end t = t - 2 return c / 2 * (t * t * ((s + 1) * t + s) + 2) + b end local function outInBack(t, b, c, d, s) if t < d / 2 then return outBack(t * 2, b, c / 2, d, s) end return inBack((t * 2) - d, b + c / 2, c / 2, d, s) end -- bounce local function outBounce(t, b, c, d) t = t / d if t < 1 / 2.75 then return c * (7.5625 * t * t) + b end if t < 2 / 2.75 then t = t - (1.5 / 2.75) return c * (7.5625 * t * t + 0.75) + b elseif t < 2.5 / 2.75 then t = t - (2.25 / 2.75) return c * (7.5625 * t * t + 0.9375) + b end t = t - (2.625 / 2.75) return c * (7.5625 * t * t + 0.984375) + b end local function inBounce(t, b, c, d) return c - outBounce(d - t, 0, c, d) + b end local function inOutBounce(t, b, c, d) if t < d / 2 then return inBounce(t * 2, 0, c, d) * 0.5 + b end return outBounce(t * 2 - d, 0, c, d) * 0.5 + c * .5 + b end local function outInBounce(t, b, c, d) if t < d / 2 then return outBounce(t * 2, b, c / 2, d) end return inBounce((t * 2) - d, b + c / 2, c / 2, d) end tween.easing = { linear = linear, quadIn = inQuad, quadOut = outQuad, quadInOut = inOutQuad, quadOutIn = outInQuad, cubicIn = inCubic, cubicOut = outCubic, cubicInOut = inOutCubic, cubicOutIn = outInCubic, quartIn = inQuart, quartOut = outQuart, quartInOut = inOutQuart, quartOutIn = outInQuart, quintIn = inQuint, quintOut = outQuint, quintInOut = inOutQuint, quintOutIn = outInQuint, sineIn = inSine, sineOut = outSine, sineInOut = inOutSine, sineOutIn = outInSine, expoIn = inExpo, expoOut = outExpo, expoInOut = inOutExpo, expoOutIn = outInExpo, circIn = inCirc, circOut = outCirc, circInOut = inOutCirc, circOutIn = outInCirc, elasticIn = inElastic, elasticOut = outElastic, elasticInOut = inOutElastic, elasticOutIn = outInElastic, backIn = inBack, backOut = outBack, backInOut = inOutBack, backOutIn = outInBack, bounceIn = inBounce, bounceOut = outBounce, bounceInOut = inOutBounce, bounceOutIn = outInBounce, } -- ping pong local function round(num) if num >= 0 then return math.floor(num+.5) else return math.ceil(num-.5) end end local function triangleWave(x) return 1 - 2 * math.abs(round(0.5 * x) - 0.5*x) end local function frac(x) local a,b = math.modf(x) return b end local function sawtooth(x) return frac(0.5 * x) end local function forever(t,d) return sawtooth(t/(d/2)) * d end local function pingpong(t,d) return (1-triangleWave(t/d)) * d end local function once(t,d) return math.min(t,d) end tween.loop = { once = once, forever = forever, pingpong = pingpong } -- public functions function tween.start(time, subject, target, options, callback, ...) checkStartParams(time, subject, target, options, callback) return newTween(time, subject, target, options, callback, {...}) end function tween.sequence(...) local n = select('#', ...) local arg = {...} assert(n > 0, "a sequence must consist of at least one tween") local head = arg[1] local tail = arg[n] for i,id in pairs(arg) do local tw = tweens[id] tw.head = head tw.tail = tail if i < n then tw.next = arg[i+1] end -- remove all except the first tween if i > 1 and tw then tweens[id] = nil end end return arg[1] end function tween.path(time, subject, target, options, callback, ...) -- need to check that target is an array and contains valid keys return newTween(time, pathFactory(subject, target) , {t=1}, options, callback, {...}) end function tween.delay(duration, callback, ...) local t = {} return tween(duration, t, {}, tween.easing.linear, callback, ...) end setmetatable(tween, { __call = function(t, ...) return tween.start(...) end }) function tween.play(id) tweens[id]=id end function tween.reset(id) local tw = tweens[id] if tw then resetTween(tw) tween.stop(tw) end end function tween.resetAll(id) for _,tw in pairs(tweens) do resetTween(tw) --copyTables(tw.subject, tw.initial) end tween.stopAll() end function tween.stop(id) -- this tween object is the head of a sequence, stop all connected tweens if id.head and id.head == id then local next = id.next while next ~= nil do tweens[next]=nil next = next.next end end if id~=nil then tweens[id]=nil end end function tween.stopAll() tweens = {} end function tween.hasExpired(id) local tw = tweens[id] if tw then return hasExpiredTween(id) end return true end function tween.update(dt) assert(type(dt) == 'number' and dt > 0, "dt must be a positive number") local expired = {} for _,t in pairs(tweens) do updateTween(t, dt) if hasExpiredTween(t) then table.insert(expired, t) end end for i=1, #expired do finishTween(expired[i]) end end function tween.count() local c = 0 for _,v in pairs(tweens) do c = c + 1 end return c end
apache-2.0