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
mtroyka/Zero-K
units/empiricaldpser.lua
3
1230
unitDef = { unitname = [[empiricaldpser]], name = [[Empirical DPS thing]], description = [[Shoot at it for science.]], acceleration = 0, buildCostEnergy = 30000000, buildCostMetal = 30000000, builder = false, buildingGroundDecalType = [[zenith_aoplane.dds]], buildPic = [[zenith.png]], buildTime = 30000000, canstop = [[1]], category = [[SINK GUNSHIP]], energyUse = 0, footprintX = 2, footprintZ = 2, iconType = [[mahlazer]], idleAutoHeal = 5, idleTime = 1800, maxDamage = 15000, maxSlope = 18, maxVelocity = 0, maxWaterDepth = 0, minCloakDistance = 150, objectName = [[zenith.s3o]], script = [[nullscript.lua]], seismicSignature = 4, sightDistance = 660, turnRate = 0, useBuildingGroundDecal = true, workerTime = 0, yardMap = [[yyyy]], } return lowerkeys({ empiricaldpser = unitDef })
gpl-2.0
thedraked/darkstar
scripts/globals/items/loaf_of_homemade_bread.lua
18
1107
----------------------------------------- -- ID: 5228 -- Item: loaf_of_homemade_bread -- Food Effect: 30Min, All Races ----------------------------------------- -- Agility 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,1800,5228); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Tahrongi_Canyon/npcs/Stone_Monument.lua
14
1295
----------------------------------- -- Area: Tahrongi Canyon -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos -499.189 12.600 373.592 117 ----------------------------------- package.loaded["scripts/zones/Tahrongi_Canyon/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Tahrongi_Canyon/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x01000); 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
thedraked/darkstar
scripts/zones/Western_Adoulin/npcs/Virsaint.lua
14
1308
----------------------------------- -- Area: Western Adoulin -- NPC: Virsaint -- Type: Standard NPC and Quest NPC -- Involved with Quests: 'A Certain Substitute Patrolman' -- @zone 256 -- @pos 32 0 -5 ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ACSP = player:getQuestStatus(ADOULIN, A_CERTAIN_SUBSTITUTE_PATROLMAN); if ((ACSP == QUEST_ACCEPTED) and (player:getVar("ACSP_NPCs_Visited") == 4)) then -- Progresses Quest: 'A Certain Substitute Patrolman' player:startEvent(0x09FC); else -- Standard dialogue player:startEvent(0x021C); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x09FC) then -- Progresses Quest: 'A Certain Substitute Patrolman' player:setVar("ACSP_NPCs_Visited", 5); end end;
gpl-3.0
SnabbCo/snabbswitch
src/lib/yang/binary.lua
3
23753
-- Use of this source code is governed by the Apache 2.0 license; see -- COPYING. module(..., package.seeall) local S = require("syscall") local ffi = require("ffi") local lib = require("core.lib") local shm = require("core.shm") local file = require("lib.stream.file") local schema = require("lib.yang.schema") local util = require("lib.yang.util") local value = require("lib.yang.value") local data = require('lib.yang.data') local ctable = require('lib.ctable') local cltable = require('lib.cltable') local MAGIC = "yangconf" local VERSION = 0x0000f000 local header_t = ffi.typeof([[ struct { uint8_t magic[8]; uint32_t version; uint64_t source_mtime_sec; uint32_t source_mtime_nsec; uint32_t schema_name; uint32_t revision_date; uint64_t data_start; uint64_t data_len; uint64_t strtab_start; uint64_t strtab_len; } ]]) local uint32_t = ffi.typeof('uint32_t') -- A string table is written out as a uint32 count, followed by that -- many offsets indicating where the Nth string ends, followed by the -- string data for those strings. local function string_table_builder() local strtab = {} local strings = {} local count = 0 function strtab:intern(str) if strings[str] then return strings[str] end strings[str] = count count = count + 1 return strings[str] end function strtab:emit(stream) local by_index = {} for str, idx in pairs(strings) do by_index[idx] = str end local strtab_start = assert(stream:seek()) stream:write_scalar(uint32_t, count) local str_end = 0 for i=0,count-1 do str_end = str_end + by_index[i]:len() stream:write_scalar(uint32_t, str_end) end for i=0,count-1 do str_end = str_end + by_index[i]:len() stream:write_bytes(by_index[i], by_index[i]:len()) end return strtab_start, assert(stream:seek()) - strtab_start end return strtab end local function read_string_table(stream, strtab_len) assert(strtab_len >= 4) local count = stream:read_scalar(nil, uint32_t) assert(strtab_len >= (4 * (count + 1))) local offsets = stream:read_array(nil, uint32_t, count) assert(strtab_len == (4 * (count + 1)) + offsets[count-1]) local strings = {} local offset = 0 for i=0,count-1 do local len = offsets[i] - offset assert(len >= 0) strings[i] = stream:read_chars(len) offset = offset + len end return strings end local value_emitters = {} local function value_emitter(ctype) if value_emitters[ctype] then return value_emitters[ctype] end local type = data.typeof(ctype) local align = ffi.alignof(type) local size = ffi.sizeof(type) local buf = ffi.typeof('$[1]', type)() local function emit(val, stream) buf[0] = val stream:write_array(type, buf, 1) end value_emitters[ctype] = emit return emit end local function table_size(tab) local size = 0 for k,v in pairs(tab) do size = size + 1 end return size end local SPARSE_ARRAY_END = 0xffffffff local function data_emitter(production) local handlers = {} local translators = {} local function visit1(production) return assert(handlers[production.type])(production) end local function expand(production) if production.type ~= "struct" then return production end local expanded = {} for keyword,prod in pairs(production.members) do if translators[prod.type] ~= nil then translators[prod.type](expanded, keyword, prod) else expanded[keyword] = prod end end return {type="struct", members=expanded} end local function visitn(productions) local ret = {} local expanded_production = productions for keyword, production in pairs(productions) do expanded_production[keyword] = expand(production) end for keyword,production in pairs(expanded_production) do ret[keyword] = visit1(production) end return ret end function translators.choice(productions, keyword, production) -- Now bring the choice statements up to the same level replacing it. for case, block in pairs(production.choices) do for name, body in pairs(block) do productions[name] = body end end end function handlers.struct(production) local member_keys = {} for k,_ in pairs(production.members) do table.insert(member_keys, k) end local function order_predicate (x, y) if (type(x) == 'number' and type(y) == 'number') or (type(x) == 'string' and type(y) == 'string') then return x >= y else return type(y) == 'number' end end table.sort(member_keys, order_predicate) if production.ctype then local data_t = data.typeof(production.ctype) return function(data, stream) stream:write_stringref('cstruct') stream:write_stringref(production.ctype) stream:write_struct(data_t, data) end else local emit_member = visitn(production.members) local normalize_id = data.normalize_id return function(data, stream) stream:write_stringref('lstruct') -- We support Lua tables with string and number (<=uint32_t) keys, -- first we emit the number keyed members... local outn = {} for _,k in ipairs(member_keys) do if type(k) == 'number' then local id = tonumber(ffi.cast("uint32_t", k)) assert(id == k) if data[id] ~= nil then table.insert(outn, {id, emit_member[k], data[id]}) end end end stream:write_scalar(uint32_t, #outn) for _,elt in ipairs(outn) do local id, emit, data = unpack(elt) stream:write_scalar(uint32_t, id) emit(data, stream) end -- ...and then the string keyed members. local outs = {} for _,k in ipairs(member_keys) do if type(k) == 'string' then local id = normalize_id(k) if data[id] ~= nil then table.insert(outs, {id, emit_member[k], data[id]}) end end end stream:write_scalar(uint32_t, #outs) for _,elt in ipairs(outs) do local id, emit, data = unpack(elt) stream:write_stringref(id) emit(data, stream) end end end end function handlers.array(production) if production.ctype then local data_t = data.typeof(production.ctype) return function(data, stream) stream:write_stringref('carray') stream:write_stringref(production.ctype) stream:write_scalar(uint32_t, #data) stream:write_array(data_t, data.ptr, #data) end else local emit_tagged_value = visit1( {type='scalar', argument_type=production.element_type}) return function(data, stream) stream:write_stringref('larray') stream:write_scalar(uint32_t, #data) for i=1,#data do emit_tagged_value(data[i], stream) end end end end function handlers.table(production) if production.key_ctype and production.value_ctype then return function(data, stream) stream:write_stringref('ctable') stream:write_stringref(production.key_ctype) stream:write_stringref(production.value_ctype) data:save(stream) end elseif production.native_key then local emit_value = visit1({type='struct', members=production.values, ctype=production.value_ctype}) -- FIXME: sctable if production.value_ctype? return function(data, stream) -- A string-keyed table is the same as a tagged struct. stream:write_stringref('lstruct') local number_keyed_members = {} for k, v in pairs(data) do if type(k) == 'number' then assert(ffi.cast("uint32_t", k) == k) number_keyed_members[k] = v end end stream:write_scalar(uint32_t, table_size(number_keyed_members)) for k,v in pairs(number_keyed_members) do stream:write_scalar(uint32_t, k) emit_value(v, stream) end local string_keyed_members = {} for k, v in pairs(data) do if type(k) == 'string' then string_keyed_members[k] = v end end stream:write_scalar(uint32_t, table_size(string_keyed_members)) for k,v in pairs(string_keyed_members) do stream:write_stringref(k) emit_value(v, stream) end end elseif production.key_ctype then local emit_keys = visit1({type='table', key_ctype=production.key_ctype, value_ctype='uint32_t'}) local emit_value = visit1({type='struct', members=production.values}) return function(data, stream) stream:write_stringref('cltable') emit_keys(data.keys, stream) for i, value in pairs(data.values) do stream:write_scalar(uint32_t, i) emit_value(value, stream) end stream:write_scalar(uint32_t, SPARSE_ARRAY_END) end else local emit_key = visit1({type='struct', members=production.keys, ctype=production.key_ctype}) local emit_value = visit1({type='struct', members=production.values, ctype=production.value_ctype}) -- FIXME: lctable if production.value_ctype? return function(data, stream) stream:write_stringref('lltable') stream:write_scalar(uint32_t, table_size(data)) for k,v in pairs(data) do emit_key(k, stream) emit_value(v, stream) end end end end local native_types = lib.set('enumeration', 'identityref', 'string') function handlers.scalar(production) local primitive_type = production.argument_type.primitive_type local type = assert(value.types[primitive_type], "unsupported type: "..primitive_type) -- FIXME: needs a case for unions if native_types[primitive_type] then return function(data, stream) stream:write_stringref('stringref') stream:write_stringref(data) end elseif primitive_type == 'empty' then return function (data, stream) stream:write_stringref('flag') stream:write_scalar(uint32_t, data and 1 or 0) end elseif type.ctype then local ctype = type.ctype local emit_value = value_emitter(ctype) local serialization = 'cscalar' if ctype:match('[{%[]') then serialization = 'cstruct' end return function(data, stream) stream:write_stringref(serialization) stream:write_stringref(ctype) emit_value(data, stream) end else error("unimplemented: "..primitive_type) end end return visit1(production) end function data_compiler_from_grammar(emit_data, schema_name, schema_revision) return function(data, filename, source_mtime) source_mtime = source_mtime or {sec=0, nsec=0} local stream = file.tmpfile("rusr,wusr,rgrp,roth", lib.dirname(filename)) local strtab = string_table_builder() local header = header_t( MAGIC, VERSION, source_mtime.sec, source_mtime.nsec, strtab:intern(schema_name), strtab:intern(schema_revision or '')) -- Write with empty data_len etc, fix it later. stream:write_struct(header_t, header) header.data_start = assert(stream:seek()) function stream:write_stringref(str) return self:write_scalar(uint32_t, strtab:intern(str)) end emit_data(data, stream) header.data_len = assert(stream:seek()) - header.data_start header.strtab_start, header.strtab_len = strtab:emit(stream) assert(stream:seek('set', 0)) -- Fix up header. stream:write_struct(header_t, header) stream:rename(filename) stream:close() end end function data_compiler_from_schema(schema, is_config) local grammar = data.data_grammar_from_schema(schema, is_config) return data_compiler_from_grammar(data_emitter(grammar), schema.id, schema.last_revision) end function config_compiler_from_schema(schema) return data_compiler_from_schema(schema, true) end function state_compiler_from_schema(schema) return data_compiler_from_schema(schema, false) end function compile_config_for_schema(schema, data, filename, source_mtime) return config_compiler_from_schema(schema)(data, filename, source_mtime) end function compile_config_for_schema_by_name(schema_name, data, filename, source_mtime) return compile_config_for_schema(schema.load_schema_by_name(schema_name), data, filename, source_mtime) end -- Hackily re-use the YANG serializer for Lua data consisting of tables, -- ffi data, numbers, and strings. Truly a hack; to be removed in the -- all-singing YANG future that we deserve where all data has an -- associated schema. local function ad_hoc_grammar_from_data(data) if type(data) == 'table' then local members = {} for k,v in pairs(data) do assert(type(k) == 'string' or type(k) == 'number') members[k] = ad_hoc_grammar_from_data(v) end return {type='struct', members=members} elseif type(data) == 'cdata' then -- Hackety hack. local ctype = tostring(ffi.typeof(data)):match('^ctype<(.*)>$') local primitive_types = { ['unsigned char [4]'] = 'legacy-ipv4-address', ['unsigned char (&)[4]'] = 'legacy-ipv4-address', ['unsigned char [6]'] = 'mac-address', ['unsigned char (&)[6]'] = 'mac-address', ['unsigned char [16]'] = 'ipv6-address', ['unsigned char (&)[16]'] = 'ipv6-address', ['uint8_t'] = 'uint8', ['int8_t'] = 'int8', ['uint16_t'] = 'uint16', ['int16_t'] = 'int16', ['uint32_t'] = 'uint32', ['int32_t'] = 'int32', ['uint64_t'] = 'uint64', ['int64_t'] = 'int64', ['double'] = 'decimal64' -- ['float'] = 'decimal64', } local prim = primitive_types[ctype] if not prim then error('unhandled ffi ctype: '..ctype) end return {type='scalar', argument_type={primitive_type=prim}} elseif type(data) == 'number' then return {type='scalar', argument_type={primitive_type='decimal64'}} elseif type(data) == 'string' then return {type='scalar', argument_type={primitive_type='string'}} elseif type(data) == 'boolean' then return {type='scalar', argument_type={primitive_type='boolean'}} else error('unhandled data type: '..type(data)) end end function compile_ad_hoc_lua_data_to_file(file_name, data) local grammar = ad_hoc_grammar_from_data(data) local emitter = data_emitter(grammar) -- Empty string as schema name; a hack. local compiler = data_compiler_from_grammar(emitter, '') return compiler(data, file_name) end local function read_compiled_data(stream, strtab) local function read_string() return assert(strtab[stream:read_scalar(nil, uint32_t)]) end local readers = {} local function read1() local tag = read_string() return assert(readers[tag], tag)() end function readers.lstruct() local ret = {} for i=1,stream:read_scalar(nil, uint32_t) do local k = stream:read_scalar(nil, uint32_t) ret[k] = read1() end for i=1,stream:read_scalar(nil, uint32_t) do local k = read_string() ret[k] = read1() end return ret end function readers.carray() local ctype = data.typeof(read_string()) local count = stream:read_scalar(nil, uint32_t) return util.ffi_array(stream:read_array(nil, ctype, count), ctype, count) end function readers.larray() local ret = {} for i=1,stream:read_scalar(nil, uint32_t) do table.insert(ret, read1()) end return ret end function readers.ctable() local key_ctype = read_string() local value_ctype = read_string() local key_t, value_t = data.typeof(key_ctype), data.typeof(value_ctype) return ctable.load(stream, {key_type=key_t, value_type=value_t}) end function readers.cltable() local keys = read1() local values = {} while true do local i = stream:read_scalar(nil, uint32_t) if i == SPARSE_ARRAY_END then break end values[i] = read1() end return cltable.build(keys, values) end function readers.lltable() local ret = {} for i=1,stream:read_scalar(nil, uint32_t) do local k = read1() ret[k] = read1() end return ret end function readers.stringref() return read_string() end function readers.cstruct() local ctype = data.typeof(read_string()) return stream:read_struct(nil, ctype) end function readers.cscalar() local ctype = data.typeof(read_string()) return stream:read_scalar(nil, ctype) end function readers.flag() if stream:read_scalar(nil, uint32_t) ~= 0 then return true end return nil end return read1() end function has_magic(stream) local success, header = pcall(stream.read_struct, stream, nil, header_t) if success then assert(stream:seek('cur', 0) == ffi.sizeof(header_t)) end assert(stream:seek('set', 0)) return success and ffi.string(header.magic, ffi.sizeof(header.magic)) == MAGIC end function load_compiled_data(stream) local header = stream:read_struct(nil, header_t) assert(ffi.string(header.magic, ffi.sizeof(header.magic)) == MAGIC, "expected file to begin with "..MAGIC) assert(header.version == VERSION, "incompatible version: "..header.version) assert(stream:seek('set', header.strtab_start)) local strtab = read_string_table(stream, header.strtab_len) local ret = {} ret.schema_name = strtab[header.schema_name] ret.revision_date = strtab[header.revision_date] ret.source_mtime = {sec=header.source_mtime_sec, nsec=header.source_mtime_nsec} assert(stream:seek('set', header.data_start)) ret.data = read_compiled_data(stream, strtab) assert(assert(stream:seek()) == header.data_start + header.data_len) return ret end function load_compiled_data_file(filename) return load_compiled_data(assert(file.open(filename))) end function data_copier_from_grammar(production) local compile = data_compiler_from_grammar(data_emitter(production), '') return function(data) return function() local basename = 'copy-'..lib.random_printable_string(160) local tmp = shm.root..'/'..shm.resolve(basename) compile(data, tmp) local copy = load_compiled_data_file(tmp).data S.unlink(tmp) return copy end end end function data_copier_for_schema(schema, is_config) local grammar = data.data_grammar_from_schema(schema, is_config) return data_copier_from_grammar(grammar) end function config_copier_for_schema(schema) return data_copier_for_schema(schema, true) end function state_copier_for_schema(schema) return data_copier_for_schema(schema, false) end function config_copier_for_schema_by_name(schema_name) return config_copier_for_schema(schema.load_schema_by_name(schema_name)) end function copy_config_for_schema(schema, data) return config_copier_for_schema(schema)(data)() end function copy_config_for_schema_by_name(schema_name, data) return config_copier_for_schema_by_name(schema_name)(data)() end function selftest() print('selfcheck: lib.yang.binary') do -- Test Lua table support local data = { foo = 12, [42] = { [43] = "bar", baz = 44 } } local tmp = os.tmpname() compile_ad_hoc_lua_data_to_file(tmp, data) local data2 = load_compiled_data_file(tmp).data assert(lib.equal(data, data2)) end local test_schema = schema.load_schema([[module snabb-simple-router { namespace snabb:simple-router; prefix simple-router; import ietf-inet-types {prefix inet;} import ietf-yang-types { prefix yang; } leaf is-active { type boolean; default true; } leaf-list integers { type uint32; } leaf-list addrs { type inet:ipv4-address; } typedef severity { type enumeration { enum indeterminate; enum minor { value 3; } enum warning { value 4; } } } container routes { list route { key addr; leaf addr { type inet:ipv4-address; mandatory true; } leaf port { type uint8 { range 0..11; } mandatory true; } } leaf severity { type severity; } } container next-hop { choice address { case mac { leaf mac { type yang:mac-address; } } case ipv4 { leaf ipv4 { type inet:ipv4-address; } } case ipv6 { leaf ipv6 { type inet:ipv6-address; } } } } container foo { leaf enable-qos { type empty; } } }]]) local mem = require('lib.stream.mem') local data = data.load_config_for_schema(test_schema, mem.open_input_string [[ is-active true; integers 1; integers 2; integers 0xffffffff; addrs 4.3.2.1; addrs 5.4.3.2; routes { route { addr 1.2.3.4; port 1; } route { addr 2.3.4.5; port 10; } route { addr 3.4.5.6; port 2; } severity minor; } next-hop { ipv4 5.6.7.8; } foo { enable-qos; } ]]) local ipv4 = require('lib.protocol.ipv4') for i=1,3 do assert(data.is_active == true) assert(#data.integers == 3) assert(data.integers[1] == 1) assert(data.integers[2] == 2) assert(data.integers[3] == 0xffffffff) assert(#data.addrs == 2) assert(data.addrs[1]==util.ipv4_pton('4.3.2.1')) assert(data.addrs[2]==util.ipv4_pton('5.4.3.2')) local routing_table = data.routes.route local key = ffi.new('struct { uint32_t addr; }') key.addr = util.ipv4_pton('1.2.3.4') assert(routing_table:lookup_ptr(key).value.port == 1) key.addr = util.ipv4_pton('2.3.4.5') assert(routing_table:lookup_ptr(key).value.port == 10) key.addr = util.ipv4_pton('3.4.5.6') assert(routing_table:lookup_ptr(key).value.port == 2) assert( data.next_hop.ipv4 == util.ipv4_pton('5.6.7.8'), "Choice type test failed (round: "..i..")" ) local tmp = os.tmpname() compile_config_for_schema(test_schema, data, tmp) local data2 = load_compiled_data_file(tmp) assert(data2.schema_name == 'snabb-simple-router') assert(data2.revision_date == '') data = copy_config_for_schema(test_schema, data2.data) os.remove(tmp) end print('selfcheck: ok') end
apache-2.0
latenitefilms/hammerspoon
extensions/eventtap/eventtap.lua
4
13785
--- === hs.eventtap === --- --- Tap into input events (mouse, keyboard, trackpad) for observation and possibly overriding them --- It also provides convenience wrappers for sending mouse and keyboard events. If you need to construct finely controlled mouse/keyboard events, see hs.eventtap.event --- --- This module is based primarily on code from the previous incarnation of Mjolnir by [Steven Degutis](https://github.com/sdegutis/). --- === hs.eventtap.event === --- --- Create, modify and inspect events for `hs.eventtap` --- --- This module is based primarily on code from the previous incarnation of Mjolnir by [Steven Degutis](https://github.com/sdegutis/). --- --- `hs.eventtap.event.newGesture` uses an external library by Calf Trail Software, LLC. --- --- Touch --- Copyright (C) 2010 Calf Trail Software, LLC --- --- This program is free software; you can redistribute it and/or --- modify it under the terms of the GNU General Public License --- as published by the Free Software Foundation; either version 2 --- of the License, or (at your option) any later version. --- --- This program is distributed in the hope that it will be useful, --- but WITHOUT ANY WARRANTY; without even the implied warranty of --- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --- GNU General Public License for more details. --- --- You should have received a copy of the GNU General Public License --- along with this program; if not, write to the Free Software --- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. local module = require("hs.libeventtap") module.event = require("hs.libeventtapevent") local fnutils = require("hs.fnutils") local keycodes = require("hs.keycodes") local timer = require("hs.timer") -- private variables and methods ----------------------------------------- local function getKeycode(s) local n if type(s)=='number' then n=s elseif type(s)~='string' then error('key must be a string or a number',3) elseif (s:sub(1, 1) == '#') then n=tonumber(s:sub(2)) else n=keycodes.map[string.lower(s)] end if not n then error('Invalid key: '..s..' - this may mean that the key requested does not exist in your keymap (particularly if you switch keyboard layouts frequently)',3) end return n end local function getMods(mods) local r={} if not mods then return r end if type(mods)=='table' then mods=table.concat(mods,'-') end if type(mods)~='string' then error('mods must be a string or a table of strings',3) end -- super simple substring search for mod names in a string mods=string.lower(mods) local function find(ps) for _,s in ipairs(ps) do if string.find(mods,s,1,true) then r[#r+1]=ps[#ps] return end end end find{'cmd','command','⌘'} find{'ctrl','control','⌃'} find{'alt','option','⌥'} find{'shift','⇧'} find{'fn'} return r end module.event.types = ls.makeConstantsTable(module.event.types) module.event.properties = ls.makeConstantsTable(module.event.properties) module.event.rawFlagMasks = ls.makeConstantsTable(module.event.rawFlagMasks) -- Public interface ------------------------------------------------------ local originalNewKeyEvent = module.event.newKeyEvent module.event.newKeyEvent = function(mods, key, isDown) if type(mods) == "nil" then mods = {} end if (type(mods) == "number" or type(mods) == "string") and type(key) == "boolean" then mods, key, isDown = nil, mods, key end local keycode = getKeycode(key) local modifiers = mods and getMods(mods) or nil -- print(finspect(table.pack(modifiers, keycode, isDown))) return originalNewKeyEvent(modifiers, keycode, isDown) end --- hs.eventtap.event.newKeyEventSequence(modifiers, character) -> table --- Function --- Generates a table containing the keydown and keyup events to generate the keystroke with the specified modifiers. --- --- Parameters: --- * modifiers - A table containing the keyboard modifiers to apply ("cmd", "alt", "shift", "ctrl", "rightCmd", "rightAlt", "rightShift", "rightCtrl", or "fn") --- * character - A string containing a character to be emitted --- --- Returns: --- * a table with events which contains the individual events that Apple recommends for building up a keystroke combination (see [hs.eventtap.event.newKeyEvent](#newKeyEvents)) in the order that they should be posted (i.e. the first half will contain keyDown events and the second half will contain keyUp events) --- --- Notes: --- * The `modifiers` table must contain the full name of the modifiers you wish used for the keystroke as defined in `hs.keycodes.map` -- the Unicode equivalents are not supported by this function. --- * The returned table will always contain an even number of events -- the first half will be the keyDown events and the second half will be the keyUp events. --- * The events have not been posted; the table can be used without change as the return value for a callback to a watcher defined with [hs.eventtap.new](#new). function module.event.newKeyEventSequence(modifiers, character) local codes = fnutils.map({table.unpack(modifiers), character}, getKeycode) local n = #codes local events = {} for i, code in ipairs(codes) do events[i] = module.event.newKeyEvent(code, true) events[2*n+1-i] = module.event.newKeyEvent(code, false) end return events end --- hs.eventtap.event.newMouseEvent(eventtype, point[, modifiers) -> event --- Constructor --- Creates a new mouse event --- --- Parameters: --- * eventtype - One of the mouse related values from `hs.eventtap.event.types` --- * point - An hs.geometry point table (i.e. of the form `{x=123, y=456}`) indicating the location where the mouse event should occur --- * modifiers - An optional table (e.g. {"cmd", "alt"}) containing zero or more of the following keys: --- * cmd --- * alt --- * shift --- * ctrl --- * fn --- --- Returns: --- * An `hs.eventtap` object function module.event.newMouseEvent(eventtype, point, modifiers) local types = module.event.types local button if eventtype == types["leftMouseDown"] or eventtype == types["leftMouseUp"] or eventtype == types["leftMouseDragged"] then button = "left" elseif eventtype == types["rightMouseDown"] or eventtype == types["rightMouseUp"] or eventtype == types["rightMouseDragged"] then button = "right" elseif eventtype == types["otherMouseDown"] or eventtype == types["otherMouseUp"] or eventtype == types["otherMouseDragged"] then button = "other" elseif eventtype == types["mouseMoved"] then button = "none" else print("Error: unrecognised mouse button eventtype: " .. tostring(eventtype)) return nil end return module.event._newMouseEvent(eventtype, point, button, modifiers) end --- hs.eventtap.leftClick(point[, delay]) --- Function --- Generates a left mouse click event at the specified point --- --- Parameters: --- * point - A table with keys `{x, y}` indicating the location where the mouse event should occur --- * delay - An optional delay (in microseconds) between mouse down and up event. Defaults to 200000 (i.e. 200ms) --- --- Returns: --- * None --- --- Notes: --- * This is a wrapper around `hs.eventtap.event.newMouseEvent` that sends `leftmousedown` and `leftmouseup` events) function module.leftClick(point, delay) if delay==nil then delay=200000 end module.event.newMouseEvent(module.event.types["leftMouseDown"], point):post() timer.usleep(delay) module.event.newMouseEvent(module.event.types["leftMouseUp"], point):post() end --- hs.eventtap.rightClick(point[, delay]) --- Function --- Generates a right mouse click event at the specified point --- --- Parameters: --- * point - A table with keys `{x, y}` indicating the location where the mouse event should occur --- * delay - An optional delay (in microseconds) between mouse down and up event. Defaults to 200000 (i.e. 200ms) --- --- Returns: --- * None --- --- Notes: --- * This is a wrapper around `hs.eventtap.event.newMouseEvent` that sends `rightmousedown` and `rightmouseup` events) function module.rightClick(point, delay) if delay==nil then delay=200000 end module.event.newMouseEvent(module.event.types["rightMouseDown"], point):post() timer.usleep(delay) module.event.newMouseEvent(module.event.types["rightMouseUp"], point):post() end --- hs.eventtap.otherClick(point[, delay][, button]) --- Function --- Generates an "other" mouse click event at the specified point --- --- Parameters: --- * point - A table with keys `{x, y}` indicating the location where the mouse event should occur --- * delay - An optional delay (in microseconds) between mouse down and up event. Defaults to 200000 (i.e. 200ms) --- * button - An optional integer, default 2, between 2 and 31 specifying the button number to be pressed. If this parameter is specified then `delay` must also be specified, though you may specify it as `nil` to use the default. --- --- Returns: --- * None --- --- Notes: --- * This is a wrapper around `hs.eventtap.event.newMouseEvent` that sends `otherMouseDown` and `otherMouseUp` events) --- * macOS recognizes up to 32 distinct mouse buttons, though few mouse devices have more than 3. The left mouse button corresponds to button number 0 and the right mouse button corresponds to 1; distinct events are used for these mouse buttons, so you should use `hs.eventtap.leftClick` and `hs.eventtap.rightClick` respectively. All other mouse buttons are coalesced into the `otherMouse` events and are distinguished by specifying the specific button with the `mouseEventButtonNumber` property, which this function does for you. --- * The specific purpose of mouse buttons greater than 2 varies by hardware and application (typically they are not present on a mouse and have no effect in an application) function module.otherClick(point, delay, button) if delay==nil then delay=200000 end if button==nil then button = 2 end if button < 2 or button > 31 then error("button number must be between 2 and 31 inclusive", 2) end module.event.newMouseEvent(module.event.types["otherMouseDown"], point):setProperty(module.event.properties["mouseEventButtonNumber"], button):post() hs.timer.usleep(delay) module.event.newMouseEvent(module.event.types["otherMouseUp"], point):setProperty(module.event.properties["mouseEventButtonNumber"], button):post() end --- hs.eventtap.middleClick(point[, delay]) --- Function --- Generates a middle mouse click event at the specified point --- --- Parameters: --- * point - A table with keys `{x, y}` indicating the location where the mouse event should occur --- * delay - An optional delay (in microseconds) between mouse down and up event. Defaults to 200000 (i.e. 200ms) --- --- Returns: --- * None --- --- Notes: --- * This function is just a wrapper which calls `hs.eventtap.otherClick(point, delay, 2)` and is included solely for backwards compatibility. module.middleClick = function(point, delay) module.otherClick(point, delay, 2) end --- hs.eventtap.keyStroke(modifiers, character[, delay, application]) --- Function --- Generates and emits a single keystroke event pair for the supplied keyboard modifiers and character --- --- Parameters: --- * modifiers - A table containing the keyboard modifiers to apply ("fn", "ctrl", "alt", "cmd", "shift", or their Unicode equivalents) --- * character - A string containing a character to be emitted --- * delay - An optional delay (in microseconds) between key down and up event. Defaults to 200000 (i.e. 200ms) --- * application - An optional hs.application object to send the keystroke to --- --- Returns: --- * None --- --- Notes: --- * This function is ideal for sending single keystrokes with a modifier applied (e.g. sending ⌘-v to paste, with `hs.eventtap.keyStroke({"cmd"}, "v")`). If you want to emit multiple keystrokes for typing strings of text, see `hs.eventtap.keyStrokes()` --- * Note that invoking this function with a table (empty or otherwise) for the `modifiers` argument will force the release of any modifier keys which have been explicitly created by [hs.eventtap.event.newKeyEvent](#newKeyEvent) and posted that are still in the "down" state. An explicit `nil` for this argument will not (i.e. the keystroke will inherit any currently "down" modifiers) function module.keyStroke(modifiers, character, delay, application) local targetApp = nil local keyDelay = 200000 if type(delay) == "userdata" then targetApp = delay else targetApp = application end if type(delay) == "number" then keyDelay = delay end --print("targetApp: "..tostring(targetApp)) --print("keyDelay: "..tostring(keyDelay)) module.event.newKeyEvent(modifiers, character, true):post(targetApp) timer.usleep(keyDelay) module.event.newKeyEvent(modifiers, character, false):post(targetApp) end --- hs.eventtap.scrollWheel(offsets, modifiers, unit) -> event --- Function --- Generates and emits a scroll wheel event --- --- Parameters: --- * offsets - A table containing the {horizontal, vertical} amount to scroll. Positive values scroll up or left, negative values scroll down or right. --- * mods - A table containing zero or more of the following: --- * cmd --- * alt --- * shift --- * ctrl --- * fn --- * unit - An optional string containing the name of the unit for scrolling. Either "line" (the default) or "pixel" --- --- Returns: --- * None function module.scrollWheel(offsets, modifiers, unit) module.event.newScrollEvent(offsets, modifiers, unit):post() end -- Return Module Object -------------------------------------------------- return module
mit
thedraked/darkstar
scripts/zones/Beadeaux/npcs/The_Mute.lua
14
1296
----------------------------------- -- Area: Beadeaux -- NPC: ??? -- @pos -166.230 -1 -73.685 147 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Beadeaux/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local duration = math.random(600,900); if (player:getQuestStatus(BASTOK,THE_CURSE_COLLECTOR) == QUEST_ACCEPTED and player:getVar("cCollectSilence") == 0) then player:setVar("cCollectSilence",1); end player:addStatusEffect(EFFECT_SILENCE,0,0,duration); 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
thedraked/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Sajaaya.lua
59
1060
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Sajaaya -- Type: Weather Reporter ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01F6,0,0,0,0,0,0,0,VanadielTime()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
NPLPackages/main
script/ide/System/Database/Collection.lua
1
11512
--[[ Title: Collection Author(s): LiXizhi, Date: 2016/5/11 Desc: Collection is like a sql table in standard database. A database contains many collections. use the lib: ------------------------------------------------------------ NPL.load("(gl)script/ide/System/Database/Collection.lua"); local Collection = commonlib.gettable("System.Database.Collection"); ------------------------------------------------------------ ]] NPL.load("(gl)script/ide/System/Database/Item.lua"); NPL.load("(gl)script/ide/System/Database/StorageProvider.lua"); NPL.load("(gl)script/ide/System/Database/IORequest.lua"); NPL.load("(gl)script/ide/System/Database/Store.lua"); local Store = commonlib.gettable("System.Database.Store"); local IORequest = commonlib.gettable("System.Database.IORequest"); local StorageProvider = commonlib.gettable("System.Database.StorageProvider"); local Item = commonlib.gettable("System.Database.Item"); local type = type; local Collection = commonlib.gettable("System.Database.Collection"); Collection.__index = Collection; function Collection:new_collection(o) o = o or {}; setmetatable(o, self); return o; end -- create a new object function Collection:new(data) return Item:new():init(self, data); end -- @param parent: the parent table database function Collection:init(name, parent) self.name = name or "default"; self.parent = parent; self.isServer = parent:IsServer(); self.writerThread = parent.writerThread; if(self:IsServer()) then self.storageProvider = StorageProvider:CreateStorage(self); end return self; end function Collection:ToData() if(not self.data) then self.data = {name=self.name, db=self.parent:GetRootFolder()}; end return self.data; end function Collection:GetParent() return self.parent; end function Collection:GetName() return self.name; end function Collection:GetProviderName() return self.parent:FindProvider(self.name); end -- return a valid and opened provider function Collection:GetProvider() self.storageProvider:CheckOpen(); return self.storageProvider; end -- whether this is a server thread function Collection:IsServer() return self.isServer; end function Collection:GetWriterThreadName() return self.writerThread or "main"; end -- find by internal id. function Collection:findById(id, callbackFunc, timeout) return self:findOne({_id = id}, callbackFunc, timeout); end -- Similar to `find` except that it just return one row. -- Find will automatically create index on query fields. -- To force not-using index on query field, please use array table. e.g. -- query = {name="a", {"email", "a@abc.com"}}, field `name` is indexed, whereas "email" is NOT. -- @param query: key, value pair table, such as {name="abc"}. if nil or {}, it will return all the rows -- it may also contain array items which means non-indexed query fields, which is used to filter the result after -- fetching other queried fields. --@param callbackFunc: function(err, row) end, where row._id is the internal row id. function Collection:findOne(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():findOne(query, callbackFunc); else return IORequest:Send("findOne", self, query, callbackFunc, timeout); end end -- Find will automatically create index on query fields. -- To force not-using index on query fields, please use array table. e.g. -- query = {name="a", {"email", "a@abc.com"}}, field `name` is indexed, whereas "email" is NOT. -- @param query: key, value pair table, such as {name="abc"}. if nil or {}, it will return all the rows -- it may also contain array items which means non-indexed query fields, which is used to filter the result after -- fetching other queried fields. -- @param callbackFunc: function(err, rows) end, where rows is array of rows found function Collection:find(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():find(query, callbackFunc); else return IORequest:Send("find", self, query, callbackFunc, timeout); end end -- @param query: key, value pair table, such as {name="abc"}. function Collection:deleteOne(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():deleteOne(query, callbackFunc); else return IORequest:Send("deleteOne", self, query, callbackFunc, timeout); end end -- this function will assume query contains at least one valid index key. -- it will not auto create index if key does not exist. -- @param query: key, value pair table, such as {name="abc", _unset={"fieldname_to_remove", "another_name"}}. -- _unset may contain array or map of field names to remove. -- @param update: additional fields to be merged with existing data; this can also be callbackFunc function Collection:updateOne(query, update, callbackFunc, timeout) if(type(update) == "function") then callbackFunc = update; update = nil; end if(self:IsServer()) then return self:GetProvider():updateOne(query, update, callbackFunc); else return IORequest:Send("updateOne", self, {query = query, update = update}, callbackFunc, timeout); end end function Collection:update(query, update, callbackFunc, timeout) if(type(update) == "function") then callbackFunc = update; update = nil; end if(self:IsServer()) then return self:GetProvider():update(query, update, callbackFunc); else return IORequest:Send("update", self, {query = query, update = update}, callbackFunc, timeout); end end -- Replaces a single document within the collection based on the query filter. -- it will not auto create index if key does not exist. -- @param query: key, value pair table, such as {name="abc"}. -- @param replacement: wholistic fields to be replace any existing doc. function Collection:replaceOne(query, replacement, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():replaceOne(query, replacement, callbackFunc); else return IORequest:Send("replaceOne", self, {query = query, replacement = replacement}, callbackFunc, timeout); end end -- if there is already one ore more records with query, this function falls back to updateOne(). -- otherwise it will insert and return full data with internal row _id. -- @param query: nil or query fields. if nil, it will insert a new record regardless of key uniqueness check. -- if it contains query fields, it will first do a findOne() first, and turns into updateOne if a row is found. -- please note, index-fields are created for queried fields just like in `find` command. -- @param update: the actuall fields function Collection:insertOne(query, update, callbackFunc, timeout) if(type(update) == "function") then callbackFunc = update; update = query; query = nil; end if(self:IsServer()) then return self:GetProvider():insertOne(query, update, callbackFunc); else return IORequest:Send("insertOne", self, {query = query, update = update}, callbackFunc, timeout); end end -- remove one or more or all index -- @param query: array of keys {keyname, ...} function Collection:removeIndex(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():removeIndex(query, callbackFunc); else return IORequest:Send("removeIndex", self, query, callbackFunc, timeout); end end -- normally one does not need to call this function. -- the store should flush at fixed interval. -- @param callbackFunc: function(err, fFlushed) end function Collection:flush(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():flush(query, callbackFunc); else return IORequest:Send("flush", self, query, callbackFunc, timeout); end end -- after issuing an really important group of commands, and you want to ensure that -- these commands are actually successful like a transaction, the client can issue a waitflush -- command to check if the previous commands are successful. Please note that waitflush command -- may take up to 3 seconds or Store.AutoFlushInterval to return. -- @param callbackFunc: function(err, fFlushed) end function Collection:waitflush(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():waitflush(query, callbackFunc); else timeout = timeout or (Store.AutoFlushInterval + 3000); return IORequest:Send("waitflush", self, query, callbackFunc, timeout); end end -- danger: call this function will remove everything, including indices -- @param callbackFunc: function(err, rowDeletedCount) end function Collection:makeEmpty(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():makeEmpty(query, callbackFunc); else return IORequest:Send("makeEmpty", self, query, callbackFunc, timeout); end end -- this is usually used for changing database settings, such as cache size and sync mode. -- this function is specific to store implementation. -- @param query: string or {sql=string, CacheSize=number, IgnoreOSCrash=bool, IgnoreAppCrash=bool, QueueSize=number, SyncMode=boolean} -- query.QueueSize: set the message queue size for both the calling thread and db processor thread. -- query.SyncMode: default to false. if true, table api is will pause until data arrives. -- @param callbackFunc: function(err, data) end function Collection:exec(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():exec(query, callbackFunc); else if(type(query) == "table") then -- also make the caller's message queue size twice as big at least if(query.QueueSize) then local value = query.QueueSize*2; if(__rts__:GetMsgQueueSize() < value) then __rts__:SetMsgQueueSize(value); LOG.std(nil, "system", "NPL", "NPL input queue size of thread (%s) is changed to %d", __rts__:GetName(), value); end end if(query.SyncMode~=nil) then IORequest.EnableSyncMode = query.SyncMode; LOG.std(nil, "system", "TableDatabase", "sync mode api is %s in thread %s", query.SyncMode and "enabled" or "disabled", __rts__:GetName()); end end return IORequest:Send("exec", self, query, callbackFunc, timeout); end end -- calling this function will always timeout, since the server will not reply function Collection:silient(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():silient(query, callbackFunc); else return IORequest:Send("silient", self, query, callbackFunc, timeout); end end -- calling this function will always timeout, since the server will not reply function Collection:count(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():count(query, callbackFunc); else return IORequest:Send("count", self, query, callbackFunc, timeout); end end -- calling this function will always timeout, since the server will not reply function Collection:delete(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():delete(query, callbackFunc); else return IORequest:Send("delete", self, query, callbackFunc, timeout); end end function Collection:injectWALPage(query, callbackFunc, timeout) if(self:IsServer()) then return self:GetProvider():injectWALPage(query, callbackFunc); else return IORequest:Send("injectWALPage", self, query, callbackFunc, timeout); end end -- 2PC for close function Collection:close(callbackFunc, timeout) if(self:IsServer()) then return self.storageProvider:Close(); else local close_commit = function (...) IORequest:Send("close_commit", self, nil, callbackFunc, timeout); end return IORequest:Send("close_prepare", self, nil, close_commit, timeout); end end
gpl-2.0
thedraked/darkstar
scripts/zones/Sacrificial_Chamber/npcs/_4j4.lua
14
1440
----------------------------------- -- Area: Sacrificial Chamber -- NPC: Mahogany Door -- @pos 300 30 -324 163 ------------------------------------- package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/missions"); require("scripts/zones/Sacrificial_Chamber/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
X-Coder/wire
lua/entities/gmod_wire_dataport.lua
10
1402
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Data Port" ENT.WireDebugName = "DataPort" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetUseType(SIMPLE_USE) self.Outputs = Wire_CreateOutputs(self, { "Port0","Port1","Port2","Port3","Port4","Port5","Port6","Port7" }) self.Inputs = Wire_CreateInputs(self, { "Port0","Port1","Port2","Port3","Port4","Port5","Port6","Port7" }) self.Ports = {} for i = 0,7 do self.Ports[i] = 0 end self.OutPorts = {} self:NextThink(CurTime()) end function ENT:Think() self.BaseClass.Think(self) for i = 0,7 do if self.OutPorts[i] then Wire_TriggerOutput(self, "Port"..i, self.OutPorts[i]) self.OutPorts[i] = nil end end self:NextThink(CurTime()) return true -- for NextThink end function ENT:ReadCell(Address) if (Address >= 0) && (Address <= 7) then return self.Ports[Address] else return nil end end function ENT:WriteCell(Address, value) if (Address >= 0) && (Address <= 7) then self.OutPorts[Address] = value return true else return false end end function ENT:TriggerInput(iname, value) for i = 0,7 do if iname == ("Port"..i) then self.Ports[i] = value end end end duplicator.RegisterEntityClass("gmod_wire_dataport", WireLib.MakeWireEnt, "Data")
gpl-3.0
mtroyka/Zero-K
LuaRules/Configs/StartBoxes/Lonely Oasis v1.lua
19
5097
local boxes = { [0] = { boxes = { { {5486, 2151}, {5537, 2426}, {5583, 2551}, {5648, 2630}, {5748, 2676}, {5924, 2680}, {6078, 2669}, {6165, 2687}, {6272, 2746}, {6420, 2777}, {6541, 2769}, {6668, 2694}, {6734, 2594}, {6765, 2447}, {6757, 2289}, {6719, 2132}, {6731, 2092}, {6821, 1998}, {6854, 1915}, {6853, 1594}, {6820, 1505}, {6765, 1433}, {6647, 1373}, {6593, 1312}, {6572, 1201}, {6584, 946}, {6561, 852}, {6460, 704}, {6354, 622}, {6295, 583}, {6273, 533}, {6161, 465}, {5986, 459}, {5902, 448}, {5758, 396}, {5621, 361}, {5480, 352}, {5379, 348}, {5288, 376}, {5199, 429}, {5128, 509}, {5086, 611}, {5009, 703}, {4958, 766}, {4940, 843}, {4944, 951}, {4986, 1041}, {5066, 1155}, {5175, 1256}, {5275, 1378}, {5400, 1738}, }, { {4916, 1171}, {4757, 1138}, {4599, 1118}, {4446, 1131}, {4320, 1173}, {4227, 1244}, {4162, 1327}, {4073, 1370}, {3973, 1363}, {3899, 1313}, {3861, 1239}, {3857, 1121}, {3898, 1044}, {3969, 954}, {4096, 835}, {4124, 758}, {4121, 670}, {4089, 590}, {4013, 523}, {3924, 501}, {3837, 519}, {3675, 582}, {3531, 609}, {3393, 599}, {3268, 536}, {3061, 444}, {2812, 371}, {2654, 377}, {2262, 451}, {2117, 507}, {1998, 612}, {1888, 775}, {1862, 890}, {1870, 1021}, {1909, 1143}, {1981, 1221}, {2063, 1291}, {2166, 1432}, {2240, 1548}, {2319, 1664}, {2399, 1738}, {2498, 1761}, {2620, 1732}, {2693, 1650}, {2747, 1498}, {2799, 1408}, {2907, 1358}, {3064, 1367}, {3270, 1441}, {3613, 1617}, {3757, 1715}, {3814, 1784}, {3902, 1986}, {3980, 2125}, {4001, 2227}, {4036, 2359}, {4100, 2468}, {4289, 2619}, {4571, 2842}, {4634, 2924}, {4711, 2980}, {4814, 2999}, {4982, 2923}, {5121, 2857}, {5319, 2804}, {5441, 2754}, {5509, 2714}, {5543, 2700}, {5458, 2561}, {5422, 2427}, {5396, 2290}, {5345, 2201}, {5237, 2037}, {5116, 1784}, {5076, 1585}, {5082, 1436}, {5006, 1267}, }, }, startpoints = { {5919, 1528}, {4583, 1335}, {2535, 606}, }, nameLong = "North-East", nameShort = "NE", }, [1] = { boxes = { { {1664, 4973}, {1614, 4812}, {1563, 4717}, {1485, 4648}, {1413, 4617}, {1352, 4614}, {1268, 4640}, {1197, 4635}, {1141, 4579}, {1048, 4530}, {936, 4498}, {833, 4501}, {747, 4514}, {643, 4552}, {570, 4604}, {510, 4672}, {481, 4728}, {477, 4793}, {478, 4940}, {462, 5052}, {415, 5144}, {367, 5219}, {335, 5347}, {329, 5463}, {364, 5591}, {462, 5723}, {631, 5904}, {664, 5976}, {665, 6074}, {690, 6167}, {775, 6250}, {858, 6309}, {911, 6400}, {975, 6511}, {1066, 6574}, {1174, 6606}, {1259, 6643}, {1388, 6759}, {1461, 6793}, {1623, 6812}, {1758, 6813}, {1935, 6769}, {2051, 6709}, {2132, 6607}, {2153, 6467}, {2149, 6209}, {2118, 6071}, {2044, 5915}, {1945, 5756}, {1768, 5407}, }, { {1771, 4943}, {1669, 4692}, {1675, 4620}, {1772, 4456}, {1875, 4314}, {1973, 4241}, {2101, 4208}, {2224, 4205}, {2337, 4191}, {2387, 4164}, {2476, 4152}, {2547, 4172}, {2623, 4226}, {2694, 4343}, {2783, 4454}, {2903, 4551}, {3031, 4697}, {3137, 4882}, {3236, 5076}, {3310, 5293}, {3396, 5419}, {3532, 5530}, {3766, 5639}, {3953, 5715}, {4193, 5763}, {4303, 5749}, {4412, 5672}, {4452, 5583}, {4469, 5505}, {4499, 5448}, {4570, 5389}, {4665, 5364}, {4800, 5401}, {4908, 5466}, {4995, 5571}, {5075, 5694}, {5189, 5856}, {5261, 6119}, {5253, 6242}, {5190, 6410}, {5070, 6538}, {4896, 6636}, {4663, 6697}, {4542, 6771}, {4370, 6803}, {4180, 6779}, {3941, 6692}, {3767, 6595}, {3660, 6496}, {3585, 6477}, {3518, 6499}, {3435, 6539}, {3326, 6538}, {3229, 6498}, {3161, 6410}, {3152, 6279}, {3178, 6189}, {3254, 6107}, {3267, 5996}, {3253, 5885}, {3182, 5830}, {3096, 5841}, {3031, 5919}, {2885, 6057}, {2702, 6119}, {2441, 6068}, {2238, 5966}, {2174, 5912}, {2104, 5800}, {2115, 5683}, {2032, 5239}, {1891, 5058}, }, }, startpoints = { {1212, 5656}, {2606, 5888}, {4527, 6500}, }, nameLong = "South-West", nameShort = "SW", }, } -- use a smaller box for duel if #Spring.GetTeamList(0) == 1 and #Spring.GetTeamList(1) == 1 then boxes[0].boxes[2] = nil boxes[1].boxes[2] = nil boxes[0].startpoints[2] = nil boxes[0].startpoints[3] = nil boxes[1].startpoints[2] = nil boxes[1].startpoints[3] = nil end return boxes, { 2 }
gpl-2.0
Ali-2h/losebot
plugins/banhammer.lua
294
10470
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id 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 get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end else return 'This isn\'t a chat group' end end if matches[1] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled", "!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete user <user_id> : Remove user from whitelist", "!whitelist delete chat : Remove chat from whitelist", "!ban user <user_id> : Kick user from chat and kicks it if joins chat again", "!ban user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick) (.*)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
mtroyka/Zero-K
scripts/spideranarchid.lua
16
4496
include "constants.lua" include "spider_walking.lua" -------------------------------------------------------------------------------- -- pieces -------------------------------------------------------------------------------- local body = piece 'body' local turret = piece 'turret' local gun = piece 'gun' local flare = piece 'flare' local aim = piece 'aim' local br = piece 'leg1' -- back right local mr = piece 'leg2' -- middle right local fr = piece 'leg3' -- front right local bl = piece 'leg4' -- back left local ml = piece 'leg5' -- middle left local fl = piece 'leg6' -- front left local smokePiece = {body, turret} -------------------------------------------------------------------------------- -- constants -------------------------------------------------------------------------------- -- Signal definitions local SIG_WALK = 1 local SIG_AIM = 2 local PERIOD = 0.1 local sleepTime = PERIOD*1000 local legRaiseAngle = math.rad(30) local legRaiseSpeed = legRaiseAngle/PERIOD local legLowerSpeed = legRaiseAngle/PERIOD local legForwardAngle = math.rad(20) local legForwardTheta = math.rad(25) local legForwardOffset = -math.rad(20) local legForwardSpeed = legForwardAngle/PERIOD local legMiddleAngle = math.rad(20) local legMiddleTheta = 0 local legMiddleOffset = 0 local legMiddleSpeed = legMiddleAngle/PERIOD local legBackwardAngle = math.rad(20) local legBackwardTheta = -math.rad(25) local legBackwardOffset = math.rad(20) local legBackwardSpeed = legBackwardAngle/PERIOD local restore_delay = 3000 -- four-stroke hexapedal walkscript local function Walk() Signal(SIG_WALK) SetSignalMask(SIG_WALK) while true do walk(br, mr, fr, bl, ml, fl, legRaiseAngle, legRaiseSpeed, legLowerSpeed, legForwardAngle, legForwardOffset, legForwardSpeed, legForwardTheta, legMiddleAngle, legMiddleOffset, legMiddleSpeed, legMiddleTheta, legBackwardAngle, legBackwardOffset, legBackwardSpeed, legBackwardTheta, sleepTime) end end local function RestoreLegs() Signal(SIG_WALK) SetSignalMask(SIG_WALK) restoreLegs(br, mr, fr, bl, ml, fl, legRaiseSpeed, legForwardSpeed, legMiddleSpeed,legBackwardSpeed) end function script.Create() StartThread(SmokeUnit, smokePiece) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(RestoreLegs) end local function RestoreAfterDelay() Sleep(restore_delay) Turn(turret, y_axis, 0, math.rad(90)) Turn(gun, x_axis, 0, math.rad(90)) Move(gun, y_axis, 0, 10) end function script.AimWeapon(num, heading, pitch) Signal(SIG_AIM) SetSignalMask(SIG_AIM) Turn(turret, y_axis, heading, math.rad(450)) Turn(gun, x_axis, -pitch, math.rad(180)) Move(gun, y_axis, 130, 40) WaitForTurn(turret, y_axis) WaitForTurn(gun, x_axis) StartThread(RestoreAfterDelay) return true end function script.AimFromWeapon(num) return aim end function script.QueryWeapon(num) return flare end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .25 then Explode(gun, sfxNone) Explode(body, sfxNone) Explode(br, sfxNone) Explode(mr, sfxNone) Explode(fr, sfxNone) Explode(bl, sfxNone) Explode(ml, sfxNone) Explode(fl, sfxNone) Explode(turret, sfxNone) return 1 elseif severity <= .50 then Explode(gun, sfxFall) Explode(body, sfxNone) Explode(br, sfxFall) Explode(mr, sfxFall) Explode(fr, sfxFall) Explode(bl, sfxFall) Explode(ml, sfxFall) Explode(fl, sfxFall) Explode(turret, sfxShatter) return 1 elseif severity <= .99 then Explode(gun, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(body, sfxNone) Explode(br, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(mr, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(fr, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(bl, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(ml, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(fl, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(turret, sfxShatter) return 2 else Explode(gun, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(body, sfxNone) Explode(br, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(mr, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(fr, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(bl, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(ml, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(fl, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(turret, sfxShatter + sfxExplode) return 2 end end
gpl-2.0
gowadbd/gowad
plugins/me.lua
2
2919
--[[ _____ ____ ____ ___ _____ |_ _| _ \ | __ ) / _ \_ _| | | | |_) | | _ \| | | || | | | | __/ | |_) | |_| || | |_| |_| |____/ \___/ |_| KASPER TP (BY @kasper_dev) _ __ _ ____ ____ _____ ____ _____ ____ | |/ / / \ / ___|| _ \| ____| _ \ |_ _| _ \ | ' / / _ \ \___ \| |_) | _| | |_) | | | | |_) | | . \ / ___ \ ___) | __/| |___| _ < | | | __/ |_|\_\/_/ \_\____/|_| |_____|_| \_\ |_| |_| --]] do local function run(msg, matches) if is_sudo(msg) then local text = 'مـرحـ(👋)ـبـا يـا '..msg.from.first_name..'\n'..'انـتـ» مـطـ(🕵)ـور فـي الـبـ(🤖)ـوتــ»'..'\n'..'ايـ{🆔}ـدك↜'..msg.from.id..'\n'..'مـعـ(Ⓜ️)ـرفـك↜ @'..(msg.from.username or "غير متوفر")..'\n'..'تـابـ؏↜ @dev_kasper' return reply_msg(msg.id, text, ok_cb, false) end if is_momod(msg) then local text = 'مـرحـ(👋)ـبـا يـا '..msg.from.first_name..'\n'..'انـتـ» ادمـ(🏅)ـن فـي الـبـ(🤖)ـوتــ»'..'\n'..'ايـ{🆔}ـدك↜'..msg.from.id..'\n'..'مـعـ(Ⓜ️)ـرفـك↜ @'..(msg.from.username or "غير متوفر")..'\n'..'تـابـ؏↜ @dev_kasper' return reply_msg(msg.id, text, ok_cb, false) end if not is_momod(msg) then local text = 'مـرحـ(👋)ـبـا يـا '..msg.from.first_name..'\n'..'انـتـ» عـ(🎖)ـضـو فـي الـبـ(🤖)ـوتــ»'..'\n'..'ايـ{🆔}ـدك↜'..msg.from.id..'\n'..'مـعـ(Ⓜ️)ـرفـك↜ @'..(msg.from.username or "غير متوفر")..'\n'..'تـابـ؏↜ @dev_kasper' return reply_msg(msg.id, text, ok_cb, false) end if is_owner(msg) then local text = 'مـرحـ(👋)ـبـا يـا '..msg.from.first_name..'\n'..'انـتـ» الـمـ(🏆)ـديـر فـي الـبـ(🤖)ـوتــ»'..'\n'..'ايـ{🆔}ـدك↜'..msg.from.id..'\n'..'مـعـ(Ⓜ️)ـرفـك↜ @'..(msg.from.username or "غير متوفر")..'\n'..'تـابـ؏↜ @dev_kasper' return reply_msg(msg.id, text, ok_cb, false) end end return { patterns = { "^[!/](me)$", "^(موقعي)$", }, run = run, } end --[[ _____ ____ ____ ___ _____ |_ _| _ \ | __ ) / _ \_ _| | | | |_) | | _ \| | | || | | | | __/ | |_) | |_| || | |_| |_| |____/ \___/ |_| KASPER TP (BY @kasper_dev) _ __ _ ____ ____ _____ ____ _____ ____ | |/ / / \ / ___|| _ \| ____| _ \ |_ _| _ \ | ' / / _ \ \___ \| |_) | _| | |_) | | | | |_) | | . \ / ___ \ ___) | __/| |___| _ < | | | __/ |_|\_\/_/ \_\____/|_| |_____|_| \_\ |_| |_| --]]
gpl-2.0
thedraked/darkstar
scripts/zones/Temenos/bcnms/Temenos_Western_Tower.lua
35
1096
----------------------------------- -- Area: Temenos -- Name: ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[Temenos_W_Tower]UniqueID",GenerateLimbusKey()); HideArmouryCrates(GetInstanceRegion(1298),TEMENOS); HideTemenosDoor(GetInstanceRegion(1298)); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("limbusbitmap",0); player:setVar("characterLimbusKey",GetServerVariable("[Temenos_W_Tower]UniqueID")); player:setVar("LimbusID",1298); player:delKeyItem(COSMOCLEANSE); player:delKeyItem(WHITE_CARD); end; -- Leaving by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then player:setPos(580,-1.5,4.452,192); ResetPlayerLimbusVariable(player) end end;
gpl-3.0
ukoloff/rufus-lua-win
vendor/lua/lib/lua/luarocks/make.lua
2
2654
--- Module implementing the LuaRocks "make" command. -- Builds sources in the current directory, but unlike "build", -- it does not fetch sources, etc., assuming everything is -- available in the current directory. module("luarocks.make", package.seeall) local build = require("luarocks.build") local fs = require("luarocks.fs") local util = require("luarocks.util") local cfg = require("luarocks.cfg") local fetch = require("luarocks.fetch") local pack = require("luarocks.pack") help_summary = "Compile package in current directory using a rockspec." help_arguments = "[--pack-binary-rock] [<rockspec>]" help = [[ Builds sources in the current directory, but unlike "build", it does not fetch sources, etc., assuming everything is available in the current directory. If no argument is given, look for a rockspec in the current directory. If more than one is found, you must specify which to use, through the command-line. This command is useful as a tool for debugging rockspecs. To install rocks, you'll normally want to use the "install" and "build" commands. See the help on those for details. If --pack-binary-rock is passed, the rock is not installed; instead, a .rock file with the contents of compilation is produced in the current directory. ]] --- Driver function for "make" command. -- @param name string: A local rockspec. -- @return boolean or (nil, string): True if build was successful; nil and an -- error message otherwise. function run(...) local flags, rockspec = util.parse_flags(...) assert(type(rockspec) == "string" or not rockspec) if not rockspec then local files = fs.list_dir(fs.current_dir()) for _, file in pairs(files) do if file:match("rockspec$") then if rockspec then return nil, "Please specify which rockspec file to use." else rockspec = file end end end if not rockspec then return nil, "Argument missing: please specify a rockspec to use on current directory." end end if not rockspec:match("rockspec$") then return nil, "Invalid argument: 'make' takes a rockspec as a parameter. See help." end if flags["pack-binary-rock"] then local rspec, err, errcode = fetch.load_rockspec(rockspec) if not rspec then return nil, err end return pack.pack_binary_rock(rspec.name, rspec.version, build.build_rockspec, rockspec, false, true, flags["nodeps"]) else local ok, err = fs.check_command_permissions(flags) if not ok then return nil, err end return build.build_rockspec(rockspec, false, true) end end
mit
thedraked/darkstar
scripts/globals/weaponskills/guillotine.lua
18
1964
----------------------------------- -- Guillotine -- Scythe weapon skill -- Skill level: 200 -- Delivers a four-hit attack. Duration varies with TP. -- Modifiers: STR:25% ; MND:25% -- 100%TP 200%TP 300%TP -- 0.875 0.875 0.875 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 4; -- ftp damage mods (for Damage Varies with TP; lines are calculated in the function params.ftp100 = 0.875; params.ftp200 = 0.875; params.ftp300 = 0.875; -- wscs are in % so 0.2=20% params.str_wsc = 0.25; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.25; params.chr_wsc = 0.0; -- critical mods, again in % (ONLY USE FOR critICAL HIT VARIES WITH TP) params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0; params.canCrit = false; -- accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the params.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.3; params.mnd_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0) then local duration = (tp/1000 * 30) + 30; if (target:hasStatusEffect(EFFECT_SILENCE) == false) then target:addStatusEffect(EFFECT_SILENCE, 1, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
thedraked/darkstar
scripts/zones/Cape_Teriggan/npcs/Cermet_Headstone.lua
14
4139
----------------------------------- -- Area: Cape Teriggan -- NPC: Cermet Headstone -- Involved in Mission: ZM5 Headstone Pilgrimage (Wind Headstone) -- @pos -107 -8 450 113 ----------------------------------- package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/missions"); require("scripts/zones/Cape_Teriggan/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(949,1) and trade:getItemCount() == 1) then if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE and player:hasKeyItem(WIND_FRAGMENT) and player:hasCompleteQuest(OUTLANDS,WANDERING_SOULS) == false) then player:addQuest(OUTLANDS,WANDERING_SOULS); player:startEvent(0x00CA,949); elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE) and player:hasCompleteQuest(OUTLANDS,WANDERING_SOULS) == false) then player:addQuest(OUTLANDS,WANDERING_SOULS); player:startEvent(0x00CA,949); else player:messageSpecial(NOTHING_HAPPENS); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then -- if requirements are met and 15 mins have passed since mobs were last defeated, spawn them if (player:hasKeyItem(WIND_FRAGMENT) == false and GetServerVariable("[ZM4]Wind_Headstone_Active") < os.time()) then player:startEvent(0x00C8,WIND_FRAGMENT); -- if 15 min window is open and requirements are met, recieve key item elseif (player:hasKeyItem(WIND_FRAGMENT) == false and GetServerVariable("[ZM4]Wind_Headstone_Active") > os.time()) then player:addKeyItem(WIND_FRAGMENT); -- Check and see if all fragments have been found (no need to check wind and dark frag) if (player:hasKeyItem(ICE_FRAGMENT) and player:hasKeyItem(EARTH_FRAGMENT) and player:hasKeyItem(WATER_FRAGMENT) and player:hasKeyItem(FIRE_FRAGMENT) and player:hasKeyItem(LIGHTNING_FRAGMENT) and player:hasKeyItem(LIGHT_FRAGMENT)) then player:messageSpecial(FOUND_ALL_FRAGS,WIND_FRAGMENT); player:addTitle(BEARER_OF_THE_EIGHT_PRAYERS); player:completeMission(ZILART,HEADSTONE_PILGRIMAGE); player:addMission(ZILART,THROUGH_THE_QUICKSAND_CAVES); else player:messageSpecial(KEYITEM_OBTAINED,WIND_FRAGMENT); end else player:messageSpecial(ALREADY_OBTAINED_FRAG,WIND_FRAGMENT); end elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then player:messageSpecial(ZILART_MONUMENT); else player:messageSpecial(CANNOT_REMOVE_FRAG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00C8 and option == 1) then SpawnMob(17240414):updateClaim(player); -- Axesarion the Wanderer SetServerVariable("[ZM4]Wind_Headstone_Active",0); elseif (csid == 0x00CA) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13248); else player:tradeComplete(); player:addItem(13248); player:messageSpecial(ITEM_OBTAINED,13248); player:completeQuest(OUTLANDS,WANDERING_SOULS); player:addTitle(BEARER_OF_BONDS_BEYOND_TIME); end end end;
gpl-3.0
lyzardiar/RETools
PublicTools/bin/tools/bin/win32/lua/jit/bcsave.lua
1
18928
---------------------------------------------------------------------------- -- LuaJIT module to save/list bytecode. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module saves or lists the bytecode for an input file. -- It's run by the -b command line option. -- ------------------------------------------------------------------------------ local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local bit = require("bit") -- Symbol name prefix for LuaJIT bytecode. local LJBC_PREFIX = "luaJIT_BC_" ------------------------------------------------------------------------------ local function usage() io.stderr:write[[ Save LuaJIT bytecode: luajit -b[options] input output -l Only list bytecode. -s Strip debug info (default). -g Keep debug info. -n name Set module name (default: auto-detect from input name). -t type Set output file type (default: auto-detect from output name). -a arch Override architecture for object files (default: native). -o os Override OS for object files (default: native). -e chunk Use chunk string as input. -- Stop handling options. - Use stdin as input and/or stdout as output. File types: c h obj o raw (default) ]] os.exit(1) end local function check(ok, ...) if ok then return ok, ... end io.stderr:write("luajit: ", ...) io.stderr:write("\n") os.exit(1) end local function readfile(input) if type(input) == "function" then return input end if input == "-" then input = nil end return check(loadfile(input)) end local function savefile(name, mode) if name == "-" then return io.stdout end return check(io.open(name, mode)) end ------------------------------------------------------------------------------ local map_type = { raw = "raw", c = "c", h = "h", o = "obj", obj = "obj", } local map_arch = { x86 = true, x64 = true, arm = true, arm64 = true, ppc = true, mips = true, mipsel = true, } local map_os = { linux = true, windows = true, osx = true, freebsd = true, netbsd = true, openbsd = true, dragonfly = true, solaris = true, } local function checkarg(str, map, err) str = string.lower(str) local s = check(map[str], "unknown ", err) return s == true and str or s end local function detecttype(str) local ext = string.match(string.lower(str), "%.(%a+)$") return map_type[ext] or "raw" end local function checkmodname(str) check(string.match(str, "^[%w_.%-]+$"), "bad module name") return string.gsub(str, "[%.%-]", "_") end local function detectmodname(str) if type(str) == "string" then local tail = string.match(str, "[^/\\]+$") if tail then str = tail end local head = string.match(str, "^(.*)%.[^.]*$") if head then str = head end str = string.match(str, "^[%w_.%-]+") else str = nil end check(str, "cannot derive module name, use -n name") return string.gsub(str, "[%.%-]", "_") end ------------------------------------------------------------------------------ local function bcsave_tail(fp, output, s) local ok, err = fp:write(s) if ok and output ~= "-" then ok, err = fp:close() end check(ok, "cannot write ", output, ": ", err) end local function bcsave_raw(output, s) local fp = savefile(output, "wb") bcsave_tail(fp, output, s) end local function bcsave_c(ctx, output, s) local fp = savefile(output, "w") if ctx.type == "c" then fp:write(string.format([[ #ifdef _cplusplus extern "C" #endif #ifdef _WIN32 __declspec(dllexport) #endif const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname)) else fp:write(string.format([[ #define %s%s_SIZE %d static const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname)) end local t, n, m = {}, 0, 0 for i=1,#s do local b = tostring(string.byte(s, i)) m = m + #b + 1 if m > 78 then fp:write(table.concat(t, ",", 1, n), ",\n") n, m = 0, #b + 1 end n = n + 1 t[n] = b end bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n") end local function bcsave_elfobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint32_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF32header; typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint64_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF64header; typedef struct { uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize; } ELF32sectheader; typedef struct { uint32_t name, type; uint64_t flags, addr, ofs, size; uint32_t link, info; uint64_t align, entsize; } ELF64sectheader; typedef struct { uint32_t name, value, size; uint8_t info, other; uint16_t sectidx; } ELF32symbol; typedef struct { uint32_t name; uint8_t info, other; uint16_t sectidx; uint64_t value, size; } ELF64symbol; typedef struct { ELF32header hdr; ELF32sectheader sect[6]; ELF32symbol sym[2]; uint8_t space[4096]; } ELF32obj; typedef struct { ELF64header hdr; ELF64sectheader sect[6]; ELF64symbol sym[2]; uint8_t space[4096]; } ELF64obj; ]] local symname = LJBC_PREFIX..ctx.modname local is64, isbe = false, false if ctx.arch == "x64" or ctx.arch == "arm64" then is64 = true elseif ctx.arch == "ppc" or ctx.arch == "mips" then isbe = true end -- Handle different host/target endianess. local function f32(x) return x end local f16, fofs = f32, f32 if ffi.abi("be") ~= isbe then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end if is64 then local two32 = ffi.cast("int64_t", 2^32) function fofs(x) return bit.bswap(x)*two32 end else fofs = f32 end end -- Create ELF object and fill in header. local o = ffi.new(is64 and "ELF64obj" or "ELF32obj") local hdr = o.hdr if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi. local bf = assert(io.open("/bin/ls", "rb")) local bs = bf:read(9) bf:close() ffi.copy(o, bs, 9) check(hdr.emagic[0] == 127, "no support for writing native object files") else hdr.emagic = "\127ELF" hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0 end hdr.eclass = is64 and 2 or 1 hdr.eendian = isbe and 2 or 1 hdr.eversion = 1 hdr.type = f16(1) hdr.machine = f16(({ x86=3, x64=62, arm=40, arm64=183, ppc=20, mips=8, mipsel=8 })[ctx.arch]) if ctx.arch == "mips" or ctx.arch == "mipsel" then hdr.flags = 0x50001006 end hdr.version = f32(1) hdr.shofs = fofs(ffi.offsetof(o, "sect")) hdr.ehsize = f16(ffi.sizeof(hdr)) hdr.shentsize = f16(ffi.sizeof(o.sect[0])) hdr.shnum = f16(6) hdr.shstridx = f16(2) -- Fill in sections and symbols. local sofs, ofs = ffi.offsetof(o, "space"), 1 for i,name in ipairs{ ".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack", } do local sect = o.sect[i] sect.align = fofs(1) sect.name = f32(ofs) ffi.copy(o.space+ofs, name) ofs = ofs + #name+1 end o.sect[1].type = f32(2) -- .symtab o.sect[1].link = f32(3) o.sect[1].info = f32(1) o.sect[1].align = fofs(8) o.sect[1].ofs = fofs(ffi.offsetof(o, "sym")) o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0])) o.sect[1].size = fofs(ffi.sizeof(o.sym)) o.sym[1].name = f32(1) o.sym[1].sectidx = f16(4) o.sym[1].size = fofs(#s) o.sym[1].info = 17 o.sect[2].type = f32(3) -- .shstrtab o.sect[2].ofs = fofs(sofs) o.sect[2].size = fofs(ofs) o.sect[3].type = f32(3) -- .strtab o.sect[3].ofs = fofs(sofs + ofs) o.sect[3].size = fofs(#symname+1) ffi.copy(o.space+ofs+1, symname) ofs = ofs + #symname + 2 o.sect[4].type = f32(1) -- .rodata o.sect[4].flags = fofs(2) o.sect[4].ofs = fofs(sofs + ofs) o.sect[4].size = fofs(#s) o.sect[5].type = f32(1) -- .note.GNU-stack o.sect[5].ofs = fofs(sofs + ofs + #s) -- Write ELF object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_peobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint16_t arch, nsects; uint32_t time, symtabofs, nsyms; uint16_t opthdrsz, flags; } PEheader; typedef struct { char name[8]; uint32_t vsize, vaddr, size, ofs, relocofs, lineofs; uint16_t nreloc, nline; uint32_t flags; } PEsection; typedef struct __attribute((packed)) { union { char name[8]; uint32_t nameref[2]; }; uint32_t value; int16_t sect; uint16_t type; uint8_t scl, naux; } PEsym; typedef struct __attribute((packed)) { uint32_t size; uint16_t nreloc, nline; uint32_t cksum; uint16_t assoc; uint8_t comdatsel, unused[3]; } PEsymaux; typedef struct { PEheader hdr; PEsection sect[2]; // Must be an even number of symbol structs. PEsym sym0; PEsymaux sym0aux; PEsym sym1; PEsymaux sym1aux; PEsym sym2; PEsym sym3; uint32_t strtabsize; uint8_t space[4096]; } PEobj; ]] local symname = LJBC_PREFIX..ctx.modname local is64 = false if ctx.arch == "x86" then symname = "_"..symname elseif ctx.arch == "x64" then is64 = true end local symexport = " /EXPORT:"..symname..",DATA " -- The file format is always little-endian. Swap if the host is big-endian. local function f32(x) return x end local f16 = f32 if ffi.abi("be") then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end end -- Create PE object and fill in header. local o = ffi.new("PEobj") local hdr = o.hdr hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch]) hdr.nsects = f16(2) hdr.symtabofs = f32(ffi.offsetof(o, "sym0")) hdr.nsyms = f32(6) -- Fill in sections and symbols. o.sect[0].name = ".drectve" o.sect[0].size = f32(#symexport) o.sect[0].flags = f32(0x00100a00) o.sym0.sect = f16(1) o.sym0.scl = 3 o.sym0.name = ".drectve" o.sym0.naux = 1 o.sym0aux.size = f32(#symexport) o.sect[1].name = ".rdata" o.sect[1].size = f32(#s) o.sect[1].flags = f32(0x40300040) o.sym1.sect = f16(2) o.sym1.scl = 3 o.sym1.name = ".rdata" o.sym1.naux = 1 o.sym1aux.size = f32(#s) o.sym2.sect = f16(2) o.sym2.scl = 2 o.sym2.nameref[1] = f32(4) o.sym3.sect = f16(-1) o.sym3.scl = 2 o.sym3.value = f32(1) o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant. ffi.copy(o.space, symname) local ofs = #symname + 1 o.strtabsize = f32(ofs + 4) o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs) ffi.copy(o.space + ofs, symexport) ofs = ofs + #symexport o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs) -- Write PE object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_machobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags; } mach_header; typedef struct { mach_header; uint32_t reserved; } mach_header_64; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint32_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint64_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command_64; typedef struct { char sectname[16], segname[16]; uint32_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2; } mach_section; typedef struct { char sectname[16], segname[16]; uint64_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2, reserved3; } mach_section_64; typedef struct { uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; } mach_symtab_command; typedef struct { int32_t strx; uint8_t type, sect; int16_t desc; uint32_t value; } mach_nlist; typedef struct { uint32_t strx; uint8_t type, sect; uint16_t desc; uint64_t value; } mach_nlist_64; typedef struct { uint32_t magic, nfat_arch; } mach_fat_header; typedef struct { uint32_t cputype, cpusubtype, offset, size, align; } mach_fat_arch; typedef struct { struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[1]; mach_nlist sym_entry; uint8_t space[4096]; } mach_obj; typedef struct { struct { mach_header_64 hdr; mach_segment_command_64 seg; mach_section_64 sec; mach_symtab_command sym; } arch[1]; mach_nlist_64 sym_entry; uint8_t space[4096]; } mach_obj_64; typedef struct { mach_fat_header fat; mach_fat_arch fat_arch[2]; struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[2]; mach_nlist sym_entry; uint8_t space[4096]; } mach_fat_obj; ]] local symname = '_'..LJBC_PREFIX..ctx.modname local isfat, is64, align, mobj = false, false, 4, "mach_obj" if ctx.arch == "x64" then is64, align, mobj = true, 8, "mach_obj_64" elseif ctx.arch == "arm" then isfat, mobj = true, "mach_fat_obj" elseif ctx.arch == "arm64" then is64, align, isfat, mobj = true, 8, true, "mach_fat_obj" else check(ctx.arch == "x86", "unsupported architecture for OSX") end local function aligned(v, a) return bit.band(v+a-1, -a) end local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE. -- Create Mach-O object and fill in header. local o = ffi.new(mobj) local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align) local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12}, arm64={0x01000007,0x0100000c} })[ctx.arch] local cpusubtype = ({ x86={3}, x64={3}, arm={3,9}, arm64={3,0} })[ctx.arch] if isfat then o.fat.magic = be32(0xcafebabe) o.fat.nfat_arch = be32(#cpusubtype) end -- Fill in sections and symbols. for i=0,#cpusubtype-1 do local ofs = 0 if isfat then local a = o.fat_arch[i] a.cputype = be32(cputype[i+1]) a.cpusubtype = be32(cpusubtype[i+1]) -- Subsequent slices overlap each other to share data. ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0]) a.offset = be32(ofs) a.size = be32(mach_size-ofs+#s) end local a = o.arch[i] a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface a.hdr.cputype = cputype[i+1] a.hdr.cpusubtype = cpusubtype[i+1] a.hdr.filetype = 1 a.hdr.ncmds = 2 a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym) a.seg.cmd = is64 and 0x19 or 0x1 a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec) a.seg.vmsize = #s a.seg.fileoff = mach_size-ofs a.seg.filesize = #s a.seg.maxprot = 1 a.seg.initprot = 1 a.seg.nsects = 1 ffi.copy(a.sec.sectname, "__data") ffi.copy(a.sec.segname, "__DATA") a.sec.size = #s a.sec.offset = mach_size-ofs a.sym.cmd = 2 a.sym.cmdsize = ffi.sizeof(a.sym) a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs a.sym.nsyms = 1 a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs a.sym.strsize = aligned(#symname+2, align) end o.sym_entry.type = 0xf o.sym_entry.sect = 1 o.sym_entry.strx = 1 ffi.copy(o.space+1, symname) -- Write Macho-O object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, mach_size)) bcsave_tail(fp, output, s) end local function bcsave_obj(ctx, output, s) local ok, ffi = pcall(require, "ffi") check(ok, "FFI library required to write this file type") if ctx.os == "windows" then return bcsave_peobj(ctx, output, s, ffi) elseif ctx.os == "osx" then return bcsave_machobj(ctx, output, s, ffi) else return bcsave_elfobj(ctx, output, s, ffi) end end ------------------------------------------------------------------------------ local function bclist(input, output) local f = readfile(input) require("jit.bc").dump(f, savefile(output, "w"), true) end local function bcsave(ctx, input, output) local f = readfile(input) local s = string.dump(f, ctx.strip) local t = ctx.type if not t then t = detecttype(output) ctx.type = t end if t == "raw" then bcsave_raw(output, s) else if not ctx.modname then ctx.modname = detectmodname(input) end if t == "obj" then bcsave_obj(ctx, output, s) else bcsave_c(ctx, output, s) end end end local function docmd(...) local arg = {...} local n = 1 local list = false local ctx = { strip = true, arch = jit.arch, os = string.lower(jit.os), type = false, modname = false, } while n <= #arg do local a = arg[n] if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then table.remove(arg, n) if a == "--" then break end for m=2,#a do local opt = string.sub(a, m, m) if opt == "l" then list = true elseif opt == "s" then ctx.strip = true elseif opt == "g" then ctx.strip = false else if arg[n] == nil or m ~= #a then usage() end if opt == "e" then if n ~= 1 then usage() end arg[1] = check(loadstring(arg[1])) elseif opt == "n" then ctx.modname = checkmodname(table.remove(arg, n)) elseif opt == "t" then ctx.type = checkarg(table.remove(arg, n), map_type, "file type") elseif opt == "a" then ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture") elseif opt == "o" then ctx.os = checkarg(table.remove(arg, n), map_os, "OS name") else usage() end end end else n = n + 1 end end if list then if #arg == 0 or #arg > 2 then usage() end bclist(arg[1], arg[2] or "-") else if #arg ~= 2 then usage() end bcsave(ctx, arg[1], arg[2]) end end ------------------------------------------------------------------------------ -- Public module functions. return { start = docmd -- Process -b command line option. }
mit
thedraked/darkstar
scripts/zones/Nashmau/npcs/Awaheen.lua
17
1921
----------------------------------- -- Area: Nashmau -- NPC: Awaheen -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Trade: Receive: -- 1 x Imperial Gold Piece (2187) 5 x Imperial Mythril Piece(2186) -- 1 x Imperial Mythril Piece(2186) 2 x Imperial Silver Piece(2185) -- 1 x Imperial Silver Piece (2185) 5 x Imperial Bronze Piece(2184) local nbr = 0; local reward = 0; if (trade:getItemCount() == 1) then if (trade:hasItemQty(2187,1)) then nbr = 5 ; reward = 2186; elseif (trade:hasItemQty(2186,1)) then nbr = 2 ; reward = 2185; elseif (trade:hasItemQty(2185,1)) then nbr = 5 ; reward = 2184; end end if (reward > 0) then local boucle; if (player:getFreeSlotsCount() >= 1) then player:tradeComplete(); player:addItem(reward,nbr); for boucle=1,nbr,1 do player:messageSpecial(ITEM_OBTAINED,reward); end else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,reward); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00F0); 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
thedraked/darkstar
scripts/globals/abilities/curing_waltz.lua
19
2259
----------------------------------- -- Ability: Curing Waltz -- Heals HP to target player. -- Obtained: Dancer Level 15 -- TP Required: 20% -- Recast Time: 00:06 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (target:getHP() == 0) then return MSGBASIC_CANNOT_ON_THAT_TARG,0; elseif (player:hasStatusEffect(EFFECT_SABER_DANCE)) then return MSGBASIC_UNABLE_TO_USE_JA2, 0; elseif (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 200) then return MSGBASIC_NOT_ENOUGH_TP,0; else -- apply waltz recast modifiers if (player:getMod(MOD_WALTZ_RECAST)~=0) then local recastMod = -60 * (player:getMod(MOD_WALTZ_RECAST)); -- 300 ms per 5% (per merit) if (recastMod <0) then --TODO end end return 0,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(EFFECT_TRANCE) then player:delTP(200); end; --Grabbing variables. local vit = target:getStat(MOD_VIT); local chr = player:getStat(MOD_CHR); local mjob = player:getMainJob(); --19 for DNC main. local sjob = player:getSubJob(); local cure = 0; --Performing sj mj check. if (mjob == 19) then cure = (vit+chr)*0.25+60; end if (sjob == 19) then cure = (vit+chr)*0.125+60; end -- apply waltz modifiers cure = math.floor(cure * (1.0 + (player:getMod(MOD_WALTZ_POTENTCY)/100))); --Reducing TP. --Applying server mods.... cure = cure * CURE_POWER; --Cap the final amount to max HP. if ((target:getMaxHP() - target:getHP()) < cure) then cure = (target:getMaxHP() - target:getHP()); end --Do it target:restoreHP(cure); target:wakeUp(); player:updateEnmityFromCure(target,cure); return cure; end;
gpl-3.0
thedraked/darkstar
scripts/globals/items/bowl_of_vegetable_broth.lua
18
1384
----------------------------------------- -- ID: 4323 -- Item: bowl_of_vegetable_broth -- Food Effect: 4Hrs, All Races ----------------------------------------- -- Vitality -1 -- Agility 5 -- Ranged Accuracy 6 -- HP Recovered While Healing 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,4323); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VIT, -1); target:addMod(MOD_AGI, 5); target:addMod(MOD_RACC, 6); target:addMod(MOD_HPHEAL, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VIT, -1); target:delMod(MOD_AGI, 5); target:delMod(MOD_RACC, 6); target:delMod(MOD_HPHEAL, 3); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Windurst_Walls/npcs/Hiwon-Biwon.lua
17
3908
----------------------------------- -- Area: Windurst Walls -- NPC: Hiwon-Biwon -- Involved In Quest: Making Headlines, Curses, Foiled...Again!? -- Working 100% ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); local CFA2 = player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_2); -- Curses,Foiled ... Again!? if (CFA2 == QUEST_ACCEPTED and player:hasItem(552) == false) then player:startEvent(0x00B6); -- get Hiwon's hair elseif (CFA2 == QUEST_COMPLETED and MakingHeadlines ~= QUEST_ACCEPTED) then player:startEvent(0x00B9); -- New Dialog after CFA2 -- Making Headlines elseif (MakingHeadlines == 1) then prog = player:getVar("QuestMakingHeadlines_var"); -- Variable to track if player has talked to 4 NPCs and a door -- 1 = Kyume -- 2 = Yujuju -- 4 = Hiwom -- 8 = Umumu -- 16 = Mahogany Door if (testflag(tonumber(prog),4) == false) then if (player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_1) == 1) then if (math.random(1,2) == 1) then player:startEvent(0x011b); -- Give scoop while sick else player:startEvent(0x011c); -- Give scoop while sick end else player:startEvent(0x0119); -- Give scoop end else player:startEvent(0x011a); -- "Getting back to the maater at hand-wand..." end else local rand = math.random(1,5); if (rand == 1) then print (rand); player:startEvent(0x0131); -- Standard Conversation elseif (rand == 2) then print (rand); player:startEvent(0x0132); -- Standard Conversation elseif (rand == 3) then print (rand); player:startEvent(0x00a8); -- Standard Conversation elseif (rand == 4) then print (rand); player:startEvent(0x00aa); -- Standard Conversation elseif (rand == 5) then print (rand); player:startEvent(0x00a9); -- Standard Conversation end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- Making Headlines if (csid == 0x0119 or csid == 0x011b or csid == 0x011c) then prog = player:getVar("QuestMakingHeadlines_var"); player:addKeyItem(WINDURST_WALLS_SCOOP); player:messageSpecial(KEYITEM_OBTAINED,WINDURST_WALLS_SCOOP); player:setVar("QuestMakingHeadlines_var",prog+4); -- Curses,Foiled...Again!? elseif (csid == 0x00B6) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,552); -- Hiwon's hair else player:addItem(552); player:messageSpecial(ITEM_OBTAINED,552); -- Hiwon's hair end end end;
gpl-3.0
thedraked/darkstar
scripts/zones/The_Shrine_of_RuAvitau/mobs/Kirin_s_Avatar.lua
22
2284
----------------------------------- -- Area: The Shrine of Ru'Avitau -- MOB: Kirin's Avatar ----------------------------------- package.loaded["scripts/zones/The_Shrine_of_RuAvitau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Shrine_of_RuAvitau/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setModelId(math.random(791, 798)); mob:hideName(false); mob:untargetable(true); mob:setUnkillable(true); end ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobEngaged(mob, target) local id = mob:getID(); local kirin = GetMobByID(mob:getID()-5); -- Kirin's Avatar is offset by 5 local action = GetMobAction(id); local distance = mob:checkDistance(target); local abilityId = nil; local modelId = mob:getModelId(); switch (modelId) : caseof { [791] = function (x) abilityId = 912; end, -- Carbuncle [792] = function (x) abilityId = 839; end, -- Fenrir [793] = function (x) abilityId = 848; end, -- Ifrit [794] = function (x) abilityId = 857; end, -- Titan [795] = function (x) abilityId = 866; end, -- Leviathan [796] = function (x) abilityId = 875; end, -- Garuda [797] = function (x) abilityId = 884; end, -- Shiva [798] = function (x) abilityId = 893; end, -- Ramuh } if (abilityId ~= nil) then mob:useMobAbility(abilityId); end end ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob, target) end ----------------------------------- -- onMobWeaponSkill ----------------------------------- function onMobWeaponSkill(target, mob, skill) mob:setUnkillable(false); mob:setHP(0); end ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end ----------------------------------- -- OnMobDespawn ----------------------------------- function onMobDespawn(mob) end
gpl-3.0
thedraked/darkstar
scripts/zones/Giddeus/npcs/Ghoo_Pakya.lua
14
2161
----------------------------------- -- Area: Giddeus -- NPC: Ghoo Pakya -- Involved in Mission 1-3 -- @pos -139 0 147 145 ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/zones/Giddeus/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE) then if (player:hasKeyItem(DRINK_OFFERINGS)) then -- We have the offerings player:startEvent(0x0031); else if (player:getVar("ghoo_talk") == 1) then -- npc: You want your offering back? player:startEvent(0x0032); elseif (player:getVar("ghoo_talk") == 2) then -- npc: You'll have to crawl back to treasure chamber, etc player:startEvent(0x0033); else -- We don't have the offerings yet or anymore player:startEvent(0x0034); end end else player:startEvent(0x0034); 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 == 0x0031) then player:delKeyItem(DRINK_OFFERINGS); player:setVar("ghoo_talk",1); if (player:hasKeyItem(FOOD_OFFERINGS) == false) then player:setVar("MissionStatus",2); end elseif (csid == 0x0032) then player:setVar("ghoo_talk",2); end end;
gpl-3.0
thedraked/darkstar
scripts/globals/items/serving_of_salmon_eggs.lua
18
1325
----------------------------------------- -- ID: 5217 -- Item: serving_of_salmon_eggs -- Food Effect: 5Min, All Races ----------------------------------------- -- Health 6 -- Magic 6 -- Dexterity 2 -- Mind -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,5217); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 6); target:addMod(MOD_MP, 6); target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 6); target:delMod(MOD_MP, 6); target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -3); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Arrapago_Reef/mobs/Medusa.lua
20
1467
----------------------------------- -- Area: Arrapago Reef -- MOB: Medusa -- @pos -458 -20 458 -- TODO: resists, attack/def boosts ----------------------------------- require("scripts/globals/titles"); require("scripts/zones/Arrapago_Reef/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("eeshpp", math.random(5,99)); -- Uses EES randomly during the fight end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob, target) local mobID = mob:getID(); target:showText(mob, MEDUSA_ENGAGE); SpawnMob(mobID+1, 180):updateEnmity(target); SpawnMob(mobID+2, 180):updateEnmity(target); SpawnMob(mobID+3, 180):updateEnmity(target); SpawnMob(mobID+4, 180):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local HPP = mob:getHPP(); if (mob:getLocalVar("usedees") == 0) then if (HPP <= mob:getLocalVar("eeshpp")) then mob:useMobAbility(1931); -- Eagle Eye Shot mob:setLocalVar("usedees", 1); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:showText(mob, MEDUSA_DEATH); player:addTitle(GORGONSTONE_SUNDERER); end;
gpl-3.0
Jg99/SCgemamod
gemamod_opensource.lua
1
29614
PLUGIN_NAME = "SilverCloudGemaMod OpenSource version" PLUGIN_AUTHOR = "Jg99" -- Jg99 PLUGIN_VERSION = "4.2.2" -- SilverCloud Gema mod dofile("lua/scripts/functions/functions.lua") -- common include("ac_server") config = { gema_mode_autodetecting = true; gema_mode_is_turned_on = true } cached_gtop = nil new_record_added = true fines = {} start_times = {} autogemakick = false dup = false colortext = true function find_place(records, name) local result = nil for i,record in ipairs(records) do if record[1] == name then result = i break end end return result end function gload() if new_record_added == false then return cached_gtop end local grecords = {} local grecords_m = {} local count = 0 for line in io.lines("lua/config/SvearkMod_maps.cfg") do local cnt = string.find(line, "=") if cnt ~= nil then local map_name = string.sub(line,1,cnt - 1) local gdata = sorted_records(load_records(map_name)) local n = grecords_m[gdata[1][1]] if n == nil then count = count + 1 table.insert(grecords, { gdata[1][1], 1}) grecords_m[gdata[1][1]] = count else grecords[grecords_m[gdata[1][1]]][2] = grecords[grecords_m[gdata[1][1]]][2] + 1 end else print("Error on gload: lua/config/SvearkMod_maps.cfg non-existant") end end table.sort(grecords, function (L, R) return L[2] > R[2] end) cached_gtop = grecords new_record_added = false return grecords end function say(text, cn) if cn == nil then cn = -1 end -- to all clientprint(cn, text) end function slice(array, S, E) local result = {} local length = #array S = S or 1 E = E or length if E < 0 then E = length + E + 1 elseif E > length then E = length end if S < 1 or S > length then return {} end local i = 1 for j = S, E do result[i] = array[j] i = i + 1 end return result end function is_gema(mapname) local implicit = { "jigsaw", "deadmeat-10" } local code = { "g", "3e", "m", "a@4" } mapname = mapname:lower() for k,v in ipairs(implicit) do if mapname:find(v) then return true end end for i = 1, #mapname - #code + 1 do local match = 0 for j = 1, #code do for k = 1, #code[j] do if mapname:sub(i+j-1, i+j-1) == code[j]:sub(k, k) then match = match + 1 end end end if match == #code then return true end end return false end -- interface to the records function sorted_records(records) local sorted_records = {} for player, delta in pairs(records) do table.insert(sorted_records, { player, delta }) end table.sort(sorted_records, function (L, R) return L[2] < R[2] end) return sorted_records end function reverse_sorted_records(records) if records == nil then return nil end local sorted_records = {} for player, delta in pairs(records) do table.insert(sorted_records, { player, delta }) end table.sort(sorted_records, function (L, R) return L[2] > R[2] end) return sorted_records end function add_record(map, player, delta) local records = load_records(map) if records[player] == nil or delta < records[player] then records[player] = delta save_records(map, records) new_record_added = true end end function save_records(map, records) local sorted_records = sorted_records(records) local lines = {} for i,record in ipairs(sorted_records) do table.insert(lines, record[1] .. " " .. tostring(record[2])) end cfg.setvalue("SvearkMod_maps", map:lower():gsub("=", ""), table.concat(lines, "\t")) end function load_records(map) local records = {} local data = cfg.getvalue("SvearkMod_maps", map:lower():gsub("=", "")) if data ~= nil then local lines = split(data, "\t") for i,line in ipairs(lines) do record = split(line, " ") records[record[1]] = tonumber(record[2]) end end return records end function get_best_record(map) local sorted_records = sorted_records(load_records(map)) local i, best_record = next(sorted_records) if best_record == nil then return PLUGIN_BLOCK end if best_record[1] or best_record[2] ~= nil then return best_record[1], best_record[2] elseif best_record[1] or best_record[2] == nil then print("Error returning best_record") end end --- function fine_player(cn, fine) if fine > 0 then if fines[cn] == nil then fines[cn] = fine else fines[cn] = fines[cn] + fine end end end function sendMOTD(cn) if not config.gema_mode_is_turned_on then return end if cn == nil then cn = -1 end commands["!mapbest"][2](cn, {}) say("\f4TYPE \fR!cmds \f4TO SEE AVAILABLE SERVER COMMANDS", cn) say("\fR[SERVER NEWS] \f9Insert News Here! Default News message.", cn) end -- commands --- params: { admin required, show message in chat, gema mode required } commands = { ["!serverdesc"] = { { true, false, false }; function (cn, args) a = tostring(args[1]) b = tostring(args[2]) c = tostring(args[3]) d = tostring(args[4]) e = tostring(args[5]) f = tostring(args[6]) g = tostring(args[7]) h = tostring(args[8]) i = tostring(args[9]) j = tostring(args[10]) if b == nil then b = "\f9" elseif c == nil then c = "\f9 " elseif d == nil then d = "\f9 " elseif e == nil then e = "\f9 " elseif f == nil then f = "\f9 " elseif g == nil then g = "\f9 " elseif h == nil then h = "\f9 " elseif i == nil then i = "\f9 " elseif j == nil then j = "\f9 " end setservname(string.format("%s %s %s %s %s %s %s %s %s %s", a, b, c, d, e, f, g, h, i, j)) say("\f9 The server name was changed to " ..string.format("%s %s %s %s %s %s %s %s %s %s.", a, b, c, d, e, f, g, h, i, j)) end }; ["!cmds"] = { { false, false, false }; function (cn, args) say("\fP-------------------------------------------------------------------------------------------------------------------------------------------------------", cn) say("\f4AVAILABLE COMMANDS: \fP| \fR!mapbest \fP| \fR!grank \fP| \fR!mybest \fP| \fR!maptop \fP| \fR!pm \f4<CN> <TEXT>\fP| \fR !whois \f4 <CN> \fP| \fR !rules \fP| \fR !gemarules \fP|\fR !gtop \fP| \fR !inf \fP| \fR!addtime \fP|", cn) say("\fP-------------------------------------------------------------------------------------------------------------------------------------------------------", cn) if isadmin(cn) then say("\f3ADMIN COMMANDS: \fP| \fR!auto \fP| \fR!gema \fP| \fR!say \f4<TEXT> \fP| \fR!ext \f4<MINUTES> \fP| \fR !setadmin PASS \fP| \fR !ipbl <CN> \fP| \fR !b or !k <CN> \fP| \fR !~mute \f4 <CN>\fP|", cn) say("\f3ADMIN CMDS CONTINUED: \f9 !serverdesc NAME | !setmaxclients # |", cn) say("\fP-------------------------------------------------------------------------------", cn) end say("\fR [SERVER INFO] \f4" .. getname(cn) .. "\fR is watching server commands.") end }; ["!mute"] = { { true, false, false }; function(cn, tcn, reason) server.mute(cn, tcn, reason) end }; ["!colortext"] = { { true, false, false }; function (cn,args) colortext = not colortext say("\f4You have " ..(colortext and "enabled" or "disabled").. " colorful text", cn) end }; ["!inf"] = { { false, false, false }; function(cn) say("\f9SilverCloud\f4 Gema Mod \fR v. 4.2.1 OpenSource , Copyleft 2011-2014 SilverCloudTech (Jg99), No Rights Reserved.", cn) say("\fR Lua AC Executables made by Sveark. \f9Our website is \f4www.sctechusa.com.", cn) end }; ["!addtime"] = { { false, false, false }; function (cn, args) if tonumber(args[1]) < 16 and tonumber(args[1]) > 2 then settimeleft(tonumber(args[1])) say(string.format("\fR [SERVER INFO] \f4 Time remaining changed to %d", args[1]), cn) else say(string.format("\f3 ERROR: Time has to be between 3 and 15 minutes, %s!", getname(cn)), cn) end end }; --]] ["!ext"] = { { true, false, true }; function (cn, args) if #args == 1 then settimeleft(tonumber(args[1])) say("\fR [SERVER INFO] \f4 Time remaining changed!") end end }; ["lol"] = { {false, false, false}; function (cn, args) say("\fR [SERVER INFO] \f4" .. getname(cn) .. " \fRLOL'D") end }; ["!deadmin"] = { {true, false, false}; function (cn, tcn) setrole(tcn, 0, false) end }; ["lmao"] = { {false, true, false}; function (cn, args) say("\fR [SERVER INFO] \f4" .. getname(cn) .. " \fR\fb Laughed his ass off!!!!") end }; ["!rules"] = { {false, false, false}; function (cn, args) local sender = cn say("\fR [SERVER INFO] \f4" .. getname(cn) .. ", \fR Here are the server's \fR\fbRULES:", cn) say("\fR [SERVER INFO] \f4 SERVER RULES: 1: NO KILLING IN GEMA = \f3Ban or Blacklist", cn) say("\fR [SERVER INFO] \f4 2: NO cheating/abusive behavior = \f3Ban/blaclklist", cn) say("\fP ----------------------------------------------------------------------------------------------------", cn) end }; ["!gemarules"] = { {false, false, false}; function (cn, args) local sender = cn say("\fR [SERVER INFO] \f4" .. getname(cn) .. ", \fR Here are the gema \fR\fbRULES:", cn) say("\fR [SERVER INFO] \f4 1. No killing in gema, Gema is an obstacle course that ", cn) say("\fR [SERVER INFO] \f4 2: you use the AssaultRifle to perform higher jumps, or with a grenade to", cn) say("\fR [SERVER INFO] \f4 perform very high jumps. Enjoy!", cn) end }; ["!pm"] = { { false, false, false }; function (cn, args) if #args < 2 then return end local to, text = tonumber(args[1]), table.concat(args, " ", 2) say(string.format("\fR [SERVER INFO] \f4PM FROM \fR%s (%d)\f4: \fM%s", getname(cn), cn, text), to) say(string.format("\fR [SERVER INFO] \f4PM FOR \fR%s \f4HAS BEEN SENT", getname(to)), cn) end }; ["!shuffleteams"] = { {true, false, false}; function (cn) shuffleteams() end }; ["!auto"] = { { true, true, false }; function (cn, args) config.gema_mode_autodetecting = not config.gema_mode_autodetecting say("\fR [SERVER INFO] \f4AUTODETECTING OF GEMA MODE IS TURNED " .. (config.gema_mode_autodetecting and "ON" or "OFF"), cn) end }; ["!ipbl"] = { {true, false, false}; function (cn, args) local name = getname(cn) if not isadmin(cn) then return end local ip = "" local mask = "" if #args > 1 then local y = split(table.concat(args, " ", 1), " ") mask = y[2] if mask == "/16" or mask == "/32" or mask == "/24" then if string.len(y[1]) < 3 then local cnx = tonumber(y[1]) if cnx == nil then say("\f4Wrong cn",cn) return end if isadmin(cnx) then return end local tempip = getip(cnx) if mask == "/24" then ip = tempip else ip = temp_ip_split(tempip) .. ".0.0" end say(string.format("\fR%s \f4is banned",getname(cnx))) ban(cnx) else ip = y[1] end else say("\f4IP blacklist failed. Wrong mask",cn) return end else if string.len(args[1]) < 7 then local cnx = tonumber(args[1]) if isadmin(cnx) then return end ip = getip(cnx) say(string.format("\fR%s \f4is banned",getname(cnx))) ban(cnx) else ip = args[1] end end if ip:match("%d+.%d+.%d+.%d+") == nil then say("\f4Not ip",cn) return end os.execute("del /var/www/serverblacklist.cfg.bkp") os.execute("cp /var/www/serverblacklist.cfg /var/www/serverblacklist.cfg.bkp") local f = assert(io.open("/var/www/serverblacklist.cfg", "a+")) f:write("\n",ip .. mask .. "\n") f:close() say(string.format("\fR%s \f4blacklisted by \fR%s",ip .. mask,name)) end }; ["!unipbl"] = { {true, false, false}; function (cn, args) if not isadmin(cn) then return end os.execute("rm /var/www/serverblacklist.cfg") os.execute("cp /var/www/serverblacklist.cfg.bkp /var/www/serverblacklist.cfg") say("\f9SilverCloud Blacklist has been undone successfully.") end }; ["!gema"] = { { true, true, false }; function (cn, args) config.gema_mode_is_turned_on = not config.gema_mode_is_turned_on say("\fR [SERVER INFO] \f4GEMA MODE IS TURNED " .. (config.gema_mode_is_turned_on and "ON" or "OFF"), cn) end }; ["!say"] = { { true, false, false }; function (cn,args) local text = table.concat(args, " ", 1) text = string.gsub(text,"\\f","\f") local parts = split(text, " ") say(text) end }; ["!duplicate"] = { { true, false, false }; function (cn,args) dup = not dup say("\f4You have " ..(dup and "enabled" or "disabled").. " duplicating text", cn) end }; ["!colortext"] = { { true, false, false }; function (cn,args) colortext = not colortext say("\f4You have " ..(colortext and "enabled" or "disabled").. " colorful text", cn) end }; ["!b"] = { { true, false, false }; function (cn, args) local name = getname(cn) local cnx = tonumber(args[1]) if cn == nil then say("\f4Wrong cn",cn) return end say(string.format("\fR[SERVER INFO] \f3" .. getname(cnx) .. "\f4 was banned by \fR" .. getname(cn) .. "\f4. IP: \f4" .. getip(cnx) )) ban(cnx) end }; ["!duplicate"] = { { true, false, false }; function (cn) dup = not dup say("\f4You have " ..(dup and "enabled" or "disabled").. " duplicating text", cn) end }; ["!k"] = { { true, false, false }; function (cn, args) local name = getname(cn) local cnx = tonumber(args[1]) if cn == nil then say("\f4Wrong cn",cn) return end say(string.format("\fR[SERVER INFO] \f3" .. getname(cnx) .. "\f4 is kicked by \fR" .. getname(cn) .. "\f4!")) disconnect(cnx, DISC_MKICK) say("\fR[SERVER INFO]\f4 " ..getname(acn).. "\f4 was kicked. IP:" ..getip(acn).. ".") end }; ["!mapbest"] = { { false, false, true }; function (cn, args) local player, delta = get_best_record(getmapname()) if player ~= nil then say(string.format("\f4THE BEST TIME FOR THIS MAP IS \fR%02d:%02d \f4(RECORDED BY \fR%s\f4)", delta / 60, delta % 60, player), cn) else say("\f4NO BEST TIME FOUND FOR THIS MAP", cn) end end }; ["!mybest"] = { { false, false, true }; function (cn, args) local records = load_records(getmapname()) local delta = records[getname(cn)] if delta == nil then say("\f4NO PRIVATE RECORD FOUND FOR THIS MAP", cn) else say(string.format("\f4YOUR BEST TIME FOR THIS MAP IS \fR%02d:%02d", delta / 60, delta % 60), cn) end end }; ["!autokick"] = { { true, false, false }; function (cn, args) autogemakick = not autogemakick say("\f4You have " ..(autogemakick and "enabled" or "disabled").. " auto gema and teamkill kick.", cn) end }; ["!mapbottom"] = { { false, false, true }; function (cn, args) logline(2, getname(cn).." viewed mapbottom") local sorted_records = reverse_sorted_records(load_records(getmapname())) if sorted_records == nil then say("\f1MAP BOTTOM IS EMPTY", cn) else local record = {} for i, record in ipairs(sorted_records) do if i > 5 then break end if record == nil then say("\f1MAP BOTTOM IS EMPTY", cn) break else if i == 1 then say("\f1 SLOWEST PLAYERS OF THIS MAP:", cn) end say(string.format("\f1%d. \f2%s \f0%02d:%02d", i, record[1], record[2] / 60, record[2] % 60), cn) end end end end }; ["!maptop"] = { { false, false, true }; function (cn, args) local sorted_records = sorted_records(load_records(getmapname())) if next(sorted_records) == nil then say("\f4MAP TOP IS EMPTY", cn) else say("\f43 FASTEST PLAYERS OF THIS MAP:", cn) for i, record in ipairs(sorted_records) do if i > 3 then break end say(string.format("\f4%d. \fR%s \f9%02d:%02d", i, record[1], record[2] / 60, record[2] % 60), cn) end end end }; ["!mrank"] = --accepts name to check { { false, false, true }; function (cn, args) local data ="(self)" if args[1] ~= nil then data = ": "..table.concat(args, " ") end logline(2, getname(cn).." viewed mrank"..data) local sorted_records = sorted_records(load_records(getmapname())) if sorted_records == nil then say("\f1NO RECORDS FOR THIS MAP", cn) return else local prn = nil local player_name = getname(cn) if args[1] ~=nil then player_name = args[1] end --use supplied name instead of self for i, record in ipairs(sorted_records) do total_records = i if record == nil then say("\f1NO RECORDS FOR THIS MAP", cn) return else -- look for player and get time if player_name == record[1] and prn == nil then -- get only first record incase there are duplicated names prt = record[2] prn = i end end end if prn == nil then if args[1] == nil then say("\f1YOU DON'T HAVE ANY RECORDS YET. MAKE AT LEAST ONE RECORD", cn) else say("\f1" .. args[1] .. " Does not have a record for this map", cn) end else if args[1] == nil then sayexept(string.format("\f2%s`s \f1 RANK FOR THIS MAP IS \f0%d \f1of \f0%d \f1TIME: \f2%02d:%02d ",player_name, prn, total_records, prt/60, prt % 60), cn) say(string.format("\f2%s\f1, YOUR MAP RANK IS \f0%d \f1of \f0%d \f1TIME: \f2%02d:%02d ",player_name, prn, total_records, prt/60, prt % 60), cn) else say(string.format("\f2%s`s \f1 RANK FOR THIS MAP IS \f0%d \f1of \f0%d \f1TIME: \f2%02d:%02d ",player_name, prn, total_records, prt/60, prt % 60), cn) end end end end }; ["!mapbest"] = { { false, false, true }; function (cn) local player, delta = get_best_record(getmapname()) if player ~= nil then if delta ~= nil then say(string.format("\f4THE BEST TIME FOR THIS MAP IS \fR%02d:%02d \f4(RECORDED BY \fR%s\f4)", delta / 60, delta % 60, player), cn) else print("ERROR") end else say("\f4NO BEST TIME FOUND FOR THIS MAP", cn) end end }; ["!mybest"] = { { false, false, true }; function (cn) local records = load_records(getmapname()) local delta = records[getname(cn)] if delta == nil then say("\f4NO PRIVATE RECORD FOUND FOR THIS MAP", cn) else say(string.format("\f4YOUR BEST TIME FOR THIS MAP IS \fR%02d:%02d", delta / 60, delta % 60), cn) end end }; ["!maptop"] = { { false, false, true }; function (cn) local sorted_records = sorted_records(load_records(getmapname())) if next(sorted_records) == nil then say("\f4MAP TOP IS EMPTY", cn) else say("\f43 FASTEST PLAYERS OF THIS MAP:", cn) for i, record in ipairs(sorted_records) do if i > 3 then break end say(string.format("\f4%d. \fR%s \f9%02d:%02d", i, record[1], record[2] / 60, record[2] % 60), cn) end end end }; ["!grank"] = { { false, true, true }; function (cn, args) local name if #args > 0 then if tonumber(args[1]) == nil then name = args[1] else x = tonumber(args[1]) if isconnected(x) ~= true then say("\f4Wrong cn",cn) return end name = getname(x) end else name = getname(cn) end top = gload() local place = find_place(top,name) if place == nil then say("\f9[\fPSERVER INFO\f9] \f4DON'T HAVE \fRGRANK\f4. MAKE AT LEAST ONE RECORD", cn) else say(string.format("\fR%s \f4GRANK IS \f9%d \f4WITH \fR%s \f4BEST RESULTS", name,place,top[place][2]),cn) end end }; ["!gtop"] = { { false, false, false }; function (cn, amount) local top = gload() if top == nil then say("\f4GTOP IS EMPTY!", cn) else if tonumber(#top) ~= nil then if amount ~= nil and tonumber(amount) ~= nil then amount = (tonumber(#top) >= tonumber(amount)) and tonumber(amount) or tonumber(#top) say("\fR" .. amount .. " \f4BEST PLAYERS ON THIS SERVER:", cn) for i, record in ipairs(top) do if i > amount and record ~= nil then break end say(string.format("\f4%d. \fR%s \f4with \fR%d \f4best records", i, record[1], record[2]), cn) end else say("\fR5 \f4BEST PLAYERS ON THIS SERVER:", cn) for i, record in ipairs(top) do if i > 5 then break end say(string.format("\f4%d. \fR%s \f4with \fR%d \f4best records", i, record[1], record[2]), cn) end end else clientprint(cn, "Top players in !gtop are NULL") end end end }; } -- handlers function onPlayerDeathAfter(tcn, acn, gib, gun) if acn ~= tcn and config.gema_mode_is_turned_on and autogemakick and isTeammode(getgamemode()) then local totalkills = getfrags(acn) + getteamkills(acn) * 2 if totalkills >= 3 then say("\f4Player \f4" .. getname(acn) .. "has been autobanned for \f3 gema killing. \f4 IP-address:" .. getip(acn)) ban(acn) elseif totalkills then -- disconnect(acn, DISC_MKICK) say("\f4Player \f3" .. getname(acn) .. "\f4 has been autokicked for \f3 gema killing.") disconnect(acn, DISC_MKICK) end end end function onPlayerSayText(cn, text) text2 = string.format("SCLog: Player %s says: %s. Their IP is: %s",getname(cn):gsub("%%", "%%%%"), text:gsub("%%", "%%%%") ,getip(cn)) logline(4, text2) if colortext then text = string.gsub(text,"\\f","\f") local parts = split(text, " ") local command, args = parts[1], slice(parts, 2) if commands[command] ~= nil then local params, callback = commands[command][1], commands[command][2] if (isadmin(cn) or not params[1]) and (config.gema_mode_is_turned_on or not params[3]) then callback(cn, args) if not params[2] then return PLUGIN_BLOCK end else return PLUGIN_BLOCK end end if isadmin(cn) then SayToAllA(text,cn) return PLUGIN_BLOCK else SayToAll(text,cn) return PLUGIN_BLOCK end --logtext = string.gsub("player" .. getname(cn) .. "says:" .. text .. ". IP-address "..getip(cn).. " has been logged") --Output text to Log --logline(3, logtext) else local parts = split(text, " ") local command, args = parts[1], slice(parts, 2) if commands[command] ~= nil then local params, callback = commands[command][1], commands[command][2] if (isadmin(cn) or not params[1]) and (config.gema_mode_is_turned_on or not params[3]) then callback(cn, args) if not params[2] then return PLUGIN_BLOCK end else return PLUGIN_BLOCK end end if isadmin(cn) then SayToAllA(text,cn) return PLUGIN_BLOCK else SayToAll(text,cn) return PLUGIN_BLOCK end end end function SayToAll(text, except) for n=0,20,1 do -- if isconnected(n) and n ~= except then if dup then say("\f4|\fX" .. except .. "\f4|\fR#\f5" .. getname(except) .. ":\f9 " .. text,n) elseif isconnected(n) and n ~= except then say("\f4|\fX" .. except .. "\f4|\fR#\f5" .. getname(except) .. ":\f9 " .. text,n) end -- end end end function SayToAllA(text, except) for n=0,20,1 do -- if isconnected(n) and n ~= except then if dup then say("\f4|\fX" .. except .. "\f4|\f3#\f5" .. getname(except) .. ":\f9 " .. text,n) elseif isconnected(n) and n ~= except then say("\f4|\fX" .. except .. "\f4|\f3#\f5" .. getname(except) .. ":\f9 " .. text,n) end -- end end end function SayToAll2(text, except) if isconnected(n) and n ~= except then say("\fR[SERVER INFO] \f4",text,n) end end function onPlayerNameChange (cn, new_name) say("\fR [SERVER INFO] \f4" .. getname(cn) .. " \fR changed name to \f4" .. new_name .. "!") end function onPlayerSendMap(map_name, cn, upload_error) if is_gema(map_name) then say("\fR SERVER INFO] \f4Gema Check: \f9 Map is a gema!, You may vote it now!", cn) upload_error = UE_NOERROR else say("\fR[SERVER INFO]\f4 Gema Check: \f3 Map is NOT a gema. You may not upload non-gema maps.", cn) upload_error = UE_IGNORE return upload_error end end if config.gema_mode_autodetecting then -- config.gema_mode_is_turned_on = (gamemode == GM_CTF and is_gema(mapname)) end sendMOTD() settimeleft(tonumber(25)) setautoteam(false) local records = load_records(getmapname()) local delta = records[getname(cn)] if delta == nil then say("\f4NO PRIVATE RECORD FOUND FOR THIS MAP", cn) else say(string.format("\f4YOUR BEST TIME FOR THIS MAP IS \fR%02d:%02d", delta / 60, delta % 60), cn) end function onPlayerConnect(cn) sendMOTD(cn) say("\f4Hello \fR" .. getname(cn) .. "!") -- say("\fR [SERVER INFO]" .. getname(cn) .. "\fR connected!!! with ip \f4" .. getip(cn) .. "") setautoteam(false) end function onPlayerCallVote(cn, type, text, number) if (type == SA_AUTOTEAM) and (not getautoteam()) then voteend(VOTE_NO) elseif (type == SA_FORCETEAM) or (type == SA_SHUFFLETEAMS) then voteend(VOTE_NO) end if (type == SA_MAP) and not (number == GM_CTF) then voteend(VOTE_NO) end if (type == SA_GIVEADMIN) or (type == SA_CLEARDEMOS) then voteend(VOTE_NO) end -- if (type == SA_BAN) or (type == SA_KICK) or (type == SA_REMBANS) or (type == --SA_GIVEADMIN) then -- voteend(1) -- end --if number ~= 5 then --voteend --if (type == SA_BAN) or (type == SA_KICK) then --voteend(1) --end setautoteam(0) end function onFlagAction(cn, action, flag) if config.gema_mode_is_turned_on and action == FA_SCORE then if start_times[cn] == nil then return end local delta = math.floor((getsvtick() - start_times[cn]) / 1000) start_times[cn] = nil if delta == 0 then return end if fines[cn] ~= nil then delta = delta + fines[cn] fines[cn] = nil end say(string.format("\f4%s SCORED AFTER %02d:%02d or %02d milliseconds", getname(cn), delta / 60, delta % 60, delta *1000)) add_record(getmapname(), getname(cn), delta) local best_player, best_delta = get_best_record(getmapname()) if best_delta == delta then say("\fR*** \f4\fbNEW BEST TIME RECORDED! \fR***") end end end function onPlayerVote(actor_cn, vote) say("\fR[SERVER INFO] \f4Player " .. getname(actor_cn) .. "\fR(\f9".. actor_cn .. "\fR)\f9 voted \f4F" .. vote .. "\fP!") end function onMapEnd() say("\f4 GG! \f9Thanks for playing a game with us!") end function temp_ip_split(ip) local x,y local xt = false local yt = true for i=1,string.len(ip),1 do if string.sub(ip,i,i) == "." then if yt == false then y = i break end if xt == false then xt = true yt = false x = i end end end return string.sub(ip,1,y-1) end function RandomMessages() local messages = {"\fR [SERVER INFO] \f4 No killing in gema! \f3 Or ban/blacklist!", "\fR [SERVER INFO] \f4Visit =AoW= clan site at http://acaowforum.tk", "\fR \fR[SERVER INFO] \f3Cheating is not allowed. Cheaters will be blacklisted and/or reported.", "\fR [SERVER INFO] \f9 Laggers don't matter in a gema!", "\fR [SERVER INFO] \f3 Abusive behavior/trolling is not allowed, and may result in a \fB ban/blacklist.", "\fR [SERVER INFO] \f4 Have fun playing gemas on SilverCloud Gema server!", "\fR [SERVER INFO] \f4 Look for other \f9SilverCloud\fP\f9=\f4A\fRo\f3W\f9= \f4Servers!", "\fR [SERVER INFO] \f4 Contact Jg99 on IRC or on forum.cubers.net!", "\fR [SERVER INFO] \f4 This gema server has a !whois (CN) cmd so you can view where players connected from (country)!"} clientprint(-1, messages[math.random(#messages)]) end function ChangeServerName() local names = {"\f9 Come Play @ SilverCloud Gemas", "\f9sctechusa.com is the main site!", "\f9No gameplay-modifying commands are used!", "\f9 Hosted by \fPJg99!", "\f9 SilverCloud Gemas has a wide selection of gemas!", "\f9 SilverCloud Gema server has useful stuff, like a gema timer!", "\f9 SAVE GEMAS NOW - SilverCloud Gemas"} setservname(names[math.random(#names)]) end function DisableAutoTeam5Secs() setautoteam(0) end function onInit() --tmr.create(9,9 * 60 * 1000, "RandomMessages") -- every 5 minutes --tmr.create(1,7 * 60 * 1000, "ChangeServerName") -- every 5 seconds tmr.create(2,7 * 1 * 1, "DisableAutoTeam5Secs") -- every 5 ms i think setautoteam(0) setnickblist("/var/www/nicknameblacklist.cfg") setblacklist("/var/www/serverblacklist.cfg") end function onDestroy() tmr.remove(1) tmr.remove(2) tmr.remove(9) end function onPlayerSpawn(cn) start_times[cn] = getsvtick() fines[cn] = nil setautoteam(0) end
gpl-2.0
thedraked/darkstar
scripts/globals/mobskills/Stormwind.lua
30
2237
--------------------------------------------- -- Stormwind -- -- Description: Creates a whirlwind that deals Wind damage to targets in an area of effect. -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown radial -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- -- onMobSkillCheck --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; --------------------------------------------- -- onMobWeaponSkill --------------------------------------------- function onMobWeaponSkill(target, mob, skill) local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); if (mob:getName() == "Kreutzet") then if (mob:actionQueueAbility() == true) then if (mob:getLocalVar("Stormwind") == 0) then mob:setLocalVar("Stormwind", 1); dmgmod = 1.25; info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT); dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); elseif (mob:getLocalVar("Stormwind") == 1) then mob:setLocalVar("Stormwind", 0); dmgmod = 1.6; info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT); dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); end elseif (mob:actionQueueAbility() == false) then for i = 0, 1 do -- Stormwind 3 times per use. Gets stronger each use. -- TODO: Should be some sort of delay here between ws's.. mob:useMobAbility(926); mob:setLocalVar("Stormwind", 0); end end end target:delHP(dmg); return dmg; end;
gpl-3.0
mtroyka/Zero-K
LuaUI/Widgets/gui_lups_stats.lua
19
4434
-- $Id: gui_lups_stats.lua 3171 2008-11-06 09:06:29Z det $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- orig-file: gui_clock.lua -- orig-file: gui_lups_stats.lua -- brief: displays the current game time -- author: jK (on code by trepan) -- -- Copyright (C) 2007. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "LupsStats", desc = "", author = "jK", date = "Dec, 2007", license = "GNU GPL, v2 or later", layer = 0, enabled = false -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- include("colors.h.lua") local floor = math.floor local vsx, vsy = widgetHandler:GetViewSizes() -- the 'f' suffixes are fractions (and can be nil) local color = { 1.0, 1.0, 1.0 } local xposf = 0.99 local xpos = xposf * vsx local yposf = 0.010 local ypos = yposf * vsy + 40 local sizef = 0.015 local size = sizef * vsy local font = "LuaUI/Fonts/FreeSansBold_14" local format = "orn" local fh = (font ~= nil) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Rendering -- function widget:DrawScreen() gl.Color(color) local fxcount, fxlayers, fx = WG['Lups'].GetStats() local totalParticles = (((fx['SimpleParticles'] or {})[2])or 0) + (((fx['NanoParticles'] or {})[2])or 0) + (((fx['StaticParticles'] or {})[2])or 0) gl.Text("-LUPS Stats-", xpos, ypos+112, size, format) gl.Text("particles: " .. totalParticles, xpos, ypos+90, size, format) gl.Text("layers: " .. fxlayers, xpos, ypos+70, size, format) gl.Text("effects: " .. fxcount, xpos, ypos+50, size, format) gl.Color(1,1,1,1) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Geometry Management -- local function UpdateGeometry() -- use the fractions if available xpos = (xposf and (xposf * vsx)) or xpos ypos = (yposf and (yposf * vsy)) or ypos size = (sizef and (sizef * vsy)) or size -- negative values reference the right/top edges xpos = (xpos < 0) and (vsx + xpos) or xpos ypos = (ypos < 0) and (vsy + ypos) or ypos end UpdateGeometry() function widget:ViewResize(viewSizeX, viewSizeY) vsx = viewSizeX vsy = viewSizeY UpdateGeometry() end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Configuration routines -- local function StoreGeoPair(tbl, fName, fValue, pName, pValue) if (fValue) then tbl[pName] = nil tbl[fName] = fValue else tbl[pName] = pValue tbl[fName] = nil end return end function widget:GetConfigData() local tbl = { color = color, format = format, font = font } StoreGeoPair(tbl, 'xposf', xposf, 'xpos', xpos) StoreGeoPair(tbl, 'yposf', yposf, 'ypos', ypos) StoreGeoPair(tbl, 'sizef', sizef, 'size', size) return tbl end -------------------------------------------------------------------------------- -- returns a fraction,pixel pair local function LoadGeoPair(tbl, fName, pName, oldPixelValue) if (tbl[fName]) then return tbl[fName], 1 elseif (tbl[pName]) then return nil, tbl[pName] else return nil, oldPixelValue end end function widget:SetConfigData(data) color = data.color or color format = data.format or format font = data.font or font if (font) then fh = fontHandler.UseFont(font) end xposf, xpos = LoadGeoPair(data, 'xposf', 'xpos', xpos) yposf, ypos = LoadGeoPair(data, 'yposf', 'ypos', ypos) sizef, size = LoadGeoPair(data, 'sizef', 'size', size) UpdateGeometry() return end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
128technology/protobuf_dissector
modules/ast/factory.lua
1
5483
---------------------------------------- -- -- Copyright (c) 2015, 128 Technology, Inc. -- -- author: Hadriel Kaplan <hadriel@128technology.com> -- -- This code is licensed under the MIT license. -- -- Version: 1.0 -- ------------------------------------------ -- prevent wireshark loading this file as a plugin if not _G['protbuf_dissector'] then return end local Settings = require "settings" local dprint = Settings.dprint local dprint2 = Settings.dprint2 local dassert = Settings.dassert local derror = Settings.derror local Syntax = require "syntax" local AstFactory = {} -- we're going to "register" statement classes in this table, so we can -- dispatch their constructors easily when building the AST AstFactory.dispatch_statement_tbl = {} AstFactory.dispatch_body_tbl = {} -- registers classes in classname index, and their ttype in dispatch_ttype_tbl -- if the ttype is a ptype, then register that instead function AstFactory:registerClass(ttype, classname, class, inBody) dassert(ttype, "No ttype given for classname:", classname) if ttype then dassert(Syntax:isTokenTtype(ttype) or Syntax:isTokenPtype(ttype), "Programming error: ttype is neither ttype nor ptype:", ttype) dassert(not self.dispatch_statement_tbl[ttype], "Programming error: Class ttype", ttype, "already registered for statements") self.dispatch_statement_tbl[ttype] = class if inBody then dassert(not self.dispatch_body_tbl[ttype], "Programming error: Class ttype", ttype, "already registered for bodies") self.dispatch_body_tbl[ttype] = class end end end function AstFactory:buildStatement(namespace, statement_table) local token = statement_table[1] dassert(token and token.ttype, "Statement table missing token or token.ttype") local ttype, ptype = token.ttype, token.ptype if self.dispatch_statement_tbl[ttype] then return self.dispatch_statement_tbl[ttype].new(namespace, statement_table) elseif self.dispatch_statement_tbl[ptype] then return self.dispatch_statement_tbl[ptype].new(namespace, statement_table) else derror(token, "\nStatement token type is not supported:", ttype, ", in table:", statement_table) end end function AstFactory:dispatchBodyStatement(namespace, statement_table) local token = statement_table[1] dassert(token and token.ttype, "Statement table missing token or token.ttype:", statement_table) local ttype, ptype = token.ttype, token.ptype if self.dispatch_body_tbl[ttype] then return self.dispatch_body_tbl[ttype].new(namespace, statement_table) elseif self.dispatch_body_tbl[ptype] then return self.dispatch_body_tbl[ptype].new(namespace, statement_table) else if token:canBeIdentifier() then derror(token, "\nStatement type word '", token.value, "' is not supported inside message/group bodies") else derror(token, "\nThe token type is not supported inside message/group bodies:", ttype, "\n\nThe statement token table:", statement_table) end end end -------------------------------------------------------------------------------- -- helper functions -- gets the rest of the values from the given subtable, starting at the given -- index position or 1 if not given; converts everything to a string function AstFactory.serializeRemaining(st, idx) idx = idx or 1 dassert(#st >= idx, "Programming error: invalid subtable or index") local value = "" while idx <= #st do value = value .. st[idx].value idx = idx + 1 end return value end -- given a statement table array and one or more ttypes, verify -- the tokens in the array match the given ttypes, in order -- a ttype of boolean false is skipped in the array function AstFactory.verifyTokenTTypes(name, st, ...) local ttypes = { ... } if #ttypes > #st then return false, name .. " statement is missing tokens: need " .. tostring(#ttypes) .. " tokens, but got " .. tostring(#st) end for idx, ttype in ipairs(ttypes) do if ttype then if ttype == "IDENTIFIER" then -- for identifiers, we verify it could be one if not st[idx]:canBeIdentifier() then return false, st[idx], name .. " statement expected an identifer for token #" .. tostring(idx) .. " but got value '" .. tostring(st[idx].value) .. "' of type " .. st[idx].ttype end elseif ttype == "NUMBER" then if st[idx].ptype ~= "NUMBER" then return false, st[idx], name .. " statement expected a number for token #" .. tostring(idx) .. " but got value '" .. tostring(st[idx].value) .. "' of type " .. st[idx].ttype end elseif st[idx].ttype ~= ttype then return false, st[idx], name .. " statement token #" .. tostring(idx) .. " was expected to be of type " .. ttype .. " but was of type " .. st[idx].ttype .. " with value '" .. tostring(st[idx].value) .. "'" end end end return true end return AstFactory
mit
thedraked/darkstar
scripts/zones/Norg/npcs/Achika.lua
14
1299
----------------------------------- -- Area: Norg -- NPC: Achika -- Type: Tenshodo Merchant -- @pos 1.300 0.000 19.259 252 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/keyitems"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then if (player:sendGuild(60421,9,23,7)) then player:showText(npc, ACHIKA_SHOP_DIALOG); end else -- player:startEvent(0x0096); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
mtroyka/Zero-K
LuaUI/Widgets/gui_darkening.lua
18
3324
-- $Id: gui_darkening.lua 3171 2008-11-06 09:06:29Z det $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Darkening", desc = "Adds a new '/luaui darkening %float%' (and '/luaui inc_dark' & '/luaui dec_dark') command.", author = "jK", date = "Nov 22, 2007", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? }; end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local mapChanged = false; local darkeningMap; local darkening = 0; local LUA_BRIGHT_MAP_FILE = "LuaUI/Config/darkeningMap.lua"; local vsx, vsy; function widget:ViewResize(viewSizeX, viewSizeY) vsx = viewSizeX; vsy = viewSizeY; end widget:ViewResize(widgetHandler:GetViewSizes()); -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function UpdateCallins() if (darkening>0) then widgetHandler:UpdateCallIn('DrawWorldPreUnit'); else widgetHandler:RemoveCallIn('DrawWorldPreUnit'); end end function SetDarkening(_,_,words) mapChanged = true; darkening = tonumber(words[1]); darkeningMap[Game.mapName] = darkening; UpdateCallins(); end function IncDarkening() mapChanged = true; darkening = darkening + 0.1; darkeningMap[Game.mapName] = darkening; UpdateCallins(); end function DecDarkening() mapChanged = true; darkening = darkening - 0.1; darkeningMap[Game.mapName] = darkening; UpdateCallins(); end function fileexists( file ) local f = io.open( file, "r" ); if f then io.close( f ); return true; else return false; end end function widget:Initialize() if fileexists(LUA_BRIGHT_MAP_FILE) then darkeningMap = include("Config/darkeningMap.lua"); end if (brightnessMap) then darkening = darkeningMap[Game.mapName]; else darkeningMap = {}; end UpdateCallins(); local help = " [0..1]: sets map darkening"; widgetHandler:AddAction("darkening", SetDarkening, nil, "t"); widgetHandler:AddAction("inc_dark", IncDarkening, nil, "t"); widgetHandler:AddAction("dec_dark", DecDarkening, nil, "t"); end function widget:Shutdown() if mapChanged then include("savetable.lua"); table.save(darkeningMap, LUA_BRIGHT_MAP_FILE); end widgetHandler:RemoveAction("darkening"); widgetHandler:RemoveAction("inc_dark"); widgetHandler:RemoveAction("dec_dark"); end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:DrawWorldPreUnit() local drawMode = Spring.GetMapDrawMode() if (drawMode=="height") or (drawMode=="path") then return end gl.MatrixMode(GL.PROJECTION); gl.PushMatrix(); gl.LoadIdentity() gl.MatrixMode(GL.MODELVIEW); gl.PushMatrix(); gl.LoadIdentity() gl.Color(0,0,0,darkening); gl.Rect(-1,1,1,-1); gl.MatrixMode(GL.PROJECTION); gl.PopMatrix() gl.MatrixMode(GL.MODELVIEW); gl.PopMatrix() end
gpl-2.0
josh-perry/VNEngine
conf.lua
1
4580
-- function love.conf(t) -- t.title = "Empty project" -- The title of the window the game is in (string) -- t.author = "Josh Perry" -- The author of the game (string) -- t.identity = nil -- The name of the save directory (string) -- t.version = "0.8.0" -- The L�VE version this game was made for (string) -- t.console = false -- Attach a console (boolean, Windows only) -- t.release = false -- Enable release mode (boolean) -- t.screen.width = 1280 -- The window width (number) -- t.screen.height = 720 -- The window height (number) -- t.screen.fullscreen = false -- Enable fullscreen (boolean) -- t.screen.vsync = false -- Enable vertical sync (boolean) -- t.screen.fsaa = 2 -- The number of FSAA-buffers (number) -- t.modules.joystick = true -- Enable the joystick module (boolean) -- t.modules.audio = true -- Enable the audio module (boolean) -- t.modules.keyboard = true -- Enable the keyboard module (boolean) -- t.modules.event = true -- Enable the event module (boolean) -- t.modules.image = true -- Enable the image module (boolean) -- t.modules.graphics = true -- Enable the graphics module (boolean) -- t.modules.timer = true -- Enable the timer module (boolean) -- t.modules.mouse = true -- Enable the mouse module (boolean) -- t.modules.sound = true -- Enable the sound module (boolean) -- t.modules.physics = true -- Enable the physics module (boolean) -- end function love.conf(t) t.identity = nil -- The name of the save directory (string) t.version = "0.10.0" -- The LÖVE version this game was made for (string) t.console = true -- Attach a console (boolean, Windows only) t.window.title = "Empty project" -- The window title (string) t.window.icon = nil -- Filepath to an image to use as the window's icon (string) t.window.width = 1280 -- The window width (number) t.window.height = 720 -- The window height (number) t.window.borderless = false -- Remove all border visuals from the window (boolean) t.window.resizable = false -- Let the window be user-resizable (boolean) t.window.minwidth = 1 -- Minimum window width if the window is resizable (number) t.window.minheight = 1 -- Minimum window height if the window is resizable (number) t.window.fullscreen = false -- Enable fullscreen (boolean) t.window.fullscreentype = "desktop" -- Standard fullscreen or desktop fullscreen mode (string) t.window.vsync = true -- Enable vertical sync (boolean) t.window.fsaa = 0 -- The number of samples to use with multi-sampled antialiasing (number) t.window.display = 1 -- Index of the monitor to show the window in (number) t.window.highdpi = false -- Enable high-dpi mode for the window on a Retina display (boolean) t.window.srgb = false -- Enable sRGB gamma correction when drawing to the screen (boolean) t.window.x = nil -- The x-coordinate of the window's position in the specified display (number) t.window.y = nil -- The y-coordinate of the window's position in the specified display (number) t.modules.audio = true -- Enable the audio module (boolean) t.modules.event = true -- Enable the event module (boolean) t.modules.graphics = true -- Enable the graphics module (boolean) t.modules.image = true -- Enable the image module (boolean) t.modules.joystick = true -- Enable the joystick module (boolean) t.modules.keyboard = true -- Enable the keyboard module (boolean) t.modules.math = true -- Enable the math module (boolean) t.modules.mouse = true -- Enable the mouse module (boolean) t.modules.physics = true -- Enable the physics module (boolean) t.modules.sound = true -- Enable the sound module (boolean) t.modules.system = true -- Enable the system module (boolean) t.modules.timer = true -- Enable the timer module (boolean), Disabling it will result 0 delta time in love.update t.modules.window = true -- Enable the window module (boolean) t.modules.thread = true -- Enable the thread module (boolean) end
mit
NPLPackages/main
script/ide/Debugger/HTTPDebugger.lua
1
5126
--[[ Title: HTTP debugger Author(s): LiXizhi, inspired by RemDebug 1.0 Date: 2016/4/13 Desc: HTTP debugger is used by NPL extensions for visual studio code and the NPL code wiki for debugging purposes. For more information, please see IPCDebugger # How to start debugger One can either start programmatically, or simply start NPL code wiki and goto menu tools::debugger Use Lib: ------------------------------------------------------- NPL.load("(gl)script/ide/Debugger/HTTPDebugger.lua"); local HTTPDebugger = commonlib.gettable("commonlib.Debugger.HTTPDebugger") commonlib.Debugger.HTTPDebugger.Start(); ------------------------------------------------------ ]] NPL.load("(gl)script/ide/Debugger/IPCDebugger.lua"); NPL.load("(gl)script/ide/STL.lua"); local HTTPDebugger = commonlib.inherit(commonlib.gettable("IPCDebugger"), commonlib.gettable("commonlib.Debugger.HTTPDebugger")); -- whether to dump messages to log.txt local debug_debugger = true; -- call this at any time to start debugger at default ip:port -- @param ip: if nil, it is "localhost" -- @param port: if nil, 8099, same as NPL admin web server function HTTPDebugger.Start(ip, port) port = port or 8099 NPL.load("(gl)script/apps/WebServer/WebServer.lua"); WebServer:Start("script/apps/WebServer/admin", ip or "localhost", port); ParaGlobal.ShellExecute("open", format("http://localhost:%s/debugger", tostring(port)), "", "", 1); end -- start the debug engine. It will begin waiting for incoming debug request from the debugger UI. -- Note: start the debug engine only start a 100ms timer that polls the "debugger IPC queue". -- So there is no performance impact to the runtime until we explicitly enable debug hook of the NPL runtime. -- @param input_queue_name: the input IPC queue name, default to "NPLDebug" function HTTPDebugger.StartDebugEngine(input_queue_name) end -- output message queue: these messages are polled by the debugger IDE at regular interval. function HTTPDebugger.GetOutputMsgList() HTTPDebugger.output_queue = HTTPDebugger.output_queue or commonlib.List:new(); return HTTPDebugger.output_queue; end -- send a debug event message to the remote debug engine via the output_queue function HTTPDebugger.Write(msg) if(debug_debugger) then LOG.std(nil, "info", "debugger_write", msg); end local output_queue = HTTPDebugger.GetOutputMsgList(); output_queue:add({ method = "debug", type = msg.type, param1 = msg.param1, param2 = msg.param2, filename = msg.filename, code = msg.code, }); end -- read the next debug message. -- @return the message table or nil function HTTPDebugger.WaitForDebugEvent() local thread = __rts__; local debug_msg; while (not debug_msg) do local nSize = thread:GetCurrentQueueSize(); local processed; for i=0, nSize-1 do local msg = thread:PeekMessage(i, {filename=true}); if(msg.filename == "script/ide/Debugger/HTTPDebugger.lua") then debug_msg = i; break; elseif(msg.filename == "script/apps/WebServer/npl_http.lua") then -- process all http message, since our debugger UI is written in HTTP. thread:PopMessageAt(i, {process = true}); processed = true; break; end end if(not processed and debug_msg == nil) then local attr = ParaEngine.GetAttributeObject(); if(attr:GetField("HasClosingRequest", false) == true) then -- if there is a closing request, send a fake detach message. LOG.std(nil, "info", "HTTPDebugger", "closing request is seen, we will detach prematurely"); local out_msg = {filename="exit"}; HTTPDebugger.Write(out_msg); return out_msg; end if(thread:GetCurrentQueueSize() == nSize) then thread:WaitForMessage(nSize); end end end if(debug_msg) then local msg = thread:PopMessageAt(debug_msg, {filename=true, msg=true}); local out_msg = msg.msg; if(debug_debugger) then LOG.std(nil, "info", "SyncDebugMsg", out_msg); end return out_msg end end -- async break request function HTTPDebugger.BreakAsync(type, param1, param2, msg, from) HTTPDebugger.GetOutputMsgList():clear(); HTTPDebugger.pause(); end -- async attach a remote IPC debugger to this NPL state and break it function HTTPDebugger.AttachAsync(type, param1, param2, msg, from) HTTPDebugger.GetOutputMsgList():clear(); -- attach debug hook HTTPDebugger.Attach(); end function HTTPDebugger.DetachAsync() HTTPDebugger.Detach() end -- this is only called when program is not paused. local function activate() HTTPDebugger.SetDebugger(HTTPDebugger); LOG.std(nil, "info", "debugger", msg); local command = msg.filename; if(command == "pause") then HTTPDebugger.BreakAsync(); elseif(command == "attach") then HTTPDebugger.AttachAsync(); elseif(command == "setb") then HTTPDebugger.SetBreakpointAsync(msg.code.filename, msg.code.line); elseif(command == "delb") then HTTPDebugger.RemoveBreakpointAsync(msg.code.filename, msg.code.line); elseif(command == "listb") then HTTPDebugger.ListBreakpoints(); elseif(command == "exec") then -- TODO: evaluate when still running elseif(command == "Detach") then HTTPDebugger.DetachAsync() end end NPL.this(activate)
gpl-2.0
SnabbCo/snabbswitch
lib/luajit/testsuite/test/misc/tonumber_scan.lua
6
11397
local ffi = require("ffi") local bit = require("bit") ffi.cdef[[ double strtod(const char *, char **); ]] local t = { -- errors false, "", false, " ", false, "+", false, "z", false, ".", false, ".z", false, "0.z", false, ".0z", false, "0xz", false, "0x.z", false, "0x0.z", false, "0x.0z", false, ".e5", false, ".p4", false, "1.p4", false, "1.p+4", false, "0x1.e+4", false, "infi", false, "+ 1", false, "- 9", -- misc 0x3ff0000000000000ULL, " \t\n\v\f\r 1", -- inf/nan 0x7ff0000000000000ULL, "iNF", 0xfff0000000000000ULL, "-Inf", 0x7ff0000000000000ULL, "+iNfInItY", 0xfff0000000000000ULL, "-INFINITY", 0xfff8000000000000ULL, "naN", 0xfff8000000000000ULL, "+NaN", 0xfff8000000000000ULL, "-nAn", -- smallest/largest numbers 0x0000000000000000ULL, "0e1000", 0x0000000000000000ULL, "0e-1000", 0x0000000000000000ULL, "0x0p2000", 0x0000000000000000ULL, "0x0p-2000", 0x7ff0000000000000ULL, "1e1000", 0x0000000000000000ULL, "1e-1000", 0xfff0000000000000ULL, "-1e1000", -- wrong for DUALNUM: 0x8000000000000000ULL, "-1e-1000", 0x7ff0000000000000ULL, "0x1p2000", 0x0000000000000000ULL, "0x1p-2000", 0xfff0000000000000ULL, "-0x1p2000", -- wrong for DUALNUM: 0x8000000000000000ULL, "-0x1p-2000", 0x0010000000000000ULL, "2.2250738585072014e-308", 0x7fefffffffffffffULL, "1.7976931348623158e+308", 0x8000b8157268fdafULL, "-1e-309", 0x000ac941b426dd3bULL, "1.5e-308", 0x000ac941b426dd3bULL, "0x0.ac941b426dd3b7p-1022", 0x0000000000000001ULL, "4.9406564584124654e-324", 0x000f9c7573d7fe52ULL, "2.171e-308", 0x241d21ecf36d4a22ULL, "1.0020284025808569e-134", 0x0000000000000001ULL, "0x1p-1074", 0x0000000000000000ULL, "0x1p-1075", 0x0000000000000000ULL, "0x1p-1076", 0x0000000000000000ULL, "0x0.ffffffffffffffffffffffffffp-1075", 0x0000000000000000ULL, "0x1.00000000000000000000000000p-1075", 0x0000000000000001ULL, "0x1.00000000000000000000000001p-1075", 0x7fe0000000000000ULL, "0x1p1023", 0x7ff0000000000000ULL, "0x1p1024", 0x7ff0000000000000ULL, "0x1p1025", 0x7ff0000000000000ULL, "0x3p1023", 0x7ff0000000000000ULL, "0x3.ffffffffffffecp1023", 0xfff0000000000000ULL, "-0xf7dcba98765432p969", 0x7fefffffffffffffULL, "0x1.fffffffffffff0000000000000p1023", 0x7fefffffffffffffULL, "0x1.fffffffffffff0000000000001p1023", 0x7fefffffffffffffULL, "0x1.fffffffffffff7ffffffffffffp1023", 0x7ff0000000000000ULL, "0x1.fffffffffffff8000000000000p1023", 0x7fefffffffffffffULL, "179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0", 0x7fefffffffffffffULL, "179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791.999", 0x7ff0000000000000ULL, "179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792.0", 0x3ff0000000000000ULL, "0x100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000p-1028", 0x1214e2995454ee0bULL, "0."..string.rep("0", 220).."1"..string.rep("4", 800), -- http://www.exploringbinary.com/15-digit-quick-and-dirty-conversions-dont-round-trip/ 0x04409cf3929ffbc3ULL, "3.409452297963e-288", 0x7fe02b4782a6c378ULL, "9.08344e+307", 0x6e05e258a3929ee5ULL, "9.88819e+221", -- http://www.exploringbinary.com/incorrectly-rounded-conversions-in-gcc-and-glibc/ 0x3fe0000000000002ULL, "0.500000000000000166533453693773481063544750213623046875", 0x42c0000000000002ULL, "3.518437208883201171875e13", 0x404f44abd5aa7ca4ULL, "62.5364939768271845828", 0x3e0bd5cbaef0fd0cULL, "8.10109172351e-10", 0x3ff8000000000000ULL, "1.50000000000000011102230246251565404236316680908203125", 0x433fffffffffffffULL, "9007199254740991.4999999999999999999999999999999995", 0x7ecd2e77eb6e3fadULL, "6.253649397682718e+302", 0x7ecd2e77eb6e3fadULL, "6.2536493976827180e+302", -- http://www.exploringbinary.com/incorrectly-rounded-conversions-in-visual-c-plus-plus/ 0x43405e6cec57761aULL, "9214843084008499", 0x3fe0000000000002ULL, "0.500000000000000166533453693773481063544750213623046875", 0x44997a3c7271b021ULL, "30078505129381147446200", 0x4458180d5bad2e3eULL, "1777820000000000000001", 0x3fe0000000000002ULL, "0.500000000000000166547006220929549868969843373633921146392822265625", 0x3fe0000000000002ULL, "0.50000000000000016656055874808561867439493653364479541778564453125", 0x3fd92bb352c4623aULL, "0.3932922657273", -- http://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/ 0x0010000000000000ULL, "2.2250738585072012e-308", -- http://www.exploringbinary.com/incorrectly-rounded-subnormal-conversions-in-java/ 0x0000000008000000ULL, "6.631236871469758276785396630275967243399099947355303144249971758736286630139265439618068200788048744105960420552601852889715006376325666595539603330361800519107591783233358492337208057849499360899425128640718856616503093444922854759159988160304439909868291973931426625698663157749836252274523485312442358651207051292453083278116143932569727918709786004497872322193856150225415211997283078496319412124640111777216148110752815101775295719811974338451936095907419622417538473679495148632480391435931767981122396703443803335529756003353209830071832230689201383015598792184172909927924176339315507402234836120730914783168400715462440053817592702766213559042115986763819482654128770595766806872783349146967171293949598850675682115696218943412532098591327667236328125e-316", 0x0000000000010000ULL, "3.237883913302901289588352412501532174863037669423108059901297049552301970670676565786835742587799557860615776559838283435514391084153169252689190564396459577394618038928365305143463955100356696665629202017331344031730044369360205258345803431471660032699580731300954848363975548690010751530018881758184174569652173110473696022749934638425380623369774736560008997404060967498028389191878963968575439222206416981462690113342524002724385941651051293552601421155333430225237291523843322331326138431477823591142408800030775170625915670728657003151953664260769822494937951845801530895238439819708403389937873241463484205608000027270531106827387907791444918534771598750162812548862768493201518991668028251730299953143924168545708663913273994694463908672332763671875e-319", 0x0000800000000100ULL, "6.953355807847677105972805215521891690222119817145950754416205607980030131549636688806115726399441880065386399864028691275539539414652831584795668560082999889551357784961446896042113198284213107935110217162654939802416034676213829409720583759540476786936413816541621287843248433202369209916612249676005573022703244799714622116542188837770376022371172079559125853382801396219552418839469770514904192657627060319372847562301074140442660237844114174497210955449896389180395827191602886654488182452409583981389442783377001505462015745017848754574668342161759496661766020028752888783387074850773192997102997936619876226688096314989645766000479009083731736585750335262099860150896718774401964796827166283225641992040747894382698751809812609536720628966577351093292236328125e-310", 0x0000000000010800ULL, "3.339068557571188581835713701280943911923401916998521771655656997328440314559615318168849149074662609099998113009465566426808170378434065722991659642619467706034884424989741080790766778456332168200464651593995817371782125010668346652995912233993254584461125868481633343674905074271064409763090708017856584019776878812425312008812326260363035474811532236853359905334625575404216060622858633280744301892470300555678734689978476870369853549413277156622170245846166991655321535529623870646888786637528995592800436177901746286272273374471701452991433047257863864601424252024791567368195056077320885329384322332391564645264143400798619665040608077549162173963649264049738362290606875883456826586710961041737908872035803481241600376705491726170293986797332763671875e-319", -- EGLIBC 2.16 tests 0x4028b0a3d70a3d71ULL, "12.345", 0x441ac4da03bc47e4ULL, "12.345e19", 0xc197d78400000000ULL, "-.1e+9", 0x3fc0000000000000ULL, ".125", 0x4415af1d78b58c40ULL, "1e20", 0x0000000000000000ULL, "0e-19", 0x3051144f2d9a718bULL, "5.9e-76", 0x4024000000000000ULL, "0x1.4p+3", 0x4024000000000000ULL, "0xAp0", 0x4024000000000000ULL, "0x0Ap0", 0x4024000000000000ULL, "0x0A", 0x4064000000000000ULL, "0xA0", 0x4064000000000000ULL, "0x0.A0p8", 0x4064000000000000ULL, "0x0.50p9", 0x4064000000000000ULL, "0x0.28p10", 0x4064000000000000ULL, "0x0.14p11", 0x4064000000000000ULL, "0x0.0A0p12", 0x4064000000000000ULL, "0x0.050p13", 0x4064000000000000ULL, "0x0.028p14", 0x4064000000000000ULL, "0x0.014p15", 0x4064000000000000ULL, "0x00.00A0p16", 0x4064000000000000ULL, "0x00.0050p17", 0x4064000000000000ULL, "0x00.0028p18", 0x4064000000000000ULL, "0x00.0014p19", 0x0008000000000000ULL, "0x1p-1023", 0x0008000000000000ULL, "0x0.8p-1022", 0x3ff0000140000000ULL, "0x80000Ap-23", 0x0000000000000000ULL, "1e-324", 0x4370000000000000ULL, "0x100000000000008p0", 0x4370000000000000ULL, "0x100000000000008.p0", 0x4370000000000000ULL, "0x100000000000008.00p0", 0x43f0000000000000ULL, "0x10000000000000800p0", 0x43f0000000000001ULL, "0x10000000000000801p0", -- Fuzzing 0x699783fbf2d24ea5ULL, "449999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", 0x43f158e460913d00ULL, "2e19", } local function tohex64(x) return "0x"..bit.tohex(tonumber(x/2LL^32))..bit.tohex(tonumber(x%2LL^32)).."ULL" end local conv = tonumber if arg and arg[1] == "strtod" then local e = ffi.new("char *[1]") function conv(s) local d = ffi.C.strtod(s, e) return (e[0][0] == 0 and #s ~= 0) and d or nil end end local u = ffi.new("union { double d; uint64_t x; }") for i=1,#t,2 do local y, s = t[i], t[i+1] local d = conv(s) local ok if d == nil then ok = (y == false) else u.d = d ok = (y == u.x) end if not ok then io.write('FAIL: "', s, '"\n GOT: ', d and tohex64(u.x) or "nil", " OK: ", y and tohex64(y) or "nil", "\n\n") -- print(" "..tohex64(u.x)..", \""..s.."\",") end end
apache-2.0
thedraked/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Rohn_Ehlbalna.lua
14
1064
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Rohn Ehlbalna -- Type: Standard NPC -- @zone 94 -- @pos -43.473 -4.5 46.496 -- -- 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(0x01b8); 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
mtroyka/Zero-K
gamedata/explosions_post.lua
17
1247
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Load CA's effects from ./effects and not ./gamedata/explosions -- local luaFiles = VFS.DirList('effects', '*.lua', '*.tdf') --couldn't be arsed to convert to lua since there is no real benefit for CEG's -Zement/DOT for _, filename in ipairs(luaFiles) do local edEnv = {} edEnv._G = edEnv edEnv.Shared = Shared edEnv.GetFilename = function() return filename end setmetatable(edEnv, { __index = system }) local success, eds = pcall(VFS.Include, filename, edEnv) if (not success) then Spring.Log("explosions_post.lua", "error", 'Error parsing ' .. filename .. ': ' .. eds) elseif (eds == nil) then Spring.Log("explosions_post.lua", "error", 'Missing return table from: ' .. filename) else for edName, ed in pairs(eds) do if ((type(edName) == 'string') and (type(ed) == 'table')) then ed.filename = filename ExplosionDefs[edName] = ed end end end end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
thedraked/darkstar
scripts/zones/Yhoator_Jungle/npcs/qm3.lua
14
1845
----------------------------------- -- Area: Davoi -- NPC: ??? (qm3) -- Involved in Quest: True will -- @pos 203 0.1 82 124 ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Yhoator_Jungle/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(OUTLANDS,TRUE_WILL) == QUEST_ACCEPTED and player:hasKeyItem(OLD_TRICK_BOX) == false) then if (player:getVar("trueWillKilledNM") >= 1) then if (GetMobAction(17285544) == 0 and GetMobAction(17285545) == 0 and GetMobAction(17285546) == 0) then player:addKeyItem(OLD_TRICK_BOX); player:messageSpecial(KEYITEM_OBTAINED,OLD_TRICK_BOX); player:setVar("trueWillKilledNM",0); end else SpawnMob(17285544):updateClaim(player); -- Kappa Akuso SpawnMob(17285545):updateClaim(player); -- Kappa Bonze SpawnMob(17285546):updateClaim(player); -- Kappa Biwa end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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
thedraked/darkstar
scripts/globals/weaponskills/cataclysm.lua
23
1521
----------------------------------- -- Cataclysm -- Skill level: 290 -- Delivers light elemental damage. Additional effect: Flash. Chance of effect varies with TP. -- Generates a significant amount of Enmity. -- Does not stack with Sneak Attack -- Aligned with Aqua Gorget. -- Aligned with Aqua Belt. -- Properties: -- Element: Light -- Skillchain Properties:Induration Reverberation -- Modifiers: STR:30% MND:30% -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; params.ele = ELE_DARK; params.skill = SKILL_STF; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 2.75; params.ftp200 = 4; params.ftp300 = 5; params.str_wsc = 0.3; params.int_wsc = 0.3; params.mnd_wsc = 0.0; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, tp, primary, action, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
thedraked/darkstar
scripts/zones/Metalworks/npcs/Lorena.lua
8
2540
----------------------------------- -- Area: Metalworks -- NPC: Lorena -- Type: Blacksmithing Guildworker's Union Representative -- @zone 237 -- @pos -104.990 1 30.995 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/zones/Metalworks/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/crafting"); local keyitems = { [0] = { id = METAL_PURIFICATION, rank = 3, cost = 40000 }, [1] = { id = METAL_ENSORCELLMENT, rank = 3, cost = 40000 }, [2] = { id = CHAINWORK, rank = 3, cost = 10000 }, [3] = { id = SHEETING, rank = 3, cost = 10000 }, [4] = { id = WAY_OF_THE_BLACKSMITH, rank = 9, cost = 20000 } }; local items = { [2] = { id = 15445, rank = 3, cost = 10000 }, [3] = { id = 14831, rank = 5, cost = 70000 }, [4] = { id = 14393, rank = 7, cost = 100000 }, [5] = { id = 153, rank = 9, cost = 150000 }, [6] = { id = 334, rank = 9, cost = 200000 }, [7] = { id = 15820, rank = 6, cost = 80000 }, [8] = { id = 3661, rank = 7, cost = 50000 }, [9] = { id = 3324, rank = 9, cost = 15000 } }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 0x321, 2); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) unionRepresentativeTrigger(player, 2, 0x320, "guild_smithing", keyitems); 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 == 0x320) then unionRepresentativeTriggerFinish(player, option, target, 2, "guild_smithing", keyitems, items); elseif (csid == 0x321) then player:messageSpecial(GP_OBTAINED, option); end end;
gpl-3.0
peteches/configs
awesome/themes/zenburn/theme.lua
6
5400
------------------------------- -- "Zenburn" awesome theme -- -- By Adrian C. (anrxc) -- ------------------------------- -- Alternative icon sets and widget icons: -- * http://awesome.naquadah.org/wiki/Nice_Icons -- {{{ Main theme = {} theme.wallpaper_cmd = { "awsetbg /usr/share/awesome/themes/zenburn/zenburn-background.png" } -- }}} -- {{{ Styles theme.font = "sans 8" -- {{{ Colors theme.fg_normal = "#DCDCCC" theme.fg_focus = "#F0DFAF" theme.fg_urgent = "#CC9393" theme.bg_normal = "#3F3F3F" theme.bg_focus = "#1E2320" theme.bg_urgent = "#3F3F3F" -- }}} -- {{{ Borders theme.border_width = "2" theme.border_normal = "#3F3F3F" theme.border_focus = "#6F6F6F" theme.border_marked = "#CC9393" -- }}} -- {{{ Titlebars theme.titlebar_bg_focus = "#3F3F3F" theme.titlebar_bg_normal = "#3F3F3F" -- }}} -- There are other variable sets -- overriding the default one when -- defined, the sets are: -- [taglist|tasklist]_[bg|fg]_[focus|urgent] -- titlebar_[normal|focus] -- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color] -- Example: --theme.taglist_bg_focus = "#CC9393" -- }}} -- {{{ Widgets -- You can add as many variables as -- you wish and access them by using -- beautiful.variable in your rc.lua --theme.fg_widget = "#AECF96" --theme.fg_center_widget = "#88A175" --theme.fg_end_widget = "#FF5656" --theme.bg_widget = "#494B4F" --theme.border_widget = "#3F3F3F" -- }}} -- {{{ Mouse finder theme.mouse_finder_color = "#CC9393" -- mouse_finder_[timeout|animate_timeout|radius|factor] -- }}} -- {{{ Menu -- Variables set for theming the menu: -- menu_[bg|fg]_[normal|focus] -- menu_[border_color|border_width] theme.menu_height = "15" theme.menu_width = "100" -- }}} -- {{{ Icons -- {{{ Taglist theme.taglist_squares_sel = "/usr/share/awesome/themes/zenburn/taglist/squarefz.png" theme.taglist_squares_unsel = "/usr/share/awesome/themes/zenburn/taglist/squarez.png" --theme.taglist_squares_resize = "false" -- }}} -- {{{ Misc theme.awesome_icon = "/usr/share/awesome/themes/zenburn/awesome-icon.png" theme.menu_submenu_icon = "/usr/share/awesome/themes/default/submenu.png" theme.tasklist_floating_icon = "/usr/share/awesome/themes/default/tasklist/floatingw.png" -- }}} -- {{{ Layout theme.layout_tile = "/usr/share/awesome/themes/zenburn/layouts/tile.png" theme.layout_tileleft = "/usr/share/awesome/themes/zenburn/layouts/tileleft.png" theme.layout_tilebottom = "/usr/share/awesome/themes/zenburn/layouts/tilebottom.png" theme.layout_tiletop = "/usr/share/awesome/themes/zenburn/layouts/tiletop.png" theme.layout_fairv = "/usr/share/awesome/themes/zenburn/layouts/fairv.png" theme.layout_fairh = "/usr/share/awesome/themes/zenburn/layouts/fairh.png" theme.layout_spiral = "/usr/share/awesome/themes/zenburn/layouts/spiral.png" theme.layout_dwindle = "/usr/share/awesome/themes/zenburn/layouts/dwindle.png" theme.layout_max = "/usr/share/awesome/themes/zenburn/layouts/max.png" theme.layout_fullscreen = "/usr/share/awesome/themes/zenburn/layouts/fullscreen.png" theme.layout_magnifier = "/usr/share/awesome/themes/zenburn/layouts/magnifier.png" theme.layout_floating = "/usr/share/awesome/themes/zenburn/layouts/floating.png" -- }}} -- {{{ Titlebar theme.titlebar_close_button_focus = "/usr/share/awesome/themes/zenburn/titlebar/close_focus.png" theme.titlebar_close_button_normal = "/usr/share/awesome/themes/zenburn/titlebar/close_normal.png" theme.titlebar_ontop_button_focus_active = "/usr/share/awesome/themes/zenburn/titlebar/ontop_focus_active.png" theme.titlebar_ontop_button_normal_active = "/usr/share/awesome/themes/zenburn/titlebar/ontop_normal_active.png" theme.titlebar_ontop_button_focus_inactive = "/usr/share/awesome/themes/zenburn/titlebar/ontop_focus_inactive.png" theme.titlebar_ontop_button_normal_inactive = "/usr/share/awesome/themes/zenburn/titlebar/ontop_normal_inactive.png" theme.titlebar_sticky_button_focus_active = "/usr/share/awesome/themes/zenburn/titlebar/sticky_focus_active.png" theme.titlebar_sticky_button_normal_active = "/usr/share/awesome/themes/zenburn/titlebar/sticky_normal_active.png" theme.titlebar_sticky_button_focus_inactive = "/usr/share/awesome/themes/zenburn/titlebar/sticky_focus_inactive.png" theme.titlebar_sticky_button_normal_inactive = "/usr/share/awesome/themes/zenburn/titlebar/sticky_normal_inactive.png" theme.titlebar_floating_button_focus_active = "/usr/share/awesome/themes/zenburn/titlebar/floating_focus_active.png" theme.titlebar_floating_button_normal_active = "/usr/share/awesome/themes/zenburn/titlebar/floating_normal_active.png" theme.titlebar_floating_button_focus_inactive = "/usr/share/awesome/themes/zenburn/titlebar/floating_focus_inactive.png" theme.titlebar_floating_button_normal_inactive = "/usr/share/awesome/themes/zenburn/titlebar/floating_normal_inactive.png" theme.titlebar_maximized_button_focus_active = "/usr/share/awesome/themes/zenburn/titlebar/maximized_focus_active.png" theme.titlebar_maximized_button_normal_active = "/usr/share/awesome/themes/zenburn/titlebar/maximized_normal_active.png" theme.titlebar_maximized_button_focus_inactive = "/usr/share/awesome/themes/zenburn/titlebar/maximized_focus_inactive.png" theme.titlebar_maximized_button_normal_inactive = "/usr/share/awesome/themes/zenburn/titlebar/maximized_normal_inactive.png" -- }}} -- }}} return theme
mit
mtroyka/Zero-K
units/jumpblackhole.lua
2
4474
unitDef = { unitname = [[jumpblackhole]], name = [[Placeholder]], description = [[Black Hole Launcher]], acceleration = 0.4, brakeRate = 1.2, buildCostEnergy = 250, buildCostMetal = 250, builder = false, buildPic = [[jumpblackhole.png]], buildTime = 250, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[30 48 30]], collisionVolumeType = [[cylY]], corpse = [[DEAD]], customParams = { helptext = [[The Placeholder is a support unit. Its projectiles create a vacuum that sucks in nearby units, clustering and holding them in place to help finish them off.]], midposoffset = [[0 10 0]], }, explodeAs = [[BIG_UNITEX]], footprintX = 2, footprintZ = 2, iconType = [[kbotwideriot]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, losEmitHeight = 40, maxDamage = 900, maxSlope = 36, maxVelocity = 2, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[KBOT2]], noAutoFire = false, noChaseCategory = [[FIXEDWING SATELLITE GUNSHIP SUB TURRET UNARMED]], objectName = [[freaker.s3o]], script = [[jumpblackhole.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], selfDestructCountdown = 5, sfxtypes = { explosiongenerators = { [[custom:PILOT]], [[custom:PILOT2]], [[custom:RAIDMUZZLE]], [[custom:VINDIBACK]], }, }, sightDistance = 605, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 22, turnRate = 1400, upright = true, workerTime = 0, weapons = { { def = [[BLACK_HOLE]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]], }, }, weaponDefs = { BLACK_HOLE = { name = [[Black Hole Launcher]], accuracy = 350, areaOfEffect = 300, avoidFeature = false, avoidFriendly = false, burnblow = true, collideFeature = false, collideFriendly = false, craterBoost = 100, craterMult = 2, customParams = { falldamageimmunity = [[120]], area_damage = 1, area_damage_radius = 70, area_damage_dps = 5600, area_damage_is_impulse = 1, area_damage_duration = 13.3, area_damage_range_falloff = 0.4, area_damage_time_falloff = 0.6, light_color = [[1 1 1]], light_radius = 500, }, damage = { default = 0, }, explosionGenerator = [[custom:black_hole_long]], explosionSpeed = 50, impulseBoost = 150, impulseFactor = -2.5, intensity = 0.9, interceptedByShieldType = 1, myGravity = 0.1, projectiles = 1, range = 475, reloadtime = 14, rgbColor = [[0.05 0.05 0.05]], size = 16, soundHit = [[weapon/blackhole_impact]], soundStart = [[weapon/blackhole_fire]], soundStartVolume = 6000, soundHitVolume = 6000, turret = true, weaponType = [[Cannon]], weaponVelocity = 550, }, }, featureDefs = { DEAD = { blocking = false, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[freaker_dead.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2c.s3o]], }, }, } return lowerkeys({ jumpblackhole = unitDef })
gpl-2.0
thedraked/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Ragyaya.lua
14
1056
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ragyaya -- Type: Standard NPC -- @zone 94 -- @pos -95.376 -3 60.795 -- -- 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(0x0196); 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
fhedberg/ardupilot
libraries/AP_Scripting/examples/MotorMatrix_fault_tolerant_hex.lua
4
1485
-- This script is an example setting up a custom motor matrix mix -- this is the config for hexacopter with the motor rotations configured for improved fault tolerance -- see: https://arxiv.org/pdf/1403.5986.pdf -- duplicate the #defines from AP_Motors local AP_MOTORS_MATRIX_YAW_FACTOR_CW = -1 local AP_MOTORS_MATRIX_YAW_FACTOR_CCW = 1 local AP_MOTORS_MOT_1 = 0 local AP_MOTORS_MOT_2 = 1 local AP_MOTORS_MOT_3 = 2 local AP_MOTORS_MOT_4 = 3 local AP_MOTORS_MOT_5 = 4 local AP_MOTORS_MOT_6 = 5 -- helper function duplication of the one found in AP_MotorsMatrix local function add_motor(motor_num, angle_degrees, yaw_factor, testing_order) MotorsMatrix:add_motor_raw(motor_num,math.cos(math.rad(angle_degrees + 90)), math.cos(math.rad(angle_degrees)), yaw_factor, testing_order) end -- this duplicates the add motor format used in AP_Motors for ease of modification of existing mixes add_motor(AP_MOTORS_MOT_1, 90, AP_MOTORS_MATRIX_YAW_FACTOR_CW, 2) add_motor(AP_MOTORS_MOT_2, -90, AP_MOTORS_MATRIX_YAW_FACTOR_CCW, 5) add_motor(AP_MOTORS_MOT_3, -30, AP_MOTORS_MATRIX_YAW_FACTOR_CCW, 6) add_motor(AP_MOTORS_MOT_4, 150, AP_MOTORS_MATRIX_YAW_FACTOR_CCW, 3) add_motor(AP_MOTORS_MOT_5, 30, AP_MOTORS_MATRIX_YAW_FACTOR_CW, 1) add_motor(AP_MOTORS_MOT_6,-150, AP_MOTORS_MATRIX_YAW_FACTOR_CW, 4) assert(MotorsMatrix:init(6), "Failed to init MotorsMatrix")
gpl-3.0
thedraked/darkstar
scripts/zones/Windurst_Walls/npcs/Juvillie.lua
14
1054
----------------------------------- -- Area: Windurst Walls -- NPC: Juvillie -- Type: Event Replayer -- @zone 239 -- @pos -180.731 -3.451 143.138 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0196); 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
thedraked/darkstar
scripts/zones/Jugner_Forest_[S]/mobs/Lobison.lua
17
1817
----------------------------------- -- Area: Jugner Forest (S) -- NPC: Lobison ----------------------------------- ----------------------------------- -- 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; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end;
gpl-3.0
GitoriousLispBackup/praxis
prods/wtf-atabimp/poly.lua
2
3926
-- Name: poly.lua --poly = {} t = 0 t_spd = 0.02 -- polyline = {} -- polyline[1] = { x = 0, y = 0 } -- polyline[2] = { x = 10, y = 40 } -- polyline[3] = { x = 0, y = 80 } -- polyline[4] = { x = 40, y = 70 } -- polyline[5] = { x = 80, y = 80 } -- polyline[6] = { x = 100, y = 50 } -- polyline[7] = { x = 110, y = 10 } -- polyline[8] = { x = 50, y = 50 } -- polylineManPos = 0 -- polylineManVel = 0.03 -- manPos = { x = 0, y = 0 } function makepolylines(numP, numL, numG) polylines = {} for i = 1, numP, 1 do polylines[i] = { line = {}, guys = {} } polylines[i].line[1] = { x = math.random(200), y = math.random(200) } direction = 0 lineStepSize = 40 for j = 1, numL, 1 do polylines[i].line[j+1] = { x = polylines[i].line[j].x + (lineStepSize + math.random(20) - 10) * ( math.sin(direction * (math.pi / 180))), y = polylines[i].line[j].y + (lineStepSize + math.random(20) - 10) * ( math.cos(direction * (math.pi / 180))) } direction = direction + (45 + math.random(10) - 5) * (math.random(2) - 1) end for j = 1, numG, 1 do polylines[i].guys[j] = { pos = j * 0.4, vel = 0.05 } end end return polylines end polylines = makepolylines(9, 12, 15) camAngle = 0 camAngle2 = 0 camAngleSpeed = 1 camAngleSpeed2 = 1.05 camOrbitCenter = { x = 150, y = 150 } camOrbitRadius = 100 camOrbitHeight = 10 function poly.init() camAngle = 0 camAngle2 = 0 camAngleSpeed = 1 camAngleSpeed2 = 1.05 camOrbitCenter = { x = 150, y = 150 } camOrbitRadius = 100 camOrbitHeight = 10 end function poly.update() t = t + t_spd -- move man along polyline for i = 1, #polylines, 1 do for j = 1, #polylines[i].guys, 1 do polylines[i].guys[j].pos = polylines[i].guys[j].pos + polylines[i].guys[j].vel numSegments = #polylines[i].line - 1 polylines[i].guys[j].pos = math.fmod(polylines[i].guys[j].pos, numSegments) end end camAngle = camAngle + camAngleSpeed * math.pi / 180 camAngle2 = camAngle2 + camAngleSpeed2 * math.pi / 180 camPos = { x = camOrbitCenter.x + camOrbitRadius * math.cos(camAngle), y = camOrbitCenter.y + camOrbitRadius * math.sin(camAngle2) } ahead = { x = camPos.x + -10 * math.sin(camAngle), y = camPos.y + 10 * math.cos(camAngle2) } --camOrbitRadius = math.sin(camAngle * 0.25) * 15 + 20 --setCamPos(camPos.x, camOrbitHeight, camPos.y) --lookAt(ahead.x, camOrbitHeight, ahead.y) end function poly.render() renderPolylines() renderMen() end function renderMan(man, poly) pos = getPolylinePos(man.pos, poly) beginTriGL() colorGL(255, 55, 0, 255) vectorGL(pos.x - 5, 5, pos.y) vectorGL(pos.x + 5, 5, pos.y) vectorGL(pos.x, 15, pos.y) endGL() end function renderMen() for i = 1, #polylines, 1 do for j = 1, #polylines[i].guys, 1 do renderMan(polylines[i].guys[j], polylines[i].line) end end end function renderPolylines() for i = 1, #polylines, 1 do renderPolyline(polylines[i].line) end end function renderPolyline(polyline) for i=1,#polyline-1,1 do drawLine(polyline[i].x, 5, polyline[i].y, polyline[i+1].x, 5, polyline[i+1].y) end end function getPolylinePos(pos, polyline) startIndex = math.floor(pos) % #polyline + 1 endIndex = math.ceil(pos) % #polyline + 1 along = math.fmod(pos, 1) pos = interpolatevec(polyline[startIndex], polyline[endIndex], along) return pos end function interpolate(pos1, pos2, prop) pos = pos1 + (pos2 - pos1) * prop return pos end function interpolatevec(vec1, vec2, prop) vec = { x = interpolate(vec1.x, vec2.x, prop), y = interpolate(vec1.y, vec2.y, prop) } return vec end
mit
filug/nodemcu-firmware
app/cjson/lua/cjson/util.lua
170
6837
local json = require "cjson" -- Various common routines used by the Lua CJSON package -- -- Mark Pulford <mark@kyne.com.au> -- Determine with a Lua table can be treated as an array. -- Explicitly returns "not an array" for very sparse arrays. -- Returns: -- -1 Not an array -- 0 Empty table -- >0 Highest index in the array local function is_array(table) local max = 0 local count = 0 for k, v in pairs(table) do if type(k) == "number" then if k > max then max = k end count = count + 1 else return -1 end end if max > count * 2 then return -1 end return max end local serialise_value local function serialise_table(value, indent, depth) local spacing, spacing2, indent2 if indent then spacing = "\n" .. indent spacing2 = spacing .. " " indent2 = indent .. " " else spacing, spacing2, indent2 = " ", " ", false end depth = depth + 1 if depth > 50 then return "Cannot serialise any further: too many nested tables" end local max = is_array(value) local comma = false local fragment = { "{" .. spacing2 } if max > 0 then -- Serialise array for i = 1, max do if comma then table.insert(fragment, "," .. spacing2) end table.insert(fragment, serialise_value(value[i], indent2, depth)) comma = true end elseif max < 0 then -- Serialise table for k, v in pairs(value) do if comma then table.insert(fragment, "," .. spacing2) end table.insert(fragment, ("[%s] = %s"):format(serialise_value(k, indent2, depth), serialise_value(v, indent2, depth))) comma = true end end table.insert(fragment, spacing .. "}") return table.concat(fragment) end function serialise_value(value, indent, depth) if indent == nil then indent = "" end if depth == nil then depth = 0 end if value == json.null then return "json.null" elseif type(value) == "string" then return ("%q"):format(value) elseif type(value) == "nil" or type(value) == "number" or type(value) == "boolean" then return tostring(value) elseif type(value) == "table" then return serialise_table(value, indent, depth) else return "\"<" .. type(value) .. ">\"" end end local function file_load(filename) local file if filename == nil then file = io.stdin else local err file, err = io.open(filename, "rb") if file == nil then error(("Unable to read '%s': %s"):format(filename, err)) end end local data = file:read("*a") if filename ~= nil then file:close() end if data == nil then error("Failed to read " .. filename) end return data end local function file_save(filename, data) local file if filename == nil then file = io.stdout else local err file, err = io.open(filename, "wb") if file == nil then error(("Unable to write '%s': %s"):format(filename, err)) end end file:write(data) if filename ~= nil then file:close() end end local function compare_values(val1, val2) local type1 = type(val1) local type2 = type(val2) if type1 ~= type2 then return false end -- Check for NaN if type1 == "number" and val1 ~= val1 and val2 ~= val2 then return true end if type1 ~= "table" then return val1 == val2 end -- check_keys stores all the keys that must be checked in val2 local check_keys = {} for k, _ in pairs(val1) do check_keys[k] = true end for k, v in pairs(val2) do if not check_keys[k] then return false end if not compare_values(val1[k], val2[k]) then return false end check_keys[k] = nil end for k, _ in pairs(check_keys) do -- Not the same if any keys from val1 were not found in val2 return false end return true end local test_count_pass = 0 local test_count_total = 0 local function run_test_summary() return test_count_pass, test_count_total end local function run_test(testname, func, input, should_work, output) local function status_line(name, status, value) local statusmap = { [true] = ":success", [false] = ":error" } if status ~= nil then name = name .. statusmap[status] end print(("[%s] %s"):format(name, serialise_value(value, false))) end local result = { pcall(func, unpack(input)) } local success = table.remove(result, 1) local correct = false if success == should_work and compare_values(result, output) then correct = true test_count_pass = test_count_pass + 1 end test_count_total = test_count_total + 1 local teststatus = { [true] = "PASS", [false] = "FAIL" } print(("==> Test [%d] %s: %s"):format(test_count_total, testname, teststatus[correct])) status_line("Input", nil, input) if not correct then status_line("Expected", should_work, output) end status_line("Received", success, result) print() return correct, result end local function run_test_group(tests) local function run_helper(name, func, input) if type(name) == "string" and #name > 0 then print("==> " .. name) end -- Not a protected call, these functions should never generate errors. func(unpack(input or {})) print() end for _, v in ipairs(tests) do -- Run the helper if "should_work" is missing if v[4] == nil then run_helper(unpack(v)) else run_test(unpack(v)) end end end -- Run a Lua script in a separate environment local function run_script(script, env) local env = env or {} local func -- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists if _G.setfenv then func = loadstring(script) if func then setfenv(func, env) end else func = load(script, nil, nil, env) end if func == nil then error("Invalid syntax.") end func() return env end -- Export functions return { serialise_value = serialise_value, file_load = file_load, file_save = file_save, compare_values = compare_values, run_test_summary = run_test_summary, run_test = run_test, run_test_group = run_test_group, run_script = run_script } -- vi:ai et sw=4 ts=4:
mit
mason-larobina/luakit
doc/luadoc/soup.lua
4
1339
--- URI parsing utilities. -- -- DOCMACRO(available:ui) -- -- The soup API provides some utilities for parsing and converting URIs, written -- in C. For historical reasons, it also provides some other miscellaneous APIs. -- -- @module soup -- @author Mason Larobina -- @copyright 2012 Mason Larobina <mason.larobina@gmail.com> --- Parse a URI. -- @function parse_uri -- @tparam string uri The URI to parse. -- @treturn table A table of URI components. --- Convert a table of URI components to a string. -- @function uri_tostring -- @tparam table uri A table of URI components. -- @treturn string The URI string. --- The URI of the proxy to use for connections. Can be a URI, the -- string `"no_proxy"`, the string `"default"`, or `nil` (which means the same -- as `"default"`). -- @property proxy_uri -- @type string -- @readwrite -- @default `"default"` --- The cookie acceptance policy. Determines which cookies are accepted and -- stored. Can be one of `"always"`, `"never"`, and --`"no_third_party"`. -- @property accept_policy -- @type string -- @readwrite -- @default `"no_third_party"` --- The path to the cookie database to use. Should only be set once. Initially -- unset, meaning no cookie database will be used. -- @property cookies_storage -- @type string -- @readwrite -- @default `nil` -- vim: et:sw=4:ts=8:sts=4:tw=80
gpl-3.0
thedraked/darkstar
scripts/globals/items/holy_bolt.lua
26
1227
----------------------------------------- -- ID: 18153 -- Item: Holy Bolt -- Additional Effect: Light Damage -- Bolt dmg is affected by light/dark staves and Chatoyant ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 105; if (target:getMainLvl() > player:getMainLvl()) then chance = chance - 5 * (target:getMainLvl() - player:getMainLvl()) chance = utils.clamp(chance, 5, 95); end if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = player:getStat(MOD_MND) - target:getStat(MOD_MND); if (dmg > 40) then dmg = dmg+(dmg-40)/2; end local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params); dmg = adjustForTarget(target,dmg,ELE_LIGHT); dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg); return SUBEFFECT_LIGHT_DAMAGE, MSGBASIC_ADD_EFFECT_DMG, dmg; end end;
gpl-3.0
X-Coder/wire
lua/entities/info_wiremapinterface/output.lua
17
2147
-- Copied from the gmod base entity, it's changed to work with wire map interface. -- It's only changed for this entity. -- This function is used to store an output. function ENT:StoreOutput(name, info) local rawData = string.Explode(",", info) local Output = {} Output.entities = rawData[1] or "" Output.input = rawData[2] or "" Output.param = rawData[3] or "" Output.delay = tonumber(rawData[4]) or 0 Output.times = tonumber(rawData[5]) or -1 self._OutputsToMap = self._OutputsToMap or {} self._OutputsToMap[name] = self._OutputsToMap[name] or {} table.insert(self._OutputsToMap[name], Output) end -- Nice helper function, this does all the work. -- Returns false if the output should be removed from the list. local function FireSingleOutput(output, this, activator, value, delayoffset) if (output.times == 0) then return false end local delay = output.delay + (delayoffset or 0) local entitiesToFire = {} if (output.entities == "!activator") then entitiesToFire = {activator} elseif (output.entities == "!self") then entitiesToFire = {this} elseif (output.entities == "!player") then entitiesToFire = player.GetAll() else entitiesToFire = ents.FindByName(output.entities) end for _,ent in pairs(entitiesToFire) do if (IsValid(ent)) then if (delay == 0) then ent:Input(output.input, activator, this, value or output.param) else timer.Simple(delay, function() if (IsValid(ent)) then ent:Input(output.input, activator, this, value or output.param) end end) end end end if (output.times ~= -1) then output.times = output.times - 1 end return ((output.times > 0) or (output.times == -1)) end -- This function is used to trigger an output. -- This changed version supports value replacemant and delay offsets. function ENT:TriggerOutput(name, activator, value, delayoffset) if (!self._OutputsToMap) then return end local OutputsToMap = self._OutputsToMap[name] if (!OutputsToMap) then return end for idx,op in pairs(OutputsToMap) do if (!FireSingleOutput(op, self, activator, value, delayoffset)) then self._OutputsToMap[name][idx] = nil end end end
gpl-3.0
kaustavha/luvit
deps/stream/stream_observable.lua
6
1512
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ --Observable is a stream that can be observed outside the pipeline. observe() --returns a new Readable stream that emits all data that passes through this --stream. Streams created by observe() do not affect back-pressure. --]] local Transform = require('./stream_transform').Transform local Readable = require('./stream_readable').Readable local Observable = Transform:extend() function Observable:initialize(options) --[[ if (!(this instanceof PassThrough)) return new PassThrough(options) --]] Transform.initialize(self, options) self.options = options self.observers = {} end function Observable:_transform(chunk, cb) for _,v in pairs(self.observers) do v:push(chunk) end cb(nil, chunk) end function Observable:observe() local obs = Readable:new(self.options) obs._read = function() end table.insert(self.observers, obs) return obs end exports.Observable = Observable
apache-2.0
pevers/OpenRA
lua/stacktraceplus.lua
59
12006
-- tables local _G = _G local string, io, debug, coroutine = string, io, debug, coroutine -- functions local tostring, print, require = tostring, print, require local next, assert = next, assert local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs local error = error assert(debug, "debug table must be available at this point") local io_open = io.open local string_gmatch = string.gmatch local string_sub = string.sub local table_concat = table.concat local _M = { max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)' } -- this tables should be weak so the elements in them won't become uncollectable local m_known_tables = { [_G] = "_G (global table)" } local function add_known_module(name, desc) local ok, mod = pcall(require, name) if ok then m_known_tables[mod] = desc end end add_known_module("string", "string module") add_known_module("io", "io module") add_known_module("os", "os module") add_known_module("table", "table module") add_known_module("math", "math module") add_known_module("package", "package module") add_known_module("debug", "debug module") add_known_module("coroutine", "coroutine module") -- lua5.2 add_known_module("bit32", "bit32 module") -- luajit add_known_module("bit", "bit module") add_known_module("jit", "jit module") local m_user_known_tables = {} local m_known_functions = {} for _, name in ipairs{ -- Lua 5.2, 5.1 "assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs", "load", "loadfile", "next", "pairs", "pcall", "print", "rawequal", "rawget", "rawlen", "rawset", "require", "select", "setmetatable", "tonumber", "tostring", "type", "xpcall", -- Lua 5.1 "gcinfo", "getfenv", "loadstring", "module", "newproxy", "setfenv", "unpack", -- TODO: add table.* etc functions } do if _G[name] then m_known_functions[_G[name]] = name end end local m_user_known_functions = {} local function safe_tostring (value) local ok, err = pcall(tostring, value) if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end end -- Private: -- Parses a line, looking for possible function definitions (in a very naïve way) -- Returns '(anonymous)' if no function name was found in the line local function ParseLine(line) assert(type(line) == "string") --print(line) local match = line:match("^%s*function%s+(%w+)") if match then --print("+++++++++++++function", match) return match end match = line:match("^%s*local%s+function%s+(%w+)") if match then --print("++++++++++++local", match) return match end match = line:match("^%s*local%s+(%w+)%s+=%s+function") if match then --print("++++++++++++local func", match) return match end match = line:match("%s*function%s*%(") -- this is an anonymous function if match then --print("+++++++++++++function2", match) return "(anonymous)" end return "(anonymous)" end -- Private: -- Tries to guess a function's name when the debug info structure does not have it. -- It parses either the file or the string where the function is defined. -- Returns '?' if the line where the function is defined is not found local function GuessFunctionName(info) --print("guessing function name") if type(info.source) == "string" and info.source:sub(1,1) == "@" then local file, err = io_open(info.source:sub(2), "r") if not file then print("file not found: "..tostring(err)) -- whoops! return "?" end local line for i = 1, info.linedefined do line = file:read("*l") end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) else local line local lineNumber = 0 for l in string_gmatch(info.source, "([^\n]+)\n-") do lineNumber = lineNumber + 1 if lineNumber == info.linedefined then line = l break end end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) end end --- -- Dumper instances are used to analyze stacks and collect its information. -- local Dumper = {} Dumper.new = function(thread) local t = { lines = {} } for k,v in pairs(Dumper) do t[k] = v end t.dumping_same_thread = (thread == coroutine.running()) -- if a thread was supplied, bind it to debug.info and debug.get -- we also need to skip this additional level we are introducing in the callstack (only if we are running -- in the same thread we're inspecting) if type(thread) == "thread" then t.getinfo = function(level, what) if t.dumping_same_thread and type(level) == "number" then level = level + 1 end return debug.getinfo(thread, level, what) end t.getlocal = function(level, loc) if t.dumping_same_thread then level = level + 1 end return debug.getlocal(thread, level, loc) end else t.getinfo = debug.getinfo t.getlocal = debug.getlocal end return t end -- helpers for collecting strings to be used when assembling the final trace function Dumper:add (text) self.lines[#self.lines + 1] = text end function Dumper:add_f (fmt, ...) self:add(fmt:format(...)) end function Dumper:concat_lines () return table_concat(self.lines) end --- -- Private: -- Iterates over the local variables of a given function. -- -- @param level The stack level where the function is. -- function Dumper:DumpLocals (level) local prefix = "\t " local i = 1 if self.dumping_same_thread then level = level + 1 end local name, value = self.getlocal(level, i) if not name then return end self:add("\tLocal variables:\r\n") while name do if type(value) == "number" then self:add_f("%s%s = number: %g\r\n", prefix, name, value) elseif type(value) == "boolean" then self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value)) elseif type(value) == "string" then self:add_f("%s%s = string: %q\r\n", prefix, name, value) elseif type(value) == "userdata" then self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value)) elseif type(value) == "nil" then self:add_f("%s%s = nil\r\n", prefix, name) elseif type(value) == "table" then if m_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value]) elseif m_user_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value]) else local txt = "{" for k,v in pairs(value) do txt = txt..safe_tostring(k)..":"..safe_tostring(v) if #txt > _M.max_tb_output_len then txt = txt.." (more...)" break end if next(value, k) then txt = txt..", " end end self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}") end elseif type(value) == "function" then local info = self.getinfo(value, "nS") local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value] if info.what == "C" then self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value))) else local source = info.short_src if source:sub(2,7) == "string" then source = source:sub(9) end --for k,v in pairs(info) do print(k,v) end fun_name = fun_name or GuessFunctionName(info) self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source) end elseif type(value) == "thread" then self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value)) end i = i + 1 name, value = self.getlocal(level, i) end end --- -- Public: -- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc. -- This function is suitable to be used as an error handler with pcall or xpcall -- -- @param thread An optional thread whose stack is to be inspected (defaul is the current thread) -- @param message An optional error string or object. -- @param level An optional number telling at which level to start the traceback (default is 1) -- -- Returns a string with the stack trace and a string with the original error. -- function _M.stacktrace(thread, message, level) if type(thread) ~= "thread" then -- shift parameters left thread, message, level = nil, thread, message end thread = thread or coroutine.running() level = level or 1 local dumper = Dumper.new(thread) local original_error if type(message) == "table" then dumper:add("an error object {\r\n") local first = true for k,v in pairs(message) do if first then dumper:add(" ") first = false else dumper:add(",\r\n ") end dumper:add(safe_tostring(k)) dumper:add(": ") dumper:add(safe_tostring(v)) end dumper:add("\r\n}") original_error = dumper:concat_lines() elseif type(message) == "string" then dumper:add(message) original_error = message end dumper:add("\r\n") dumper:add[[ Stack Traceback =============== ]] --print(error_message) local level_to_show = level if dumper.dumping_same_thread then level = level + 1 end local info = dumper.getinfo(level, "nSlf") while info do if info.what == "main" then if string_sub(info.source, 1, 1) == "@" then dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline) else dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline) end elseif info.what == "C" then --print(info.namewhat, info.name) --for k,v in pairs(info) do print(k,v, type(v)) end local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func) dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name) --dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value))) elseif info.what == "tail" then --print("tail") --for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name) dumper:add_f("(%d) tail call\r\n", level_to_show) dumper:DumpLocals(level) elseif info.what == "Lua" then local source = info.short_src local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name if source:sub(2, 7) == "string" then source = source:sub(9) end local was_guessed = false if not function_name or function_name == "?" then --for k,v in pairs(info) do print(k,v, type(v)) end function_name = GuessFunctionName(info) was_guessed = true end -- test if we have a file name local function_type = (info.namewhat == "") and "function" or info.namewhat if info.source and info.source:sub(1, 1) == "@" then dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") elseif info.source and info.source:sub(1,1) == '#' then dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") else dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source) end dumper:DumpLocals(level) else dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what) end level = level + 1 level_to_show = level_to_show + 1 info = dumper.getinfo(level, "nSlf") end return dumper:concat_lines(), original_error end -- -- Adds a table to the list of known tables function _M.add_known_table(tab, description) if m_known_tables[tab] then error("Cannot override an already known table") end m_user_known_tables[tab] = description end -- -- Adds a function to the list of known functions function _M.add_known_function(fun, description) if m_known_functions[fun] then error("Cannot override an already known function") end m_user_known_functions[fun] = description end return _M
gpl-3.0
thedraked/darkstar
scripts/zones/Bhaflau_Thickets/mobs/Sea_Puk.lua
12
1367
----------------------------------- -- Area: Bhaflau Thickets -- MOB: Sea Puk -- Note: Place holder Nis Puk ----------------------------------- require("scripts/zones/Bhaflau_Thickets/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) -- Get Sea Puk ID and check if it is a PH of NP local mobID = mob:getID(); -- Check if Sea Puk is within the Nis_Puk_PH table if (Nis_Puk_PH[mobID] ~= nil) then -- printf("%u is a PH",mobID); -- Get NP's previous ToD local NP_ToD = GetServerVariable("[POP]Nis_Puk"); -- Check if NP window is open, and there is not an NP popped already(ACTION_NONE = 0) if (NP_ToD <= os.time(t) and GetMobAction(Nis_Puk) == 0) then -- printf("NP window open"); -- Give Sea Puk 5 percent chance to pop NP if (math.random(1,20) >= 1) then -- printf("NP will pop"); UpdateNMSpawnPoint(Nis_Puk); GetMobByID(Nis_Puk):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Nis_Puk", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
thedraked/darkstar
scripts/zones/RoMaeve/Zone.lua
4
3579
----------------------------------- -- -- Zone: RoMaeve (122) -- ----------------------------------- package.loaded["scripts/zones/RoMaeve/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/RoMaeve/TextIDs"); require("scripts/globals/zone"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17277227,17277228}; SetFieldManual(manuals); local vwnpc = {17277245,17277246,17277247}; SetVoidwatchNPC(vwnpc); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-0.008,-33.595,123.478,62); end if (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 0x0003; -- doll telling "you're in the right area" end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onGameDay ----------------------------------- function onGameDay() -- Full moon + "clear" weather stuff (actually "sunshine" weather, widespread misconception since Ro'Maeve does not have "clear" weather ever) local Moongate_Offset = 17277195; -- _3e0 in npc_list local hour = VanadielHour(); if (IsMoonFull() == true and GetNPCByID(Moongate_Offset):getWeather() == WEATHER_SUNSHINE) then GetNPCByID(Moongate_Offset):openDoor(432); -- 3 game hours worth of seconds GetNPCByID(Moongate_Offset+1):openDoor(432); GetNPCByID(Moongate_Offset+7):openDoor(432); -- visual part of Qu'Hau Spring end end; ----------------------------------- -- onZoneWeatherChange ----------------------------------- function onZoneWeatherChange(weather) local Moongate_Offset = 17277195; if (weather ~= WEATHER_SUNSHINE and GetNPCByID(Moongate_Offset):getAnimation() ~= 9) then -- return to inactive state GetNPCByID(Moongate_Offset):setAnimation(9); GetNPCByID(Moongate_Offset+1):setAnimation(9); GetNPCByID(Moongate_Offset+7):setAnimation(9); elseif (weather == WEATHER_SUNSHINE and IsMoonFull() == true and VanadielHour() < 3) then -- reactivate things for the remainder of the time until 3AM local moonMinRemaining = math.floor(432 * (180 - VanadielHour() * 60 + VanadielMinute())/180) -- 180 minutes (ie 3AM) subtract the time that has passed since midnight GetNPCByID(Moongate_Offset):openDoor(moonMinRemaining); GetNPCByID(Moongate_Offset+1):openDoor(moonMinRemaining); GetNPCByID(Moongate_Offset+7):openDoor(moonMinRemaining); 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
jefferai/vlcfix
share/lua/playlist/vimeo.lua
65
3213
--[[ $Id$ Copyright © 2009-2013 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.org) François Revol (revol@free.fr) Pierre Ynard This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] function get_prefres() local prefres = -1 if vlc.var and vlc.var.inherit then prefres = vlc.var.inherit(nil, "preferred-resolution") if prefres == nil then prefres = -1 end end return prefres end -- Probe function. function probe() return ( vlc.access == "http" or vlc.access == "https" ) and ( string.match( vlc.path, "vimeo%.com/%d+$" ) or string.match( vlc.path, "player%.vimeo%.com" ) ) -- do not match other addresses, -- else we'll also try to decode the actual video url end -- Parse function. function parse() if not string.match( vlc.path, "player%.vimeo%.com" ) then -- Web page URL while true do local line = vlc.readline() if not line then break end path = string.match( line, "data%-config%-url=\"(.-)\"" ) if path then path = vlc.strings.resolve_xml_special_chars( path ) return { { path = path } } end end vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" ) return { } else -- API URL local prefres = get_prefres() local line = vlc.readline() -- data is on one line only for stream in string.gmatch( line, "{([^}]*\"profile\":[^}]*)}" ) do local url = string.match( stream, "\"url\":\"(.-)\"" ) if url then path = url if prefres < 0 then break end local height = string.match( stream, "\"height\":(%d+)[,}]" ) if not height or tonumber(height) <= prefres then break end end end if not path then vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" ) return { } end local name = string.match( line, "\"title\":\"(.-)\"" ) local artist = string.match( line, "\"owner\":{[^}]-\"name\":\"(.-)\"" ) local arturl = string.match( line, "\"thumbs\":{\"[^\"]+\":\"(.-)\"" ) local duration = string.match( line, "\"duration\":(%d+)[,}]" ) return { { path = path; name = name; artist = artist; arturl = arturl; duration = duration } } end end
gpl-2.0
thedraked/darkstar
scripts/zones/Port_Windurst/npcs/Pherchabalet.lua
14
1052
----------------------------------- -- Area: Port Windurst -- NPC: Pherchabalet -- Type: Standard NPC -- @zone 240 -- @pos 34.683 -5.999 137.447 -- -- 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(0x0229); 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
MonkeyFirst/Urho3D
bin/Data/LuaScripts/38_SceneAndUILoad.lua
26
5306
-- Scene & UI load example. -- This sample demonstrates: -- - Loading a scene from a file and showing it -- - Loading a UI layout from a file and showing it -- - Subscribing to the UI layout's events require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateUI() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Subscribe to global events for camera movement SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Load scene content prepared in the editor (XML format). GetFile() returns an open file from the resource system -- which scene.LoadXML() will read local file = cache:GetFile("Scenes/SceneLoadExample.xml") scene_:LoadXML(file) -- In Lua the file returned by GetFile() needs to be deleted manually file:delete() -- Create the camera (not included in the scene file) cameraNode = scene_:CreateChild("Camera") cameraNode:CreateComponent("Camera") -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 2.0, -10.0) end function CreateUI() -- Set up global UI style into the root UI element local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") ui.root.defaultStyle = style -- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will -- control the camera, and when visible, it will interact with the UI local cursor = ui.root:CreateChild("Cursor") cursor:SetStyleAuto() ui.cursor = cursor -- Set starting position of the cursor at the rendering window center cursor:SetPosition(graphics.width / 2, graphics.height / 2) -- Load UI content prepared in the editor and add to the UI hierarchy local layoutRoot = ui:LoadLayout(cache:GetResource("XMLFile", "UI/UILoadExample.xml")) ui.root:AddChild(layoutRoot) -- Subscribe to button actions (toggle scene lights when pressed then released) local button = layoutRoot:GetChild("ToggleLight1", true) if button ~= nil then SubscribeToEvent(button, "Released", "ToggleLight1") end button = layoutRoot:GetChild("ToggleLight2", true) if button ~= nil then SubscribeToEvent(button, "Released", "ToggleLight2") end end function ToggleLight1() local lightNode = scene_:GetChild("Light1", true) if lightNode ~= nil then lightNode.enabled = not lightNode.enabled end end function ToggleLight2() local lightNode = scene_:GetChild("Light2", true) if lightNode ~= nil then lightNode.enabled = not lightNode.enabled end end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for camera motion SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end function MoveCamera(timeStep) input.mouseVisible = input.mouseMode ~= MM_RELATIVE mouseDown = input:GetMouseButtonDown(MOUSEB_RIGHT) -- Override the MM_RELATIVE mouse grabbed settings, to allow interaction with UI input.mouseGrabbed = mouseDown -- Right mouse button controls mouse cursor visibility: hide when pressed ui.cursor.visible = not mouseDown -- Do not move if the UI has a focused element if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees -- Only move the camera when the cursor is hidden if not ui.cursor.visible then local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) end -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end end
mit
Ali-2h/losebot
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
thedraked/darkstar
scripts/zones/Windurst_Woods/npcs/Ponono.lua
44
2111
----------------------------------- -- Area: Windurst Woods -- NPC: Ponono -- Type: Clothcraft Guild Master -- @pos -38.243 -2.25 -120.954 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILL_CLOTHCRAFT); if (newRank ~= 0) then player:setSkillRank(SKILL_CLOTHCRAFT,newRank); player:startEvent(0x271c,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILL_CLOTHCRAFT); local testItem = getTestItem(player,npc,SKILL_CLOTHCRAFT); local guildMember = isGuildMember(player,3); if (guildMember == 1) then guildMember = 10000; end if (canGetNewRank(player,craftSkill,SKILL_CLOTHCRAFT) == 1) then getNewRank = 100; end player:startEvent(0x271b,testItem,getNewRank,30,guildMember,44,0,0,0); end; -- 0x271b 0x271c 0x02bc 0x02bd 0x02be 0x02bf 0x02c0 0x02c1 0x0340 0x02fd ----------------------------------- -- 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 == 0x271b and option == 1) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4099); else player:addItem(4099); player:messageSpecial(ITEM_OBTAINED,4099); signupGuild(player,8); end end end;
gpl-3.0
moomoomoo309/FamiliarFaces
src/pl/Date.lua
1
18179
--- Date and Date Format classes. -- See @{05-dates.md|the Guide}. -- -- Dependencies: `pl.class`, `pl.stringx`, `pl.utils` -- @classmod pl.Date -- @pragma nostrip local class = require 'pl.class' local os_time, os_date = os.time, os.date local stringx = require 'pl.stringx' local utils = require 'pl.utils' local assert_arg,assert_string = utils.assert_arg,utils.assert_string local Date = class() Date.Format = class() --- Date constructor. -- @param percent this can be either -- -- * `nil` or empty - use current date and time -- * number - seconds since epoch (as returned by `os.time`). Resulting time is UTC -- * `Date` - make a copy of this date -- * table - table containing year, month, etc as for `os.time`. You may leave out year, month or day, -- in which case current values will be used. -- * year (will be followed by month, day etc) -- -- @param ... true if Universal Coordinated Time, or two to five numbers: month,day,hour,min,sec -- @function Date function Date:_init(t,...) local time local nargs = select('#',...) if nargs > 2 then local extra = {...} local year = t t = { year = year, month = extra[1], day = extra[2], hour = extra[3], min = extra[4], sec = extra[5] } end if nargs == 1 then self.utc = select(1,...) == true end if t == nil or t == 'utc' then time = os_time() self.utc = t == 'utc' elseif type(t) == 'number' then time = t if self.utc == nil then self.utc = true end elseif type(t) == 'table' then if getmetatable(t) == Date then -- copy ctor time = t.time self.utc = t.utc else if not (t.year and t.month) then local lt = os_date('*t') if not t.year and not t.month and not t.day then t.year = lt.year t.month = lt.month t.day = lt.day else t.year = t.year or lt.year t.month = t.month or (t.day and lt.month or 1) t.day = t.day or 1 end end t.day = t.day or 1 time = os_time(t) end else error("bad type for Date constructor: "..type(t),2) end self:set(time) end --- set the current time of this Date object. -- @int t seconds since epoch function Date:set(t) self.time = t if self.utc then self.tab = os_date('!*t',t) else self.tab = os_date('*t',t) end end --- get the time zone offset from UTC. -- @int ts seconds ahead of UTC function Date.tzone (ts) if ts == nil then ts = os_time() elseif type(ts) == "table" then if getmetatable(ts) == Date then ts = ts.time else ts = Date(ts).time end end local utc = os_date('!*t',ts) local lcl = os_date('*t',ts) lcl.isdst = false return os.difftime(os_time(lcl), os_time(utc)) end --- convert this date to UTC. function Date:toUTC () local ndate = Date(self) if not self.utc then ndate.utc = true ndate:set(ndate.time) end return ndate end --- convert this UTC date to local. function Date:toLocal () local ndate = Date(self) if self.utc then ndate.utc = false ndate:set(ndate.time) --~ ndate:add { sec = Date.tzone(self) } end return ndate end --- set the year. -- @int y Four-digit year -- @class function -- @name Date:year --- set the month. -- @int m month -- @class function -- @name Date:month --- set the day. -- @int d day -- @class function -- @name Date:day --- set the hour. -- @int h hour -- @class function -- @name Date:hour --- set the minutes. -- @int min minutes -- @class function -- @name Date:min --- set the seconds. -- @int sec seconds -- @class function -- @name Date:sec --- set the day of year. -- @class function -- @int yday day of year -- @name Date:yday --- get the year. -- @int y Four-digit year -- @class function -- @name Date:year --- get the month. -- @class function -- @name Date:month --- get the day. -- @class function -- @name Date:day --- get the hour. -- @class function -- @name Date:hour --- get the minutes. -- @class function -- @name Date:min --- get the seconds. -- @class function -- @name Date:sec --- get the day of year. -- @class function -- @name Date:yday for _,c in ipairs{'year','month','day','hour','min','sec','yday'} do Date[c] = function(self,val) if val then assert_arg(1,val,"number") self.tab[c] = val self:set(os_time(self.tab)) return self else return self.tab[c] end end end --- name of day of week. -- @bool full abbreviated if true, full otherwise. -- @ret string name function Date:weekday_name(full) return os_date(full and '%A' or '%a',self.time) end --- name of month. -- @int full abbreviated if true, full otherwise. -- @ret string name function Date:month_name(full) return os_date(full and '%B' or '%b',self.time) end --- is this day on a weekend?. function Date:is_weekend() return self.tab.wday == 1 or self.tab.wday == 7 end --- add to a date object. -- @param percent a table containing one of the following keys and a value: -- one of `year`,`month`,`day`,`hour`,`min`,`sec` -- @return this date function Date:add(t) local old_dst = self.tab.isdst local key,val = next(t) self.tab[key] = self.tab[key] + val self:set(os_time(self.tab)) if old_dst ~= self.tab.isdst then self.tab.hour = self.tab.hour - (old_dst and 1 or -1) self:set(os_time(self.tab)) end return self end --- last day of the month. -- @return int day function Date:last_day() local d = 28 local m = self.tab.month while self.tab.month == m do d = d + 1 self:add{day=1} end self:add{day=-1} return self end --- difference between two Date objects. -- @tparam Date other Date object -- @treturn Date.Interval object function Date:diff(other) local dt = self.time - other.time if dt < 0 then error("date difference is negative!",2) end return Date.Interval(dt) end --- long numerical ISO data format version of this date. function Date:__tostring() local fmt = '%Y-%m-%dT%H:%M:%S' if self.utc then fmt = "!"..fmt end local t = os_date(fmt,self.time) if self.utc then return t .. 'Z' else local offs = self:tzone() if offs == 0 then return t .. 'Z' end local sign = offs > 0 and '+' or '-' local h = math.ceil(offs/3600) local m = (offs % 3600)/60 if m == 0 then return t .. ('%s%02d'):format(sign,h) else return t .. ('%s%02d:%02d'):format(sign,h,m) end end end --- equality between Date objects. function Date:__eq(other) return self.time == other.time end --- ordering between Date objects. function Date:__lt(other) return self.time < other.time end --- difference between Date objects. -- @function Date:__sub Date.__sub = Date.diff --- add a date and an interval. -- @param other either a `Date.Interval` object or a table such as -- passed to `Date:add` function Date:__add(other) local nd = Date(self) if Date.Interval:class_of(other) then other = {sec=other.time} end nd:add(other) return nd end Date.Interval = class(Date) ---- Date.Interval constructor -- @int t an interval in seconds -- @function Date.Interval function Date.Interval:_init(t) self:set(t) end function Date.Interval:set(t) self.time = t self.tab = os_date('!*t',self.time) end local function ess(n) if n > 1 then return 's ' else return ' ' end end --- If it's an interval then the format is '2 hours 29 sec' etc. function Date.Interval:__tostring() local t, res = self.tab, '' local y,m,d = t.year - 1970, t.month - 1, t.day - 1 if y > 0 then res = res .. y .. ' year'..ess(y) end if m > 0 then res = res .. m .. ' month'..ess(m) end if d > 0 then res = res .. d .. ' day'..ess(d) end if y == 0 and m == 0 then local h = t.hour if h > 0 then res = res .. h .. ' hour'..ess(h) end if t.min > 0 then res = res .. t.min .. ' min ' end if t.sec > 0 then res = res .. t.sec .. ' sec ' end end if res == '' then res = 'zero' end return res end ------------ Date.Format class: parsing and renderinig dates ------------ -- short field names, explicit os.date names, and a mask for allowed field repeats local formats = { d = {'day',{true,true}}, y = {'year',{false,true,false,true}}, m = {'month',{true,true}}, H = {'hour',{true,true}}, M = {'min',{true,true}}, S = {'sec',{true,true}}, } --- Date.Format constructor. -- @string fmt. A string where the following fields are significant: -- -- * d day (either d or dd) -- * y year (either yy or yyy) -- * m month (either m or mm) -- * H hour (either H or HH) -- * M minute (either M or MM) -- * S second (either S or SS) -- -- Alternatively, if fmt is nil then this returns a flexible date parser -- that tries various date/time schemes in turn: -- -- * [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601), like `2010-05-10 12:35:23Z` or `2008-10-03T14:30+02` -- * times like 15:30 or 8.05pm (assumed to be today's date) -- * dates like 28/10/02 (European order!) or 5 Feb 2012 -- * month name like march or Mar (case-insensitive, first 3 letters); here the -- day will be 1 and the year this current year -- -- A date in format 3 can be optionally followed by a time in format 2. -- Please see test-date.lua in the tests folder for more examples. -- @usage df = Date.Format("yyyy-mm-dd HH:MM:SS") -- @class function -- @name Date.Format function Date.Format:_init(fmt) if not fmt then self.fmt = '%Y-%m-%d %H:%M:%S' self.outf = self.fmt self.plain = true return end local append = table.insert local D,PLUS,OPENP,CLOSEP = '\001','\002','\003','\004' local vars,used = {},{} local patt,outf = {},{} local i = 1 while i < #fmt do local ch = fmt:sub(i,i) local df = formats[ch] if df then if used[ch] then error("field appeared twice: "..ch,4) end used[ch] = true -- this field may be repeated local _,inext = fmt:find(ch..'+',i+1) local cnt = not _ and 1 or inext-i+1 if not df[2][cnt] then error("wrong number of fields: "..ch,4) end -- single chars mean 'accept more than one digit' local p = cnt==1 and (D..PLUS) or (D):rep(cnt) append(patt,OPENP..p..CLOSEP) append(vars,ch) if ch == 'y' then append(outf,cnt==2 and '%y' or '%Y') else append(outf,'%'..ch) end i = i + cnt else append(patt,ch) append(outf,ch) i = i + 1 end end -- escape any magic characters fmt = utils.escape(table.concat(patt)) -- fmt = table.concat(patt):gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1') -- replace markers with their magic equivalents fmt = fmt:gsub(D,'%%d'):gsub(PLUS,'+'):gsub(OPENP,'('):gsub(CLOSEP,')') self.fmt = fmt self.outf = table.concat(outf) self.vars = vars end local parse_date --- parse a string into a Date object. -- @string str a date string -- @return date object function Date.Format:parse(str) assert_string(1,str) if self.plain then return parse_date(str,self.us) end local res = {str:match(self.fmt)} if #res==0 then return nil, 'cannot parse '..str end local tab = {} for i,v in ipairs(self.vars) do local name = formats[v][1] -- e.g. 'y' becomes 'year' tab[name] = tonumber(res[i]) end -- os.date() requires these fields; if not present, we assume -- that the time set is for the current day. if not (tab.year and tab.month and tab.day) then local today = Date() tab.year = tab.year or today:year() tab.month = tab.month or today:month() tab.day = tab.day or today:day() end local Y = tab.year if Y < 100 then -- classic Y2K pivot tab.year = Y + (Y < 35 and 2000 or 1999) elseif not Y then tab.year = 1970 end return Date(tab) end --- convert a Date object into a string. -- @param d a date object, or a time value as returned by @{os.time} -- @return string function Date.Format:tostring(d) local tm local fmt = self.outf if type(d) == 'number' then tm = d else tm = d.time if d.utc then fmt = '!'..fmt end end return os_date(fmt,tm) end --- force US order in dates like 9/11/2001 function Date.Format:US_order(yesno) self.us = yesno end --local months = {jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12} local months local parse_date_unsafe local function create_months() local ld, day1 = parse_date_unsafe '2000-12-31', {day=1} months = {} for i = 1,12 do ld = ld:last_day() ld:add(day1) local mon = ld:month_name():lower() months [mon] = i end end --[[ Allowed patterns: - [day] [monthname] [year] [time] - [day]/[month][/year] [time] ]] local function looks_like_a_month(w) return w:match '^%a+,*$' ~= nil end local is_number = stringx.isdigit local function tonum(s,l1,l2,kind) kind = kind or '' local n = tonumber(s) if not n then error(("%snot a number: '%s'"):format(kind,s)) end if n < l1 or n > l2 then error(("%s out of range: %s is not between %d and %d"):format(kind,s,l1,l2)) end return n end local function parse_iso_end(p,ns,sec) -- may be fractional part of seconds local _,nfrac,secfrac = p:find('^%.%d+',ns+1) if secfrac then sec = sec .. secfrac p = p:sub(nfrac+1) else p = p:sub(ns+1) end -- ISO 8601 dates may end in Z (for UTC) or [+-][isotime] -- (we're working with the date as lower case, hence 'z') if p:match 'z$' then -- we're UTC! return sec, {h=0,m=0} end p = p:gsub(':','') -- turn 00:30 to 0030 local _,_,sign,offs = p:find('^([%+%-])(%d+)') if not sign then return sec, nil end -- not UTC if #offs == 2 then offs = offs .. '00' end -- 01 to 0100 local tz = { h = tonumber(offs:sub(1,2)), m = tonumber(offs:sub(3,4)) } if sign == '-' then tz.h = -tz.h; tz.m = -tz.m end return sec, tz end function parse_date_unsafe (s,US) s = s:gsub('T',' ') -- ISO 8601 local parts = stringx.split(s:lower()) local i,p = 1,parts[1] local function nextp() i = i + 1; p = parts[i] end local year,min,hour,sec,apm local tz local _,nxt,day, month = p:find '^(%d+)/(%d+)' if day then -- swop for US case if US then day, month = month, day end _,_,year = p:find('^/(%d+)',nxt+1) nextp() else -- ISO year,month,day = p:match('^(%d+)%-(%d+)%-(%d+)') if year then nextp() end end if p and not year and is_number(p) then -- has to be date if #p < 4 then day = p nextp() else -- unless it looks like a 24-hour time year = true end end if p and looks_like_a_month(p) then -- date followed by month p = p:sub(1,3) if not months then create_months() end local mon = months[p] if mon then month = mon else error("not a month: " .. p) end nextp() end if p and not year and is_number(p) then year = p nextp() end if p then -- time is hh:mm[:ss], hhmm[ss] or H.M[am|pm] _,nxt,hour,min = p:find '^(%d+):(%d+)' local ns if nxt then -- are there seconds? _,ns,sec = p:find ('^:(%d+)',nxt+1) --if ns then sec,tz = parse_iso_end(p,ns or nxt,sec) --end else -- might be h.m _,ns,hour,min = p:find '^(%d+)%.(%d+)' if ns then apm = p:match '[ap]m$' else -- or hhmm[ss] local hourmin _,nxt,hourmin = p:find ('^(%d+)') if nxt then hour = hourmin:sub(1,2) min = hourmin:sub(3,4) sec = hourmin:sub(5,6) if #sec == 0 then sec = nil end sec,tz = parse_iso_end(p,nxt,sec) end end end end local today if year == true then year = nil end if not (year and month and day) then today = Date() end day = day and tonum(day,1,31,'day') or (month and 1 or today:day()) month = month and tonum(month,1,12,'month') or today:month() year = year and tonumber(year) or today:year() if year < 100 then -- two-digit year pivot around year < 2035 year = year + (year < 35 and 2000 or 1900) end hour = hour and tonum(hour,0,apm and 12 or 24,'hour') or 12 if apm == 'pm' then hour = hour + 12 end min = min and tonum(min,0,59) or 0 sec = sec and tonum(sec,0,60) or 0 --60 used to indicate leap second local res = Date {year = year, month = month, day = day, hour = hour, min = min, sec = sec} if tz then -- ISO 8601 UTC time local corrected = false if tz.h ~= 0 then res:add {hour = -tz.h}; corrected = true end if tz.m ~= 0 then res:add {min = -tz.m}; corrected = true end res.utc = true -- we're in UTC, so let's go local... if corrected then res = res:toLocal() end-- we're UTC! end return res end function parse_date (s) local ok, d = pcall(parse_date_unsafe,s) if not ok then -- error d = d:gsub('.-:%d+: ','') return nil, d else return d end end return Date
mit
thedraked/darkstar
scripts/globals/items/blackened_newt.lua
18
1560
----------------------------------------- -- ID: 4581 -- Item: Blackened Newt -- Food Effect: 180Min, All Races ----------------------------------------- -- Dexterity 4 -- Mind -3 -- Attack % 18 -- Attack Cap 60 -- Virus Resist 5 -- Charm Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4581); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -3); target:addMod(MOD_FOOD_ATTP, 18); target:addMod(MOD_FOOD_ATT_CAP, 60); target:addMod(MOD_VIRUSRES, 5); target:addMod(MOD_CHARMRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -3); target:delMod(MOD_FOOD_ATTP, 18); target:delMod(MOD_FOOD_ATT_CAP, 60); target:delMod(MOD_VIRUSRES, 5); target:delMod(MOD_CHARMRES, 5); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Northern_San_dOria/npcs/Aurege.lua
13
1981
----------------------------------- -- Area: Northern San d'Oria -- NPC: Aurege -- Type: Quest Giver NPC -- Starts Quest: Exit the Gambler -- @zone 231 -- @pos -156.253 11.999 253.691 ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) exitTheGambler = player:getQuestStatus(SANDORIA,EXIT_THE_GAMBLER); if (player:hasKeyItem(MAP_OF_KING_RANPERRES_TOMB)) then player:startEvent(0x0202); elseif (exitTheGambler == QUEST_COMPLETED) then player:startEvent(0x0204); else player:startEvent(0x0209); 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); exitTheGambler = player:getQuestStatus(SANDORIA,EXIT_THE_GAMBLER); if (exitTheGambler == QUEST_AVAILABLE) then player:addQuest(SANDORIA,EXIT_THE_GAMBLER); elseif (exitTheGambler == QUEST_COMPLETED and player:hasKeyItem(MAP_OF_KING_RANPERRES_TOMB) == false) then player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_KING_RANPERRES_TOMB); player:addKeyItem(MAP_OF_KING_RANPERRES_TOMB); player:addTitle(DAYBREAK_GAMBLER); player:addFame(SANDORIA,30); end end;
gpl-3.0
thedraked/darkstar
scripts/globals/effects/transcendency.lua
35
1814
----------------------------------- require("scripts/globals/status"); ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 9000); target:addMod(MOD_MP, 9000); target:addMod(MOD_REGEN, 300); target:addMod(MOD_REFRESH, 300); target:addMod(MOD_REGAIN, 500); target:addMod(MOD_STR, 900); target:addMod(MOD_DEX, 900); target:addMod(MOD_VIT, 900); target:addMod(MOD_AGI, 900); target:addMod(MOD_INT, 900); target:addMod(MOD_MND, 900); target:addMod(MOD_CHR, 900); target:addMod(MOD_ATT, 9000); target:addMod(MOD_DEF, 9000); target:addMod(MOD_ACC, 1000); target:addMod(MOD_EVA, 1000); target:addMod(MOD_MATT, 900); target:addMod(MOD_RACC, 1000); target:addMod(MOD_RATT, 9000); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 9000); target:delMod(MOD_MP, 9000); target:delMod(MOD_REGEN, 300); target:delMod(MOD_REFRESH, 300); target:delMod(MOD_REGAIN, 500); target:delMod(MOD_STR, 900); target:delMod(MOD_DEX, 900); target:delMod(MOD_VIT, 900); target:delMod(MOD_AGI, 900); target:delMod(MOD_INT, 900); target:delMod(MOD_MND, 900); target:delMod(MOD_CHR, 900); target:delMod(MOD_ATT, 9000); target:delMod(MOD_DEF, 9000); target:delMod(MOD_ACC, 1000); target:delMod(MOD_EVA, 1000); target:delMod(MOD_MATT, 900); target:delMod(MOD_RACC, 1000); target:delMod(MOD_RATT, 9000); end;
gpl-3.0
thedraked/darkstar
scripts/globals/items/bowl_of_zoni_broth.lua
18
1686
----------------------------------------- -- ID: 5618 -- Item: bowl_of_zoni_broth -- Food Effect: 3Hrs, All Races ----------------------------------------- -- HP 10 -- MP 10 -- Strength 1 -- Dexterity 1 -- Vitality 1 -- Agility 1 -- HP Recovered While Healing 1 -- MP Recovered 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,10800,5618); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_MP, 10); target:addMod(MOD_STR, 1); target:addMod(MOD_DEX, 1); target:addMod(MOD_VIT, 1); target:addMod(MOD_AGI, 1); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_MP, 10); target:delMod(MOD_STR, 1); target:delMod(MOD_DEX, 1); target:delMod(MOD_VIT, 1); target:delMod(MOD_AGI, 1); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
NPLPackages/main
script/kids/3DMapSystemApp/mcml/pe_editor.lua
1
68092
--[[ Title: all controls for editor display controls. Author(s): LiXizhi Date: 2008/2/15 Desc: pe:editor,pe:container(alignment="_ctt") pe:editor-divider, pe:editor-buttonset, pe:editor-button(DefaultButton=true), pe:editor-custom, form ---++ Button or input tag | *Property* | *Descriptions* | | type | "submit", "button", onclick event format is different for these two. | | onclick | onclick callback of type function(btnName,mcmlNode) if type is not "submit" or function(btnName, values, bindingContext), if type is "submit". document object is available inside the function. | | param[1-5] | additional params to be passed to onclick event. | | tooltip | mouse over tooltip | | enabled | "true" or "false", whether to enable the button. | | PasswordChar | "*", if one wants to display "*" for any text input| | DefaultButton | boolean, default to false. if true it is the default button when enter is pressed. If type is submit, it is the default button by default. | | textscale | float of text scale, usually 1.1-1.5 | | shadow | bool of shadow | | animstyle | int of ParaUIObject.animstyle | | textcolor | for single line editbox only. this is the text color. | | cursor | the mouse over cursor file | | onkeyup | onkeyup callback of type function(name,mcmlNode) if type is "text"| | CaretColor | the caret color of the edit box, only used when type is "text" and it is single lined | | autofocus | if true, the text input will automatically get key focus. | | uiname | the low level ui name. so that if unique, we will be able to get it via ParaUI.GetUIObject(uiname) | | hotkey | the virtual key name such as "DIK_A, DIK_F1, DIK_SPACE" | | href | if there is no onclick event then this is same as <a> tag | | spacing | for text or button control. | button css property | background-rotation | [-3.14, 3.14]| | padding | spacing between the foreground image and background2 image | | spacing | spacing between the text and background, mostly used in auto sized button | | text-align | "left","right", default to center aligned | | text-valign | "top", "center", default to center aligned vertically. Note text-align must be specified in order for this attribute to take effect. | | text-noclip | true, false, default to false. whether text should be cliped. Note text-align must be specified in order for this attribute to take effect. | | text-singleline | true, false, default to true. whether text should be single lined. Note text-align must be specified in order for this attribute to take effect. | | text-wordbreak | default to false. | | text-offset-x | offset the text inside the button | | text-offset-y | offset the text inside the button | | min-width | min-width of the button. if the button text is long, the actual width may be bigger. | | max-width | max-width of the button. force using left align if text is too long. | Here is a sample of a button with padding <verbatim> <input type="button" name="btn1" value="hello" tooltip="button with padding and background2" style="padding:10px;background2:url(Texture/alphadot.png);" /> </verbatim> __note__: if button type property is "submit", it must be inside a form tag, in order for its bindingcontext and values to take effect in its onclick event handler. ---++ pe:container and pe:editor tags only these tags support css right float and css vertical alignment, as well as alignment property e.g. 1. style="float:right;vertical-align: bottom" is similar to "_rb" or right bottom in NPL. And it does not consume parent space. 1. style="float:left;vertical-align: bottom" is similar to "_lb" or right bottom in NPL. And it does not consume parent space. 1. style="float:right;" is similar to "_rt" or right top in NPL. And it does not consume parent space. 1. alignment="_ctt", where the alignment property supports all NPL alignment types 1. relation and visible style attributes are supported. | *Property* | *Descriptions* | | ClickThrough | true to click through | | onclick | function(name, mcmlNode) end | | onsize | this is useful to detect size change of windows. | | SelfPaint | whether it will paint on its own render target. name attribute must be specified. | | oncreate | function(name, mcmlNode) end, called when container is just created. | | for | function(name, mcmlNode) end | | valign | "center" which will vertically align using the used height of inner controls. userful if the inner text height is unknown. | ---++ form tag it is similar to html form tag except that the target property recoginizes mcml targets. *target property* <br/> It may be "_self", "_blank", "_mcmlblank", "[iframename]". if this property is specified, the href will be regarded as mcml page file even if it begins with http. iframename can be any iframe control name, where the href mcml page will be opened. if it is "_self", it will be opened in the current page control. if it is "_mcmlblank", it will be opened in a new popup mcml window. ---++ textarea | *Property* | *Descriptions* | | rows | number of rows | | endofline | we shall replace all occurances of endofline text inside inner text with "\n". Commonly used endofline is ";" and "<br/>" | | WordWrap | boolean, default to "false", whether use word wrapping, only valid when SingleLineEdit is true| | SingleLineEdit | boolean, default to "false", whether to use one line only for editing. It is possible to edit in one line and show in multiple line when WordWrap is true. | | enable_ime | false to disable ime | | syntax_map | text highlighter to use. currently only "NPL","PureText" are supported. default to nil. | | EmptyText | empty text to display such as "click to enter text ..." | | VerticalScrollBarStep | | | fontsize | font size to use for multiline text. | | lineheight | lineheight | | css.lineheight | line height for multiline text. | | spacing | for text or button control. | | UseSystemControl | true to use advanced multiple line edit box in new system control | | OnMouseOverWordChange | called when user mouse over a given word, function(word, line:Unistring, from, to). this is only implemented for bUseSystemControl==true. | | OnRightClick | called when user right click on text, function(event). this is only implemented for bUseSystemControl==true. | | InputMethodEnabled | only valid when UseSystemControl is true. default to true | use the lib: ------------------------------------------------------- NPL.load("(gl)script/kids/3DMapSystemApp/mcml/pe_editor.lua"); ------------------------------------------------------- ]] NPL.load("(gl)script/kids/3DMapSystemApp/mcml/pe_hotkey.lua"); local hotkey_manager = commonlib.gettable("Map3DSystem.mcml_controls.hotkey_manager"); NPL.load("(gl)script/ide/TooltipHelper.lua"); local mcml_controls = commonlib.gettable("Map3DSystem.mcml_controls"); ----------------------------------- -- pe:editor and pe:container control ----------------------------------- local pe_editor = commonlib.gettable("Map3DSystem.mcml_controls.pe_editor"); -- all temp bindings: a mapping from pe_editor instance name to its binding object. pe_editor.allBindings = {}; -- create a new binding object with an editor instance name. function pe_editor.NewBinding(instName, bindingContext) bindingContext = bindingContext or commonlib.BindingContext:new(); bindingContext.editorInstName = instName; bindingContext.values = bindingContext.values or {}; pe_editor.allBindings[instName] = bindingContext; return bindingContext; end -- get the binding context. the bindingContext.values is the data source, which is a table of name value pairs retrieved from the sub controls. function pe_editor.GetBinding(instName) return pe_editor.allBindings[instName]; end -- create editor or pe_container function pe_editor.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height,style, parentLayout) if(mcmlNode:GetAttribute("display") == "none") then return end local instName = mcmlNode:GetAttributeWithCode("uiname", nil, true) or mcmlNode:GetInstanceName(rootName); if(mcmlNode.name == "pe:editor") then -- create a new binding context whenever a pe_editor is met. bindingContext = pe_editor.NewBinding(instName, bindingContext); bindingContext.formNode_ = mcmlNode; end local css = mcmlNode:GetStyle(mcml_controls.pe_css.default[mcmlNode.name] or Map3DSystem.mcml_controls.pe_html.css[mcmlNode.name]) or {}; local alignment = mcmlNode:GetAttributeWithCode("alignment", nil, true); if(not alignment) then alignment = "_lt"; if(css.float == "right") then if(css["vertical-align"] and css["vertical-align"] == "bottom") then alignment = "_rb"; else alignment = "_rt"; end else if(css["vertical-align"] and css["vertical-align"] == "bottom") then alignment = "_lb"; end end end local padding_left, padding_top, padding_bottom, padding_right = (css["padding-left"] or css["padding"] or 0),(css["padding-top"] or css["padding"] or 0), (css["padding-bottom"] or css["padding"] or 0),(css["padding-right"] or css["padding"] or 0); local margin_left, margin_top, margin_bottom, margin_right = (css["margin-left"] or css["margin"] or 0),(css["margin-top"] or css["margin"] or 0), (css["margin-bottom"] or css["margin"] or 0),(css["margin-right"] or css["margin"] or 0); local availWidth, availHeight = parentLayout:GetPreferredSize(); local maxWidth, maxHeight = parentLayout:GetMaxSize(); local width, height = mcmlNode:GetAttribute("width"), mcmlNode:GetAttribute("height"); if(width) then css.width = tonumber(string.match(width, "%d+")); if(css.width and string.match(width, "%%$")) then css.width=math.floor((maxWidth-margin_left-margin_right)*css.width/100); if(availWidth<(css.width+margin_left+margin_right)) then css.width=availWidth-margin_left-margin_right; end if(css.width<=0) then css.width = nil; end end end if(height) then css.height = tonumber(string.match(height, "%d+")); if(css.height and string.match(height, "%%$")) then css.height=math.floor((maxHeight-margin_top-margin_bottom)*css.height/100); if(availHeight<(css.height+margin_top+margin_bottom)) then css.height=availHeight-margin_top-margin_bottom; end if(css.height<=0) then css.height = nil; end end end -- whether this control takes up space local bUseSpace; if(css.float) then if(css.width) then if(availWidth<(css.width+margin_left+margin_right)) then parentLayout:NewLine(); end end else parentLayout:NewLine(); end local myLayout = parentLayout:clone(); myLayout:ResetUsedSize(); if(css.position == "absolute") then -- absolute positioning in parent myLayout:SetPos(css.left, css.top); width,height = myLayout:GetSize(); elseif(css.position == "relative") then -- relative positioning in next render position. myLayout:OffsetPos(css.left, css.top); width,height = myLayout:GetSize(); else left, top, width, height = myLayout:GetPreferredRect(); myLayout:SetPos(left,top); bUseSpace = true; end if(css.width) then myLayout:IncWidth(left+margin_left+margin_right+css.width-width) end if(css.height) then myLayout:IncHeight(top+margin_top+margin_bottom+css.height-height) end -- for inner control preferred size myLayout:OffsetPos(margin_left+padding_left, margin_top+padding_top); myLayout:IncWidth(-margin_right-padding_right) myLayout:IncHeight(-margin_bottom-padding_bottom) -- create editor container local parent_left, parent_top, parent_width, parent_height = myLayout:GetPreferredRect(); parent_left = parent_left-padding_left; parent_top = parent_top-padding_top; parent_width = parent_width + padding_right parent_height = parent_height + padding_bottom local _this if(alignment == "_fi") then left, top, width, height = parentLayout:GetPreferredRect(); _this = ParaUI.CreateUIObject("container", instName, alignment, parent_left, parent_top, width-(parent_width), height-(parent_height)) else _this = ParaUI.CreateUIObject("container", instName, alignment, parent_left, parent_top, parent_width-parent_left,parent_height-parent_top) end _parent:AddChild(_this); _parent = _this; if(mcmlNode:GetAttributeWithCode("SelfPaint", nil)) then _this:SetField("SelfPaint", true); end mcmlNode.uiobject_id = _this.id; --replaced by leio:2012/08/15 --if(mcmlNode:GetBool("visible", true) == false) then --_this.visible = false; --end local visible = mcmlNode:GetAttributeWithCode("visible", nil, true); visible = tostring(visible); if(visible and visible == "false")then _this.visible = false; end if(mcmlNode:GetBool("enabled", true) == false) then _this.enabled = false; end if(mcmlNode:GetNumber("zorder")) then _this.zorder = mcmlNode:GetNumber("zorder"); end local bClickThrough = mcmlNode:GetAttributeWithCode("ClickThrough") if( bClickThrough==true or bClickThrough == "true") then _this:SetField("ClickThrough", true); end if(css["background-color"]) then css.background = css.background or "Texture/whitedot.png"; end if(css.background) then _this.background = css.background; if(css["background-color"]) then _guihelper.SetUIColor(_this, css["background-color"]); end if(css["colormask"]) then _guihelper.SetColorMask(_this, css["colormask"]); end end -- create contentLayout, so that they are all relative to the new container. local contentLayout = myLayout:clone(); contentLayout:OffsetPos(-parent_left, -parent_top); contentLayout:IncHeight(-parent_top) contentLayout:IncWidth(-parent_left) contentLayout:SetUsedSize(contentLayout:GetAvailablePos()) -- create each child node. pe_editor.refresh(rootName, mcmlNode, bindingContext, _parent, {color = css.color, ["font-family"] = css["font-family"], ["font-size"]=css["font-size"], ["base-font-size"]=css["base-font-size"], ["font-weight"] = css["font-weight"], ["text-align"] = css["text-align"],["line-height"] = css["line-height"], ["text-shadow"] = css["text-shadow"], ["shadow-color"]=css["shadow-color"], ["shadow-quality"]=css["shadow-quality"] }, contentLayout) -- calculate used size local width, height = contentLayout:GetUsedSize(); if(mcmlNode:GetAttribute("valign") == "center") then local _, used_height = contentLayout:GetUsedSize(); local _, parent_height = contentLayout:GetSize(); local offset_y = math.floor((parent_height - used_height)*0.5); if(offset_y > 0) then width = width + offset_y; _parent.y = _parent.y + offset_y; end end myLayout:AddObject(width-padding_left, height-padding_top); local left, top = parentLayout:GetAvailablePos(); width, height = myLayout:GetUsedSize() width = width + padding_right + margin_right height = height + padding_bottom + margin_bottom if(css.width) then width = left + css.width + margin_left+margin_right; end if(css.height) then height = top + css.height + margin_top+margin_bottom; end -- resize container if(alignment ~= "_fi") then _parent.height = height-top-margin_top-margin_bottom; _parent.width = width-left-margin_right-margin_left; end if(alignment == "_lt") then if(bUseSpace) then parentLayout:AddObject(width-left, height-top); if(not css.float) then parentLayout:NewLine(); end end elseif(alignment == "_rt") then _parent.x = - _parent.width- margin_left - margin_right; elseif(alignment == "_rb") then _parent.x = - _parent.width- margin_left - margin_right; _parent.y = - _parent.height- margin_top - margin_bottom; elseif(alignment == "_lb") then _parent.y = - _parent.height- margin_top - margin_bottom; end if(css.visible and css.visible== "false") then _parent.visible = false; end -- handle onclick event local onclick; local onclick_for; local ontouch; onclick = mcmlNode:GetString("onclick"); if(onclick == "") then onclick = nil; end onclick_for = mcmlNode:GetString("for"); if(onclick_for == "") then onclick_for = nil; end ontouch = mcmlNode:GetString("ontouch"); if(ontouch == "") then ontouch = nil; end local tooltip = mcmlNode:GetAttributeWithCode("tooltip",nil,true); if(tooltip and tooltip~="") then local tooltip_page = string.match(tooltip or "", "page://(.+)"); local tooltip_static_page = string.match(tooltip or "", "page_static://(.+)"); if(tooltip_page) then CommonCtrl.TooltipHelper.BindObjTooltip(mcmlNode.uiobject_id, tooltip_page, mcmlNode:GetNumber("tooltip_offset_x"), mcmlNode:GetNumber("tooltip_offset_y"), mcmlNode:GetNumber("show_width"),mcmlNode:GetNumber("show_height"),mcmlNode:GetNumber("show_duration"), mcmlNode:GetBool("enable_tooltip_hover"), nil, mcmlNode:GetBool("tooltip_is_interactive"), mcmlNode:GetBool("is_lock_position"), mcmlNode:GetBool("use_mouse_offset"), mcmlNode:GetNumber("screen_padding_bottom"), nil, nil, nil, mcmlNode:GetBool("offset_ctrl_width"), mcmlNode:GetBool("offset_ctrl_height")); elseif(tooltip_static_page) then CommonCtrl.TooltipHelper.BindObjTooltip(mcmlNode.uiobject_id, tooltip_static_page, mcmlNode:GetNumber("tooltip_offset_x"), mcmlNode:GetNumber("tooltip_offset_y"), mcmlNode:GetNumber("show_width"),mcmlNode:GetNumber("show_height"),mcmlNode:GetNumber("show_duration"),mcmlNode:GetBool("enable_tooltip_hover"),mcmlNode:GetBool("click_through")); else _parent.tooltip = tooltip; end end local btnName = mcmlNode:GetAttributeWithCode("name") if(onclick_for or onclick or ontouch) then -- tricky: we will just prefetch any params with code that may be used in the callback for i=1,5 do if(not mcmlNode:GetAttributeWithCode("param"..i)) then break; end end if(onclick_for or onclick) then _parent:SetScript("onmouseup", Map3DSystem.mcml_controls.pe_editor_button.on_click, mcmlNode, nil, bindingContext, btnName); end if(ontouch) then _parent:SetScript("ontouch", Map3DSystem.mcml_controls.pe_editor_button.on_touch, mcmlNode, nil, bindingContext, btnName); end end local oncreate_callback = mcmlNode:GetAttributeWithCode("oncreate"); if(oncreate_callback) then Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, oncreate_callback, btnName, mcmlNode) end local onsize_callback = mcmlNode:GetAttributeWithCode("onsize"); if(onsize_callback) then _parent:SetScript("onsize", function(uiobj) Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onsize_callback, btnName, mcmlNode, uiobj) end) end local candrag = mcmlNode:GetAttributeWithCode("candrag"); if(candrag==true or candrag == "true") then _parent.candrag = true; local onDragBegin_callback = mcmlNode:GetAttributeWithCode("ondragbegin"); _parent:SetScript("ondragbegin", function(uiobj) Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onDragBegin_callback, btnName, mcmlNode, uiobj) end) local onDragEnd_callback = mcmlNode:GetAttributeWithCode("ondragend"); _parent:SetScript("ondragend", function(uiobj) Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onDragEnd_callback, btnName, mcmlNode, uiobj) end) local onDragEnd_callback = mcmlNode:GetAttributeWithCode("ondragmove"); _parent:SetScript("ondragmove", function(uiobj) Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onDragEnd_callback, btnName, mcmlNode, uiobj) end) end end -- refresh the inner controls. function pe_editor.refresh(rootName, mcmlNode, bindingContext, _parent, style, contentLayout) -- clear this container _parent:RemoveAll(); -- create all child nodes UI controls. local labelwidth = mcmlNode:GetNumber("labelwidth"); local _, childnode; for childnode in mcmlNode:next() do local left, top, width, height = contentLayout:GetPreferredRect(); if((type(childnode) == "table") and (childnode.name == "pe:editor-text" or childnode.name == "pe:editor-custom" or childnode.name == "pe:editor-buttonset" or childnode.name == "pe:editor-divider"))then local lableText = childnode:GetAttribute("label"); if(lableText and lableText~="") then local _this = ParaUI.CreateUIObject("text", "", "_lt", left, top+3, labelwidth, 16) --_guihelper.SetUIFontFormat(_this, 2 + 32 + 256); -- align to right and single lined. _this.text = lableText; _parent:AddChild(_this); end contentLayout:NewLine(); local innerLayout = contentLayout:clone(); innerLayout:OffsetPos(labelwidth, nil); left, top, width, height = innerLayout:GetPreferredRect(); Map3DSystem.mcml_controls.create(rootName, childnode, bindingContext, _parent, left, top, width, height, style, innerLayout) contentLayout:AddChildLayout(innerLayout); contentLayout:NewLine(); else Map3DSystem.mcml_controls.create(rootName, childnode, bindingContext, _parent, left, top, width, height, style, contentLayout) end end end ----------------------------------- -- HTML <form> control ----------------------------------- local pe_form = {}; Map3DSystem.mcml_controls.pe_form = pe_form; -- similar to HTML <form> function pe_form.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height,style, parentLayout) if(mcmlNode:GetAttribute("display") == "none") then return end local instName = mcmlNode:GetInstanceName(rootName); -- create a new binding context whenever a pe_editor is met. bindingContext = pe_editor.NewBinding(instName, bindingContext); bindingContext.formNode_ = mcmlNode; -- create each child node. local childnode; for childnode in mcmlNode:next() do local left, top, width, height = parentLayout:GetPreferredRect(); Map3DSystem.mcml_controls.create(rootName,childnode, bindingContext, _parent, left, top, width, height, style, parentLayout) end end ----------------------------------- -- pe:editor-custom control ----------------------------------- local pe_editor_custom = {}; Map3DSystem.mcml_controls.pe_editor_custom = pe_editor_custom; -- increase the top by height. function pe_editor_custom.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) if(mcmlNode:GetAttribute("display") == "none") then return end parentLayout:NewLine(); local myLayout = parentLayout:clone(); myLayout:ResetUsedSize(); local childnode; for childnode in mcmlNode:next() do local left, top, width, height = myLayout:GetPreferredRect(); Map3DSystem.mcml_controls.create(rootName, childnode, bindingContext, _parent, left, top, width, height, style, myLayout) end myLayout:NewLine(); local left, top = parentLayout:GetAvailablePos(); local width, height = myLayout:GetUsedSize(); width, height = width-left, height -top; local minHeight = mcmlNode:GetNumber("height"); if(minHeight>height) then height = minHeight; end parentLayout:AddObject(width, height); parentLayout:NewLine(); end ----------------------------------- -- pe:editor-buttonset control ----------------------------------- local pe_editor_buttonset = commonlib.gettable("Map3DSystem.mcml_controls.pe_editor_buttonset"); -- increment left by the width of this button. Button width is sized according to text length. -- the buttonset control takes up 26 pixels in height function pe_editor_buttonset.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) parentLayout:NewLine(); local myLayout = parentLayout:clone(); myLayout:ResetUsedSize(); local css = mcmlNode:GetStyle(); -- search any buttons local childnode; for childnode in mcmlNode:next("pe:editor-button") do local left, top, width, height = myLayout:GetPreferredRect(); Map3DSystem.mcml_controls.create(rootName, childnode, bindingContext, _parent, left, top, width, height, nil, myLayout) end myLayout:NewLine(); local left, top = parentLayout:GetAvailablePos(); local width, height = myLayout:GetUsedSize(); width, height = width-left, height -top; parentLayout:AddObject(width, height); parentLayout:NewLine(); if(css and css.background) then local _this=ParaUI.CreateUIObject("button","s","_lt", left, top, width, height); _this.background = css.background; _this.enabled = false; if(css["background-color"]) then _guihelper.SetUIColor(_this, css["background-color"]); else _guihelper.SetUIColor(_this, "255 255 255 255"); end _parent:AddChild(_this); _this:BringToBack(); end end ----------------------------------- -- pe:editor-button control ----------------------------------- local pe_editor_button = commonlib.gettable("Map3DSystem.mcml_controls.pe_editor_button"); -- a mapping from button name to mcml node instance. pe_editor_button.button_instances = {}; -- the button control takes up 26 pixels in height, and button itself is 22 pixel height and has a default spacing of 5. function pe_editor_button.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) if(mcmlNode:GetAttribute("display") == "none") then return end local buttonText = mcmlNode:GetString("text") or mcmlNode:GetAttributeWithCode("value", nil, true) or mcmlNode:GetInnerText(); local css = mcmlNode:GetStyle(mcml_controls.pe_css.default["pe:editor-button"] or Map3DSystem.mcml_controls.pe_html.css["pe:editor-button"]); local textscale = mcmlNode:GetNumber("textscale") or css.textscale; -- -- for font: font-family: Arial; font-size: 14pt;font-weight: bold; -- local font; local scale; if(css and (css["font-family"] or css["font-size"] or css["font-weight"]))then local font_family = css["font-family"] or "System"; -- this is tricky. we convert font size to integer, and we will use scale if font size is either too big or too small. local font_size = math.floor(tonumber(css["font-size"] or 12)); local max_font_size = 50; local min_font_size = 11; if(font_size>max_font_size) then font_size = max_font_size; end if(font_size<min_font_size) then font_size = min_font_size; end local font_weight = css["font-weight"] or "norm"; font = string.format("%s;%d;%s", font_family, font_size, font_weight); end local margin_left, margin_top, margin_bottom, margin_right = (css["margin-left"] or css["margin"] or 0),(css["margin-top"] or css["margin"] or 0), (css["margin-bottom"] or css["margin"] or 0),(css["margin-right"] or css["margin"] or 0); local maxWidth, maxHeight = parentLayout:GetMaxSize(); local width, height = mcmlNode:GetAttribute("width"), mcmlNode:GetAttribute("height"); if(width) then css.width = tonumber(string.match(width, "%d+")); if(css.width and string.match(width, "%%$")) then if(css.position == "screen") then css.width = ParaUI.GetUIObject("root").width * css.width/100; else local availWidth, availHeight = parentLayout:GetPreferredSize(); css.width=math.floor((maxWidth-margin_left-margin_right)*css.width/100); if(availWidth<(css.width+margin_left+margin_right)) then css.width=availWidth-margin_left-margin_right; end if(css.width<=0) then css.width = nil; end end end end if(height) then css.height = tonumber(string.match(height, "%d+")); if(css.height and string.match(height, "%%$")) then if(css.position == "screen") then css.height = ParaUI.GetUIObject("root").height * css.height/100; else css.height=math.floor((maxHeight-margin_top-margin_bottom)*css.height/100); local availWidth, availHeight = parentLayout:GetPreferredSize(); if(availHeight<(css.height+margin_top+margin_bottom)) then css.height=availHeight-margin_top-margin_bottom; end if(css.height<=0) then css.height = nil; end end end end local buttonWidth; local height = css.height or 22; if(css.width) then buttonWidth = css.width; else buttonWidth = _guihelper.GetTextWidth(buttonText, font) * (textscale or 1); local spacing = mcmlNode:GetNumber("spacing") or css.spacing; if(spacing) then buttonWidth = buttonWidth + spacing * 2; else buttonWidth = buttonWidth + 5; end if(css["min-width"]) then local min_width = css["min-width"]; if(min_width and min_width>buttonWidth) then buttonWidth = min_width; end elseif(css["max-width"]) then local max_width = css["max-width"]; if(max_width and max_width<buttonWidth) then if((buttonWidth - max_width) > 20) then css["text-align"] = css["text-align"] or "left"; end buttonWidth = max_width; end end end if(css.padding) then buttonWidth = buttonWidth + css.padding*2; height = height + css.padding*2; end width = parentLayout:GetPreferredSize(); if((buttonWidth+margin_left+margin_right)>width) then parentLayout:NewLine(); width = parentLayout:GetMaxSize(); if(buttonWidth>width and not css.width) then buttonWidth = width end end left, top = parentLayout:GetAvailablePos(); local align = mcmlNode:GetAttribute("align") or css.align; if(align and align~="left") then local max_width = buttonWidth; local left, top, right, bottom = parentLayout:GetAvailableRect(); -- align at center. if(align == "center") then margin_left = (maxWidth - max_width)/2 elseif(align == "right") then margin_left = right - max_width - margin_right - left; end end -- align at center. local valign = mcmlNode:GetAttribute("valign"); if(valign and valign~="top") then local max_height = css.height; local left, top, right, bottom = myLayout:GetAvailableRect(); if(valign == "center") then height = height + (maxHeight - max_height)/2 elseif(valign == "bottom") then height = bottom - max_height - margin_bottom; end end local instName = mcmlNode:GetAttributeWithCode("uiname", nil, true) or mcmlNode:GetInstanceName(rootName); local _this = ParaUI.CreateUIObject("button", instName or "b", "_lt", left+margin_left, top+margin_top, buttonWidth, height) mcmlNode.uiobject_id = _this.id; -- keep the uiobject's reference id if(css.padding) then _this:SetField("Padding", css.padding) end local icon = mcmlNode:GetAttribute("icon"); local icon_obj if icon then local icon_width = tonumber(mcmlNode:GetAttribute("icon_width")) or 0 local icon_height = tonumber(mcmlNode:GetAttribute("icon_height")) or 0 local icon_off_x = tonumber(mcmlNode:GetAttribute("icon_off_x")) or 0 local icon_off_y = tonumber(mcmlNode:GetAttribute("icon_off_y")) or 0 local icon_x = left + margin_left + buttonWidth/2 - icon_width/2 + icon_off_x local icon_y = top+ margin_top + height/2 - icon_height/2 + icon_off_y local icon_name = instName and instName .. "_icon" or "b_icon" icon_obj = ParaUI.CreateUIObject("button", icon_name, "_lt", icon_x, icon_y, icon_width, icon_height) _guihelper.SetUIColor(icon_obj, "255 255 255 255"); -- icon_obj.zorder = 10 icon_obj.enabled = false icon_obj.background = icon end if(css["text-offset-x"]) then _this:SetField("TextOffsetX", tonumber(css["text-offset-x"]) or 0) end if(css["text-offset-y"]) then _this:SetField("TextOffsetY", tonumber(css["text-offset-y"]) or 0) end if(buttonText and buttonText~="") then _this.text = buttonText; end if(font) then _this.font = font; end local bg = mcmlNode:GetAttributeWithCode("background"); if(bg or css.background) then local replace_bg = mcmlNode:GetAttributeWithCode("Replace_BG"); if(replace_bg)then _this.background = replace_bg; else _this.background = bg or css.background; end local normal_bg = mcmlNode:GetAttributeWithCode("Normal_BG") or css.Normal_BG; local mouseover_bg = mcmlNode:GetAttributeWithCode("MouseOver_BG") or css.MouseOver_BG; local pressed_bg = mcmlNode:GetAttributeWithCode("Pressed_BG") or css.Pressed_BG; local disabled_bg = mcmlNode:GetAttributeWithCode("Disabled_BG") or normal_bg or css.background; if(normal_bg and mouseover_bg and pressed_bg and disabled_bg) then _guihelper.SetVistaStyleButton3(_this, normal_bg, mouseover_bg, disabled_bg, pressed_bg); elseif(normal_bg and mouseover_bg and pressed_bg == nil) then _guihelper.SetVistaStyleButton3(_this, normal_bg, mouseover_bg, disabled_bg, nil); end if(css["background-color"]) then _guihelper.SetUIColor(_this, css["background-color"]); end if(css["background-rotation"]) then _this.rotation = tonumber(css["background-rotation"]) end if(css.color) then _guihelper.SetButtonFontColor(_this, css.color, css.color2); end else if(pe_editor.default_button_offset_y) then _this:SetField("TextOffsetY", pe_editor.default_button_offset_y); end end if(css.background2) then local bg2_color; if(css["background2-color"]) then bg2_color = css["background2-color"] end _guihelper.SetVistaStyleButton(_this, nil, css.background2, bg2_color); end local alignFormat = 1; -- center align if(css["text-align"]) then if(css["text-align"] == "right") then alignFormat = 2; elseif(css["text-align"] == "left") then alignFormat = 0; end end if(css["text-singleline"] ~= "false") then alignFormat = alignFormat + 32; else if(css["text-wordbreak"] == "true") then alignFormat = alignFormat + 16; end end if(css["text-noclip"] ~= "false") then alignFormat = alignFormat + 256; end if(css["text-valign"] ~= "top") then alignFormat = alignFormat + 4; end _guihelper.SetUIFontFormat(_this, alignFormat) if(mcmlNode:GetAttribute("enabled")) then if(mcmlNode:GetBool("enabled") == nil) then _this.enabled = mcmlNode:GetAttributeWithCode("enabled"); else _this.enabled = mcmlNode:GetBool("enabled"); end end local visible = mcmlNode:GetAttributeWithCode("visible", nil, true); if(visible~=true and visible and tostring(visible) == "false")then _this.visible = false; end local zorder = mcmlNode:GetNumber("zorder") or css.zorder; if(zorder) then _this.zorder = zorder; end local href = mcmlNode:GetAttributeWithCode("href"); local onclick = mcmlNode.onclickscript or mcmlNode:GetString("onclick"); if(onclick == "")then onclick = nil; end local onclick_for = mcmlNode:GetString("for"); if(onclick_for == "") then onclick_for = nil; end local ontouch = mcmlNode:GetString("ontouch"); if(ontouch == "")then ontouch = nil; end local ondoubleclick = mcmlNode:GetString("ondoubleclick"); if(ondoubleclick == "")then ondoubleclick = nil end local btnName if(href) then if(href ~= "#") then href = mcmlNode:GetAbsoluteURL(href); end -- open in current window -- looking for an iframe in the ancestor of this node. local pageCtrl = mcmlNode:GetPageCtrl(); if(pageCtrl) then local pageCtrlName = pageCtrl.name; if(href:match("^http://")) then -- TODO: this may be a security warning _this.onclick = string.format([[;ParaGlobal.ShellExecute("open", %q, "", "", 1);]], href); else _this.onclick = string.format(";Map3DSystem.mcml_controls.pe_a.OnClickHRefToTarget(%q, %q)", href, pageCtrlName); end else log("warning: mcml <input type=\"button\"> can not find any iframe in its ancestor node to which the target url can be loaded\n"); end elseif(onclick or onclick_for or ontouch or ondoubleclick) then btnName = mcmlNode:GetAttributeWithCode("name",nil,true) -- tricky: we will just prefetch any params with code that may be used in the callback for i=1,5 do if(not mcmlNode:GetAttributeWithCode("param"..i)) then break; end end local hotkey = mcmlNode:GetAttributeWithCode("hotkey", nil, true); if(hotkey and onclick) then hotkey_manager.register_key(hotkey, function(virtual_key) local uiobj; if(mcmlNode.uiobject_id) then uiobj = ParaUI.GetUIObject(mcmlNode.uiobject_id); if(uiobj and uiobj:IsValid()) then return pe_editor_button.on_click(uiobj, mcmlNode, instName, bindingContext, btnName); end end end, mcmlNode.uiobject_id); end if(onclick or onclick_for) then _this:SetScript("onclick", pe_editor_button.on_click, mcmlNode, instName, bindingContext, btnName); elseif(ondoubleclick) then _this:SetScript("onclick", pe_editor_button.on_double_click, mcmlNode, instName, bindingContext, btnName); elseif(ontouch) then _this:SetScript("ontouch", pe_editor_button.on_touch, mcmlNode, instName, bindingContext, btnName); end end local onmouseenter = mcmlNode:GetString("onmouseenter"); if(onmouseenter and onmouseenter ~= "")then btnName = btnName or mcmlNode:GetAttributeWithCode("name",nil,true) _this:SetScript("onmouseenter", pe_editor_button.onmouseenter, mcmlNode, instName, bindingContext, btnName); end local onmouseleave = mcmlNode:GetString("onmouseleave"); if(onmouseleave and onmouseleave ~= "")then btnName = btnName or mcmlNode:GetAttributeWithCode("name",nil,true) _this:SetScript("onmouseleave", pe_editor_button.onmouseleave, mcmlNode, instName, bindingContext, btnName); end local force_ui_name = mcmlNode:GetAttributeWithCode("force_ui_name"); if(force_ui_name) then _this.name = force_ui_name; end -- create a default button for the container to allow enter in text input to directly invoke submit call local btnType = mcmlNode:GetString("type"); if(btnType == "submit") then _this:SetDefault(true); end local tooltip = mcmlNode:GetAttributeWithCode("tooltip",nil,true); if(tooltip and tooltip ~= "")then local tooltip_page = string.match(tooltip or "", "page://(.+)"); local tooltip_static_page = string.match(tooltip or "", "page_static://(.+)"); if(tooltip_page) then CommonCtrl.TooltipHelper.BindObjTooltip(mcmlNode.uiobject_id, tooltip_page, mcmlNode:GetNumber("tooltip_offset_x"), mcmlNode:GetNumber("tooltip_offset_y"), mcmlNode:GetNumber("show_width"),mcmlNode:GetNumber("show_height"),mcmlNode:GetNumber("show_duration"), nil, nil, nil, mcmlNode:GetBool("is_lock_position"), mcmlNode:GetBool("use_mouse_offset"), mcmlNode:GetNumber("screen_padding_bottom"), nil, nil, nil, mcmlNode:GetBool("offset_ctrl_width"), mcmlNode:GetBool("offset_ctrl_height")); elseif(tooltip_static_page) then CommonCtrl.TooltipHelper.BindObjTooltip(mcmlNode.uiobject_id, tooltip_static_page, mcmlNode:GetNumber("tooltip_offset_x"), mcmlNode:GetNumber("tooltip_offset_y"), mcmlNode:GetNumber("show_width"),mcmlNode:GetNumber("show_height"),mcmlNode:GetNumber("show_duration"),mcmlNode:GetBool("enable_tooltip_hover"),mcmlNode:GetBool("click_through"),mcmlNode:GetBool("is_tool_tip_click_enabled"), mcmlNode:GetBool("is_lock_position")); else _this.tooltip = tooltip; end end local animstyle = mcmlNode:GetNumber("animstyle") or css.animstyle if(animstyle) then _this.animstyle = animstyle; end if(textscale) then _this.textscale = mcmlNode:GetNumber("textscale") or css.textscale; end if(mcmlNode:GetBool("shadow") or css["text-shadow"]) then _this.shadow = true; if(css["shadow-quality"]) then _this:SetField("TextShadowQuality", tonumber(css["shadow-quality"]) or 0); end if(css["shadow-color"]) then _this:SetField("TextShadowColor", _guihelper.ColorStr_TO_DWORD(css["shadow-color"])); end end if(mcmlNode:GetBool("alwaysmouseover")) then _this:SetField("AlwaysMouseOver", true); end _parent:AddChild(_this); if icon_obj then _parent:AddChild(icon_obj); end if(mcmlNode:GetAttribute("DefaultButton")) then _this:SetDefault(true); end local cursor_file = mcmlNode:GetAttributeWithCode("cursor"); if(cursor_file and cursor_file~="") then _this.cursor = cursor_file; end if(css.position ~= "relative") then parentLayout:AddObject(buttonWidth+margin_left+margin_right, margin_top+margin_bottom+height); end end -- @param instName: obsoleted field. can be nil. function pe_editor_button.onmouseenter(uiobj, mcmlNode, instName, bindingContext, buttonName) if(not mcmlNode or not uiobj) then return end local onmouseenter = mcmlNode:GetString("onmouseenter"); if(onmouseenter == "")then onmouseenter = nil; end local result; if(onmouseenter) then -- the callback function format is function(buttonName, mcmlNode, touchEvent) end result = Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onmouseenter, buttonName, mcmlNode) end return result; end -- @param instName: obsoleted field. can be nil. function pe_editor_button.onmouseleave(uiobj, mcmlNode, instName, bindingContext, buttonName) if(not mcmlNode or not uiobj) then return end local onmouseleave = mcmlNode:GetString("onmouseleave"); if(onmouseleave == "")then onmouseleave = nil; end local result; if(onmouseleave) then -- the callback function format is function(buttonName, mcmlNode, touchEvent) end result = Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onmouseleave, buttonName, mcmlNode) end return result; end -- @param instName: obsoleted field. can be nil. function pe_editor_button.on_touch(uiobj, mcmlNode, instName, bindingContext, buttonName) if(not mcmlNode or not uiobj) then return end local ontouch = mcmlNode:GetString("ontouch"); if(ontouch == "")then ontouch = nil; end local result; if(ontouch) then -- the callback function format is function(buttonName, mcmlNode, touchEvent) end result = Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, ontouch, buttonName, mcmlNode, msg) end return result; end function pe_editor_button.on_double_click(uiobj, mcmlNode, instName, bindingContext, buttonName) if(not mcmlNode or not uiobj) then return end local ondoubleclick = mcmlNode:GetString("ondoubleclick"); if pe_editor_button.curDoubleClickInstName == instName then pe_editor_button.curDoubleClickInstName = nil return Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, ondoubleclick, buttonName, mcmlNode) end pe_editor_button.curDoubleClickInstName = instName commonlib.Timer:new( { callbackFunc = function() pe_editor_button.curDoubleClickInstName = nil end } ):Change(700, nil) end -- this is the new on_click handler. -- @param instName: obsoleted field. can be nil. function pe_editor_button.on_click(uiobj, mcmlNode, instName, bindingContext, buttonName) if(not mcmlNode or not uiobj) then return end local onclick = mcmlNode.onclickscript or mcmlNode:GetString("onclick"); if(onclick == "")then onclick = nil; end local onclick_for = mcmlNode:GetString("for"); if(onclick_for == "") then onclick_for = nil; end local result; if(onclick) then local btnType = mcmlNode:GetString("type"); if( btnType=="submit") then -- user clicks the normal button. -- the callback function format is function(buttonName, values, bindingContext, mcmlNode) end local values; if(bindingContext) then bindingContext:UpdateControlsToData(); values = bindingContext.values end result = Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onclick, buttonName, values, bindingContext, mcmlNode); else -- user clicks the button, yet without form info -- the callback function format is function(buttonName, mcmlNode) end result = Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onclick, buttonName, mcmlNode) end end if(onclick_for) then -- call the OnClick method of the mcml control by id or name local pageCtrl = mcmlNode:GetPageCtrl(); if(pageCtrl) then local target_node = pageCtrl:GetNodeByID(onclick_for); if(target_node) then if(target_node ~= mcmlNode) then target_node:InvokeMethod("HandleClickFor", mcmlNode, bindingContext); else LOG.std(nil, "warn", "mcml", "the for target of %s can not be itself", onclick_for); end else LOG.std(nil, "warn", "mcml", "the for target of %s is not found in the page", onclick_for); end end end return result; end -- some other control forwarded a click message to this control -- @param mcmlNode: the for node target -- @param fromNode: from which node the click event is fired. function pe_editor_button.HandleClickFor(mcmlNode, fromNode, bindingContext) local uiobj; if(mcmlNode.uiobject_id) then uiobj = ParaUI.GetUIObject(mcmlNode.uiobject_id); end pe_editor_button.on_click(uiobj, mcmlNode, nil, bindingContext, mcmlNode:GetAttribute("name")); end -- obsoleted: get the onclick script based on the button node and bindingContext -- @param instName: button instance name for the mcmlNode -- @param mcmlNode: the mcml button node object -- @param bindingContext: the bindingContext -- @return: nil or the onclick script with heading ";" function pe_editor_button.GetOnClickScript(instName, mcmlNode, bindingContext) local onclickscript; local editorInstName; if(bindingContext) then editorInstName = bindingContext.editorInstName or "" end local name, onclick = mcmlNode:GetAttributeWithCode("name") or "", mcmlNode.onclickscript or mcmlNode:GetString("onclick") or ""; local btnType = mcmlNode:GetString("type") if(onclick ~= "") then if( btnType=="submit") then onclickscript = string.format(";Map3DSystem.mcml_controls.pe_editor_button.OnClick(%q,%q,%q,%q)", editorInstName or "", name, onclick, instName or ""); else onclickscript = string.format(";Map3DSystem.mcml_controls.pe_editor_button.OnGeneralClick(%q,%q,%q)", name, onclick, instName or ""); end else if(btnType == "submit")then -- if it is a submit button without onclick, we will search for <form> and <pe:editor> tag -- and use automatic HTTP URL GET. local formNode = mcmlNode:GetParent("form") or mcmlNode:GetParent("pe:editor") if(formNode) then -- find target page ctrl inside which to open the new url local pageCtrlName; local _targetName = formNode:GetString("target"); if(_targetName==nil or _targetName== "_self") then -- open in current window -- looking for an iframe in the ancestor of this node. local pageCtrl = formNode:GetPageCtrl(); if (pageCtrl) then pageCtrlName = pageCtrl.name; else log("warning: mcml <form> can not find any iframe in its ancestor node to which the target url can be loaded\n"); end elseif(_targetName== "_blank") then -- TODO: open in a new window elseif(_targetName== "_mcmlblank") then -- TODO: open in a new window else -- search for iframes with the target name local iFrames = formNode:GetRoot():GetAllChildWithName("iframe"); local _; if(iFrames) then for _, iframe in ipairs(iFrames) do -- only accept iframe node with the same name of _targetName if(iframe:GetString("name") == _targetName) then pageCtrlName = iframe:GetInstanceName(rootName); end end end if(not pageCtrlName) then log("warning: mcml <form> can not find the iframe target ".._targetName.."\n"); end end if(pageCtrlName) then -- -- find target url -- local url = formNode:GetAttribute("action"); if(url) then onclickscript = string.format(";Map3DSystem.mcml_controls.pe_editor_button.OnSubmit(%q,%q,%q,%q)", editorInstName or "", name, url, pageCtrlName); else log("warning: <form> or <pe:editor> tag does not have a action attribute, the submit button has no where to post request.\n"); end end else log("warning: a submit button is not inside <form> or <pe:editor> node \n") end end end return onclickscript; end -- get the MCML value on the node function pe_editor_button.GetValue(mcmlNode) return mcmlNode:GetAttribute("text") or mcmlNode:GetAttribute("value") or mcmlNode:GetInnerText(); end -- get the MCML value on the node function pe_editor_button.SetValue(mcmlNode, value) if(mcmlNode:GetAttribute("text")) then mcmlNode:SetAttribute("text", value); elseif(mcmlNode:GetAttribute("value"))then mcmlNode:SetAttribute("value", value); elseif(mcmlNode:GetInnerText()~="") then mcmlNode:SetInnerText(value) else -- default to value property mcmlNode:SetAttribute("value", value); end end -- get the UI value on the node function pe_editor_button.GetUIValue(mcmlNode, pageInstName) local btn = mcmlNode:GetControl(pageInstName); if(btn) then return btn.text; end end -- set the UI value on the node function pe_editor_button.SetUIValue(mcmlNode, pageInstName, value) local btn = mcmlNode:GetControl(pageInstName); if(btn) then if(type(value) == "number") then value = tostring(value); elseif(type(value) == "table") then return end btn.text = value; end end -- set the UI enabled on the node function pe_editor_button.SetUIEnabled(mcmlNode, pageInstName, value) local btn = mcmlNode:GetControl(pageInstName); mcmlNode:SetAttribute("enabled", tostring(value)); if(btn) then if(type(value) == "boolean") then btn.enabled = value; end end end -- get the UI background on the node function pe_editor_button.GetUIBackground(mcmlNode, pageInstName) local btn = mcmlNode:GetControl(pageInstName); if(btn) then if(type(value) == "string") then return btn.background; end end end -- set the UI background on the node function pe_editor_button.SetUIBackground(mcmlNode, pageInstName, value) local btn = mcmlNode:GetControl(pageInstName); mcmlNode:SetCssStyle("background", value); if(btn) then if(type(value) == "string") then btn.background = value; --mcmlNode:SetCssStyle("background", value); end end end -- Public method: for button. -- @param bEnable: true to enable the button. function pe_editor_button.SetEnable(mcmlNode, pageInstName, bEnabled) local btn = mcmlNode:GetControl(pageInstName); if(btn) then local invisibleondisabled = mcmlNode:GetBool("invisibleondisabled"); if(invisibleondisabled == true) then btn.visible = (bEnabled == true); end btn.enabled = (bEnabled == true); end end -- obsoleted: user clicks the button yet without form info -- the callback function format is function(buttonName, mcmlNode) end function pe_editor_button.OnGeneralClick(buttonName, callback, instName) Map3DSystem.mcml_controls.OnPageEvent(pe_editor_button.button_instances[instName], callback, buttonName, pe_editor_button.button_instances[instName]) end -- obsoleted: similar to pe_editor_button.OnGeneralClick except that the callback function is called with given parameters. function pe_editor_button.OnParamsClick(callback, instName, ...) Map3DSystem.mcml_controls.OnPageEvent(pe_editor_button.button_instances[instName], callback, ...) end -- obsoleted: user clicks the normal button. -- the callback function format is function(buttonName, values, bindingContext) end function pe_editor_button.OnClick(editorInstName, buttonName, callback, instName) local bindingContext; if(editorInstName and editorInstName~="")then bindingContext = pe_editor.GetBinding(editorInstName); end local values; if(bindingContext) then bindingContext:UpdateControlsToData(); values = bindingContext.values end Map3DSystem.mcml_controls.OnPageEvent(pe_editor_button.button_instances[instName], callback, buttonName, values, bindingContext) end -- obsoleted(may be refactored in future): user clicks the submit button. we will automatically post to url. Local server is not used. -- @param buttonName -- @param editorInstName -- @param url: the HTTP get url -- @param pageCtrlName: where to open the submitted page function pe_editor_button.OnSubmit(editorInstName, buttonName, url, pageCtrlName) local bindingContext = pe_editor.GetBinding(editorInstName); local values; if(bindingContext) then bindingContext:UpdateControlsToData(); values = bindingContext.values if(url) then local ctl = CommonCtrl.GetControl(pageCtrlName); if(ctl ~= nil) then NPL.load("(gl)script/ide/System/localserver/UrlHelper.lua"); url = System.localserver.UrlHelper.BuildURLQuery(url, values); --_guihelper.MessageBox(url.."\n"..pageCtrlName.."\n"); -- disable caching for page get in this place local cachePolicy = System.localserver.CachePolicy:new("access plus 0"); ctl:Init(url, cachePolicy, true); else log("warning: unable to find page ctrl "..pageCtrlName.."\n") end end end end ----------------------------------- -- pe:editor-text control ----------------------------------- local pe_editor_text = {}; Map3DSystem.mcml_controls.pe_editor_text = pe_editor_text; -- increment top by the height of the control. -- the control takes up (22*rows) pixels in height, and editbox itself is 22 pixel height. function pe_editor_text.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) local name = mcmlNode:GetAttributeWithCode("name",nil,true); local text = mcmlNode:GetAttribute("text") or mcmlNode:GetAttributeWithCode("value",nil,true) or mcmlNode:GetInnerText(); local rows = tonumber(mcmlNode:GetAttributeWithCode("rows", 1, true)); local css = mcmlNode:GetStyle(mcml_controls.pe_css.default["pe:editor-text"] or mcml_controls.pe_html.css["pe:editor-text"]); local margin_left, margin_top, margin_bottom, margin_right = (css["margin-left"] or css["margin"] or 0),(css["margin-top"] or css["margin"] or 0), (css["margin-bottom"] or css["margin"] or 0),(css["margin-right"] or css["margin"] or 0); local left, top, width, height = parentLayout:GetPreferredRect(); local fontsize = mcmlNode:GetAttributeWithCode("fontsize", nil, true) if(fontsize) then fontsize = tonumber(fontsize); end local lineheight = mcmlNode:GetAttributeWithCode("lineheight", nil, true); if(lineheight) then lineheight = tonumber(lineheight); elseif(css["line-height"]) then lineheight = tonumber(css["line-height"]); end if(mcmlNode:GetAttribute("height")) then local height = mcmlNode:GetAttribute("height"); css.height = tonumber(string.match(height, "%d+")); if(css.height and string.match(height, "%%$")) then if(css.position == "screen") then css.height = ParaUI.GetUIObject("root").height * css.height/100; else local availWidth, availHeight = parentLayout:GetPreferredSize(); local maxWidth, maxHeight = parentLayout:GetMaxSize(); css.height=math.floor((maxHeight-margin_top-margin_bottom)*css.height/100); if(availHeight<(css.height+margin_top+margin_bottom)) then css.height=availHeight-margin_top-margin_bottom; end if(css.height<=0) then css.height = nil; end end end end width, height = width-left-margin_left-margin_right, css.height or ((lineheight or 20)*rows + (css["padding-top"] or 0) + (css["padding-bottom"] or 0)); if(css.width and (rows==1 or css.width<width)) then width = css.width end if(css.height and (rows==1 or css.height<height)) then height = css.height; end parentLayout:AddObject(width+margin_left+margin_right, margin_top+margin_bottom+height); left=left+margin_left; top=top+margin_top local uiname = mcmlNode:GetAttributeWithCode("uiname", nil, true) local instName = uiname or mcmlNode:GetInstanceName(rootName); if(rows>1 or mcmlNode.name=="textarea") then -- multiline editbox NPL.load("(gl)script/ide/MultiLineEditbox.lua"); local bReadOnly = mcmlNode:GetAttributeWithCode("ReadOnly", nil, true) bReadOnly = (bReadOnly== true or bReadOnly=="true"); local ctl = CommonCtrl.MultiLineEditbox:new{ name = instName, alignment = "_lt", left=left, top=top, width = width, height = height, parent = _parent, DefaultNodeHeight = lineheight, fontFamily = css["font-family"], fontsize = fontsize, ReadOnly = bReadOnly, ShowLineNumber = mcmlNode:GetBool("ShowLineNumber"), SingleLineEdit = mcmlNode:GetBool("SingleLineEdit"), VerticalScrollBarStep = mcmlNode:GetNumber("VerticalScrollBarStep"), WordWrap = mcmlNode:GetBool("WordWrap"), textcolor = mcmlNode:GetString("textcolor") or css.textcolor, empty_text = mcmlNode:GetAttributeWithCode("EmptyText"), container_bg = "", bUseSystemControl = mcmlNode:GetBool("UseSystemControl"), language = mcmlNode:GetAttributeWithCode("language", nil), AlwaysShowCurLineBackground = mcmlNode:GetBool("AlwaysShowCurLineBackground", true), InputMethodEnabled = mcmlNode:GetBool("enable_ime", true), }; local onkeyup = mcmlNode:GetString("onkeyup"); if(onkeyup)then ctl.onkeyup = function() Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onkeyup, name, mcmlNode); end end local onchange = mcmlNode:GetString("onchange"); if(onchange)then ctl.onchange = function() Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onchange, name, mcmlNode); end end local OnMouseOverWordChange = mcmlNode:GetString("OnMouseOverWordChange"); if(OnMouseOverWordChange)then ctl.OnMouseOverWordChange = function(self, word, line, from, to) Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, OnMouseOverWordChange, word, line, from, to); end end local OnRightClick = mcmlNode:GetString("OnRightClick"); if(OnRightClick)then ctl.OnRightClick = function(self, event) Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, OnRightClick, event); end end if mcmlNode:GetBool("MoveViewWhenAttachWithIME", false) then ctl:setMoveViewWhenAttachWithIME(true); end local syntax_map = mcmlNode:GetString("syntax_map"); if(syntax_map) then ctl.syntax_map = CommonCtrl.MultiLineEditbox["syntax_map_"..syntax_map]; end ctl:Show(true); local endofline = mcmlNode:GetString("endofline") if(endofline) then text = string.gsub(text, endofline, "\n"); end ctl:SetText(text); mcmlNode.control = ctl; if(bindingContext and name) then bindingContext:AddBinding(bindingContext.values, name, instName, commonlib.Binding.ControlTypes.IDE_editbox, "text") end else -- single line editbox local _this; if(("password" == mcmlNode:GetString("type")) or mcmlNode:GetString("PasswordChar")) then if (System.os.GetPlatform() == "android" or System.os.GetPlatform() == "ios") then _this = ParaUI.CreateUIObject("imeeditbox", instName, "_lt", left, top, width, height); else _this = ParaUI.CreateUIObject("editbox", instName, "_lt", left, top, width, height); end _this.text = text; _this.background = css.background; _this.PasswordChar = mcmlNode:GetString("PasswordChar") or "*"; _parent:AddChild(_this); else if(mcmlNode:GetString("enable_ime") ~= "false") then _this = ParaUI.CreateUIObject("imeeditbox", instName, "_lt", left, top, width, height) else if (System.os.GetPlatform() == "android") then if (ParaEngine.GetAttributeObject():GetField("GetUsbMode", false)) then _this = ParaUI.CreateUIObject("imeeditbox", instName, "_lt", left, top, width, height) else _this = ParaUI.CreateUIObject("editbox", instName, "_lt", left, top, width, height) end else _this = ParaUI.CreateUIObject("editbox", instName, "_lt", left, top, width, height) end end _this.text = text; _this.background = css.background; _parent:AddChild(_this); end if(_this) then if mcmlNode:GetBool("ReadOnly") then _this.enabled = false; end if mcmlNode:GetBool("MoveViewWhenAttachWithIME") then _this:SetField("MoveViewWhenAttachWithIME", true); end end mcmlNode.uiobject_id = _this.id; if(css and (css["font-family"] or css["font-size"] or css["font-weight"]))then local font_family = css["font-family"] or "System"; -- this is tricky. we convert font size to integer, and we will use scale if font size is either too big or too small. local font_size = math.floor(tonumber(css["font-size"] or 12)); local font_weight = css["font-weight"] or "norm"; local font = string.format("%s;%d;%s", font_family, font_size, font_weight); _this.font = font; end local alignFormat = 0; if(css["text-align"]) then if (css["text-align"] == "center") then alignFormat = 3; elseif (css["text-align"] == "right") then alignFormat = 2; elseif (css["text-align"] == "left") then alignFormat = 0; end end if(css["text-singleline"] == "true") then alignFormat = alignFormat + 32; else if(css["text-wordbreak"] == "true") then alignFormat = alignFormat + 16; end end if(css["text-noclip"] == "true") then alignFormat = alignFormat + 256; end if(css["text-valign"] == "center") then alignFormat = alignFormat + 4; end if(alignFormat~=0) then _guihelper.SetUIFontFormat(_this, alignFormat); _guihelper.SetUIFontFormat(_this, alignFormat, "selected_text"); end local empty_text = mcmlNode:GetAttributeWithCode("EmptyText"); if(empty_text and empty_text~="") then _this:SetField("EmptyText", empty_text); end local emptyTextColor = mcmlNode:GetAttributeWithCode("EmptyTextColor"); if (emptyTextColor and emptyTextColor ~= '') then _this:SetField("EmptyTextColor", _guihelper.ColorStr_TO_DWORD(emptyTextColor)); end if(mcmlNode:GetBool("autofocus")) then _this:Focus(); end local tooltip = mcmlNode:GetAttributeWithCode("tooltip") if(tooltip) then _this.tooltip = tooltip; end local spacing = mcmlNode:GetNumber("spacing") if(spacing) then _this.spacing = spacing; end if(mcmlNode:GetString("onkeyup")) then _this:SetScript("onkeyup", pe_editor_text.onkeyup, mcmlNode, instName, bindingContext, name); end if(mcmlNode:GetString("onmodify") or mcmlNode:GetString("onchange") or uiname) then _this:SetScript("onmodify", pe_editor_text.onmodify, mcmlNode, instName, bindingContext, name); end if(mcmlNode:GetString("onactivate") or uiname) then _this:SetScript("onactivate", pe_editor_text.onactivate, mcmlNode, instName, bindingContext, name); end if(mcmlNode:GetString("onfocusin")) then _this:SetScript("onfocusin", pe_editor_text.onfocusin, mcmlNode, instName, bindingContext, name); end if(mcmlNode:GetString("onfocusout")) then _this:SetScript("onfocusout", pe_editor_text.onfocusout, mcmlNode, instName, bindingContext, name); end local CaretColor = mcmlNode:GetString("CaretColor") or css.CaretColor; if(CaretColor) then _this:SetField("CaretColor", _guihelper.ColorStr_TO_DWORD(CaretColor)); end if(css["text-shadow"]) then _this.shadow = true; if(css["shadow-quality"]) then _this:SetField("TextShadowQuality", tonumber(css["shadow-quality"]) or 0); end if(css["shadow-color"]) then _this:SetField("TextShadowColor", _guihelper.ColorStr_TO_DWORD(css["shadow-color"])); end end if(System.options.IsTouchDevice and mcmlNode:GetBool("auto_virtual_keyboard", System.options.auto_virtual_keyboard)) then -- _this:SetField("InputMethodEnabled", false); _this:SetScript("onfocusin", pe_editor_text.onfocusin, mcmlNode, instName, bindingContext, name); end local text_color = mcmlNode:GetString("textcolor") or css.textcolor; if(text_color) then _guihelper.SetFontColor(_this, text_color) end if(bindingContext and name) then bindingContext:AddBinding(bindingContext.values, name, instName, commonlib.Binding.ControlTypes.ParaUI_editbox, "text") end end end function pe_editor_text.onactivate(uiobj, mcmlNode, instName, bindingContext, name) if(not mcmlNode or not uiobj) then return end local onactivate = mcmlNode:GetString("onactivate") or ""; if(onactivate and onactivate~="") then -- the callback function format is function(name, mcmlNode) end Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onactivate, name, mcmlNode,uiobj); end end function pe_editor_text.onfocusin(uiobj, mcmlNode, instName, bindingContext, name) if(not mcmlNode or not uiobj) then return end if(mcmlNode:GetBool("auto_virtual_keyboard", System.options.auto_virtual_keyboard)) then NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/TouchVirtualKeyboardIcon.lua"); local TouchVirtualKeyboardIcon = commonlib.gettable("MyCompany.Aries.Game.GUI.TouchVirtualKeyboardIcon"); TouchVirtualKeyboardIcon.GetSingleton():ShowKeyboard(true) end local onclick = mcmlNode:GetString("onfocusin") or ""; -- the callback function format is function(name, mcmlNode) end Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onclick, name, mcmlNode,uiobj); end -- this is the new on_click handler. function pe_editor_text.onkeyup(uiobj, mcmlNode, instName, bindingContext, name) if(not mcmlNode or not uiobj) then return end local onkeyup = mcmlNode:GetString("onkeyup") or ""; -- the callback function format is function(name, mcmlNode) end Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onkeyup, name, mcmlNode,uiobj); end -- this is the onchange handler. function pe_editor_text.onmodify(uiobj, mcmlNode, instName, bindingContext, name) if(not mcmlNode or not uiobj) then return end local onmodify = mcmlNode:GetString("onmodify") or mcmlNode:GetString("onchange") or ""; if(onmodify ~= "") then -- the callback function format is function(name, mcmlNode) end Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onmodify, name, mcmlNode,uiobj); end end -- this is the onfocusin handler. function pe_editor_text.onfocusin(uiobj, mcmlNode, instName, bindingContext, name) if(not mcmlNode or not uiobj) then return end local onfocusin = mcmlNode:GetString("onfocusin"); -- the callback function format is function(name, mcmlNode) end Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onfocusin, name, mcmlNode, uiobj); end -- this is the onfocusout handler. function pe_editor_text.onfocusout(uiobj, mcmlNode, instName, bindingContext, name) if(not mcmlNode or not uiobj) then return end local onfocusout = mcmlNode:GetString("onfocusout"); -- the callback function format is function(name, mcmlNode) end Map3DSystem.mcml_controls.OnPageEvent(mcmlNode, onfocusout, name, mcmlNode, uiobj); end -- get the MCML value on the node function pe_editor_text.GetValue(mcmlNode) local text = mcmlNode:GetAttribute("text") or mcmlNode:GetAttribute("value") or mcmlNode:GetInnerText(); if(mcmlNode:GetBool("UseBadWordFilter")) then text = MyCompany.Aries.Chat.BadWordFilter.FilterString(text); end return text; end -- set the MCML value on the node function pe_editor_text.SetValue(mcmlNode, value) if(type(value) == "number") then value = tostring(value); elseif(type(value) == "table") then return end if(mcmlNode:GetAttribute("text")) then mcmlNode:SetAttribute("text", value); elseif(mcmlNode:GetAttribute("value"))then mcmlNode:SetAttribute("value", value); elseif(mcmlNode:GetInnerText()~="") then mcmlNode:SetInnerText(value) else -- default to value property mcmlNode:SetAttribute("value", value); end end -- get the UI value on the node function pe_editor_text.GetUIValue(mcmlNode, pageInstName) local editBox = mcmlNode:GetControl(pageInstName); if(editBox) then if(type(editBox)=="table" and type(editBox.GetText) == "function") then return editBox:GetText(); else return editBox.text; end end end -- set the UI value on the node function pe_editor_text.SetUIValue(mcmlNode, pageInstName, value) local editBox = mcmlNode:GetControl(pageInstName); if(editBox) then if(type(value) == "number") then value = tostring(value); elseif(type(value) == "table") then return end if(type(editBox)=="table" and type(editBox.SetText) == "function") then editBox:SetText(value); else editBox.text = value; end end end ----------------------------------- -- pe:editor-divider control: just render a dummy gray line ----------------------------------- local pe_editor_divider = {}; Map3DSystem.mcml_controls.pe_editor_divider = pe_editor_divider; -- increment top by divider height, e.g. 5 pixels. function pe_editor_divider.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout) parentLayout:NewLine(); local css = mcmlNode:GetStyle(mcml_controls.pe_css.default["hr"] or Map3DSystem.mcml_controls.pe_html.css["hr"]); local margin_left, margin_top, margin_bottom, margin_right = (css["margin-left"] or css["margin"] or 0),(css["margin-top"] or css["margin"] or 0), (css["margin-bottom"] or css["margin"] or 0),(css["margin-right"] or css["margin"] or 0); local left, top, width = parentLayout:GetPreferredRect(); local height = css.height or 1; parentLayout:AddObject(width-left, margin_top+margin_bottom+height); parentLayout:NewLine(); local _this = ParaUI.CreateUIObject("button", "b", "_lt", left+margin_left, top+margin_top, width-left-margin_left-margin_right, height) _this.enabled = false; if(css.background) then _this.background = css.background; if(css["background-color"]) then _guihelper.SetUIColor(_this, css["background-color"]); else _guihelper.SetUIColor(_this, "255 255 255 255"); end end _parent:AddChild(_this); end
gpl-2.0
thedraked/darkstar
scripts/zones/Norg/npcs/Mamaulabion.lua
17
8832
----------------------------------- -- Area: Norg -- NPC: Mamaulabion -- Starts and finishes Quest: Mama Mia -- @zone 252 -- @pos -57 -9 68 (88) --CSIDs for Mamaulabion --0x005D / 93 = Standard --0x00BF / 191 = start quest --0x00C0 / 192 = quest accepted --0x00C1 / 193 = given an item --0x00C2 / 194 = given an item you already gave --0x00C3 / 195 = all 7 items given --0x00C4 / 196 = after 7 items, but need more time until reward is given --0x00C5 / 197 = reward --0x00C6 / 198 = after quest is complete --0x00F3 / 243 = get new ring if you dropped yours --I did alot of copy/pasting, so you may notice a reduncency on comments XD --But it can make it easier to follow aswell. --"Mamaulabion will inform you of the items delivered thus far, as of the May 2011 update." --i have no clue where this event is, so i have no idea how to add this (if this gets scripted, please remove this comment) --"Upon completion of this quest, the above items no longer appear in the rewards list for defeating the Prime Avatars." --will require changing other avatar quests and making a variable for it all. (if this gets scripted, please remove this comment) ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(OUTLANDS,MAMA_MIA) == QUEST_ACCEPTED) then local tradesMamaMia = player:getVar("tradesMamaMia") if (trade:hasItemQty(1202,1) and trade:getItemCount() == 1) then -- Trade Bubbly water wasSet = player:getMaskBit(tradesMamaMia,0) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",0,true) if (player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif (wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif (trade:hasItemQty(1203,1) and trade:getItemCount() == 1) then -- Trade Egil's torch wasSet = player:getMaskBit(tradesMamaMia,1) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",1,true) if (player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif (wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif (trade:hasItemQty(1204,1) and trade:getItemCount() == 1) then -- Trade Eye of mept wasSet = player:getMaskBit(tradesMamaMia,2) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",2,true) if (player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif (wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif (trade:hasItemQty(1205,1) and trade:getItemCount() == 1) then -- Trade Desert Light wasSet = player:getMaskBit(tradesMamaMia,3) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",3,true) if (player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif (wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif (trade:hasItemQty(1206,1) and trade:getItemCount() == 1) then -- Trade Elder Branch wasSet = player:getMaskBit(tradesMamaMia,4) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",4,true) if (player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif (wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif (trade:hasItemQty(1207,1) and trade:getItemCount() == 1) then -- Trade Rust 'B' Gone wasSet = player:getMaskBit(tradesMamaMia,5) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",5,true) if (player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif (wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif (trade:hasItemQty(1208,1) and trade:getItemCount() == 1) then -- Trade Ancients' Key wasSet = player:getMaskBit(tradesMamaMia,6) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",6,true) if (player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif (wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local MamaMia = player:getQuestStatus(OUTLANDS,MAMA_MIA); local moonlitPath = player:getQuestStatus(WINDURST,THE_MOONLIT_PATH); local EvokersRing = player:hasItem(14625); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local questday = player:getVar("MamaMia_date") if (MamaMia == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 4 and moonlitPath == QUEST_COMPLETED) then player:startEvent(0x00BF); -- Start Quest "Mama Mia" elseif (MamaMia == QUEST_ACCEPTED) then local tradesMamaMia = player:getVar("tradesMamaMia") local maskFull = player:isMaskFull(tradesMamaMia,7) if (maskFull) then if (realday == questday) then player:startEvent(0x00C4); --need to wait longer for reward elseif (questday ~= 0) then player:startEvent(0x00C5); --Reward end else player:startEvent(0x00C0); -- During Quest "Mama Mia" end elseif (MamaMia == QUEST_COMPLETED and EvokersRing) then player:startEvent(0x00C6); -- New standard dialog after "Mama Mia" is complete elseif (MamaMia == QUEST_COMPLETED and EvokersRing == false) then player:startEvent(0x00F3); -- Quest completed, but dropped ring else player:startEvent(0x005D); -- 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 == 0x00BF) then player:addQuest(OUTLANDS,MAMA_MIA); elseif (csid == 0x00C1) then player:tradeComplete(); elseif (csid == 0x00C3) then player:tradeComplete(); player:setVar("MamaMia_date", os.date("%j")); -- %M for next minute, %j for next day elseif (csid == 0x00C5) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14625); -- Evokers Ring else player:addItem(14625); -- Evokers Ring player:messageSpecial(ITEM_OBTAINED,14625); -- Evokers Ring player:addFame(OUTLANDS,30); --idk how much fame the quest adds, just left at 30 which the levi quest gave. player:completeQuest(OUTLANDS,MAMA_MIA); player:setVar("tradesMamaMia",0) end elseif (csid == 0x00F3) then if (option == 1) then player:delQuest(OUTLANDS,MAMA_MIA); player:addQuest(OUTLANDS,MAMA_MIA); end end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Port_Jeuno/npcs/Sugandhi.lua
17
1570
----------------------------------- -- Area: Port Bastok -- NPC: Sugandhi -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,SUGANDHI_SHOP_DIALOG); stock = {0x4059,5589,1, -- Kukri 0x40A1,21067,1, -- Broadsword 0x4081,11588,1, -- Tuck 0x40AE,61200,1, -- Falchion 0x4052,2181,2, -- Knife 0x4099,30960,2, -- Mythril Sword 0x40A8,4072,2, -- Scimitar 0x4051,147,3, -- Bronze Knife 0x4015,104,3, -- Cat Baghnakhs 0x4097,241,3, -- Bronze Sword 0x4098,7128,3, -- Iron Sword 0x4085,9201,3, -- Degen 0x40A7,698,3} -- Sapara showNationShop(player, NATION_BASTOK, 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
thedraked/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Ekki-Mokki.lua
14
1061
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ekki-Mokki -- Type: Standard NPC -- @zone 94 -- @pos -26.558 -4.5 62.930 -- -- 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(0x0199); 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
pexcn/openwrt
luci-1-master/applications/luci-app-cpulimit/luasrc/model/cbi/cpulimit.lua
20
1274
m = Map("cpulimit", translate("cpulimit"),translate("Use cpulimit to limit app's cpu using.")) s = m:section(TypedSection, "list", translate("Settings")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true enable = s:option(Flag, "enabled", translate("enable", "enable")) enable.optional = false enable.rmempty = false local pscmd="ps | awk '{print $5}' | sed '1d' | sort -k2n | uniq | sed '/^\\\[/d' | sed '/sed/d' | sed '/awk/d' | sed '/hostapd/d' | sed '/pppd/d' | sed '/mwan3/d' | sed '/sleep/d' | sed '/sort/d' | sed '/ps/d' | sed '/uniq/d' | awk -F '/' '{print $NF}'" local shellpipe = io.popen(pscmd,"r") exename = s:option(Value, "exename", translate("exename"), translate("name of the executable program file.CAN NOT BE A PATH!")) exename.optional = false exename.rmempty = false exename.default = "vsftpd" for psvalue in shellpipe:lines() do exename:value(psvalue) end limit = s:option(Value, "limit", translate("limit")) limit.optional = false limit.rmempty = false limit.default = "50" limit:value("100","100%") limit:value("90","90%") limit:value("80","80%") limit:value("70","70%") limit:value("60","60%") limit:value("50","50%") limit:value("40","40%") limit:value("30","30%") limit:value("20","20%") limit:value("10","10%") return m
gpl-2.0
mason-larobina/luakit
lib/history_chrome.lua
3
11838
--- Save history in sqlite3 database - chrome page. -- -- This module provides the luakit://history/ chrome page - a user interface for -- searching the web browsing history. -- -- @module history_chrome -- @copyright 2010-2011 Mason Larobina <mason.larobina@gmail.com> -- Grab the luakit environment we need local history = require("history") local chrome = require("chrome") local modes = require("modes") local add_cmds = modes.add_cmds local _M = {} --- CSS applied to the history chrome page. -- @readwrite _M.stylesheet = [===[ .day-heading { font-size: 1.3em; font-weight: 100; margin: 1em 0 0.5em 0; -webkit-user-select: none; cursor: default; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .day-sep { height: 1em; } .item { font-weight: 400; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .item span { padding: 0.2em; } .item .time { -webkit-user-select: none; cursor: default; color: #888; display: inline-block; width: 5em; text-align: right; border-right: 1px solid #ddd; padding-right: 0.5em; margin-right: 0.1em; } .item a { text-decoration: none; } .item .domain a { color: #aaa; } .item .domain a:hover { color: #666; } .item.selected { background-color: #eee; } .nav-button-box { margin: 2em; } .nav-button-box a { display: none; border: 1px solid #aaa; padding: 0.4em 1em; } ]===] local html_template = [==[ <!doctype html> <html> <head> <meta charset="utf-8"> <title>History</title> <style type="text/css"> {%stylesheet} </style> </head> <body> <header id="page-header"> <h1>History</h1> <span id="search-box"> <input type="text" id="search" placeholder="Search history..." /> <input type="button" class="button" id="clear-button" value="✕" /> <input type="hidden" id="page" /> </span> <input type="button" id="search-button" class="button" value="Search" /> <div class="rhs"> <input type="button" class="button" disabled id="clear-selected-button" value="Clear selected" /> <input type="button" class="button" disabled id="clear-results-button" value="Clear results" /> <input type="button" class="button" id="clear-all-button" value="Clear all" /> </div> </header> <div id="results" class="content-margin"></div> <div class="nav-button-box"> <a id="nav-prev">prev</a> <a id="nav-next">next</a> </div> <script>{%javascript}</script> </body> ]==] local main_js = [=[ function createElement (tag, attributes, children, events) { let $node = document.createElement(tag) for (let a in attributes) { $node.setAttribute(a, attributes[a]) } for (let $child of children) { $node.appendChild($child) } if (events) { for (let eventType in events) { let action = events[eventType] $node.addEventListener(eventType, action) } } return $node } function empty ($el) { while ($el.firstChild) $el.removeChild($el.firstChild) } window.addEventListener('load', () => { const limit = 100 let resultsLen = 0 const $clearAll = document.getElementById('clear-all-button') const $clearResults = document.getElementById('clear-results-button') const $clearSelected = document.getElementById('clear-selected-button') const $next = document.getElementById('nav-next') const $page = document.getElementById('page') const $prev = document.getElementById('nav-prev') const $results = document.getElementById('results') const $search = document.getElementById('search') $page.value = $page.value || 1 function makeHistoryItem (h) { let domain = /https?:\/\/([^/]+)\//.exec(h.uri) domain = domain ? domain[1] : '' function escapeHTML(string) { let entityMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '/': '&#x2F;', '`': '&#x60;', '=': '&#x3D;' } return String(string).replace(/[&<>"'`=\/]/g, s => entityMap[s]); } return ` <div class=item data-id="${h.id}"> <span class=time>${h.time}</span> <span class=title> <a href="${h.uri}">${escapeHTML(h.title || h.uri)}</a> </span> <span class=domain> <a href=#>${domain}</a> </span> </div> ` // return createElement('div', { class: 'item', 'data-id': h.id }, [ // createElement('span', { class: 'time' }, [ // document.createTextNode(h.time) // ]), // createElement('span', { class: 'title' }, [ // createElement('a', { href: h.uri }, [ // document.createTextNode(h.title || h.uri) // ]) // ]), // createElement('span', { class: 'domain' }, [ // createElement('a', { href: '#' }, [ // document.createTextNode(domain) // ], { // click: event => { // $search.value = event.target.textContent // search() // } // }) // ]) // ], { // click: event => { // event.target.classList.toggle('selected') // $clearSelected.disabled = $results.getElementsByClassName('selected').length === 0 // } // }) } function updateClearButtons (all, results, selected) { $clearAll.disabled = !!all $clearResults.disabled = !!results $clearSelected.disabled = !!selected } function updateNavButtons () { $next.style.display = resultsLen === limit ? 'inline-block' : 'none' $prev.style.display = parseInt($page.value, 10) > 1 ? 'inline-block' : 'none' } function search () { let query = $search.value history_search({ query: query, limit: limit, page: parseInt($page.value, 10) }).then(results => { resultsLen = results.length || 0 updateClearButtons(query, !query, true) empty($results) if (!results.length) { updateNavButtons() return } $results.innerHTML = results.map((item, i) => { let lastItem = results[i - 1] || {} let html = item.date !== lastItem.date ? `<div class=day-heading>${item.date}</div>` : (lastItem.last_visit - item.last_visit) > 3600 ? `<div class=day-sep></div>` : ""; return html + makeHistoryItem(item) }).join('') updateNavButtons() }) } function clearEls (className) { let ids = Array.from(document.getElementsByClassName(className)) .map($el => $el.dataset.id) if (ids.length > 0) history_clear_list(ids) search() } $search.addEventListener('keydown', event => { if (event.which === 13) { // 13 is the code for the 'Return' key $page.value = 1 search() $search.blur() reset_mode() } }) document.getElementById('clear-button') .addEventListener('click', () => { $search.value = '' $page.value = 1 search() }) document.getElementById('search-button') .addEventListener('click', () => { $page.value = 1 search() }) $clearAll.addEventListener('click', () => { if (!window.confirm('Clear all browser history?')) return history_clear_all() search() $clearAll.blur() }) $clearResults.addEventListener('click', () => { clearEls('item') $clearResults.blur() }) $clearSelected.addEventListener('click', () => { clearEls('selected') $clearSelected.blur() }) $next.addEventListener('click', () => { let page = parseInt($page.value, 10) $page.value = page + 1 search() }) $prev.addEventListener('click', () => { let page = parseInt($page.value, 10) $page.value = Math.max(page - 1, 1) search() }) document.addEventListener('click', event => { if (event.target.matches(".item > .domain > a")) { $search.value = event.target.textContent search() } else if (event.target.matches(".item")) { event.target.classList.toggle('selected') $clearSelected.disabled = $results.getElementsByClassName('selected').length === 0 } }) initial_search_term().then(query => { if (query) $search.value = query search(query) }) }) ]=] local initial_search_term local export_funcs = { history_search = function (_, opts) local sql = { "SELECT", "*", "FROM history" } local where, args, argc = {}, {}, 1 string.gsub(opts.query or "", "(-?)([^%s]+)", function (notlike, term) if term ~= "" then table.insert(where, (notlike == "-" and "NOT " or "") .. string.format("(text GLOB ?%d)", argc, argc)) argc = argc + 1 table.insert(args, "*"..string.lower(term).."*") end end) if #where ~= 0 then sql[2] = [[ *, lower(uri||title) AS text ]] table.insert(sql, "WHERE " .. table.concat(where, " AND ")) end local order_by = [[ ORDER BY last_visit DESC LIMIT ?%d OFFSET ?%d ]] table.insert(sql, string.format(order_by, argc, argc+1)) local limit, page = opts.limit or 100, opts.page or 1 table.insert(args, limit) table.insert(args, limit > 0 and (limit * (page - 1)) or 0) sql = table.concat(sql, " ") if #where ~= 0 then local wrap = [[SELECT id, uri, title, last_visit FROM (%s)]] sql = string.format(wrap, sql) end local rows = history.db:exec(sql, args) for _, row in ipairs(rows) do local time = rawget(row, "last_visit") rawset(row, "date", os.date("%A, %d %B %Y", time)) rawset(row, "time", os.date("%H:%M", time)) end return rows end, history_clear_all = function (_) history.db:exec [[ DELETE FROM history ]] end, history_clear_list = function (_, ids) if not ids or #ids == 0 then return end local marks = {} for i=1,#ids do marks[i] = "?" end history.db:exec("DELETE FROM history WHERE id IN (" .. table.concat(marks, ",") .. " )", ids) end, initial_search_term = function (_) local term = initial_search_term initial_search_term = nil return term end, } chrome.add("history", function () local html = string.gsub(html_template, "{%%(%w+)}", { -- Merge common chrome stylesheet and history stylesheet stylesheet = chrome.stylesheet .. _M.stylesheet, javascript = main_js, }) return html end, nil, export_funcs) -- Prevent history items from turning up in history history.add_signal("add", function (uri) if string.match(uri, "^luakit://history/") then return false end end) add_cmds({ { ":history", "Open <luakit://history/> in a new tab.", function (w, o) initial_search_term = o.arg w:new_tab("luakit://history/") end }, }) return _M -- vim: et:sw=4:ts=8:sts=4:tw=80
gpl-3.0
mtroyka/Zero-K
LuaUI/i18nlib/i18n/variants.lua
36
1195
local variants = {} local function reverse(arr, length) local result = {} for i=1, length do result[i] = arr[length-i+1] end return result, length end local function concat(arr1, len1, arr2, len2) for i = 1, len2 do arr1[len1 + i] = arr2[i] end return arr1, len1 + len2 end function variants.ancestry(locale) local result, length, accum = {},0,nil locale:gsub("[^%-]+", function(c) length = length + 1 accum = accum and (accum .. '-' .. c) or c result[length] = accum end) return reverse(result, length) end function variants.isParent(parent, child) return not not child:match("^".. parent .. "%-") end function variants.root(locale) return locale:match("[^%-]+") end function variants.fallbacks(locale, fallbackLocale) if locale == fallbackLocale or variants.isParent(fallbackLocale, locale) then return variants.ancestry(locale) end if variants.isParent(locale, fallbackLocale) then return variants.ancestry(fallbackLocale) end local ancestry1, length1 = variants.ancestry(locale) local ancestry2, length2 = variants.ancestry(fallbackLocale) return concat(ancestry1, length1, ancestry2, length2) end return variants
gpl-2.0
dmolina/my-config
awesome/.config/awesome/awesome_copycats/lain/layout/termfair.lua
6
4710
--[[ Licensed under GNU General Public License v2 * (c) 2014, projektile * (c) 2013, Luke Bonham * (c) 2010-2012, Peter Hofmann --]] local tag = require("awful.tag") local beautiful = require("beautiful") local math = { ceil = math.ceil, floor = math.floor, max = math.max } local tonumber = tonumber local termfair = { name = "termfair" } function termfair.arrange(p) -- Layout with fixed number of vertical columns (read from nmaster). -- New windows align from left to right. When a row is full, a now -- one above it is created. Like this: -- (1) (2) (3) -- +---+---+---+ +---+---+---+ +---+---+---+ -- | | | | | | | | | | | | -- | 1 | | | -> | 2 | 1 | | -> | 3 | 2 | 1 | -> -- | | | | | | | | | | | | -- +---+---+---+ +---+---+---+ +---+---+---+ -- (4) (5) (6) -- +---+---+---+ +---+---+---+ +---+---+---+ -- | 4 | | | | 5 | 4 | | | 6 | 5 | 4 | -- +---+---+---+ -> +---+---+---+ -> +---+---+---+ -- | 3 | 2 | 1 | | 3 | 2 | 1 | | 3 | 2 | 1 | -- +---+---+---+ +---+---+---+ +---+---+---+ -- A useless gap (like the dwm patch) can be defined with -- beautiful.useless_gap_width. local useless_gap = tonumber(beautiful.useless_gap_width) or 0 if useless_gap < 0 then useless_gap = 0 end -- A global border can be defined with -- beautiful.global_border_width local global_border = tonumber(beautiful.global_border_width) or 0 if global_border < 0 then global_border = 0 end -- Screen. local wa = p.workarea local cls = p.clients -- Borders are factored in. wa.height = wa.height - (global_border * 2) wa.width = wa.width - (global_border * 2) wa.x = wa.x + global_border wa.y = wa.y + global_border -- How many vertical columns? local t = tag.selected(p.screen) local num_x = termfair.nmaster or tag.getnmaster(t) -- Do at least "desired_y" rows. local desired_y = termfair.ncol or tag.getncol(t) if #cls > 0 then local num_y = math.max(math.ceil(#cls / num_x), desired_y) local cur_num_x = num_x local at_x = 0 local at_y = 0 local remaining_clients = #cls local width = math.floor((wa.width - (num_x + 1)*useless_gap) / num_x) local height = math.floor((wa.height - (num_y + 1)*useless_gap) / num_y) -- We start the first row. Left-align by limiting the number of -- available slots. if remaining_clients < num_x then cur_num_x = remaining_clients end -- Iterate in reversed order. for i = #cls,1,-1 do -- Get x and y position. local c = cls[i] local this_x = cur_num_x - at_x - 1 local this_y = num_y - at_y - 1 -- Calc geometry. local g = {} if this_x == (num_x - 1) then g.width = wa.width - (num_x - 1)*width - (num_x + 1)*useless_gap - 2*c.border_width else g.width = width - 2*c.border_width end if this_y == (num_y - 1) then g.height = wa.height - (num_y - 1)*height - (num_y + 1)*useless_gap - 2*c.border_width else g.height = height - 2*c.border_width end g.x = wa.x + this_x*width g.y = wa.y + this_y*height if useless_gap > 0 then -- All clients tile evenly. g.x = g.x + (this_x + 1)*useless_gap g.y = g.y + (this_y + 1)*useless_gap end if g.width < 1 then g.width = 1 end if g.height < 1 then g.height = 1 end c:geometry(g) remaining_clients = remaining_clients - 1 -- Next grid position. at_x = at_x + 1 if at_x == num_x then -- Row full, create a new one above it. at_x = 0 at_y = at_y + 1 -- We start a new row. Left-align. if remaining_clients < num_x then cur_num_x = remaining_clients end end end end end return termfair
gpl-3.0
thedraked/darkstar
scripts/zones/AlTaieu/Zone.lua
32
2324
----------------------------------- -- -- Zone: AlTaieu (33) -- ----------------------------------- package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/AlTaieu/TextIDs"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-25,-1 ,-620 ,33); end if (player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus")==0) then cs=0x0001; elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==0) then cs=0x00A7; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0001) then player:setVar("PromathiaStatus",1); player:addKeyItem(LIGHT_OF_ALTAIEU); player:messageSpecial(KEYITEM_OBTAINED,LIGHT_OF_ALTAIEU); player:addTitle(SEEKER_OF_THE_LIGHT); elseif (csid == 0x00A7) then player:setVar("PromathiaStatus",1); end end;
gpl-3.0
mtroyka/Zero-K
LuaRules/Gadgets/lockunits_modoption.lua
6
2583
if (not gadgetHandler:IsSyncedCode()) then return end function gadget:GetInfo() return { name = "LockOptions", desc = "Modoption for locking units. 90% Copypasted from game_perks.lua", author = "Storage, GoogleFrog", license = "Public Domain", layer = -1, enabled = true, } end local disabledunitsstring = Spring.GetModOptions().disabledunits or "" if (disabledunitsstring == "") then --no unit to disable, exit return end local disabledCount = 0 local disabledUnits = {} local UnitDefBothNames = {} -- Includes humanName and name local function AddName(name, unitDefId) UnitDefBothNames[name] = UnitDefBothNames[name] or {} UnitDefBothNames[name][#UnitDefBothNames[name] + 1] = unitDefId end for unitDefID = 1, #UnitDefs do AddName(UnitDefs[unitDefID].humanName, unitDefID) AddName(UnitDefs[unitDefID].name, unitDefID) end local alreadyDisabled = {} GG.TableEcho(UnitDefBothNames) for name in string.gmatch(disabledunitsstring, '([^+]+)') do Spring.Echo(name) if UnitDefBothNames[name] then for i = 1, #UnitDefBothNames[name] do local unitDefID = UnitDefBothNames[name][i] if not alreadyDisabled[unitDefID] then disabledCount = disabledCount + 1 disabledUnits[disabledCount] = unitDefID alreadyDisabled[unitDefID] = true end end end end for i = 1, disabledCount do Spring.SetGameRulesParam("disabled_unit_" .. UnitDefs[disabledUnits[i]].name, 1) end local function UnlockUnit(unitID, lockDefID) local cmdDescID = Spring.FindUnitCmdDesc(unitID, -lockDefID) if (cmdDescID) then local cmdArray = {disabled = false} Spring.EditUnitCmdDesc(unitID, cmdDescID, cmdArray) end end local function LockUnit(unitID, lockDefID) local cmdDescID = Spring.FindUnitCmdDesc(unitID, -lockDefID) if (cmdDescID) then local cmdArray = {disabled = true} Spring.EditUnitCmdDesc(unitID, cmdDescID, cmdArray) end end local function RemoveUnit(unitID, lockDefID) local cmdDescID = Spring.FindUnitCmdDesc(unitID, -lockDefID) if (cmdDescID) then Spring.RemoveUnitCmdDesc(unitID, cmdDescID) end end local function SetBuildOptions(unitID, unitDefID) local unitDef = UnitDefs[unitDefID] if (unitDef.isBuilder) then for _, buildoptionID in pairs(unitDef.buildOptions) do for i = 1, disabledCount do RemoveUnit(unitID, disabledUnits[i]) end end end end function gadget:UnitCreated(unitID, unitDefID) SetBuildOptions(unitID, unitDefID) end function gadget:Initialize() local units = Spring.GetAllUnits() for i=1, #units do local udid = Spring.GetUnitDefID(units[i]) gadget:UnitCreated(units[i], udid) end end
gpl-2.0
X-Coder/wire
lua/wire/stools/damage_detector.lua
9
1260
WireToolSetup.setCategory( "Detection" ) WireToolSetup.open( "damage_detector", "Damage Detector", "gmod_wire_damage_detector", nil, "Damage Detectors" ) if CLIENT then language.Add( "Tool.wire_damage_detector.name", "Damage Detector Tool (Wire)" ) language.Add( "Tool.wire_damage_detector.desc", "Spawns a damage detector for use with the wire system" ) language.Add( "Tool.wire_damage_detector.0", "Primary: Create/Update Detector, Secondary: Link Detector to an entity, Reload: Unlink Detector" ) language.Add( "Tool.wire_damage_detector.1", "Now select the entity to link to." ) language.Add( "Tool.wire_damage_detector.includeconstrained", "Include Constrained Props" ) end WireToolSetup.BaseLang() WireToolSetup.SetupMax( 10 ) TOOL.ClientConVar = { model = "models/jaanus/wiretool/wiretool_siren.mdl", includeconstrained = 0 } if SERVER then function TOOL:GetConVars() return self:GetClientNumber( "includeconstrained" ) end -- Uses default WireToolObj:MakeEnt's WireLib.MakeWireEnt function end WireToolSetup.SetupLinking() function TOOL.BuildCPanel(panel) ModelPlug_AddToCPanel(panel, "Misc_Tools", "wire_damage_detector") panel:CheckBox("#Tool.wire_damage_detector.includeconstrained","wire_damage_detector_includeconstrained") end
gpl-3.0
thedraked/darkstar
scripts/zones/Ship_bound_for_Mhaura/npcs/Lokhong.lua
14
1204
----------------------------------- -- Area: Ship bound for Mhaura -- NPC: Lokhong -- Type: Guild Merchant: Fishing Guild -- @pos 1.841 -2.101 -9.000 221 ----------------------------------- package.loaded["scripts/zones/Ship_bound_for_Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Ship_bound_for_Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(521,1,23,5)) then player:showText(npc,LOKHONG_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
JackYoustra/gm_SCIWS
lua/entities/ciws.lua
1
2577
AddCSLuaFile() include('shared.lua') function ENT:SpawnFunction( ply, tr, ClassName ) if ( !tr.Hit ) then return end local SpawnPos = tr.HitPos + tr.HitNormal * 16 local ent = ents.Create( ClassName ) ent:SetPos( SpawnPos ) ent:Spawn() ent:Activate() ent:OnSpawn(ent) return ent end function ENT:Draw() -- self.BaseClass.Draw(self) -- Overrides Draw self:DrawModel() -- Draws Model Client Side end function ENT:OnSpawn(self) print("spawn called") //timer.Create(uuid(), 0.03, 0, function() scan(self) end); end function ENT:Think() -- Do stuff scan(self) self:NextThink( CurTime() ) return true end function ENT:Initialize() if CLIENT then return end self:SetModel( "models/props_interiors/BathTub01a.mdl" ) self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) local physics = self:GetPhysicsObject() if ( IsValid(physics) ) then physics:Wake() end end function scan(self) print("scan") local distance = 1001 local currentTarget = nil for k, v in pairs( ents.FindInSphere(self:GetPos(), 1000) ) do local class = v:GetClass() if v.IsNPC() and v:Health() > 0 then local currentDistance = self:GetPos():Distance(v:GetPos()) if (currentDistance < distance) then distance = currentDistance currentTarget = v end end end if (currentTarget != nil) then CIWSShoot(self, currentTarget:GetPos()) end end function CIWSShoot(self, targetPosition) sound.Play( "ciwsshort.mp3", self:GetPos(), 75, 100, 1) bullet = {} bullet.Attacker = self bullet.Num = 1 bullet.Force = 2 bullet.Damage = 1 bullet.Tracer = 1 bullet.TracerName = "Tracer" //https://maurits.tv/data/garrysmod/wiki/wiki.garrysmod.com/index7161.html bullet.Src = self:GetPos() bullet.Spread = Vector(16, 16, 0) local shotVector = targetPosition shotVector:Sub(self:GetPos()) bullet.Dir = shotVector self:FireBullets(bullet) end function TheMenu( Panel ) Panel:ClearControls() Panel:AddHeader() //Do menu things here end function createthemenu() spawnmenu.AddToolMenuOption( "Options", "Stuff", "CustomMenu", "My Custom Menu", "custom_doit", "", -- Resource File( Probably shouldn't use ) TheMenu ) end hook.Add( "PopulateToolMenu", "pleasework", createthemenu ) local random = math.random function uuid() local template ='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' return string.gsub(template, '[xy]', function (c) local v = (c == 'x') and random(0, 0xf) or random(8, 0xb) return string.format('%x', v) end) end
gpl-2.0
mtroyka/Zero-K
scripts/corshad.lua
4
7452
local base = piece 'base' local fuselage = piece 'fuselage' local wingl1 = piece 'wingl1' local wingr1 = piece 'wingr1' local wingl2 = piece 'wingl2' local wingr2 = piece 'wingr2' local engines = piece 'engines' local fins = piece 'fins' local rflap = piece 'rflap' local lflap = piece 'lflap' local predrop = piece 'predrop' local drop = piece 'drop' local thrustl = piece 'thrustl' local thrustr = piece 'thrustr' local wingtipl = piece 'wingtipl' local wingtipr = piece 'wingtipr' local xp,zp = piece("x","z") local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitHeading = Spring.GetUnitHeading local spGetUnitVelocity = Spring.GetUnitVelocity local spMoveCtrlGetTag = Spring.MoveCtrl.GetTag local spGetUnitMoveTypeData = Spring.GetUnitMoveTypeData local spSetAirMoveTypeData = Spring.MoveCtrl.SetAirMoveTypeData local spGetGroundHeight = Spring.GetGroundHeight local min, max = math.min, math.max local smokePiece = {fuselage, thrustr, thrustl} local bombs = 1 include "bombers.lua" include "fakeUpright.lua" include "constants.lua" include "fixedwingTakeOff.lua" local ud = UnitDefs[unitDefID] local highBehaviour = { wantedHeight = UnitDefNames["corshad"].wantedHeight*1.5, maxPitch = ud.maxPitch, maxBank = ud.maxBank, turnRadius = ud.turnRadius, maxAileron = ud.maxAileron, maxElevator = ud.maxElevator, maxRudder = ud.maxRudder, } local lowBehaviour = { maxPitch = 0.72, maxBank = 0.5, turnRadius = 100, maxAileron = 0.004, maxElevator = 0.018, maxRudder = 0.015, } local SIG_TAKEOFF = 1 local SIG_CHANGE_FLY_HEIGHT = 2 local SIG_SPEED_CONTROL = 4 local takeoffHeight = UnitDefNames["corshad"].wantedHeight local fullHeight = UnitDefNames["corshad"].wantedHeight/1.5 local minSpeedMult = 0.75 local function BehaviourChangeThread(behaviour) Signal(SIG_CHANGE_FLY_HEIGHT) SetSignalMask(SIG_CHANGE_FLY_HEIGHT) takeoffHeight = behaviour.wantedHeight/1.5 local state = spGetUnitMoveTypeData(unitID).aircraftState local flying = spMoveCtrlGetTag(unitID) == nil and (state == "flying" or state == "takeoff") if not flying then StartThread(TakeOffThread, takeoffHeight, SIG_TAKEOFF) end while not flying do Sleep(600) state = spGetUnitMoveTypeData(unitID).aircraftState flying = spMoveCtrlGetTag(unitID) == nil and (state == "flying" or state == "takeoff") end Spring.MoveCtrl.SetAirMoveTypeData(unitID, behaviour) --Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", 1) --GG.UpdateUnitAttributes(unitID) --GG.UpdateUnitAttributes(unitID) end local function SpeedControl() Signal(SIG_SPEED_CONTROL) SetSignalMask(SIG_SPEED_CONTROL) while true do local x,y,z = spGetUnitPosition(unitID) local terrain = max(spGetGroundHeight(x,z), 0) -- not amphibious, treat water as ground local speedMult = minSpeedMult + (1-minSpeedMult)*max(0, min(1, (y - terrain-50)/(fullHeight-60))) Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", speedMult) GG.UpdateUnitAttributes(unitID) GG.UpdateUnitAttributes(unitID) Sleep(50 + 2*max(0, y - terrain - 80)) end end function BomberDive_FlyHigh() StartThread(BehaviourChangeThread, highBehaviour) end function BomberDive_FlyLow(height) height = math.min(height, highBehaviour.wantedHeight) StartThread(SpeedControl) lowBehaviour.wantedHeight = height StartThread(BehaviourChangeThread, lowBehaviour) end function script.StartMoving() --Turn(fins, z_axis, math.rad(-(-30)), math.rad(50)) Move(wingr1, x_axis, 0, 50) Move(wingr2, x_axis, 0, 50) Move(wingl1, x_axis, 0, 50) Move(wingl2, x_axis, 0, 50) StartThread(SpeedControl) end function script.StopMoving() --Turn(fins, z_axis, math.rad(-(0)), math.rad(80)) Move(wingr1, x_axis, 5, 30) Move(wingr2, x_axis, 5, 30) Move(wingl1, x_axis, -5, 30) Move(wingl2, x_axis, -5, 30) StartThread(TakeOffThread, takeoffHeight, SIG_TAKEOFF) end local function Lights() while select(5, Spring.GetUnitHealth(unitID)) < 1 do Sleep(400) end while true do EmitSfx(wingtipr, 1024) EmitSfx(wingtipl, 1025) Sleep(2000) end end function script.Create() StartThread(SmokeUnit, smokePiece) StartThread(TakeOffThread, takeoffHeight, SIG_TAKEOFF) FakeUprightInit(xp, zp, drop) --StartThread(Lights) end function script.QueryWeapon(num) return drop end function script.AimFromWeapon(num) return drop end function script.AimWeapon(num, heading, pitch) return (Spring.GetUnitRulesParam(unitID, "noammo") ~= 1) end local predictMult = 3 function script.BlockShot(num, targetID) if num ~= 2 then return false end local ableToFire = not ((GetUnitValue(COB.CRASHING) == 1) or (Spring.GetUnitRulesParam(unitID, "noammo") == 1)) if not (targetID and ableToFire) then return not ableToFire end local x,y,z = spGetUnitPosition(unitID) local _,_,_,_,_,_,tx,ty,tz = spGetUnitPosition(targetID, true, true) local vx,vy,vz = spGetUnitVelocity(targetID) local heading = spGetUnitHeading(unitID)*headingToRad vx, vy, vz = vx*predictMult, vy*predictMult, vz*predictMult local dx, dy, dz = tx + vx - x, ty + vy - y, tz + vz - z local cosHeading = cos(heading) local sinHeading = sin(heading) dx, dz = cosHeading*dx - sinHeading*dz, cosHeading*dz + sinHeading*dx --Spring.Echo(vx .. ", " .. vy .. ", " .. vz) --Spring.Echo(dx .. ", " .. dy .. ", " .. dz) --Spring.Echo(heading) if dz < 30 and dz > -30 and dx < 100 and dx > -100 and dy < 0 then FakeUprightTurn(unitID, xp, zp, base, predrop) Move(drop, x_axis, dx) Move(drop, z_axis, dz) dy = math.max(dy, -30) Move(drop, y_axis, dy) local distance = (Spring.GetUnitSeparation(unitID, targetID) or 0) local unitHeight = (GG.GetUnitHeight and GG.GetUnitHeight(targetID)) or 0 distance = math.max(0, distance - unitHeight/2) local projectileTime = 35*math.min(1, distance/340) if GG.OverkillPrevention_CheckBlock(unitID, targetID, 800.1, projectileTime, false, false, true) then -- Remove attack command on blocked target, it's already dead so move on. local cQueue = Spring.GetCommandQueue(unitID, 1) if cQueue and cQueue[1] and cQueue[1].id == CMD.ATTACK and (not cQueue[1].params[2]) and cQueue[1].params[1] == targetID then Spring.GiveOrderToUnit(unitID, CMD.REMOVE, {cQueue[1].tag}, {} ) end return true end return false end return true end function script.FireWeapon(num) if num == 2 then GG.Bomber_Dive_fired(unitID) Sleep(33) -- delay before clearing attack order; else bomb loses target and fails to home Move(drop, x_axis, 0) Move(drop, z_axis, 0) Move(drop, y_axis, 0) Reload() elseif num == 3 then GG.Bomber_Dive_fake_fired(unitID) end end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= 0.25 then Explode(fuselage, sfxNone) Explode(engines, sfxNone) Explode(wingl1, sfxNone) Explode(wingr2, sfxNone) return 1 elseif severity <= 0.50 or (Spring.GetUnitMoveTypeData(unitID).aircraftState == "crashing") then Explode(fuselage, sfxNone) Explode(engines, sfxNone) Explode(wingl2, sfxNone) Explode(wingr1, sfxNone) return 1 elseif severity <= 1 then Explode(fuselage, sfxNone) Explode(engines, sfxFall + sfxSmoke + sfxFire) Explode(wingl1, sfxFall + sfxSmoke + sfxFire) Explode(wingr2, sfxFall + sfxSmoke + sfxFire) return 2 else Explode(fuselage, sfxNone) Explode(engines, sfxFall + sfxSmoke + sfxFire) Explode(wingl1, sfxFall + sfxSmoke + sfxFire) Explode(wingl2, sfxFall + sfxSmoke + sfxFire) return 2 end end
gpl-2.0
X-Coder/wire
lua/entities/gmod_wire_textentry.lua
9
7253
-- Author: mitterdoo (with help from Divran) AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Text Entry (Wire)" ENT.WireDebugName = "Text Entry" function ENT:SetupDataTables() self:NetworkVar("Float",0,"Hold") self:NetworkVar("Bool",0,"DisableUse") end if CLIENT then local panel ---------------------------------------------------- -- Show the prompt ---------------------------------------------------- net.Receive("wire_textentry_show",function() local self=net.ReadEntity() if !IsValid(self) then return end panel = Derma_StringRequest( "Wire Text Entry", "Enter text below", "", function(text) net.Start("wire_textentry_action") net.WriteEntity(self) net.WriteString(text) net.SendToServer() end, function() net.Start("wire_textentry_action") net.WriteEntity(self) net.WriteString("") net.SendToServer() end, "Enter","Cancel" ) end) net.Receive( "wire_textentry_kick", function() if IsValid( panel ) then panel:Remove() end end) return end ---------------------------------------------------- -- UpdateOverlay ---------------------------------------------------- function ENT:UpdateOverlay() local hold = math.Round(math.max(self:GetHold(),0),1) local txt = "Hold Length: " .. (hold > 0 and hold or "Forever") if self.BlockInput then txt = txt.."\nBlocking Input" elseif IsValid(self.User) then txt = txt.."\nIn use by: " .. self.User:Nick() end if self:GetDisableUse() then txt = txt .. "\nUse disabled" end self:SetOverlayText(txt) end ---------------------------------------------------- -- Initialize ---------------------------------------------------- function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetUseType(SIMPLE_USE) self.Inputs=WireLib.CreateInputs(self,{"Block Input","Prompt"}) self.Outputs=WireLib.CreateOutputs(self,{"In Use","Text [STRING]","User [ENTITY]"}) self.BlockInput=false self.NextPrompt = 0 self:UpdateOverlay() end ---------------------------------------------------- -- Vehicle linking ---------------------------------------------------- function ENT:TriggerInput(name,value) if name == "Block Input" then self.BlockInput = value~=0 self:UpdateOverlay() if IsValid( self.User ) then self:Unprompt( true ) end elseif name == "Prompt" then if value ~= 0 then self:Prompt() end end end ---------------------------------------------------- -- Vehicle linking ---------------------------------------------------- function ENT:UnlinkEnt(ent) if not IsValid( ent ) then return false, "Invalid entity specified" end if IsValid(self.Vehicle) then self.Vehicle:RemoveCallOnRemove( "wire_textentry_onremove" ) self.Vehicle.WireTextEntry = nil end self.Vehicle = nil WireLib.SendMarks( self, {} ) return true end function ENT:LinkEnt(ent) if not IsValid( ent ) then return false, "Invalid entity specified" end if not ent:IsVehicle() then return false, "Entity must be a vehicle" end if IsValid( self.Vehicle ) then -- remove old callback self.Vehicle:RemoveCallOnRemove( "wire_textentry_onremove" ) self.Vehicle.WireTextEntry = nil end self.Vehicle = ent self.Vehicle.WireTextEntry = self -- add new callback self.Vehicle:CallOnRemove( "wire_textentry_onremove", function() self:UnlinkEnt( ent ) end) WireLib.SendMarks( self, { ent } ) return true end function ENT:ClearEntities() self:UnlinkEnt(self.Vehicle) end function ENT:OnRemove() if IsValid( self.Vehicle ) then -- remove callback self.Vehicle:RemoveCallOnRemove( "wire_textentry_onremove" ) self.Vehicle.WireTextEntry = nil end self:Unprompt( true ) end ---------------------------------------------------- -- Receiving text from client ---------------------------------------------------- util.AddNetworkString("wire_textentry_action") net.Receive("wire_textentry_action",function(len,ply) local self=net.ReadEntity() if not IsValid( self ) or not IsValid( ply ) or ply ~= self.User then return end local text = net.ReadString() if not self.BlockInput then WireLib.TriggerOutput( self, "Text", text ) local timername = "wire_textentry_" .. self:EntIndex() timer.Remove( timername ) if math.max(self:GetHold(),0) > 0 then timer.Create( timername, math.max(self:GetHold(),0), 1, function() if IsValid( self ) then WireLib.TriggerOutput( self, "User", nil ) WireLib.TriggerOutput( self, "Text", "" ) end end) end end self:Unprompt() -- in all cases, make text entry available for use again self:UpdateOverlay() end) ---------------------------------------------------- -- Prompt -- Sends prompt to user etc ---------------------------------------------------- util.AddNetworkString("wire_textentry_show") function ENT:Prompt( ply ) if ply then if CurTime() < self.NextPrompt then return end -- anti spam self.NextPrompt = CurTime() + 0.1 if self.BlockInput or IsValid( self.User ) then WireLib.AddNotify(ply,"That text entry is not accepting input right now!",NOTIFY_ERROR,5,6) return end self.User = ply WireLib.TriggerOutput( self, "User", ply ) WireLib.TriggerOutput( self, "In Use", 1 ) local timername = "wire_textentry_" .. self:EntIndex() timer.Remove( timername ) net.Start( "wire_textentry_show" ) net.WriteEntity( self ) net.Send( ply ) self:UpdateOverlay() elseif IsValid( self.Vehicle ) and IsValid( self.Vehicle:GetDriver() ) then -- linked self:Prompt( self.Vehicle:GetDriver() ) -- prompt for driver else -- not linked self:Prompt( self:GetPlayer() ) -- prompt for owner end end ---------------------------------------------------- -- Unprompt -- Unsets user, making the text entry usable by other users ---------------------------------------------------- util.AddNetworkString("wire_textentry_kick") function ENT:Unprompt( kickuser ) if IsValid( self.User ) and kickuser then net.Start( "wire_textentry_kick" ) net.Send( self.User ) end local timername = "wire_textentry_" .. self:EntIndex() timer.Remove( timername ) self.User = nil WireLib.TriggerOutput( self, "In Use", 0 ) self:UpdateOverlay() end ---------------------------------------------------- -- PlayerLeaveVehicle ---------------------------------------------------- hook.Add( "PlayerLeaveVehicle", "wire_textentry_leave_vehicle", function( ply, vehicle ) if vehicle.WireTextEntry and IsValid( vehicle.WireTextEntry ) and IsValid( vehicle.WireTextEntry.User ) and vehicle.WireTextEntry.User == ply then vehicle.WireTextEntry:Unprompt( true ) end end) ---------------------------------------------------- -- Use ---------------------------------------------------- function ENT:Use(ply) if self:GetDisableUse() or not IsValid( ply ) then return end self:Prompt( ply ) end ---------------------------------------------------- -- Setup ---------------------------------------------------- function ENT:Setup(hold,disableuse) hold = tonumber(hold) if hold then self:SetHold( math.max( hold, 0 ) ) end disableuse = tobool(disableuse) if disableuse ~= nil then self:SetDisableUse( disableuse ) end self:UpdateOverlay() end duplicator.RegisterEntityClass("gmod_wire_textentry",WireLib.MakeWireEnt,"Data")
gpl-3.0
thedraked/darkstar
scripts/zones/Port_San_dOria/npcs/Eddy.lua
14
1051
----------------------------------- -- Area: Port San d'Oria -- NPC: Eddy -- Type: NPC Quest Giver -- @zone 232 -- @pos -5.209 -8.999 39.833 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02d3); 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
mtroyka/Zero-K
LuaRules/Configs/cai/strategies.lua
20
7579
--[[ example buildTasksMods buildTasksMods = function(buildConfig) buildConfig.robots.factoryByDefId[UnitDefNames['factorycloak'].id].importance = 0 buildConfig.robots.factoryByDefId[UnitDefNames['factoryshield'].id].importance = 1 buildConfig.robots.factoryByDefId[UnitDefNames['factoryveh'].id].importance = 0 buildConfig.robots.factoryByDefId[UnitDefNames['factoryspider'].id].importance = 0 end, --]] local function noFunc() end -- these buildTaskMods function by editing the config supplied as the arg local function BuildTasksMod_Blitz(buildConfig) local factory = buildConfig.robots.factoryByDefId factory[UnitDefNames['factorycloak'].id].importance = 1.1 factory[UnitDefNames['factoryshield'].id].importance = 0.9 factory[UnitDefNames['factoryveh'].id].importance = 1.2 factory[UnitDefNames['factoryhover'].id].importance = 1.2 factory[UnitDefNames['factoryspider'].id].importance = 0.8 factory[UnitDefNames['factoryjump'].id].importance = 0.8 for fac, data in pairs(factory) do if not data.airFactory then data[3].importanceMult = data[3].importanceMult*1.2 -- more raiders data[4].importanceMult = data[4].importanceMult*0.8 -- fewer arty data[5].importanceMult = data[5].importanceMult*1.15 -- more assaults data[6].importanceMult = data[6].importanceMult*0.9 -- fewer skirms data[7].importanceMult = data[7].importanceMult*0.9 -- fewer riots end for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 0.8 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 0.9 end end local econ = buildConfig.robots.econByDefId for econBldg, data in pairs(econ) do for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 0.8 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 0.9 end end end local function BuildTasksMod_Pusher(buildConfig) local factory = buildConfig.robots.factoryByDefId factory[UnitDefNames['factoryshield'].id].importance = 1.1 factory[UnitDefNames['factoryhover'].id].importance = 0.9 factory[UnitDefNames['factoryspider'].id].importance = 0.9 factory[UnitDefNames['factorytank'].id].importance = 1.1 for fac, data in pairs(factory) do if not data.airFactory then data[3].importanceMult = data[3].importanceMult*0.9 -- fewer raiders data[4].importanceMult = data[4].importanceMult*1.1 -- more arty data[6].importanceMult = data[6].importanceMult*1.2 -- more skirms data[7].importanceMult = data[7].importanceMult*1.1 -- more riots end for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 0.9 end end local econ = buildConfig.robots.econByDefId for econBldg, data in pairs(econ) do for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 0.9 end end end local function BuildTasksMod_Defensive(buildConfig) local factory = buildConfig.robots.factoryByDefId factory[UnitDefNames['factorycloak'].id].importance = 0.9 factory[UnitDefNames['factoryshield'].id].importance = 1.1 factory[UnitDefNames['factoryveh'].id].importance = 1.1 factory[UnitDefNames['factoryhover'].id].importance = 0.8 factory[UnitDefNames['factoryspider'].id].importance = 0.8 factory[UnitDefNames['factoryjump'].id].importance = 1.1 factory[UnitDefNames['factorytank'].id].importance = 1.1 for fac, data in pairs(factory) do if not data.airFactory then data[3].importanceMult = data[3].importanceMult*0.8 -- fewer raiders data[4].importanceMult = data[4].importanceMult*0.9 -- less arty data[5].importanceMult = data[5].importanceMult*0.9 -- fewer assaults data[6].importanceMult = data[6].importanceMult*1.1 -- more skirms data[7].importanceMult = data[7].importanceMult*1.2 -- more riots end for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 1.2 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 1.2 end end local econ = buildConfig.robots.econByDefId for econBldg, data in pairs(econ) do for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 1.2 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 1.2 end end end local function BuildTasksMod_Lolz(buildConfig) local factory = buildConfig.robots.factoryByDefId factory[UnitDefNames['factorycloak'].id].importance = 0 factory[UnitDefNames['factoryshield'].id].importance = 0 factory[UnitDefNames['factoryveh'].id].importance = 0 factory[UnitDefNames['factoryhover'].id].importance = 0 factory[UnitDefNames['factoryspider'].id].importance = 0 factory[UnitDefNames['factoryjump'].id].importance = 1 factory[UnitDefNames['factorytank'].id].importance = 0 factory[UnitDefNames['factoryjump'].id].minFacCount = 0 for fac, data in pairs(factory) do if not data.airFactory then --data[3].importanceMult = data[3].importanceMult*0.8 -- fewer raiders --data[4].importanceMult = data[4].importanceMult*0.9 -- less arty --data[5].importanceMult = data[5].importanceMult*0.9 -- fewer assaults data[6].importanceMult = data[6].importanceMult*5 -- more moderators!!! --data[7].importanceMult = data[7].importanceMult*1.2 -- more riots end for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] data.airDefenceQuota[i] = data.airDefenceQuota[i] end end local econ = buildConfig.robots.econByDefId for econBldg, data in pairs(econ) do for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 1.2 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 1.2 end end end strategies = { [1] = { -- standard name = "Standard", chance = 0.2, commanders = { {ID = "dyntrainer_strike_base", chance = 1}, }, buildTasksMods = noFunc, conAndEconHandlerMods = {}, }, [2] = { -- blitz name = "Blitz", chance = 0.2, commanders = { {ID = "dyntrainer_strike_base", chance = 0.5}, {ID = "dyntrainer_recon_base", chance = 0.5}, }, buildTasksMods = BuildTasksMod_Blitz, conAndEconHandlerMods = {}, }, [3] = { -- pusher name = "Push", chance = 0.2, commanders = { {ID = "dyntrainer_strike_base", chance = 0.5}, {ID = "dyntrainer_assault_base", chance = 0.5}, }, buildTasksMods = BuildTasksMod_Pusher, conAndEconHandlerMods = {}, }, [4] = { -- defensive name = "Defensive", chance = 0.2, commanders = { {ID = "dyntrainer_strike_base", chance = 0.5}, {ID = "dyntrainer_assault_base", chance = 0.5}, }, buildTasksMods = BuildTasksMod_Defensive, conAndEconHandlerMods = {}, }, [5] = { -- econ -- FIXME: doesn't do anything right now name = "Econ", chance = 0.2, commanders = { {ID = "dyntrainer_strike_base", chance = 0.5}, {ID = "dyntrainer_support_base", chance = 0.5}, }, buildTasksMods = noFunc, conAndEconHandlerMods = {}, }, [6] = { -- lolz name = "lolz", chance = 0, commanders = { {ID = "dyntrainer_strike_base", chance = 1}, }, buildTasksMods = BuildTasksMod_Lolz, conAndEconHandlerMods = {}, }, } local function SelectComm(player, team, strat) local rand = math.random() local commName local total = 0 for i = 1, #strategies[strat].commanders do total = total + strategies[strat].commanders[i].chance if rand < total then commName = strategies[strat].commanders[i].ID Spring.SetTeamRulesParam(team, "start_unit", commName) Spring.Echo("CAI: team "..team.." has selected strategy: "..strategies[strat].name..", using commander "..commName) break end end end function SelectRandomStrat(player, team) local count = #strategies local rand = math.random() local stratIndex = 1 local total = 0 for i = 1, count do total = total + strategies[i].chance if rand <= total then SelectComm(player, team, i) stratIndex = i break end end return stratIndex end
gpl-2.0
X-Coder/wire
lua/entities/gmod_wire_egp/lib/objects/poly.lua
9
1712
-- Author: Divran local Obj = EGP:NewObject( "Poly" ) Obj.w = nil Obj.h = nil Obj.x = nil Obj.y = nil Obj.vertices = {} Obj.verticesindex = "vertices" Obj.HasUV = true -- Returns whether c is to the left of the line from a to b. local function counterclockwise( a, b, c ) local area = (a.x - c.x) * (b.y - c.y) - (b.x - c.x) * (a.y - c.y) return area > 0 end Obj.Draw = function( self ) if (self.a>0 and #self.vertices>2) then render.CullMode(counterclockwise(unpack(self.vertices)) and MATERIAL_CULLMODE_CCW or MATERIAL_CULLMODE_CW) surface.SetDrawColor( self.r, self.g, self.b, self.a ) surface.DrawPoly( self.vertices ) render.CullMode(MATERIAL_CULLMODE_CCW) end end Obj.Transmit = function( self, Ent, ply ) if (#self.vertices <= 28) then net.WriteUInt( #self.vertices, 8 ) for i=1,#self.vertices do net.WriteInt( self.vertices[i].x, 16 ) net.WriteInt( self.vertices[i].y, 16 ) net.WriteFloat( self.vertices[i].u or 0 ) net.WriteFloat( self.vertices[i].v or 0 ) end else net.WriteUInt( 0, 8 ) EGP:InsertQueue( Ent, ply, EGP._SetVertex, "SetVertex", self.index, self.vertices ) end net.WriteInt( self.parent, 16 ) EGP:SendMaterial( self ) EGP:SendColor( self ) end Obj.Receive = function( self ) local tbl = {} tbl.vertices = {} for i=1,net.ReadUInt(8) do tbl.vertices[ #tbl.vertices+1 ] = { x = net.ReadInt(16), y = net.ReadInt(16), u = net.ReadFloat(), v = net.ReadFloat() } end tbl.parent = net.ReadInt(16) EGP:ReceiveMaterial( tbl ) EGP:ReceiveColor( tbl, self ) return tbl end Obj.DataStreamInfo = function( self ) return { vertices = self.vertices, material = self.material, r = self.r, g = self.g, b = self.b, a = self.a, parent = self.parent } end
gpl-3.0
thedraked/darkstar
scripts/globals/abilities/manifestation.lua
27
1202
----------------------------------- -- Ability: Manifestation -- Extends the effect of your next enfeebling1 black magic spell to targets within range. MP cost and casting time2 are doubled. -- Obtained: Scholar Level 40 -- Recast Time: Stratagem Charge -- Duration: 1 compatible black magic spell or 60 seconds, whichever occurs first -- -- Level |Charges |Recharge Time per Charge -- ----- -------- --------------- -- 10 |1 |4:00 minutes -- 30 |2 |2:00 minutes -- 50 |3 |1:20 minutes -- 70 |4 |1:00 minute -- 90 |5 |48 seconds ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_MANIFESTATION) then return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) player:addStatusEffect(EFFECT_MANIFESTATION,1,0,60); return EFFECT_MANIFESTATION; end;
gpl-3.0
thedraked/darkstar
scripts/zones/Port_Bastok/npcs/Evi.lua
17
2244
----------------------------------- -- Area: Port Bastok -- NPC: Evi -- Starts Quests: Past Perfect (100%) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) PastPerfect = player:getQuestStatus(BASTOK,PAST_PERFECT); if (PastPerfect == QUEST_ACCEPTED and player:hasKeyItem(TATTERED_MISSION_ORDERS)) then player:startEvent(0x0083); elseif (player:getFameLevel(BASTOK) >= 2 and player:getVar("PastPerfectVar") == 2) then player:startEvent(0x0082); elseif (PastPerfect == QUEST_AVAILABLE) then player:startEvent(0x0068); else player:startEvent(0x0015); 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 == 0x0068 and player:getVar("PastPerfectVar") == 0) then player:setVar("PastPerfectVar",1); elseif (csid == 0x0082) then player:addQuest(BASTOK,PAST_PERFECT); elseif (csid == 0x0083) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12560); else if (player:addItem(12560)) then player:delKeyItem(TATTERED_MISSION_ORDERS); player:setVar("PastPerfectVar",0); player:messageSpecial(ITEM_OBTAINED,12560); player:addFame(BASTOK,110); player:completeQuest(BASTOK,PAST_PERFECT); end end end end;
gpl-3.0
NPLPackages/main
script/ide/Animation/ObjectAnimationUsingKeyFrames.lua
1
3801
--[[ Title: ObjectAnimationUsingKeyFrames Author(s): Leio Zhang Date: 2008/7/24 Desc: use the lib: ------------------------------------------------------------ NPL.load("(gl)script/ide/Animation/ObjectAnimationUsingKeyFrames.lua"); ------------------------------------------------------------ --]] NPL.load("(gl)script/ide/commonlib.lua"); NPL.load("(gl)script/ide/Animation/KeyFrame.lua"); NPL.load("(gl)script/ide/Animation/TimeSpan.lua"); local ObjectAnimationUsingKeyFrames = commonlib.inherit(CommonCtrl.Animation.AnimationUsingKeyFrames, { property = "ObjectAnimationUsingKeyFrames", name = "ObjectAnimationUsingKeyFrames_instance", mcmlTitle = "pe:objectAnimationUsingKeyFrames", -- CreateMeshPhysicsObject --Value = { -- ["MeshPhysicsObjectParameters"] =[[ 1.000000,1.000000,1.000000, false, "1.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000"]] -- ["SetPosition"] = [[1, 0, 1]], -- ["SetFacing"] = [[0.000000]], -- ["SetScale"] = [[10.000000]], -- ["SetRotation"] = [[255.251480, 0.000000, 254.844879]], -- ["Asset"] = [[model/05plants/02tree/06椰子树/椰树_new1_v.x]] --} -- "Create2DContainer","Create2DButton","Create2DText" --Value = { -- ["postion"] = "1,1,1,1" -- left,right,width,height -- ["text"] = "test" -- it is available when SurpportProperty is Create2DButton or Create2DText -- } SurpportProperty = {"CreateMeshPhysicsObject","ModifyMeshPhysicsObject","DeleteMeshPhysicsObject","Create2DContainer","Create2DButton","Create2DText"}, }); commonlib.setfield("CommonCtrl.Animation.ObjectAnimationUsingKeyFrames",ObjectAnimationUsingKeyFrames); -- override parent InsertFirstKeyFrame function ObjectAnimationUsingKeyFrames:InsertFirstKeyFrame() --local Value =CommonCtrl.Animation.Util.GetDisplayObjProperty(self) ; local keyframe = CommonCtrl.Animation.DiscreteObjectKeyFrame:new{ KeyTime = "00:00:00", Value = nil, } commonlib.insertArrayItem(self.keyframes, 1, keyframe); end function ObjectAnimationUsingKeyFrames:getValue(time) -- hide all had been created object CommonCtrl.Animation.KeyFramesPool.WhoIsShowed(self,time) local curKeyframe = self:getCurrentKeyframe(time); if(not curKeyframe)then return nil,nil,time; end local begin = curKeyframe:GetValue(); if(not begin)then return nil,curKeyframe,time; end local nextKeyframe = self:getNextKeyframe(time); if (not nextKeyframe or nextKeyframe.parentProperty =="DiscreteKeyFrame") then return begin,curKeyframe,time; end return nil,curKeyframe,time; end function ObjectAnimationUsingKeyFrames:ReverseToMcml() if(not self.TargetName or not self.TargetProperty)then return "\r\n" end local node_value = ""; local k,frame; for k,frame in ipairs(self.keyframes) do node_value = node_value..frame:ReverseToMcml().."\r\n"; end local str = string.format([[<pe:objectAnimationUsingKeyFrames TargetName="%s" TargetProperty="%s">%s</pe:objectAnimationUsingKeyFrames>]],self.TargetName,self.TargetProperty,node_value.."\r\n"); return str; end -------------------------------------------------------------------------- -- DiscreteObjectKeyFrame local DiscreteObjectKeyFrame = commonlib.inherit(CommonCtrl.Animation.KeyFrame, { parentProperty = "DiscreteKeyFrame", property = "DiscreteObjectKeyFrame", name = "DiscreteObjectKeyFrame_instance", mcmlTitle = "pe:discreteObjectKeyFrame", }); commonlib.setfield("CommonCtrl.Animation.DiscreteObjectKeyFrame ",DiscreteObjectKeyFrame ); function DiscreteObjectKeyFrame:ReverseToMcml() if(not self.Value or not self.KeyTime)then return "\r\n" end local node_value = commonlib.serialize(self.Value); local node = string.format([[<pe:discreteObjectKeyFrame KeyTime="%s">%s</pe:discreteObjectKeyFrame>]],self.KeyTime,"\r\n"..node_value); return node; end
gpl-2.0
thedraked/darkstar
scripts/globals/items/tortilla_bueno.lua
18
1172
----------------------------------------- -- ID: 5181 -- Item: tortilla_bueno -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 8 -- Vitality 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5181); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 8); target:addMod(MOD_VIT, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 8); target:delMod(MOD_VIT, 4); end;
gpl-3.0
moomoomoo309/FamiliarFaces
src/pl/input.lua
6
5156
--- Iterators for extracting words or numbers from an input source. -- -- require 'pl' -- local total,n = seq.sum(input.numbers()) -- print('average',total/n) -- -- _source_ is defined as a string or a file-like object (i.e. has a read() method which returns the next line) -- -- See @{06-data.md.Reading_Unstructured_Text_Data|here} -- -- Dependencies: `pl.utils` -- @module pl.input local strfind = string.find local strsub = string.sub local strmatch = string.match local utils = require 'pl.utils' local unpack = utils.unpack local pairs,type,tonumber = pairs,type,tonumber local patterns = utils.patterns local io = io local input = {} --- create an iterator over all tokens. -- based on allwords from PiL, 7.1 -- @func getter any function that returns a line of text -- @string pattern -- @string[opt] fn Optionally can pass a function to process each token as it's found. -- @return an iterator function input.alltokens (getter,pattern,fn) local line = getter() -- current line local pos = 1 -- current position in the line return function () -- iterator function while line do -- repeat while there are lines local s, e = strfind(line, pattern, pos) if s then -- found a word? pos = e + 1 -- next position is after this token local res = strsub(line, s, e) -- return the token if fn then res = fn(res) end return res else line = getter() -- token not found; try next line pos = 1 -- restart from first position end end return nil -- no more lines: end of traversal end end local alltokens = input.alltokens -- question: shd this _split_ a string containing line feeds? --- create a function which grabs the next value from a source. If the source is a string, then the getter -- will return the string and thereafter return nil. If not specified then the source is assumed to be stdin. -- @param f a string or a file-like object (i.e. has a read() method which returns the next line) -- @return a getter function function input.create_getter(f) if f then if type(f) == 'string' then local ls = utils.split(f,'\n') local i,n = 0,#ls return function() i = i + 1 if i > n then return nil end return ls[i] end else -- anything that supports the read() method! if not f.read then error('not a file-like object') end return function() return f:read() end end else return io.read -- i.e. just read from stdin end end --- generate a sequence of numbers from a source. -- @param f A source -- @return An iterator function input.numbers(f) return alltokens(input.create_getter(f), '('..patterns.FLOAT..')',tonumber) end --- generate a sequence of words from a source. -- @param f A source -- @return An iterator function input.words(f) return alltokens(input.create_getter(f),"%w+") end local function apply_tonumber (no_fail,...) local args = {...} for i = 1,#args do local n = tonumber(args[i]) if n == nil then if not no_fail then return nil,args[i] end else args[i] = n end end return args end --- parse an input source into fields. -- By default, will fail if it cannot convert a field to a number. -- @param ids a list of field indices, or a maximum field index -- @string delim delimiter to parse fields (default space) -- @param f a source @see create_getter -- @tab opts option table, `{no_fail=true}` -- @return an iterator with the field values -- @usage for x,y in fields {2,3} do print(x,y) end -- 2nd and 3rd fields from stdin function input.fields (ids,delim,f,opts) local sep local s local getter = input.create_getter(f) local no_fail = opts and opts.no_fail local no_convert = opts and opts.no_convert if not delim or delim == ' ' then delim = '%s' sep = '%s+' s = '%s*' else sep = delim s = '' end local max_id = 0 if type(ids) == 'table' then for i,id in pairs(ids) do if id > max_id then max_id = id end end else max_id = ids ids = {} for i = 1,max_id do ids[#ids+1] = i end end local pat = '[^'..delim..']*' local k = 1 for i = 1,max_id do if ids[k] == i then k = k + 1 s = s..'('..pat..')' else s = s..pat end if i < max_id then s = s..sep end end local linecount = 1 return function() local line,results,err repeat line = getter() linecount = linecount + 1 if not line then return nil end if no_convert then results = {strmatch(line,s)} else results,err = apply_tonumber(no_fail,strmatch(line,s)) if not results then utils.quit("line "..(linecount-1)..": cannot convert '"..err.."' to number") end end until #results > 0 return unpack(results) end end return input
mit
nicholas-leonard/slides
nvidiagtc/solution/train-rnnlm.lua
1
9300
require 'paths' require 'rnn' local dl = require 'dataload' --[[ command line arguments ]]-- cmd = torch.CmdLine() cmd:text() cmd:text('Train a Language Model on PennTreeBank dataset using RNN or LSTM or GRU') cmd:text('Example:') cmd:text("th train-rnnlm.lua -progress -cuda -lstm -seqlen 20 -hiddensize '{200,200}' -batchsize 20 -startlr 1 -cutoff 5 -maxepoch 13 -schedule '{[5]=0.5,[6]=0.25,[7]=0.125,[8]=0.0625,[9]=0.03125,[10]=0.015625,[11]=0.0078125,[12]=0.00390625}'") cmd:text('Options:') -- training cmd:option('-startlr', 0.05, 'learning rate at t=0') cmd:option('-minlr', 0.00001, 'minimum learning rate') cmd:option('-saturate', 400, 'epoch at which linear decayed LR will reach minlr') cmd:option('-schedule', '', 'learning rate schedule. e.g. {[5] = 0.004, [6] = 0.001}') cmd:option('-momentum', 0.9, 'momentum') cmd:option('-maxnormout', -1, 'max l2-norm of each layer\'s output neuron weights') cmd:option('-cutoff', -1, 'max l2-norm of concatenation of all gradParam tensors') cmd:option('-batchSize', 32, 'number of examples per batch') cmd:option('-cuda', false, 'use CUDA') cmd:option('-device', 1, 'sets the device (GPU) to use') cmd:option('-maxepoch', 1000, 'maximum number of epochs to run') cmd:option('-earlystop', 50, 'maximum number of epochs to wait to find a better local minima for early-stopping') cmd:option('-progress', false, 'print progress bar') cmd:option('-silent', false, 'don\'t print anything to stdout') cmd:option('-uniform', 0.1, 'initialize parameters using uniform distribution between -uniform and uniform. -1 means default initialization') -- rnn layer cmd:option('-lstm', false, 'use Long Short Term Memory (nn.LSTM instead of nn.Recurrent)') cmd:option('-gru', false, 'use Gated Recurrent Units (nn.GRU instead of nn.Recurrent)') cmd:option('-seqlen', 5, 'sequence length : back-propagate through time (BPTT) for this many time-steps') cmd:option('-hiddensize', '{200}', 'number of hidden units used at output of each recurrent layer. When more than one is specified, RNN/LSTMs/GRUs are stacked') cmd:option('-dropout', 0, 'apply dropout with this probability after each rnn layer. dropout <= 0 disables it.') -- data cmd:option('-batchsize', 32, 'number of examples per batch') cmd:option('-trainsize', -1, 'number of train examples seen between each epoch') cmd:option('-validsize', -1, 'number of valid examples used for early stopping and cross-validation') cmd:option('-savepath', paths.concat(dl.SAVE_PATH, 'rnnlm'), 'path to directory where experiment log (includes model) will be saved') cmd:option('-id', '', 'id string of this experiment (used to name output file) (defaults to a unique id)') cmd:text() local opt = cmd:parse(arg or {}) opt.hiddensize = loadstring(" return "..opt.hiddensize)() opt.schedule = loadstring(" return "..opt.schedule)() if not opt.silent then table.print(opt) end opt.id = opt.id == '' and ('ptb' .. ':' .. dl.uniqueid()) or opt.id --[[ data set ]]-- local trainset, validset, testset = dl.loadPTB({opt.batchsize,1,1}) if not opt.silent then print("Vocabulary size : "..#trainset.ivocab) print("Train set split into "..opt.batchsize.." sequences of length "..trainset:size()) end --[[ language model ]]-- local lm = nn.Sequential() -- input layer (i.e. word embedding space) local lookup = nn.LookupTable(#trainset.ivocab, opt.hiddensize[1]) lookup.maxnormout = -1 -- prevent weird maxnormout behaviour lm:add(lookup) -- input is seqlen x batchsize if opt.dropout > 0 and not opt.gru then -- gru has a dropout option lm:add(nn.Dropout(opt.dropout)) end lm:add(nn.SplitTable(1)) -- tensor to table of tensors -- rnn layers local stepmodule = nn.Sequential() -- applied at each time-step local inputsize = opt.hiddensize[1] for i,hiddensize in ipairs(opt.hiddensize) do local rnn if opt.gru then -- 1 Gated Recurrent Units rnn = nn.GRU(inputsize, hiddensize, nil, opt.dropout/2) elseif opt.lstm then -- 1 Long Short Term Memory units require 'nngraph' nn.FastLSTM.usenngraph = true -- faster rnn = nn.FastLSTM(inputsize, hiddensize) else -- simple recurrent neural network local rm = nn.Sequential() -- input is {x[t], h[t-1]} :add(nn.ParallelTable() :add(i==1 and nn.Identity() or nn.Linear(inputsize, hiddensize)) -- input layer :add(nn.Linear(hiddensize, hiddensize))) -- recurrent layer :add(nn.CAddTable()) -- merge :add(nn.Sigmoid()) -- transfer rnn = nn.Recurrence(rm, hiddensize, 1) end stepmodule:add(rnn) if opt.dropout > 0 then stepmodule:add(nn.Dropout(opt.dropout)) end inputsize = hiddensize end -- output layer stepmodule:add(nn.Linear(inputsize, #trainset.ivocab)) stepmodule:add(nn.LogSoftMax()) -- encapsulate stepmodule into a Sequencer lm:add(nn.Sequencer(stepmodule)) -- remember previous state between batches lm:remember((opt.lstm or opt.gru) and 'both' or 'eval') if not opt.silent then print"Language Model:" print(lm) end if opt.uniform > 0 then for k,param in ipairs(lm:parameters()) do param:uniform(-opt.uniform, opt.uniform) end end --[[ loss function ]]-- local crit = nn.ClassNLLCriterion() -- target is also seqlen x batchsize. local targetmodule = nn.SplitTable(1) if opt.cuda then targetmodule = nn.Sequential() :add(nn.Convert()) :add(targetmodule) end local criterion = nn.SequencerCriterion(crit) --[[ CUDA ]]-- if opt.cuda then require 'cunn' cutorch.setDevice(opt.device) lm:cuda() criterion:cuda() targetmodule:cuda() end --[[ experiment log ]]-- -- is saved to file every time a new validation minima is found local xplog = {} xplog.opt = opt -- save all hyper-parameters and such xplog.dataset = 'PennTreeBank' xplog.vocab = trainset.vocab -- will only serialize params/gradParams xplog.model = nn.Serial(lm) xplog.model:mediumSerial() --xplog.model = lm xplog.criterion = criterion xplog.targetmodule = targetmodule -- keep a log of NLL for each epoch xplog.trainppl = {} xplog.valppl = {} -- will be used for early-stopping xplog.minvalppl = 99999999 xplog.epoch = 0 local ntrial = 0 paths.mkdir(opt.savepath) local epoch = 1 opt.lr = opt.startlr opt.trainsize = opt.trainsize == -1 and trainset:size() or opt.trainsize opt.validsize = opt.validsize == -1 and validset:size() or opt.validsize while opt.maxepoch <= 0 or epoch <= opt.maxepoch do print("") print("Epoch #"..epoch.." :") -- 1. training local a = torch.Timer() lm:training() local sumErr = 0 for i, inputs, targets in trainset:subiter(opt.seqlen, opt.trainsize) do targets = targetmodule:forward(targets) -- forward local outputs = lm:forward(inputs) local err = criterion:forward(outputs, targets) sumErr = sumErr + err -- backward local gradOutputs = criterion:backward(outputs, targets) lm:zeroGradParameters() lm:backward(inputs, gradOutputs) -- update if opt.cutoff > 0 then local norm = lm:gradParamClip(opt.cutoff) -- affects gradParams opt.meanNorm = opt.meanNorm and (opt.meanNorm*0.9 + norm*0.1) or norm end lm:updateGradParameters(opt.momentum) -- affects gradParams lm:updateParameters(opt.lr) -- affects params lm:maxParamNorm(opt.maxnormout) -- affects params if opt.progress then xlua.progress(math.min(i + opt.seqlen, opt.trainsize), opt.trainsize) end if i % 1000 == 0 then collectgarbage() end end -- learning rate decay if opt.schedule then opt.lr = opt.schedule[epoch] or opt.lr else opt.lr = opt.lr + (opt.minlr - opt.startlr)/opt.saturate end opt.lr = math.max(opt.minlr, opt.lr) if not opt.silent then print("learning rate", opt.lr) if opt.meanNorm then print("mean gradParam norm", opt.meanNorm) end end if cutorch then cutorch.synchronize() end local speed = a:time().real/opt.trainsize print(string.format("Speed : %f sec/batch ", speed)) local ppl = torch.exp(sumErr/opt.trainsize) print("Training PPL : "..ppl) xplog.trainppl[epoch] = ppl -- 2. cross-validation lm:evaluate() local sumErr = 0 for i, inputs, targets in validset:subiter(opt.seqlen, opt.validsize) do targets = targetmodule:forward(targets) local outputs = lm:forward(inputs) local err = criterion:forward(outputs, targets) sumErr = sumErr + err end local ppl = torch.exp(sumErr/opt.validsize) print("Validation PPL : "..ppl) xplog.valppl[epoch] = ppl ntrial = ntrial + 1 -- early-stopping if ppl < xplog.minvalppl then -- save best version of model xplog.minvalppl = ppl xplog.epoch = epoch local filename = paths.concat(opt.savepath, opt.id..'.t7') print("Found new minima. Saving to "..filename) torch.save(filename, xplog) ntrial = 0 elseif ntrial >= opt.earlystop then print("No new minima found after "..ntrial.." epochs.") print("Stopping experiment.") break end collectgarbage() epoch = epoch + 1 end print("Evaluate model using : ") print("th evaluate-rnnlm.lua --xplogpath "..paths.concat(opt.savepath, opt.id..'.t7')..(opt.cuda and '-cuda' or ''))
bsd-3-clause
Devul/DarkRP
entities/weapons/ls_sniper/shared.lua
7
2644
AddCSLuaFile() if SERVER then AddCSLuaFile("cl_init.lua") end if CLIENT then SWEP.PrintName = "Silenced Sniper" SWEP.Author = "DarkRP Developers" SWEP.Slot = 0 SWEP.SlotPos = 0 SWEP.IconLetter = "n" killicon.AddFont("ls_sniper", "CSKillIcons", SWEP.IconLetter, Color(200, 200, 200, 255)) end DEFINE_BASECLASS("weapon_cs_base2") SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Category = "DarkRP (Weapon)" SWEP.ViewModel = "models/weapons/cstrike/c_snip_g3sg1.mdl" SWEP.WorldModel = "models/weapons/w_snip_g3sg1.mdl" SWEP.Weight = 3 SWEP.HoldType = "ar2" SWEP.Primary.Sound = Sound("Weapon_M4A1.Silenced") SWEP.Primary.Damage = 100 SWEP.Primary.Recoil = 0.03 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.0001 - .05 SWEP.Primary.ClipSize = 25 SWEP.Primary.Delay = 0.7 SWEP.Primary.DefaultClip = 75 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "smg1" SWEP.IronSightsPos = Vector(0, 0, 0) -- this is just to make it disappear so it doesn't show up whilst scoped --[[--------------------------------------------------------------------------- SetupDataTables ---------------------------------------------------------------------------]] function SWEP:SetupDataTables() BaseClass.SetupDataTables(self) -- Int 0 = BurstBulletNum -- Int 1 = TotalUsedMagCount self:NetworkVar("Int", 2, "ScopeLevel") end --[[--------------------------------------------------------------------------- Reload ---------------------------------------------------------------------------]] function SWEP:Reload() if not IsValid(self:GetOwner()) then return end self:GetOwner():SetFOV(0, 0) self:SetScopeLevel(0) return BaseClass.Reload(self) end --[[--------------------------------------------------------------------------- SecondaryAttack ---------------------------------------------------------------------------]] local zoomFOV = {0, 0, 25, 5} function SWEP:SecondaryAttack() if not IsValid(self:GetOwner()) then return end if not self.IronSightsPos then return end self:SetNextSecondaryFire(CurTime() + 0.1) self:SetScopeLevel((self:GetScopeLevel() + 1) % 4) self:SetIronsights(self:GetScopeLevel() > 0) self:GetOwner():SetFOV(zoomFOV[self:GetScopeLevel() + 1], 0) end --[[--------------------------------------------------------------------------- Holster the weapon ---------------------------------------------------------------------------]] function SWEP:Holster() if not IsValid(self:GetOwner()) then return end self:GetOwner():SetFOV(0, 0) self:SetScopeLevel(0) self:SetIronsights(false) return BaseClass.Holster(self) end
mit
X-Coder/wire
lua/entities/gmod_wire_expression2/base/compiler.lua
8
25316
--[[ Expression 2 Compiler for Garry's Mod Andreas "Syranide" Svensson, me@syranide.com ]] AddCSLuaFile() Compiler = {} Compiler.__index = Compiler function Compiler.Execute(...) -- instantiate Compiler local instance = setmetatable({}, Compiler) -- and pcall the new instance's Process method. return pcall(Compiler.Process, instance, ...) end function Compiler:Error(message, instr) error(message .. " at line " .. instr[2][1] .. ", char " .. instr[2][2], 0) end function Compiler:Process(root, inputs, outputs, persist, delta, includes) -- Took params out becuase it isnt used. self.context = {} self:InitScope() -- Creates global scope! self.inputs = inputs self.outputs = outputs self.persist = persist self.includes = includes or {} self.prfcounter = 0 self.prfcounters = {} self.tvars = {} self.funcs = {} self.dvars = {} self.funcs_ret = {} for name, v in pairs(inputs) do self:SetGlobalVariableType(name, wire_expression_types[v][1], { nil, { 0, 0 } }) end for name, v in pairs(outputs) do self:SetGlobalVariableType(name, wire_expression_types[v][1], { nil, { 0, 0 } }) end for name, v in pairs(persist) do self:SetGlobalVariableType(name, wire_expression_types[v][1], { nil, { 0, 0 } }) end for name, v in pairs(delta) do self.dvars[name] = v end self:PushScope() local script = Compiler["Instr" .. string.upper(root[1])](self, root) self:PopScope() return script, self end function tps_pretty(tps) if not tps or #tps == 0 then return "void" end local ttt = {} for i = 1, #tps do ttt[i] = string.lower(wire_expression_types2[tps[i]][1]) if ttt[i] == "NORMAL" then ttt[i] = "number" end end return table.concat(ttt, ", ") end local function op_find(name) return E2Lib.optable_inv[name] end --[[ Scopes: Rusketh ]] -- function Compiler:InitScope() self.Scopes = {} self.ScopeID = 0 self.Scopes[0] = self.GlobalScope or {} --for creating new enviroments self.Scope = self.Scopes[0] self.GlobalScope = self.Scope end function Compiler:PushScope(Scope) self.ScopeID = self.ScopeID + 1 self.Scope = Scope or {} self.Scopes[self.ScopeID] = self.Scope end function Compiler:PopScope() self.ScopeID = self.ScopeID - 1 self.Scope = self.Scopes[self.ScopeID] self.Scopes[self.ScopeID] = self.Scope return table.remove(self.Scopes, self.ScopeID + 1) end function Compiler:SaveScopes() return { self.Scopes, self.ScopeID, self.Scope } end function Compiler:LoadScopes(Scopes) self.Scopes = Scopes[1] self.ScopeID = Scopes[2] self.Scope = Scopes[3] end function Compiler:SetLocalVariableType(name, type, instance) local typ = self.Scope[name] if typ and typ ~= type then self:Error("Variable (" .. E2Lib.limitString(name, 10) .. ") of type [" .. tps_pretty({ typ }) .. "] cannot be assigned value of type [" .. tps_pretty({ type }) .. "]", instance) end self.Scope[name] = type return self.ScopeID end function Compiler:SetGlobalVariableType(name, type, instance) for i = self.ScopeID, 0, -1 do local typ = self.Scopes[i][name] if typ and typ ~= type then self:Error("Variable (" .. E2Lib.limitString(name, 10) .. ") of type [" .. tps_pretty({ typ }) .. "] cannot be assigned value of type [" .. tps_pretty({ type }) .. "]", instance) elseif typ then return i end end self.GlobalScope[name] = type return 0 end function Compiler:GetVariableType(instance, name) for i = self.ScopeID, 0, -1 do local type = self.Scopes[i][name] if type then return type, i end end self:Error("Variable (" .. E2Lib.limitString(name, 10) .. ") does not exist", instance) return nil end -- --------------------------------------------------------------------------- function Compiler:EvaluateStatement(args, index) local name = string.upper(args[index + 2][1]) local ex, tp = Compiler["Instr" .. name](self, args[index + 2]) -- ex.TraceBack = args[index + 2] ex.TraceName = name return ex, tp end function Compiler:Evaluate(args, index) local ex, tp = self:EvaluateStatement(args, index) if tp == "" then self:Error("Function has no return value (void), cannot be part of expression or assigned", args[index + 2]) end return ex, tp end function Compiler:HasOperator(instr, name, tps) local pars = table.concat(tps) local a = wire_expression2_funcs["op:" .. name .. "(" .. pars .. ")"] return a and true or false end function Compiler:AssertOperator(instr, name, alias, tps) if not self:HasOperator(instr, name, tps) then self:Error("No such operator: " .. op_find(alias) .. "(" .. tps_pretty(tps) .. ")", instr) end end function Compiler:GetOperator(instr, name, tps) local pars = table.concat(tps) local a = wire_expression2_funcs["op:" .. name .. "(" .. pars .. ")"] if not a then self:Error("No such operator: " .. op_find(name) .. "(" .. tps_pretty(tps) .. ")", instr) return end self.prfcounter = self.prfcounter + (a[4] or 3) return { a[3], a[2], a[1] } end function Compiler:UDFunction(Sig) if self.funcs_ret and self.funcs_ret[Sig] then return { Sig, self.funcs_ret[Sig], function(self, args) if self.funcs and self.funcs[Sig] then return self.funcs[Sig](self, args) elseif self.funcs_ret and self.funcs_ret[Sig] then -- This only occurs if a function's definition isn't executed before the function is called -- Would probably only accidentally come about when pasting an E2 that has function definitions in -- if(first()) instead of if(first() || duped()) error("UDFunction: " .. Sig .. " undefined at runtime!", -1) -- return wire_expression_types2[self.funcs_ret[Sig]][2] -- This would return the default value for the type, probably better to error though end end, 20 } end end function Compiler:GetFunction(instr, Name, Args) local Params = table.concat(Args) local Func = wire_expression2_funcs[Name .. "(" .. Params .. ")"] if not Func then Func = self:UDFunction(Name .. "(" .. Params .. ")") end if not Func then for I = #Params, 0, -1 do Func = wire_expression2_funcs[Name .. "(" .. Params:sub(1, I) .. "...)"] if Func then break end end end if not Func then self:Error("No such function: " .. Name .. "(" .. tps_pretty(Args) .. ")", instr) return end self.prfcounter = self.prfcounter + (Func[4] or 20) return { Func[3], Func[2], Func[1] } end function Compiler:GetMethod(instr, Name, Meta, Args) local Params = Meta .. ":" .. table.concat(Args) local Func = wire_expression2_funcs[Name .. "(" .. Params .. ")"] if not Func then Func = self:UDFunction(Name .. "(" .. Params .. ")") end if not Func then for I = #Params, #Meta + 1, -1 do Func = wire_expression2_funcs[Name .. "(" .. Params:sub(1, I) .. "...)"] if Func then break end end end if not Func then self:Error("No such function: " .. tps_pretty({ Meta }) .. ":" .. Name .. "(" .. tps_pretty(Args) .. ")", instr) return end self.prfcounter = self.prfcounter + (Func[4] or 20) return { Func[3], Func[2], Func[1] } end function Compiler:PushPrfCounter() self.prfcounters[#self.prfcounters + 1] = self.prfcounter self.prfcounter = 0 end function Compiler:PopPrfCounter() local prfcounter = self.prfcounter self.prfcounter = self.prfcounters[#self.prfcounters] self.prfcounters[#self.prfcounters] = nil return prfcounter end -- ------------------------------------------------------------------------ function Compiler:InstrSEQ(args) self:PushPrfCounter() local stmts = { self:GetOperator(args, "seq", {})[1], 0 } for i = 1, #args - 2 do stmts[#stmts + 1] = self:EvaluateStatement(args, i) end stmts[2] = self:PopPrfCounter() return stmts end function Compiler:InstrBRK(args) return { self:GetOperator(args, "brk", {})[1] } end function Compiler:InstrCNT(args) return { self:GetOperator(args, "cnt", {})[1] } end function Compiler:InstrFOR(args) local var = args[3] local estart, tp1 = self:Evaluate(args, 2) local estop, tp2 = self:Evaluate(args, 3) local estep, tp3 if args[6] then estep, tp3 = self:Evaluate(args, 4) if tp1 ~= "n" or tp2 ~= "n" or tp3 ~= "n" then self:Error("for(" .. tps_pretty({ tp1 }) .. ", " .. tps_pretty({ tp2 }) .. ", " .. tps_pretty({ tp3 }) .. ") is invalid, only supports indexing by number", args) end else if tp1 ~= "n" or tp2 ~= "n" then self:Error("for(" .. tps_pretty({ tp1 }) .. ", " .. tps_pretty({ tp2 }) .. ") is invalid, only supports indexing by number", args) end end self:PushScope() self:SetLocalVariableType(var, "n", args) local stmt = self:EvaluateStatement(args, 5) self:PopScope() return { self:GetOperator(args, "for", {})[1], var, estart, estop, estep, stmt } end function Compiler:InstrWHL(args) self:PushScope() self:PushPrfCounter() local cond = self:Evaluate(args, 1) local prf_cond = self:PopPrfCounter() local stmt = self:EvaluateStatement(args, 2) self:PopScope() return { self:GetOperator(args, "whl", {})[1], cond, stmt, prf_cond } end function Compiler:InstrIF(args) self:PushPrfCounter() local ex1, tp1 = self:Evaluate(args, 1) local prf_cond = self:PopPrfCounter() self:PushScope() local st1 = self:EvaluateStatement(args, 2) self:PopScope() self:PushScope() local st2 = self:EvaluateStatement(args, 3) self:PopScope() local rtis = self:GetOperator(args, "is", { tp1 }) local rtif = self:GetOperator(args, "if", { rtis[2] }) return { rtif[1], prf_cond, { rtis[1], ex1 }, st1, st2 } end function Compiler:InstrDEF(args) local ex1, tp1 = self:Evaluate(args, 1) self:PushPrfCounter() local ex2, tp2 = self:Evaluate(args, 2) local prf_ex2 = self:PopPrfCounter() local rtis = self:GetOperator(args, "is", { tp1 }) local rtif = self:GetOperator(args, "def", { rtis[2] }) local rtdat = self:GetOperator(args, "dat", {}) if tp1 ~= tp2 then self:Error("Different types (" .. tps_pretty({ tp1 }) .. ", " .. tps_pretty({ tp2 }) .. ") returned in default conditional", args) end return { rtif[1], { rtis[1], { rtdat[1], nil } }, ex1, ex2, prf_ex2 }, tp1 end function Compiler:InstrCND(args) local ex1, tp1 = self:Evaluate(args, 1) self:PushPrfCounter() local ex2, tp2 = self:Evaluate(args, 2) local prf_ex2 = self:PopPrfCounter() self:PushPrfCounter() local ex3, tp3 = self:Evaluate(args, 3) local prf_ex3 = self:PopPrfCounter() local rtis = self:GetOperator(args, "is", { tp1 }) local rtif = self:GetOperator(args, "cnd", { rtis[2] }) if tp2 ~= tp3 then self:Error("Different types (" .. tps_pretty({ tp2 }) .. ", " .. tps_pretty({ tp3 }) .. ") returned in conditional", args) end return { rtif[1], { rtis[1], ex1 }, ex2, ex3, prf_ex2, prf_ex3 }, tp2 end function Compiler:InstrFUN(args) local exprs = { false } local tps = {} for i = 1, #args[4] do local ex, tp = self:Evaluate(args[4], i - 2) tps[#tps + 1] = tp exprs[#exprs + 1] = ex end local rt = self:GetFunction(args, args[3], tps) exprs[1] = rt[1] exprs[#exprs + 1] = tps return exprs, rt[2] end function Compiler:InstrSFUN(args) local exprs = { false } local fexp, ftp = self:Evaluate(args, 1) if ftp ~= "s" then self:Error("User function is not string-type", args) end local tps = {} for i = 1, #args[4] do local ex, tp = self:Evaluate(args[4], i - 2) tps[#tps + 1] = tp exprs[#exprs + 1] = ex end local rtsfun = self:GetOperator(args, "sfun", {})[1] local typeids_str = table.concat(tps, "") return { rtsfun, fexp, exprs, tps, typeids_str, args[5] }, args[5] end function Compiler:InstrMTO(args) local exprs = { false } local tps = {} local ex, tp = self:Evaluate(args, 2) exprs[#exprs + 1] = ex for i = 1, #args[5] do local ex, tp = self:Evaluate(args[5], i - 2) tps[#tps + 1] = tp exprs[#exprs + 1] = ex end local rt = self:GetMethod(args, args[3], tp, tps) exprs[1] = rt[1] exprs[#exprs + 1] = tps return exprs, rt[2] end function Compiler:InstrASS(args) local op = args[3] local ex, tp = self:Evaluate(args, 2) local ScopeID = self:SetGlobalVariableType(op, tp, args) local rt = self:GetOperator(args, "ass", { tp }) if ScopeID == 0 and self.dvars[op] then local stmts = { self:GetOperator(args, "seq", {})[1], 0 } stmts[3] = { self:GetOperator(args, "ass", { tp })[1], "$" .. op, { self:GetOperator(args, "var", {})[1], op, ScopeID }, ScopeID } stmts[4] = { rt[1], op, ex, ScopeID } return stmts, tp else return { rt[1], op, ex, ScopeID }, tp end end function Compiler:InstrASSL(args) local op = args[3] local ex, tp = self:Evaluate(args, 2) local ScopeID = self:SetLocalVariableType(op, tp, args) local rt = self:GetOperator(args, "ass", { tp }) if ScopeID == 0 then self:Error("Invalid use of 'local' inside the global scope.", args) end -- Just to make code look neater. return { rt[1], op, ex, ScopeID }, tp end function Compiler:InstrGET(args) local ex, tp = self:Evaluate(args, 1) local ex1, tp1 = self:Evaluate(args, 2) local tp2 = args[5] if tp2 == nil then if not self:HasOperator(args, "idx", { tp, tp1 }) then self:Error("No such operator: get " .. tps_pretty({ tp }) .. "[" .. tps_pretty({ tp1 }) .. "]", args) end local rt = self:GetOperator(args, "idx", { tp, tp1 }) return { rt[1], ex, ex1 }, rt[2] else if not self:HasOperator(args, "idx", { tp2, "=", tp, tp1 }) then self:Error("No such operator: get " .. tps_pretty({ tp }) .. "[" .. tps_pretty({ tp1, tp2 }) .. "]", args) end local rt = self:GetOperator(args, "idx", { tp2, "=", tp, tp1 }) return { rt[1], ex, ex1 }, tp2 end end function Compiler:InstrSET(args) local ex, tp = self:Evaluate(args, 1) local ex1, tp1 = self:Evaluate(args, 2) local ex2, tp2 = self:Evaluate(args, 3) if args[6] == nil then if not self:HasOperator(args, "idx", { tp, tp1, tp2 }) then self:Error("No such operator: set " .. tps_pretty({ tp }) .. "[" .. tps_pretty({ tp1 }) .. "]=" .. tps_pretty({ tp2 }), args) end local rt = self:GetOperator(args, "idx", { tp, tp1, tp2 }) return { rt[1], ex, ex1, ex2, ScopeID }, rt[2] else if tp2 ~= args[6] then self:Error("Indexing type mismatch, specified [" .. tps_pretty({ args[6] }) .. "] but value is [" .. tps_pretty({ tp2 }) .. "]", args) end if not self:HasOperator(args, "idx", { tp2, "=", tp, tp1, tp2 }) then self:Error("No such operator: set " .. tps_pretty({ tp }) .. "[" .. tps_pretty({ tp1, tp2 }) .. "]", args) end local rt = self:GetOperator(args, "idx", { tp2, "=", tp, tp1, tp2 }) return { rt[1], ex, ex1, ex2 }, tp2 end end -- generic code for all binary non-boolean operators for _, operator in ipairs({ "add", "sub", "mul", "div", "mod", "exp", "eq", "neq", "geq", "leq", "gth", "lth", "band", "band", "bor", "bxor", "bshl", "bshr" }) do Compiler["Instr" .. operator:upper()] = function(self, args) local ex1, tp1 = self:Evaluate(args, 1) local ex2, tp2 = self:Evaluate(args, 2) local rt = self:GetOperator(args, operator, { tp1, tp2 }) return { rt[1], ex1, ex2 }, rt[2] end end function Compiler:InstrINC(args) local op = args[3] local tp, ScopeID = self:GetVariableType(args, op) local rt = self:GetOperator(args, "inc", { tp }) if ScopeID == 0 and self.dvars[op] then local stmts = { self:GetOperator(args, "seq", {})[1], 0 } stmts[3] = { self:GetOperator(args, "ass", { tp })[1], "$" .. op, { self:GetOperator(args, "var", {})[1], op, ScopeID }, ScopeID } stmts[4] = { rt[1], op, ScopeID } return stmts else return { rt[1], op, ScopeID } end end function Compiler:InstrDEC(args) local op = args[3] local tp, ScopeID = self:GetVariableType(args, op) local rt = self:GetOperator(args, "dec", { tp }) if ScopeID == 0 and self.dvars[op] then local stmts = { self:GetOperator(args, "seq", {})[1], 0 } stmts[3] = { self:GetOperator(args, "ass", { tp })[1], "$" .. op, { self:GetOperator(args, "var", {})[1], op, ScopeID }, ScopeID } stmts[4] = { rt[1], op, ScopeID } return stmts else return { rt[1], op, ScopeID } end end function Compiler:InstrNEG(args) local ex1, tp1 = self:Evaluate(args, 1) local rt = self:GetOperator(args, "neg", { tp1 }) return { rt[1], ex1 }, rt[2] end function Compiler:InstrNOT(args) local ex1, tp1 = self:Evaluate(args, 1) local rt1is = self:GetOperator(args, "is", { tp1 }) local rt = self:GetOperator(args, "not", { rt1is[2] }) return { rt[1], { rt1is[1], ex1 } }, rt[2] end function Compiler:InstrAND(args) local ex1, tp1 = self:Evaluate(args, 1) local ex2, tp2 = self:Evaluate(args, 2) local rt1is = self:GetOperator(args, "is", { tp1 }) local rt2is = self:GetOperator(args, "is", { tp2 }) local rt = self:GetOperator(args, "and", { rt1is[2], rt2is[2] }) return { rt[1], { rt1is[1], ex1 }, { rt2is[1], ex2 } }, rt[2] end function Compiler:InstrOR(args) local ex1, tp1 = self:Evaluate(args, 1) local ex2, tp2 = self:Evaluate(args, 2) local rt1is = self:GetOperator(args, "is", { tp1 }) local rt2is = self:GetOperator(args, "is", { tp2 }) local rt = self:GetOperator(args, "or", { rt1is[2], rt2is[2] }) return { rt[1], { rt1is[1], ex1 }, { rt2is[1], ex2 } }, rt[2] end function Compiler:InstrTRG(args) local op = args[3] local tp = self:GetVariableType(args, op) local rt = self:GetOperator(args, "trg", {}) return { rt[1], op }, rt[2] end function Compiler:InstrDLT(args) local op = args[3] local tp, ScopeID = self:GetVariableType(args, op) if ScopeID ~= 0 or not self.dvars[op] then self:Error("Delta operator ($" .. E2Lib.limitString(op, 10) .. ") cannot be used on temporary variables", args) end self.dvars[op] = true self:AssertOperator(args, "sub", "dlt", { tp, tp }) local rt = self:GetOperator(args, "sub", { tp, tp }) local rtvar = self:GetOperator(args, "var", {}) return { rt[1], { rtvar[1], op, ScopeID }, { rtvar[1], "$" .. op, ScopeID } }, rt[2] end function Compiler:InstrIWC(args) local op = args[3] if self.inputs[op] then local tp = self:GetVariableType(args, op) local rt = self:GetOperator(args, "iwc", {}) return { rt[1], op }, rt[2] elseif self.outputs[op] then local tp = self:GetVariableType(args, op) local rt = self:GetOperator(args, "owc", {}) return { rt[1], op }, rt[2] else self:Error("Connected operator (->" .. E2Lib.limitString(op, 10) .. ") can only be used on inputs or outputs", args) end end function Compiler:InstrNUM(args) self.prfcounter = self.prfcounter + 0.5 RunString("Compiler.native = function() return " .. args[3] .. " end") return { Compiler.native }, "n" end function Compiler:InstrNUMI(args) self.prfcounter = self.prfcounter + 1 Compiler.native = { 0, tonumber(args[3]) } RunString("local value = Compiler.native Compiler.native = function() return value end") return { Compiler.native }, "c" end function Compiler:InstrNUMJ(args) self.prfcounter = self.prfcounter + 1 Compiler.native = { 0, 0, tonumber(args[3]), 0 } RunString("local value = Compiler.native Compiler.native = function() return value end") return { Compiler.native }, "q" end function Compiler:InstrNUMK(args) self.prfcounter = self.prfcounter + 1 Compiler.native = { 0, 0, 0, tonumber(args[3]) } RunString("local value = Compiler.native Compiler.native = function() return value end") return { Compiler.native }, "q" end function Compiler:InstrSTR(args) self.prfcounter = self.prfcounter + 1.0 RunString(string.format("Compiler.native = function() return %q end", args[3])) return { Compiler.native }, "s" end function Compiler:InstrVAR(args) self.prfcounter = self.prfcounter + 1.0 local tp, ScopeID = self:GetVariableType(args, args[3]) RunString(string.format("Compiler.native = function(self) return self.Scopes[%i][%q] end", ScopeID, args[3])) -- This Line! return { Compiler.native }, tp end function Compiler:InstrFEA(args) -- local sfea = self:Instruction(trace, "fea", keyvar, valvar, valtype, tableexpr, self:Block("foreach statement")) local keyvar, valvar, valtype = args[3], args[4], args[5] local tableexpr, tabletp = self:Evaluate(args, 4) local op = self:GetOperator(args, "fea", { tabletp }) self:PushScope() self:SetLocalVariableType(keyvar, op[2], args) self:SetLocalVariableType(valvar, valtype, args) local stmt, _ = self:EvaluateStatement(args, 5) self:PopScope() return { op[1], keyvar, valvar, valtype, tableexpr, stmt } end function Compiler:InstrFUNCTION(args) local Sig, Return, Type, Args, Block = args[3], args[4], args[5], args[6], args[7] Return = Return or "" Type = Type or "" local OldScopes = self:SaveScopes() self:InitScope() -- Create a new Scope Enviroment self:PushScope() for K, D in pairs(Args) do local Name, Type = D[1], wire_expression_types[D[2]][1] self:SetLocalVariableType(Name, Type, args) end if self.funcs_ret[Sig] and self.funcs_ret[Sig] ~= Return then local TP = tps_pretty(self.funcs_ret[Sig]) self:Error("Function " .. Sig .. " must be given return type " .. TP, args) end self.funcs_ret[Sig] = Return self.func_ret = Return local Stmt = self:EvaluateStatement(args, 5) -- Offset of -2 self.func_ret = nil self:PopScope() self:LoadScopes(OldScopes) -- Reload the old enviroment self.prfcounter = self.prfcounter + 40 return { self:GetOperator(args, "function", {})[1], Stmt, args } end function Compiler:InstrRETURN(args) local Value, Type = self:Evaluate(args, 1) if not self.func_ret or self.func_ret == "" then self:Error("Return type mismatch: void expected, got " .. tps_pretty(Type), args) elseif self.func_ret ~= Type then self:Error("Return type mismatch: " .. tps_pretty(self.func_ret) .. " expected, got " .. tps_pretty(Type), args) end return { self:GetOperator(args, "return", {})[1], Value, Type } end function Compiler:InstrRETURNVOID(args) if self.func_ret and self.func_ret ~= "" then self:Error("Return type mismatch: " .. tps_pretty(self.func_ret) .. " expected got, void", args) end return { self:GetOperator(args, "return", {})[1], Value, Type } end function Compiler:InstrKVTABLE(args) local s = {} local stypes = {} local exprs = args[3] for k, v in pairs(exprs) do local key, type = self["Instr" .. string.upper(k[1])](self, k) if type == "s" or type == "n" then local value, type = self["Instr" .. string.upper(v[1])](self, v) s[key] = value stypes[key] = type else self:Error("String or number expected, got " .. tps_pretty(type), k) end end return { self:GetOperator(args, "kvtable", {})[1], s, stypes }, "t" end function Compiler:InstrKVARRAY(args) local values = {} local types = {} local exprs = args[3] for k, v in pairs(exprs) do local key, type = self["Instr" .. string.upper(k[1])](self, k) if type == "n" then local value, type = self["Instr" .. string.upper(v[1])](self, v) values[key] = value types[key] = type else self:Error("Number expected, got " .. tps_pretty(type), k) end end return { self:GetOperator(args, "kvarray", {})[1], values, types }, "r" end function Compiler:InstrSWITCH(args) self:PushPrfCounter() local value, type = Compiler["Instr" .. string.upper(args[3][1])](self, args[3]) -- This is the value we are passing though the switch statment local prf_cond = self:PopPrfCounter() self:PushScope() local cases = {} local Cases = args[4] for i = 1, #Cases do local case, block, prf_eq, eq = Cases[i][1], Cases[i][2], 0, nil if case then -- The default will not have one self.ScopeID = self.ScopeID - 1 -- For the case statments we pop the scope back self:PushPrfCounter() local ex, tp = Compiler["Instr" .. string.upper(case[1])](self, case) --This is the value we are checking against prf_eq = self:PopPrfCounter() -- We add some pref self.ScopeID = self.ScopeID + 1 if tp == "" then -- There is no value self:Error("Function has no return value (void), cannot be part of expression or assigned", args) elseif tp ~= type then -- Value types do not match. self:Error("Case missmatch can not compare " .. tps_pretty(type) .. " with " .. tps_pretty(tp), args) end eq = { self:GetOperator(args, "eq", { type, tp })[1], value, ex } -- This is the equals operator to check if values match else default=i end local stmts = Compiler["Instr" .. string.upper(block[1])](self, block) -- This is statments that are run when Values match cases[i] = { eq, stmts, prf_eq } end self:PopScope() local rtswitch = self:GetOperator(args, "switch", {}) return { rtswitch[1], prf_cond, cases, default } end function Compiler:InstrINCLU(args) local file = args[3] local include = self.includes[file] if not include or not include[1] then self:Error("Problem including file '" .. file .. "'", args) end if not include[2] then include[2] = true -- Tempory value to prvent E2 compiling itself when itself. (INFINATE LOOOP!) local OldScopes = self:SaveScopes() self:InitScope() -- Create a new Scope Enviroment self:PushScope() local root = include[1] local status, script = pcall(Compiler["Instr" .. string.upper(root[1])], self, root) if not status then if script:find("C stack overflow") then script = "Include depth to deep" end if not self.IncludeError then -- Otherwise Errors messages will be wrapped inside other error messages! self.IncludeError = true self:Error("include '" .. file .. "' -> " .. script, args) else error(script, 0) end end include[2] = script self:PopScope() self:LoadScopes(OldScopes) -- Reload the old enviroment end return { self:GetOperator(args, "include", {})[1], file } end
gpl-3.0
thedraked/darkstar
scripts/zones/Southern_San_dOria/npcs/Blendare.lua
14
1949
----------------------------------- -- Area: Southern San d'Oria -- NPC: Blendare -- Type: Standard NPC -- @zone 230 -- @pos 33.033 0.999 -30.119 -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeBlendare") == 0) then player:messageSpecial(BLENDARE_DIALOG); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeBlendare",1); player:messageSpecial(FLYER_ACCEPTED); player:tradeComplete(); elseif (player:getVar("tradeBlendare") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x025e) -- my brother always takes my sweets -- player:startEvent(0x0256) --did nothing no speech or text -- player:startEvent(0x03b1) --black screen and hang 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 == 0x025e) then player:setVar("BrothersCS", 1) end end;
gpl-3.0
Devul/DarkRP
gamemode/modules/fadmin/fadmin/playeractions/noclip/sv_init.lua
7
3121
local sbox_noclip = GetConVar("sbox_noclip") local function SetNoclip(ply, cmd, args) if not FAdmin.Access.PlayerHasPrivilege(ply, "SetNoclip") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end if not args[1] then return false end local targets = FAdmin.FindPlayer(args[1]) if not targets or #targets == 1 and not IsValid(targets[1]) then FAdmin.Messages.SendMessage(ply, 1, "Player not found") return false end local Toggle = tobool(tonumber(args[2])) or false for _, target in pairs(targets) do if IsValid(target) then if Toggle then target:FAdmin_SetGlobal("FADmin_CanNoclip", true) target:FAdmin_SetGlobal("FADmin_DisableNoclip", false) if not FAdmin.Access.PlayerHasPrivilege(target, "Noclip") then FAdmin.Messages.SendMessage(ply, 3, "This is not permanent! Make it permanent with a custom group in SetAccess!") end else target:FAdmin_SetGlobal("FADmin_CanNoclip", false) target:FAdmin_SetGlobal("FADmin_DisableNoclip", true) if target:GetMoveType() == MOVETYPE_NOCLIP then target:SetMoveType(MOVETYPE_WALK) end end end end if Toggle then FAdmin.Messages.FireNotification("noclipenable", ply, targets) else FAdmin.Messages.FireNotification("noclipdisable", ply, targets) end return true, targets, Toggle end FAdmin.StartHooks["zz_Noclip"] = function() FAdmin.Messages.RegisterNotification{ name = "noclipenable", hasTarget = true, receivers = "involved", message = {"instigator", " enabled noclip for ", "targets"}, } FAdmin.Messages.RegisterNotification{ name = "noclipdisable", hasTarget = true, receivers = "involved", message = {"instigator", " disabled noclip for ", "targets"}, } FAdmin.Access.AddPrivilege("Noclip", 2) FAdmin.Access.AddPrivilege("SetNoclip", 2) FAdmin.Commands.AddCommand("SetNoclip", SetNoclip) end local function sendNoclipMessage(ply) if ply.FADmin_HasGotNoclipMessage then return end FAdmin.Messages.SendMessage(ply, 4, "Noclip allowed") ply.FADmin_HasGotNoclipMessage = true end hook.Add("PlayerNoClip", "FAdmin_noclip", function(ply) if ply:FAdmin_GetGlobal("FADmin_DisableNoclip") then FAdmin.Messages.SendMessage(ply, 5, "Noclip disallowed!") return false end -- No further judgement when sbox_noclip is on if sbox_noclip:GetBool() then return end if ply:FAdmin_GetGlobal("FADmin_CanNoclip") then sendNoclipMessage(ply) return true end -- Has privilege if not FAdmin.Access.PlayerHasPrivilege(ply, "Noclip") then return end -- Disallow if other hooks say no for k, v in pairs(hook.GetTable().PlayerNoClip) do if k == "FAdmin_noclip" then continue end if v(ply) == false then return false end end sendNoclipMessage(ply) return true end)
mit
thedraked/darkstar
scripts/zones/Windurst_Waters/npcs/Taajiji.lua
17
1798
----------------------------------- -- Area: Windurst Waters -- NPC: Taajiji -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,TAAJIJI_SHOP_DIALOG); stock = { 0x113B, 756,1, --Dhalmel Pie 0x1152, 5050,1, --Mushroom Risotto 0x11CA, 12762,1, --Shallops Tropicale 0x1129, 984,1, --Orange Kuchen 0x119A, 5216,2, --Mutton Tortilla 0x1158, 6064,2, --Whitefish Stew 0x11DC, 1669,2, --Beaugreen Sautee 0x1146, 184,2, --Orange Juice 0x1156, 1324,2, --Dhalmel Steak 0x1138, 128,3, --Tortilla 0x118C, 552,3, --Puls 0x1151, 2387,3, --Dhalmel Stew 0x119D, 10,3, --Distilled Water 0x118D, 184,3, --Windurstian Tea 0x11CB, 1711,3 --Windurst Salad } showNationShop(player, NATION_WINDURST, 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
thedraked/darkstar
scripts/globals/weaponskills/raging_fists.lua
26
1437
----------------------------------- -- Raging Fists -- Hand-to-Hand weapon skill -- Skill Level: 125 -- Delivers a fivefold attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder Belt. -- Element: None -- Modifiers: STR:30% ; DEX:30% -- 100%TP 200%TP 300%TP -- 1.00 4.6 9 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 5; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.2; params.dex_wsc = 0.2; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp200 = 4.6; params.ftp300 = 9 params.str_wsc = 0.3; params.dex_wsc = 0.3; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
SnabbCo/snabbswitch
src/apps/lwaftr/binding_table.lua
2
14193
-- AFTR Binding Table -- -- A binding table is a collection of softwires (tunnels). One endpoint -- of the softwire is in the AFTR and the other is in the B4. A -- softwire provisions an IPv4 address (or a part of an IPv4 address) to -- a customer behind a B4. The B4 arranges for all IPv4 traffic to be -- encapsulated in IPv6 and sent to the AFTR; the AFTR does the reverse. -- The binding table is how the AFTR knows which B4 is associated with -- an incoming packet. -- -- There are three parts of a binding table: the PSID info map, the -- border router (BR) address table, and the softwire map. -- -- The PSID info map facilitates IPv4 address sharing. The lightweight -- 4-over-6 architecture supports sharing of IPv4 addresses by -- partitioning the space of TCP/UDP/ICMP ports into disjoint "port -- sets". Each softwire associated with an IPv4 address corresponds to -- a different set of ports on that address. The way that the ports are -- partitioned is specified in RFC 7597: each address has an associated -- set of parameters that specifies how to compute a "port set -- identifier" (PSID) from a given port. -- -- 0 1 -- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 -- +-----------+-----------+-------+ -- Ports in | A | PSID | j | -- the CE port set | > 0 | | | -- +-----------+-----------+-------+ -- | a bits | k bits |m bits | -- -- Figure 2: Structure of a Port-Restricted Port Field -- -- Source: http://tools.ietf.org/html/rfc7597#section-5.1 -- -- We find the specification's names to be a bit obtuse, so we refer to -- them using the following names: -- -- a bits = reserved_ports_bit_count. -- k bits = psid_length. -- m bits = shift. -- -- When a packet comes in, we take the IPv4 address and look up the PSID -- parameters from the PSID info table. We use those parameters to -- compute the PSID. Together, the IPv4 address and PSID are used as a -- key into the softwire table, which determines if the packet -- corresponds to a known softwire, and if so the IPv6 address of the B4. -- -- A successful lookup into the softwire table will also indicate the -- IPv6 address of the AFTR itself. As described in -- https://www.ietf.org/id/draft-farrer-softwire-br-multiendpoints-01.txt, -- an AFTR may have multiple configured addresses. -- -- Note that if reserved_ports_bit_count is nonzero, the lwAFTR must -- drop a packet whose port is less than 2^reserved_ports_bit_count. In -- practice though we just return a PSID that is out of range (greater -- or equal to 2^psid_length), which will cause the softwire lookup to -- fail. Likewise if we get a packet to an IPv4 address that's not -- under our control, we return 0 for the PSID, knowing that the -- subsequent softwire lookup will fail. -- module(..., package.seeall) local bit = require('bit') local ffi = require("ffi") local rangemap = require("apps.lwaftr.rangemap") local ctable = require("lib.ctable") local ipv6 = require("lib.protocol.ipv6") local ipv4_ntop = require("lib.yang.util").ipv4_ntop local band, lshift, rshift = bit.band, bit.lshift, bit.rshift psid_map_key_t = ffi.typeof[[ struct { uint32_t addr; } ]] psid_map_value_t = ffi.typeof[[ struct { uint16_t psid_length; uint16_t shift; } ]] BTLookupQueue = {} -- BTLookupQueue needs a binding table to get softwires and PSID lookup. function BTLookupQueue.new(binding_table) local ret = { binding_table = assert(binding_table), } ret.streamer = binding_table.softwires:make_lookup_streamer(32) ret.packet_queue = ffi.new("struct packet * [32]") ret.length = 0 return setmetatable(ret, {__index=BTLookupQueue}) end function BTLookupQueue:enqueue_lookup(pkt, ipv4, port) local n = self.length local streamer = self.streamer streamer.entries[n].key.ipv4 = ipv4 streamer.entries[n].key.psid = port self.packet_queue[n] = pkt n = n + 1 self.length = n return n == 32 end function BTLookupQueue:process_queue() if self.length > 0 then local streamer = self.streamer for n = 0, self.length-1 do local ipv4 = streamer.entries[n].key.ipv4 local port = streamer.entries[n].key.psid streamer.entries[n].key.psid = self.binding_table:lookup_psid(ipv4, port) end streamer:stream() end return self.length end function BTLookupQueue:get_lookup(n) if n < self.length then local streamer = self.streamer local pkt, b4_ipv6, br_ipv6 pkt = self.packet_queue[n] if not streamer:is_empty(n) then b4_ipv6 = streamer.entries[n].value.b4_ipv6 br_ipv6 = streamer.entries[n].value.br_address end return pkt, b4_ipv6, br_ipv6 end end function BTLookupQueue:reset_queue() self.length = 0 end local BindingTable = {} local lookup_key function BindingTable.new(psid_map, softwires) local ret = { psid_map = assert(psid_map), softwires = assert(softwires), } lookup_key = ret.softwires.entry_type().key return setmetatable(ret, {__index=BindingTable}) end function BindingTable:add_softwire_entry(entry_blob) local entry = self.softwires.entry_type() assert(ffi.sizeof(entry) == ffi.sizeof(entry_blob)) ffi.copy(entry, entry_blob, ffi.sizeof(entry_blob)) self.softwires:add(entry.key, entry.value) end function BindingTable:remove_softwire_entry(entry_key_blob) local entry = self.softwires.entry_type() assert(ffi.sizeof(entry.key) == ffi.sizeof(entry_key_blob)) ffi.copy(entry.key, entry_key_blob, ffi.sizeof(entry_key_blob)) self.softwires:remove(entry.key) end function BindingTable:lookup(ipv4, port) local psid = self:lookup_psid(ipv4, port) lookup_key.ipv4 = ipv4 lookup_key.psid = psid local entry = self.softwires:lookup_ptr(lookup_key) if entry then return entry.value end return nil end function BindingTable:is_managed_ipv4_address(ipv4) -- The PSID info map covers only the addresses that are declared in -- the binding table. Other addresses are recorded as having -- psid_length == shift == 0. local psid_info = self.psid_map:lookup(ipv4).value return psid_info.psid_length + psid_info.shift > 0 end function BindingTable:lookup_psid(ipv4, port) local psid_info = self.psid_map:lookup(ipv4).value local psid_len, shift = psid_info.psid_length, psid_info.shift local psid_mask = lshift(1, psid_len) - 1 local psid = band(rshift(port, shift), psid_mask) -- Are there any restricted ports for this address? if psid_len + shift < 16 then local reserved_ports_bit_count = 16 - psid_len - shift local first_allocated_port = lshift(1, reserved_ports_bit_count) -- The port is within the range of restricted ports. Assign a -- bogus PSID so that lookup will fail. if port < first_allocated_port then psid = psid_mask + 1 end end return psid end -- Iterate over the set of IPv4 addresses managed by a binding -- table. Invoke like: -- -- for ipv4_lo, ipv4_hi, psid_info in bt:iterate_psid_map() do ... end -- -- The IPv4 values are host-endianness uint32 values, and are an -- inclusive range to which the psid_info applies. The psid_info is a -- psid_map_value_t pointer, which has psid_length and shift members. function BindingTable:iterate_psid_map() local f, state, lo = self.psid_map:iterate() local function next_entry() local hi, value repeat lo, hi, value = f(state, lo) if lo == nil then return end until value.psid_length > 0 or value.shift > 0 return lo, hi, value end return next_entry end -- Iterate over the softwires in a binding table. Invoke like: -- -- for entry in bt:iterate_softwires() do ... end -- -- Each entry is a pointer with two members, "key" and "value". They -- key is a softwire_key_t and has "ipv4" and "psid" members. The value -- is a softwire_value_t and has "br_address" and "b4_ipv6" members. Both -- members are a uint8_t[16]. function BindingTable:iterate_softwires() return self.softwires:iterate() end function pack_psid_map_entry (softwire) local port_set = assert(softwire.value.port_set) local psid_length = port_set.psid_length local shift = 16 - psid_length - (port_set.reserved_ports_bit_count or 0) assert(psid_length + shift <= 16, ("psid_length %s + shift %s should not exceed 16"): format(psid_length, shift)) local key = softwire.key.ipv4 local value = {psid_length = psid_length, shift = shift} return key, value end function load (conf) local psid_builder = rangemap.RangeMapBuilder.new(psid_map_value_t) -- Lets create an intermediatory PSID map to verify if we've added -- a PSID entry yet, if we have we need to verify that the values -- are the same, if not we need to error. local inter_psid_map = { keys = {} } function inter_psid_map:exists (key, value) local v = self.keys[key] if not v then return false end if v.psid_length ~= v.psid_length or v.shift ~= v.shift then error("Port set already added with different values: "..key) end return true end function inter_psid_map:add (key, value) self.keys[key] = value end for entry in conf.softwire:iterate() do -- Check that the map either hasn't been added or that -- it's the same value as one which has. local psid_key, psid_value = pack_psid_map_entry(entry) if not inter_psid_map:exists(psid_key, psid_value) then inter_psid_map:add(psid_key, psid_value) psid_builder:add(entry.key.ipv4, psid_value) end end local psid_map = psid_builder:build(psid_map_value_t(), true) return BindingTable.new(psid_map, conf.softwire) end function selftest() print('selftest: binding_table') local function load_str(str) local mem = require("lib.stream.mem") local yang = require('lib.yang.yang') local data = require('lib.yang.data') local schema = yang.load_schema_by_name('snabb-softwire-v3') local grammar = data.config_grammar_from_schema(schema) local subgrammar = assert(grammar.members['softwire-config']) local subgrammar = assert(subgrammar.members['binding-table']) local parse = data.data_parser_from_grammar(subgrammar) return load(parse(mem.open_input_string(str))) end local map = load_str([[ softwire { ipv4 178.79.150.233; psid 80; b4-ipv6 127:2:3:4:5:6:7:128; br-address 8:9:a:b:c:d:e:f; port-set { psid-length 16; }} softwire { ipv4 178.79.150.233; psid 2300; b4-ipv6 127:11:12:13:14:15:16:128; br-address 8:9:a:b:c:d:e:f; port-set { psid-length 16; }} softwire { ipv4 178.79.150.233; psid 2700; b4-ipv6 127:11:12:13:14:15:16:128; br-address 8:9:a:b:c:d:e:f; port-set { psid-length 16; }} softwire { ipv4 178.79.150.233; psid 4660; b4-ipv6 127:11:12:13:14:15:16:128; br-address 8:9:a:b:c:d:e:f; port-set { psid-length 16; }} softwire { ipv4 178.79.150.233; psid 7850; b4-ipv6 127:11:12:13:14:15:16:128; br-address 8:9:a:b:c:d:e:f; port-set { psid-length 16; }} softwire { ipv4 178.79.150.233; psid 22788; b4-ipv6 127:11:12:13:14:15:16:128; br-address 8:9:a:b:c:d:e:f; port-set { psid-length 16; }} softwire { ipv4 178.79.150.233; psid 54192; b4-ipv6 127:11:12:13:14:15:16:128; br-address 8:9:a:b:c:d:e:f; port-set { psid-length 16; }} softwire { ipv4 178.79.150.15; psid 0; b4-ipv6 127:22:33:44:55:66:77:128; br-address 8:9:a:b:c:d:e:f; port-set { psid-length 4; }} softwire { ipv4 178.79.150.15; psid 1; b4-ipv6 127:22:33:44:55:66:77:128; br-address 8:9:a:b:c:d:e:f; port-set { psid-length 4; }} softwire { ipv4 178.79.150.2; psid 7850; b4-ipv6 127:24:35:46:57:68:79:128; br-address 1E:1:1:1:1:1:1:af; port-set { psid-length 16; }} softwire { ipv4 178.79.150.3; psid 4; b4-ipv6 127:14:25:36:47:58:69:128; br-address 1E:2:2:2:2:2:2:af; port-set { psid-length 6; }} ]]) local ipv4_pton = require('lib.yang.util').ipv4_pton local ipv6_protocol = require("lib.protocol.ipv6") local function lookup(ipv4, port) return map:lookup(ipv4_pton(ipv4), port) end local function assert_lookup(ipv4, port, ipv6, br) local val = assert(lookup(ipv4, port)) assert(ffi.C.memcmp(ipv6_protocol:pton(ipv6), val.b4_ipv6, 16) == 0) assert(ffi.C.memcmp(ipv6_protocol:pton(br), val.br_address, 16) == 0) end assert_lookup('178.79.150.233', 80, '127:2:3:4:5:6:7:128', '8:9:a:b:c:d:e:f') assert(lookup('178.79.150.233', 79) == nil) assert(lookup('178.79.150.233', 81) == nil) assert_lookup('178.79.150.15', 80, '127:22:33:44:55:66:77:128', '8:9:a:b:c:d:e:f') assert_lookup('178.79.150.15', 4095, '127:22:33:44:55:66:77:128', '8:9:a:b:c:d:e:f') assert_lookup('178.79.150.15', 4096, '127:22:33:44:55:66:77:128', '8:9:a:b:c:d:e:f') assert_lookup('178.79.150.15', 8191, '127:22:33:44:55:66:77:128', '8:9:a:b:c:d:e:f') assert(lookup('178.79.150.15', 8192) == nil) assert_lookup('178.79.150.2', 7850, '127:24:35:46:57:68:79:128', '1E:1:1:1:1:1:1:af') assert(lookup('178.79.150.3', 4095) == nil) assert_lookup('178.79.150.3', 4096, '127:14:25:36:47:58:69:128', '1E:2:2:2:2:2:2:af') assert_lookup('178.79.150.3', 5119, '127:14:25:36:47:58:69:128', '1E:2:2:2:2:2:2:af') assert(lookup('178.79.150.3', 5120) == nil) assert(lookup('178.79.150.4', 7850) == nil) do local psid_map_iter = { { ipv4_pton('178.79.150.2'), { psid_length=16, shift=0 } }, { ipv4_pton('178.79.150.3'), { psid_length=6, shift=10 } }, { ipv4_pton('178.79.150.15'), { psid_length=4, shift=12 } }, { ipv4_pton('178.79.150.233'), { psid_length=16, shift=0 } } } local i = 1 for lo, hi, value in map:iterate_psid_map() do local ipv4, expected = unpack(psid_map_iter[i]) assert(lo == ipv4) assert(hi == ipv4) assert(value.psid_length == expected.psid_length) assert(value.shift == expected.shift) i = i + 1 end assert(i == #psid_map_iter + 1) end print('ok') end
apache-2.0
thedraked/darkstar
scripts/zones/Tavnazian_Safehold/TextIDs.lua
7
2111
-- 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> HOMEPOINT_SET = 10914; -- Home point set! FISHING_MESSAGE_OFFSET = 10253; -- You can't fish here -- Other Texts ITEM_DELIVERY_DIALOG = 10911; -- I can send your items to anywhere in Vana'diel! -- Quest Dialog NOMAD_MOOGLE_DIALOG = 10885; -- I'm a traveling moogle, kupo. I help adventurers in the Outlands access items they have stored in a Mog House elsewhere, kupo. -- Shop Text CAIPHIMONRIDE_SHOP_DIALOG = 10898; -- Welcome! Thanks to the supplies from Jeuno, I've been able to fix some of the weapons I had in storage! MELLEUPAUX_SHOP_DIALOG = 10900; -- Hello! With the arrival of supplies from Jeuno, we are now able to sell some of the items we had stored in these warehouses. KOMALATA_SHOP_DIALOG = 10895; -- Do you need any Tavnazian produce? We don't have much, but find a fine cook and your problems will be solved! MAZUROOOZURO_SHOP_DIALOG = 10894; -- Hidely-howdy-ho! I'll sell you what I've got if you fork over enough dough! MIGRAN_SHOP_DIALOG = 10904; -- Even with the aid from Jeuno, I still have trouble feeding my six children... NILEROUCHE_SHOP_DIALOG = 10893; -- Hello, traveler! Please have a look at these fine Tavnazian-built products! MISSEULIEU_SHOP_DIALOG = 10902; -- Greetings, adventurer! I've been given authorization to begin the sale of the old Tavnazian armor we had in storage! YOU_CANNOT_ENTER_DYNAMIS = 11824; -- You cannot enter Dynamis PLAYERS_HAVE_NOT_REACHED_LEVEL = 11826; -- Players who have not reached levelare prohibited from entering Dynamis. MYSTERIOUS_VOICE = 11812; -- You hear a mysterious, floating voice: -- conquest Base CONQUEST_BASE = 6532; -- Tallying conquest results... -- Porter Moogle RETRIEVE_DIALOG_ID = 12249; -- You retrieve$ from the porter moogle's care.
gpl-3.0
thedraked/darkstar
scripts/zones/Castle_Oztroja/npcs/_47k.lua
14
1624
----------------------------------- -- Area: Castle Oztroja -- NPC: _47k (Torch Stand) -- Notes: Opens door _472 near password #1 -- @pos -57.412 -1.864 -30.627 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorID = npc:getID() - 3; local DoorA = GetNPCByID(DoorID):getAnimation(); local TorchStandA = npc:getAnimation(); local Torch1 = npc:getID(); local Torch2 = npc:getID() + 1; if (DoorA == 9 and TorchStandA == 9) then player:startEvent(0x000a); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) local Torch1 = GetNPCByID(17396168):getID(); local Torch2 = GetNPCByID(Torch1):getID() + 1; local DoorID = GetNPCByID(Torch1):getID() - 3; if (option == 1) then GetNPCByID(Torch1):openDoor(10); -- Torch Lighting GetNPCByID(Torch2):openDoor(10); -- Torch Lighting GetNPCByID(DoorID):openDoor(6); end end; -- printf("CSID: %u",csid); -- printf("RESULT: %u",option);
gpl-3.0